生生不息

生生不息

AI实现CCC-GARCH模型

2025-06-29
AI实现CCC-GARCH模型

提示词

# Python代码
# 读取下载的Excel文件并处理
df = pd.read_excel('../数据/棉花十年行情数据.xlsx')#换成你保存文件的路径
df = df[['日期', '收盘价']]
df.set_index('日期', inplace=True)

#检查数据 
df.tail()
# Python代码
# 读取棕榈油期货行情数据Excel文件
df2 = pd.read_excel('../数据/棕榈油十年行情数据.xlsx', index_col='日期')
df2 = df2['收盘价']

# df是棉花期货的收盘价
# 将两个期货的收盘价合并进一个dataframe
df = df.join(df2, lsuffix='棉花',rsuffix='棕榈油')

# 检查结果
df.tail()
# Python代码
# 计算两种期货的价格变动
returns = df.pct_change().dropna()*100

# 重命名列名
returns.columns = ['棉花期货涨跌', '棕榈油期货涨跌']

# 数据可视化
returns.plot(subplots=True, figsize=(15,10))
plt.title('两种期货的价格波动', fontsize=20)
plt.savefig('图9-5.jpg',dpi=300)
plt.show()

使用上面的returns DataFrame,分别用两种期货的行情数据拟合GARCH模型,并将模型的系数、条件波动性、标准化残差和模型本身保存在不同的列表中,请给出示例代码。

答案

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from arch import arch_model

# 1. 数据准备(已加载returns DataFrame)
# 假设returns DataFrame包含'棉花期货涨跌'和'棕榈油期货涨跌'两列收益率数据
print(returns.head())

# 2. 初始化存储结果的列表
model_params = []        # 存储模型系数
cond_volatility = []     # 存储条件波动性
std_residuals = []       # 存储标准化残差
garch_models = []        # 存储模型对象本身
model_summaries = []     # 存储模型摘要
forecast_results = []    # 存储预测结果

# 3. 对每个期货品种拟合GARCH模型
commodities = ['棉花期货涨跌', '棕榈油期货涨跌']

for commodity in commodities:
    print(f"\n{'='*50}")
    print(f"拟合{commodity}的GARCH模型...")
    print('='*50)
  
    # 3.1 拟合GARCH(1,1)模型[1,5,10](@ref)
    model = arch_model(
        returns[commodity].dropna(),
        mean='Constant',   # 常数均值模型
        vol='Garch',       # GARCH波动率模型
        p=1,               # GARCH阶数
        q=1,               # ARCH阶数
        dist='StudentsT'   # 使用学生t分布考虑厚尾特征[4](@ref)
    )
  
    # 3.2 模型拟合[2,6](@ref)
    result = model.fit(disp='off', show_warning=False)
  
    # 3.3 保存模型对象
    garch_models.append(result)
  
    # 3.4 保存模型系数[1,10](@ref)
    params = result.params
    model_params.append(params)
    print(f"{commodity}模型参数:")
    print(params.to_string())
  
    # 3.5 保存条件波动性[1,7](@ref)
    vol_series = result.conditional_volatility
    cond_volatility.append(vol_series)
    print(f"\n{commodity}平均条件波动率: {vol_series.mean():.4f}")
  
    # 3.6 计算并保存标准化残差[7,8](@ref)
    resid = result.resid
    std_resid = resid / vol_series
    std_residuals.append(std_resid)
    print(f"{commodity}标准化残差均值: {std_resid.mean():.4f},标准差: {std_resid.std():.4f}")
  
    # 3.7 保存模型摘要
    model_summaries.append(result.summary())
  
    # 3.8 波动率预测(未来5天)[1](@ref)
    forecast = result.forecast(horizon=5)
    forecast_results.append(forecast)
    print(f"\n{commodity}未来波动率预测:")
    print(np.sqrt(forecast.variance.iloc[-1]))

# 4. 结果可视化
plt.figure(figsize=(15, 10))

# 4.1 棉花期货结果
plt.subplot(2, 2, 1)
plt.plot(cond_volatility[0], label='条件波动率', color='blue')
plt.title('棉花期货: 条件波动率', fontsize=12)
plt.grid(alpha=0.3)
plt.legend()

plt.subplot(2, 2, 2)
plt.hist(std_residuals[0], bins=50, alpha=0.7, color='green')
plt.title('棉花期货: 标准化残差分布', fontsize=12)
plt.grid(alpha=0.3)

# 4.2 棕榈油期货结果
plt.subplot(2, 2, 3)
plt.plot(cond_volatility[1], label='条件波动率', color='red')
plt.title('棕榈油期货: 条件波动率', fontsize=12)
plt.grid(alpha=0.3)
plt.legend()

plt.subplot(2, 2, 4)
plt.hist(std_residuals[1], bins=50, alpha=0.7, color='orange')
plt.title('棕榈油期货: 标准化残差分布', fontsize=12)
plt.grid(alpha=0.3)

plt.tight_layout()
plt.savefig('garch_model_results.png', dpi=300)
plt.show()

# 5. 模型保存(可选)[3](@ref)
import joblib

# 5.1 保存模型对象
model_data = {
    'commodities': commodities,
    'params': model_params,
    'cond_volatility': cond_volatility,
    'std_residuals': std_residuals,
    'models': garch_models
}

joblib.dump(model_data, 'garch_models.pkl')

# 5.2 保存模型摘要文本
with open('garch_model_summaries.txt', 'w') as f:
    for i, summary in enumerate(model_summaries):
        f.write(f"{'='*50}\n")
        f.write(f"{commodities[i]} GARCH模型摘要\n")
        f.write(f"{'='*50}\n\n")
        f.write(str(summary))
        f.write("\n\n\n")

print("\n模型结果已保存到文件:")
print("garch_models.pkl - 包含所有模型对象和数据")
print("garch_model_summaries.txt - 包含模型摘要")

结果:

计算恒定条件相关性矩阵

提示词

简化代码加描述

# Python代码
# 'returns' 包含 '棉花期货涨跌' 和 '棕榈油期货涨跌' 列
# 初始化空列表用于保存结果
model_coeffs = []
conditional_volatility = []
standard_resid = []
garch_models = []

# 提取列名,即两种期货的名称
columns = returns.columns

# 遍历每个期货,拟合 GARCH 模型并保存结果
for column in columns:
    # 创建 GARCH 模型
    model = arch_model(returns[column], vol='Garch', p=1, q=1)
  
    # 拟合模型
    result = model.fit(update_freq=0, disp="off")
  
    # 将结果保存到相应的列表中
    model_coeffs.append(result.params)
    conditional_volatility.append(result.conditional_volatility)
    standard_resid.append(result.std_resid)
    garch_models.append(result)



# 将模型系数转化为dataframe
coeffs_df = pd.DataFrame(model_coeffs, index=columns)
# 检查结果
coeffs_df

现在要基于上面代码中的standard_resid计算恒定条件相关性矩阵,请给出示例代码。

答案

import numpy as np
import pandas as pd

# 1. 将标准化残差组合成DataFrame
# 假设standard_resid是包含两个期货品种标准化残差的列表
std_resid_df = pd.DataFrame({
    '棉花标准化残差': standard_resid[0],
    '棕榈油标准化残差': standard_resid[1]
}, index=returns.index)  # 使用原始收益率数据的索引

# 2. 计算恒定条件相关系数
# CCC矩阵的核心是计算标准化残差的样本相关系数
ccc_matrix = std_resid_df.corr()

# 3. 输出CCC矩阵
print("恒定条件相关性(CCC)矩阵:")
print(ccc_matrix)

# 4. 高级可视化(使用热力图展示)
import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 8))
sns.heatmap(
    ccc_matrix,
    annot=True,          # 显示数值
    cmap='coolwarm',     # 冷暖色系区分正负相关
    vmin=-1, vmax=1,     # 相关系数范围
    square=True,         # 单元格为正方形
    fmt=".4f",           # 显示4位小数
    linewidths=0.5       # 单元格边界线宽
)
plt.title('标准化残差的恒定条件相关性矩阵', fontsize=14)
plt.savefig('ccc_correlation_matrix.png', dpi=300, bbox_inches='tight')
plt.show()

结果: