如何创建展示各期限隐含波动率占比的Pandas DataFrame
解决方案
首先先简化并确认原始DataFrame的构建(修正你原代码中的冗余步骤):
import pandas as pd # 定义期限和对应的隐含波动率 tenors = ['ON','1W','2W','3W','1M','2M','3M','6M','9M','1Y','2Y','3Y','5Y','7Y','10Y'] implied_vols = [8.6325, 7.3975, 9. , 8.6275, 8.5 , 8.375 , 8.07 , 7.82 , 7.77 , 7.7 , 7.8 , 8.025 , 8.535 , 8.83 , 9.15 ] # 构建目标DataFrame new_df = pd.DataFrame({'Tenor': tenors, 'Implied_Vol': implied_vols}).set_index('Tenor')
方法一:利用广播高效生成占比矩阵
这是最简洁高效的方式,通过pandas的向量广播特性直接计算:
# 计算每个期限IV与所有期限IV的占比(转为百分比) vol_ratio_matrix = new_df['Implied_Vol'].values[:, None] / new_df['Implied_Vol'].values * 100 # 转为DataFrame,设置行和列索引为原期限 vol_ratio_df = pd.DataFrame(vol_ratio_matrix, index=new_df.index, columns=new_df.index) # 可选择保留两位小数 vol_ratio_df = vol_ratio_df.round(2)
方法二:基于你的循环思路优化
如果你倾向于用循环实现,可以把每个计算结果作为列添加到新DataFrame中:
vol_ratio_df = pd.DataFrame() for tenor in new_df.index: # 计算所有期限IV相对于当前tenor的占比(百分比),列名为当前tenor vol_ratio_df[tenor] = (new_df['Implied_Vol'] / new_df['Implied_Vol'][tenor]) * 100 # 保留两位小数 vol_ratio_df = vol_ratio_df.round(2)
最终生成的vol_ratio_df就是你需要的DataFrame:行和列都是期限(Tenor),单元格值为对应行期限的隐含波动率除以对应列期限的隐含波动率的百分比,对角线值均为100(自身占比)。
内容的提问来源于stack exchange,提问作者HDBrew
相关产品推荐
相关产品推荐

