指数加权平均值 一下是基于pandas的。
应该是和exponential smoothing or Holt–Winters method 是基于一个基础的。
DEMO, 原址:http://connor-johnson.com/2014/02/01/smoothing-with-exponentially-weighted-moving-averages/
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 01 13:02:50 2014
@author: dell
"""
import pandas, numpy as np
ewma = pandas.stats.moments.ewma
import matplotlib.pyplot as plt
# make a hat function, and add noise
x = np.linspace(0,1,100)
x = np.hstack((x,x[::-1]))
x += np.random.normal( loc=0, scale=0.1, size=200 )
plt.plot( x, alpha=0.4, label='Raw' )
# take EWMA in both directions with a smaller span term
fwd = ewma( x, span=15 ) # take EWMA in fwd direction
bwd = ewma( x[::-1], span=15 ) # take EWMA in bwd direction
c = np.vstack(( fwd, bwd[::-1] )) # lump fwd and bwd together
c = np.mean( c, axis=0 ) # average
# regular EWMA, with bias against trend
plt.plot( ewma( x, span=20 ), 'b', label='EWMA, span=20' )
# "corrected" (?) EWMA
plt.plot( c, 'r', label='Reversed-Recombined' )
plt.legend(loc=8)
plt.savefig( 'ewma_correction.png', fmt='png', dpi=100 )
DEMO II
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 01 14:10:05 2014
@author: dell
"""
import numpy as np
import matplotlib.pyplot as plt
def holt_winters_second_order_ewma( x, span, beta ):
N = x.size
alpha = 2.0 / ( 1 + span )
s = np.zeros(( N, ))
b = np.zeros(( N, ))
s[0] = x[0]
for i in range( 1, N ):
s[i] = alpha * x[i] + ( 1 - alpha )*( s[i-1] + b[i-1] )
b[i] = beta * ( s[i] - s[i-1] ) + ( 1 - beta ) * b[i-1]
return s
# make a hat function, and add noise
x = np.linspace(0,1,100)
x = np.hstack((x,x[::-1]))
x += np.random.normal( loc=0, scale=0.1, size=200 ) + 3.0
plt.plot( x, alpha=0.4, label='Raw' )
# holt winters second order ewma
plt.plot( holt_winters_second_order_ewma( x, 10, 0.3 ), 'b', label='Holt-Winters' )
plt.title('Holt-Winters' )
plt.legend( loc=8 )
plt.savefig( 'holt_winters.png', fmt='png', dpi=100 )