AR, MA and ARMA models
Linear time-series models: linear processes as white-noise filters, autoregressive, moving-average and ARMA models. Study causality and invertibility through polynomial roots, ACF and PACF signatures, Yule-Walker estimation and the Durbin-Levinson recursion, which gives both the PACF and the best linear predictor.
After this lesson you can
- Calculate theoretical ACF and PACF for AR(1), AR(2), MA(1) and ARMA(1,1) and recognize their signatures in data.
- Determine causality and invertibility from polynomial roots and obtain the MA(∞) representation.
- Estimate an AR(p) using Yule-Walker and least squares and compare their properties.
- Implement Durbin-Levinson and use it to calculate PACF and linear forecasts with their errors.
- Explain the identifiability problem when φ(z) and θ(z) share roots.
Before you start
- 26Weak (second-order) stationarityAutocovariance functionAutocorrelation functionWhite noise and its variantsSample ACF and Bartlett's formula
- 02Toeplitz matrixPositive definite matrixCholesky decompositionOrthogonal projectionLeast squares
- 03Power series and radius of convergence
- 01Linear homogeneous recurrences
- 05Method of moments
The past as a filter
A value today can retain an old shock’s effect or share a recent innovation with yesterday’s value. An autoregressive model describes the first kind of memory through a recurrence; a moving average mixes present and past innovations. These names describe mechanisms different from the centered moving averages used to decompose a series.
In an AR(2), move the inverse roots and observe how the path and autocorrelation change. Complex conjugate roots can produce damped oscillations without a permanent deterministic cycle.
Linear processes and the lag operator
Let be centered white noise with variance . A causal linear process is written
The sum converges in by orthogonality of innovations. Its autocovariance is
The result depends on weak stationarity and convergence, not on Gaussian innovations. If coefficients are absolutely summable, the filter is also stable in that stronger sense. Relation recovers negative lags.
The lag operator acts as . An autoregressive AR() model and a moving-average MA() model use the convention
If it is AR, if it is MA, and when both can be positive it is an ARMA(). The constant of an AR regression with mean is , not necessarily . The statsmodels library takes AR polynomial coefficients, with signs opposite to the recurrence, and initial coefficient 1.
Roots, causality and invertibility
Causality and invertibility are read from polynomials without common factors, reduced to their actual degree. If no root of lies in the closed unit disk, the ARMA admits a stable causal representation . If no root of lies in that disk, innovations can be recovered through a stable causal filter of centered observations: .
The polynomial roots are outside the circle; their inverses are inside. The boundary requires special treatment: absolute stability does not follow. A stationary noncausal representation may exist with AR roots outside the causal region if it depends on future innovations; here causal refers to filter direction, not experimental causality.
If and share a factor, it cancels in the reduced representation and original parameters are not identifiable from the process law. For example, contains exact cancellation; under the corresponding stable causal solution, for any . Nearly shared roots give a weak signal and can make estimation unstable even when not identical.
AR(1), AR(2) y MA(1)
For with , the causal solution is . Thus,
With signs alternate; with the ACF decays without alternating. For a causal AR(2), the Yule-Walker equations give
The strict causal region is , and . If inverse roots are with and , the transient response oscillates with angular period and decreasing envelope. This does not require the spectral maximum or period estimated from a finite path to equal that value exactly.
For , , and for . Therefore . The pairs and can produce the same autocovariance if innovation variance is adjusted: invertibility chooses to obtain a canonical representation. Matching autocovariances do not imply equal finite-dimensional distributions without additional assumptions such as Gaussianity.
The mixed ARMA(1,1) case
With and ,
The formula follows by summing products of coefficients . Cancellation leaves white noise: writing two parameters does not create two identifiable effects. Invertibility of this representation additionally requires . In general, neither ACF nor PACF of a mixed model has a clean cutoff.
Partial autocorrelation at is the final coefficient of the best linear predictor of from , or equivalently the correlation of endpoints after projection onto intermediate lags, when residual variances are positive. In a causal AR() with effective order , PACF vanishes after ; in an MA(), ACF vanishes after . These cutoffs are theoretical and a finite sample may produce bars beyond them.
For MA(1), if , PACF at is
the expression has a limit when . For AR(1), PACF is at the first lag and zero afterward; for AR(2) it is and , and vanishes afterward. For ARMA(1,1), apply the next section’s recursion to its ACF: it yields each theoretical PACF without assuming a cutoff. Near cancellations and short samples can make distinct signatures look similar.
Linear prediction and Durbin-Levinson
Orthogonal projection onto leads to the Yule-Walker equations , with and . For unknown mean, center the series; sample covariance with common divisor keeps the matrix positive semidefinite. The solution is unique if is positive definite.
The Durbin-Levinson recursion extends the projection one lag at a time. With and ,
is PACF, are linear predictor coefficients and its error variance. The reduction follows by projecting onto the new residual orthogonal to the previous space. If a covariance matrix is singular, division requires handling the degenerate case. This is optimal linear prediction; it equals conditional expectation under joint Gaussianity, but not necessarily for every non-Gaussian process.
Estimation is not identification by looking at bars
Yule-Walker replaces theoretical autocovariances with estimates and solves the Toeplitz system. Conditional least squares fits each observation to available lags, discarding the prefix and estimating an intercept when appropriate. The methods differ in boundaries, normalization and treatment of the mean; they need not agree in finite samples.
For a fixed causal AR(1), with iid finite-variance innovations and usual regularity conditions, the least-squares estimator is consistent and its first-order asymptotic variance is . That approximation does not automatically describe short samples or parameters approaching one with well. When is close to one, burn-in needed to simulate stationarity grows and finite-sample biases can be significant.
Lab: filters, projections and estimation
In the following cells innovations are iid normal, seeds are fixed and burn-in is stated. The theoretical representation is truncated to calculate a controllable approximation: compare it with statsmodels arma_acf, which takes polynomials with initial coefficient.
import numpy as np
from statsmodels.tsa.arima_process import arma_acf, ArmaProcess
def psi_arma(phi, theta, cantidad):
phi, theta = np.asarray(phi), np.asarray(theta)
psi = np.zeros(cantidad)
psi[0] = 1.
for j in range(1, cantidad):
psi[j] = (theta[j-1] if j <= len(theta) else 0.)
for i in range(1, min(j, len(phi))+1):
psi[j] += phi[i-1]*psi[j-i]
return psi
def acf_desde_psi(psi, maxlag):
g = np.array([psi[:len(psi)-h] @ psi[h:] for h in range(maxlag+1)])
return g/g[0]
def simular_arma(phi, theta, n, burn, rng):
phi, theta = np.asarray(phi), np.asarray(theta)
p, q = len(phi), len(theta)
e = rng.normal(size=n+burn)
x = np.zeros(n+burn)
for t in range(len(x)):
x[t] = e[t]
for i in range(1, min(p,t)+1):
x[t] += phi[i-1]*x[t-i]
for j in range(1, min(q,t)+1):
x[t] += theta[j-1]*e[t-j]
return x[burn:]
phi, theta = [.7], [.4]
psi = psi_arma(phi, theta, 300)
ref_acf = arma_acf(np.r_[1., -np.array(phi)], np.r_[1., theta], lags=11)
print("primeros pesos:", np.round(psi[:6], 5))
print("máximo error ACF truncada:", np.max(abs(acf_desde_psi(psi, 10)-ref_acf)))
rng = np.random.default_rng(2611)
serie = simular_arma(phi, theta, 2000, 300, rng)
modelo = ArmaProcess(np.r_[1., -np.array(phi)], np.r_[1., theta])
print("proceso causal e invertible:", modelo.isstationary, modelo.isinvertible)
print("media y varianza de una trayectoria:", serie.mean(), serie.var())
r1, r2 = np.random.default_rng(12), np.random.default_rng(12)
propia = simular_arma(phi, theta, 300, 100, r1)
referencia = modelo.generate_sample(nsample=300, burnin=100, distrvs=r2.standard_normal)
print("error máximo de simulación con innovaciones iguales:", np.max(abs(propia-referencia)))Burn-in approximates stationarity; a fixed length does not guarantee it for every root near one. In this example the power of falls quickly; if you change the model, reconsider length and truncation error.
from scipy.linalg import toeplitz
from statsmodels.tsa.stattools import levinson_durbin
def durbin(gamma):
gamma = np.asarray(gamma, dtype=float)
if len(gamma) < 1 or gamma[0] <= 0:
raise ValueError("covarianza inicial inválida")
coef = np.empty(0)
pacf = [1.]
errores = [gamma[0]]
for k in range(1, len(gamma)):
reflejo = (gamma[k]-np.dot(coef, gamma[1:k][::-1]))/errores[-1]
nuevo = np.r_[coef-reflejo*coef[::-1], reflejo]
error = errores[-1]*(1-reflejo**2)
if error <= 0:
raise ValueError("matriz no definida positiva")
coef = nuevo
pacf.append(reflejo)
errores.append(error)
return coef, np.array(pacf), np.array(errores)
gamma = acf_desde_psi(psi, 10)
coef, pacf, errores = durbin(gamma)
directo = np.linalg.solve(toeplitz(gamma[:10]), gamma[1:11])
ref_v, ref_ar, ref_pacf, _, _ = levinson_durbin(gamma, nlags=10, isacov=True)
print("error respecto al sistema directo:", np.max(abs(coef-directo)))
print("error PACF frente a statsmodels:", np.max(abs(pacf-ref_pacf)))
print("varianza final propia y de referencia:", errores[-1], ref_v)
print("PACF teórica, primeros 4 retardos:", np.round(pacf[1:5], 5))def acov_muestral(x, p):
z = x-x.mean()
return np.array([z[:len(z)-h] @ z[h:]/len(z) for h in range(p+1)])
def yw(x, p):
g = acov_muestral(np.asarray(x), p)
return np.linalg.solve(toeplitz(g[:p]), g[1:])
def ols_ar(x, p):
x = np.asarray(x)
matriz = np.column_stack([np.ones(len(x)-p)] +
[x[p-j:len(x)-j] for j in range(1,p+1)])
return np.linalg.lstsq(matriz, x[p:], rcond=None)[0]
from statsmodels.regression.linear_model import yule_walker
coef_yw = yw(serie, 2)
coef_ols = ols_ar(serie, 2)
coef_ref, _ = yule_walker(serie, order=2, method="mle", demean=True)
print("YW propio y statsmodels:", coef_yw, coef_ref)
print("OLS con intercepto:", coef_ols)The following simulation repeats an AR(1) with a fixed coefficient near one. Each replication has new innovations and 500 burn-in steps; the comparison concerns the selected generator and sizes, not a universal bias law. Monte Carlo error decreases with more replications.
rng = np.random.default_rng(64)
reps, phi = 600, .95
for n in (80, 500):
x = np.zeros(reps)
trayectoria = np.empty((reps, n))
for t in range(500+n):
x = phi*x+rng.normal(size=reps)
if t >= 500:
trayectoria[:, t-500] = x
centrada = trayectoria-trayectoria.mean(axis=1, keepdims=True)
yw1 = np.sum(centrada[:,:-1]*centrada[:,1:], axis=1)/np.sum(centrada**2, axis=1)
anterior, actual = trayectoria[:,:-1], trayectoria[:,1:]
anterior = anterior-anterior.mean(axis=1, keepdims=True)
actual = actual-actual.mean(axis=1, keepdims=True)
ols1 = np.sum(anterior*actual, axis=1)/np.sum(anterior**2, axis=1)
print("n, media YW, media OLS, sesgo YW, desviación YW:",
n, yw1.mean(), ols1.mean(), yw1.mean()-phi, yw1.std(ddof=1))Exercises
Step 1 of 3. Why do partial sums of Σφʲεₜ₋ⱼ converge in L²?
import numpy as np
def durbin_levinson(gamma):
pass
def predecir(historia, media, coef):
passStep 1 of 3. If the first noise has variance σ², what must the second variance be?
An ARMA is an innovation filter. Roots determine when it can be expressed causally and noise recovered; Yule-Walker and Durbin-Levinson turn its autocovariance into linear predictions and error variances.