I was looking into why the numpy version of SMA didn't match the for loop version, and looking at each step in the for loop version, it appears that it is not doing the final window correctly. Is this intentional or am I misinterpreting what is going on? I haven't tested the JS version, but appears to be identical to the python one.
In [1]: x = [42,75,3,5,99,22,88]
In [2]: SMA(x, 3, 1)
window: [42, 75, 3] sum( 120.0000) / count( 3.0000) = 40.0000
window: [75, 3, 5] sum( 83.0000) / count( 3.0000) = 27.6667
window: [3, 5, 99] sum( 107.0000) / count( 3.0000) = 35.6667
window: [5, 99, 22, 88] sum( 214.0000) / count( 4.0000) = 53.5000
window: [99, 22, 88, 88] sum( 297.0000) / count( 4.0000) = 53.5000
Out[2]: [40.0, 27.666666666666668, 35.666666666666664, 53.5]
def SMA(data, _range, slide):
ret = []
s = 0.0
c = 0.0
window_start = 0
window = []
for i in range(len(data)):
if i-window_start >= _range or i==len(data)-1:
if i==len(data)-1 or c==0:
s += data[i]
window.append(data[i])
c += 1
ret.append( s/c )
print("window: {} \t sum({:10.4f}) / count({:10.4f}) = {:10.4f} ".format(window, s, c, ret[-1]))
old_start = window_start
while window_start < len(data) and window_start-old_start < slide:
s -= data[window_start]
window = window[1::]
c -= 1
window_start += 1
s += data[i]
window.append(data[i])
c += 1
print("window: {} \t sum({:10.4f}) / count({:10.4f}) = {:10.4f} ".format(window, s, c, ret[-1]))
return ret