NumPy version of “Exponential weighted moving average”, equivalent to pandas.ewm().mean()

后端 未结 12 777
一生所求
一生所求 2020-11-27 12:30

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         


        
12条回答
  •  星月不相逢
    2020-11-27 12:41

    Building on top of Divakar's great answer, here is an implementation which corresponds to the adjust=True flag of the pandas function, i.e. using weights rather than recursion.

    def numpy_ewma(data, window):
        alpha = 2 /(window + 1.0)
        scale = 1/(1-alpha)
        n = data.shape[0]
        scale_arr = (1-alpha)**(-1*np.arange(n))
        weights = (1-alpha)**np.arange(n)
        pw0 = (1-alpha)**(n-1)
        mult = data*pw0*scale_arr
        cumsums = mult.cumsum()
        out = cumsums*scale_arr[::-1] / weights.cumsum()
    
        return out
    

提交回复
热议问题