Skip to content

Instantly share code, notes, and snippets.

@bigsnarfdude
Created May 17, 2013 05:52
Show Gist options
  • Save bigsnarfdude/5597200 to your computer and use it in GitHub Desktop.
Save bigsnarfdude/5597200 to your computer and use it in GitHub Desktop.
Python Moving Average
from random import randint
from itertools import islice
from __future__ import division # For Python 2
y = [ randint(1,999) for num in range(30) ]
def window(seq, n=2):
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def moving_averages(values, size):
for selection in window(values, size):
yield sum(selection) / size
for avg in moving_averages(map(int, y), 5):
print(avg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment