Algorithmcore
Yule-Walker equations
Also called Yule-Walker estimation.
Estimates an AR(p) model by solving the Toeplitz system of sample autocovariances Gamma_p phi = gamma_p, in O(p^2) by the Levinson-Durbin recursion.
- Time
- Θ(n p) worst · best
- Space
- Θ(n) extra
- Where
- n = the length of the series; p = the autoregressive order
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- G. Udny Yule, Gilbert Walker, Norman Levinson, James Durbin, 1931
The Yule-Walker equations link the coefficients of an autoregressive model to its autocovariances: , where is the Toeplitz matrix of autocovariances and . The Yule-Walker estimator replaces the autocovariances by their sample values, with the divisor , and solves the system. It is a method-of-moments estimator. The Levinson-Durbin recursion solves the system for all orders in operations and gives the sample partial autocorrelations on the way. The fitted model is always causal, and for an AR process the estimator is as efficient as maximum likelihood in large samples. It is biased toward zero in small samples, and most when a root is near the unit circle. It is the same computation as autocorrelation-method linear prediction in signal processing.
In plain words
Suppose each value of a series is a weighted sum of the last few values plus noise, and you want the weights. Multiply the model equation by an earlier value and average. You get one equation for each lag, which ties the weights to how strongly the series is correlated with itself at that lag. Estimate those correlations from the data and solve the equations. A clever recursion solves them one order at a time: it fits one lag, then two, and so on, and each step costs little. The number it adds at each step is the partial autocorrelation, which tells you whether one more lag helps.
The problem
Model. come from a causal AR() process with and . The order is given.
Population equations. Multiply by and take expectations. Causality makes uncorrelated with the past, so
In matrix form and .
Estimator. With the sample mean and ,
Output. , , and the sample partial autocorrelations .
Requirements. The data are not all equal. Then is positive definite and the solution exists and is unique.
The algorithm
YULE-WALKER(x[1..n], p)- 1
m ← (x[1] + ... + x[n]) / n - 2
for h ← 0 to p do γ[h] ← (1/n) Σ_{t=1}^{n-h} (x[t+h] - m)(x[t] - m) - 3
v ← γ[0] - 4
for k ← 1 to p do - 5
a ← (γ[k] - Σ_{j=1}^{k-1} φ[j] γ[k-j]) / v - 6
for j ← 1 to k-1 do φ'[j] ← φ[j] - a · φ[k-j] - 7
φ'[k] ← a; φ ← φ'; pacf[k] ← a - 8
v ← v · (1 - a²) - 9
return (φ[1..p], v, pacf[1..k])
Lines L1 and L2 compute the sample autocovariances with the divisor . Lines L3 to L8 are the Durbin-Levinson recursion: after step , solves the order- system and is the order- prediction error. The code works with any field arithmetic, so the tests run it on Fraction values and compare with Gaussian elimination. With a known mean, L1 is skipped and .
Example
Take , , . The deviations are , and
| step | after the step | ||
|---|---|---|---|
| 0 | 3.36 | ||
| 1 | |||
| 2 | 1.148254 | ||
| 3 | 1.146005 |
In exact arithmetic , the AR(2) fit is and . The AR(2) polynomial has complex roots of modulus , so the fitted model is causal, as the theory promises. The third partial autocorrelation, , reduces by only 0.2%, which points to . The tests check all of these numbers.
Correctness
The full proof is in proofs/correctness.md. Claim 1 derives the population equations from causality. Claim 2 proves the recursion: the order- system is persymmetric, so the order- solution read backwards solves the reversed system, and a single scalar fixes the last equation; the prediction error then falls by the factor . Claim 3 shows that the divisor- matrix is positive definite when the data are not constant, so every and every . Claim 4 proves that the fitted polynomial has all its roots outside the unit circle. The large-sample results below are cited, not proved.
Proof: The Durbin-Levinson recursion solves the Yule-Walker system of every order, and with the divisor-n autocovariance the fitted autoregression is always causalfull
Setting. is an even function on the integers, , and is the exchange matrix, which reverses the order of a vector. For the estimator, is the sample autocovariance with the divisor , computed by lines L1 and L2. For let solve , and let , with .
Claim 1 (the population equations). If is a causal AR() process with , then and . If is nonsingular, these equations determine and from .
Proof. Put . Causality gives , so for , and . Multiply the model equation by and take expectations: for , which is . With : .
Claim 2 (the recursion). Suppose is nonsingular for and . Then for each , with
the solution of order is for and , and . These are lines L5 to L8, so after step the variables hold and , and the value appended to the PACF list is .
Proof. Because is a symmetric Toeplitz matrix, (persymmetry), with . Partition
and try for a scalar . The first block row gives , for every . The last row gives
which equals exactly when . Since is nonsingular, this is the unique solution. For the error,
Claim 3 (positive definiteness). If the data are not all equal, then is positive definite for every . Hence every and every , so lines L5 and L8 never divide by 0 and the code never raises its error on such data.
Proof. Let for and otherwise. Not all are 0. Then over all integers , and for ,
If this is 0, then the convolution of with is 0, so the polynomial product is 0. The first factor is not the zero polynomial, so . Thus is positive definite. Next, can be written with in the top left corner and in the bottom right, because it is persymmetric. Its Schur complement is , so . By Claim 2, , so .
Claim 4 (the fitted model is causal). If the data are not all equal, then every root of satisfies .
Proof. The function (0 for ) is even and nonnegative definite, by the computation in Claim 3 for every . So it is the autocovariance of a stationary Gaussian process with mean 0 (Brockwell and Davis 1991, Section 1.5). Work in the complex space with . Because is real, symmetric and positive definite, the vector is the unique minimizer over of , and the minimum is .
Let be a root, and write with . Put . Its variance does not depend on and is positive, because and is positive definite. For any , is of the form , so
The function is a strictly convex quadratic in , with the unique minimizer and minimum . Since attains the smallest possible value , it is the minimizer: . By the Cauchy-Schwarz inequality, . If , then , which contradicts Claim 3. So , that is .
Claim 5 (exact arithmetic). Lines L1 to L9 use only addition, subtraction, multiplication and division. On rational inputs in exact rational arithmetic they return the exact solution and the exact .
Proof. Claims 2 and 3 show that each step is defined and computes the stated quantities, and no step uses a square root or a comparison other than the positivity checks.
The tests check Claim 2 against Gaussian elimination in Fraction arithmetic, Claim 1 with exact autocovariances of four AR models (the recursion returns the true , , and a PACF that is 0 after lag ), Claim 3 through on random data, and the worked example in exact arithmetic.
Cited, not proved here. For a causal AR() process with IID noise of finite variance, , in probability, and for , (Brockwell and Davis 1991, Sections 8.2 and 8.10). The simulations on the page measure the finite-sample behaviour.
Complexity
L2 takes multiplications, which is . The recursion L3 to L8 takes about multiplications. So the total is , since . Solving the system by Gaussian elimination instead would cost , and by Cholesky . For long series and large , the autocovariances can be computed by the fast Fourier transform in . The code keeps a centred copy of the data, extra space, and for the coefficients.
Properties
-
Asymptotically efficient for AR models (cited). For a causal AR() process with IID noise of finite variance, and in probability (Brockwell and Davis 1991, Section 8.10). This is the same limit as for Gaussian maximum likelihood and conditional least squares. For AR(2) with , the limit gives and . A simulation (seed 32, 1000 series of ) gave , and (measured).
-
Bias in small samples (measured). AR(1) with mean estimated, Gaussian noise, 2000 series per row, seed 31. YW is the Yule-Walker estimate and LS the conditional least squares estimate; "limit sd" is .
mean YW mean LS sd YW sd LS limit sd 0.5 50 0.4406 0.4501 0.1279 0.1303 0.1225 0.5 200 0.4855 0.4879 0.0599 0.0602 0.0612 0.9 50 0.7932 0.8157 0.0925 0.0937 0.0616 0.9 200 0.8759 0.8805 0.0351 0.0348 0.0308 0.99 50 0.8553 0.8873 0.0793 0.0837 0.0199 0.99 200 0.9573 0.9656 0.0229 0.0231 0.0100 Both estimates are biased toward 0, and Yule-Walker more so, because the divisor shrinks by the factor . Near the unit root the bias is several standard deviations and the limit standard deviation is far too small. The Whittle likelihood page has a table that also compares the exact maximum likelihood estimate.
-
Always causal (proved). The fitted model has all roots of outside the unit circle. The Burg method also gives a causal fit, but conditional least squares can give a noncausal one.
-
Not efficient for MA or ARMA models. Moment equations for MA parameters are nonlinear and inefficient; see the moving-average model page, where the moment estimator of an MA(1) at has 3.6 times the variance of maximum likelihood.
-
Order recursive. One run to order gives the fits of all orders and their error variances , which is what order selection by the PACF or the Akaike information criterion needs.
Variants and improvements
- Burg's method. Estimates each from forward and backward prediction errors of the data, not from . It has less bias for short series and peaked spectra, and is still causal. See the Burg method.
- Tapered Yule-Walker. Multiply the data by a taper before computing . This reduces the bias from the edges.
- Least squares (covariance method). Regress on for . This uses no divisor- shrinkage and has less bias, but the system is not Toeplitz and the fit may be noncausal.
- Exact maximum likelihood. For Gaussian data, maximize the exact likelihood, computed by the innovations algorithm or by the closed form of the AR density, starting from the Yule-Walker fit.
- Multivariate. For a vector autoregression the same equations hold with matrix autocovariances, and Whittle's multivariate recursion solves them.
When to use it
Use it as a fast and safe first fit of an AR model: as the start of a maximum likelihood search, for order selection with the sample PACF, for AR spectral estimation, or inside other methods that need a causal fit. For final estimates on short series, or when a root may be near the unit circle, prefer the exact maximum likelihood, least squares or Burg estimates. For data with an MA part, use the innovations algorithm or the Whittle likelihood instead.
Pitfalls
- The divisor . Using with the divisor can make indefinite. Then can become negative, can exceed 1, and the fit can be noncausal. The stationary process page gives a five-point example with a negative determinant.
- A trend or a unit root. The equations assume stationarity. On a trending or integrated series, estimates nothing useful and is strongly biased. Difference the series first, as in the ARIMA model.
- Forgetting the mean. The sample mean must be subtracted. If the mean is known to be 0, skip L1; if it is not, subtracting it costs a little bias in small samples.
- Sign conventions. Signal processing writes the prediction error filter as , so , and the reflection coefficients have the opposite sign to .
- Reading the PACF bounds too strictly. The bounds hold at each lag for a true AR() process. Over 20 lags, one value outside them is expected by chance.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yule-walker-equations/. The authors are listed in prov/Y7J377.jsonl.
"""Yule-Walker estimation of an AR(p) model.
The sample autocovariances use the divisor n. The Toeplitz system Gamma_p phi = gamma_p is
solved by the Durbin-Levinson recursion in O(p^2) operations. The code uses only +, -, * and /,
so it runs unchanged on fractions.Fraction inputs and then gives the exact solution.
"""
from __future__ import annotations
from typing import Sequence
def sample_autocovariance(x: Sequence, max_lag: int, demean: bool = True) -> list:
"""Return gamma_hat(0..max_lag) with the divisor n (not n - h)."""
n = len(x)
if n == 0:
raise ValueError("empty series")
if not 0 <= max_lag < n:
raise ValueError("need 0 <= max_lag < n")
m = sum(x) / n if demean else 0 # @line L1
d = [xi - m for xi in x]
gamma = []
for h in range(max_lag + 1): # @line L2
gamma.append(sum(d[t + h] * d[t] for t in range(n - h)) / n)
return gamma
def levinson_durbin(gamma: Sequence, p: int) -> tuple[list, object, list]:
"""Solve Gamma_p phi = gamma_p by the Durbin-Levinson recursion.
Returns (phi[1..p] as a list of length p, the innovation variance v_p, the partial
autocorrelations phi_11, ..., phi_pp). Raises ValueError if some v_k is not positive,
which happens only when the Toeplitz matrix is singular or not positive definite.
"""
if p < 0 or len(gamma) < p + 1:
raise ValueError("need gamma(0..p)")
v = gamma[0] # @line L3
if not v > 0:
raise ValueError("gamma(0) must be positive")
phi: list = []
pacf: list = []
for k in range(1, p + 1): # @line L4
a = (gamma[k] - sum(phi[j - 1] * gamma[k - j] for j in range(1, k))) / v # @line L5
new = [phi[j - 1] - a * phi[k - j - 1] for j in range(1, k)] # @line L6
new.append(a) # @line L7
phi = new
pacf.append(a)
v = v * (1 - a * a) # @line L8
if not v > 0:
raise ValueError("the autocovariance matrix is not positive definite")
return phi, v, pacf # @line L9
def yule_walker(x: Sequence, p: int, demean: bool = True) -> tuple[list, object]:
"""Yule-Walker estimates (phi_hat[1..p], sigma2_hat) of an AR(p) model."""
gamma = sample_autocovariance(x, p, demean)
phi, v, _ = levinson_durbin(gamma, p)
return phi, v
def sample_pacf(x: Sequence, max_lag: int, demean: bool = True) -> list:
"""Sample partial autocorrelations phi_hat_11, ..., phi_hat_hh from the same recursion."""
gamma = sample_autocovariance(x, max_lag, demean)
return levinson_durbin(gamma, max_lag)[2]
test_yule_walker_equations.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yule-walker-equations/. The authors are listed in prov/Y7J377.jsonl.
import math
import random
from fractions import Fraction
import pytest
from yule_walker_equations import levinson_durbin, sample_autocovariance, sample_pacf, yule_walker
def solve_fraction(a: list[list[Fraction]], b: list[Fraction]) -> list[Fraction]:
"""Gaussian elimination with exact rational arithmetic (the brute force)."""
n = len(b)
m = [row[:] + [b[i]] for i, row in enumerate(a)]
for c in range(n):
piv = next(r for r in range(c, n) if m[r][c] != 0)
m[c], m[piv] = m[piv], m[c]
for r in range(n):
if r != c and m[r][c] != 0:
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return [m[i][n] / m[i][i] for i in range(n)]
def ar_autocovariance_exact(phi: list[Fraction], sigma2: Fraction, max_lag: int) -> list[Fraction]:
"""gamma(0..max_lag) of a causal AR(p): solve the first p + 1 Yule-Walker equations
in gamma(0..p) by elimination, then extend with the AR recursion."""
p = len(phi)
a = [[Fraction(0)] * (p + 1) for _ in range(p + 1)]
b = [Fraction(0)] * (p + 1)
for k in range(p + 1): # gamma(k) - sum_j phi_j gamma(|k - j|) = sigma2 [k == 0]
a[k][k] += 1
for j in range(1, p + 1):
a[k][abs(k - j)] -= phi[j - 1]
b[k] = sigma2 if k == 0 else Fraction(0)
g = solve_fraction(a, b)
while len(g) <= max_lag:
h = len(g)
g.append(sum(phi[j - 1] * g[h - j] for j in range(1, p + 1)))
return g[:max_lag + 1]
def simulate_ar(phi: list[float], n: int, rng: random.Random, burn: int = 300) -> list[float]:
x = [0.0] * (n + burn)
for t in range(n + burn):
x[t] = rng.gauss(0.0, 1.0) + sum(phi[j] * x[t - 1 - j] for j in range(len(phi)) if t - 1 - j >= 0)
return x[burn:]
def test_ar1_estimate_is_r1_over_r0_exactly():
rng = random.Random(1)
for _ in range(50):
n = rng.randint(3, 15)
x = [Fraction(rng.randint(-9, 9)) for _ in range(n)]
if len(set(x)) == 1:
continue
g = sample_autocovariance(x, 1)
phi, s2 = yule_walker(x, 1)
assert phi == [g[1] / g[0]]
assert s2 == g[0] - g[1] ** 2 / g[0]
def test_levinson_matches_gaussian_elimination_in_fractions():
rng = random.Random(2)
for _ in range(40):
n = rng.randint(8, 20)
p = rng.randint(1, 5)
x = [Fraction(rng.randint(-20, 20), rng.randint(1, 4)) for _ in range(n)]
g = sample_autocovariance(x, p)
mat = [[g[abs(i - j)] for j in range(p)] for i in range(p)]
ref = solve_fraction(mat, g[1:p + 1])
phi, v, _ = levinson_durbin(g, p)
assert phi == ref
assert v == g[0] - sum(a * b for a, b in zip(ref, g[1:p + 1]))
def test_exact_autocovariances_give_the_true_model_and_a_pacf_cut_off():
cases = [
[Fraction(1, 2), Fraction(3, 10)],
[Fraction(1), Fraction(-1, 2)],
[Fraction(-3, 5)],
[Fraction(2, 5), Fraction(-1, 5), Fraction(1, 10)],
]
for phi in cases:
p = len(phi)
g = ar_autocovariance_exact(phi, Fraction(2), p + 4)
est, v, pacf = levinson_durbin(g, p + 4)
assert est[:p] == phi and all(a == 0 for a in est[p:])
assert v == 2
assert all(a == 0 for a in pacf[p:])
assert pacf[p - 1] == phi[-1]
def test_sample_autocovariance_by_hand():
x = [Fraction(v) for v in (2, 4, 6, 5, 3)]
assert sample_autocovariance(x, 2) == [Fraction(2), Fraction(1, 5), Fraction(-6, 5)]
def test_worked_example_numbers():
x = [Fraction(v) for v in (3, 5, 6, 4, 2, 1, 3, 6, 7, 5)]
g = sample_autocovariance(x, 2)
assert g == [Fraction(84, 25), Fraction(207, 125), Fraction(-267, 250)]
phi, v, pacf = levinson_durbin(g, 2)
assert pacf[0] == Fraction(69, 140)
assert phi == [Fraction(25461, 29678), Fraction(-10991, 14839)]
assert v == Fraction(2129868, 1854875)
def test_fitted_model_is_causal():
rng = random.Random(3)
for _ in range(100):
n = rng.randint(5, 40)
p = rng.randint(1, min(6, n - 1))
x = [rng.gauss(0, 1) + 3 * math.sin(t) for t in range(n)]
pacf = sample_pacf(x, p)
assert all(abs(a) < 1 for a in pacf)
if p == 2: # the stationarity triangle
phi, _ = yule_walker(x, 2)
assert phi[0] + phi[1] < 1 and phi[1] - phi[0] < 1 and abs(phi[1]) < 1
def test_monte_carlo_ar2_estimates_near_truth():
# Measured, not proved: mean over r = 100 series of n = 400, seed 4.
rng = random.Random(4)
r, n = 100, 400
s1 = s2 = 0.0
for _ in range(r):
phi, _ = yule_walker(simulate_ar([0.5, 0.3], n, rng), 2)
s1 += phi[0]
s2 += phi[1]
# The asymptotic standard deviation of each estimate is sqrt((1 - 0.09) / 400) = 0.048,
# so the standard error of the mean is 0.0048; allow 4 of them plus an O(1/n) bias of 0.02.
assert abs(s1 / r - 0.5) < 0.04
assert abs(s2 / r - 0.3) < 0.04
def test_errors():
with pytest.raises(ValueError):
yule_walker([1.0, 1.0, 1.0], 1)
with pytest.raises(ValueError):
sample_autocovariance([1.0, 2.0], 2)
with pytest.raises(ValueError):
levinson_durbin([Fraction(1), Fraction(1)], 1)
History
George Udny Yule (1927) fitted an AR(2) model to Wolfer's sunspot numbers to show that a disturbed oscillation, not a hidden periodicity, explains them. Gilbert Walker (1931) wrote the general equations between the coefficients and the autocorrelations and used them for air pressure at Darwin, a study connected with his work on the Southern Oscillation. Norman Levinson (1947) gave a recursion for Toeplitz systems in Wiener's filtering problem, and James Durbin (1960) gave the version for AR fitting that also returns the partial autocorrelations. John Parker Burg (1967) replaced the autocovariance estimate by a direct estimate of the reflection coefficients.
References
- G. Udny Yule, On a method of investigating periodicities in disturbed series, with special reference to Wolfer's sunspot numbers, Philosophical Transactions of the Royal Society A 226, 1927, pp. 267 to 298 (the AR(2) fit to the sunspot numbers)
- Gilbert Walker, On periodicity in series of related terms, Proceedings of the Royal Society A 131, 1931, pp. 518 to 532 (the equations of general order)
- Peter J. Brockwell and Richard A. Davis, Time Series: Theory and Methods, second edition, Springer, 1991, Section 5.2 (the Durbin-Levinson algorithm, pp. 169 to 174), Section 8.1 (the Yule-Walker equations, p. 239), Section 8.2 (preliminary AR estimation by the Durbin-Levinson algorithm, p. 241) and Section 8.10 (asymptotic behaviour of the Yule-Walker estimates, p. 262)
- Peter J. Brockwell and Richard A. Davis, Introduction to Time Series and Forecasting, third edition, Springer, 2016, Section 2.5.3 (the Durbin-Levinson algorithm, p. 60) and Section 5.1.1 (Yule-Walker estimation, p. 123)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Y7J377 Edit this page History Report an error Markdown