如何使用arch库实现多期波动率预测?解决horizon参数显示异常问题
问题描述
我用arch库拟合了GARCH模型,尝试预测未来波动率,但无法查看次日之后的预测结果。修改horizon参数后仅生成命名为“h.”开头的新列,请问该如何解决?
代码示例
# 生成100期向前预测 gm_forecast = gm_result.forecast(horizon = 3, method='bootstrap', reindex=False) # reindex消除警告 # 打印预测方差 print(gm_forecast.mean) print(gm_forecast.residual_variance) print(gm_forecast.variance)
输出结果
h.1 h.2 h.3 Date 2022-05-20 0.230553 0.230553 0.230553 h.1 h.2 h.3 Date 2022-05-20 6.842437 7.512426 7.476012 h.1 h.2 h.3 Date 2022-05-20 6.842437 7.512426 7.476012
解决方案
你看到的h.1、h.2、h.3列其实就是样本最后一个日期(2022-05-20)之后第1、2、3期的波动率预测结果,并非没有生成次日之后的预测。arch库的forecast方法默认针对样本末尾日期,一次性输出后续horizon期的预测值,结果以列的形式区分各期,而非按日期行展开。
如果需要将预测值转换为「未来日期+对应预测值」的直观格式,可以用以下代码处理:
import pandas as pd # 提取波动率预测结果(以variance为例) forecast_var = gm_forecast.variance # 获取样本最后日期,生成对应未来3天的日期序列 last_date = forecast_var.index[0] future_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=3) # 将列形式的预测值重塑为带日期的DataFrame forecast_df = pd.DataFrame( forecast_var.values.flatten(), index=future_dates, columns=['predicted_variance'] ) print(forecast_df)
处理后输出格式如下:
predicted_variance 2022-05-21 6.842437 2022-05-22 7.512426 2022-05-23 7.476012
如果需要对样本内多个日期做滚动式的后续波动率预测,需要使用rolling_forecast方法替换单次的forecast。
内容的提问来源于stack exchange,提问作者Ekaterina Solodova
相关产品推荐
相关产品推荐

