calculate exponential moving average in python

后端 未结 14 2394
囚心锁ツ
囚心锁ツ 2020-12-01 00:59

I have a range of dates and a measurement on each of those dates. I\'d like to calculate an exponential moving average for each of the dates. Does anybody know how to do t

14条回答
  •  时光说笑
    2020-12-01 01:27

    Papahaba's answer was almost what I was looking for (thanks!) but I needed to match initial conditions. Using an IIR filter with scipy.signal.lfilter is certainly the most efficient. Here's my redux:

    Given a NumPy vector, x

    import numpy as np
    from scipy import signal
    
    period = 12
    b = np.array((1,), 'd')
    a = np.array((period, 1-period), 'd')
    zi = signal.lfilter_zi(b, a)
    y, zi = signal.lfilter(b, a, x, zi=zi*x[0:1])
    

    Get the N-point EMA (here, 12) returned in the vector y

提交回复
热议问题