How do I get the exponential weighted moving average in NumPy just like the following in pandas?
import pandas as pd
import pandas_datareader as pdr
from dat
A very simple solution that avoids numba but that is almost as fast as Alexander McFarlane's solution, especially for large arrays and large window
sizes, is to use scipy's lfilter
function (because an EWMA is a linear filter):
from scipy.signal import lfiltic, lfilter
# careful not to mix between scipy.signal and standard python signal
# (https://docs.python.org/3/library/signal.html) if your code handles some processes
def ewma_linear_filter(array, window):
alpha = 2 /(window + 1)
b = [alpha]
a = [1, alpha-1]
zi = lfiltic(b, a, array[0:1], [0])
return lfilter(b, a, array, zi=zi)[0]
Timings are as follows:
n = 10_000_000
window = 100_000
data = np.random.normal(0, 1, n)
%timeit _ewma_infinite_hist(data, window)
%timeit linear_filter(data, window)
86 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
92.6 ms ± 751 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)