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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Søren Johansen, 1988
The Johansen test finds how many independent stationary linear combinations, or cointegrating relations, a set of integrated series has. It writes a vector autoregression in error correction form, where the matrix that multiplies the lagged levels has rank equal to the number of relations. The maximum likelihood estimate of a rank 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 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 follow a Gaussian VAR(), written in vector error correction form,
with (case "none") or free (case "c", an unrestricted constant, which gives linear trends in the levels). If is I(1) with exactly cointegrating relations, then and with of size . The columns of span the cointegrating vectors, and holds the speeds of adjustment. The hypotheses are nested: : , for . is the unrestricted VAR, and is a VAR in differences.
Statistic. With the eigenvalues of the problem in line L5 and the number of rows,
The trace statistic is the likelihood ratio statistic for against , and the maximum eigenvalue statistic tests against . Both facts are proved on the correctness page.
Null distribution. Asymptotic and nonstandard. Under with exactly relations, converges to the trace of a matrix functional of a -dimensional Brownian motion,
where in case "none" and is a demeaned or trend-adjusted in the other cases (Johansen 1988, 1991). The limit does not depend on , , or . 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 when the statistic exceeds the quantile for and the case. The 95% points (MacKinnon, Haug and Michelis 1999):
| 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 in case "c", the limit is , with 95% point , because the stochastic trend then has a drift that dominates. The rank is chosen by the sequential rule: test in turn and stop at the first that is not rejected. Each test has asymptotic size . For the true rank , the procedure picks with a probability that goes to 0, and with probability tending to .
p-value. MacKinnon, Haug and Michelis (1999) give response surface p-values. A Monte Carlo p-value from independent random walks is valid asymptotically for .
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 ) gives a small and is hard to find. The finite-sample size is above nominal when or is large relative to . Bartlett corrections or the bootstrap help there.
The algorithm
JOHANSEN(Y₁..Y_n ∈ ℝ^K, p, case, α)- 1
R0_t ← residual of ∇Y_t after OLS on ∇Y_{t−1}, …, ∇Y_{t−p+1} (and 1 in case "c") - 2
R1_t ← residual of Y_{t−1} after OLS on the same regressors - 3
S_ij ← (1/T) Σ_t R_i,t R_j,tᵀ for i, j ∈ {0, 1} - 4
L ← Cholesky factor of S11 (S11 = L Lᵀ) - 5
(λ_i, v_i) ← eigenpairs of C = L⁻¹ S10 S00⁻¹ S01 L⁻ᵀ, λ₁ ≥ … ≥ λ_K - 6
β ← L⁻ᵀ [v₁ … v_K]; α ← S01 β - 7
trace(r) ← −T Σ_{i>r} log(1 − λ_i); max(r) ← −T log(1 − λ_{r+1}) - 8
r̂ ← the first r with trace(r) < c_α(K − r, case), or K if none - 9
return (λ, trace, max, r̂, β[:, 1..r̂], α[:, 1..r̂])
Lines L4 to L6 turn the generalized problem into a symmetric eigenvalue problem, which a Jacobi or QR eigensolver handles stably. The vectors satisfy . The estimate of under is with the first columns. Since only the span of is identified, practice normalizes one entry of each vector to 1 for reporting.
Example
By hand. Take , , (no lagged differences), case "none", with and . Then , , , and the moment matrices are integers over 6:
| step | value |
|---|---|
| L3: | |
| L3: (rows: , columns: ) | |
| L3: | |
| L5: trace and determinant of | and |
| L5: , | 0.98151, 0.18031 |
| L6: , scaled so its first entry is 1 | |
| 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 , keep , so |
The denominator is . The factor cancels in the eigenvalues, so they are exact algebraic numbers, the roots of . With six rows the asymptotic quantiles are not reliable; the example only shows the steps.
Three series with one relation. With seed 2026, let and be independent Gaussian random walks of length 200, , and . With , and case "none" ():
| trace() | 95% point | max() | 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 , and the first vector, scaled, is , close to the true . The maximum eigenvalue test of against rejects narrowly (11.57 against 11.22), so the two rules disagree here. The Engle-Granger regression of on and gives slopes and and , 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 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 the best and are those of a regression of on , and . By the Poincaré separation theorem this ratio is minimized by the first generalized eigenvectors, with minimum . The trace and maximum eigenvalue statistics follow as differences of . The page also proves that the Cholesky reduction of lines L4 to L6 solves the generalized problem with , that , that the eigenvalues are unchanged when is replaced by (and in case "c") for invertible , and that for , with 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 (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 (Lemma 6), that the eigenvalues are invariant to invertible linear maps of the data (Lemma 7), and that for 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, and 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 collect the lagged differences and, in case "c", the constant. For fixed and , the Gaussian log likelihood of is maximized over by the least squares fit, and the concentrated log likelihood is
with and the residuals of lines L1 and L2.
Proof. Stack the rows: , where is . The quadratic form is minimized over by the least squares fit of on , for any positive definite , 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 , where is the projection onto the orthogonal complement of the columns of , and . These are exactly the residuals of lines L1 and L2.
Lemma 2 (fixed ). Under with fixed of full rank , the maximum over and is attained at and , and
The concentrated log likelihood is .
Proof. With fixed, is a multivariate regression on the regressors , common to all equations. By the same fact as in Lemma 1, least squares gives , and the residual covariance is the Gaussian maximum likelihood estimate of , which is . At that the quadratic term equals . For the determinant, consider the block matrix
Its determinant equals by the Schur complement of the lower right block, and also by the Schur complement of the upper left block. Equate the two forms and divide.
Theorem 3 (reduced rank regression). Let solve , with . Over all matrices of rank ,
attained by the first columns of from line L6. Hence is the maximum likelihood estimate of under .
Proof. Write and , which is symmetric with eigenvalues (Lemma 5). Put . Then the ratio in Lemma 2 is . Replacing by for invertible multiplies the numerator and the denominator by , so we may take with orthonormal columns, . The matrix is symmetric with eigenvalues , where , all positive. By the Poincaré separation theorem, a consequence of the Courant-Fischer minimax principle, the eigenvalues of satisfy for . So . Equality holds when the columns of are the eigenvectors of for the largest , since then . That corresponds to , which is line L6.
Corollary 4 (the statistics are likelihood ratios). The maximized log likelihood under is plus a constant that does not depend on . Therefore of the likelihood ratio of against is , and of against is .
Proof. Theorem 3 with Lemma 2 gives the maximized value for each , including , where ranges over all invertible matrices and the model is the unrestricted VAR. Take differences.
Lemma 5 (lines L4 to L6). If with and , then . For an orthonormal eigenbasis of , satisfies .
Proof. . Also . is symmetric because and is symmetric, so an orthonormal eigenbasis exists.
The implementation symmetrizes before the Jacobi method, which removes rounding asymmetry and does not change 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 ). is positive semidefinite, and is positive semidefinite.
Proof. is a Gram matrix. For , note that is the Schur complement of in the moment matrix , which is positive semidefinite; the Schur complement of a positive definite block in a positive semidefinite matrix is positive semidefinite. So . These are the squared canonical correlations between and .
Lemma 7 (invariance). Let be an invertible matrix. Replacing by in case "none", or by in case "c", leaves every unchanged, and becomes up to the choice of eigenbasis.
Proof. The lagged differences become , which span the same column space, and in case "c" the constant disappears in the differences and is absorbed by the constant regressor in the levels. So and , and . Then , which has the same roots. The eigenvector equation is solved by .
Lemma 8 (one series). For , and case "none", , where is the t ratio of in .
Proof. Let and . Then . The residual sum of squares is , so . Then .
So the trace statistic for is , 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 problem needs at most a few sweeps.
Complexity
On a real RAM, lines L1 and L2 regress columns on regressors ( in case "c"). A QR factorization of the regressors costs and the projections . Line L3 costs . Lines L4 to L6 cost for the Cholesky factor and the products, and per Jacobi sweep, with a number of sweeps that is small in practice. With , the total is time and space for the regressors.
Numerical stability. Do not form 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 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 infinite; it signals an exact fit, usually too many lags for the sample.
Properties
- Maximum likelihood. Under Gaussian errors, spans the maximum likelihood estimate of the cointegrating space, and it is superconsistent, with a mixed normal limit that gives tests of linear restrictions on .
- Symmetric in the variables. No series has to be chosen as the dependent variable. The eigenvalues are invariant to invertible linear maps of .
- 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 with 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 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 () and a restricted linear trend avoid quadratic trends in the levels. They use augmented by 1 or 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 gives finite-sample critical values.
- Tests on and . Linear restrictions on the cointegrating space or on the adjustment speeds are likelihood ratio tests with 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 .
- Small samples. The asymptotic quantiles are too small when is small relative to , 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 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.
# 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
- 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
- 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
- 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
- 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
- James D. Hamilton, Time Series Analysis, Princeton University Press, 1994, Chapter 20 (full-information maximum likelihood analysis of cointegrated systems)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AA2XYN Edit this page History Report an error Markdown