開始使用免費開始

取得預測與首次評估

現在我們已經訓練好隨機森林模型(rfr),接下來要用它在測試集上產生預測。這樣做是為了評估模型表現——基本判斷是:它是否和直接買進指數 SPY 一樣好,或更好?

我們會使用標準的 sklearn .predict(features) 方法,接著把每月報酬與投組預測值相乘。因為每個月會有 3 列資料,我們用 np.sum() 將它們加總。最後,同時繪製依我們預測得到的每月報酬與 SPY,並加以比較。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 使用 rfr 隨機森林模型的 .predict() 方法,對 train_featurestest_features 產生預測。
  • 將測試集範圍內的 returns_monthlytest_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()
編輯並執行程式碼