取得預測與首次評估
現在我們已經訓練好隨機森林模型(rfr),接下來要用它在測試集上產生預測。這樣做是為了評估模型表現——基本判斷是:它是否和直接買進指數 SPY 一樣好,或更好?
我們會使用標準的 sklearn .predict(features) 方法,接著把每月報酬與投組預測值相乘。因為每個月會有 3 列資料,我們用 np.sum() 將它們加總。最後,同時繪製依我們預測得到的每月報酬與 SPY,並加以比較。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 使用
rfr隨機森林模型的.predict()方法,對train_features與test_features產生預測。 - 將測試集範圍內的
returns_monthly與test_predictions相乘,得到測試集預測的報酬。 - 繪製測試集期間
'SPY'的returns_monthly(從train_size到資料結尾的所有資料)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Get predictions from model on train and test
train_predictions = rfr.predict(train_features)
test_predictions = ____
# Calculate and plot returns from our RF predictions and the SPY returns
test_returns = np.sum(returns_monthly.iloc[train_size:] * ____, axis=1)
plt.plot(test_returns, label='algo')
plt.plot(returns_monthly['SPY'].iloc[____], label='SPY')
plt.legend()
plt.show()