I'm trying to find the moving average of 20 numbers at a time, being read from a list. This moving average then needs to be inserted into the list. Here is my code:
inplis = file(r'table.csv','r').readlines() outp = file(r'avg_volume.csv','w') import math emptyList =  totalVolume = 0 counter = 0 for i in inplis: rec = i.strip().split(",") if rec == 'Date': rec.insert(1,emptyList) continue else: counter = counter + len(i) while counter == 20: volume = float(rec) totalVolume = totalVolume + volume break avgVolume = totalVolume/20 rec.insert(1,emptyList) rec= avgVolume if counter!=20: continue import string newStr = string.join(map(str,rec),",")+'\n' outp.write(newStr) outp.close()
There is obviously something wrong with the way the variable counter is being incremented but I don't know how to fix it.. I am trying to get it to count each i, and when it reaches 20, to find totalVolume and avgVolume. Volume is the 5th element of each i, where I am splitting the input file into one big list named inplis, which is then being split into invidual records named rec.
I'd appreciate any guidance, thank you!!