如何在Python statsmodels ARIMA预测中反转差异?

时间:2017-06-07 17:03:17

标签: python time-series forecasting statsmodels

我试图用Python和Statsmodels围绕ARIMA预测。具体而言,为了使ARIMA算法起作用,需要通过差分(或类似方法)使数据静止。问题是:在进行剩余预测之后,如何在差异化之后反转差异,以回归预测,包括趋势和季节性差异?

(我看到了一个类似的问题here但是唉,没有发布任何答案。)

这是我迄今为止所做的工作(基于掌握Python数据分析的最后一章中的示例,Magnus Vilhelm Persson; Luiz Felipe Martins)。数据来自DataMarket

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels import tsa 
from statsmodels.tsa import stattools as stt 
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.arima_model import ARIMA 

def is_stationary(df, maxlag=15, autolag=None, regression='ct'): 
    """Test if df is stationary using Augmented 
    Dickey Fuller""" 

    adf_test = stt.adfuller(df,maxlag=maxlag, autolag=autolag, regression=regression) 
    adf = adf_test[0]
    cv_5 = adf_test[4]["5%"]

    result = adf < cv_5    
    return result

def d_param(df, max_lag=12):
    d = 0
    for i in range(1, max_lag):
        if is_stationary(df.diff(i).dropna()):
            d = i
            break;
    return d

def ARMA_params(df):
    p, q = tsa.stattools.arma_order_select_ic(df.dropna(),ic='aic').aic_min_order
    return p, q

# read data
carsales = pd.read_csv('data/monthly-car-sales-in-quebec-1960.csv', 
                   parse_dates=['Month'],  
                   index_col='Month',  
                   date_parser=lambda d:pd.datetime.strptime(d, '%Y-%m'))
carsales = carsales.iloc[:,0] 

# get components
carsales_decomp = seasonal_decompose(carsales, freq=12)
residuals = carsales - carsales_decomp.seasonal - carsales_decomp.trend 
residuals = residuals.dropna()

# fit model
d = d_param(carsales, max_lag=12)
p, q = ARMA_params(residuals)
model = ARIMA(residuals, order=(p, d, q)) 
model_fit = model.fit() 

# plot prediction
model_fit.plot_predict(start='1961-12-01', end='1970-01-01', alpha=0.10) 
plt.legend(loc='upper left') 
plt.xlabel('Year') 
plt.ylabel('Sales')
plt.title('Residuals 1960-1970')
print(arimares.aic, arimares.bic)  

结果情节令人满意,但并未包含趋势,季节性信息。如何反转差分以重新获得趋势/季节性? Residual plot

1 个答案:

答案 0 :(得分:0)

Relying on differencing when a time trend (or multiple) may be a better strategy. Period 33 is an outlier and if you ignore it then it has consequences.

The PACF doesn't show a strong seasonal component.enter image description here

It is a weak seasonal AR with March, April, May and June with strong correlation.

enter image description here