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

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

    Here is another solution O came up with in the meantime. It is about four times faster than the pandas solution.

    def numpy_ewma(data, window):
        returnArray = np.empty((data.shape[0]))
        returnArray.fill(np.nan)
        e = data[0]
        alpha = 2 / float(window + 1)
        for s in range(data.shape[0]):
            e =  ((data[s]-e) *alpha ) + e
            returnArray[s] = e
        return returnArray
    

    I used this formula as a starting point. I am sure that this can be improved even more, but it is at least a starting point.

提交回复
热议问题