數據平滑
是用來處理噪聲數據,使數據變化較為平順.可以使用移動平均線, 也可以使用hanning函數
Key_Function
np.hanning函數: 是一個加權余弦的窗函數, 相當於是余弦移動平均線
np.polysub函數: 輸入兩個多項式系數數組, 返回一個表示兩個多項式差的多項式的系數數組
np.isreal函數: 判斷數組元素是否是實數
np.select函數: 根據給定的條件, 從數組中挑選出符合條件的元素並組成數組返回
np.trim_zeros函數: 去掉一維數組中開頭或末尾為0的元素
Code
import numpy as np import matplotlib.pyplot as plt N = 8 weights = np.hanning(N) print(weights) ''' [ 0. 0.1882551 0.61126047 0.95048443 0.95048443 0.61126047 0.1882551 0. ] ''' # 本例使用的是收盤價 bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True) bhp_returns = np.diff(bhp) / bhp[:-1] print(len(bhp_returns)) # 29 smooth_bhp = np.convolve(weights/weights.sum(), bhp_returns)[N-1:-N+1] # 使用歸一化的weights作為權重 vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True) vale_returns = np.diff(vale) / vale[:-1] smooth_vale = np.convolve(weights/weights.sum(), vale_returns)[N-1:-N+1] t = np.arange(N-1, len(bhp_returns)) plt.plot(t, bhp_returns[N-1:], lw=1.0) plt.plot(t, smooth_bhp, lw=3.0) plt.plot(t, vale_returns[N-1:], lw=5.0) plt.plot(t, smooth_vale, lw=7.0) plt.show()
接上面代碼
# 使用多項式擬合平滑后的數據 K = 8 t = np.arange(N-1, len(bhp_returns)) poly_bhp = np.polyfit(t, smooth_bhp, K) poly_vale = np.polyfit(t, smooth_vale, K) # 求解兩條曲線的交叉點 # 通過求兩個多項式的差, 然后對所得的多項式求根 poly_sub = np.polysub(poly_bhp, poly_vale) xpoints = np.roots(poly_sub) ''' [ 27.73321597+0.j 27.51284094+0.j 24.32064343+0.j 18.86423973+0.j 12.43797190+1.73218179j 12.43797190-1.73218179j 6.34613053+0.62519463j 6.34613053-0.62519463j] ''' reals = np.isreal(xpoints) print(reals) # [ True True True True False False False False] xpoints = np.select([reals], [xpoints]) print(xpoints) ''' [ 27.73321597+0.j 27.51284094+0.j 24.32064343+0.j 18.86423973+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j] ''' xpoints = xpoints.real print(xpoints) ''' [ 27.73321597 27.51284094 24.32064343 18.86423973 0. 0. 0. 0. ] ''' print(np.trim_zeros(xpoints)) # [ 27.73321597 27.51284094 24.32064343 18.86423973]