Algorithm Search⌘K

Algorithmcore

Augmented Dickey-Fuller test

Also called ADF test, Dickey-Fuller test, unit root test.

Tests the null of a unit root by the t-statistic of the lagged level in a regression of differences, with lagged differences added. Its null law is nonstandard.

Time
Θ(n k^2) worst · best
Space
Θ(n k) extra
Where
k = the number of regressors (the lagged level plus deterministic terms plus lagged differences); n = the length of the series
Properties
deterministicnot exactofflineiterative
Origin
David A. Dickey, Wayne A. Fuller, 1979

The augmented Dickey-Fuller (ADF) test decides whether a time series has a unit root, that is, whether it behaves like a random walk that never returns to a fixed mean. It regresses the first difference ∇Xt\nabla X_t on the lagged level Xt−1X_{t-1}, on deterministic terms (none, a constant, or a constant and a linear trend) and on pp lagged differences, and uses the ordinary t ratio τ\tau of the coefficient of Xt−1X_{t-1}. The null hypothesis is a unit root. The alternative is a stationary (or trend-stationary) autoregression. Under the null, τ\tau does not have a t or normal law: its limit is a functional of Brownian motion, with 5% points of about −1.94-1.94, −2.86-2.86 and −3.41-3.41 for the three choices of deterministic terms. The lagged differences absorb short-run correlation so that the same table applies to any stationary ARMA dynamics in the differences.

In plain words

Some series wander. A stock price or the level of a lake can drift away and never feel a pull back to an average. Other series move around a fixed level and always come back. The test asks which kind you have. It looks at how today's change depends on yesterday's level. If high levels are followed by falls and low levels by rises, there is a pull back to a center, and the series is stable. If the level tells you nothing about the next change, the series wanders. The difficulty is that a wandering series fools the usual tables: the pull back looks stronger than it is. So the test uses its own table of cut-off values, built by simulating wandering series. A few past changes are added to the fit so that short-term patterns do not confuse the answer.

The problem

Model and hypotheses. The observed series is Xt=dt+UtX_t = d_t + U_t, t=1,…,nt = 1, \dots, n, where dtd_t is a deterministic term (zero, a constant aa, or a line a+bta + bt) and UtU_t is an autoregression ϕ(B)Ut=εt\phi(B)U_t = \varepsilon_t of order p+1p + 1, with ϕ(z)=1−ϕ1z−⋯−ϕp+1zp+1\phi(z) = 1 - \phi_1 z - \dots - \phi_{p+1}z^{p+1}, BB the backshift operator and εt∼WN(0,σ2)\varepsilon_t \sim \mathrm{WN}(0, \sigma^2) as on the ARMA model page. Any such autoregression can be rewritten exactly as

∇Ut=ρUt−1+∑i=1pγi∇Ut−i+εt,ρ=−ϕ(1),γi=−∑j=i+1p+1ϕj.\nabla U_t = \rho U_{t-1} + \sum_{i=1}^{p}\gamma_i \nabla U_{t-i} + \varepsilon_t, \qquad \rho = -\phi(1), \qquad \gamma_i = -\sum_{j=i+1}^{p+1}\phi_j.

The null hypothesis is H0:ρ=0H_0: \rho = 0, which holds exactly when z=1z = 1 is a root of ϕ\phi. Then XtX_t is integrated of order one, an ARIMA process with d=1d = 1. The alternative is H1:ρ<0H_1: \rho < 0, which holds whenever all roots of ϕ\phi lie outside the unit circle, so that UtU_t is a stationary process and XtX_t is stationary around dtd_t. The test is one-sided: explosive roots (ρ>0\rho > 0) are not part of the alternative.

Statistic. Fit by ordinary least squares, over t=p+2,…,nt = p + 2, \dots, n (so T=n−p−1T = n - p - 1 rows),

∇Xt=ρXt−1+δ⊤dt∗+∑i=1pγi∇Xt−i+et,\nabla X_t = \rho X_{t-1} + \delta^\top d^*_t + \sum_{i=1}^{p}\gamma_i \nabla X_{t-i} + e_t,

where dt∗d^*_t is empty (case "n"), 11 (case "c") or (1,t)(1, t) (case "ct"). The statistic is the t ratio τ=ρ^/se⁡(ρ^)\tau = \hat\rho/\operatorname{se}(\hat\rho), with se⁡(ρ^)=s[(Z⊤Z)−1]11\operatorname{se}(\hat\rho) = s\sqrt{[(Z^\top Z)^{-1}]_{11}}, ZZ the T×kT \times k regressor matrix and s2=∑et2/(T−k)s^2 = \sum e_t^2/(T - k). The deterministic terms in the regression must contain those in the model: case "c" covers dt=ad_t = a, and case "ct" covers dt=a+btd_t = a + bt and also a random walk with drift.

Null distribution. Asymptotic and nonstandard. In case "n" with p=0p = 0 and iid errors, Dickey and Fuller (1979) showed

Tρ^⇒W(1)2−12∫01W(r)2 dr,τ⇒W(1)2−12(∫01W(r)2 dr)1/2,T\hat\rho \Rightarrow \frac{W(1)^2 - 1}{2\int_0^1 W(r)^2\,dr}, \qquad \tau \Rightarrow \frac{W(1)^2 - 1}{2\left(\int_0^1 W(r)^2\,dr\right)^{1/2}},

where WW is a standard Brownian motion. In cases "c" and "ct", WW is replaced by its residual after projection on 11 or on (1,r)(1, r). Said and Dickey (1984) showed that the same limits hold for ARMA errors when p→∞p \to \infty with p3/T→0p^3/T \to 0. These limits are cited, not proved here. In finite samples the law of τ\tau is exact by simulation in one case: with Gaussian errors and p=0p = 0, τ\tau in cases "c" and "ct" does not depend on the start value, the scale or (in case "ct") the drift, so a simulation from a standard Gaussian random walk gives the exact null law at every nn, up to Monte Carlo error. This is proved below.

Rejection rule and size. Reject H0H_0 at level α\alpha when τ<cα(T)\tau < c_\alpha(T), with the response surface of MacKinnon (2010), cα(T)=β0+β1/T+β2/T2+β3/T3c_\alpha(T) = \beta_0 + \beta_1/T + \beta_2/T^2 + \beta_3/T^3. Some values:

case T=25T = 25, 1% / 5% / 10% T=100T = 100 T=∞T = \infty
"n" −2.661-2.661 / −1.955-1.955 / −1.609-1.609 −2.588-2.588 / −1.944-1.944 / −1.614-1.614 −2.566-2.566 / −1.941-1.941 / −1.617-1.617
"c" −3.724-3.724 / −2.986-2.986 / −2.633-2.633 −3.498-3.498 / −2.891-2.891 / −2.582-2.582 −3.430-3.430 / −2.862-2.862 / −2.567-2.567
"ct" −4.375-4.375 / −3.603-3.603 / −3.238-3.238 −4.052-4.052 / −3.455-3.455 / −3.153-3.153 −3.959-3.959 / −3.410-3.410 / −3.127-3.127

The standard normal 5% point is −1.645-1.645, far to the right of these. The size is asymptotically α\alpha. In finite samples it depends on how well the pp lags capture the short-run dynamics.

p-value. p=P(τ∞≤τ)p = P(\tau_\infty \le \tau) for the limiting law. MacKinnon (1996) gives response surface approximations. The implementation gives a Monte Carlo p-value (1+#{τ(r)≤τ})/(1+R)(1 + \#\{\tau^{(r)} \le \tau\})/(1 + R) from RR simulated Gaussian random walks of the same length, which is exact for Gaussian errors with p=0p = 0 in cases "c" and "ct".

Sensitivity and power. The test detects a pull toward the mean, ρ<0\rho < 0. Under a fixed stationary alternative Tρ^→−∞T\hat\rho \to -\infty and the power tends to 1. Near the unit root the power is low: for an AR(1) with ϕ1=0.9\phi_1 = 0.9 and n=100n = 100, case "c" without lags rejects at 5% in about a third of samples. Large negative moving-average terms in ∇Xt\nabla X_t inflate the size, because the series then looks stationary over short spans.

The algorithm

  1. ADF(X₁..Xₙ, case, p) ▷ case ∈ {n, c, ct}, p lagged differences
  2. 1for t ← 2 to n: D_t ← X_t − X_{t−1}
  3. 2T ← n − p − 1
  4. 3for t ← p + 2 to n: ▷ one row per usable time point
  5. 4z_t ← (X_{t−1}, d*_t, D_{t−1}, …, D_{t−p}); response D_t
  6. 5Z = QR, with Q of size T×k and R upper triangular ▷ Gram-Schmidt or Householder
  7. 6β̂ ← R⁻¹ Qᵀ D; e ← D − Z β̂; s² ← eᵀe / (T − k)
  8. 7se ← s · ‖row 1 of R⁻¹‖ ▷ [(ZᵀZ)⁻¹]₁₁ = Σ_c (R⁻¹)₁c²
  9. 8τ ← β̂₁ / se
  10. 9c ← β₀ + β₁/T + β₂/T² + β₃/T³ ▷ MacKinnon (2010), for case and α
  11. 10return (τ, c, reject ⇔ τ < c)

The number of lags pp is chosen before line L1. The usual rule fits every pp from 0 to pmax⁡p_{\max} on the same rows t=pmax⁡+2,…,nt = p_{\max} + 2, \dots, n, picks the pp that minimizes the AIC or BIC, Tlog⁡(RSS/T)+penalty×kT\log(\mathrm{RSS}/T) + \text{penalty} \times k, and then refits with that pp on all usable rows. A common choice is Schwert's pmax⁡=⌊12(n/100)1/4⌋p_{\max} = \lfloor 12(n/100)^{1/4}\rfloor, which is 12 at n=100n = 100 and 14 at n=200n = 200. Another is to start at pmax⁡p_{\max} and drop the last lag while its t ratio is below 1.645 in absolute value.

Example

By hand. Take X=(3,5,4,6,8,7,9,8)X = (3, 5, 4, 6, 8, 7, 9, 8), case "c" and p=0p = 0. Then T=7T = 7 and the regression is of ∇Xt\nabla X_t on a constant and Xt−1X_{t-1}:

step value
L1: ∇Xt\nabla X_t, t=2..8t = 2..8 2,−1,2,2,−1,2,−12, -1, 2, 2, -1, 2, -1 (mean 5/75/7)
L4: Xt−1X_{t-1} 3,5,4,6,8,7,93, 5, 4, 6, 8, 7, 9 (mean 6)
Sxx=∑(Xt−1−6)2S_{xx} = \sum (X_{t-1} - 6)^2 28
Sxd=∑(Xt−1−6)(∇Xt−5/7)S_{xd} = \sum (X_{t-1} - 6)(\nabla X_t - 5/7) −12-12
L6: ρ^=Sxd/Sxx\hat\rho = S_{xd}/S_{xx}, constant 5/7−6ρ^5/7 - 6\hat\rho −3/7=−0.4286-3/7 = -0.4286, 23/723/7
L6: residual sum of squares, s2=RSS/5s^2 = \mathrm{RSS}/5 72/772/7, 72/35=2.057172/35 = 2.0571
L7: se⁡=s2/Sxx\operatorname{se} = \sqrt{s^2/S_{xx}} 0.27105
L8: τ\tau −5/2=−1.5811-\sqrt{5/2} = -1.5811
L9: c0.05(7)c_{0.05}(7) −3.4776-3.4776

Since −1.58>−3.48-1.58 > -3.48, the test does not reject the unit root. A one-sided t table with 5 degrees of freedom would put the cut-off at −2.015-2.015, which is far less strict. The Monte Carlo p-value from 9999 Gaussian random walks of length 8 is about 0.44.

A random walk against a stationary series. From the same 200 standard normal shocks (seed 2026), build a random walk Xt=Xt−1+εtX_t = X_{t-1} + \varepsilon_t and an AR(1) series Xt=0.5Xt−1+εtX_t = 0.5X_{t-1} + \varepsilon_t. With case "c", AIC lag selection and pmax⁡=14p_{\max} = 14:

series chosen pp TT τ\tau c0.05(T)c_{0.05}(T) decision
random walk 0 199 −1.99-1.99 −2.876-2.876 keep H0H_0
AR(1), ϕ1=0.5\phi_1 = 0.5 2 197 −7.80-7.80 −2.876-2.876 reject

Power and size. With n=100n = 100, case "c", p=0p = 0 and 1000 samples each, the rejection rate at 5% is 1.000 for ϕ1=0.5\phi_1 = 0.5, 0.868 for ϕ1=0.8\phi_1 = 0.8, 0.336 for ϕ1=0.9\phi_1 = 0.9, 0.128 for ϕ1=0.95\phi_1 = 0.95 and 0.055 under the null ϕ1=1\phi_1 = 1. These rates are measured, not derived.

Correctness

Three facts are proved in the correctness proof. First, the ADF regression is an exact rewriting of an AR(p+1p + 1) model, with ρ=−ϕ(1)\rho = -\phi(1), so ρ=0\rho = 0 is the same as a unit root, and ρ<0\rho < 0 holds for every causal stationary autoregression, because ϕ(0)=1\phi(0) = 1 and ϕ\phi has no zero on [0,1][0, 1]. Under the null, ϕ(z)=(1−z)(1−∑γizi)\phi(z) = (1 - z)(1 - \sum\gamma_i z^i), so the lagged differences are exactly the autoregression of ∇Xt\nabla X_t. Second, lines L5 to L8 compute the ordinary least squares t ratio, because Z=QRZ = QR gives β^=R−1Q⊤D\hat\beta = R^{-1}Q^\top D and (Z⊤Z)−1=R−1R−⊤(Z^\top Z)^{-1} = R^{-1}R^{-\top}. Third, τ\tau does not change when XtX_t is replaced by a+cXta + c X_t with c≠0c \ne 0 in case "c", or by a+bt+cXta + bt + cX_t in case "ct", because the regressor span and the t ratio are unchanged. Under the null with Gaussian errors and p=0p = 0 this makes the simulated law exact, and the Monte Carlo p-value has P(p≤α)≤αP(p \le \alpha) \le \alpha for every nn. The Dickey-Fuller limit law and the Said-Dickey extension are cited, not proved.

Proof: The ADF regression is an exact rewriting of an autoregression, the routine returns its least squares t ratio, the ratio is invariant to level, scale and trend, and the simulated p-value is validfull

We prove four things about ADF. The regression is an exact reparametrization of an AR(p+1p + 1) model in which the null ρ=0\rho = 0 is a unit root and every causal stationary model has ρ<0\rho < 0 (Lemmas 1 and 2). Lines L5 to L8 return the ordinary least squares t ratio (Lemma 3). The ratio is invariant to the transformations of Lemma 4. Under the null with Gaussian errors and p=0p = 0, this makes the Monte Carlo p-value valid at every sample size (Theorem 5). We do not prove the Dickey-Fuller limit laws or their extension by Said and Dickey to ARMA errors. We cite them from Dickey and Fuller (1979), Phillips (1987) and Said and Dickey (1984), and Hamilton (1994), Chapter 17, gives a full derivation.

Notation: ϕ(z)=1−∑j=1p+1ϕjzj\phi(z) = 1 - \sum_{j=1}^{p+1}\phi_j z^j, BB is the backshift operator, ∇=1−B\nabla = 1 - B.

Lemma 1 (the ADF form). For any real ϕ1,…,ϕp+1\phi_1, \dots, \phi_{p+1}, set ρ=−ϕ(1)\rho = -\phi(1) and γi=−∑j=i+1p+1ϕj\gamma_i = -\sum_{j=i+1}^{p+1}\phi_j for i=1,…,pi = 1, \dots, p. Then, as polynomials,

ϕ(z)=(1−z)−ρz−∑i=1pγi(zi−zi+1).(1)\phi(z) = (1 - z) - \rho z - \sum_{i=1}^{p}\gamma_i (z^i - z^{i+1}). \qquad (1)

Hence ϕ(B)Ut=εt\phi(B)U_t = \varepsilon_t holds exactly when ∇Ut=ρUt−1+∑i=1pγi∇Ut−i+εt\nabla U_t = \rho U_{t-1} + \sum_{i=1}^{p}\gamma_i\nabla U_{t-i} + \varepsilon_t. The map from (ϕ1,…,ϕp+1)(\phi_1, \dots, \phi_{p+1}) to (ρ,γ1,…,γp)(\rho, \gamma_1, \dots, \gamma_p) is one-to-one.

Proof. Compare coefficients of the right side of (1). The constant term is 1. Since −ρ=ϕ(1)=1−∑j≥1ϕj-\rho = \phi(1) = 1 - \sum_{j \ge 1}\phi_j, the coefficient of zz is −1−ρ−γ1=−1+(1−∑j≥1ϕj)+∑j≥2ϕj=−ϕ1-1 - \rho - \gamma_1 = -1 + (1 - \sum_{j \ge 1}\phi_j) + \sum_{j \ge 2}\phi_j = -\phi_1. For 2≤j≤p2 \le j \le p the coefficient of zjz^j is γj−1−γj=−∑l≥jϕl+∑l≥j+1ϕl=−ϕj\gamma_{j-1} - \gamma_j = -\sum_{l \ge j}\phi_l + \sum_{l \ge j+1}\phi_l = -\phi_j. The coefficient of zp+1z^{p+1} is γp=−ϕp+1\gamma_p = -\phi_{p+1}. So both sides of (1) agree. Applying (1) with zz replaced by BB to UtU_t gives ϕ(B)Ut=∇Ut−ρUt−1−∑iγi∇Ut−i\phi(B)U_t = \nabla U_t - \rho U_{t-1} - \sum_i \gamma_i \nabla U_{t-i}, which is the second claim. The inverse map is ϕp+1=−γp\phi_{p+1} = -\gamma_p, ϕj=γj−γj−1\phi_j = \gamma_j - \gamma_{j-1} for 2≤j≤p2 \le j \le p, and ϕ1=1+ρ+γ1\phi_1 = 1 + \rho + \gamma_1, so the map is one-to-one. □\square

When Xt=dt+UtX_t = d_t + U_t with dtd_t a constant or a line, ∇Xt=∇dt+∇Ut\nabla X_t = \nabla d_t + \nabla U_t and Xt−1=dt−1+Ut−1X_{t-1} = d_{t-1} + U_{t-1}. Substituting, the deterministic parts combine into a constant (when dt=ad_t = a) or a constant plus a multiple of tt (when dt=a+btd_t = a + bt). So the regression with dt∗=1d^*_t = 1 or dt∗=(1,t)d^*_t = (1, t) contains the true model.

Lemma 2 (the hypotheses). (a) ρ=0\rho = 0 if and only if ϕ(1)=0\phi(1) = 0, that is, z=1z = 1 is a root of ϕ\phi. In that case ϕ(z)=(1−z)(1−∑i=1pγizi)\phi(z) = (1 - z)(1 - \sum_{i=1}^p \gamma_i z^i). (b) If every root of ϕ\phi has modulus greater than 1, then ρ<0\rho < 0.

Proof. (a) The first claim is ρ=−ϕ(1)\rho = -\phi(1). With ρ=0\rho = 0, (1) reads ϕ(z)=(1−z)−∑iγizi(1−z)=(1−z)(1−∑iγizi)\phi(z) = (1 - z) - \sum_i\gamma_i z^i(1 - z) = (1 - z)(1 - \sum_i\gamma_i z^i). (b) ϕ\phi is a real polynomial with ϕ(0)=1>0\phi(0) = 1 > 0. It has no zero in [0,1][0, 1], since such a zero would be a root of modulus at most 1. By continuity ϕ\phi keeps its sign on [0,1][0, 1], so ϕ(1)>0\phi(1) > 0 and ρ=−ϕ(1)<0\rho = -\phi(1) < 0. □\square

Part (a) says that under the null, ∇Ut\nabla U_t is the autoregression (1−∑γiBi)∇Ut=εt(1 - \sum\gamma_i B^i)\nabla U_t = \varepsilon_t, so the lagged differences remove exactly the serial correlation in ∇Xt\nabla X_t. The converse of (b) is false: ρ<0\rho < 0 also holds for some models with complex roots inside the unit circle. The test's alternative is the set of causal stationary models.

Lemma 3 (lines L5 to L8). Let ZZ be the T×kT \times k matrix with rows ztz_t, of full column rank, and let Z=QRZ = QR with Q⊤Q=IkQ^\top Q = I_k and RR upper triangular with positive diagonal. Then β^=R−1Q⊤D\hat\beta = R^{-1}Q^\top D is the least squares solution, e=D−Zβ^e = D - Z\hat\beta is its residual, and s ∥(R−1)1,⋅∥=s[(Z⊤Z)−1]11s\,\|(R^{-1})_{1,\cdot}\| = s\sqrt{[(Z^\top Z)^{-1}]_{11}}. So line L8 returns the ordinary t ratio of the first coefficient.

Proof. Z⊤Z=R⊤Q⊤QR=R⊤RZ^\top Z = R^\top Q^\top Q R = R^\top R, which is invertible since RR has a positive diagonal. The normal equations Z⊤Zβ=Z⊤DZ^\top Z\beta = Z^\top D read R⊤Rβ=R⊤Q⊤DR^\top R\beta = R^\top Q^\top D; cancel the invertible R⊤R^\top to get Rβ=Q⊤DR\beta = Q^\top D, whose unique solution is β^\hat\beta. Next, (Z⊤Z)−1=R−1R−⊤(Z^\top Z)^{-1} = R^{-1}R^{-\top}, whose (1,1)(1,1) entry is ∑c(R−1)1c2\sum_c (R^{-1})_{1c}^2. □\square

Modified Gram-Schmidt, used in the implementation, produces the same QQ and RR as classical Gram-Schmidt in exact arithmetic, with better orthogonality in floating point. The implementation stops with an error if a column is (numerically) a combination of the earlier ones, which is the full rank condition.

Lemma 4 (invariance). Let Yt=a+bt+cXtY_t = a + bt + cX_t with c≠0c \ne 0. In case "ct", τ(Y)=τ(X)\tau(Y) = \tau(X) for all a,ba, b. In case "c", τ(Y)=τ(X)\tau(Y) = \tau(X) when b=0b = 0. In case "n", τ(Y)=τ(X)\tau(Y) = \tau(X) when a=b=0a = b = 0.

Proof. Take case "ct". The response is ∇Yt=b+c∇Xt\nabla Y_t = b + c\nabla X_t, and the regressors are 11, tt, Yt−1=(a−b)+bt+cXt−1Y_{t-1} = (a - b) + bt + cX_{t-1} and ∇Yt−i=b+c∇Xt−i\nabla Y_{t-i} = b + c\nabla X_{t-i}. Let MM be the projection that removes the span of 11, tt and the lagged differences. That span equals the span of 11, tt and the ∇Xt−i\nabla X_{t-i}, because each ∇Yt−i\nabla Y_{t-i} differs from c∇Xt−ic\nabla X_{t-i} by a constant. By the Frisch-Waugh-Lovell theorem, ρ^=(MY−1)⊤(M∇Y)/∥MY−1∥2\hat\rho = (MY_{-1})^\top(M\nabla Y)/\|MY_{-1}\|^2, where Y−1Y_{-1} is the column of Yt−1Y_{t-1}. Now MY−1=cMX−1MY_{-1} = cMX_{-1} and M∇Y=cM∇XM\nabla Y = cM\nabla X, since MM kills the constants and the trend. So ρ^(Y)=c2(⋅)/c2(⋅)=ρ^(X)\hat\rho(Y) = c^2(\cdot)/c^2(\cdot) = \hat\rho(X). The full residual vector is M∇Y−ρ^MY−1=c(M∇X−ρ^MX−1)M\nabla Y - \hat\rho MY_{-1} = c(M\nabla X - \hat\rho MX_{-1}), so s(Y)=∣c∣s(X)s(Y) = |c|s(X). The variance factor is [(Z⊤Z)−1]11=1/∥MY−1∥2=1/(c2∥MX−1∥2)[(Z^\top Z)^{-1}]_{11} = 1/\|MY_{-1}\|^2 = 1/(c^2\|MX_{-1}\|^2). Hence se⁡(Y)=∣c∣s(X)/(∣c∣∥MX−1∥)=se⁡(X)\operatorname{se}(Y) = |c|s(X)/(|c|\|MX_{-1}\|) = \operatorname{se}(X) and τ(Y)=τ(X)\tau(Y) = \tau(X). In case "c", with b=0b = 0, the same argument works with MM removing 11 and the lagged differences. In case "n", with a=b=0a = b = 0, all columns and the response are multiplied by cc. □\square

Theorem 5 (an exact Monte Carlo test). Suppose p=0p = 0 and, under H0H_0, Xt=X0+μt+σStX_t = X_0 + \mu t + \sigma S_t with St=∑s≤tηsS_t = \sum_{s \le t}\eta_s, ηs\eta_s iid N(0,1)N(0, 1), σ>0\sigma > 0, and μ=0\mu = 0 in case "c". Let τ(1),…,τ(R)\tau^{(1)}, \dots, \tau^{(R)} be the statistics of RR independent standard Gaussian random walks of length nn started at 0, and pMC=(1+#{r:τ(r)≤τ})/(1+R)p_{\mathrm{MC}} = (1 + \#\{r : \tau^{(r)} \le \tau\})/(1 + R). Then P(pMC≤α)≤αP(p_{\mathrm{MC}} \le \alpha) \le \alpha for every α∈(0,1)\alpha \in (0, 1) and every nn.

Proof. By Lemma 4, τ(X)=τ(S)\tau(X) = \tau(S), and SS has the same law as each simulated walk. So τ,τ(1),…,τ(R)\tau, \tau^{(1)}, \dots, \tau^{(R)} are iid. Their common law is continuous, since τ\tau is a nonconstant ratio of smooth functions of a Gaussian vector, so ties have probability 0. The rank of τ\tau among the R+1R + 1 values is then uniform on {1,…,R+1}\{1, \dots, R + 1\}, and pMCp_{\mathrm{MC}} equals this rank divided by R+1R + 1. Hence P(pMC≤α)=⌊α(R+1)⌋/(R+1)≤αP(p_{\mathrm{MC}} \le \alpha) = \lfloor\alpha(R + 1)\rfloor/(R + 1) \le \alpha. □\square

For p≥1p \ge 1, or for non-Gaussian errors, the finite-sample law of τ\tau depends on γ\gamma and on the error law, and the simulated p-value is only approximate.

Cited: the limit law. Under H0H_0, with εt\varepsilon_t iid with finite variance and p=0p = 0, the statistic converges in distribution to the functionals of Brownian motion stated on the page (Dickey and Fuller 1979; Phillips 1987 under weaker conditions). Said and Dickey (1984) prove that with ARMA errors and p→∞p \to \infty, p3/T→0p^3/T \to 0, the t ratio has the same limit. The rejection rule τ<cα(T)\tau < c_\alpha(T) therefore has size tending to α\alpha. The response surface cα(T)c_\alpha(T) of MacKinnon (2010) is an empirical fit to simulations. Its fitting error is small next to the Monte Carlo error of a typical study, but it is not an exact formula.

Termination. Line L1 runs n−1n - 1 times, lines L3 and L4 TT times, the QR factorization of line L5 has kk outer steps, and lines L6 to L10 are finite. So ADF terminates. The lag search runs ADF at most pmax⁡+1p_{\max} + 1 times. □\square

Complexity

On a real RAM, one ADF regression with TT rows and kk regressors costs Θ(Tk2)\Theta(Tk^2) time for the QR factorization and Θ(k3)\Theta(k^3) for the triangular solves, so Θ(nk2)\Theta(nk^2) in total since T>kT > k. The design matrix takes Θ(nk)\Theta(nk) space. Lag selection over p=0,…,pmax⁡p = 0, \dots, p_{\max} costs Θ(npmax⁡3)\Theta(n p_{\max}^3) if every regression is refitted. Adding one column to an existing QR factorization costs Θ(Tk)\Theta(Tk), which brings the search down to Θ(npmax⁡2)\Theta(n p_{\max}^2). A Monte Carlo p-value with RR replicates costs RR more regressions.

Numerical stability. The level Xt−1X_{t-1} and the constant are nearly collinear when the series is far from 0 relative to its spread, and Z⊤ZZ^\top Z then has a large condition number. Forming the normal equations squares that condition number. The QR route in lines L5 to L7 works with ZZ directly. In case "ct", the trend column tt and the level are also nearly collinear for a trending series. Centering the trend column (t−tˉt - \bar t) changes neither ρ^\hat\rho nor τ\tau, and it improves the conditioning.

Properties

  • Exact rewriting. The ADF regression is a reparametrization of an AR(p+1p + 1) with deterministic terms. Nothing is approximated when the true order is at most p+1p + 1.
  • Invariant. τ\tau is unchanged by a change of level and scale (case "c"), and also by an added linear trend (case "ct"). In case "n" only a change of scale leaves it unchanged, so the start value matters.
  • Superconsistent under the null. ρ^−ρ=Op(1/T)\hat\rho - \rho = O_p(1/T), not Op(1/T)O_p(1/\sqrt T). The coefficients γi\gamma_i of the stationary lags are still T\sqrt T-consistent and asymptotically normal (Sims, Stock and Watson 1990).
  • Free of nuisance parameters in the limit. With enough lags, the limit law of τ\tau does not depend on γ\gamma or on σ2\sigma^2, so one table serves all ARMA dynamics. The finite-sample law does depend on them.
  • Consistent. For a fixed stationary alternative the power tends to 1 as n→∞n \to \infty.
  • Low power near the unit root. With n=100n = 100, a root of 0.9 is detected only about a third of the time.

Variants and improvements

  • Dickey-Fuller test. The case p=0p = 0. It is valid only when the differences are white noise under the null.
  • Coefficient test. Use Tρ^/(1−∑γ^i)T\hat\rho/(1 - \sum\hat\gamma_i) in place of τ\tau, with its own table. It has better power in some settings and worse size in others.
  • F tests for joint hypotheses. Dickey and Fuller (1981) give likelihood ratio (F-type) statistics for ρ=0\rho = 0 together with b=0b = 0 or a=0a = 0, with nonstandard tables.
  • Phillips-Perron test. Keep p=0p = 0 and correct τ\tau for serial correlation with a nonparametric long-run variance (the same Bartlett kernel estimator as in the KPSS test). It handles heteroscedastic errors, but its size is poor under negative MA roots.
  • DF-GLS (Elliott, Rothenberg and Stock 1996). Remove the deterministic terms by a quasi-difference GLS fit at a local alternative ρˉ=1−cˉ/T\bar\rho = 1 - \bar c/T, then run the ADF regression without deterministic terms. Its power is close to the Gaussian power envelope, and it is clearly better than the ADF test near the unit root.
  • Modified information criteria (Ng and Perron 2001). A lag choice whose penalty depends on ρ^\hat\rho, which fixes much of the size distortion under negative MA roots.
  • Reversed null. The KPSS test takes stationarity as the null. Running both tests separates "clearly stationary", "clearly a unit root" and "the data cannot tell".
  • Bootstrap. Fit the AR model to ∇Xt\nabla X_t, resample its residuals, rebuild random walks, and recompute τ\tau. A block bootstrap of the differences is an alternative.
  • Residual-based cointegration test. Applied to the residuals of a regression of one I(1) series on others, the same statistic is the Engle-Granger test, with different critical values.

When to use it

Use the ADF test before fitting an ARIMA model, to decide whether to difference, and before a regression of one trending series on another, to see whether the series are I(1) and the Engle-Granger or Johansen machinery is needed. Choose case "ct" when the series has a visible trend, case "c" when it has a nonzero level and no trend, and case "n" only when theory fixes the mean at 0. For short series near the unit root, prefer DF-GLS, and report the KPSS result as well.

Pitfalls

  • Normal or t tables. The 5% point in case "c" is −2.86-2.86, not −1.645-1.645. Using a t table rejects the unit root far too often.
  • Wrong deterministic terms. If the series has a trend and the regression has only a constant, τ\tau almost never rejects even when the series is trend-stationary. If a random walk has a drift and the regression has only a constant, τ\tau is asymptotically normal (West 1988), and the Dickey-Fuller table is wrong. With a drift of 1 per step and n=100n = 100, case "c" rejected in 0.4% of samples at the nominal 5% level. Use case "ct" for drifting series.
  • Too few lags. If ∇Xt\nabla X_t is an MA(1) with θ=−0.8\theta = -0.8, the test with p=0p = 0 and n=100n = 100 rejects the true unit root in almost every sample. Even with AIC lag selection it rejected in 45% of samples at the nominal 5% level (400 samples; Schwert 1989 reports the same pattern).
  • Too many lags. Each extra lag costs one observation and some power. Do not fix pp large out of caution.
  • Different rows for different lags. Information criteria must compare fits on the same rows. Comparing a p=2p = 2 fit on n−3n - 3 rows with a p=10p = 10 fit on n−11n - 11 rows biases the choice.
  • Structural breaks. A single shift in level or slope makes a stationary series look like a random walk, and the test then fails to reject (Perron 1989). Look for breaks with change-point detection and use a test that allows them.
  • Reading "not rejected" as "unit root". Failing to reject means the data do not exclude a unit root. A root of 0.95 and a root of 1 are hard to tell apart with 100 observations.

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.

adf_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/augmented-dickey-fuller-test/. The authors are listed in prov/61BK07.jsonl.
"""Augmented Dickey-Fuller unit root test.

The test regression is

    dy_t = rho * y_(t-1) + [a] + [b t] + sum_(i=1..p) g_i dy_(t-i) + e_t,

with dy_t = y_t - y_(t-1). The statistic is tau = rho-hat / se(rho-hat), the
ordinary t ratio. Under H_0: rho = 0 (a unit root) tau has the nonstandard
Dickey-Fuller law, so it is compared with the MacKinnon (2010) response surface
critical values, not with a t table. trend is "n" (no deterministic terms),
"c" (a constant) or "ct" (a constant and a linear trend).
The code is in this file and not in augmented_dickey_fuller_test.py, because
tools treat a file whose name ends in _test.py as a test file.
"""

import math
import random

# MacKinnon (2010), Queen's Economics Department Working Paper 1227, Table 2,
# one variable (N = 1). Critical value at sample size T: b0 + b1/T + b2/T^2 + b3/T^3.
MACKINNON_2010 = {
    "n": {0.01: (-2.56574, -2.2358, -3.627, 0.0),
          0.05: (-1.94100, -0.2686, -3.365, 31.223),
          0.10: (-1.61682, 0.2656, -2.714, 25.364)},
    "c": {0.01: (-3.43035, -6.5393, -16.786, -79.433),
          0.05: (-2.86154, -2.8903, -4.234, -40.040),
          0.10: (-2.56677, -1.5384, -2.809, 0.0)},
    "ct": {0.01: (-3.95877, -9.0531, -28.428, -134.155),
           0.05: (-3.41049, -4.3904, -9.036, -45.374),
           0.10: (-3.12705, -2.5856, -3.925, -22.380)},
}


def mackinnon_critical_value(trend, level, nobs=None):
    """Lower-tail critical value of tau at the given level (0.01, 0.05 or 0.10).

    nobs=None gives the asymptotic value b0."""
    b = MACKINNON_2010[trend][level]
    if nobs is None:
        return b[0]
    u = 1.0 / nobs
    return b[0] + b[1] * u + b[2] * u * u + b[3] * u * u * u


def qr_mgs(columns):
    """Thin QR factorization of the n x k matrix with the given columns, by
    modified Gram-Schmidt. Returns (q, r) with q a list of k orthonormal columns."""
    k = len(columns)
    q = []
    r = [[0.0] * k for _ in range(k)]
    for j in range(k):
        v = [float(a) for a in columns[j]]
        norm0 = math.sqrt(sum(a * a for a in v))
        for i in range(j):
            d = sum(a * b for a, b in zip(q[i], v))
            r[i][j] = d
            v = [a - d * b for a, b in zip(v, q[i])]
        nrm = math.sqrt(sum(a * a for a in v))
        if norm0 == 0.0 or nrm <= 1e-12 * norm0:
            raise ValueError("the regressors are linearly dependent")
        r[j][j] = nrm
        q.append([a / nrm for a in v])
    return q, r


def upper_inverse(r):
    """Inverse of an upper triangular matrix by back substitution."""
    k = len(r)
    rinv = [[0.0] * k for _ in range(k)]
    for c in range(k):
        for j in range(c, -1, -1):
            rhs = (1.0 if j == c else 0.0) - sum(r[j][l] * rinv[l][c] for l in range(j + 1, c + 1))
            rinv[j][c] = rhs / r[j][j]
    return rinv


def ols(columns, y):
    """Least squares through the QR factorization. Returns (coef, resid, s2, se)
    with s2 = RSS / (n - k) and se the usual standard errors."""
    n, k = len(y), len(columns)
    if n <= k:
        raise ValueError("need more observations than regressors")
    q, r = qr_mgs(columns)
    rinv = upper_inverse(r)
    qty = [sum(a * float(b) for a, b in zip(qj, y)) for qj in q]
    coef = [sum(rinv[j][c] * qty[c] for c in range(j, k)) for j in range(k)]
    resid = [float(y[t]) - sum(coef[j] * float(columns[j][t]) for j in range(k)) for t in range(n)]
    s2 = sum(e * e for e in resid) / (n - k)
    se = [math.sqrt(s2 * sum(rinv[j][c] ** 2 for c in range(j, k))) for j in range(k)]
    return coef, resid, s2, se


def adf_regression(y, lags=0, trend="c", first=None):
    """Fit the ADF regression with a fixed number of lagged differences, on the
    rows t = first .. n-1 (0-based; default first = lags + 1).

    Returns a dict with tau, rho (the coefficient of y_(t-1)), nobs, rss and k."""
    if trend not in MACKINNON_2010:
        raise ValueError("trend must be 'n', 'c' or 'ct'")
    y = [float(v) for v in y]
    n = len(y)
    if first is None:
        first = lags + 1
    dy = [0.0] + [y[t] - y[t - 1] for t in range(1, n)]  # @line L1
    nobs = n - first  # @line L2
    k = 1 + {"n": 0, "c": 1, "ct": 2}[trend] + lags
    cols = [[] for _ in range(k)]
    resp = []
    for t in range(first, n):  # @line L3
        row = [y[t - 1]] + {"n": [], "c": [1.0], "ct": [1.0, float(t)]}[trend] + [dy[t - i] for i in range(1, lags + 1)]
        for j in range(k):
            cols[j].append(row[j])
        resp.append(dy[t])  # @line L4
    if nobs <= k:
        raise ValueError("need more observations than regressors")
    q, r = qr_mgs(cols)  # @line L5
    rinv = upper_inverse(r)
    qty = [sum(a * b for a, b in zip(qj, resp)) for qj in q]
    coef = [sum(rinv[j][c] * qty[c] for c in range(j, k)) for j in range(k)]
    resid = [resp[t] - sum(coef[j] * cols[j][t] for j in range(k)) for t in range(nobs)]
    rss = sum(e * e for e in resid)
    s2 = rss / (nobs - k)  # @line L6
    se = math.sqrt(s2 * sum(v * v for v in rinv[0]))  # @line L7
    tau = coef[0] / se  # @line L8
    return {"tau": tau, "rho": coef[0], "nobs": nobs, "rss": rss, "k": k, "lags": lags}


def schwert_max_lag(n):
    """Schwert (1989) rule: floor(12 (n/100)^(1/4))."""
    return int(12.0 * (n / 100.0) ** 0.25)


def select_lags(y, max_lag, trend="c", criterion="aic"):
    """Choose the number of lagged differences.

    "aic" and "bic" fit every order 0..max_lag on the same rows and minimise
    nobs log(RSS/nobs) + penalty * k. "t-stat" starts at max_lag and drops the
    last lag while its |t| is below 1.645 (general to specific)."""
    y = [float(v) for v in y]
    first = max_lag + 1
    if criterion in ("aic", "bic"):
        best, best_ic = 0, math.inf
        for p in range(max_lag + 1):
            f = adf_regression(y, p, trend, first)
            pen = 2.0 if criterion == "aic" else math.log(f["nobs"])
            ic = f["nobs"] * math.log(f["rss"] / f["nobs"]) + pen * f["k"]
            if ic < best_ic - 1e-12:
                best, best_ic = p, ic
        return best
    if criterion == "t-stat":
        n = len(y)
        for p in range(max_lag, 0, -1):
            rows = range(first, n)
            cols = [[y[t - 1] for t in rows]]
            if trend != "n":
                cols.append([1.0] * len(rows))
            if trend == "ct":
                cols.append([float(t) for t in rows])
            for i in range(1, p + 1):
                cols.append([y[t - i] - y[t - i - 1] for t in rows])
            coef, _, _, se = ols(cols, [y[t] - y[t - 1] for t in rows])
            if abs(coef[-1] / se[-1]) >= 1.645:
                return p
        return 0
    raise ValueError("criterion must be 'aic', 'bic' or 't-stat'")


def augmented_dickey_fuller_test(y, trend="c", lags=None, max_lag=None, criterion="aic"):
    """The ADF test. lags=None selects the order by criterion up to max_lag
    (default: the Schwert rule), then refits on all usable rows.

    Returns tau, the chosen lags, nobs, the 1%, 5% and 10% critical values at
    that nobs, and reject (at 5%). Reject the unit root at level a when tau < critical[a]."""
    y = [float(v) for v in y]
    if lags is None:
        if max_lag is None:
            max_lag = schwert_max_lag(len(y))
        max_lag = max(0, min(max_lag, (len(y) - 4) // 3))
        lags = select_lags(y, max_lag, trend, criterion)
    fit = adf_regression(y, lags, trend)
    fit["critical"] = {a: mackinnon_critical_value(trend, a, fit["nobs"]) for a in (0.01, 0.05, 0.10)}  # @line L9
    fit["reject"] = fit["tau"] < fit["critical"][0.05]  # @line L10
    return fit


def simulate_null(n, trend="c", lags=0, reps=1000, rng=None):
    """tau for reps Gaussian random walks of length n (y_0 = 0, unit variance)."""
    rng = rng or random.Random(0)
    out = []
    for _ in range(reps):
        y, s = [], 0.0
        for _ in range(n):
            s += rng.gauss(0.0, 1.0)
            y.append(s)
        out.append(adf_regression(y, lags, trend)["tau"])
    return out


def monte_carlo_p_value(tau, n, trend="c", lags=0, reps=999, rng=None):
    """(1 + #{simulated tau <= tau}) / (1 + reps), from Gaussian random walks.

    With trend "c" or "ct" and lags = 0, tau does not depend on the start value,
    the drift (for "ct") or the scale, so for Gaussian errors this p-value is
    exact up to Monte Carlo error at every n."""
    sims = simulate_null(n, trend, lags, reps, rng)
    return (1 + sum(1 for s in sims if s <= tau)) / (1 + reps)
augmented_dickey_fuller_test.py 12 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/augmented-dickey-fuller-test/. The authors are listed in prov/61BK07.jsonl.
"""Entry point named after the slug. The code lives in adf_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from adf_core import (MACKINNON_2010, adf_regression, augmented_dickey_fuller_test,
                      mackinnon_critical_value, monte_carlo_p_value, ols, qr_mgs, schwert_max_lag,
                      select_lags, simulate_null, upper_inverse)

__all__ = ["MACKINNON_2010", "adf_regression", "augmented_dickey_fuller_test",
           "mackinnon_critical_value", "monte_carlo_p_value", "ols", "qr_mgs", "schwert_max_lag",
           "select_lags", "simulate_null", "upper_inverse"]
test_augmented_dickey_fuller_test.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/augmented-dickey-fuller-test/. The authors are listed in prov/61BK07.jsonl.

import math
import random
from fractions import Fraction

import pytest

from augmented_dickey_fuller_test import (adf_regression, augmented_dickey_fuller_test,
                                          mackinnon_critical_value, monte_carlo_p_value, ols,
                                          schwert_max_lag, select_lags, simulate_null)


def exact_ols(columns, y):
    """Brute force: solve the normal equations X^T X b = X^T y in exact rationals."""
    k = len(columns)
    cols = [[Fraction(v) for v in c] for c in columns]
    yy = [Fraction(v) for v in y]
    a = [[sum(p * q for p, q in zip(cols[i], cols[j])) for j in range(k)]
         + [sum(p * q for p, q in zip(cols[i], yy))] for i in range(k)]
    for c in range(k):
        piv = next(r for r in range(c, k) if a[r][c] != 0)
        a[c], a[piv] = a[piv], a[c]
        for r in range(k):
            if r != c and a[r][c] != 0:
                f = a[r][c] / a[c][c]
                a[r] = [u - f * v for u, v in zip(a[r], a[c])]
    b = [a[i][k] / a[i][i] for i in range(k)]
    resid = [v - sum(b[j] * cols[j][t] for j in range(k)) for t, v in enumerate(yy)]
    return b, resid


def exact_inverse_diag(columns):
    k = len(columns)
    cols = [[Fraction(v) for v in c] for c in columns]
    a = [[sum(p * q for p, q in zip(cols[i], cols[j])) for j in range(k)]
         + [Fraction(int(i == j)) for j in range(k)] for i in range(k)]
    for c in range(k):
        piv = next(r for r in range(c, k) if a[r][c] != 0)
        a[c], a[piv] = a[piv], a[c]
        a[c] = [u / a[c][c] for u in a[c]]
        for r in range(k):
            if r != c and a[r][c] != 0:
                f = a[r][c]
                a[r] = [u - f * v for u, v in zip(a[r], a[c])]
    return [a[i][k + i] for i in range(k)]


def test_worked_example() -> None:
    # The page example: y = 3 5 4 6 8 7 9 8, constant, no lags.
    y = [3, 5, 4, 6, 8, 7, 9, 8]
    r = adf_regression(y, 0, "c")
    assert r["nobs"] == 7
    assert abs(r["rho"] - (-3 / 7)) < 1e-13
    assert abs(r["rss"] - 72 / 7) < 1e-12
    assert abs(r["tau"] - (-math.sqrt(5 / 2))) < 1e-12
    assert abs(mackinnon_critical_value("c", 0.05, 7) - (-3.4775828571)) < 1e-9


@pytest.mark.parametrize("trend", ["n", "c", "ct"])
@pytest.mark.parametrize("lags", [0, 1, 3])
def test_regression_matches_exact_normal_equations(trend, lags) -> None:
    rng = random.Random(100 + lags)
    y = [rng.randint(-20, 20) for _ in range(25)]
    first = lags + 1
    rows = range(first, len(y))
    resp = [y[t] - y[t - 1] for t in rows]
    cols = [[y[t - 1] for t in rows]]
    if trend != "n":
        cols.append([1] * len(resp))
    if trend == "ct":
        cols.append(list(rows))
    for i in range(1, lags + 1):
        cols.append([y[t - i] - y[t - i - 1] for t in rows])
    b, resid = exact_ols(cols, resp)
    rss = sum(e * e for e in resid)
    s2 = rss / (len(resp) - len(cols))
    tau = float(b[0]) / math.sqrt(float(s2 * exact_inverse_diag(cols)[0]))
    r = adf_regression(y, lags, trend)
    assert abs(r["rho"] - float(b[0])) < 1e-10
    assert abs(r["rss"] - float(rss)) < 1e-8 * float(rss)
    assert abs(r["tau"] - tau) < 1e-9
    coef, res2, _, _ = ols(cols, resp)
    assert all(abs(u - float(v)) < 1e-9 for u, v in zip(coef, b))


def test_dependent_regressors_rejected() -> None:
    with pytest.raises(ValueError):
        ols([[1, 2, 3, 4], [2, 4, 6, 8]], [1, 0, 1, 0])


@pytest.mark.parametrize("trend,shift", [("c", lambda t: 7.5), ("ct", lambda t: -3.0 + 0.4 * t)])
def test_invariance_to_level_drift_and_scale(trend, shift) -> None:
    # With trend "c" tau ignores y -> a + c y; with "ct" also an added linear trend.
    rng = random.Random(7)
    y, s = [], 0.0
    for _ in range(60):
        s += rng.gauss(0, 1)
        y.append(s)
    for lags in (0, 2):
        base = adf_regression(y, lags, trend)["tau"]
        moved = adf_regression([shift(t) + 3.0 * v for t, v in enumerate(y)], lags, trend)["tau"]
        assert abs(base - moved) < 1e-9


@pytest.mark.parametrize("trend", ["n", "c", "ct"])
def test_size_against_mackinnon_surface(trend) -> None:
    # Random walks of length 100 give nobs = 99. The share of tau below the 5%
    # MacKinnon value must be 0.05 within 4 binomial standard errors (0.016).
    reps = 3000
    sims = simulate_null(100, trend, 0, reps, random.Random({"n": 11, "c": 12, "ct": 13}[trend]))
    crit = mackinnon_critical_value(trend, 0.05, 99)
    rate = sum(1 for s in sims if s < crit) / reps
    assert abs(rate - 0.05) < 4 * math.sqrt(0.05 * 0.95 / reps)


def test_asymptotic_values() -> None:
    assert mackinnon_critical_value("n", 0.05) == -1.94100
    assert mackinnon_critical_value("c", 0.05) == -2.86154
    assert mackinnon_critical_value("ct", 0.05) == -3.41049
    for tr in ("n", "c", "ct"):
        c = [mackinnon_critical_value(tr, a, 100) for a in (0.01, 0.05, 0.10)]
        assert c[0] < c[1] < c[2]


def test_power_against_stationary_ar1() -> None:
    rng = random.Random(21)
    rejections = 0
    for _ in range(40):
        y, s = [], 0.0
        for _ in range(200):
            s = 0.5 * s + rng.gauss(0, 1)
            y.append(s)
        r = augmented_dickey_fuller_test(y, "c")
        rejections += r["tau"] < r["critical"][0.05]
    assert rejections >= 38


def test_lag_selection_finds_ar_in_differences() -> None:
    # dy_t = 0.6 dy_(t-1) + e_t: one lagged difference is needed.
    rng = random.Random(5)
    y, d, s = [], 0.0, 0.0
    for _ in range(300):
        d = 0.6 * d + rng.gauss(0, 1)
        s += d
        y.append(s)
    assert select_lags(y, 8, "c", "bic") == 1
    assert select_lags(y, 8, "c", "aic") >= 1
    assert select_lags(y, 8, "c", "t-stat") >= 1
    r = augmented_dickey_fuller_test(y, "c", criterion="bic")
    assert r["lags"] == 1 and r["nobs"] == 298


def test_schwert_rule() -> None:
    assert [schwert_max_lag(n) for n in (50, 100, 200, 1000)] == [10, 12, 14, 21]


def test_monte_carlo_p_value() -> None:
    y = [3, 5, 4, 6, 8, 7, 9, 8]
    tau = adf_regression(y, 0, "c")["tau"]
    p = monte_carlo_p_value(tau, 8, "c", 0, 1999, random.Random(5))
    assert 0.38 < p < 0.51
    assert monte_carlo_p_value(-50.0, 8, "c", 0, 99, random.Random(1)) == 0.01

History

The unit root problem became central in econometrics in the 1970s, when it was noticed that regressions of one trending series on another often gave large t ratios by chance (Granger and Newbold 1974). David Dickey and Wayne Fuller derived the null distributions in Dickey's 1976 thesis at Iowa State; the tables were printed in Fuller's 1976 textbook, and the limit laws appeared in their 1979 paper in the Journal of the American Statistical Association. Their 1981 paper in Econometrica added likelihood ratio tests. Said and Dickey (1984) showed that adding lagged differences extends the test to ARMA errors of unknown order. Nelson and Plosser (1982) applied it to fourteen US macroeconomic series and could not reject a unit root in most, which started a long debate about trends in economic data. Phillips (1987) gave the Brownian motion form of the limits under weak conditions, and MacKinnon (1991, 1996, 2010) replaced the original tables with response surfaces fitted to large simulations.

References

  1. James D. Hamilton, Time Series Analysis, Princeton University Press, 1994, Chapter 17 (univariate processes with unit roots), the four cases of the Dickey-Fuller regression and the augmented test
  2. Wayne A. Fuller, Introduction to Statistical Time Series, second edition, Wiley, 1996, the chapter on unit root and explosive time series, with the tables of the Dickey-Fuller percentiles
  3. David A. Dickey and Wayne A. Fuller, Distribution of the estimators for autoregressive time series with a unit root, Journal of the American Statistical Association 74(366) (1979), pages 427 to 431, the limit laws of the coefficient and t statistics in the three regressions
  4. Said E. Said and David A. Dickey, Testing for unit roots in autoregressive-moving average models of unknown order, Biometrika 71(3) (1984), pages 599 to 607, the augmented regression with a number of lags that grows with n
  5. MacKinnon 2010, Table 2, the response surface coefficients for one variable (N = 1), cases nc, c and ct
  6. James G. MacKinnon, Numerical distribution functions for unit root and cointegration tests, Journal of Applied Econometrics 11(6) (1996), pages 601 to 618, response surface p-values for the Dickey-Fuller statistics
  7. G. William Schwert, Tests for unit roots, a Monte Carlo investigation, Journal of Business and Economic Statistics 7(2) (1989), pages 147 to 159, the size distortion under a negative moving-average root and the rule for the maximum lag

Where this leads

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