Skip to content

Instantly share code, notes, and snippets.

@glortho
Created May 14, 2015 20:31
Show Gist options
  • Save glortho/c2632c69454113e9f961 to your computer and use it in GitHub Desktop.
Save glortho/c2632c69454113e9f961 to your computer and use it in GitHub Desktop.
Exp Moving Averages
#!/bin/sh
"exec" "twxec" "-e" "calc_emas" "$0" "$@"
import numpy as np
from itertools import count
from math import sqrt
import time
class ExpMovingAvg(object):
def __init__(self, tau=[10]):
self.start_time = time.time()
self.time_elapsed = 0
self.last_time = None
self.tau = np.array(tau).astype('float')
self._value = None
def sample(self, t, value):
self._value = value
if(self.last_time is None):
self.last_time = t
self.ema = value * np.ones(len(self.tau))
self.last_ema = self.ema
else:
dt = t - self.last_time
if(dt > 0):
a = float(dt) / self.tau
u = np.exp(-1.0 * a)
self.last_ema = self.ema
self.ema = (1 - u) * value + u * self.last_ema
self.last_time = t
self.time_elapsed = int(self.last_time) - int(self.start_time)
# return self.ema
time_scales = [5, 15, 60]
EMA = ExpMovingAvg(time_scales)
def calc_emas(msg):
statpack = {}
EMA.sample(int(time.time()), sqrt(msg["count"]) * float(msg["value"]))
statpack["5s"] = [EMA.ema[0], EMA.last_ema[0]]
statpack["15s"] = [EMA.ema[1], EMA.last_ema[1]]
statpack["60s"] = [EMA.ema[2], EMA.last_ema[2]]
statpack["time(secs)"] = EMA.time_elapsed
return statpack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment