Skip to content

Instantly share code, notes, and snippets.

@microwaves
Created September 19, 2014 22:17
Show Gist options
  • Select an option

  • Save microwaves/b6ce406d3158bfd9d929 to your computer and use it in GitHub Desktop.

Select an option

Save microwaves/b6ce406d3158bfd9d929 to your computer and use it in GitHub Desktop.
A simple class to calculate moving averages.
class MovingAverage(object):
def __init__(self):
self.mutant_range = lambda start, end: range(start, end + 1)
def exponential_moving_average(self, values, index=None, tail=None):
index, tail = self.__index_and_tail_or_defaults(values, index, tail)
alpha = 2.0 / (tail + 1)
n = sum(map(lambda x: ((1 - alpha) ** (x - 1) * values[index - x + 1]),
self.mutant_range(1, tail)))
d = sum(map(lambda x: ((1 - alpha) ** (x -1)),
self.mutant_range(1, tail)))
return n / d
def __index_and_tail_or_defaults(self, values, index, tail):
if tail is None:
tail = len(values)
if index is None:
index = len(values) - 1
return [index, tail]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment