创建特征与目标
要用机器学习挑选最优投资组合,您需要生成特征和目标。我们的特征已在上个练习中创建——价格的指数加权移动平均。我们的目标将是我们通过最高 Sharpe 比率找到的最优投资组合。
我们将使用 pandas 的 .iterrows() 方法获取 ewma_monthly DataFrame 的 index, value 对。在循环中,将当前的 ewma_monthly 值设为特征。然后使用最佳 Sharpe 比率的索引(来自 max_sharpe_idxs)获取每个月的最佳 portfolio_weights,并将其设为目标。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 在循环中对
ewma_monthly使用.iterrows()方法,迭代index, value。 - 在循环里使用
date和best_idx来索引portfolio_weights,以基于最佳 Sharpe 比率获得理想的投资组合权重。 - 将
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:])