I've scoured stackoverflow, and I can't find exactly what fits the bill for me.
I'm calculating a weighted moving average for a rolling window.
The equation is:
#weighted average temp with smoothing factor, a
#T_w = sum[k=1,24](a^(k-1)*T(t-k)) / sum[k=1,24]a^(k-1)
Seems easy enough, but I need to apply this average to a rolling window. I can do rolling mean (simple moving average):
T_ = pd.DataFrame()
T_ = temps['T'].rolling(window=24).mean()
But now I want to apply weights for ONLY the window I'm averaging over. Python's .ewm() doesn't cut the mustard, because I want the weights to be just for the window I'm "rolling" over.
I've found a few snippets that seem like they might work, but components fail:
from functools import partial
window = 13
alpha = 1-ln(2)/3 # This is ewma's decay factor.
weights = list(reversed([(1-alpha)**n for n in range(window)]))
ewma = partial(average, weights=weight)
rolling_average = series.rolling(window).apply(ewma)
Here, the problem I've run into is how partial() calls average() -- this was introduced here - Create a rolling custom EWMA on a pandas dataframe - but I can't comment yet (newb), and I don't know where to take this.
Another solution I have implemented, but it doesn't do exactly what I need:
alpha = 0.1 # This is my smoothing parameter
weights = list(reversed([(1-alpha)**n for n in range(window)]))
def f(w):
def g(x):
return (w*x).mean()
return g
T_ = pd.DataFrame()
T_ = temps['T'].rolling(window=24).apply(f(weights))
Based on a proposed solution here: Calculating weighted moving average using pandas Rolling method The problem with this approach is that it calculates the mean, whereas I need effectively something like this:
return (w*x).sum() / w.sum()
But that doesn't work, because
AttributeError: 'list' object has no attribute 'sum'
How do I calculate a rolling weighted moving average with a specified window (here, the last 24 hours), and a specified smoothing parameter a (which is only applied to the last 24 hours) ?