Friday, 15 May 2015

How to calculate moving average in Python 3? -



How to calculate moving average in Python 3? -

let's have list:

y = ['1', '2', '3', '4','5','6','7','8','9','10']

i want create function calculates moving n-day average. if n 5, want code calculate first 1-5, add together , find average, 3.0, go on 2-6, calculate average, 4.0, 3-7, 4-8, 5-9, 6-10.

i don't want calculate first n-1 days, starting nth day, it'll count previous days.

def moving_average(x:'list of prices', n): num in range(len(x)+1): print(x[num-n:num])

this seems print out want:

[] [] [] [] [] ['1', '2', '3', '4', '5'] ['2', '3', '4', '5', '6'] ['3', '4', '5', '6', '7'] ['4', '5', '6', '7', '8'] ['5', '6', '7', '8', '9'] ['6', '7', '8', '9', '10']

however, don't know how calculate numbers within lists. ideas?

there great sliding window generator in old version of python docs itertools examples:

from itertools import islice def window(seq, n=2): "returns sliding window (of width n) on info iterable" " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result elem in it: result = result[1:] + (elem,) yield result

using moving averages trivial:

from __future__ import partition # python 2 def moving_averages(values, size): selection in window(values, size): yield sum(selection) / size

running against input (mapping strings integers) gives:

>>> y= ['1', '2', '3', '4','5','6','7','8','9','10'] >>> avg in moving_averages(map(int, y), 5): ... print(avg) ... 3.0 4.0 5.0 6.0 7.0 8.0

to homecoming none first n - 1 iterations 'incomplete' sets, expand moving_averages function little:

def moving_averages(values, size): _ in range(size - 1): yield none selection in window(values, size): yield sum(selection) / size

python python-3.x

No comments:

Post a Comment