绘制含最佳夏普比率的有效前沿
现在我们再次绘制有效前沿,但要为具有最佳夏普指数的投资组合添加一个标记。可视化数据总是有助于更好地理解它。
回顾一下:有效前沿是在散点图中绘制的,x 轴为投资组合波动率,y 轴为投资组合收益率。我们将从 covariances.keys() 中获取数据中的最新日期,不过也可以使用 portfolio_returns 等任一字典来获取日期。然后从 portfolio_volatility 和 portfolio_returns 中取出该最新日期对应的波动率和收益率。最后从 max_sharpe_idxs[date] 获取拥有最佳夏普指数的投资组合的索引,并用 plt.scatter() 将所有内容绘制出来。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 将
cur_volatility设置为最新date对应的投资组合波动率。 - 通过在 x 轴绘制波动率、在 y 轴绘制收益率来构建"有效前沿"图。
- 从
max_sharpe_idxs中获取最新date的最佳投资组合索引。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Get most recent (current) returns and volatility
date = sorted(covariances.keys())[-1]
cur_returns = portfolio_returns[date]
cur_volatility = ____
# Plot efficient frontier with sharpe as point
plt.scatter(x=____, y=____, alpha=0.1, color='blue')
best_idx = max_sharpe_idxs[____]
# Place an orange "X" on the point with the best Sharpe ratio
plt.scatter(x=cur_volatility[best_idx], y=cur_returns[best_idx], marker='x', color='orange')
plt.xlabel('Volatility')
plt.ylabel('Returns')
plt.show()