Module contents
Lesson 13 of 31Core 115 min

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

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.

InteractiveUnpacking the airline model

AirPassengers contains 144 monthly totals from 1949 to 1960, in thousands of passengers; these are the same data as the previous lesson. Source: R Datasets. Differences lose one and twelve observations respectively; the time axis starts at the first available transformed observation.

Series after selected operations

Transformed observation

Sample ACF

Monthly lag

Sample PACF

Monthly lag

ACF uses centered autocovariances with divisor n; PACF is computed from them using Durbin–Levinson. A single sample’s appearance does not automatically identify an order. The airline model is usually applied to the logarithm with both differences: its MA component has lags 0, 1, 12 and 13.

Log-likelihood surface of selected vector

θ horizontal; Θ vertical. A darker shade indicates higher log likelihood.
  • Selected point
  • Grid maximum

For each pair, the current vector is assumed to have zero mean and exact covariance of (1+θB)(1+ΘB¹²)ε, with Gaussian innovations; σ² is maximized analytically. Joint density is computed by banded Cholesky without fixing initial innovations to zero. The grid ranges from −0.9 to 0.9 in steps of 0.1 and its maximum is not a continuous optimum.

This is the likelihood of the selected transformed or differenced vector, without modeling initial level values; it excludes a transformation Jacobian and a complete likelihood of original levels. Changing transformation or differences changes the observed vector: do not directly compare models across those choices using these numbers. The map is descriptive, not a confidence region.

-0.4
-0.4
Observations in current series131
Point log likelihood242.77
Grid maximum244.51
θ and Θ at grid maximum−0.4, −0.6
Difference from maximum−1.74
Transform and difference the monthly series; compare ACF and PACF and explore seasonal parameters. Figure values are calculated using the indicated series and model.

SARIMA and cross-lags

A multiplicative SARIMA with period mm combines regular and seasonal polynomials:

ϕ(B)Φ(Bm)(1−B)d(1−Bm)DXt=c+θ(B)Θ(Bm)εt.\phi(B)\Phi(B^m)(1-B)^d(1-B^m)^D X_t =c+\theta(B)\Theta(B^m)\varepsilon_t.

Multiplication matters: it is not equivalent to concatenating a list of lags. Under the positive MA convention, the airline model ARIMA(0,1,1)(0,1,1)12(0,1,1)(0,1,1)_{12} satisfies

(1−B)(1−B12)Xt=(1+θB)(1+ΘB12)εt=εt+θεt−1+Θεt−12+θΘεt−13.(1-B)(1-B^{12})X_t =(1+\theta B)(1+\Theta B^{12})\varepsilon_t =\varepsilon_t+\theta\varepsilon_{t-1} +\Theta\varepsilon_{t-12}+\theta\Theta\varepsilon_{t-13}.

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 Xt−Xt−1−Xt−12+Xt−13X_t-X_{t-1}-X_{t-12}+X_{t-13}. 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 dd and DD using tests and problem knowledge. A logarithmic transformation changes scale and requires adjusting interpretation of forecasts and likelihoods.

Innovations and exact likelihood

Let X=(X1,…,Xn)T\boldsymbol X=(X_1,\ldots,X_n)^\mathsf T be Gaussian with known mean and positive-definite covariance Σ\Sigma. 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 ete_t with variance vtv_t. Under Gaussianity, innovations are independent. If Σ=T diag(v1,…,vn)TT\Sigma=T\,\mathrm{diag}(v_1,\ldots,v_n)T^\mathsf T, with TT lower triangular and unit diagonal,

log⁡L=−12∑t=1n[log⁡(2π)+log⁡vt+et2vt].\log L=-\frac12\sum_{t=1}^{n} \left[\log(2\pi)+\log v_t+\frac{e_t^2}{v_t}\right].

For covariance γ(i−j)\gamma(i-j) and i>ji>j, coefficients follow from

Tij=γ(i−j)−∑k<jTikTjkvkvj,vi=γ(0)−∑k<iTik2vk.T_{ij}=\frac{\gamma(i-j)-\sum_{k<j}T_{ik}T_{jk}v_k}{v_j}, \qquad v_i=\gamma(0)-\sum_{k<i}T_{ik}^2v_k.

The innovation is ei=Xi−μi−∑j<iTijeje_i=X_i-\mu_i-\sum_{j<i}T_{ij}e_j. The factorization has determinant ∏ivi\prod_i v_i because det⁡T=1\det T=1; the transformation from centered observations to innovations is triangular with determinant one. Positivity of each viv_i guarantees valid steps. If Σ\Sigma 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.

InteractiveThe geometry of likelihood

Perspective surface: height represents log likelihood minus its grid maximum.

Top view: horizontal φ, vertical θ. The orange point marks true parameters.

  • True parameters
  • Evaluated point
  • Cancellation θ = −φ

Darker blue corresponds to values closer to the maximum. Both views visually clip differences below −14; calculations and readouts use unclipped values. Points form a grid of 21 by 21, with |φ| and |θ| ≤ 0.9. The maximum is the greatest on that grid, not a continuous optimization.

The sample follows Xₜ = φXₜ₋₁ + εₜ + θεₜ₋₁, with zero-mean normal innovations of variance 1 and 200 warm-up steps. Changing n or true parameters reuses the same reproducible stream. Near φ + θ = 0, near-cancellation may leave a poorly identified ridge.

The exact method Cholesky-factorizes the full vector’s stationary covariance; variance is profiled as the Mahalanobis quadratic divided by n. The conditional method fixes ε₀ = 0, conditions on X₀ and profiles n − 1 residuals. Absolute log likelihoods use different numbers of observations: compare their surfaces, not their levels directly.

Surface
80
0.6
0.4
1
0.00
0.00
Valid grid points441 / 441
Selected-surface maximum−117.54
Maximum at (φ, θ), within grid(0.54, 0.36)
Exact log likelihood at point−148.29
Conditional log likelihood at point−146.35
Profiled σ²: exact / conditional2.39 / 2.38
Compare exact and conditional likelihoods for a simulated ARMA(1,1). Near cancellation, different parameter pairs can give similar forecasts.

In ARMA(1,1), if θ≈−ϕ\theta\approx-\phi, 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), ϕ=tanh⁡a\phi=\tanh a and θ=tanh⁡b\theta=\tanh b keep both moduli below one for finite a,ba,b. Higher orders require appropriate parameterizations or constraints for all roots; applying tanh⁡\tanh to each coefficient separately does not guarantee that every root meets stability conditions.

The information criteria, for maximized log-likelihood ℓ\ell, kk estimated parameters and nn comparable observations, are

AIC=−2ℓ+2k,AICc=AIC+2k(k+1)n−k−1,BIC=−2ℓ+klog⁡n.\mathrm{AIC}=-2\ell+2k,\quad \mathrm{AICc}=\mathrm{AIC}+\frac{2k(k+1)}{n-k-1},\quad \mathrm{BIC}=-2\ell+k\log n.

AICc requires n>k+1n>k+1. 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 dd or DD 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 p+q+P+Qp+q+P+Q 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.

InteractiveRepeated forecasts
Time relative to origin; point marks evaluated horizon
  • Fit history
  • 95% interval
  • 80% interval and forecast
  • Observed future

The series satisfies ΔXₜ = 0.12 + εₜ with innovation variance 1. The t(3) option uses a three-degree-of-freedom t divided by √3 to preserve that variance. At each origin we fit the mean and sample deviation of the last m increments. The figure shows the first path and its last origin; the observed future is generated separately from the fit.

For both innovation types, the fan assumes Gaussian errors with estimated deviation and uses 2500 simulations shared across origins to obtain marginal quantiles at each horizon, not a simultaneous band for the whole path. Including drift uncertainty approximates error variance by σ̂²(h + h²/m), adding a normal drift perturbation of deviation σ̂/√m to innovations. This plug-in approximation neither integrates uncertainty in σ nor guarantees exact coverage, especially with heavy tails.

Coverage evaluates 64 independent paths and 20 consecutive origins per path at one horizon. Fit windows overlap and, if h > 1, future periods also overlap; therefore the 1280 cases are not independent. The counter intervals use 500 whole-path resamples and describe approximate Monte Carlo variation conditional on simulated fan quantiles. A finite run can exceed or fall below the nominal level.

Actual innovations
20
1
80% coverage1003 / 1280 · 78.4 %
Path bootstrap, 80%76.3 % a 80.2 %
95% coverage1185 / 1280 · 92.6 %
Path bootstrap, 95%91.3 % a 93.8 %
Estimated drift and deviation in shown path0.288 · 1.054
Seed2613
Compare forecast fans and coverage in simulated replications and rolling origins. Observed coverage is finite and depends on assumptions and the fitted model.

At each rolling origin TT, fit using only the past and check the observation at horizon hh. 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.

[ ]ARMA(1,1): covariances and innovations factorizationBrowser
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 tanh⁡\tanh constrains parameters and the mean is fixed at zero. Differences from the true value reflect small-sample variation and are not automatically errors.

[ ]Exact likelihood and optimizationBrowser
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.

[ ]Comparison with SARIMAX likelihoodBrowser
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.

[ ]Passengers, log scale and differencesBrowser
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.

[ ]Seasonal MA: covariance, likelihood and predictionBrowser
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 ww 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.

[ ]Three orders on the same differencesBrowser
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 pp value does not prove residuals are independent or normal.

[ ]Innovation diagnosticsBrowser
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, exp⁡(μ+v/2)\exp(\mu+v/2) 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.

[ ]Rolling origins and out-of-sample comparisonBrowser
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

ProofFrom covariance to innovations
Prove: Prove that the Gaussian density of a centered vector with positive-definite covariance Σ factors into one-step innovation densities.
0
Use Σ=T diag(v) Tᵀ, where T is triangular with unit diagonal, and e=T⁻¹x.

Step 1 of 3. What is the determinant of Σ?

NumericCrossed seasonal lags
In (1+θB)(1+ΘB¹²), with nonzero θ and Θ, how many distinct positive innovation lags appear when expanding the product?
CodeFactorization and density
Implement innovations_algorithm(gamma, n), returning unit-diagonal lower-triangular T and variances v for Σ=T diag(v) Tᵀ with Σᵢⱼ=gamma[|i−j|]. Reject insufficient covariances or nonpositive variances. Also implement loglike_innov(x, T, v), calculating the centered Gaussian log-density of x with scale already included in v.
import numpy as np

def innovations_algorithm(gamma, n):
  pass

def loglike_innov(x, T, v):
  pass
Shift+Enter to run
QuizA residual pattern
A model for monthly data leaves significant autocorrelation near lag 12. What is the most reasonable next step?
QuizCriteria on comparable data
A procedure calculates one model likelihood on levels and another on first differences, discarding their initial conditions. Why is choosing the lowest AIC insufficient?
Key idea

SARIMA 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.