기본 콘텐츠로 건너뛰기

pandas_ta를 적용한 통계적 인덱스 지표

[time series]ARIMAX

ARIMAX

이 모형은 여러개의 독립변수에 대해 arima 모형을 적용한 것으로 ARIMAX(ARIMA with Exogenous Variables)모형이라고 합니다.

arima 모형의 이론적 배경을 가지고 단순히 다변수의 독립변수를 적용한 것입니다.

import numpy as np
import pandas as pd
import FinanceDataReader as fdr
import matplotlib.pyplot as plt

from statsmodels.tsa.stattools import acf, pacf
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.metrics import mean_squared_error
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller, kpss #정상성 검정
from statsmodels.tsa.ar_model import AutoReg #AR모형
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.arima.model import ARIMA
from pmdarima import auto_arima
from statsmodels.stats.diagnostic import acorr_ljungbox #잔차의 자기상관 검정
st=pd.Timestamp(2024,9, 1)
et=pd.Timestamp(2025, 5,7)
trgnme="000660"
trg=fdr.DataReader(trgnme,  st, et)[["Open", "High", "Low", "Close", "Volume"]]
df=trg.copy()
df=df.asfreq("B")
df.index
DatetimeIndex(['2024-09-02', '2024-09-03', '2024-09-04', '2024-09-05',
               '2024-09-06', '2024-09-09', '2024-09-10', '2024-09-11',
               '2024-09-12', '2024-09-13',
               ...
               '2025-04-24', '2025-04-25', '2025-04-28', '2025-04-29',
               '2025-04-30', '2025-05-01', '2025-05-02', '2025-05-05',
               '2025-05-06', '2025-05-07'],
              dtype='datetime64[ns]', name='Date', length=178, freq='B')
df=df.ffill()
df.isnull().sum()
Open      0
High      0
Low       0
Close     0
Volume    0
dtype: int64
y=df["Close"]
X=df[["Open", "High", "Low"]]

model=ARIMA(y, exog=X, order=(2,2,0)).fit()
print(model.summary())
SARIMAX Results                                
==============================================================================
Dep. Variable:                  Close   No. Observations:                  178
Model:                 ARIMA(2, 2, 0)   Log Likelihood               -1630.797
Date:                Thu, 08 May 2025   AIC                           3273.593
Time:                        17:10:49   BIC                           3292.616
Sample:                    09-02-2024   HQIC                          3281.309
                         - 05-07-2025                                         
Covariance Type:                  opg                                         
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
Open          -0.6576      0.049    -13.553      0.000      -0.753      -0.562
High           0.8875      0.064     13.965      0.000       0.763       1.012
Low            0.7735      0.067     11.482      0.000       0.641       0.906
ar.L1         -1.0064      0.063    -16.038      0.000      -1.129      -0.883
ar.L2         -0.5726      0.062     -9.199      0.000      -0.695      -0.451
sigma2      6.789e+06   1.04e-09   6.53e+15      0.000    6.79e+06    6.79e+06
===================================================================================
Ljung-Box (L1) (Q):                  11.68   Jarque-Bera (JB):                 4.09
Prob(Q):                              0.00   Prob(JB):                         0.13
Heteroskedasticity (H):               0.62   Skew:                            -0.36
Prob(H) (two-sided):                  0.07   Kurtosis:                         2.80
===================================================================================

Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
[2] Covariance matrix is singular or near-singular, with condition number 2.69e+32. Standard errors may be unstable.

잔차에 대한 정상성 검정인 Ljung-Box (L1) (Q)와 정규성 검정인 Jarque-Bera (JB)의 결과는 모두 0.05보다 크므로 각 검정의 귀무가설을 기각할 수 없습니다. 즉, 이 모형의 잔차는 정상적이며 정규분포에 부합하므로 백색잡음이라 할 수 있습니다.

pred=model.predict(start=0,  end=len(df)-1)

plt.figure(figsize=(10, 3))
plt.plot(df.Close, label="origin")
plt.plot(pred, label="predict")
plt.show()

이 모델의 차분 차수는 2입니다. 그러므로 미래를 예측하기 위해서는 "2행 × 독립변수의 수" 차원의 독립변수가 필요합니다. 다음은 데이터의 최종일 다음 2일에 대한 예측입니다.

model.predict(start=len(df), end=len(df)+1, exog=X.tail(2))
2025-05-08    185754.471527
2025-05-09    190694.385431
Freq: B, Name: predicted_mean, dtype: float64

댓글