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

后端 未结 12 773
一生所求
一生所求 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:58

    This answer may seem irrelevant. But, for those who also need to calculate the exponentially weighted variance (and also standard deviation) with NumPy, the following solution will be useful:

    import numpy as np
    
    def ew(a, alpha, winSize):
        _alpha = 1 - alpha
        ws = _alpha ** np.arange(winSize)
        w_sum = ws.sum()
        ew_mean = np.convolve(a, ws)[winSize - 1] / w_sum
        bias = (w_sum ** 2) / ((w_sum ** 2) - (ws ** 2).sum())
        ew_var = (np.convolve((a - ew_mean) ** 2, ws)[winSize - 1] / w_sum) * bias
        ew_std = np.sqrt(ew_var)
        return (ew_mean, ew_var, ew_std)
    

提交回复
热议问题