評估報酬
現在來看看,我們的投資組合選股表現,與只投資 SPY 相比如何。雖然 R\(^2\) 值偏低,我們仍想檢視預測是否有前景。
我們會把起始投資金額設為 $1000,然後分別迴圈套用我們的預測報酬與 SPY 的報酬。我們會使用投資組合選股與 SPY 的月度報酬,將其套用到起始現金餘額。這樣就能得到逐月的投資表現,並可觀察整體來說我們的預測相較於 SPY 的結果。接著,我們可以把根據預測得到的投資組合繪圖,並與 SPY 比較。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 將
algo_cash與spy_cash的第一個清單元素都設為相同的金額(cash)。 - 在
test_returns迴圈中,將cash乘上1 + r,把該期報酬套用到cash。 - 與
test_returns迴圈相同,在 SPY 的績效迴圈中,先將cash乘上1 + r以加入該期報酬,再把cash附加到spy_cash。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate the effect of our portfolio selection on a hypothetical $1k investment
cash = 1000
algo_cash, spy_cash = [cash], ____ # set equal starting cash amounts
for r in test_returns:
cash *= 1 + r
algo_cash.append(cash)
# Calculate performance for SPY
cash = 1000 # reset cash amount
for r in returns_monthly['SPY'].iloc[train_size:]:
cash ____ ____
____
print('algo returns:', (algo_cash[-1] - algo_cash[0]) / algo_cash[0])
print('SPY returns:', (spy_cash[-1] - spy_cash[0]) / spy_cash[0])