CPI(Consumer Price Index,消费者价格指数)是衡量一组代表性消费品及服务项目价格水平随时间变动的相对数,反映居民家庭购买消费商品及服务的价格水平的变动情况。其计算方式通常采用加权平均法,核心公式为:
C P I = ∑ ( P t × Q b ) ∑ ( P b × Q b ) × 100 CPI = \frac{\sum (P_t \times Q_b)}{\sum (P_b \times Q_b)} \times 100 CPI=∑(Pb×Qb)∑(Pt×Qb)×100
其中:
- P t P_t Pt是当前价格
- P b P_b Pb是基期价格
- Q b Q_b Qb是基期数量(固定权数)
- 乘以100是为了将基期指数定为100
下面是一个用Python实现CPI计算的示例,包含基础计算、多期趋势分析和可视化功能:
import pandas as pd
import matplotlib.pyplot as plt
class CPICalculator:
def __init__(self):
"""初始化CPI计算器"""
self.basket = None
self.cpi_data = None
def set_basket(self, items, base_prices, base_quantities):
"""设置消费品篮子
Args:
items (list): 商品名称列表
base_prices (list): 基期价格列表
base_quantities (list): 基期数量列表
"""
if len(items) != len(base_prices) or len(items) != len(base_quantities):
raise ValueError("商品名称、基期价格和基期数量的长度必须一致")
self.basket = pd.DataFrame({
'商品': items,
'基期价格': base_prices,
'基期数量': base_quantities
})
return self.basket
def calculate_cpi(self, current_prices, period_label='当前'):
"""计算单期CPI
Args:
current_prices (list): 当前价格列表
period_label (str): 时期标签
Returns:
float: CPI值
"""
if self.basket is None:
raise ValueError("请先设置消费品篮子")
if len(current_prices) != len(self.basket):
raise ValueError("当前价格列表的长度必须与消费品篮子中的商品数量一致")
# 计算基期总支出
self.basket['基期支出'] = self.basket['基期价格'] * self.basket['基期数量']
base_total = self.basket['基期支出'].sum()
# 计算当前总支出
self.basket[f'{period_label}价格'] = current_prices
self.basket[f'{period_label}支出'] = self.basket[f'{period_label}价格'] * self.basket['基期数量']
current_total = self.basket[f'{period_label}支出'].sum()
# 计算CPI
cpi = (current_total / base_total) * 100
# 存储CPI数据
if self.cpi_data is None:
self.cpi_data = pd.DataFrame({
'时期': [period_label],
'CPI': [cpi]
})
else:
new_data = pd.DataFrame({
'时期': [period_label],
'CPI': [cpi]
})
self.cpi_data = pd.concat([self.cpi_data, new_data], ignore_index=True)
return cpi
def calculate_inflation_rate(self):
"""计算通货膨胀率
Returns:
pd.DataFrame: 包含各期通货膨胀率的数据框
"""
if self.cpi_data is None or len(self.cpi_data) < 2:
raise ValueError("至少需要两期CPI数据才能计算通货膨胀率")
self.cpi_data['通货膨胀率(%)'] = self.cpi_data['CPI'].pct_change() * 100
return self.cpi_data[['时期', '通货膨胀率(%)']].dropna()
def plot_cpi_trend(self):
"""绘制CPI趋势图"""
if self.cpi_data is None or len(self.cpi_data) < 2:
raise ValueError("至少需要两期CPI数据才能绘制趋势图")
plt.figure(figsize=(10, 6))
plt.plot(self.cpi_data['时期'], self.cpi_data['CPI'], marker='o', linestyle='-')
plt.title('CPI趋势图')
plt.xlabel('时期')
plt.ylabel('CPI')
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# 使用示例
if __name__ == "__main__":
# 创建CPI计算器实例
cpi_calc = CPICalculator()
# 设置消费品篮子
items = ['面包', '牛奶', '鸡蛋', '汽油']
base_prices = [5, 8, 12, 6] # 基期价格(元)
base_quantities = [10, 5, 2, 40] # 基期购买数量
basket = cpi_calc.set_basket(items, base_prices, base_quantities)
print("消费品篮子信息:")
print(basket)
# 计算第一期CPI(假设为2020年)
prices_2020 = [5, 8, 12, 6] # 2020年价格
cpi_2020 = cpi_calc.calculate_cpi(prices_2020, '2020')
print(f"\n2020年CPI: {cpi_2020:.2f}")
# 计算第二期CPI(假设为2021年)
prices_2021 = [5.5, 8.5, 13, 7] # 2021年价格
cpi_2021 = cpi_calc.calculate_cpi(prices_2021, '2021')
print(f"2021年CPI: {cpi_2021:.2f}")
# 计算第三期CPI(假设为2022年)
prices_2022 = [6, 9, 14, 8] # 2022年价格
cpi_2022 = cpi_calc.calculate_cpi(prices_2022, '2022')
print(f"2022年CPI: {cpi_2022:.2f}")
# 计算通货膨胀率
inflation_rates = cpi_calc.calculate_inflation_rate()
print("\n各期通货膨胀率:")
print(inflation_rates)
# 绘制CPI趋势图
cpi_calc.plot_cpi_trend()
这个实现具有以下特点:
- 使用面向对象设计,便于扩展和维护
- 支持多期CPI计算和通货膨胀率分析
- 提供数据可视化功能,直观展示CPI变化趋势
- 包含完整的错误处理机制
- 代码结构清晰,注释完善,易于理解和使用
使用时,你可以根据实际需求修改商品篮子、价格数据或添加更多功能,如季节性调整、权重更新等高级CPI计算方法。