多只股票的年度收益相关性
您已经在视频中看到如何计算相关性并可视化结果。
在本练习中,我们为您提供了 Apple(AAPL)、Amazon(AMZN)、IBM(IBM)、WalMart(WMT)和 Exxon Mobile(XOM)从 2001 年 7 月到 2017 年 5 月底最近 4,000 个交易日的历史股价。
您将计算年末收益率、所有股票之间的两两相关性,并将结果可视化为带注释的热力图。
本练习是课程的一部分
Python 中的时间序列数据处理
练习说明
我们已将 pandas 导入为 pd,将 seaborn 导入为 sns,并将 matplotlib.pyplot 导入为 plt。我们已将这 5 只股票的每日收盘价加载到名为 data 的变量中。
- 使用
.info()进行检查。 - 对
data使用以年末为频率(别名:'A')的.resample(),并从每个子期中选择.last()价格;将结果赋给annual_prices。 - 对
annual_prices应用.pct_change()来计算annual_returns。 - 对
annual_returns应用.corr()来计算correlations,并打印结果。 - 将
correlations可视化为带注释的sns.heatmap()。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Inspect data here
print(____)
# Calculate year-end prices here
annual_prices = ____
# Calculate annual returns here
annual_returns = ____
# Calculate and print the correlation matrix here
correlations = ____
print(____)
# Visualize the correlations as heatmap here