[PYTHON] Time-series analysis Implementation is stuck-Notes-

Premise

Book of time series analysis https://www.amazon.co.jp/%E6%99%82%E7%B3%BB%E5%88%97%E8%A7%A3%E6%9E%90-%E8%87%AA%E5%B7%B1%E5%9B%9E%E5%B8%B0%E5%9E%8B%E3%83%A2%E3%83%87%E3%83%AB%E3%83%BB%E7%8A%B6%E6%85%8B%E7%A9%BA%E9%96%93%E3%83%A2%E3%83%87%E3%83%AB%E3%83%BB%E7%95%B0%E5%B8%B8%E6%A4%9C%E7%9F%A5-Advanced-%E5%B3%B6%E7%94%B0-%E7%9B%B4%E5%B8%8C/dp/4320125010/ref=sr_1_1?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&dchild=1&keywords=%E6%99%82%E7%B3%BB%E5%88%97%E8%A7%A3%E6%9E%90&qid=1600932241&sr=8-1

Problem 1

AR model determined by AIC

#import is implemented as usual
model = ar_model.AR(y)
for i in range(20):
    results = model.fit(maxlag=i+1)

Then the following error occurs

RuntimeError: 
Model has been fit using maxlag=1, method=cmle, ic=None, trend=c. These
cannot be changed in subsequent calls to `fit`. Instead, use a new instance of
AR.

What I tried

code

model = ar_model.AR(y)
results = model.fit(maxlag=1)
print(results.aic)
results = model.fit(maxlag=2)
print(results.aic)

Output result

10.623349835083612
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-30-956416629a7e> in <module>
      2 results = model.fit(maxlag=1)
      3 print(results.aic)
----> 4 results = model.fit(maxlag=2)
      5 print(results.aic)

/opt/conda/envs/timeseries/lib/python3.8/site-packages/statsmodels/tsa/ar_model.py in fit(self, maxlag, method, ic, trend, transparams, start_params, solver, maxiter, full_output, disp, callback, **kwargs)
   1349         fit_params = (maxlag, method, ic, trend)
   1350         if self._fit_params is not None and self._fit_params != fit_params:
-> 1351             raise RuntimeError(REPEATED_FIT_ERROR.format(*self._fit_params))
   1352         if maxlag is None:
   1353             maxlag = int(round(12 * (nobs / 100.0) ** (1 / 4.0)))

RuntimeError: 
Model has been fit using maxlag=1, method=cmle, ic=None, trend=c. These
cannot be changed in subsequent calls to `fit`. Instead, use a new instance of
AR.

Solution 1

code

for i in range(20):
    model = ar_model.AR(y_diff)
    results = model.fit(maxlag=i+1)
    print(f'lag = {i + 1}\taic : {results.aic}')

Get the results you expect

Recommended Posts

Time-series analysis Implementation is stuck-Notes-
Implementation of independent component analysis
Simple regression analysis implementation in Keras
What is Multinomial Logistic Regression Analysis?