为波动率计算协方差
在 MPT 中,我们用波动率来量化风险。计算投资组合波动率的数学公式较为复杂,并且需要用到日收益率的协方差。现在我们将遍历 returns_monthly DataFrame 中的每个月,计算对应的日收益率协方差。
对于 pandas 的日期时间索引,您可以使用 df.index.month 和 df.index.year 获取月份和年份。我们将用它来为 returns_daily 创建一个掩码,得到循环中当前月份和年份对应的日收益率。然后使用该掩码对 DataFrame 进行子集选择,如:df[mask]。这会在循环的每一轮中,获取 returns_daily 中属于当前月份和年份的记录。最后,我们使用 pandas 的 .cov() 方法计算日收益率的协方差。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 遍历
returns_monthly的索引。 - 为
returns_daily创建一个掩码,使用来自returns_monthly的当前月份和年份,并与循环中i的当前月份和年份匹配。 - 将该掩码应用于
returns_daily,并使用.cov()计算协方差。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Daily covariance of stocks (for each monthly period)
covariances = {}
rtd_idx = returns_daily.index
for i in returns_monthly.____:
# Mask daily returns for each month and year, and calculate covariance
mask = (rtd_idx.month == i.month) & (rtd_idx.____ == i.____)
# Use the mask to get daily returns for the current month and year of monthy returns index
covariances[i] = returns_daily[____].cov()
print(covariances[i])