建立移動平均與 RSI 特徵
我們想把歷史資料加入機器學習模型,以做出更好的預測,但直接加入大量歷史時間步會很麻煩。相對地,我們可以用技術指標,將先前多個時間點的資訊濃縮成單一時間步。
移動平均是最簡單的指標之一——它是前幾個資料點的平均值。這可用 TAlib 函式庫中的 talib.SMA() 來計算。
另一個常見的技術指標是相對強弱指標(RSI)。其定義為:
\(RSI = 100 - \frac{100} {1 + RS}\)
\(RS = \frac{\text{average gain over } n \text{ periods}} {\text{average loss over } n \text{ periods}}\)
其中的 n 期可在 talib.RSI() 的 timeperiod 參數中設定。
RSI 常用的期間是 14,因此我們會在計算中採用這個設定之一。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 建立一個特徵名稱清單(先以只包含
'5d_close_pct'的清單開始)。 - 使用 14、30、50、200 這些 timeperiod,從調整後收盤價(
lng_df['Adj_Close'])以talib.SMA()計算移動平均。 - 以調整後收盤價除以移動平均,將其相對化(以
Adj_Close做正規化)。 - 在迴圈中,使用
talib.RSI()以Adj_Close計算 RSI,並以n作為 timeperiod。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
feature_names = ____ # a list of the feature names for later
# Create moving averages and rsi for timeperiods of 14, 30, 50, and 200
for n in [____]:
# Create the moving average indicator and divide by Adj_Close
lng_df['ma' + str(n)] = talib.SMA(lng_df['Adj_Close'].values,
timeperiod=n) / lng_df[____]
# Create the RSI indicator
lng_df['rsi' + str(n)] = talib.____(lng_df['Adj_Close'].____, timeperiod=____)
# Add rsi and moving average to the feature name list
feature_names = feature_names + ['ma' + str(n), 'rsi' + str(n)]
print(feature_names)