import pandas as pd import numpy as np import matplotlib.pyplot as plt from statsmodels.tsa.stattools import adfuller from statsmodels.stats.diagnostic import acorr_ljungbox from arch import arch_model from pmdarima.arima import auto_arima # 读取Excel数据 data = pd.read_excel('三个-负向标准化-二分.xlsx') data2 = pd.read_excel # 将数据转换为时间序列 data['DATE'] = pd.to_datetime(data['DATE']) # data.set_index('DATE', inplace=True) data = data['F4'] # ADF检验 ADFresult = adfuller(data) print('ADF Statistic: %f' % ADFresult[0]) print('p-value: %f' % ADFresult[1]) if ADFresult[1] > 0.05: # 进行差分 diff_data = data.diff().dropna() # 再次进行ADF检验 AADFresult = adfuller(diff_data) print('ADF Statistic after differencing: %f' % AADFresult[0]) print('p-value after differencing: %f' % AADFresult[1]) data = diff_data # Ljung-Box检验 # result = acorr_ljungbox(data, lags=10) # print('Ljung-Box Statistics: ', result[0]) # print('p-values: ', result[1]) # 使用auto_arima函数选择最佳ARIMA模型 stepwise_model = auto_arima(data, start_p=0, start_q=0, max_p=15, max_q=15, start_P=0, seasonal=False, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=False) model_resid = stepwise_model.resid() print(stepwise_model.summary()) # # 计算ARIMA-GARCH组合模型的参数 # model = arch_model(model_resid, mean='AR', lags=2, vol='GARCH', p=2, o=0, q=1) # AGresult = model.fit(disp='off') # print(AGresult.summary()) model = arch_model(model_resid, mean='AR', lags=2, vol='GARCH', o=0) # 使用 auto_arima 函数自动确定 p 和 q 的值 stepwise_fit = auto_arima(model_resid, start_p=0, start_q=0, max_p=5, max_q=5, start_P=0, seasonal=True, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True, stepwise=False) # 根据自动确定的 p 和 q 的值来拟合模型 model = arch_model(model_resid, mean='AR', lags=2, vol='GARCH', p=stepwise_fit.order[1], q=stepwise_fit.order[2], o=0) AGresult = model.fit(disp='off') print(AGresult.summary())后面加上对最终残差进行检验的代码
时间: 2024-02-19 18:01:52 浏览: 167
numpy-1.26.4.tar.gz
可以加上以下代码来对最终的残差进行检验:
# 残差序列的Ljung-Box检验
resid_lb = acorr_ljungbox(AGresult.resid, lags=10)
print('Ljung-Box Statistics of Residuals: ', resid_lb[0])
print('p-values of Residuals: ', resid_lb[1])
# 残差序列的自相关图和偏自相关图
fig, ax = plt.subplots(nrows=2, figsize=(10, 8))
fig.subplots_adjust(hspace=0.5)
ax[0].plot(AGresult.resid)
ax[0].set_title('Residuals of ARIMA-GARCH Model')
ax[1] = plot_acf(AGresult.resid, ax=ax[1], lags=10)
plt.show()
其中,acorr_ljungbox() 函数用于进行 Ljung-Box 检验,plot_acf() 函数用于绘制自相关图和偏自相关图。通过这些检验和图形可以对模型的残差进行评估,判断模型是否具有良好的拟合效果。
阅读全文