使用 garch 对中证 500 进行滚动预测并评估 VaR 的代码?
解读
中证 500 指数日收益序列存在“波动聚集、尖峰厚尾、杠杆效应”三大特征,面试官希望候选人:
- 用滚动窗口(rolling window)而非全样本一次性拟合,体现“真·实盘”思维;
- 每一步都用前 N 日数据估计 GARCH 参数,预测下一日波动率,并计算 1-day 99% VaR;
- 用 Kupiec 失败率检验或动态损失函数(如 QS)回测 VaR 有效性;
- 代码必须“能跑、能改、能上线”——变量命名规范、注释中文、无硬编码路径、支持中文 Windows 字体。
知识点
- 日收益计算:对数收益、复权价、停牌填充
- GARCH(P,Q) 条件方差方程与稳健标准误(HAC)
- 滚动窗口:for-loop + 预分配、或 tall/ timetable + slidingwindow
- VaR 参数法:假设标准化残差 ~ 标准化 t,自由度由 GARCH 输出
- 回测:失败率、LRuc、LRcc、DQ、ES 回测
- MATLAB 细节:garch 对象与 estimate 的 Options、presample 处理、中文画图、parfor 加速
答案
%% 0. 环境清理与数据读取(万得/聚宽导出 CSV,含日期、收盘价)
clear; clc; close all;
data = readtable('CSI500.csv','TextType','string'); % 中文路径友好
data = sortrows(data,'Date'); % 升序
price = data.Close; % 复权收盘价
ret = 100 * diff(log(price)); % 对数收益*100,与GARCH尺度匹配
dates = data.Date(2:end);
%% 1. 参数区(可改)
win = 1000; % 滚动窗长
VaRLevel= 0.99; % 99% VaR
P = 1; % GARCH(P,Q)
Q = 1;
%% 2. 预分配
T = numel(ret);
nRoll = T - win;
VaR = NaN(nRoll,1); % 预测 VaR
converg = false(nRoll,1); % 收敛标志
params = table();
%% 3. 滚动估计与预测
for i = 1:nRoll
y0 = ret(i:i+win-1); % 训练集
spec = garch('Constant',0.05,'GARCH',0.8,'ARCH',0.15,'Distribution','t');
try
[Est,~,~,LogL] = estimate(spec,y0,'Display','off',...
'Options',optimoptions('fmincon','Algorithm','sqp',...
'Display','off','MaxIterations',200));
[~,sigma2] = forecast(Est,1,'Y0',y0); % 预测下一期条件方差
nu = Est.DoF; % t 分布自由度
VaR(i) = -tinv(1-VaRLevel,nu) * sqrt(sigma2);
converg(i) = true;
catch ME
warning('第 %d 次滚动未收敛:%s',i,ME.message);
VaR(i) = NaN;
end
end
%% 4. 回测:失败率与 Kupiec LR
idx = win+1:T;
actual = ret(idx);
hit = actual < -VaR;
failRate = mean(hit);
LRuc = -2*log( ((1-VaRLevel)^(nRoll-sum(hit)) * VaRLevel^sum(hit)) / ...
( (1-failRate)^(nRoll-sum(hit)) * failRate^sum(hit) ) );
pValue = 1 - chi2cdf(LRuc,1);
fprintf('失败率 = %.2f%%,LR 统计量 = %.3f,p 值 = %.4f\n',failRate*100,LRuc,pValue);
%% 5. 可视化(中文)
figure;
yyaxis left
plot(dates(idx),actual,'k','LineWidth',0.8); hold on
plot(dates(idx),-VaR,'r','LineWidth',1.2);
ylabel('日收益 %');
yyaxis right
plot(dates(idx),cumsum(hit),'b','LineWidth',1);
ylabel('累计突破次数');
title('中证500 滚动GARCH(1,1)-t 99% VaR 回测');
legend('实际收益','VaR','累计突破','Location','best');
set(gca,'FontName','SimHei');
grid on
%% 6. 输出 CSV 供风控平台对接
out = timetable(dates(idx),actual,VaR,hit,'VariableNames',{'Return','VaR','Hit'});
writetimetable(out,'CSI500_GARCH_VaR.csv');
拓展思考
- 杠杆效应:改用 EGARCH 或 GJR-GARCH,观察 VaR 在极端下跌日是否更保守;
- 多步 VaR:用
simulate生成路径,计算 5-day 99% VaR,满足《证券公司风控指标》要求; - 并行加速:把
for换成parfor,在 8 核笔记本上提速 5-6 倍; - 模型风险:引入 Model Confidence Set (Hansen),对比 GARCH、GAS、Realized GARCH;
- 监管报送:把输出封装成 MATLAB Production Server RESTful API,每日收盘后 30 秒内自动推送 VaR 与 ES 到证监局 XBRL 模板。