Created
September 19, 2014 22:17
-
-
Save microwaves/b6ce406d3158bfd9d929 to your computer and use it in GitHub Desktop.
A simple class to calculate moving averages.
This file contains hidden or 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
| 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