1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import pandas as pd import numpy as np
# 创建示例数据(日期为索引,收盘价和CPI两列) dates = pd.date_range(start='2024-01', periods=12, freq='M') data = { 'close': [100, 105, 108, 112, 115, 120, 118, 125, 130, 135, 140, 145], 'cpi': [280, 282, 285, 288, 290, 295, 298, 302, 305, 308, 312, 315] } df = pd.DataFrame(data, index=dates)
# ===== 核心计算步骤 ===== # 1. 计算股票名义收益率(简单收益率) df['nominal_return'] = df['close'].pct_change() * 100 # [3](@ref)
# 2. 计算通货膨胀率(基于CPI的月度环比) df['inflation_rate'] = (df['cpi'].pct_change() * 100) # [5,6](@ref)
# 3. 计算实际收益率(通胀调整后的收益率) df['real_return'] = ((1 + df['nominal_return']/100) / (1 + df['inflation_rate']/100) - 1) * 100 # [5](@ref)
# 4. 价格通胀调整(以基期CPI为基准) base_cpi = df['cpi'].iloc[0] # 取第一个月为基准期 df['real_price'] = df['close'] / (df['cpi'] / base_cpi) # [5,6](@ref)
# 处理首行NaN df.fillna(0, inplace=True)
# 打印结果 print(df[['close', 'cpi', 'nominal_return', 'inflation_rate', 'real_return', 'real_price']])
|