I struggle to implement the moving average formula in my function. Took me quite a while to get where the code is right now.
Is there a library I could probably take?
Input:
ma([2,3,4,3,2,6,9,3,2,1], 4)
Expected Output:
[None, None, None, 3.0, 3.0, 3.75, 5.0, 5.0, 5.0, 3.75]
My Output:
[None, None, 0.0, 3.0, 3.75, 5.0, 5.0, None, None, None]
I am running into the problem that the middle parts of my result is right but the rest is a mystery.
- Why does it return None for the last three values in the list?
def ma(prices, n):
ma = []
sums = []
s = 0
ave = 0
for idx, i in enumerate(prices):
s += i
sums.append(s)
print('idx: ' + str(idx))
print('list of sums ' + str(sums))
#print('sum ' + str(s))
if i >= n+1:
print('sums[idx] ' + str(sums[idx]))
print('sums[idx-n] ' + str(sums[idx-n]))
ave = (sums[idx] - sums[idx-n]) / n
print('ave ' + str(ave))
ma.append(ave)
print('ma ' + str(ma))
else:
m = None
ma.append(m)
print('ma ' + str(ma))
(Sorry for all those print
function calls, but I really wanted to get to the source of the issue).