Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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: Γpϕ=γp\Gamma_p \phi = \gamma_p, where Γp\Gamma_p is the p×pp \times p Toeplitz matrix of autocovariances γ(i−j)\gamma(i - j) and γp=(γ(1),…,γ(p))\gamma_p = (\gamma(1), \ldots, \gamma(p)). The Yule-Walker estimator replaces the autocovariances by their sample values, with the divisor nn, and solves the system. It is a method-of-moments estimator. The Levinson-Durbin recursion solves the system for all orders 1,…,p1, \ldots, p in O(p2)O(p^2) 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. X1,…,XnX_1, \ldots, X_n come from a causal AR(pp) process ϕ(B)(Xt−μ)=εt\phi(B)(X_t - \mu) = \varepsilon_t with ϕ(z)=1−ϕ1z−⋯−ϕpzp\phi(z) = 1 - \phi_1 z - \cdots - \phi_p z^p and {εt}∼WN(0,σ2)\{\varepsilon_t\} \sim \mathrm{WN}(0, \sigma^2). The order pp is given.

Population equations. Multiply Xt−μ=∑iϕi(Xt−i−μ)+εtX_t - \mu = \sum_i \phi_i (X_{t-i} - \mu) + \varepsilon_t by Xt−k−μX_{t-k} - \mu and take expectations. Causality makes εt\varepsilon_t uncorrelated with the past, so

γ(k)=∑i=1pϕiγ(k−i)(k=1,…,p),σ2=γ(0)−∑i=1pϕiγ(i).\gamma(k) = \sum_{i=1}^{p} \phi_i \gamma(k - i) \quad (k = 1, \ldots, p), \qquad \sigma^2 = \gamma(0) - \sum_{i=1}^{p} \phi_i \gamma(i).

In matrix form Γpϕ=γp\Gamma_p \phi = \gamma_p and σ2=γ(0)−ϕ⊤γp\sigma^2 = \gamma(0) - \phi^\top \gamma_p.

Estimator. With xˉ\bar x the sample mean and γ^(h)=1n∑t=1n−h(xt+h−xˉ)(xt−xˉ)\hat\gamma(h) = \frac1n \sum_{t=1}^{n-h} (x_{t+h} - \bar x)(x_t - \bar x),

ϕ^=Γ^p−1γ^p,σ^2=γ^(0)−ϕ^⊤γ^p.\hat\phi = \hat\Gamma_p^{-1} \hat\gamma_p, \qquad \hat\sigma^2 = \hat\gamma(0) - \hat\phi^\top \hat\gamma_p.

Output. ϕ^1,…,ϕ^p\hat\phi_1, \ldots, \hat\phi_p, σ^2\hat\sigma^2, and the sample partial autocorrelations ϕ^11,…,ϕ^pp\hat\phi_{11}, \ldots, \hat\phi_{pp}.

Requirements. The data are not all equal. Then Γ^p\hat\Gamma_p is positive definite and the solution exists and is unique.

The algorithm

  1. YULE-WALKER(x[1..n], p)
  2. 1m ← (x[1] + ... + x[n]) / n
  3. 2for h ← 0 to p do γ[h] ← (1/n) Σ_{t=1}^{n-h} (x[t+h] - m)(x[t] - m)
  4. 3v ← γ[0]
  5. 4for k ← 1 to p do
  6. 5a ← (γ[k] - Σ_{j=1}^{k-1} φ[j] γ[k-j]) / v
  7. 6for j ← 1 to k-1 do φ'[j] ← φ[j] - a · φ[k-j]
  8. 7φ'[k] ← a; φ ← φ'; pacf[k] ← a
  9. 8v ← v · (1 - a²)
  10. 9return (φ[1..p], v, pacf[1..k])

Lines L1 and L2 compute the sample autocovariances with the divisor nn. Lines L3 to L8 are the Durbin-Levinson recursion: after step kk, ϕ[1..k]\phi[1..k] solves the order-kk system Γ^kϕ=γ^k\hat\Gamma_k \phi = \hat\gamma_k and vv is the order-kk 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 m=μm = \mu.

Example

Take x=(3,5,6,4,2,1,3,6,7,5)x = (3, 5, 6, 4, 2, 1, 3, 6, 7, 5), n=10n = 10, xˉ=4.2\bar x = 4.2. The deviations are −1.2,0.8,1.8,−0.2,−2.2,−3.2,−1.2,1.8,2.8,0.8-1.2, 0.8, 1.8, -0.2, -2.2, -3.2, -1.2, 1.8, 2.8, 0.8, and

γ^(0)=3.36=8425,γ^(1)=1.656=207125,γ^(2)=−1.068=−267250,γ^(3)=−2.092.\hat\gamma(0) = 3.36 = \tfrac{84}{25}, \quad \hat\gamma(1) = 1.656 = \tfrac{207}{125}, \quad \hat\gamma(2) = -1.068 = -\tfrac{267}{250}, \quad \hat\gamma(3) = -2.092.
step kk a=ϕ^kka = \hat\phi_{kk} ϕ^\hat\phi after the step vv
0 3.36
1 1.656/3.36=0.4928571.656/3.36 = 0.492857 (0.492857)(0.492857) 3.36(1−0.4928572)=2.5438293.36(1 - 0.492857^2) = 2.543829
2 (−1.068−0.492857×1.656)/2.543829=−0.740683(-1.068 - 0.492857 \times 1.656)/2.543829 = -0.740683 (0.857908,−0.740683)(0.857908, -0.740683) 1.148254
3 0.050817/1.148254=0.0442560.050817/1.148254 = 0.044256 (0.890688,−0.778651,0.044256)(0.890688, -0.778651, 0.044256) 1.146005

In exact arithmetic ϕ^11=69/140\hat\phi_{11} = 69/140, the AR(2) fit is (25461/29678,−10991/14839)(25461/29678, -10991/14839) and σ^2=2129868/1854875\hat\sigma^2 = 2129868/1854875. The AR(2) polynomial 1−0.8579z+0.7407z21 - 0.8579z + 0.7407z^2 has complex roots 0.579±1.007i0.579 \pm 1.007i of modulus 1.162>11.162 > 1, so the fitted model is causal, as the theory promises. The third partial autocorrelation, 0.0440.044, reduces vv by only 0.2%, which points to p=2p = 2. 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-kk system is persymmetric, so the order-(k−1)(k-1) solution read backwards solves the reversed system, and a single scalar aa fixes the last equation; the prediction error then falls by the factor 1−a21 - a^2. Claim 3 shows that the divisor-nn matrix Γ^p\hat\Gamma_p is positive definite when the data are not constant, so every v>0v > 0 and every ∣a∣<1|a| < 1. Claim 4 proves that the fitted polynomial ϕ^(z)\hat\phi(z) 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. γ\gamma is an even function on the integers, Γk=[γ(i−j)]i,j=1k\Gamma_k = [\gamma(i - j)]_{i,j=1}^{k}, γk=(γ(1),…,γ(k))⊤\gamma_k = (\gamma(1), \ldots, \gamma(k))^\top and EkE_k is the k×kk \times k exchange matrix, which reverses the order of a vector. For the estimator, γ=γ^\gamma = \hat\gamma is the sample autocovariance with the divisor nn, computed by lines L1 and L2. For k≥1k \ge 1 let ϕk=(ϕk1,…,ϕkk)⊤\phi_k = (\phi_{k1}, \ldots, \phi_{kk})^\top solve Γkϕk=γk\Gamma_k \phi_k = \gamma_k, and let vk=γ(0)−ϕk⊤γkv_k = \gamma(0) - \phi_k^\top \gamma_k, with v0=γ(0)v_0 = \gamma(0).

Claim 1 (the population equations). If {Xt}\{X_t\} is a causal AR(pp) process Xt−μ=∑i=1pϕi(Xt−i−μ)+εtX_t - \mu = \sum_{i=1}^p \phi_i (X_{t-i} - \mu) + \varepsilon_t with {εt}∼WN(0,σ2)\{\varepsilon_t\} \sim \mathrm{WN}(0, \sigma^2), then Γpϕ=γp\Gamma_p \phi = \gamma_p and σ2=γ(0)−ϕ⊤γp\sigma^2 = \gamma(0) - \phi^\top \gamma_p. If Γp\Gamma_p is nonsingular, these equations determine ϕ\phi and σ2\sigma^2 from γ(0),…,γ(p)\gamma(0), \ldots, \gamma(p).

Proof. Put μ=0\mu = 0. Causality gives Xt−k=∑j≥0ψjεt−k−jX_{t-k} = \sum_{j \ge 0} \psi_j \varepsilon_{t-k-j}, so E[εtXt−k]=0\mathbb{E}[\varepsilon_t X_{t-k}] = 0 for k≥1k \ge 1, and E[εtXt]=E[εt(∑iϕiXt−i+εt)]=σ2\mathbb{E}[\varepsilon_t X_t] = \mathbb{E}[\varepsilon_t (\sum_i \phi_i X_{t-i} + \varepsilon_t)] = \sigma^2. Multiply the model equation by Xt−kX_{t-k} and take expectations: γ(k)=∑iϕiγ(k−i)\gamma(k) = \sum_i \phi_i \gamma(k - i) for k=1,…,pk = 1, \ldots, p, which is Γpϕ=γp\Gamma_p \phi = \gamma_p. With k=0k = 0: γ(0)=∑iϕiγ(i)+σ2\gamma(0) = \sum_i \phi_i \gamma(i) + \sigma^2. □\square

Claim 2 (the recursion). Suppose Γk\Gamma_k is nonsingular for k=1,…,pk = 1, \ldots, p and vk−1≠0v_{k-1} \ne 0. Then for each kk, with

ak=γ(k)−∑j=1k−1ϕk−1,j γ(k−j)vk−1,a_k = \frac{\gamma(k) - \sum_{j=1}^{k-1} \phi_{k-1,j}\, \gamma(k - j)}{v_{k-1}},

the solution of order kk is ϕkj=ϕk−1,j−akϕk−1,k−j\phi_{kj} = \phi_{k-1,j} - a_k \phi_{k-1,k-j} for j<kj < k and ϕkk=ak\phi_{kk} = a_k, and vk=vk−1(1−ak2)v_k = v_{k-1}(1 - a_k^2). These are lines L5 to L8, so after step kk the variables hold ϕk\phi_k and vkv_k, and the value appended to the PACF list is ϕkk\phi_{kk}.

Proof. Because Γk−1\Gamma_{k-1} is a symmetric Toeplitz matrix, EΓk−1E=Γk−1E \Gamma_{k-1} E = \Gamma_{k-1} (persymmetry), with E=Ek−1E = E_{k-1}. Partition

Γk=(Γk−1Eγk−1γk−1⊤Eγ(0)),γk=(γk−1γ(k)),\Gamma_k = \begin{pmatrix} \Gamma_{k-1} & E\gamma_{k-1} \\ \gamma_{k-1}^\top E & \gamma(0) \end{pmatrix}, \qquad \gamma_k = \begin{pmatrix} \gamma_{k-1} \\ \gamma(k) \end{pmatrix},

and try ϕk=(ϕk−1−aEϕk−1, a)\phi_k = (\phi_{k-1} - a E\phi_{k-1},\ a) for a scalar aa. The first block row gives Γk−1ϕk−1−aΓk−1Eϕk−1+aEγk−1=γk−1−aEΓk−1ϕk−1+aEγk−1=γk−1\Gamma_{k-1}\phi_{k-1} - a \Gamma_{k-1} E \phi_{k-1} + a E\gamma_{k-1} = \gamma_{k-1} - a E \Gamma_{k-1}\phi_{k-1} + a E\gamma_{k-1} = \gamma_{k-1}, for every aa. The last row gives

γk−1⊤Eϕk−1−a γk−1⊤ϕk−1+aγ(0)=∑j=1k−1ϕk−1,jγ(k−j)+avk−1,\gamma_{k-1}^\top E \phi_{k-1} - a\, \gamma_{k-1}^\top \phi_{k-1} + a\gamma(0) = \sum_{j=1}^{k-1} \phi_{k-1,j}\gamma(k - j) + a v_{k-1},

which equals γ(k)\gamma(k) exactly when a=aka = a_k. Since Γk\Gamma_k is nonsingular, this is the unique solution. For the error,

vk=γ(0)−(ϕk−1−akEϕk−1)⊤γk−1−akγ(k)=vk−1+ak(∑jϕk−1,jγ(k−j)−γ(k))=vk−1−ak2vk−1.□v_k = \gamma(0) - (\phi_{k-1} - a_k E\phi_{k-1})^\top \gamma_{k-1} - a_k\gamma(k) = v_{k-1} + a_k\Big(\sum_{j} \phi_{k-1,j}\gamma(k - j) - \gamma(k)\Big) = v_{k-1} - a_k^2 v_{k-1}. \quad \square

Claim 3 (positive definiteness). If the data x1,…,xnx_1, \ldots, x_n are not all equal, then Γ^k\hat\Gamma_k is positive definite for every k≥1k \ge 1. Hence every vk>0v_k > 0 and every ∣ak∣<1|a_k| < 1, so lines L5 and L8 never divide by 0 and the code never raises its error on such data.

Proof. Let dt=xt−xˉd_t = x_t - \bar x for 1≤t≤n1 \le t \le n and dt=0d_t = 0 otherwise. Not all dtd_t are 0. Then γ^(h)=1n∑tdt+hdt\hat\gamma(h) = \frac1n \sum_t d_{t+h} d_t over all integers tt, and for c∈Rkc \in \mathbb{R}^k,

c⊤Γ^kc=1n∑i,jcicj∑tdt+i−jdt=1n∑s(∑i=1kcids−i)2≥0.c^\top \hat\Gamma_k c = \frac1n \sum_{i,j} c_i c_j \sum_t d_{t+i-j} d_t = \frac1n \sum_s \Big(\sum_{i=1}^{k} c_i d_{s-i}\Big)^2 \ge 0.

If this is 0, then the convolution of (dt)(d_t) with (ci)(c_i) is 0, so the polynomial product (∑tdtzt)(∑icizi)(\sum_t d_t z^t)(\sum_i c_i z^i) is 0. The first factor is not the zero polynomial, so c=0c = 0. Thus Γ^k\hat\Gamma_k is positive definite. Next, Γk+1\Gamma_{k+1} can be written with γ(0)\gamma(0) in the top left corner and Γk\Gamma_k in the bottom right, because it is persymmetric. Its Schur complement is γ(0)−γk⊤Γk−1γk=vk\gamma(0) - \gamma_k^\top \Gamma_k^{-1}\gamma_k = v_k, so vk=det⁡Γk+1/det⁡Γk>0v_k = \det\Gamma_{k+1}/\det\Gamma_k > 0. By Claim 2, 1−ak2=vk/vk−1∈(0,1]1 - a_k^2 = v_k/v_{k-1} \in (0, 1], so ∣ak∣<1|a_k| < 1. □\square

Claim 4 (the fitted model is causal). If the data are not all equal, then every root ζ\zeta of ϕ^(z)=1−ϕ^p1z−⋯−ϕ^ppzp\hat\phi(z) = 1 - \hat\phi_{p1} z - \cdots - \hat\phi_{pp} z^p satisfies ∣ζ∣>1|\zeta| > 1.

Proof. The function γ^\hat\gamma (0 for ∣h∣≥n|h| \ge n) is even and nonnegative definite, by the computation in Claim 3 for every kk. So it is the autocovariance of a stationary Gaussian process {Yt}\{Y_t\} with mean 0 (Brockwell and Davis 1991, Section 1.5). Work in the complex space L2L^2 with ∥W∥2=E∣W∣2\lVert W \rVert^2 = \mathbb{E}|W|^2. Because Γ^p\hat\Gamma_p is real, symmetric and positive definite, the vector ϕ^p\hat\phi_p is the unique minimizer over b∈Cpb \in \mathbb{C}^p of ∥Yt−∑j=1pbjYt−j∥2\lVert Y_t - \sum_{j=1}^p b_j Y_{t-j} \rVert^2, and the minimum is vpv_p.

Let ζ\zeta be a root, and write ϕ^(z)=(1−z/ζ) c(z)\hat\phi(z) = (1 - z/\zeta)\, c(z) with c(z)=1+c1z+⋯+cp−1zp−1c(z) = 1 + c_1 z + \cdots + c_{p-1} z^{p-1}. Put Ut=c(B)YtU_t = c(B) Y_t. Its variance s=∥Ut∥2s = \lVert U_t \rVert^2 does not depend on tt and is positive, because c≠0c \ne 0 and Γ^p\hat\Gamma_p is positive definite. For any λ∈C\lambda \in \mathbb{C}, Ut−λUt−1=c(B)(1−λB)YtU_t - \lambda U_{t-1} = c(B)(1 - \lambda B) Y_t is of the form Yt−∑j=1pbjYt−jY_t - \sum_{j=1}^{p} b_j Y_{t-j}, so

g(λ)=∥Ut−λUt−1∥2≥vp,with equality at λ=1/ζ.g(\lambda) = \lVert U_t - \lambda U_{t-1} \rVert^2 \ge v_p, \quad \text{with equality at } \lambda = 1/\zeta.

The function gg is a strictly convex quadratic in λ\lambda, with the unique minimizer λ∗=E[UtUt−1‾]/s\lambda^* = \mathbb{E}[U_t \overline{U_{t-1}}]/s and minimum g(λ∗)=s(1−∣λ∗∣2)g(\lambda^*) = s(1 - |\lambda^*|^2). Since 1/ζ1/\zeta attains the smallest possible value vpv_p, it is the minimizer: 1/ζ=λ∗1/\zeta = \lambda^*. By the Cauchy-Schwarz inequality, ∣λ∗∣≤1|\lambda^*| \le 1. If ∣λ∗∣=1|\lambda^*| = 1, then vp=g(λ∗)=0v_p = g(\lambda^*) = 0, which contradicts Claim 3. So ∣1/ζ∣<1|1/\zeta| < 1, that is ∣ζ∣>1|\zeta| > 1. □\square

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 Γ^p−1γ^p\hat\Gamma_p^{-1}\hat\gamma_p and the exact σ^2=vp\hat\sigma^2 = v_p.

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. □\square

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 ϕ\phi, vp=σ2v_p = \sigma^2, and a PACF that is 0 after lag pp), Claim 3 through ∣ϕ^kk∣<1|\hat\phi_{kk}| < 1 on random data, and the worked example in exact arithmetic.

Cited, not proved here. For a causal AR(pp) process with IID noise of finite variance, n(ϕ^p−ϕ)→N(0,σ2Γp−1)\sqrt{n}(\hat\phi_p - \phi) \to N(0, \sigma^2\Gamma_p^{-1}), σ^2→σ2\hat\sigma^2 \to \sigma^2 in probability, and for h>ph > p, n ϕ^hh→N(0,1)\sqrt{n}\,\hat\phi_{hh} \to N(0, 1) (Brockwell and Davis 1991, Sections 8.2 and 8.10). The simulations on the page measure the finite-sample behaviour.

Complexity

L2 takes (p+1)(n−p/2)(p + 1)(n - p/2) multiplications, which is Θ(np)\Theta(np). The recursion L3 to L8 takes about p2p^2 multiplications. So the total is Θ(np+p2)=Θ(np)\Theta(np + p^2) = \Theta(np), since p<np < n. Solving the system by Gaussian elimination instead would cost Θ(p3)\Theta(p^3), and by Cholesky p3/3p^3/3. For long series and large pp, the autocovariances can be computed by the fast Fourier transform in O(nlog⁡n)O(n \log n). The code keeps a centred copy of the data, Θ(n)\Theta(n) extra space, and O(p)O(p) for the coefficients.

Properties

  • Asymptotically efficient for AR models (cited). For a causal AR(pp) process with IID noise of finite variance, n(ϕ^−ϕ)→N(0,σ2Γp−1)\sqrt{n}(\hat\phi - \phi) \to N(0, \sigma^2 \Gamma_p^{-1}) and σ^2→σ2\hat\sigma^2 \to \sigma^2 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 ϕ=(0.5,0.3)\phi = (0.5, 0.3), the limit gives nVar⁡(ϕ^i)=1−ϕ22=0.91n\operatorname{Var}(\hat\phi_i) = 1 - \phi_2^2 = 0.91 and nCov⁡(ϕ^1,ϕ^2)=−ϕ1(1+ϕ2)=−0.65n\operatorname{Cov}(\hat\phi_1, \hat\phi_2) = -\phi_1(1 + \phi_2) = -0.65. A simulation (seed 32, 1000 series of n=400n = 400) gave 0.9060.906, 0.9700.970 and −0.656-0.656 (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 (1−ϕ2)/n\sqrt{(1 - \phi^2)/n}.

    ϕ\phi nn 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 nn shrinks γ^(h)\hat\gamma(h) by the factor (n−h)/n(n - h)/n. 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 ϕ^(z)\hat\phi(z) 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 θ=0.5\theta = 0.5 has 3.6 times the variance of maximum likelihood.

  • Order recursive. One run to order pp gives the fits of all orders 1,…,p1, \ldots, p and their error variances vkv_k, which is what order selection by the PACF or the Akaike information criterion needs.

Variants and improvements

  • Burg's method. Estimates each ϕ^kk\hat\phi_{kk} from forward and backward prediction errors of the data, not from γ^\hat\gamma. 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 γ^\hat\gamma. This reduces the bias from the edges.
  • Least squares (covariance method). Regress xtx_t on xt−1,…,xt−px_{t-1}, \ldots, x_{t-p} for t=p+1,…,nt = p + 1, \ldots, n. This uses no divisor-nn 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 n−hn - h. Using γ^(h)\hat\gamma(h) with the divisor n−hn - h can make Γ^p\hat\Gamma_p indefinite. Then vv can become negative, ∣ϕ^kk∣|\hat\phi_{kk}| 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, ϕ^\hat\phi 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 1+a1z−1+⋯1 + a_1 z^{-1} + \cdots, so aj=−ϕja_j = -\phi_j, and the reflection coefficients have the opposite sign to ϕ^kk\hat\phi_{kk}.
  • Reading the PACF bounds too strictly. The bounds ±1.96/n\pm 1.96/\sqrt{n} hold at each lag for a true AR(pp) 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.

yule_walker_equations.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example