Moving Average

简单移动平均(sma)

def moving_average(f_t):
    if type(f_t) is not np.ndarray:
        raise TypeError\
            ('Expected one dimensional numpy array.')
    if f_t.shape[1] != 1:
        raise IndexError\
            ('Expected one dimensional numpy array, %d dimensions given.' % (f_t.shape[1]))

    f_t = f_t.flatten()
    window = 5
    mode = 'same'
    g_t = np.ones(int(window))/float(window)   # array([0.2, 0.2, 0.2, 0.2, 0.2])
    # Deal with boundaries with atleast lag/2 day window
    # ma = np.convolve(f_t,g_t,mode)
    # ma = np.convolve(f_t,g_t,mode)[window-1:-window+1]
    ma = np.convolve(f_t,g_t)[window-1:-window+1]     #numpy卷积实现
    return ma

执行结果:

蓝色是原始数据,棕色是经过移动平均算法弱化后的数据。

也可以使用pandas的DataFrame的rolling函数:

df[<metric>].rolling(5).mean()

 

指数加权移动平均(ewma)

指数加权(exponentially weighted)的权重通过指数函数计算得到,

越近期的数据具有越小的衰减因子(decay factor),对应更大的权重。

根据跨度指定衰减,即  α=2/(span+1), for span1,则需要指定参数span;

根据质心指定衰减,即 α=1/(1+com), for com0,则需要指定参数com;

# 根据质心指定衰减参数

ewma1 = pd.Series.ewm(series, ignore_na=False, min_periods=0, adjust=True, com=1).mean()
ewma2 = pd.Series.ewm(series, ignore_na=False, min_periods=0, adjust=True, com=2).mean()
ewma5 = pd.Series.ewm(series, ignore_na=False, min_periods=0, adjust=True, com=5).mean()

plt.figure(figsize=(20,8))
plt.plot(v,label='raw')
plt.plot(ewma1,label='ewma1')
plt.plot(ewma2,label='ewma2')
plt.plot(ewma5,label='ewma5')
plt.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
plt.legend()
# plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f mbps'))
plt.show()

 

rolling是简单移动平均;

可以看出com值越小,衰减因子α越大,相同位置的真实值对应权重越小,则最终加权移动平均效果越接近真实值。

 

卷积运算

2018-08-07 补充

import numpy as np
from matplotlib import pyplot as plt

def moving_average(array, window=3):
    N = window
    n=np.ones(N)
    weights=n/N
    sma=np.convolve(weights,array)[N-1:-N+1]

    t=np.arange(N-1,len(array))
    plt.plot(t,array[N-1:],lw=1)
    plt.plot(t,sma,lw=2)
    plt.show()
    return sma

 

numpy.convolve(weights,array)[N-1:-N+1]
 
 
weight = [a,b,c]
array = [i,j,k,m,n]
 
Result:
[ai, bi+aj, ci+bj+ak, cj+bk+am, ck+bm+an, cm+bn, cn][N-1:-N+1]

 

如何理解卷积运算?

 

 

参考:https://www.cnblogs.com/21207-iHome/p/6231607.html

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html

 

posted @ 2018-08-05 21:36  青山应回首  阅读(836)  评论(0编辑  收藏  举报