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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 on the lagged level , on deterministic terms (none, a constant, or a constant and a linear trend) and on lagged differences, and uses the ordinary t ratio of the coefficient of . The null hypothesis is a unit root. The alternative is a stationary (or trend-stationary) autoregression. Under the null, does not have a t or normal law: its limit is a functional of Brownian motion, with 5% points of about , and 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 , , where is a deterministic term (zero, a constant , or a line ) and is an autoregression of order , with , the backshift operator and as on the ARMA model page. Any such autoregression can be rewritten exactly as
The null hypothesis is , which holds exactly when is a root of . Then is integrated of order one, an ARIMA process with . The alternative is , which holds whenever all roots of lie outside the unit circle, so that is a stationary process and is stationary around . The test is one-sided: explosive roots () are not part of the alternative.
Statistic. Fit by ordinary least squares, over (so rows),
where is empty (case "n"), (case "c") or (case "ct"). The statistic is the t ratio , with , the regressor matrix and . The deterministic terms in the regression must contain those in the model: case "c" covers , and case "ct" covers and also a random walk with drift.
Null distribution. Asymptotic and nonstandard. In case "n" with and iid errors, Dickey and Fuller (1979) showed
where is a standard Brownian motion. In cases "c" and "ct", is replaced by its residual after projection on or on . Said and Dickey (1984) showed that the same limits hold for ARMA errors when with . These limits are cited, not proved here. In finite samples the law of is exact by simulation in one case: with Gaussian errors and , 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 , up to Monte Carlo error. This is proved below.
Rejection rule and size. Reject at level when , with the response surface of MacKinnon (2010), . Some values:
| case | , 1% / 5% / 10% | ||
|---|---|---|---|
| "n" | / / | / / | / / |
| "c" | / / | / / | / / |
| "ct" | / / | / / | / / |
The standard normal 5% point is , far to the right of these. The size is asymptotically . In finite samples it depends on how well the lags capture the short-run dynamics.
p-value. for the limiting law. MacKinnon (1996) gives response surface approximations. The implementation gives a Monte Carlo p-value from simulated Gaussian random walks of the same length, which is exact for Gaussian errors with in cases "c" and "ct".
Sensitivity and power. The test detects a pull toward the mean, . Under a fixed stationary alternative and the power tends to 1. Near the unit root the power is low: for an AR(1) with and , case "c" without lags rejects at 5% in about a third of samples. Large negative moving-average terms in inflate the size, because the series then looks stationary over short spans.
The algorithm
ADF(X₁..Xₙ, case, p) ▷ case ∈ {n, c, ct}, p lagged differences- 1
for t ← 2 to n: D_t ← X_t − X_{t−1} - 2
T ← n − p − 1 - 3
for t ← p + 2 to n: ▷ one row per usable time point - 4
z_t ← (X_{t−1}, d*_t, D_{t−1}, …, D_{t−p}); response D_t - 5
Z = QR, with Q of size T×k and R upper triangular ▷ Gram-Schmidt or Householder - 6
β̂ ← R⁻¹ Qᵀ D; e ← D − Z β̂; s² ← eᵀe / (T − k) - 7
se ← s · ‖row 1 of R⁻¹‖ ▷ [(ZᵀZ)⁻¹]₁₁ = Σ_c (R⁻¹)₁c² - 8
τ ← β̂₁ / se - 9
c ← β₀ + β₁/T + β₂/T² + β₃/T³ ▷ MacKinnon (2010), for case and α - 10
return (τ, c, reject ⇔ τ < c)
The number of lags is chosen before line L1. The usual rule fits every from 0 to on the same rows , picks the that minimizes the AIC or BIC, , and then refits with that on all usable rows. A common choice is Schwert's , which is 12 at and 14 at . Another is to start at and drop the last lag while its t ratio is below 1.645 in absolute value.
Example
By hand. Take , case "c" and . Then and the regression is of on a constant and :
| step | value |
|---|---|
| L1: , | (mean ) |
| L4: | (mean 6) |
| 28 | |
| L6: , constant | , |
| L6: residual sum of squares, | , |
| L7: | 0.27105 |
| L8: | |
| L9: |
Since , the test does not reject the unit root. A one-sided t table with 5 degrees of freedom would put the cut-off at , 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 and an AR(1) series . With case "c", AIC lag selection and :
| series | chosen | decision | |||
|---|---|---|---|---|---|
| random walk | 0 | 199 | keep | ||
| AR(1), | 2 | 197 | reject |
Power and size. With , case "c", and 1000 samples each, the rejection rate at 5% is 1.000 for , 0.868 for , 0.336 for , 0.128 for and 0.055 under the null . 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() model, with , so is the same as a unit root, and holds for every causal stationary autoregression, because and has no zero on . Under the null, , so the lagged differences are exactly the autoregression of . Second, lines L5 to L8 compute the ordinary least squares t ratio, because gives and . Third, does not change when is replaced by with in case "c", or by in case "ct", because the regressor span and the t ratio are unchanged. Under the null with Gaussian errors and this makes the simulated law exact, and the Monte Carlo p-value has for every . 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() model in which the null is a unit root and every causal stationary model has (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 , 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: , is the backshift operator, .
Lemma 1 (the ADF form). For any real , set and for . Then, as polynomials,
Hence holds exactly when . The map from to is one-to-one.
Proof. Compare coefficients of the right side of (1). The constant term is 1. Since , the coefficient of is . For the coefficient of is . The coefficient of is . So both sides of (1) agree. Applying (1) with replaced by to gives , which is the second claim. The inverse map is , for , and , so the map is one-to-one.
When with a constant or a line, and . Substituting, the deterministic parts combine into a constant (when ) or a constant plus a multiple of (when ). So the regression with or contains the true model.
Lemma 2 (the hypotheses). (a) if and only if , that is, is a root of . In that case . (b) If every root of has modulus greater than 1, then .
Proof. (a) The first claim is . With , (1) reads . (b) is a real polynomial with . It has no zero in , since such a zero would be a root of modulus at most 1. By continuity keeps its sign on , so and .
Part (a) says that under the null, is the autoregression , so the lagged differences remove exactly the serial correlation in . The converse of (b) is false: 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 be the matrix with rows , of full column rank, and let with and upper triangular with positive diagonal. Then is the least squares solution, is its residual, and . So line L8 returns the ordinary t ratio of the first coefficient.
Proof. , which is invertible since has a positive diagonal. The normal equations read ; cancel the invertible to get , whose unique solution is . Next, , whose entry is .
Modified Gram-Schmidt, used in the implementation, produces the same and 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 with . In case "ct", for all . In case "c", when . In case "n", when .
Proof. Take case "ct". The response is , and the regressors are , , and . Let be the projection that removes the span of , and the lagged differences. That span equals the span of , and the , because each differs from by a constant. By the Frisch-Waugh-Lovell theorem, , where is the column of . Now and , since kills the constants and the trend. So . The full residual vector is , so . The variance factor is . Hence and . In case "c", with , the same argument works with removing and the lagged differences. In case "n", with , all columns and the response are multiplied by .
Theorem 5 (an exact Monte Carlo test). Suppose and, under , with , iid , , and in case "c". Let be the statistics of independent standard Gaussian random walks of length started at 0, and . Then for every and every .
Proof. By Lemma 4, , and has the same law as each simulated walk. So are iid. Their common law is continuous, since is a nonconstant ratio of smooth functions of a Gaussian vector, so ties have probability 0. The rank of among the values is then uniform on , and equals this rank divided by . Hence .
For , or for non-Gaussian errors, the finite-sample law of depends on and on the error law, and the simulated p-value is only approximate.
Cited: the limit law. Under , with iid with finite variance and , 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 , , the t ratio has the same limit. The rejection rule therefore has size tending to . The response surface 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 times, lines L3 and L4 times, the QR factorization of line L5 has outer steps, and lines L6 to L10 are finite. So ADF terminates. The lag search runs ADF at most times.
Complexity
On a real RAM, one ADF regression with rows and regressors costs time for the QR factorization and for the triangular solves, so in total since . The design matrix takes space. Lag selection over costs if every regression is refitted. Adding one column to an existing QR factorization costs , which brings the search down to . A Monte Carlo p-value with replicates costs more regressions.
Numerical stability. The level and the constant are nearly collinear when the series is far from 0 relative to its spread, and then has a large condition number. Forming the normal equations squares that condition number. The QR route in lines L5 to L7 works with directly. In case "ct", the trend column and the level are also nearly collinear for a trending series. Centering the trend column () changes neither nor , and it improves the conditioning.
Properties
- Exact rewriting. The ADF regression is a reparametrization of an AR() with deterministic terms. Nothing is approximated when the true order is at most .
- Invariant. 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. , not . The coefficients of the stationary lags are still -consistent and asymptotically normal (Sims, Stock and Watson 1990).
- Free of nuisance parameters in the limit. With enough lags, the limit law of does not depend on or on , 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 .
- Low power near the unit root. With , a root of 0.9 is detected only about a third of the time.
Variants and improvements
- Dickey-Fuller test. The case . It is valid only when the differences are white noise under the null.
- Coefficient test. Use in place of , 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 together with or , with nonstandard tables.
- Phillips-Perron test. Keep and correct 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 , 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 , 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 , resample its residuals, rebuild random walks, and recompute . 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 , not . 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, almost never rejects even when the series is trend-stationary. If a random walk has a drift and the regression has only a constant, is asymptotically normal (West 1988), and the Dickey-Fuller table is wrong. With a drift of 1 per step and , case "c" rejected in 0.4% of samples at the nominal 5% level. Use case "ct" for drifting series.
- Too few lags. If is an MA(1) with , the test with and 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 large out of caution.
- Different rows for different lags. Information criteria must compare fits on the same rows. Comparing a fit on rows with a fit on 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.
# 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
- 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
- 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
- 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
- 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
- MacKinnon 2010, Table 2, the response surface coefficients for one variable (N = 1), cases nc, c and ct
- 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
- 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.
| 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 61BK07 Edit this page History Report an error Markdown