Algorithm Search⌘K

Algorithmadvanced

Innovations algorithm

Also called Brockwell-Davis innovations algorithm.

Computes one-step predictors and their error variances from a covariance function by orthogonalizing the observations. It gives the exact Gaussian likelihood.

Time
Θ(n^3) worstΘ(n q^2) banded
Space
Θ(n^2) extra
Where
n = the number of observations; q = the band width of the covariance (the MA order)
Properties
deterministicexactonlineiterative
Origin
Peter J. Brockwell, Richard A. Davis, Craig F. Ansley, 1987

The innovations algorithm turns a covariance function into one-step predictions. Given κ(i,j)=E[XiXj]\kappa(i, j) = \mathbb{E}[X_i X_j] for a series X1,X2,…X_1, X_2, \ldots with mean 0, it computes the best linear predictor X^m+1\hat X_{m+1} of each value from the ones before it, and the mean squared error vmv_m of that prediction. The predictors are written in terms of the past prediction errors Xj−X^jX_j - \hat X_j, called innovations, which are uncorrelated. This makes the recursion a Gram-Schmidt orthogonalization of the observations, or equally an LDL⊤LDL^\top Cholesky factorization of their covariance matrix. Unlike the Levinson-Durbin recursion, it does not need stationarity. For a moving-average process of order qq the covariance is banded and the work falls from Θ(n3)\Theta(n^3) to Θ(nq2)\Theta(n q^2). The errors and variances give the exact Gaussian likelihood, so the algorithm is the standard way to fit MA and ARMA models by maximum likelihood.

In plain words

Watch a series one value at a time and predict the next value from all you have seen. When the value arrives, the gap between it and your prediction is the new information it brings, the innovation. Innovations from different times are unrelated to each other, so you can build each new prediction as a weighted sum of the past innovations, with weights that the covariances tell you. The recursion finds these weights one time step at a time. It also tells you how large each prediction error should be, and that is all the likelihood of normal data needs. If values far apart in time are unrelated, most weights are zero and the work is small.

The problem

Model. X1,…,XnX_1, \ldots, X_n have mean 0 and known covariance κ(i,j)=E[XiXj]\kappa(i, j) = \mathbb{E}[X_i X_j]. The covariance matrix Kn=[κ(i,j)]i,j=1nK_n = [\kappa(i, j)]_{i,j=1}^n is positive definite. Stationarity is not needed. For a stationary series, κ(i,j)=γ(i−j)\kappa(i, j) = \gamma(i - j).

Output. For m=0,…,n−1m = 0, \ldots, n - 1, the coefficients θm1,…,θmm\theta_{m1}, \ldots, \theta_{mm} and the error variances vmv_m such that

X^1=0,X^m+1=∑j=1mθmj (Xm+1−j−X^m+1−j),vm=E[(Xm+1−X^m+1)2],\hat X_1 = 0, \qquad \hat X_{m+1} = \sum_{j=1}^{m} \theta_{mj}\,(X_{m+1-j} - \hat X_{m+1-j}), \qquad v_m = \mathbb{E}[(X_{m+1} - \hat X_{m+1})^2],

where X^m+1\hat X_{m+1} is the best linear predictor of Xm+1X_{m+1} from X1,…,XmX_1, \ldots, X_m.

Uses.

  • Prediction. The predictors follow from the data and the θmj\theta_{mj} in O(n2)O(n^2) more operations, or O(nq)O(nq) when the covariance has band width qq.
  • Likelihood. For Gaussian data,
−2log⁡L=nlog⁡(2π)+∑j=1nlog⁡vj−1+∑j=1n(Xj−X^j)2vj−1,-2\log L = n \log(2\pi) + \sum_{j=1}^{n} \log v_{j-1} + \sum_{j=1}^{n} \frac{(X_j - \hat X_j)^2}{v_{j-1}},

with no matrix inverse or determinant.

  • MA estimation. Run on the sample autocovariances, θ^m1,…,θ^mq\hat\theta_{m1}, \ldots, \hat\theta_{mq} estimate the MA(qq) coefficients when mm is large (Brockwell and Davis 1991, Section 8.3).

The algorithm

  1. INNOVATIONS(κ, n)
  2. 1v[0] ← κ(1, 1)
  3. 2for m ← 1 to n - 1 do
  4. 3for k ← 0 to m - 1 do
  5. 4s ← κ(m+1, k+1) - Σ_{j=0}^{k-1} θ[k][k-j] · θ[m][m-j] · v[j]
  6. 5θ[m][m-k] ← s / v[k]
  7. 6v[m] ← κ(m+1, m+1) - Σ_{j=0}^{m-1} θ[m][m-j]² · v[j]
  8. 7return (θ, v)

For a covariance with band width qq (κ(i,j)=0\kappa(i, j) = 0 when ∣i−j∣>q|i - j| > q), start the loops in L3, L4 and L6 at max⁡(0,m−q)\max(0, m - q) instead of 0; the skipped coefficients are 0. The code takes q as an optional argument for this. Line L5 divides by v[k]v[k], which is positive when KnK_n is positive definite. The code raises an error if some vm≤0v_m \le 0. It uses only the four field operations, so it runs exactly on Fraction values.

Example

Take the MA(1) process Xt=εt+12εt−1X_t = \varepsilon_t + \frac12 \varepsilon_{t-1} with σ2=1\sigma^2 = 1, so γ(0)=5/4\gamma(0) = 5/4, γ(1)=1/2\gamma(1) = 1/2 and γ(h)=0\gamma(h) = 0 for h≥2h \ge 2.

  • v0=5/4v_0 = 5/4.
  • m=1m = 1: θ11=γ(1)/v0=2/5\theta_{11} = \gamma(1)/v_0 = 2/5, and v1=5/4−(2/5)2⋅5/4=21/20v_1 = 5/4 - (2/5)^2 \cdot 5/4 = 21/20.
  • m=2m = 2: θ22=κ(3,1)/v0=0\theta_{22} = \kappa(3, 1)/v_0 = 0, then θ21=(1/2−θ11θ22v0)/v1=10/21\theta_{21} = (1/2 - \theta_{11}\theta_{22}v_0)/v_1 = 10/21, and v2=5/4−(10/21)2⋅21/20=85/84v_2 = 5/4 - (10/21)^2 \cdot 21/20 = 85/84.
  • m=3m = 3: θ31=42/85\theta_{31} = 42/85, θ32=θ33=0\theta_{32} = \theta_{33} = 0, v3=341/340v_3 = 341/340.

In general vm=Sm+1/Smv_m = S_{m+1}/S_m and θm1=θ/vm−1\theta_{m1} = \theta/v_{m-1} with Sm=1+θ2+⋯+θ2mS_m = 1 + \theta^2 + \cdots + \theta^{2m} and θ=1/2\theta = 1/2, so vm→1=σ2v_m \to 1 = \sigma^2 and θm1→1/2\theta_{m1} \to 1/2.

Now observe x=(1,−1,2)x = (1, -1, 2).

jj xjx_j x^j\hat x_j innovation xj−x^jx_j - \hat x_j vj−1v_{j-1}
1 1 0 1 5/4
2 -1 25⋅1=0.4\frac25 \cdot 1 = 0.4 −1.4-1.4 21/20
3 2 1021⋅(−1.4)=−23\frac{10}{21} \cdot (-1.4) = -\frac23 83\frac83 85/84
4 4285⋅83=11285=1.3176\frac{42}{85} \cdot \frac83 = \frac{112}{85} = 1.3176 341/340

The quadratic form is 1/(5/4)+1.96/(21/20)+(64/9)/(85/84)=824/85=9.69411/(5/4) + 1.96/(21/20) + (64/9)/(85/84) = 824/85 = 9.6941, and the product of the variances is 85/64=det⁡K385/64 = \det K_3. So −2log⁡L=3log⁡(2π)+log⁡(85/64)+9.6941=15.4915-2\log L = 3\log(2\pi) + \log(85/64) + 9.6941 = 15.4915. The tests check these values against the determinant and the inverse of K3K_3 in exact arithmetic.

Correctness

The full proof is in proofs/correctness.md. The innovations Uj=Xj−X^jU_j = X_j - \hat X_j are orthogonal and span the same space as X1,…,XjX_1, \ldots, X_j, so X^m+1\hat X_{m+1} is the sum of the projections of Xm+1X_{m+1} on each Uk+1U_{k+1}, with coefficient ⟨Xm+1,Uk+1⟩/vk\langle X_{m+1}, U_{k+1}\rangle / v_k. Expanding Uk+1U_{k+1} by its own predictor gives line L4, and Pythagoras gives line L6. In matrix form, X=CUX = C U with CC unit lower triangular, so Kn=CDC⊤K_n = C D C^\top with D=diag⁡(v0,…,vn−1)D = \operatorname{diag}(v_0, \ldots, v_{n-1}). This proves the likelihood formula. A banded covariance makes Xm+1X_{m+1} orthogonal to every Uk+1U_{k+1} with m−k>qm - k > q, which justifies the shortened loops.

Proof: The innovations algorithm computes the best linear one-step predictors, their error variances and the LDL factorization of the covariance matrixfull

Setting. X1,…,XnX_1, \ldots, X_n are real random variables with mean 0 and finite variance, and κ(i,j)=E[XiXj]\kappa(i, j) = \mathbb{E}[X_i X_j]. The matrix Kn=[κ(i,j)]i,j=1nK_n = [\kappa(i, j)]_{i,j=1}^n is positive definite. Work in the Hilbert space L2L^2 with ⟨Y,Z⟩=E[YZ]\langle Y, Z \rangle = \mathbb{E}[YZ]. Let Hm=span⁡{X1,…,Xm}H_m = \operatorname{span}\{X_1, \ldots, X_m\}, with H0={0}H_0 = \{0\}, let X^m+1\hat X_{m+1} be the orthogonal projection of Xm+1X_{m+1} on HmH_m, and let Um+1=Xm+1−X^m+1U_{m+1} = X_{m+1} - \hat X_{m+1} and vm=∥Um+1∥2v_m = \lVert U_{m+1} \rVert^2. In the code, θ[m][j]\theta[m][j] is θmj\theta_{mj}.

Claim 1 (the innovations are an orthogonal basis). For every mm, U1,…,UmU_1, \ldots, U_m are pairwise orthogonal, vm−1>0v_{m-1} > 0, and span⁡{U1,…,Um}=Hm\operatorname{span}\{U_1, \ldots, U_m\} = H_m.

Proof. By induction on mm. For m=1m = 1, U1=X1U_1 = X_1 and v0=κ(1,1)>0v_0 = \kappa(1, 1) > 0. Suppose the claim holds for mm. Then Um+1=Xm+1−X^m+1U_{m+1} = X_{m+1} - \hat X_{m+1} is orthogonal to HmH_m, which contains U1,…,UmU_1, \ldots, U_m. Since X^m+1∈Hm\hat X_{m+1} \in H_m, span⁡{U1,…,Um+1}=span⁡(Hm∪{Xm+1})=Hm+1\operatorname{span}\{U_1, \ldots, U_{m+1}\} = \operatorname{span}(H_m \cup \{X_{m+1}\}) = H_{m+1}. If vm=0v_m = 0, then Xm+1=X^m+1∈HmX_{m+1} = \hat X_{m+1} \in H_m almost surely, so Xm+1X_{m+1} is a linear combination of X1,…,XmX_1, \ldots, X_m and Km+1K_{m+1} is singular. This contradicts the positive definiteness of KnK_n, because Km+1K_{m+1} is a leading principal submatrix. So vm>0v_m > 0. □\square

Claim 2 (the predictor in terms of innovations). For m≥1m \ge 1,

X^m+1=∑k=0m−1θm,m−k Uk+1,θm,m−k=⟨Xm+1,Uk+1⟩vk,\hat X_{m+1} = \sum_{k=0}^{m-1} \theta_{m,m-k}\, U_{k+1}, \qquad \theta_{m,m-k} = \frac{\langle X_{m+1}, U_{k+1} \rangle}{v_k},

and vm=κ(m+1,m+1)−∑k=0m−1θm,m−k2vkv_m = \kappa(m+1, m+1) - \sum_{k=0}^{m-1} \theta_{m,m-k}^2 v_k.

Proof. By Claim 1, U1,…,UmU_1, \ldots, U_m is an orthogonal basis of HmH_m with nonzero vectors, so the projection on HmH_m is the sum of the projections on each Uk+1U_{k+1}. That is the first formula. By Pythagoras, ∥Xm+1∥2=∥X^m+1∥2+∥Um+1∥2\lVert X_{m+1} \rVert^2 = \lVert \hat X_{m+1} \rVert^2 + \lVert U_{m+1} \rVert^2 and ∥X^m+1∥2=∑kθm,m−k2vk\lVert \hat X_{m+1} \rVert^2 = \sum_k \theta_{m,m-k}^2 v_k. This is the formula for vmv_m, which is line L6. □\square

Claim 3 (lines L4 and L5). For 0≤k≤m−10 \le k \le m - 1,

⟨Xm+1,Uk+1⟩=κ(m+1,k+1)−∑j=0k−1θk,k−j θm,m−j vj.\langle X_{m+1}, U_{k+1} \rangle = \kappa(m+1, k+1) - \sum_{j=0}^{k-1} \theta_{k,k-j}\, \theta_{m,m-j}\, v_j.

So, if lines L3 to L5 compute θm,m−k\theta_{m,m-k} in the order k=0,1,…,m−1k = 0, 1, \ldots, m - 1, every value on the right side is known when it is needed, and line L5 stores the correct θm,m−k\theta_{m,m-k}.

Proof. By Claim 2 applied to step kk, Uk+1=Xk+1−∑j=0k−1θk,k−jUj+1U_{k+1} = X_{k+1} - \sum_{j=0}^{k-1} \theta_{k,k-j} U_{j+1} (for k=0k = 0 the sum is empty). Hence

⟨Xm+1,Uk+1⟩=κ(m+1,k+1)−∑j=0k−1θk,k−j⟨Xm+1,Uj+1⟩,\langle X_{m+1}, U_{k+1} \rangle = \kappa(m+1, k+1) - \sum_{j=0}^{k-1} \theta_{k,k-j} \langle X_{m+1}, U_{j+1} \rangle,

and ⟨Xm+1,Uj+1⟩=θm,m−jvj\langle X_{m+1}, U_{j+1} \rangle = \theta_{m,m-j} v_j by Claim 2. The right side uses θk,⋅\theta_{k,\cdot} from an earlier step and θm,m−j\theta_{m,m-j} with j<kj < k, which line L5 set earlier in the same step. Dividing by vk>0v_k > 0 (Claim 1) gives line L5. □\square

By induction on mm, Claims 2 and 3 show that after step mm the code holds the exact θm1,…,θmm\theta_{m1}, \ldots, \theta_{mm} and vmv_m. Line L1 sets v0=κ(1,1)v_0 = \kappa(1, 1), which is correct because X^1=0\hat X_1 = 0.

Claim 4 (the factorization and the likelihood). Let CC be the unit lower triangular n×nn \times n matrix with Cm+1,k+1=θm,m−kC_{m+1,k+1} = \theta_{m,m-k} for k<mk < m, and D=diag⁡(v0,…,vn−1)D = \operatorname{diag}(v_0, \ldots, v_{n-1}). Then X=CUX = C U and Kn=CDC⊤K_n = C D C^\top. Hence det⁡Kn=∏j=0n−1vj\det K_n = \prod_{j=0}^{n-1} v_j and x⊤Kn−1x=∑j=1n(xj−x^j)2/vj−1x^\top K_n^{-1} x = \sum_{j=1}^n (x_j - \hat x_j)^2 / v_{j-1}, where x^j\hat x_j is the predictor of Claim 2 evaluated at the data. For Gaussian XX,

−2log⁡L=nlog⁡(2π)+∑j=1nlog⁡vj−1+∑j=1n(xj−x^j)2vj−1.-2 \log L = n \log(2\pi) + \sum_{j=1}^n \log v_{j-1} + \sum_{j=1}^n \frac{(x_j - \hat x_j)^2}{v_{j-1}}.

Proof. Xm+1=X^m+1+Um+1X_{m+1} = \hat X_{m+1} + U_{m+1} and Claim 2 give row m+1m+1 of X=CUX = CU. By Claim 1, E[UU⊤]=D\mathbb{E}[UU^\top] = D, so Kn=E[XX⊤]=CDC⊤K_n = \mathbb{E}[XX^\top] = C D C^\top. Then det⁡Kn=(det⁡C)2det⁡D=∏vj\det K_n = (\det C)^2 \det D = \prod v_j. The map from xx to uu with x=Cux = Cu is u=C−1xu = C^{-1}x, and uj=xj−x^ju_j = x_j - \hat x_j because the predictors computed from the data satisfy the same triangular relation. So x⊤Kn−1x=u⊤D−1ux^\top K_n^{-1} x = u^\top D^{-1} u. The Gaussian density (2π)−n/2(det⁡Kn)−1/2exp⁡(−12x⊤Kn−1x)(2\pi)^{-n/2} (\det K_n)^{-1/2} \exp(-\frac12 x^\top K_n^{-1} x) gives the formula. □\square

Claim 5 (banded covariance). If κ(i,j)=0\kappa(i, j) = 0 whenever ∣i−j∣>q|i - j| > q, then θm,m−k=0\theta_{m,m-k} = 0 for k<m−qk < m - q. So starting the loops in L3, L4 and L6 at max⁡(0,m−q)\max(0, m - q) gives the same result.

Proof. By Claim 1, Uk+1∈Hk+1=span⁡{X1,…,Xk+1}U_{k+1} \in H_{k+1} = \operatorname{span}\{X_1, \ldots, X_{k+1}\}. If k<m−qk < m - q, then m+1−i>qm + 1 - i > q for every i≤k+1i \le k + 1, so Xm+1X_{m+1} is orthogonal to each XiX_i in that span and ⟨Xm+1,Uk+1⟩=0\langle X_{m+1}, U_{k+1} \rangle = 0. By Claim 2, θm,m−k=0\theta_{m,m-k} = 0. The terms dropped from the sums in L4 and L6 all contain such a factor θm,m−j\theta_{m,m-j} with j<m−qj < m - q, so they are 0. □\square

Claim 6 (exact arithmetic). Lines L1 to L7 use only addition, subtraction, multiplication and division by vk>0v_k > 0. On rational covariances in exact rational arithmetic they return the exact θmj\theta_{mj} and vmv_m.

Proof. Claims 1 to 5. No square root or rounding occurs. □\square

The tests check Claim 4 against an independent LDL⊤LDL^\top factorization of random positive definite matrices in Fraction arithmetic, and the likelihood against a direct determinant and quadratic form. They check Claim 5 by comparing the banded and full versions on MA(qq) covariances, and the MA(1) closed form vm=Sm+1/Smv_m = S_{m+1}/S_m with Sm=∑i=0mθ2iS_m = \sum_{i=0}^{m} \theta^{2i} in exact arithmetic.

Cited, not proved here. For an invertible MA(qq) process, θmj→θj\theta_{mj} \to \theta_j and vm→σ2v_m \to \sigma^2 as m→∞m \to \infty (Brockwell and Davis 1991, Chapter 5). If m→∞m \to \infty with m3/n→0m^3/n \to 0, the estimates θ^m1,…,θ^mq\hat\theta_{m1}, \ldots, \hat\theta_{mq} from sample autocovariances are consistent and asymptotically normal (Brockwell and Davis 1991, Section 8.3). The simulation on the page measures the finite-sample behaviour for MA(1).

Complexity

  • Full recursion. L4 and L6 do ∑m=1n−1(m2+m)=(n−1)n(n+1)/3\sum_{m=1}^{n-1}(m^2 + m) = (n - 1)n(n + 1)/3 multiplications, counting both products in each term, so the time is Θ(n3)\Theta(n^3), the same order as the Cholesky decomposition it is equivalent to. A run with a counting number type gave 330 multiplications for n=10n = 10 and 170640 for n=80n = 80, equal to the formula.
  • Banded, MA(qq). Each step mm costs about q(q+1)q(q + 1) multiplications, so the total is about nq(q+1)n q(q + 1), which is Θ(nq2)\Theta(n q^2) and 2n2n for q=1q = 1. Measured counts for n=100n = 100 were 198, 590, 1172 and 1940 for q=1,2,3,4q = 1, 2, 3, 4, just under nq(q+1)=200,600,1200,2000n q(q + 1) = 200, 600, 1200, 2000.
  • Predictions. Given the coefficients, the nn predictors cost Θ(n2)\Theta(n^2), or Θ(nq)\Theta(nq) in the banded case.
  • Space. The code keeps all rows of θ\theta, which is Θ(n2)\Theta(n^2). The banded case needs only the last qq rows and the last qq variances, O(q2)O(q^2) for the recursion, if the predictors are computed on the fly.

For a stationary series with no band, the Durbin-Levinson recursion finds the same predictors in Θ(n2)\Theta(n^2), so the innovations algorithm is the better choice only for banded or nonstationary covariances.

Properties

  • Exact. In exact arithmetic it returns the exact predictors, error variances and likelihood. There is no truncation, and no stationary start-up assumption: the first predictions use only the data actually seen.

  • Online. Step mm uses only κ(i,j)\kappa(i, j) for i,j≤m+1i, j \le m + 1, so a new observation adds one step, which costs O(m2)O(m^2) in general and O(q2)O(q^2) in the banded case.

  • Convergence to the Wold quantities. For a stationary invertible MA(qq) process, vm→σ2v_m \to \sigma^2 and θmj→θj\theta_{mj} \to \theta_j as m→∞m \to \infty. The rate is geometric when the roots of θ(z)\theta(z) are outside the unit circle. For MA(1) with θ=1\theta = 1, which is not invertible, vm=σ2(m+2)/(m+1)v_m = \sigma^2 (m + 2)/(m + 1), so the convergence is only like 1/m1/m.

  • Preliminary MA estimates (measured). MA(1) with θ=0.5\theta = 0.5, θ^m1\hat\theta_{m1} from the sample autocovariances, 200 series per row:

    nn mm mean sd 1/n1/\sqrt{n} maximum likelihood sd (1−θ2)/n\sqrt{(1 - \theta^2)/n}
    200 5 0.4902 0.0746 0.0707 0.0612
    200 10 0.4891 0.0704 0.0707 0.0612
    200 20 0.4989 0.0682 0.0707 0.0612
    1000 5 0.4957 0.0345 0.0316 0.0274
    1000 10 0.4972 0.0332 0.0316 0.0274
    1000 20 0.4970 0.0350 0.0316 0.0274

    The theory (Brockwell and Davis 1991, Section 8.3) gives n(θ^m1−θ1)→N(0,1)\sqrt{n}(\hat\theta_{m1} - \theta_1) \to N(0, 1) when m→∞m \to \infty slowly with nn, so the asymptotic variance is 1/n1/n, not the (1−θ2)/n(1 - \theta^2)/n of maximum likelihood. The simulation agrees: the estimate is consistent but not efficient, and it is a good start for the likelihood search.

Variants and improvements

  • ARMA processes. For a causal ARMA(pp, qq) process, apply the recursion to Wt=σ−1XtW_t = \sigma^{-1}X_t for t≤mt \le m and Wt=σ−1ϕ(B)XtW_t = \sigma^{-1}\phi(B)X_t for t>mt > m, with m=max⁡(p,q)m = \max(p, q). The covariance of WW is banded after the first mm rows, so the cost is O(nm2)O(n m^2) (Brockwell and Davis 1991, Section 5.3). This is Ansley's method for the exact ARMA likelihood.
  • Durbin-Levinson recursion. For stationary series it computes the predictor coefficients on XX instead of on the innovations, in Θ(n2)\Theta(n^2); see the Yule-Walker equations and Levinson-Durbin recursion pages.
  • Kalman filter. For a process in state space form, the Kalman filter produces the same innovations and variances in O(nr3)O(n r^3) for a state of dimension rr, and also handles missing values and nonstationary starts.
  • Multivariate series. The same recursion holds with matrices: Θmj\Theta_{mj} are k×kk \times k matrices and VmV_m are covariance matrices.
  • Preliminary ARMA estimates. Combining the innovations estimates of the MA(∞\infty) weights ψj\psi_j with the relation ψ(z)ϕ(z)=θ(z)\psi(z)\phi(z) = \theta(z) gives preliminary ARMA estimates (Brockwell and Davis 1991, Section 8.4).

When to use it

Use it to compute the exact Gaussian likelihood or exact finite-sample forecasts of an MA or ARMA model, and for nonstationary covariances where Durbin-Levinson does not apply. It is the core of the prediction error method for these models. For a long stationary AR series, use Durbin-Levinson. For models with missing data, regression effects or time-varying parameters, a state space form with the Kalman filter is usually easier.

Pitfalls

  • Indices. The book indexes θmj\theta_{mj} by the step mm and the lag jj of the innovation, so θ[m][m−k]\theta[m][m-k] in L5 is the weight on the innovation Uk+1U_{k+1}. Mixing the two indices is the most common error.
  • The cost without a band. The full recursion is cubic, not quadratic. It is the predictor step, once the coefficients are known, that is quadratic.
  • A covariance that is not positive definite. Sample autocovariances with the divisor n−hn - h can give a negative vmv_m. Use the divisor nn.
  • Noninvertible MA models. With a root of θ(z)\theta(z) on the unit circle, vmv_m converges to σ2\sigma^2 slowly and the estimates of θ\theta often pile up at the boundary. Restrict the search to the invertible region.
  • Floating point. The recursion is a Cholesky factorization in disguise and has the same rounding behaviour. Its error grows with the condition number of KnK_n, which is large when the spectral density is close to 0 at some frequency.

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.

innovations_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/innovations-algorithm/. The authors are listed in prov/1XEA6P.jsonl.

"""The innovations algorithm (Brockwell and Davis 1991, section 5.2).

For a zero-mean series X_1, ..., X_n with covariances kappa(i, j) = E[X_i X_j], it returns the
coefficients theta[m][j] (1 <= j <= m) and the mean squared errors v[m] of the one-step
predictors

    Xhat_1 = 0,   Xhat_(m+1) = sum_(j=1..m) theta[m][j] (X_(m+1-j) - Xhat_(m+1-j)).

The recursion uses only +, -, * and /, so it runs unchanged on fractions.Fraction values.
Indices follow the book: kappa is called with 1-based arguments.
"""

from __future__ import annotations

import math
from typing import Callable, Sequence


def innovations(kappa: Callable[[int, int], object], n: int, q: int | None = None):
    """Return (theta, v). theta[m] is a list with theta[m][j] at index j (index 0 unused).

    If q is given, kappa(i, j) must be 0 whenever |i - j| > q (an MA(q) process). Then
    theta[m][j] = 0 for j > q and the loops skip those zeros, so the cost is O(n q^2).
    """
    if n < 1:
        raise ValueError("need n >= 1")
    theta: list[list] = [[0]]
    v = [kappa(1, 1)]  # @line L1
    if not v[0] > 0:
        raise ValueError("kappa(1, 1) must be positive")
    for m in range(1, n):  # @line L2
        row = [0] * (m + 1)
        k_lo = 0 if q is None else max(0, m - q)
        for k in range(k_lo, m):  # @line L3
            s = kappa(m + 1, k + 1)
            for j in range(k_lo, k):
                s -= theta[k][k - j] * row[m - j] * v[j]  # @line L4
            row[m - k] = s / v[k]  # @line L5
        theta.append(row)
        vm = kappa(m + 1, m + 1) - sum(row[m - j] * row[m - j] * v[j] for j in range(k_lo, m))  # @line L6
        if not vm > 0:
            raise ValueError("the covariance matrix is not positive definite")
        v.append(vm)
    return theta, v  # @line L7


def one_step_predictors(x: Sequence, theta: list[list]) -> list:
    """Return Xhat_1, ..., Xhat_n (and Xhat_(n+1) if theta has n rows past row 0)."""
    n = len(x)
    xhat = [0 * x[0] if n else 0]
    for m in range(1, min(n, len(theta) - 1) + 1):
        xhat.append(sum(theta[m][j] * (x[m - j] - xhat[m - j]) for j in range(1, m + 1)))
    return xhat


def gaussian_neg2_loglik(x: Sequence[float], kappa: Callable[[int, int], float],
                         q: int | None = None) -> float:
    """-2 log L of a zero-mean Gaussian vector with covariance kappa, by the innovations.

    -2 log L = n log(2 pi) + sum_j log v_(j-1) + sum_j (X_j - Xhat_j)^2 / v_(j-1).
    """
    n = len(x)
    theta, v = innovations(kappa, n, q)
    xhat = one_step_predictors(list(x), theta)
    total = n * math.log(2 * math.pi)
    total += math.fsum(math.log(v[j]) for j in range(n))
    total += math.fsum((x[j] - xhat[j]) ** 2 / v[j] for j in range(n))
    return total


def ma_autocovariance(theta: Sequence, sigma2, max_lag: int) -> list:
    """gamma(h) of X_t = e_t + theta_1 e_(t-1) + ... + theta_q e_(t-q), e ~ WN(0, sigma2)."""
    c = [1] + list(theta)
    q = len(c) - 1
    return [sigma2 * sum(c[j] * c[j + h] for j in range(q - h + 1)) if h <= q else 0 * sigma2
            for h in range(max_lag + 1)]


def stationary_kappa(gamma: Sequence) -> Callable[[int, int], object]:
    """kappa(i, j) = gamma(|i - j|) for a stationary series, with gamma(h) = 0 past the list."""
    zero = 0 * gamma[0]

    def kappa(i: int, j: int):
        h = abs(i - j)
        return gamma[h] if h < len(gamma) else zero

    return kappa


def ma_preliminary_estimate(x: Sequence[float], q: int, m: int) -> tuple[list[float], float]:
    """Preliminary MA(q) estimate (Brockwell and Davis 1991, section 8.3).

    Run the recursion on the sample autocovariances (divisor n) up to step m and return
    (theta_hat[m][1..q], v_hat[m]).
    """
    n = len(x)
    if not q <= m < n:
        raise ValueError("need q <= m < n")
    mean = math.fsum(x) / n
    d = [xi - mean for xi in x]
    gamma = [math.fsum(d[t + h] * d[t] for t in range(n - h)) / n for h in range(m + 1)]
    theta, v = innovations(stationary_kappa(gamma), m + 1)
    return [theta[m][j] for j in range(1, q + 1)], v[m]
test_innovations_algorithm.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/innovations-algorithm/. The authors are listed in prov/1XEA6P.jsonl.

import math
import random
from fractions import Fraction

import pytest

from innovations_algorithm import (
    gaussian_neg2_loglik,
    innovations,
    ma_autocovariance,
    ma_preliminary_estimate,
    one_step_predictors,
    stationary_kappa,
)


def ldl(a: list[list[Fraction]]) -> tuple[list[list[Fraction]], list[Fraction]]:
    """The LDL^T factorization of a symmetric positive definite matrix in exact arithmetic."""
    n = len(a)
    low = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)]
    d = [Fraction(0)] * n
    for j in range(n):
        d[j] = a[j][j] - sum(low[j][k] ** 2 * d[k] for k in range(j))
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] * d[k] for k in range(j))) / d[j]
    return low, d


def solve_and_det(a: list[list[Fraction]], b: list[Fraction]) -> tuple[list[Fraction], Fraction]:
    """Gaussian elimination in Fractions: the solution of a y = b and det(a)."""
    n = len(b)
    m = [row[:] + [b[i]] for i, row in enumerate(a)]
    det = Fraction(1)
    for c in range(n):
        piv = next(r for r in range(c, n) if m[r][c] != 0)
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            det = -det
        det *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    y = [Fraction(0)] * n
    for i in reversed(range(n)):
        y[i] = (m[i][n] - sum(m[i][j] * y[j] for j in range(i + 1, n))) / m[i][i]
    return y, det


def random_spd(n: int, rng: random.Random) -> list[list[Fraction]]:
    b = [[Fraction(rng.randint(-3, 3)) for _ in range(n)] for _ in range(n)]
    return [[sum(b[i][k] * b[j][k] for k in range(n)) + (1 if i == j else 0) for j in range(n)]
            for i in range(n)]


def test_matches_ldl_of_the_covariance_matrix():
    rng = random.Random(1)
    for n in range(1, 8):
        for _ in range(5):
            a = random_spd(n, rng)
            theta, v = innovations(lambda i, j: a[i - 1][j - 1], n)
            low, d = ldl(a)
            assert v == d
            for m in range(1, n):
                for k in range(m):
                    assert theta[m][m - k] == low[m][k]


def test_ma1_closed_form():
    th, s2 = Fraction(1, 2), Fraction(3)
    g = ma_autocovariance([th], s2, 1)
    theta, v = innovations(stationary_kappa(g), 12)

    def big_s(k: int) -> Fraction:
        return sum(th ** (2 * i) for i in range(k + 1))

    for m in range(12):
        assert v[m] == s2 * big_s(m + 1) / big_s(m)
        if m >= 1:
            assert theta[m][1] == th * s2 / v[m - 1]
            assert all(t == 0 for t in theta[m][2:])


def test_banded_version_equals_full_version_for_ma_q():
    rng = random.Random(2)
    for q in (1, 2, 3):
        for _ in range(4):
            th = [Fraction(rng.randint(-5, 5), 4) for _ in range(q)]
            g = ma_autocovariance(th, Fraction(1), q)
            full = innovations(stationary_kappa(g), 15)
            band = innovations(stationary_kappa(g), 15, q=q)
            assert full == band
            assert all(t == 0 for m in range(q + 1, 15) for t in full[0][m][q + 1:])


def test_ma_autocovariance_against_expansion():
    rng = random.Random(3)
    for q in range(5):
        th = [Fraction(rng.randint(-6, 6), 3) for _ in range(q)]
        c = [Fraction(1)] + th
        s2 = Fraction(rng.randint(1, 5))
        got = ma_autocovariance(th, s2, q + 3)
        for h in range(q + 4):
            # X_(t+h) = sum_i c_i e_(t+h-i) and X_t = sum_j c_j e_(t-j); only equal noise indices
            # contribute, each with variance s2.
            brute = sum(c[i] * c[j] * s2 for i in range(q + 1) for j in range(q + 1) if h - i == -j)
            assert got[h] == brute


def test_ar1_predictor_is_phi_times_last_value():
    phi = Fraction(3, 5)
    g = [phi ** h / (1 - phi ** 2) for h in range(10)]
    theta, v = innovations(stationary_kappa(g), 10)
    x = [Fraction(v_) for v_ in (2, -1, 3, 0, 5, -4, 1, 1, 2, -2)]
    xhat = one_step_predictors(x, theta)
    assert xhat[0] == 0
    assert all(xhat[m] == phi * x[m - 1] for m in range(1, 10))
    assert v[0] == 1 / (1 - phi ** 2) and all(vm == 1 for vm in v[1:])


def test_likelihood_matches_direct_determinant_and_quadratic_form():
    rng = random.Random(4)
    for n in (1, 3, 6, 9):
        a = random_spd(n, rng)
        x = [Fraction(rng.randint(-5, 5)) for _ in range(n)]
        y, det = solve_and_det(a, x)
        quad = sum(xi * yi for xi, yi in zip(x, y))
        direct = n * math.log(2 * math.pi) + math.log(det) + float(quad)
        got = gaussian_neg2_loglik([float(t) for t in x], lambda i, j: float(a[i - 1][j - 1]))
        assert got == pytest.approx(direct, rel=1e-12, abs=1e-9)


def test_preliminary_ma1_estimate_is_near_truth():
    # Measured, not proved: mean over r = 20 series of n = 2000 with theta = 0.5, seed 5.
    rng = random.Random(5)
    r, total = 20, 0.0
    for _ in range(r):
        e = [rng.gauss(0, 1) for _ in range(2001)]
        x = [e[t] + 0.5 * e[t - 1] for t in range(1, 2001)]
        est, v = ma_preliminary_estimate(x, 1, 20)
        total += est[0]
    # The innovations estimate has asymptotic variance 1/n here (Brockwell and Davis 1991,
    # section 8.3), so the standard error of the mean is about 0.005; the bias for m = 20 is small.
    assert abs(total / r - 0.5) < 0.04


def test_errors():
    with pytest.raises(ValueError):
        innovations(lambda i, j: 1.0, 2)  # a singular all-ones matrix
    with pytest.raises(ValueError):
        innovations(lambda i, j: 0.0, 1)

History

The innovations idea comes from filtering theory, where Kailath's innovations approach of the late 1960s wrote linear estimation in terms of the uncorrelated prediction errors. For time series models, Ansley (1979) computed the exact Gaussian likelihood of an ARMA process by a Cholesky factorization of the banded covariance matrix of ϕ(B)Xt\phi(B)X_t. Brockwell and Davis gave the recursion for one-step predictors its standard form and name in the 1987 first edition of Time Series: Theory and Methods, together with its use for MA estimation and recursive likelihood evaluation. Their textbooks made it a standard tool, beside the Durbin-Levinson recursion and the Kalman filter.

References

  1. Peter J. Brockwell and Richard A. Davis, Time Series: Theory and Methods, second edition, Springer, 1991, Section 5.2 (the innovations algorithm, pp. 169 to 174), Section 5.3 (recursive prediction of an ARMA process, p. 175), Section 8.3 (preliminary MA estimates by the innovations algorithm, p. 245) and Section 8.6 (recursive calculation of the Gaussian likelihood, p. 254)
  2. Peter J. Brockwell and Richard A. Davis, Introduction to Time Series and Forecasting, third edition, Springer, 2016, Section 2.5.4 (the innovations algorithm, p. 62), Section 5.1.3 (MA estimation, p. 132) and Section 5.2 (maximum likelihood, p. 139)
  3. Craig F. Ansley, An algorithm for the exact likelihood of a mixed autoregressive-moving average process, Biometrika 66(1), 1979, pp. 59 to 65 (the Cholesky factor of the banded covariance of the transformed process)

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.banded
  • 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