Last active
July 6, 2022 07:54
-
-
Save casebeer/8327849 to your computer and use it in GitHub Desktop.
Exponential moving average generator example in Python
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
def consumer(func): | |
''' | |
Decorator taking care of initial next() call to "sending" generators | |
From PEP-342 | |
http://www.python.org/dev/peps/pep-0342/ | |
''' | |
def wrapper(*args,**kw): | |
gen = func(*args, **kw) | |
next(gen) | |
return gen | |
wrapper.__name__ = func.__name__ | |
wrapper.__dict__ = func.__dict__ | |
wrapper.__doc__ = func.__doc__ | |
return wrapper | |
@consumer | |
def ema(alpha=0.5): | |
''' | |
Exponential moving average generator | |
http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average | |
Higher alpha discounts old results faster, alpha in range (0, 1). | |
''' | |
current, average = 0, 0 | |
while True: | |
average = current * alpha + average * (1 - alpha) | |
current = yield average | |
if __name__ == '__main__': | |
# example | |
g = ema() | |
while True: | |
print g.send(10) | |
raw_input("Hit Enter to continue...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment