Algorithm Search⌘K

Algorithmadvanced

Johansen test

Also called Johansen trace test, Johansen cointegration test.

Finds the number of cointegrating relations in a vector autoregression by the canonical correlations between differences and lagged levels.

Time
Θ(n K^2 p^2 + K^3) worst · best
Space
Θ(n K p) extra
Where
K = the number of series; n = the length of the series; p = the order of the vector autoregression
Properties
deterministicnot exactofflineiterative
Origin
Søren Johansen, 1988

The Johansen test finds how many independent stationary linear combinations, or cointegrating relations, a set of KK integrated series has. It writes a vector autoregression in error correction form, where the matrix Π\Pi that multiplies the lagged levels has rank rr equal to the number of relations. The maximum likelihood estimate of a rank rr matrix comes from a generalized eigenvalue problem: the eigenvalues are the squared canonical correlations between the differences and the lagged levels, after both are cleaned of the short-run terms. The trace and maximum eigenvalue statistics are likelihood ratio statistics built from the small eigenvalues. Their null laws are nonstandard and depend on K−rK - r and on the deterministic terms. Unlike the Engle-Granger test, the method treats all series alike and estimates all the relations at once.

In plain words

Several series wander, but some mixtures of them may stay put. The test asks how many such mixtures exist. It first strips out the short-term wiggles. Then it looks for the mixtures of the levels that best predict the next changes. Each candidate mixture comes with a score between 0 and 1 that says how strongly it pulls the series back. Real long-run ties give large scores. Directions in which the series just wander give scores near 0. The test counts the scores that are too large to be chance, from the largest down, and stops at the first one that could be noise. The count is the number of long-run ties.

The problem

Model and hypotheses. Let Yt∈RKY_t \in \mathbb{R}^K follow a Gaussian VAR(pp), written in vector error correction form,

∇Yt=ΠYt−1+∑i=1p−1Γi∇Yt−i+μ+εt,εt iid N(0,Ω),\nabla Y_t = \Pi Y_{t-1} + \sum_{i=1}^{p-1}\Gamma_i\nabla Y_{t-i} + \mu + \varepsilon_t, \qquad \varepsilon_t \text{ iid } N(0, \Omega),

with μ=0\mu = 0 (case "none") or μ\mu free (case "c", an unrestricted constant, which gives linear trends in the levels). If YtY_t is I(1) with exactly rr cointegrating relations, then rank⁡Π=r\operatorname{rank}\Pi = r and Π=αβ⊤\Pi = \alpha\beta^\top with α,β\alpha, \beta of size K×rK \times r. The columns of β\beta span the cointegrating vectors, and α\alpha holds the speeds of adjustment. The hypotheses are nested: H(r)H(r): rank⁡Π≤r\operatorname{rank}\Pi \le r, for r=0,…,Kr = 0, \dots, K. H(K)H(K) is the unrestricted VAR, and H(0)H(0) is a VAR in differences.

Statistic. With λ^1≥⋯≥λ^K\hat\lambda_1 \ge \dots \ge \hat\lambda_K the eigenvalues of the problem in line L5 and TT the number of rows,

LRtrace(r)=−T∑i=r+1Klog⁡(1−λ^i),LRmax⁡(r)=−Tlog⁡(1−λ^r+1).\mathrm{LR}_{\mathrm{trace}}(r) = -T\sum_{i=r+1}^{K}\log(1 - \hat\lambda_i), \qquad \mathrm{LR}_{\max}(r) = -T\log(1 - \hat\lambda_{r+1}).

The trace statistic is the likelihood ratio statistic for H(r)H(r) against H(K)H(K), and the maximum eigenvalue statistic tests H(r)H(r) against H(r+1)H(r + 1). Both facts are proved on the correctness page.

Null distribution. Asymptotic and nonstandard. Under H(r)H(r) with exactly rr relations, LRtrace(r)\mathrm{LR}_{\mathrm{trace}}(r) converges to the trace of a matrix functional of a (K−r)(K - r)-dimensional Brownian motion,

tr⁡{∫01dW F⊤(∫01FF⊤du)−1∫01F dW⊤},\operatorname{tr}\left\{\int_0^1 dW\,F^\top\left(\int_0^1 FF^\top du\right)^{-1}\int_0^1 F\,dW^\top\right\},

where F=WF = W in case "none" and FF is a demeaned or trend-adjusted WW in the other cases (Johansen 1988, 1991). The limit does not depend on Ω\Omega, α\alpha, β\beta or Γi\Gamma_i. It is cited, not proved here. The quantiles come from simulation: Osterwald-Lenum (1992) tabulated them, and MacKinnon, Haug and Michelis (1999) fitted response surfaces.

Rejection rule and size. Reject H(r)H(r) when the statistic exceeds the quantile for K−rK - r and the case. The 95% points (MacKinnon, Haug and Michelis 1999):

K−rK - r trace, "none" trace, "c" max, "none" max, "c"
1 4.1296 3.8415 4.1296 3.8415
2 12.3212 15.4943 11.2246 14.2639
3 24.2761 29.7961 17.7961 21.1314
4 40.1749 47.8545 24.1592 27.5858
5 60.0627 69.8189 30.4428 33.8777

For K−r=1K - r = 1 in case "c", the limit is χ2(1)\chi^2(1), with 95% point 1.962=3.84151.96^2 = 3.8415, because the stochastic trend then has a drift that dominates. The rank is chosen by the sequential rule: test r=0,1,…r = 0, 1, \dots in turn and stop at the first rr that is not rejected. Each test has asymptotic size α\alpha. For the true rank r0r_0, the procedure picks r^<r0\hat r < r_0 with a probability that goes to 0, and r^=r0\hat r = r_0 with probability tending to 1−α1 - \alpha.

p-value. MacKinnon, Haug and Michelis (1999) give response surface p-values. A Monte Carlo p-value from K−rK - r independent random walks is valid asymptotically for r=0r = 0.

Sensitivity and power. The trace test has power against any larger rank, the maximum eigenvalue test against one more relation. A relation that adjusts slowly (small α\alpha) gives a small λ^\hat\lambda and is hard to find. The finite-sample size is above nominal when KK or pp is large relative to nn. Bartlett corrections or the bootstrap help there.

The algorithm

  1. JOHANSEN(Y₁..Y_n ∈ ℝ^K, p, case, α)
  2. 1R0_t ← residual of ∇Y_t after OLS on ∇Y_{t−1}, …, ∇Y_{t−p+1} (and 1 in case "c")
  3. 2R1_t ← residual of Y_{t−1} after OLS on the same regressors
  4. 3S_ij ← (1/T) Σ_t R_i,t R_j,tᵀ for i, j ∈ {0, 1}
  5. 4L ← Cholesky factor of S11 (S11 = L Lᵀ)
  6. 5(λ_i, v_i) ← eigenpairs of C = L⁻¹ S10 S00⁻¹ S01 L⁻ᵀ, λ₁ ≥ … ≥ λ_K
  7. 6β ← L⁻ᵀ [v₁ … v_K]; α ← S01 β
  8. 7trace(r) ← −T Σ_{i>r} log(1 − λ_i); max(r) ← −T log(1 − λ_{r+1})
  9. 8r̂ ← the first r with trace(r) < c_α(K − r, case), or K if none
  10. 9return (λ, trace, max, r̂, β[:, 1..r̂], α[:, 1..r̂])

Lines L4 to L6 turn the generalized problem det⁡(λS11−S10S00−1S01)=0\det(\lambda S_{11} - S_{10}S_{00}^{-1}S_{01}) = 0 into a symmetric eigenvalue problem, which a Jacobi or QR eigensolver handles stably. The vectors satisfy β⊤S11β=I\beta^\top S_{11}\beta = I. The estimate of Π\Pi under H(r)H(r) is α^rβ^r⊤\hat\alpha_r\hat\beta_r^\top with the first rr columns. Since only the span of βr\beta_r is identified, practice normalizes one entry of each vector to 1 for reporting.

Example

By hand. Take K=2K = 2, n=7n = 7, p=1p = 1 (no lagged differences), case "none", with Y1=(1,3,2,4,3,5,4)Y_1 = (1, 3, 2, 4, 3, 5, 4) and Y2=(0,2,3,3,5,4,6)Y_2 = (0, 2, 3, 3, 5, 4, 6). Then T=6T = 6, R0t=∇YtR_{0t} = \nabla Y_t, R1t=Yt−1R_{1t} = Y_{t-1}, and the moment matrices are integers over 6:

step value
L3: TS00T S_{00} (15−3−314)\begin{pmatrix}15 & -3\\-3 & 14\end{pmatrix}
L3: TS01T S_{01} (rows: ∇Y\nabla Y, columns: Yt−1Y_{t-1}) (072011)\begin{pmatrix}0 & 7\\20 & 11\end{pmatrix}
L3: TS11T S_{11} (64595963)\begin{pmatrix}64 & 59\\59 & 63\end{pmatrix}
L5: trace and determinant of S11−1S10S00−1S01S_{11}^{-1}S_{10}S_{00}^{-1}S_{01} 128672/110751128672/110751 and 19600/11075119600/110751
L5: λ^1\hat\lambda_1, λ^2\hat\lambda_2 0.98151, 0.18031
L6: β^1\hat\beta_1, scaled so its first entry is 1 (1,−0.837)(1, -0.837)
L7: trace(0), trace(1) 25.13, 1.19
L7: max(0), max(1) 23.94, 1.19
L8: compare with 12.3212 and 4.1296 reject r=0r = 0, keep r=1r = 1, so r^=1\hat r = 1

The denominator 110751=551⋅201110751 = 551 \cdot 201 is det⁡(TS11)det⁡(TS00)\det(TS_{11})\det(TS_{00}). The factor TT cancels in the eigenvalues, so they are exact algebraic numbers, the roots of z2−(128672/110751)z+19600/110751z^2 - (128672/110751)z + 19600/110751. With six rows the asymptotic quantiles are not reliable; the example only shows the steps.

Three series with one relation. With seed 2026, let x1x_1 and x2x_2 be independent Gaussian random walks of length 200, ut=0.5ut−1+εtu_t = 0.5u_{t-1} + \varepsilon_t, and yt=x1t−x2t+uty_t = x_{1t} - x_{2t} + u_t. With K=3K = 3, p=1p = 1 and case "none" (T=199T = 199):

rr λ^r+1\hat\lambda_{r+1} trace(rr) 95% point max(rr) 95% point
0 0.2836 77.99 24.28 66.36 17.80
1 0.0565 11.64 12.32 11.57 11.22
2 0.0003 0.06 4.13 0.06 4.13

The trace sequence stops at r^=1\hat r = 1, and the first vector, scaled, is β^1=(1,−0.981,1.015)\hat\beta_1 = (1, -0.981, 1.015), close to the true (1,−1,1)(1, -1, 1). The maximum eigenvalue test of r=1r = 1 against r=2r = 2 rejects narrowly (11.57 against 11.22), so the two rules disagree here. The Engle-Granger regression of yy on x1x_1 and x2x_2 gives slopes 0.9930.993 and −1.055-1.055 and τ=−7.92\tau = -7.92, which also finds the relation.

Size. With two independent Gaussian random walks of length 200 and 2000 samples (each 2000-sample design here starts a new generator with seed 11, as in the tests), the trace test of r=0r = 0 at the 95% point 12.3212 rejected in 5.7% of samples, and the simulated 95% quantile was 12.74. With three walks it rejected in 6.2% at 24.2761. These rates are measured, not derived. With case "c" applied to walks without drift, it rejected in 11.8% at 15.4943. This shows the cost of a wrong deterministic case. With a drift of 0.3 per step, the case "c" rate fell to 6.5% in 1000 samples.

Correctness

The correctness page proves that the procedure computes the Gaussian maximum likelihood estimate under each rank and the likelihood ratio statistics. First, the short-run terms are concentrated out by the Frisch-Waugh projection of lines L1 and L2. For fixed β\beta the best α\alpha and Ω\Omega are those of a regression of R0R_0 on β⊤R1\beta^\top R_1, and det⁡Ω^(β)=det⁡S00⋅det⁡β⊤(S11−S10S00−1S01)β/det⁡β⊤S11β\det\hat\Omega(\beta) = \det S_{00}\cdot\det\beta^\top(S_{11} - S_{10}S_{00}^{-1}S_{01})\beta/\det\beta^\top S_{11}\beta. By the Poincaré separation theorem this ratio is minimized by the first rr generalized eigenvectors, with minimum det⁡S00∏i≤r(1−λ^i)\det S_{00}\prod_{i \le r}(1 - \hat\lambda_i). The trace and maximum eigenvalue statistics follow as differences of −Tlog⁡det⁡Ω^-T\log\det\hat\Omega. The page also proves that the Cholesky reduction of lines L4 to L6 solves the generalized problem with β⊤S11β=I\beta^\top S_{11}\beta = I, that 0≤λ^i≤10 \le \hat\lambda_i \le 1, that the eigenvalues are unchanged when YtY_t is replaced by AYtAY_t (and AYt+cAY_t + c in case "c") for invertible AA, and that for K=1K = 1, λ^=t2/(t2+T−1)\hat\lambda = t^2/(t^2 + T - 1) with tt the Dickey-Fuller t ratio. The asymptotic null laws are cited from Johansen (1988, 1991).

Proof: Johansen's eigenvalue procedure gives the Gaussian maximum likelihood estimate for each cointegration rank, and the trace and maximum eigenvalue statistics are the likelihood ratio statisticsfull

We prove that the reduced rank regression of lines L1 to L6 maximizes the Gaussian likelihood of the error correction model under rank⁡Π≤r\operatorname{rank}\Pi \le r (Lemmas 1 and 2 and Theorem 3), that the trace and maximum eigenvalue statistics of line L7 are the likelihood ratio statistics (Corollary 4), that the Cholesky reduction solves the generalized eigenproblem (Lemma 5), that 0≤λ^i≤10 \le \hat\lambda_i \le 1 (Lemma 6), that the eigenvalues are invariant to invertible linear maps of the data (Lemma 7), and that for K=1K = 1 the procedure reduces to the Dickey-Fuller t ratio (Lemma 8). We do not prove the asymptotic null laws of the statistics (Johansen 1988, 1991), the accuracy of the simulated quantiles, the consistency of the sequential rank choice, or the convergence rate of the Jacobi method. Throughout, S00S_{00} and S11S_{11} are assumed positive definite, which holds when the regressors of lines L1 and L2 have full rank and no exact linear relation holds among the residuals.

Lemma 1 (concentrating out the short-run terms). Let ZtZ_t collect the lagged differences and, in case "c", the constant. For fixed Π\Pi and Ω\Omega, the Gaussian log likelihood of ∇Yt=ΠYt−1+ΓZt+εt\nabla Y_t = \Pi Y_{t-1} + \Gamma Z_t + \varepsilon_t is maximized over Γ\Gamma by the least squares fit, and the concentrated log likelihood is

ℓ(Π,Ω)=−T2log⁡det⁡Ω−12∑t(R0t−ΠR1t)⊤Ω−1(R0t−ΠR1t)+const,\ell(\Pi, \Omega) = -\frac{T}{2}\log\det\Omega - \frac12\sum_t(R_{0t} - \Pi R_{1t})^\top\Omega^{-1}(R_{0t} - \Pi R_{1t}) + \text{const},

with R0tR_{0t} and R1tR_{1t} the residuals of lines L1 and L2.

Proof. Stack the rows: D=Y−1Π⊤+ZΓ⊤+ED = Y_{-1}\Pi^\top + Z\Gamma^\top + E, where DD is T×KT \times K. The quadratic form tr⁡{Ω−1(D−Y−1Π⊤−ZΓ⊤)⊤(D−Y−1Π⊤−ZΓ⊤)}\operatorname{tr}\{\Omega^{-1}(D - Y_{-1}\Pi^\top - Z\Gamma^\top)^\top(D - Y_{-1}\Pi^\top - Z\Gamma^\top)\} is minimized over Γ\Gamma by the least squares fit of D−Y−1Π⊤D - Y_{-1}\Pi^\top on ZZ, for any positive definite Ω\Omega, because generalized least squares with a common regressor matrix in every equation equals least squares equation by equation (this is the result proved on the vector autoregression page). The minimizing residual is MZ(D−Y−1Π⊤)=R0−R1Π⊤M_Z(D - Y_{-1}\Pi^\top) = R_0 - R_1\Pi^\top, where MZM_Z is the projection onto the orthogonal complement of the columns of ZZ, R0=MZDR_0 = M_ZD and R1=MZY−1R_1 = M_ZY_{-1}. These are exactly the residuals of lines L1 and L2. □\square

Lemma 2 (fixed β\beta). Under Π=αβ⊤\Pi = \alpha\beta^\top with β\beta fixed of full rank rr, the maximum over α\alpha and Ω\Omega is attained at α^(β)=S01β(β⊤S11β)−1\hat\alpha(\beta) = S_{01}\beta(\beta^\top S_{11}\beta)^{-1} and Ω^(β)=S00−S01β(β⊤S11β)−1β⊤S10\hat\Omega(\beta) = S_{00} - S_{01}\beta(\beta^\top S_{11}\beta)^{-1}\beta^\top S_{10}, and

det⁡Ω^(β)=det⁡S00⋅det⁡β⊤(S11−S10S00−1S01)βdet⁡β⊤S11β.\det\hat\Omega(\beta) = \det S_{00}\cdot\frac{\det\beta^\top(S_{11} - S_{10}S_{00}^{-1}S_{01})\beta}{\det\beta^\top S_{11}\beta}.

The concentrated log likelihood is −T2log⁡det⁡Ω^(β)−TK2+const-\frac T2\log\det\hat\Omega(\beta) - \frac{TK}{2} + \text{const}.

Proof. With β\beta fixed, R0t=α(β⊤R1t)+εtR_{0t} = \alpha(\beta^\top R_{1t}) + \varepsilon_t is a multivariate regression on the rr regressors β⊤R1t\beta^\top R_{1t}, common to all equations. By the same fact as in Lemma 1, least squares gives α^(β)\hat\alpha(\beta), and the residual covariance is the Gaussian maximum likelihood estimate of Ω\Omega, which is Ω^(β)\hat\Omega(\beta). At that Ω\Omega the quadratic term equals tr⁡(Ω^−1TΩ^)=TK\operatorname{tr}(\hat\Omega^{-1}T\hat\Omega) = TK. For the determinant, consider the block matrix

(S00S01ββ⊤S10β⊤S11β).\begin{pmatrix}S_{00} & S_{01}\beta\\ \beta^\top S_{10} & \beta^\top S_{11}\beta\end{pmatrix}.

Its determinant equals det⁡(β⊤S11β)det⁡(S00−S01β(β⊤S11β)−1β⊤S10)\det(\beta^\top S_{11}\beta)\det(S_{00} - S_{01}\beta(\beta^\top S_{11}\beta)^{-1}\beta^\top S_{10}) by the Schur complement of the lower right block, and also det⁡S00det⁡(β⊤S11β−β⊤S10S00−1S01β)\det S_{00}\det(\beta^\top S_{11}\beta - \beta^\top S_{10}S_{00}^{-1}S_{01}\beta) by the Schur complement of the upper left block. Equate the two forms and divide. □\square

Theorem 3 (reduced rank regression). Let λ^1≥⋯≥λ^K\hat\lambda_1 \ge \dots \ge \hat\lambda_K solve det⁡(λS11−S10S00−1S01)=0\det(\lambda S_{11} - S_{10}S_{00}^{-1}S_{01}) = 0, with λ^K<1\hat\lambda_K < 1. Over all K×rK \times r matrices β\beta of rank rr,

min⁡βdet⁡Ω^(β)=det⁡S00∏i=1r(1−λ^i),\min_\beta\det\hat\Omega(\beta) = \det S_{00}\prod_{i=1}^{r}(1 - \hat\lambda_i),

attained by the first rr columns of β^\hat\beta from line L6. Hence α^rβ^r⊤\hat\alpha_r\hat\beta_r^\top is the maximum likelihood estimate of Π\Pi under H(r)H(r).

Proof. Write S11=LL⊤S_{11} = LL^\top and C=L−1S10S00−1S01L−⊤C = L^{-1}S_{10}S_{00}^{-1}S_{01}L^{-\top}, which is symmetric with eigenvalues λ^i\hat\lambda_i (Lemma 5). Put γ=L⊤β\gamma = L^\top\beta. Then the ratio in Lemma 2 is det⁡γ⊤(I−C)γ/det⁡γ⊤γ\det\gamma^\top(I - C)\gamma/\det\gamma^\top\gamma. Replacing γ\gamma by γM\gamma M for invertible MM multiplies the numerator and the denominator by (det⁡M)2(\det M)^2, so we may take γ=G\gamma = G with orthonormal columns, G⊤G=IrG^\top G = I_r. The matrix A=I−CA = I - C is symmetric with eigenvalues a1≤⋯≤aKa_1 \le \dots \le a_K, where ai=1−λ^ia_i = 1 - \hat\lambda_i, all positive. By the Poincaré separation theorem, a consequence of the Courant-Fischer minimax principle, the eigenvalues μ1≤⋯≤μr\mu_1 \le \dots \le \mu_r of G⊤AGG^\top AG satisfy μj≥aj\mu_j \ge a_j for j=1..rj = 1..r. So det⁡G⊤AG=∏jμj≥∏j≤raj=∏i≤r(1−λ^i)\det G^\top AG = \prod_j\mu_j \ge \prod_{j \le r}a_j = \prod_{i \le r}(1 - \hat\lambda_i). Equality holds when the columns of GG are the eigenvectors v1..vrv_1..v_r of CC for the rr largest λ^i\hat\lambda_i, since then G⊤AG=diag⁡(1−λ^1,…,1−λ^r)G^\top AG = \operatorname{diag}(1 - \hat\lambda_1, \dots, 1 - \hat\lambda_r). That GG corresponds to β=L−⊤[v1…vr]\beta = L^{-\top}[v_1 \dots v_r], which is line L6. □\square

Corollary 4 (the statistics are likelihood ratios). The maximized log likelihood under H(r)H(r) is −T2(log⁡det⁡S00+∑i≤rlog⁡(1−λ^i))-\frac T2\left(\log\det S_{00} + \sum_{i \le r}\log(1 - \hat\lambda_i)\right) plus a constant that does not depend on rr. Therefore −2log⁡-2\log of the likelihood ratio of H(r)H(r) against H(K)H(K) is −T∑i=r+1Klog⁡(1−λ^i)-T\sum_{i=r+1}^{K}\log(1 - \hat\lambda_i), and of H(r)H(r) against H(r+1)H(r + 1) is −Tlog⁡(1−λ^r+1)-T\log(1 - \hat\lambda_{r+1}).

Proof. Theorem 3 with Lemma 2 gives the maximized value for each rr, including r=Kr = K, where β\beta ranges over all invertible matrices and the model is the unrestricted VAR. Take differences. □\square

Lemma 5 (lines L4 to L6). If Cv=λvCv = \lambda v with ∥v∥=1\lVert v\rVert = 1 and β=L−⊤v\beta = L^{-\top}v, then S10S00−1S01β=λS11βS_{10}S_{00}^{-1}S_{01}\beta = \lambda S_{11}\beta. For an orthonormal eigenbasis VV of CC, β^=L−⊤V\hat\beta = L^{-\top}V satisfies β^⊤S11β^=I\hat\beta^\top S_{11}\hat\beta = I.

Proof. S10S00−1S01β=LCL⊤L−⊤v=LCv=λLv=λLL⊤L−⊤v=λS11βS_{10}S_{00}^{-1}S_{01}\beta = LCL^\top L^{-\top}v = LCv = \lambda Lv = \lambda LL^\top L^{-\top}v = \lambda S_{11}\beta. Also β^⊤S11β^=V⊤L−1LL⊤L−⊤V=V⊤V=I\hat\beta^\top S_{11}\hat\beta = V^\top L^{-1}LL^\top L^{-\top}V = V^\top V = I. CC is symmetric because S01=S10⊤S_{01} = S_{10}^\top and S00−1S_{00}^{-1} is symmetric, so an orthonormal eigenbasis exists. □\square

The implementation symmetrizes CC before the Jacobi method, which removes rounding asymmetry and does not change CC in exact arithmetic. Each Jacobi rotation is an orthogonal similarity, so the eigenvalues are preserved, and the product of the rotations is orthogonal.

Lemma 6 (the eigenvalues lie in [0,1][0, 1]). CC is positive semidefinite, and I−CI - C is positive semidefinite.

Proof. C=(S00−1/2S01L−⊤)⊤(S00−1/2S01L−⊤)C = (S_{00}^{-1/2}S_{01}L^{-\top})^\top(S_{00}^{-1/2}S_{01}L^{-\top}) is a Gram matrix. For I−C=L−1(S11−S10S00−1S01)L−⊤I - C = L^{-1}(S_{11} - S_{10}S_{00}^{-1}S_{01})L^{-\top}, note that S11−S10S00−1S01S_{11} - S_{10}S_{00}^{-1}S_{01} is the Schur complement of S00S_{00} in the moment matrix 1T∑t(R0t⊤,R1t⊤)⊤(R0t⊤,R1t⊤)\frac1T\sum_t(R_{0t}^\top, R_{1t}^\top)^\top(R_{0t}^\top, R_{1t}^\top), which is positive semidefinite; the Schur complement of a positive definite block in a positive semidefinite matrix is positive semidefinite. So 0≤λ^i≤10 \le \hat\lambda_i \le 1. These are the squared canonical correlations between R0R_0 and R1R_1. □\square

Lemma 7 (invariance). Let AA be an invertible K×KK \times K matrix. Replacing YtY_t by AYtAY_t in case "none", or by AYt+cAY_t + c in case "c", leaves every λ^i\hat\lambda_i unchanged, and β^\hat\beta becomes A−⊤β^A^{-\top}\hat\beta up to the choice of eigenbasis.

Proof. The lagged differences become A∇Yt−iA\nabla Y_{t-i}, which span the same column space, and in case "c" the constant cc disappears in the differences and is absorbed by the constant regressor in the levels. So R0↦R0A⊤R_0 \mapsto R_0A^\top and R1↦R1A⊤R_1 \mapsto R_1A^\top, and Sij↦ASijA⊤S_{ij} \mapsto AS_{ij}A^\top. Then det⁡(λAS11A⊤−AS10A⊤(AS00A⊤)−1AS01A⊤)=(det⁡A)2det⁡(λS11−S10S00−1S01)\det(\lambda AS_{11}A^\top - AS_{10}A^\top(AS_{00}A^\top)^{-1}AS_{01}A^\top) = (\det A)^2\det(\lambda S_{11} - S_{10}S_{00}^{-1}S_{01}), which has the same roots. The eigenvector equation is solved by A−⊤βA^{-\top}\beta. □\square

Lemma 8 (one series). For K=1K = 1, p=1p = 1 and case "none", λ^=t2/(t2+T−1)\hat\lambda = t^2/(t^2 + T - 1), where tt is the t ratio of ρ\rho in ∇Yt=ρYt−1+et\nabla Y_t = \rho Y_{t-1} + e_t.

Proof. Let N=(∑Yt−1∇Yt)2/∑Yt−12N = (\sum Y_{t-1}\nabla Y_t)^2/\sum Y_{t-1}^2 and D=∑(∇Yt)2D = \sum(\nabla Y_t)^2. Then λ^=S012/(S00S11)=N/D\hat\lambda = S_{01}^2/(S_{00}S_{11}) = N/D. The residual sum of squares is D−ND - N, so t2=ρ^2∑Yt−12/s2=(T−1)N/(D−N)t^2 = \hat\rho^2\sum Y_{t-1}^2/s^2 = (T - 1)N/(D - N). Then t2/(t2+T−1)=N/(N+D−N)=N/Dt^2/(t^2 + T - 1) = N/(N + D - N) = N/D. □\square

So the trace statistic for K=1K = 1 is −Tlog⁡(1−t2/(t2+T−1))=Tlog⁡(1+t2/(T−1))-T\log(1 - t^2/(t^2 + T - 1)) = T\log(1 + t^2/(T - 1)), a two-sided function of the Dickey-Fuller statistic.

Termination. Lines L1 to L4 and L6 to L8 are loops with fixed bounds. Line L5 runs cyclic Jacobi sweeps until the off-diagonal mass is below a relative tolerance, with at most a fixed number of sweeps. The cyclic Jacobi method converges for symmetric matrices, quadratically in the end (Forsythe and Henrici 1960; Wilkinson 1962), which we cite. In the tests a 3×33 \times 3 problem needs at most a few sweeps.

Complexity

On a real RAM, lines L1 and L2 regress 2K2K columns on q=K(p−1)+dq = K(p - 1) + d regressors (d=1d = 1 in case "c"). A QR factorization of the regressors costs Θ(Tq2)\Theta(Tq^2) and the projections Θ(TqK)\Theta(TqK). Line L3 costs Θ(TK2)\Theta(TK^2). Lines L4 to L6 cost Θ(K3)\Theta(K^3) for the Cholesky factor and the products, and O(K3)O(K^3) per Jacobi sweep, with a number of sweeps that is small in practice. With T≈nT \approx n, the total is Θ(nK2p2+K3)\Theta(nK^2p^2 + K^3) time and Θ(nKp)\Theta(nKp) space for the regressors.

Numerical stability. Do not form S11−1S10S00−1S01S_{11}^{-1}S_{10}S_{00}^{-1}S_{01} and call a general eigensolver: that matrix is not symmetric and its eigenvectors can be badly conditioned. The Cholesky route keeps the problem symmetric. Levels that are far from 0 make S11S_{11} badly conditioned in case "none"; scaling each series by its standard deviation changes no eigenvalue, by the invariance result. An eigenvalue that rounds to 1 makes log⁡(1−λ)\log(1 - \lambda) infinite; it signals an exact fit, usually too many lags for the sample.

Properties

  • Maximum likelihood. Under Gaussian errors, β^r\hat\beta_r spans the maximum likelihood estimate of the cointegrating space, and it is superconsistent, with a mixed normal limit that gives χ2\chi^2 tests of linear restrictions on β\beta.
  • Symmetric in the variables. No series has to be chosen as the dependent variable. The eigenvalues are invariant to invertible linear maps of YtY_t.
  • All relations at once. It estimates the rank and a basis of the cointegrating space, not a single vector.
  • Identification of the space only. Any βM\beta M with MM invertible fits as well; individual vectors need restrictions to be interpreted.
  • Depends on the deterministic case. The five standard cases (no constant, restricted constant, unrestricted constant, restricted trend, unrestricted trend) have different null laws.
  • Generalizes Dickey-Fuller. With K=1K = 1 and no deterministic terms, the trace statistic is a monotone function of the squared Dickey-Fuller t ratio.

Variants and improvements

  • Restricted constant and trends. A constant inside the cointegrating relation (ΠYt−1+μ=α(β⊤Yt−1+ρ0)\Pi Y_{t-1} + \mu = \alpha(\beta^\top Y_{t-1} + \rho_0)) and a restricted linear trend avoid quadratic trends in the levels. They use Yt−1Y_{t-1} augmented by 1 or tt in line L2 and their own tables.
  • Bartlett correction. Johansen (2002) scales the trace statistic by a factor that corrects its mean, which brings the size close to nominal in small samples.
  • Bootstrap. A recursive residual bootstrap of the VECM under H(r)H(r) gives finite-sample critical values.
  • Tests on β\beta and α\alpha. Linear restrictions on the cointegrating space or on the adjustment speeds are likelihood ratio tests with χ2\chi^2 limits, computed by the same reduced rank regression on transformed data.
  • Information criteria. The rank and the lag order can be chosen jointly by AIC or BIC.
  • Structural breaks. Johansen, Mosconi and Nielsen (2000) allow for known break dates in the deterministic terms.

When to use it

Use the Johansen test for three or more I(1) series, or for two when no series is a natural dependent variable, and when the number of relations is itself a question, as in money demand systems or term structures of interest rates. It needs a well-specified VAR: choose the lag order first (by AIC or BIC on the VAR in levels), check the residuals for autocorrelation, and choose the deterministic case from a plot of the series. For a single relation with a known dependent variable the Engle-Granger test is simpler. If a series may be stationary, test it with the ADF or KPSS test first, because a stationary series adds a trivial "relation".

Pitfalls

  • Wrong deterministic case. Using the unrestricted constant tables for series without drift inflated the size from 5% to about 12% in the example. Plot the data and choose the case before testing.
  • Lag order. Too few lags leave autocorrelated errors and distort the size; too many cost power. The trace statistics can change by a lot with pp.
  • Small samples. The asymptotic quantiles are too small when TT is small relative to KpKp, so the rank is overestimated. Use a Bartlett correction or a bootstrap.
  • Trace and max disagree. The two statistics can point to different ranks, as in the example. Report both and the sequential trace choice.
  • Stationary series in the system. A stationary variable makes a unit vector a cointegrating vector and raises the rank by one without any economic link.
  • Interpreting raw eigenvectors. The vectors are only identified up to a basis change. Impose and test restrictions before reading off coefficients.
  • Rank zero is not "no relation found". Failing to reject r=0r = 0 may mean low power, especially when the adjustment is slow.

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.

johansen_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/johansen-test/. The authors are listed in prov/AA2XYN.jsonl.
"""The Johansen trace and maximum eigenvalue tests for the cointegration rank.

The vector error correction form of a VAR(p) in K variables is

    dY_t = Pi Y_(t-1) + sum_(i=1..p-1) G_i dY_(t-i) + mu + e_t.

The test removes the short-run terms (lagged differences and, in case "c",
the constant) from dY_t and from Y_(t-1) by least squares, forms the moment
matrices S_00, S_01, S_11 of the two residual sets, and solves the generalized
eigenproblem

    det(lambda S_11 - S_10 S_00^(-1) S_01) = 0.

The eigenvalues are the squared canonical correlations between the two
residual sets. The trace statistic for rank r is -T sum_(i>r) log(1 - lambda_i)
and the maximum eigenvalue statistic is -T log(1 - lambda_(r+1)).
"""

import math
import random

# Asymptotic quantiles (90%, 95%, 99%) from MacKinnon, Haug and Michelis (1999),
# as tabulated in statsmodels coint_tables.py. Row K - r = 1..5.
# "none": no deterministic terms. "c": unrestricted constant (linear trends in the data).
TRACE = {
    "none": [(2.9762, 4.1296, 6.9406), (10.4741, 12.3212, 16.3640), (21.7781, 24.2761, 29.5147),
             (37.0339, 40.1749, 46.5716), (56.2839, 60.0627, 67.6367)],
    "c": [(2.7055, 3.8415, 6.6349), (13.4294, 15.4943, 19.9349), (27.0669, 29.7961, 35.4628),
          (44.4929, 47.8545, 54.6815), (65.8202, 69.8189, 77.8202)],
}
MAX_EIG = {
    "none": [(2.9762, 4.1296, 6.9406), (9.4748, 11.2246, 15.0923), (15.7175, 17.7961, 22.2519),
             (21.8370, 24.1592, 29.0609), (27.9160, 30.4428, 35.7359)],
    "c": [(2.7055, 3.8415, 6.6349), (12.2971, 14.2639, 18.5200), (18.8928, 21.1314, 25.8650),
          (25.1236, 27.5858, 32.7172), (31.2379, 33.8777, 39.3693)],
}
_LEVEL_INDEX = {0.10: 0, 0.05: 1, 0.01: 2}


def critical_value(table, case, k_minus_r, level=0.05):
    """Asymptotic critical value for the trace ("trace") or max-eigenvalue ("max") statistic."""
    t = TRACE if table == "trace" else MAX_EIG
    return t[case][k_minus_r - 1][_LEVEL_INDEX[level]]


def _residualize(targets, regressors):
    """Residuals of each target column after least squares on the regressor columns.

    Uses modified Gram-Schmidt on the regressors, so the residual of each target
    is its projection onto the orthogonal complement of their span."""
    basis = []
    for col in regressors:
        v = [float(a) for a in col]
        norm0 = math.sqrt(sum(a * a for a in v))
        for q in basis:
            d = sum(a * b for a, b in zip(q, v))
            v = [a - d * b for a, b in zip(v, q)]
        nrm = math.sqrt(sum(a * a for a in v))
        if norm0 == 0.0 or nrm <= 1e-12 * norm0:
            raise ValueError("the short-run regressors are linearly dependent")
        basis.append([a / nrm for a in v])
    out = []
    for col in targets:
        v = [float(a) for a in col]
        for q in basis:
            d = sum(a * b for a, b in zip(q, v))
            v = [a - d * b for a, b in zip(v, q)]
        out.append(v)
    return out


def moments(a, b):
    """(1/T) sum_t a_t b_t^T for lists of columns a and b."""
    t = len(a[0])
    return [[sum(x * y for x, y in zip(ai, bj)) / t for bj in b] for ai in a]


def cholesky(s):
    """Lower triangular L with L L^T = s, for a symmetric positive definite s."""
    k = len(s)
    low = [[0.0] * k for _ in range(k)]
    for i in range(k):
        for j in range(i + 1):
            v = s[i][j] - sum(low[i][m] * low[j][m] for m in range(j))
            if i == j:
                if v <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(v)
            else:
                low[i][j] = v / low[j][j]
    return low


def lower_inverse(low):
    """Inverse of a lower triangular matrix by forward substitution."""
    k = len(low)
    inv = [[0.0] * k for _ in range(k)]
    for c in range(k):
        for i in range(c, k):
            rhs = (1.0 if i == c else 0.0) - sum(low[i][m] * inv[m][c] for m in range(c, i))
            inv[i][c] = rhs / low[i][i]
    return inv


def solve_spd(s, b):
    """s^(-1) b for symmetric positive definite s and a matrix b (list of rows)."""
    low = cholesky(s)
    li = lower_inverse(low)
    k = len(s)
    sinv = [[sum(li[m][i] * li[m][j] for m in range(k)) for j in range(k)] for i in range(k)]
    return [[sum(sinv[i][m] * b[m][j] for m in range(k)) for j in range(len(b[0]))] for i in range(k)]


def jacobi_eigen(a, tol=1e-14, max_sweeps=100):
    """Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.

    Returns (values, vectors) with values in decreasing order and vectors as
    columns of an orthogonal matrix (vectors[i][j] is entry i of vector j)."""
    k = len(a)
    a = [row[:] for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(k)] for i in range(k)]
    for _ in range(max_sweeps):
        off = sum(a[i][j] ** 2 for i in range(k) for j in range(k) if i != j)
        scale = sum(a[i][i] ** 2 for i in range(k)) or 1.0
        if off <= tol * tol * scale:
            break
        for p in range(k - 1):
            for q in range(p + 1, k):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for m in range(k):
                    amp, amq = a[m][p], a[m][q]
                    a[m][p], a[m][q] = c * amp - s * amq, s * amp + c * amq
                for m in range(k):
                    apm, aqm = a[p][m], a[q][m]
                    a[p][m], a[q][m] = c * apm - s * aqm, s * apm + c * aqm
                for m in range(k):
                    vmp, vmq = v[m][p], v[m][q]
                    v[m][p], v[m][q] = c * vmp - s * vmq, s * vmp + c * vmq
    order = sorted(range(k), key=lambda i: -a[i][i])
    return [a[i][i] for i in order], [[v[m][i] for i in order] for m in range(k)]


def johansen(data, case="none", lags=0, level=0.05):
    """Johansen rank tests for K series (data is a list of K series of equal length n).

    lags is the number of lagged differences (the VAR order minus 1). case is
    "none" (no deterministic terms) or "c" (unrestricted constant). Returns the
    eigenvalues, the trace and max-eigenvalue statistics for r = 0..K-1, their
    critical values, the rank chosen by the sequential trace test, the
    eigenvectors beta (columns, normalized by beta^T S_11 beta = I), alpha =
    S_01 beta and T."""
    if case not in TRACE:
        raise ValueError("case must be 'none' or 'c'")
    k = len(data)
    if not 1 <= k <= 5:
        raise ValueError("between 1 and 5 series are supported")
    n = len(data[0])
    rows = range(lags + 1, n)
    big_t = len(rows)
    if big_t <= k * (lags + 1) + 1:
        raise ValueError("series too short for this many lags")
    diff = [[0.0] + [s[t] - s[t - 1] for t in range(1, n)] for s in data]
    short = [[d[t - i] for t in rows] for i in range(1, lags + 1) for d in diff]
    if case == "c":
        short.append([1.0] * big_t)
    r0 = _residualize([[d[t] for t in rows] for d in diff], short)  # @line L1
    r1 = _residualize([[s[t - 1] for t in rows] for s in data], short)  # @line L2
    s00, s01, s11 = moments(r0, r0), moments(r0, r1), moments(r1, r1)  # @line L3
    s10 = [[s01[j][i] for j in range(k)] for i in range(k)]
    low = cholesky(s11)  # @line L4
    li = lower_inverse(low)
    m = [[sum(s10[i][a] * x for a, x in enumerate(col)) for col in zip(*solve_spd(s00, s01))]
         for i in range(k)]  # S_10 S_00^(-1) S_01
    c = [[sum(li[i][a] * m[a][b] * li[j][b] for a in range(k) for b in range(k)) for j in range(k)]
         for i in range(k)]
    c = [[(c[i][j] + c[j][i]) / 2.0 for j in range(k)] for i in range(k)]
    lam, vec = jacobi_eigen(c)  # @line L5
    lam = [min(max(x, 0.0), 1.0 - 1e-15) for x in lam]
    beta = [[sum(li[a][i] * vec[a][j] for a in range(k)) for j in range(k)] for i in range(k)]  # @line L6
    alpha = [[sum(s01[i][a] * beta[a][j] for a in range(k)) for j in range(k)] for i in range(k)]
    logs = [math.log(1.0 - x) for x in lam]
    trace = [-big_t * sum(logs[r:]) for r in range(k)]  # @line L7
    max_eig = [-big_t * logs[r] for r in range(k)]
    crit_trace = [critical_value("trace", case, k - r, level) for r in range(k)]
    crit_max = [critical_value("max", case, k - r, level) for r in range(k)]
    rank = next((r for r in range(k) if trace[r] < crit_trace[r]), k)  # @line L8
    return {"eigenvalues": lam, "trace": trace, "max_eig": max_eig, "crit_trace": crit_trace,  # @line L9
            "crit_max": crit_max, "rank": rank, "beta": beta, "alpha": alpha, "nobs": big_t,
            "s00": s00, "s01": s01, "s11": s11}


def simulate_trace(n, k, case="none", reps=500, rng=None):
    """Trace statistics for r = 0 from reps sets of k independent Gaussian random walks."""
    rng = rng or random.Random(0)
    out = []
    for _ in range(reps):
        data = []
        for _ in range(k):
            s, w = 0.0, []
            for _ in range(n):
                s += rng.gauss(0.0, 1.0)
                w.append(s)
            data.append(w)
        out.append(johansen(data, case, 0)["trace"][0])
    return out
johansen_test.py 10 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/johansen-test/. The authors are listed in prov/AA2XYN.jsonl.
"""Entry point named after the slug. The code lives in johansen_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from johansen_core import (MAX_EIG, TRACE, cholesky, critical_value, jacobi_eigen, johansen,
                           lower_inverse, moments, simulate_trace, solve_spd)

__all__ = ["MAX_EIG", "TRACE", "cholesky", "critical_value", "jacobi_eigen", "johansen",
           "lower_inverse", "moments", "simulate_trace", "solve_spd"]
test_johansen_test.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/johansen-test/. The authors are listed in prov/AA2XYN.jsonl.

import math
import random
from fractions import Fraction

import pytest

from johansen_test import cholesky, critical_value, jacobi_eigen, johansen, simulate_trace

Y1 = [1, 3, 2, 4, 3, 5, 4]
Y2 = [0, 2, 3, 3, 5, 4, 6]


def walk(rng, n, drift=0.0):
    s, out = 0.0, []
    for _ in range(n):
        s += drift + rng.gauss(0.0, 1.0)
        out.append(s)
    return out


def matmul(a, b):
    return [[sum(a[i][m] * b[m][j] for m in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]


def transpose(a):
    return [list(r) for r in zip(*a)]


def inv2(m):
    d = m[0][0] * m[1][1] - m[0][1] * m[1][0]
    return [[m[1][1] / d, -m[0][1] / d], [-m[1][0] / d, m[0][0] / d]]


def test_worked_example_exact() -> None:
    # K = 2, no lags, no deterministic terms, n = 7 (T = 6). T times the moment
    # matrices are integers, and the eigenvalues are the roots of
    # z^2 - (128672/110751) z + 19600/110751.
    r = johansen([Y1, Y2], "none", 0)
    r0 = [[Fraction(s[t] - s[t - 1]) for t in range(1, 7)] for s in (Y1, Y2)]
    r1 = [[Fraction(s[t - 1]) for t in range(1, 7)] for s in (Y1, Y2)]
    mom = lambda a, b: [[sum(x * y for x, y in zip(ai, bj)) for bj in b] for ai in a]
    s00, s01, s11 = mom(r0, r0), mom(r0, r1), mom(r1, r1)
    assert s00 == [[15, -3], [-3, 14]] and s01 == [[0, 7], [20, 11]] and s11 == [[64, 59], [59, 63]]
    for got, want in ((r["s00"], s00), (r["s01"], s01), (r["s11"], s11)):
        assert all(abs(got[i][j] - float(want[i][j]) / 6) < 1e-12 for i in range(2) for j in range(2))
    a = matmul(inv2(s11), matmul(transpose(s01), matmul(inv2(s00), s01)))
    tr, det = a[0][0] + a[1][1], a[0][0] * a[1][1] - a[0][1] * a[1][0]
    assert tr == Fraction(128672, 110751) and det == Fraction(19600, 110751)
    lam = r["eigenvalues"]
    assert abs(lam[0] + lam[1] - float(tr)) < 1e-12 and abs(lam[0] * lam[1] - float(det)) < 1e-12
    assert abs(lam[0] - 0.981505077) < 1e-9 and abs(lam[1] - 0.180308361) < 1e-9
    assert abs(r["trace"][0] - 25.1345164) < 1e-6 and abs(r["trace"][1] - 1.1929624) < 1e-6
    assert abs(r["max_eig"][0] - 23.9415540) < 1e-6
    assert r["rank"] == 1 and r["nobs"] == 6


def test_one_series_is_the_dickey_fuller_t_ratio() -> None:
    # K = 1, no lags, no constant: lambda = t^2 / (t^2 + T - 1), where t is the
    # Dickey-Fuller t ratio of dy_t = rho y_(t-1) + e_t. Exact in rationals.
    rng = random.Random(8)
    y = [0]
    for _ in range(29):
        y.append(y[-1] + rng.randint(-3, 3))
    big_t = 29
    num = sum(Fraction(y[t - 1]) * (y[t] - y[t - 1]) for t in range(1, 30))
    syy = sum(Fraction(y[t - 1]) ** 2 for t in range(1, 30))
    sdd = sum(Fraction(y[t] - y[t - 1]) ** 2 for t in range(1, 30))
    lam = num * num / (syy * sdd)
    rss = sdd - num * num / syy
    t2 = (num / syy) ** 2 * syy / (rss / (big_t - 1))
    assert lam == t2 / (t2 + big_t - 1)
    r = johansen([y], "none", 0)
    assert abs(r["eigenvalues"][0] - float(lam)) < 1e-12
    assert abs(r["trace"][0] + big_t * math.log(1 - float(lam))) < 1e-9


@pytest.mark.parametrize("lags,case", [(0, "none"), (1, "none"), (2, "c")])
def test_generalized_eigen_equation_and_normalization(lags, case) -> None:
    # S_10 S_00^(-1) S_01 beta_j = lambda_j S_11 beta_j and beta^T S_11 beta = I.
    rng = random.Random(lags + 10)
    data = [walk(rng, 60) for _ in range(3)]
    r = johansen(data, case, lags)
    s00, s01, s11 = r["s00"], r["s01"], r["s11"]
    k = 3
    s10 = transpose(s01)
    low = cholesky(s00)
    # s00^(-1) by solving with the Cholesky factor, column by column
    inv = [[0.0] * k for _ in range(k)]
    for c in range(k):
        z = [0.0] * k
        for i in range(k):
            z[i] = ((1.0 if i == c else 0.0) - sum(low[i][m] * z[m] for m in range(i))) / low[i][i]
        x = [0.0] * k
        for i in range(k - 1, -1, -1):
            x[i] = (z[i] - sum(low[m][i] * x[m] for m in range(i + 1, k))) / low[i][i]
        for i in range(k):
            inv[i][c] = x[i]
    m = matmul(s10, matmul(inv, s01))
    beta = r["beta"]
    btsb = matmul(transpose(beta), matmul(s11, beta))
    assert all(abs(btsb[i][j] - (1.0 if i == j else 0.0)) < 1e-9 for i in range(k) for j in range(k))
    for j in range(k):
        b = [beta[i][j] for i in range(k)]
        lhs = [sum(m[i][a] * b[a] for a in range(k)) for i in range(k)]
        rhs = [r["eigenvalues"][j] * sum(s11[i][a] * b[a] for a in range(k)) for i in range(k)]
        assert all(abs(p - q) < 1e-9 for p, q in zip(lhs, rhs))
    assert all(0.0 <= v < 1.0 for v in r["eigenvalues"])
    assert all(a >= b for a, b in zip(r["eigenvalues"], r["eigenvalues"][1:]))


def test_invariance_to_linear_maps() -> None:
    # Y -> A Y (A invertible) leaves the eigenvalues unchanged; with case "c" so does Y -> A Y + c.
    rng = random.Random(21)
    data = [walk(rng, 80) for _ in range(2)]
    a = [[2.0, -1.0], [0.5, 3.0]]
    mapped = [[a[i][0] * data[0][t] + a[i][1] * data[1][t] for t in range(80)] for i in range(2)]
    shifted = [[v + 7.0 * (i + 1) for v in mapped[i]] for i in range(2)]
    for lags in (0, 2):
        base = johansen(data, "none", lags)["eigenvalues"]
        assert all(abs(p - q) < 1e-9 for p, q in zip(base, johansen(mapped, "none", lags)["eigenvalues"]))
        base_c = johansen(data, "c", lags)["eigenvalues"]
        assert all(abs(p - q) < 1e-9 for p, q in zip(base_c, johansen(shifted, "c", lags)["eigenvalues"]))


def test_jacobi_against_known_spectrum() -> None:
    # A = Q diag(3, 1, -2) Q^T with a known orthogonal Q (a Householder reflector).
    v = [1.0, 2.0, 2.0]
    q = [[(1.0 if i == j else 0.0) - 2 * v[i] * v[j] / 9.0 for j in range(3)] for i in range(3)]
    d = [3.0, 1.0, -2.0]
    a = [[sum(q[i][m] * d[m] * q[j][m] for m in range(3)) for j in range(3)] for i in range(3)]
    vals, vecs = jacobi_eigen(a)
    assert all(abs(p - w) < 1e-12 for p, w in zip(vals, d))
    for j in range(3):
        col = [vecs[i][j] for i in range(3)]
        av = [sum(a[i][m] * col[m] for m in range(3)) for i in range(3)]
        assert all(abs(av[i] - vals[j] * col[i]) < 1e-12 for i in range(3))


def test_size_of_trace_test() -> None:
    # Two independent walks, n = 200, 600 samples: the rejection rate of r = 0 at
    # the 95% MHM point 12.3212 is within 4 binomial SE (0.036) of 0.05.
    reps = 600
    sims = simulate_trace(200, 2, "none", reps, random.Random(11))
    rate = sum(1 for s in sims if s > critical_value("trace", "none", 2)) / reps
    assert abs(rate - 0.05) < 4 * math.sqrt(0.05 * 0.95 / reps)


def test_finds_one_relation() -> None:
    # y = x1 - x2 + u with u an AR(1), so beta is proportional to (1, -1, 1).
    rng = random.Random(2026)
    x1, x2 = walk(rng, 200), walk(rng, 200)
    u, a = [], 0.0
    for _ in range(200):
        a = 0.5 * a + rng.gauss(0.0, 1.0)
        u.append(a)
    y = [p - q + e for p, q, e in zip(x1, x2, u)]
    r = johansen([y, x1, x2], "none", 0)
    assert r["rank"] == 1
    b = [r["beta"][i][0] / r["beta"][0][0] for i in range(3)]
    assert abs(b[1] + 1.0) < 0.05 and abs(b[2] - 1.0) < 0.05
    # The two tests can disagree: here the max-eigenvalue statistic for r = 1
    # (11.57) is just above its 95% point 11.2246, while the trace (11.64) is below 12.3212.
    assert r["trace"][1] < r["crit_trace"][1]
    assert r["max_eig"][0] > r["crit_max"][0] and r["max_eig"][1] > r["crit_max"][1]


def test_tables() -> None:
    for case in ("none", "c"):
        for table in ("trace", "max"):
            v = [critical_value(table, case, j) for j in range(1, 6)]
            assert all(x < y for x, y in zip(v, v[1:]))
    # With one common trend and an unrestricted constant the limit is chi-square(1).
    assert abs(critical_value("trace", "c", 1) - 1.959964 ** 2) < 1e-3
    # Trace and max-eigenvalue agree when K - r = 1.
    assert critical_value("trace", "none", 1) == critical_value("max", "none", 1)


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        johansen([Y1, Y2], "ct", 0)
    with pytest.raises(ValueError):
        johansen([Y1, Y2], "none", 3)
    with pytest.raises(ValueError):
        cholesky([[1.0, 2.0], [2.0, 1.0]])

History

Søren Johansen worked out the Gaussian likelihood analysis of cointegrated VARs in 1988, building on reduced rank regression (Anderson 1951) and canonical correlations (Hotelling 1936). Johansen and Katarina Juselius applied it to money demand in Denmark and Finland in 1990, and Johansen (1991) gave the full theory with deterministic terms. Osterwald-Lenum (1992) published the tables that most software used for years. MacKinnon, Haug and Michelis (1999) replaced them with response surfaces. Johansen's 1995 monograph collects the theory.

References

  1. Søren Johansen, Statistical analysis of cointegration vectors, Journal of Economic Dynamics and Control 12(2-3) (1988), pages 231 to 254, the reduced rank regression, the eigenvalue problem, and the limit law of the likelihood ratio statistic for the rank
  2. Søren Johansen, Estimation and hypothesis testing of cointegration vectors in Gaussian vector autoregressive models, Econometrica 59(6) (1991), pages 1551 to 1580, the models with a constant and the trace and maximum eigenvalue statistics
  3. Michael Osterwald-Lenum, A note with quantiles of the asymptotic distribution of the maximum likelihood cointegration rank test statistics, Oxford Bulletin of Economics and Statistics 54(3) (1992), pages 461 to 472, the simulated quantiles for the five cases of deterministic terms
  4. James G. MacKinnon, Alfred A. Haug and Leo Michelis, Numerical distribution functions of likelihood ratio tests for cointegration, Journal of Applied Econometrics 14(5) (1999), pages 563 to 577, the response surfaces for the quantiles and p-values of the trace and maximum eigenvalue statistics
  5. James D. Hamilton, Time Series Analysis, Princeton University Press, 1994, Chapter 20 (full-information maximum likelihood analysis of cointegrated systems)
  6. Helmut Lütkepohl, New Introduction to Multiple Time Series Analysis, Springer, 2005, the chapters on vector error correction models, their estimation by reduced rank regression, and tests of the cointegration rank

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