Created
May 17, 2013 05:52
-
-
Save bigsnarfdude/5597200 to your computer and use it in GitHub Desktop.
Python Moving Average
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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