I've written a simple rolling average function, which works well. I also don't want to use external libraries like numpy or pandas, just so you know.
def get_rolling_average(data, period):
rolling = []
for i in range (0, len(data)):
end = i + period
nums = data[i:end]
# if i < (period-1):
# nums = data[0:i+1]
# rolling.append(mean(nums))
if len(nums) == period:
rolling.append(mean(nums))
return rolling
def round_nicely(num, places):
return round(num, places)
def mean(lst):
summ = sum(lst[0:len(lst)])
summ = float(summ)
return round_nicely(summ/len(lst),1)
print("Rolling average!")
xl = [45, 51, 73, 82, 76, 56, 57, 78, 89, 59]
print get_rolling_average(xl, 3)
With the results being
Rolling average!
[56.3, 68.7, 77.0, 71.3, 63.0, 63.7, 74.7, 75.3]
However, I want to include the first few values if they are smaller than the period. In this exmple, it'll be just 45 & 48.
Rolling average!
[45.0, 48.0, 56.3, 68.7, 77.0, 71.3, 63.0, 63.7, 74.7, 75.3]
where
(45)/1 = 45.0
(45 + 51)/2 = 48.0
I'm not sure the most Pythonic method to do this. I've got a bit of a brain-freeze and my most cohesive attempt is the three lines commented out, but it skips a value.