Algorithmcore
Durbin-Watson test
Also called Durbin-Watson statistic.
Tests for first-order autocorrelation of regression residuals by the sum of squared successive differences over the sum of squares. Values near 2 mean none.
- Time
- Θ(n p^2 + B n p) worst · best
- Space
- Θ(n p) extra
- Where
- B = the number of simulated samples; n = the number of observations; p = the number of columns of X, with p < n
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James Durbin, Geoffrey S. Watson, 1950
The Durbin-Watson test checks whether the errors of a linear regression on time-ordered data are correlated with their neighbours. It fits the model by ordinary least squares and computes from the residuals. Without correlation is near 2; positive correlation makes successive residuals similar and small, and negative correlation makes large. Under normal errors the null law of depends on the design but not on the coefficients or the error variance. Durbin and Watson could not tabulate a law for every , so they bracketed it between two laws that depend only on and ; this gives the classical bounds test with its inconclusive region. Today the exact p-value for the given is easy to get, here by simulation.
In plain words
When data come in time order, an error in one period often carries over to the next. A fitted line then looks better than it is, because its standard errors assume that every error is new. The test looks at the misses of the fitted line in time order. If neighbouring misses are close to each other, the sum of their squared differences is small compared with the sum of their squares. The ratio of the two is about 2 when the misses are unrelated, much lower than 2 when misses repeat, and higher than 2 when they flip sign. To judge whether a value is unusual, the method simulates many sets of pure noise for the same design and counts how often the noise gives a value as low.
The problem
Model. with a fixed real matrix of rank whose columns include the constant, the time order of the rows, and errors from the stationary first-order autoregressive model with independent and . The regressors must not include lagged values of .
Hypotheses. : , so the errors are independent ; : . The alternatives and are handled in the same way.
Statistic. With the residuals , , and the lag-one residual autocorrelation :
So , and .
Null distribution. Under , , where is the tridiagonal matrix with . Its law depends only on . It is the law of , with the nonzero eigenvalues of and independent standard normal .
Rejection rule and p-value. Against , small is extreme. The Monte Carlo p-value is , where are computed from standard normal response vectors with the same ; reject at level when it is at most . This test has exact size when is an integer. The classical bounds test compares with tabulated points and : reject if , do not reject if , and give no answer between them.
Power. The test is built for AR(1) errors and has good power against them; it also reacts to other forms of correlation that make positive. It has little power against correlation at longer lags only, such as a seasonal pattern.
The algorithm
DURBIN-WATSON(X[1..n, 1..p], y[1..n], B)- 1
Q₁ ← orthonormal basis of the columns of X by Householder QR; e ← y - Q₁Q₁ᵀy - 2
S ← Σₜ eₜ² - 3
D ← Σ_{t=2..n} (eₜ - eₜ₋₁)² - 4
d ← D / S; r₁ ← Σ_{t=2..n} eₜeₜ₋₁ / S - 5
for k ← 1 to B: draw ε* with independent N(0, 1) entries - 6
d*ₖ ← D / S of the residuals ε* - Q₁Q₁ᵀε* ▷ lines L2 to L4 again - 7
p ← (1 + #{k : d*ₖ ≤ d}) / (1 + B) ▷ against ρ > 0 - 8
return (d, r₁, p)
Line L1 needs the factorization only once; every simulated sample in line L6 reuses , so a sample costs . Simulated samples use and ; any other values give the same , because the statistic of equals that of . Against the count is , and the two-sided p-value is twice the smaller one-sided p-value, at most 1.
Example
Take , an intercept and a linear trend, so has the rows and , and
The residuals of the least squares line are
which stay above or below zero for runs of two to four periods. Then and .
| method | result at the 5% level |
|---|---|
| Monte Carlo p-value, , seed 7 | , reject |
| bounds, | 0.131 |
| bounds, | 0.0296 |
| bounds test | inconclusive, since |
The two bound probabilities were estimated from 20000 draws of (seed 3). The exact p-value lies between them, as the theory says. Here it is close to the upper bound, because the trend column is nearly an eigenvector of , and for such a design the law of is close to that of . The bounds test gives no answer, but the test for the actual design rejects.
Measured size and power. With and the 5% level, for each Monte Carlo p-value:
| errors | rejection rate | ||
|---|---|---|---|
| independent | 20 | 600 | 0.037 |
| independent | 30 | 2000 | 0.0535 |
| AR(1), | 30 | 1000 | 0.401 |
| AR(1), | 30 | 1000 | 0.936 |
The first two rows agree with the exact size 0.05 within the Monte Carlo error, about 0.009 for and 0.005 for . The power for shows that is too short to detect weak correlation reliably.
Correctness
The proof shows four exact facts. First, the identity , and when the constant is a column of . Second, the matrix has the eigenvalues , , with for the constant vector. Third, the residuals of are , so under normal the law of does not depend on or ; the observed and simulated statistics are then exchangeable, and the Monte Carlo p-value has exact size. Fourth, by the Cauchy interlacing theorem the eigenvalues of on the residual space satisfy , so for the same
and the laws of and depend only on and . This is the bounding result of Durbin and Watson.
What is cited and not proved: the numerical method of Imhof (1961) for the exact distribution function, and the limit under AR(1) errors. The size of the test for non-normal errors and all power values are measured, not proved.
Proof: The Durbin-Watson statistic lies in (0, 4), its null law depends only on X and not on b or sigma, and the bounds d_L and d_U bracket itfull
The arithmetic is exact. is a fixed real matrix of rank whose columns include the constant , , and . Let be the tridiagonal matrix with diagonal and next to the diagonal, so that
Lines L2 to L4 compute exactly these sums, and line L1 computes with an orthonormal basis of the columns of , which is .
Lemma 1 (identity and range). , and .
Proof. Expanding the squares, ; divide by . For the upper bound, gives , with equality only if for all and , that is . For the lower bound, only if all are equal; since is a column of , , so they would all be 0.
Lemma 2 (the eigenvalues of A). has the eigenvalues , , with eigenvectors . In particular with eigenvector .
Proof. Let and . For , . For , , and , the same. For , follows in the same way, because . The are distinct, so these are all the eigenvalues.
Lemma 3 (the null law does not depend on b or sigma). For and , the statistic of equals that of . Under , with , so
whose law depends only on . Hence the Monte Carlo p-value of lines L5 to L7, with computed from standard normal vectors, has under whenever is an integer.
Proof. , and is unchanged when is multiplied by . With , , and cancels. The observed and the simulated are then independent with the same continuous law, so they are exchangeable and have no ties with probability 1. The rank of among the values is uniform on , and exactly when that rank is at most .
Lemma 4 (the bounds). Let be the eigenvalues of restricted to the orthogonal complement of the columns of . Then under , has the law of with independent standard normal, and
So with and built from the same , , and for every .
Proof. Let be an matrix whose orthonormal columns span and diagonalize . Then , and with , and . Since is an eigenvector of the symmetric , the space is invariant, and on it has the eigenvalues by Lemma 2. is a subspace of of codimension , so the Cauchy interlacing theorem (a consequence of the Courant-Fischer minimax characterization) gives . Each ratio is a weighted mean of its eigenvalues with the same weights , so the order carries over to , and then to the distribution functions.
The laws of and depend only on and , which is why they could be tabulated once; Durbin and Watson (1950, 1951) proved this bounding result.
What is cited, not proved. The exact distribution function can be computed by the numerical inversion of Imhof (1961); this is not done here. When the errors follow a stationary AR(1) process with coefficient and the design is regular, and in probability; this is a standard consequence of the ergodic theorem and is not proved here. The size of the Monte Carlo test under non-normal errors, and the power, are measured on the page.
Termination. Line L1 is a Householder factorization with steps and one projection, lines L2 to L4 are three sums, and the loop of lines L5 and L6 runs times with work each: operations.
Complexity
The Householder factorization in line L1 costs , and lines L2 to L4 cost . Each of the simulated samples needs one projection, , so the total is time and extra space for . The statistic alone, without a p-value, costs . The exact law by Imhof's method needs the eigenvalues , which costs by a dense symmetric eigenvalue method, and then a numerical integral.
Properties
- Exact test for the given design. Under normal independent errors the Monte Carlo test has exact size for every that contains the constant, with no table and no inconclusive region.
- Invariance. is unchanged by for , so the unknown and do not matter.
- Range and centre. . Under the mean of is , which is near 2 for large .
- First order only. The statistic uses only lag-one products of the residuals.
- Depends on the time order. Rows must be in time order; sorting the rows by some other key gives a test of a different hypothesis.
- Normality. The exact null law assumes normal errors. For other error laws with a finite variance the test is valid only for large ; this was not measured here.
Variants and improvements
- Bounds test. The original form uses the tabulated and for given and . It needs no computation of the law but has an inconclusive region, which is wide for small , as the example shows.
- Exact p-value by quadratic forms. Compute the eigenvalues of and evaluate by Imhof's numerical inversion or a related algorithm for quadratic forms. The simulation on this page gives the same p-value up to Monte Carlo error.
- Negative and two-sided alternatives. Use against , or double the smaller one-sided p-value.
- Lagged dependent variables. When is a regressor, is biased toward 2 and the test loses power. Durbin (1970) gave the statistic and an alternative test that regresses on and the regressors.
- Higher lags. To test several lags at once, regress on and and test the lag coefficients, or use the Ljung-Box test on the residuals; the partial autocorrelation function shows which lags matter.
When to use it
Use it as a quick check of serial correlation after a regression on time-ordered data with fixed regressors, an intercept and no lagged response. A small means that the usual standard errors are too small. The remedies are to model the correlation, for example with generalized least squares for AR(1) errors or an ARIMA model for the errors, or to keep the least squares fit and use standard errors that allow for serial correlation. For data without a time order, the test has no meaning.
Pitfalls
- Lagged response as a regressor. Then is biased toward 2 and can hide strong correlation; use Durbin's or the lagged-residual regression.
- No intercept. The bounds and in the tables assume a constant column; without it they do not apply. The Monte Carlo version works for any , but the range result needs the constant.
- Inconclusive is not "no correlation". In the example the bounds test gives no answer, yet the exact p-value is 0.028. Compute the exact p-value for the given .
- A low from a wrong mean. A missing trend, a missing seasonal term or a nonlinear effect leaves runs of residuals of the same sign, and falls although the errors are independent. Plot the residuals against time before concluding that the errors are correlated.
- Gaps and unequal spacing. The statistic assumes equally spaced observations without gaps; differences across a gap compare periods that are not neighbours.
- Not rejecting with small . With the power against was only 0.40 in the table above.
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/durbin-watson-test/. The authors are listed in prov/TBDQN3.jsonl.
"""The Durbin-Watson test of serial correlation in regression residuals.
d = sum_{t>=2} (e_t - e_{t-1})^2 / sum_t e_t^2, with e the least squares residuals of y on X.
Under H0 with independent normal errors, e = M eps with M = I - H, so the law of d depends only on
X: simulating standard normal y for the given X gives a Monte Carlo p-value with exact size.
The bounds d_L and d_U use the eigenvalues 2 - 2 cos(pi j / n) of the matrix A of the quadratic
form in the numerator. The code is in this file and not in durbin_watson_test.py, because tools
treat a file whose name ends in _test.py as a test file.
"""
import math
import random
from typing import NamedTuple
RANK_TOL = 1e-12
class DWResult(NamedTuple):
d: float # the Durbin-Watson statistic
r1: float # the lag-1 residual autocorrelation sum e_t e_(t-1) / sum e_t^2
p_value: float # Monte Carlo p-value for the chosen alternative
reps: int # number of simulated samples
def householder_q1(a: list) -> list:
"""Rows of Q1 (n x p, orthonormal columns spanning the columns of a), by Householder QR."""
n = len(a)
p = len(a[0]) if n else 0
if p == 0 or n <= p:
raise ValueError("need a design with n > p >= 1")
a = [[float(v) for v in row] for row in a]
col = [math.sqrt(math.fsum(a[i][j] ** 2 for i in range(n))) for j in range(p)]
vs = []
for j in range(p):
norm = math.sqrt(math.fsum(a[i][j] ** 2 for i in range(j, n)))
if norm == 0.0 or norm <= RANK_TOL * col[j]:
raise ValueError("the design has rank below its number of columns")
alpha = -norm if a[j][j] >= 0.0 else norm
v = [0.0] * j + [a[j][j] - alpha] + [a[i][j] for i in range(j + 1, n)]
vv = math.fsum(t * t for t in v)
for k in range(j, p):
s = 2.0 * math.fsum(v[i] * a[i][k] for i in range(j, n)) / vv
for i in range(j, n):
a[i][k] -= s * v[i]
vs.append((v, vv))
# Q1 = H_1 ... H_p applied to the first p unit vectors.
q = [[1.0 if i == k else 0.0 for k in range(p)] for i in range(n)]
for j in range(p - 1, -1, -1):
v, vv = vs[j]
for k in range(p):
s = 2.0 * math.fsum(v[i] * q[i][k] for i in range(j, n)) / vv
for i in range(j, n):
q[i][k] -= s * v[i]
return q
def project_out(q: list, y: list) -> list:
"""Residuals y - Q1 Q1^T y."""
p = len(q[0])
c = [math.fsum(q[i][k] * y[i] for i in range(len(y))) for k in range(p)]
return [yi - math.fsum(qi[k] * c[k] for k in range(p)) for qi, yi in zip(q, y)]
def dw_statistic(e: list) -> tuple[float, float]:
"""(d, r1) for a residual vector e."""
s = math.fsum(t * t for t in e) # @line L2
if s == 0.0:
raise ValueError("all residuals are 0")
num = math.fsum((e[t] - e[t - 1]) ** 2 for t in range(1, len(e))) # @line L3
r1 = math.fsum(e[t] * e[t - 1] for t in range(1, len(e))) / s
return num / s, r1 # @line L4
def durbin_watson(x: list, y: list, alternative: str = "positive", reps: int = 999,
seed: int = 1) -> DWResult:
"""Durbin-Watson statistic and Monte Carlo p-value for the given design.
alternative: "positive" (small d is extreme), "negative" (large d) or "two-sided".
Cost: Theta(n p^2 + B n p) time, Theta(n p) space.
"""
if alternative not in ("positive", "negative", "two-sided"):
raise ValueError("alternative must be positive, negative or two-sided")
n = len(x)
if len(y) != n:
raise ValueError("x and y must have the same length")
q = householder_q1(x) # @line L1
e = project_out(q, y) # @line L1
if math.fsum(t * t for t in e) <= 1e-24 * math.fsum(float(v) ** 2 for v in y):
raise ValueError("y is fitted exactly by X, so d is undefined")
d, r1 = dw_statistic(e)
rng = random.Random(seed)
below = above = 0
tol = 1e-12 * max(d, 1.0)
for _ in range(reps): # @line L5
dstar = dw_statistic(project_out(q, [rng.gauss(0.0, 1.0) for _ in range(n)]))[0] # @line L6
below += dstar <= d + tol
above += dstar >= d - tol
if alternative == "positive": # @line L7
p = (1 + below) / (1 + reps)
elif alternative == "negative":
p = (1 + above) / (1 + reps)
else:
p = min(1.0, 2.0 * (1 + min(below, above)) / (1 + reps))
return DWResult(d, r1, p, reps) # @line L8
def bound_eigenvalues(n: int) -> list:
"""Eigenvalues 2 - 2 cos(pi j / n), j = 0..n-1, of the matrix A with d = e^T A e / e^T e."""
return [2.0 - 2.0 * math.cos(math.pi * j / n) for j in range(n)]
def bounds_p_values(d: float, n: int, p: int, reps: int = 9999, seed: int = 1) -> tuple[float, float]:
"""Monte Carlo P(d_L <= d) and P(d_U <= d) for a design with an intercept and p columns.
d_L = sum lam_i xi_i^2 / sum xi_i^2 over i = 1..n-p, and d_U the same with lam_(i+p-1).
Since d_L <= d <= d_U for the same xi, the exact p-value P(d* <= d) lies between the two.
Against positive correlation: if P(d_L <= d) < alpha, reject; if P(d_U <= d) > alpha, do not
reject; otherwise the bounds test is inconclusive.
"""
lam = bound_eigenvalues(n)
m = n - p
low, high = lam[1:m + 1], lam[p:p + m]
rng = random.Random(seed)
cl = cu = 0
for _ in range(reps):
xi2 = [rng.gauss(0.0, 1.0) ** 2 for _ in range(m)]
s = math.fsum(xi2)
cl += math.fsum(a * b for a, b in zip(low, xi2)) / s <= d
cu += math.fsum(a * b for a, b in zip(high, xi2)) / s <= d
return cl / reps, cu / reps
durbin_watson_test.py 11 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/durbin-watson-test/. The authors are listed in prov/TBDQN3.jsonl.
"""Entry point named after the slug. The code lives in durbin_watson_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from durbin_watson_core import (
DWResult, bound_eigenvalues, bounds_p_values, durbin_watson, dw_statistic, householder_q1, project_out,
)
__all__ = ["DWResult", "bound_eigenvalues", "bounds_p_values", "durbin_watson", "dw_statistic",
"householder_q1", "project_out"]
test_durbin_watson_test.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/durbin-watson-test/. The authors are listed in prov/TBDQN3.jsonl.
import math
import random
from fractions import Fraction
import pytest
from durbin_watson_test import (bound_eigenvalues, bounds_p_values, durbin_watson, dw_statistic,
householder_q1, project_out)
EX_T = list(range(1, 13))
EX_X = [[1, t] for t in EX_T]
EX_Y = [Fraction(v) for v in ["1.0", "1.9", "3.1", "3.2", "3.0", "3.6", "4.4", "5.6", "6.2", "6.1", "6.0", "6.8"]]
def solve(a, b):
k = len(a)
m = [[Fraction(v) for v in row] + [Fraction(b[i])] for i, row in enumerate(a)]
for c in range(k):
piv = next(r for r in range(c, k) if m[r][c] != 0)
m[c], m[piv] = m[piv], m[c]
for r in range(k):
if r != c and m[r][c] != 0:
f = m[r][c] / m[c][c]
m[r] = [u - f * v for u, v in zip(m[r], m[c])]
return [m[i][k] / m[i][i] for i in range(k)]
def exact_residuals(x, y):
p = len(x[0])
gram = [[sum(Fraction(r[i]) * r[j] for r in x) for j in range(p)] for i in range(p)]
b = solve(gram, [sum(Fraction(r[i]) * v for r, v in zip(x, y)) for i in range(p)])
return [Fraction(v) - sum(Fraction(a) * c for a, c in zip(r, b)) for r, v in zip(x, y)]
def exact_d(e):
s = sum(t * t for t in e)
return sum((e[t] - e[t - 1]) ** 2 for t in range(1, len(e))) / s, sum(e[t] * e[t - 1] for t in range(1, len(e))) / s
def jacobi_eigenvalues(a, sweeps=60):
"""Eigenvalues of a symmetric matrix by cyclic Jacobi rotations."""
a = [row[:] for row in a]
n = len(a)
for _ in range(sweeps):
off = math.fsum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
if off < 1e-26:
break
for p in range(n - 1):
for q in range(p + 1, n):
if abs(a[p][q]) < 1e-300:
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 k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
return sorted(a[i][i] for i in range(n))
def dw_matrix(n):
return [[(2.0 if 0 < i < n - 1 else 1.0) if i == j else (-1.0 if abs(i - j) == 1 else 0.0)
for j in range(n)] for i in range(n)]
def test_page_example_exact():
e = exact_residuals(EX_X, EX_Y)
d, r1 = exact_d(e)
s = sum(t * t for t in e)
assert d == 2 * (1 - r1) - (e[0] ** 2 + e[-1] ** 2) / s
res = durbin_watson(EX_X, [float(v) for v in EX_Y], reps=1999, seed=7)
assert res.d == pytest.approx(float(d), rel=1e-12)
assert res.r1 == pytest.approx(float(r1), rel=1e-12)
assert res.d == pytest.approx(1.2189, abs=1e-4) and res.r1 == pytest.approx(0.3329, abs=1e-4)
# With B = 9999 the Monte Carlo p-value was 0.0278; here B = 1999 (4 SE about 0.015).
assert abs(res.p_value - 0.0278) <= 0.015
def test_identity_range_and_invariance_exact():
rng = random.Random(31)
for _ in range(10):
n = rng.randint(6, 12)
x = [[1, t, rng.randint(-3, 3)] for t in range(n)]
y = [Fraction(rng.randint(-9, 9)) for _ in range(n)]
try:
e = exact_residuals(x, y)
except StopIteration:
continue
if all(t == 0 for t in e):
continue
d, r1 = exact_d(e)
s = sum(t * t for t in e)
assert d == 2 * (1 - r1) - (e[0] ** 2 + e[-1] ** 2) / s
assert 0 < d < 4 # with an intercept the residuals add to 0, so they are not all equal
# Residuals of a y + X c are a e, so d does not depend on b or sigma.
a, c = Fraction(rng.choice([-3, -1, 2, 5]), rng.randint(1, 4)), [rng.randint(-5, 5) for _ in range(3)]
y2 = [a * yi + sum(ci * xi for ci, xi in zip(c, row)) for yi, row in zip(y, x)]
assert exact_d(exact_residuals(x, y2))[0] == d
assert durbin_watson(x, [float(v) for v in y], reps=1).d == pytest.approx(float(d), rel=1e-10)
def test_projection_is_least_squares():
q = householder_q1(EX_X)
e = project_out(q, [float(v) for v in EX_Y])
assert e == pytest.approx([float(t) for t in exact_residuals(EX_X, EX_Y)], abs=1e-12)
for j in range(2):
for k in range(2):
assert math.fsum(row[j] * row[k] for row in q) == pytest.approx(float(j == k), abs=1e-12)
def test_eigenvalues_and_interlacing():
"""A has eigenvalues 2 - 2 cos(pi j / n). The nonzero eigenvalues nu_i of M A M satisfy
lam_i <= nu_i <= lam_(i+p-1), which gives d_L <= d <= d_U for the same normal draws."""
n = 12
lam = bound_eigenvalues(n)
assert jacobi_eigenvalues(dw_matrix(n)) == pytest.approx(lam, abs=1e-10)
rng = random.Random(32)
for x in (EX_X, [[1.0, rng.gauss(0, 1), rng.gauss(0, 1)] for _ in range(n)]):
p = len(x[0])
q = householder_q1(x)
m = [[(1.0 if i == j else 0.0) - math.fsum(q[i][k] * q[j][k] for k in range(p)) for j in range(n)]
for i in range(n)]
a = dw_matrix(n)
ma = [[math.fsum(m[i][k] * a[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
mam = [[math.fsum(ma[i][k] * m[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
nu = jacobi_eigenvalues(mam)[p:] # drop the p zero eigenvalues of the column space of X
for i in range(n - p):
assert lam[i + 1] - 1e-9 <= nu[i] <= lam[i + p] + 1e-9
def test_bounds_bracket_the_monte_carlo_p_value_measured():
"""For the example, P(d_L <= d) = 0.131 and P(d_U <= d) = 0.030 with 20000 draws: the bounds
test is inconclusive at 5%, while the Monte Carlo p-value 0.028 rejects. The trend regressor is
close to an eigenvector of A, so the law of d is close to that of d_U."""
d = durbin_watson(EX_X, [float(v) for v in EX_Y], reps=1).d
lo, hi = bounds_p_values(d, 12, 2, reps=4000, seed=3)
assert hi == pytest.approx(0.0296, abs=0.012)
assert lo == pytest.approx(0.131, abs=0.022)
assert hi < 0.05 < lo
def test_size_and_power_measured():
"""n = 20, X = [1, t], 5% level, B = 99. Under H0 the Monte Carlo test has exact size 0.05:
with r = 600 (4 SE about 0.036) the rate must be within 0.036 of 0.05. With AR(1) errors,
rho = 0.7, n = 30 the measured power was 0.936 with r = 1000; here r = 150 and it must be at least 0.8."""
rng = random.Random(5)
n, r = 20, 600
x = [[1, t] for t in range(n)]
rej = sum(durbin_watson(x, [rng.gauss(0.0, 1.0) for _ in range(n)], reps=99, seed=k + 1).p_value <= 0.05
for k in range(r))
assert abs(rej / r - 0.05) <= 0.036
n, r, rho = 30, 150, 0.7
x = [[1, t] for t in range(n)]
rej = 0
for k in range(r):
u = rng.gauss(0.0, 1.0) / math.sqrt(1.0 - rho * rho)
y = []
for t in range(n):
y.append(1.0 + 0.1 * t + u)
u = rho * u + rng.gauss(0.0, 1.0)
rej += durbin_watson(x, y, reps=99, seed=1000 + k).p_value <= 0.05
assert rej / r >= 0.8
def test_bad_inputs():
with pytest.raises(ValueError):
durbin_watson(EX_X, [1.0] * 11)
with pytest.raises(ValueError):
durbin_watson(EX_X, [float(t) for t in EX_T], reps=1) # a perfect fit
with pytest.raises(ValueError):
durbin_watson(EX_X, [float(v) for v in EX_Y], alternative="up")
assert dw_statistic([1.0, -1.0, 1.0, -1.0])[0] == pytest.approx(3.0)
History
Durbin and Watson (1950) defined , showed that its null law under normal errors is that of a ratio of quadratic forms whose weights depend on , and bracketed it between two laws that depend only on and . Their second paper (1951) gave the tables of and that made the test a standard part of regression output. Imhof (1961) gave a numerical method for the distribution of quadratic forms in normal variables, which made the exact p-value for a given design computable. Durbin (1970) showed that the test fails when a lagged response is a regressor and proposed the statistic for that case.
References
- J. Durbin and G. S. Watson, Testing for serial correlation in least squares regression. I, Biometrika 37(3-4), 1950, pp. 409 to 428, The whole paper (the statistic d, its null law as a ratio of quadratic forms in the eigenvalues of M A M, and the bounds d_L and d_U)
- J. Durbin and G. S. Watson, Testing for serial correlation in least squares regression. II, Biometrika 38(1-2), 1951, pp. 159 to 178, The whole paper (the tables of the bounds d_L and d_U and the approximations for the inconclusive region)
- J. P. Imhof, Computing the distribution of quadratic forms in normal variables, Biometrika 48(3-4), 1961, pp. 419 to 426, The whole paper (numerical inversion of the characteristic function, which gives the exact null distribution of d for a given X)
- J. Durbin, Testing for serial correlation in least-squares regression when some of the regressors are lagged dependent variables, Econometrica 38(3), 1970, pp. 410 to 421, The whole paper (the bias of d toward 2 when a lagged response is a regressor, and the h statistic)
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 TBDQN3 Edit this page History Report an error Markdown