建立特徵與目標
要用機器學習挑出最佳投資組合,我們需要產生特徵與目標。上一個練習你已經建立了特徵——價格的指數加權移動平均(EWMA)。目標則是從夏普比率最高時找到的最佳投資組合。
我們會使用 pandas 的 .iterrows() 方法,從 ewma_monthly DataFrame 取得 index, value 配對。在迴圈中,將當前的 ewma_monthly 值設為特徵。接著利用最佳夏普比率的索引(max_sharpe_idxs)來取得每個月份對應的最佳 portfolio_weights,並將其設為目標。
本練習屬於課程
Python 金融 Machine Learning
練習說明
- 對
ewma_monthly使用.iterrows(),在迴圈中逐一取得index, value。 - 在迴圈中使用
date搭配best_idx索引portfolio_weights,取得基於最佳夏普比率的理想投資組合權重。 - 將
ewma附加到特徵陣列中。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
targets, features = [], []
# Create features from price history and targets as ideal portfolio
for date, ewma in ewma_monthly.____:
# Get the index of the best sharpe ratio
best_idx = max_sharpe_idxs[date]
targets.append(portfolio_weights[____][____])
features.append(____) # add ewma to features
targets = np.array(targets)
features = np.array(features)
print(targets[-5:])