Full Box-Jenkins: SARIMA, exact likelihood, diagnostics and forecasting
The complete ARIMA modeling cycle: identification, estimation, diagnostics and forecasting. Add multiplicative seasonality through SARIMA, construct exact Gaussian likelihood with the innovations algorithm, select orders using information criteria, diagnose residuals and obtain forecasts with intervals. Finish with the Hyndman-Khandakar automatic search and its limitations.
After this lesson you can
- Write and expand a multiplicative SARIMA model and identify its seasonal ACF and PACF signature.
- Implement the innovations algorithm and exact ARMA likelihood and maximize it numerically.
- Select orders with AICc within a fixed d and explain why AIC values with different differencing are not directly comparable.
- Diagnose residuals and decide what to change when diagnostics fail.
- Produce forecasts with intervals and evaluate empirical coverage at rolling origins.
Before you start
- 26ARIMA modelPartial autocorrelation functionPortmanteau tests (Box-Pierce and Ljung-Box)Durbin-Levinson recursion and best linear predictorBox-Cox transformationForecasting baselinesLinear process
- 05Maximum likelihood estimator (MLE)Fisher information
- 14Bayesian information criterion
- 06BFGS method
- 02Cholesky decomposition
- 09Cholesky in finite precision: stability and jitter
A model is a cycle, not a call to fit
The monthly international-passenger series grows and changes scale; each year resembles the previous one but is not identical. A useful forecast starts by examining scale and seasonality, proposes a model, checks what remains unexplained and evaluates it on later observations.
The following exploration starts from the same public series used in series decomposition. Transform and difference step by step before interpreting autocorrelations: each operation changes the modeled object.
SARIMA and cross-lags
A multiplicative SARIMA with period combines regular and seasonal polynomials:
Multiplication matters: it is not equivalent to concatenating a list of lags. Under the positive MA convention, the airline model ARIMA satisfies
Lag 13 arises from interaction between the two MA parts. If both parameters are nonzero, there are four nonzero coefficients including the current one. The difference on the left also expands as . In monthly data, lags that are multiples of 12 may suggest a seasonal component; an isolated bar does not identify an order by itself.
Seasonal differencing removes exact period-12 repetition but can introduce dependence if unnecessary. First examine scale and patterns, then choose and using tests and problem knowledge. A logarithmic transformation changes scale and requires adjusting interpretation of forecasts and likelihoods.
Innovations and exact likelihood
Let be Gaussian with known mean and positive-definite covariance . The exact Gaussian likelihood of a stationary ARMA uses the joint distribution of the full vector, including its initial stationary distribution. Exact here refers to that finite distribution under the model, not a guarantee that the model is true.
The innovations algorithm decomposes each observation into its best linear prediction from previous observations and an innovation with variance . Under Gaussianity, innovations are independent. If , with lower triangular and unit diagonal,
For covariance and , coefficients follow from
The innovation is . The factorization has determinant because ; the transformation from centered observations to innovations is triangular with determinant one. Positivity of each guarantees valid steps. If is singular or numerically nearly singular, handle the degeneracy rather than dividing by zero variance.
A conditional likelihood may fix or discard initial observations and innovations; changing their treatment gives a different function from the exact likelihood. Near a boundary root or with short samples, this difference can affect estimation. The Kalman filter calculates the same kind of decomposition in a state-space representation with suitable initialization.
In ARMA(1,1), if , the AR factor nearly cancels the MA factor. The surface may have a ridge and standard errors may grow: many parameters explain almost the same process. More optimization decimal places do not remove that uncertainty.
Estimate and select
To maximize likelihood, respect causality and invertibility. In ARMA(1,1), and keep both moduli below one for finite . Higher orders require appropriate parameterizations or constraints for all roots; applying to each coefficient separately does not guarantee that every root meets stability conditions.
The information criteria, for maximized log-likelihood , estimated parameters and comparable observations, are
AICc requires . Count innovation variance and any estimated mean or initial state according to the likelihood definition. Compare orders on the same observations, transformation, initial conditions and likelihood definition.
When likelihood is calculated on previously differenced series, different or change the data and their initial conditions: do not compare AIC values as though they measured the same density. Fix differencing first and compare AR and MA orders within it. This is the recommendation of Forecasting: Principles and Practice. In principle, models with different orders can be compared if fully specified likelihoods are constructed on exactly the same data with compatible initialization treatments; do not assume compatibility from a software table. Log-likelihoods on original and transformed scales also require the corresponding Jacobian.
Diagnostics before publishing a forecast
Residual diagnostics examine standardized innovations after initialization. A lag-12 pattern suggests revisiting the seasonal part and transformation; it does not by itself establish that exactly one parameter must be added. Ljung-Box combines autocorrelations and typically subtracts degrees of freedom for a fitted ARMA, provided enough lags are used.
An approximately flat residual ACF does not guarantee independence. The ARCH-LM test examines dependence in squares; a normality test examines another feature important for Gaussian intervals. All three results can change with sample, initialization and prior model selection. If they fail, revisit specification, seasonality, breaks, outliers and conditional variance; evaluate again on later data.
Forecast fans and coverage
ARIMA prediction intervals combine uncertainty in future innovations with model dynamics. An interval calculated by plugging in parameter estimates usually treats them as known and can omit some fitting uncertainty. Heavier-tailed distributions or changing variance can also invalidate Gaussian intervals.
At each rolling origin , fit using only the past and check the observation at horizon . A 95% interval does not promise to cover every realization; coverage near nominal is expected under its assumptions and with enough independent evaluations. Nearby origins share training data and often future errors, so point count does not equal independent replication count. Group by path or use an estimate respecting this dependence.
The Box-Jenkins cycle alternates identification, estimation, diagnostics and evaluation. The Hyndman-Khandakar procedure automates part of selection with tests and stepwise order search; their paper describes information-criterion search after choosing differences. Local search can miss better combinations, and decisions depend on tests, limits and implementation options. Automation does not replace inspection of residuals and breaks or a test set.
Lab: innovations and a reproducible likelihood
First construct and factor the exact covariance of an ARMA(1,1). Innovation variance is one in the matrix; its scale is later estimated by profiling. The example is small so each cell runs in the browser.
import numpy as np
from scipy.linalg import toeplitz
from scipy.optimize import minimize
from statsmodels.tsa.arima_process import arma_acovf, ArmaProcess
def gamma_arma11(phi, theta, n):
if abs(phi) >= 1 or n < 1:
raise ValueError("se requiere AR causal")
g = np.empty(n)
g[0] = (1+2*phi*theta+theta**2)/(1-phi**2)
if n > 1:
g[1] = (phi+theta)*(1+phi*theta)/(1-phi**2)
for h in range(2,n):
g[h] = phi*g[h-1]
return g
def innovations_algorithm(gamma, n):
gamma = np.asarray(gamma, dtype=float)
if n < 1 or len(gamma) < n or gamma[0] <= 0:
raise ValueError("covarianzas insuficientes")
T = np.eye(n)
v = np.empty(n)
for i in range(n):
for j in range(i):
T[i,j] = (gamma[i-j]-np.dot(T[i,:j]*v[:j], T[j,:j]))/v[j]
v[i] = gamma[0]-np.dot(T[i,:i]**2,v[:i])
if v[i] <= 1e-12:
raise ValueError("covarianza no definida positiva")
return T, v
gamma = gamma_arma11(.6, -.3, 30)
T, v = innovations_algorithm(gamma, len(gamma))
Sigma = toeplitz(gamma)
L = np.linalg.cholesky(Sigma)
print("error de covarianza frente a statsmodels:",
np.max(abs(gamma-arma_acovf([1,-.6],[1,-.3],nobs=len(gamma)))))
print("error de reconstrucción y de Cholesky:",
np.max(abs([email protected](v)@T.T-Sigma)),
np.max(abs(T*np.sqrt(v)[None,:]-L)))The next cell generates an independent sample and maximizes exact profile likelihood with stationary initialization. Transformation constrains parameters and the mean is fixed at zero. Differences from the true value reflect small-sample variation and are not automatically errors.
def loglike_perfil(x, gamma):
n = len(x)
T, v = innovations_algorithm(gamma, n)
e = np.empty(n)
for i in range(n):
e[i] = x[i]-T[i,:i]@e[:i]
escala = np.mean(e*e/v)
if escala <= 0:
raise ValueError("escala no positiva")
ll = -.5*(n*(np.log(2*np.pi)+1+np.log(escala))+np.log(v).sum())
return ll, escala
rng = np.random.default_rng(13)
modelo = ArmaProcess([1,-.6],[1,-.3])
x = modelo.generate_sample(nsample=32, burnin=200, distrvs=rng.standard_normal)
def objetivo(z):
phi, theta = np.tanh(z)
return -loglike_perfil(x, gamma_arma11(phi,theta,len(x)))[0]
opt = minimize(objetivo, [0.,0.], method="L-BFGS-B",
bounds=[(-3,3),(-3,3)], options={"maxiter": 80})
phi_hat, theta_hat = np.tanh(opt.x)
ll, sigma2_hat = loglike_perfil(x, gamma_arma11(phi_hat,theta_hat,len(x)))
print("convergencia, φ, θ, varianza y log-verosimilitud:",
opt.success, phi_hat, theta_hat, sigma2_hat, ll)Compare that same density with SARIMAX without changing sample, mean or scale. The library likelihood uses a state-space representation; subsequent estimation can depend on optimizer and bounds.
from statsmodels.tsa.statespace.sarimax import SARIMAX
ref_model = SARIMAX(x, order=(1,0,1), trend="n",
enforce_stationarity=True, enforce_invertibility=True)
ll_ref = ref_model.loglike([phi_hat, theta_hat, sigma2_hat])
ref_fit = ref_model.fit(start_params=[phi_hat,theta_hat,sigma2_hat],
disp=False, maxiter=80)
print("log-verosimilitud propia y SARIMAX:", ll, ll_ref)
print("parámetros y errores estándar SARIMAX:", ref_fit.params, ref_fit.bse)
print("estado de convergencia:", ref_fit.mle_retvals.get("converged"))Extend to seasonality
Reuse the 144 AirPassengers values from the previous lesson. First separate the final two years: initial fitting and order selection use only the first 120 months. In subsequent sequential evaluation, the first evaluated year becomes available past for the second origin.
pasajeros = np.array([112,118,132,129,121,135,148,148,136,119,104,118,115,126,141,135,125,149,170,170,158,133,114,140,145,150,178,163,172,178,199,199,184,162,146,166,171,180,193,181,183,218,230,242,209,191,172,194,196,196,236,235,229,243,264,272,237,211,180,201,204,188,235,227,234,264,302,293,259,229,203,229,242,233,267,269,270,315,364,347,312,274,237,278,284,277,317,313,318,374,413,405,355,306,271,306,315,301,356,348,355,422,465,467,404,347,305,336,340,318,362,348,363,435,491,505,404,359,310,337,360,342,406,396,420,472,548,559,463,407,362,405,417,391,419,461,472,535,622,606,508,461,390,432], dtype=float)
train, test = pasajeros[:120], pasajeros[120:]
log_train = np.log(train)
dif = np.diff(log_train)
w = dif[12:]-dif[:-12]
print("entrenamiento, prueba y diferencias disponibles:", len(train), len(test), len(w))
print("primeros valores de la serie diferenciada:", np.round(w[:4], 5))In the airline model, innovation coefficients occur at lags 0, 1, 12 and 13. To compare without excessive browser cost, the following exact fit uses the first 36 differences. It calculates all their autocovariances from coefficient products and profiles variance. The library model uses those same differences as data, not the full level series.
def gamma_airline(theta, Theta, n):
psi = np.zeros(14)
psi[[0,1,12,13]] = [1.,theta,Theta,theta*Theta]
return np.array([psi[:len(psi)-h]@psi[h:] if h < len(psi) else 0.
for h in range(n)])
estacional = w[:36]
def objetivo_air(z):
theta, Theta = np.tanh(z)
return -loglike_perfil(estacional, gamma_airline(theta,Theta,len(estacional)))[0]
opt_air = minimize(objetivo_air, [0.,0.], method="L-BFGS-B",
bounds=[(-3,3),(-3,3)], options={"maxiter": 80})
theta_hat, Theta_hat = np.tanh(opt_air.x)
gamma_air = gamma_airline(theta_hat,Theta_hat,len(estacional)+1)
ll_air, scale_air = loglike_perfil(estacional, gamma_air[:-1])
ref_air = SARIMAX(estacional, order=(0,0,1), seasonal_order=(0,0,1,12),
trend="n", enforce_invertibility=True)
ll_ref_air = ref_air.loglike([theta_hat,Theta_hat,scale_air])
print("convergencia y parámetros:", opt_air.success, theta_hat, Theta_hat, scale_air)
print("parámetro libre cerca del límite de búsqueda:", np.any(abs(opt_air.x) > 2.99))
print("log-verosimilitud propia y SARIMAX:", ll_air, ll_ref_air)
ref_air_fit = ref_air.fit(start_params=[theta_hat,Theta_hat,scale_air],
disp=False, maxiter=100)
print("estimaciones y errores estándar SARIMAX:", ref_air_fit.params, ref_air_fit.bse)
print("convergencia SARIMAX:", ref_air_fit.mle_retvals.get("converged"))
Sigma = toeplitz(gamma_air[:-1])
cruzada = gamma_air[1:][::-1]
pred = [email protected](Sigma, estacional)
var = scale_air*(gamma_air[0][email protected](Sigma, cruzada))
ref_filtered = ref_air.filter([theta_hat,Theta_hat,scale_air])
pronostico = ref_filtered.get_forecast(steps=1)
print("predicción propia y SARIMAX:", pred, np.asarray(pronostico.predicted_mean)[0])
print("varianza propia y SARIMAX:", var, np.asarray(pronostico.var_pred_mean)[0])The preceding forecast concerns the twice-differenced series and is not yet a passenger forecast. To return to levels, undo both differences and then the logarithmic transformation. The cell’s comparisons condition on estimated parameters and selected history. The boundary indicator warns if the custom search reaches its imposed edge: in that case do not interpret the result as a well-identified interior maximum, even if the optimizer reports convergence.
Select, diagnose and evaluate
The following candidates are fitted to the same stationary training series with the same initialization. Compare AICc without using the test set. A small selection teaches the procedure; it is not exhaustive and does not prove the best model was found.
candidatos = [
("ruido", (0,0,0), (0,0,0,12)),
("MA regular", (0,0,1), (0,0,0,12)),
("MA regular y estacional", (0,0,1), (0,0,1,12)),
]
ajustados = []
for nombre, orden, estacional_orden in candidatos:
fit = SARIMAX(w, order=orden, seasonal_order=estacional_orden, trend="n",
enforce_invertibility=True).fit(disp=False, maxiter=100)
ajustados.append((nombre, fit))
print(nombre, "AICc:", fit.aicc, "convergencia:", fit.mle_retvals.get("converged"))
mejor_nombre, mejor = min(ajustados, key=lambda item: item[1].aicc)
print("elegido en entrenamiento:", mejor_nombre)The next diagnostic uses the model selected on training data and omits the initialization period reported by the library. Lag 24 covers two years; the choice should be fixed before inspecting results. A high value does not prove residuals are independent or normal.
from statsmodels.stats.diagnostic import acorr_ljungbox, het_arch
from scipy.stats import jarque_bera
inicio = mejor.loglikelihood_burn
resid = mejor.filter_results.standardized_forecasts_error[0, inicio:]
resid = resid[np.isfinite(resid)]
grados = mejor.model.k_ar_params+mejor.model.k_ma_params+mejor.model.k_seasonal_ar_params+mejor.model.k_seasonal_ma_params
lb = acorr_ljungbox(resid, lags=[24], model_df=grados)
arch = het_arch(resid, nlags=12, ddof=grados)
jb = jarque_bera(resid)
print("innovaciones, parámetros dinámicos:", len(resid), grados)
print("Ljung-Box Q y p:", lb["lb_stat"].iloc[0], lb["lb_pvalue"].iloc[0])
print("ARCH-LM estadístico y p:", arch[0], arch[1])
print("Jarque-Bera estadístico y p:", jb.statistic, jb.pvalue)To evaluate passenger levels, fit a SARIMA at each origin and compare it with seasonal naive and additive ETS. The SARIMA forecast is calculated on logs: under the normal predictive distribution, is the original-scale mean, appropriate for squared error. Intervals transform endpoints of the log-scale distribution. The last horizon at each origin is reserved to measure coverage without using it for fitting.
from statsmodels.tsa.exponential_smoothing.ets import ETSModel
errores_sarima, errores_base, errores_ets = [], [], []
aciertos80, aciertos95 = [], []
for origen in (120,132):
pasado = pasajeros[:origen]
real = pasajeros[origen:origen+12]
modelo = SARIMAX(np.log(pasado), order=(0,1,1),
seasonal_order=(0,1,1,12), trend="n",
enforce_invertibility=True).fit(disp=False, maxiter=100)
prediccion = modelo.get_forecast(steps=12)
mu = np.asarray(prediccion.predicted_mean)
var = np.asarray(prediccion.var_pred_mean)
media = np.exp(mu+var/2)
base = pasado[-12:]
ets = ETSModel(pasado, error="add", trend="add", seasonal="add",
seasonal_periods=12, initialization_method="heuristic").fit(disp=False, maxiter=100)
pred_ets = np.asarray(ets.forecast(12))
errores_sarima.extend(real-media)
errores_base.extend(real-base)
errores_ets.extend(real-pred_ets)
i80 = np.exp(np.asarray(prediccion.conf_int(alpha=.2))[-1])
i95 = np.exp(np.asarray(prediccion.conf_int(alpha=.05))[-1])
aciertos80.append(i80[0] <= real[-1] <= i80[1])
aciertos95.append(i95[0] <= real[-1] <= i95[1])
print("origen, convergencia SARIMA/ETS:",
origen, modelo.mle_retvals.get("converged"), ets.mle_retvals.get("converged"))
print("RMSE SARIMA, ingenuo estacional y ETS:",
*(np.sqrt(np.mean(np.asarray(e)**2)) for e in
(errores_sarima, errores_base, errores_ets)))
print("cobertura h=12 en dos orígenes, 80% y 95%:", sum(aciertos80), sum(aciertos95), "de", len(aciertos80))Two origins are insufficient to estimate coverage precisely. The simulated fans above allow repeated experiments under an explicit model; additional historical data would require a longer evaluation while preserving temporal separation.
Exercises
Step 1 of 3. What is the determinant of Σ?
import numpy as np
def innovations_algorithm(gamma, n):
pass
def loglike_innov(x, T, v):
passSARIMA combines regular and seasonal filters; its innovations factor a finite Gaussian likelihood. Order selection is completed by diagnostics and temporal evaluation, and interval coverage is checked rather than assumed.