簡單移動平均線
簡單移動平均線是計算與等權重的指示函數的卷積,也可以不等權重.
1.用ones函數創建一個元素均為1的數組,然后對整個數組除以N,得到等權重.
2.使用權值,調用convolve函數.
3.從convolve函數分安徽的數組中取出中間的長度為N的部分(即兩者作卷積運算時完全重疊的區域.)
4.使用matplotlib繪圖
import numpy as np
import matplotlib.pyplot as plt
import sys
N=int(sys.argv[1]) weights=np.ones(N)/N print("WEIGHTS",weights) c=np.loadtxt('/home/syd/Documents/stockdata.csv',delimiter=',', skiprows=(2),usecols=(2,),unpack=True) sam=np.convolve(weights,c)[N-1:-N+1] t=np.arange(N-1,len(c)) plt.plot(t,c[N-1:],lw=1.0) plt.plot(t,sam,lw=2.0) plt.show()
窗函數:hanning漢寧窗
漢寧窗是一個加權余弦窗函數.numpy.hanning(M) Return the Hanning window.
Parameters: M : int
Number of points in the output window. If zero or
Returns: out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value one
appears only if M is odd).
1.調用hanning函數計算權重,生成一個長度為N的窗口,輸入參數N
N=int(sys.argv[1]) weights=np.hanning(N) print(weights)
2.使用convolve,進行卷積運算.然后繪圖.
import numpy as np
import matplotlib.pyplot as plt
import sys
N=int(sys.argv[1]) weights=np.hanning(N) print("WEIGHTS",weights) c=np.loadtxt('/home/syd/Documents/stockdata.csv',delimiter=',', skiprows=(2),usecols=(2,),unpack=True) sam=np.convolve(weights/weights.sum(),c)[N-1:-N+1] t=np.arange(N-1,len(c)) plt.plot(t,c[N-1:],lw=1.0) plt.plot(t,sam,lw=2.0) plt.show()