Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 d=∑t≥2(et−et−1)2/∑tet2d = \sum_{t \ge 2}(e_t - e_{t-1})^2/\sum_te_t^2 from the residuals. Without correlation dd is near 2; positive correlation makes successive residuals similar and dd small, and negative correlation makes dd large. Under normal errors the null law of dd depends on the design XX but not on the coefficients or the error variance. Durbin and Watson could not tabulate a law for every XX, so they bracketed it between two laws that depend only on nn and pp; this gives the classical bounds test with its inconclusive region. Today the exact p-value for the given XX 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. y=Xb+εy = Xb + \varepsilon with XX a fixed real n×pn \times p matrix of rank p<np < n whose columns include the constant, t=1,…,nt = 1, \dots, n the time order of the rows, and errors from the stationary first-order autoregressive model εt=ρεt−1+ut\varepsilon_t = \rho\varepsilon_{t-1} + u_t with independent ut∼N(0,σ2)u_t \sim N(0, \sigma^2) and ∣ρ∣<1|\rho| < 1. The regressors must not include lagged values of yy.

Hypotheses. H0H_0: ρ=0\rho = 0, so the errors are independent N(0,σ2)N(0, \sigma^2); H1H_1: ρ>0\rho > 0. The alternatives ρ<0\rho < 0 and ρ≠0\rho \ne 0 are handled in the same way.

Statistic. With the residuals e=Mye = My, M=I−X(X⊤X)−1X⊤M = I - X(X^\top X)^{-1}X^\top, and the lag-one residual autocorrelation r1r_1:

d=∑t=2n(et−et−1)2∑t=1net2=2(1−r1)−e12+en2∑tet2,r1=∑t=2netet−1∑tet2.d = \frac{\sum_{t=2}^n(e_t - e_{t-1})^2}{\sum_{t=1}^ne_t^2} = 2(1 - r_1) - \frac{e_1^2 + e_n^2}{\sum_te_t^2}, \qquad r_1 = \frac{\sum_{t=2}^ne_te_{t-1}}{\sum_te_t^2}.

So d≈2(1−r1)d \approx 2(1 - r_1), and 0<d<40 < d < 4.

Null distribution. Under H0H_0, d=ε⊤MAMε/ε⊤Mεd = \varepsilon^\top MAM\varepsilon/\varepsilon^\top M\varepsilon, where AA is the tridiagonal matrix with e⊤Ae=∑t≥2(et−et−1)2e^\top Ae = \sum_{t \ge 2}(e_t - e_{t-1})^2. Its law depends only on XX. It is the law of ∑iνiξi2/∑iξi2\sum_i\nu_i\xi_i^2/\sum_i\xi_i^2, with ν1,…,νn−p\nu_1, \dots, \nu_{n-p} the nonzero eigenvalues of MAMMAM and independent standard normal ξi\xi_i.

Rejection rule and p-value. Against ρ>0\rho > 0, small dd is extreme. The Monte Carlo p-value is (1+#{dk∗≤d})/(1+B)(1 + \#\{d^*_k \le d\})/(1 + B), where d1∗,…,dB∗d^*_1, \dots, d^*_B are computed from BB standard normal response vectors with the same XX; reject at level α\alpha when it is at most α\alpha. This test has exact size α\alpha when α(B+1)\alpha(B + 1) is an integer. The classical bounds test compares dd with tabulated points dLd_L and dUd_U: reject if d<dLd < d_L, do not reject if d>dUd > d_U, 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 r1r_1 positive. It has little power against correlation at longer lags only, such as a seasonal pattern.

The algorithm

  1. DURBIN-WATSON(X[1..n, 1..p], y[1..n], B)
  2. 1Q₁ ← orthonormal basis of the columns of X by Householder QR; e ← y - Q₁Q₁ᵀy
  3. 2S ← Σₜ eₜ²
  4. 3D ← Σ_{t=2..n} (eₜ - eₜ₋₁)²
  5. 4d ← D / S; r₁ ← Σ_{t=2..n} eₜeₜ₋₁ / S
  6. 5for k ← 1 to B: draw ε* with independent N(0, 1) entries
  7. 6d*ₖ ← D / S of the residuals ε* - Q₁Q₁ᵀε* ▷ lines L2 to L4 again
  8. 7p ← (1 + #{k : d*ₖ ≤ d}) / (1 + B) ▷ against ρ > 0
  9. 8return (d, r₁, p)

Line L1 needs the factorization only once; every simulated sample in line L6 reuses Q1Q_1, so a sample costs Θ(np)\Theta(np). Simulated samples use σ=1\sigma = 1 and b=0b = 0; any other values give the same d∗d^*, because the statistic of ay+Xcay + Xc equals that of yy. Against ρ<0\rho < 0 the count is #{dk∗≥d}\#\{d^*_k \ge d\}, and the two-sided p-value is twice the smaller one-sided p-value, at most 1.

Example

Take t=1,…,12t = 1, \dots, 12, an intercept and a linear trend, so XX has the rows (1,t)(1, t) and p=2p = 2, and

y=(1.0,1.9,3.1,3.2,3.0,3.6,4.4,5.6,6.2,6.1,6.0,6.8).y = (1.0, 1.9, 3.1, 3.2, 3.0, 3.6, 4.4, 5.6, 6.2, 6.1, 6.0, 6.8).

The residuals of the least squares line are

e=(−0.447,−0.055,0.636,0.228,−0.480,−0.388,−0.096,0.596,0.688,0.080,−0.528,−0.236),e = (-0.447, -0.055, 0.636, 0.228, -0.480, -0.388, -0.096, 0.596, 0.688, 0.080, -0.528, -0.236),

which stay above or below zero for runs of two to four periods. Then r1=0.3329r_1 = 0.3329 and d=1.2189d = 1.2189.

method result at the 5% level
Monte Carlo p-value, B=9999B = 9999, seed 7 p=0.0278p = 0.0278, reject
bounds, P(dL≤d)P(d_L \le d) 0.131
bounds, P(dU≤d)P(d_U \le d) 0.0296
bounds test inconclusive, since 0.0296<0.05<0.1310.0296 < 0.05 < 0.131

The two bound probabilities were estimated from 20000 draws of ξ\xi (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 AA, and for such a design the law of dd is close to that of dUd_U. The bounds test gives no answer, but the test for the actual design rejects.

Measured size and power. With X=[1,t]X = [1, t] and the 5% level, B=99B = 99 for each Monte Carlo p-value:

errors nn rr rejection rate
independent N(0,1)N(0, 1) 20 600 0.037
independent N(0,1)N(0, 1) 30 2000 0.0535
AR(1), ρ=0.3\rho = 0.3 30 1000 0.401
AR(1), ρ=0.7\rho = 0.7 30 1000 0.936

The first two rows agree with the exact size 0.05 within the Monte Carlo error, about 0.009 for r=600r = 600 and 0.005 for r=2000r = 2000. The power for ρ=0.3\rho = 0.3 shows that n=30n = 30 is too short to detect weak correlation reliably.

Correctness

The proof shows four exact facts. First, the identity d=2(1−r1)−(e12+en2)/Sd = 2(1 - r_1) - (e_1^2 + e_n^2)/S, and 0<d<40 < d < 4 when the constant is a column of XX. Second, the matrix AA has the eigenvalues λj=2−2cos⁡(πj/n)\lambda_j = 2 - 2\cos(\pi j/n), j=0,…,n−1j = 0, \dots, n - 1, with λ0=0\lambda_0 = 0 for the constant vector. Third, the residuals of ay+Xcay + Xc are aeae, so under normal H0H_0 the law of dd does not depend on bb or σ\sigma; 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 νi\nu_i of AA on the residual space satisfy λi≤νi≤λi+p−1\lambda_i \le \nu_i \le \lambda_{i+p-1}, so for the same ξ\xi

dL=∑i=1n−pλiξi2∑iξi2≤d≤dU=∑i=1n−pλi+p−1ξi2∑iξi2,d_L = \frac{\sum_{i=1}^{n-p}\lambda_i\xi_i^2}{\sum_i\xi_i^2} \le d \le d_U = \frac{\sum_{i=1}^{n-p}\lambda_{i+p-1}\xi_i^2}{\sum_i\xi_i^2},

and the laws of dLd_L and dUd_U depend only on nn and pp. 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 d→2(1−ρ)d \to 2(1 - \rho) 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. XX is a fixed real n×pn \times p matrix of rank p<np < n whose columns include the constant 1\mathbf 1, M=I−X(X⊤X)−1X⊤M = I - X(X^\top X)^{-1}X^\top, and e=My≠0e = My \ne 0. Let AA be the n×nn \times n tridiagonal matrix with diagonal (1,2,…,2,1)(1, 2, \dots, 2, 1) and −1-1 next to the diagonal, so that

e⊤Ae=∑t=2n(et−et−1)2,d=e⊤Aee⊤e,r1=∑t=2netet−1e⊤e.e^\top Ae = \sum_{t=2}^n(e_t - e_{t-1})^2, \qquad d = \frac{e^\top Ae}{e^\top e}, \qquad r_1 = \frac{\sum_{t=2}^ne_te_{t-1}}{e^\top e}.

Lines L2 to L4 compute exactly these sums, and line L1 computes e=y−Q1Q1⊤ye = y - Q_1Q_1^\top y with Q1Q_1 an orthonormal basis of the columns of XX, which is MyMy.

Lemma 1 (identity and range). d=2(1−r1)−(e12+en2)/e⊤ed = 2(1 - r_1) - (e_1^2 + e_n^2)/e^\top e, and 0<d<40 < d < 4.

Proof. Expanding the squares, ∑t=2n(et−et−1)2=2e⊤e−e12−en2−2∑t=2netet−1\sum_{t=2}^n(e_t - e_{t-1})^2 = 2e^\top e - e_1^2 - e_n^2 - 2\sum_{t=2}^ne_te_{t-1}; divide by e⊤ee^\top e. For the upper bound, (a−b)2≤2a2+2b2(a - b)^2 \le 2a^2 + 2b^2 gives e⊤Ae≤4e⊤e−2e12−2en2≤4e⊤ee^\top Ae \le 4e^\top e - 2e_1^2 - 2e_n^2 \le 4e^\top e, with equality only if et=−et−1e_t = -e_{t-1} for all tt and e1=en=0e_1 = e_n = 0, that is e=0e = 0. For the lower bound, d=0d = 0 only if all ete_t are equal; since 1\mathbf 1 is a column of XX, 1⊤e=0\mathbf 1^\top e = 0, so they would all be 0. □\square

Lemma 2 (the eigenvalues of A). AA has the eigenvalues λj=2−2cos⁡(πj/n)\lambda_j = 2 - 2\cos(\pi j/n), j=0,…,n−1j = 0, \dots, n - 1, with eigenvectors vt(j)=cos⁡(πj(t−12)/n)v^{(j)}_t = \cos(\pi j(t - \frac12)/n). In particular λ0=0\lambda_0 = 0 with eigenvector 1\mathbf 1.

Proof. Let θ=πj/n\theta = \pi j/n and at=θ(t−12)a_t = \theta(t - \frac12). For 2≤t≤n−12 \le t \le n - 1, 2vt−vt−1−vt+1=2cos⁡at−2cos⁡atcos⁡θ=(2−2cos⁡θ)vt2v_t - v_{t-1} - v_{t+1} = 2\cos a_t - 2\cos a_t\cos\theta = (2 - 2\cos\theta)v_t. For t=1t = 1, v1−v2=cos⁡θ2−cos⁡3θ2v_1 - v_2 = \cos\frac\theta2 - \cos\frac{3\theta}2, and (2−2cos⁡θ)cos⁡θ2=2cos⁡θ2−cos⁡3θ2−cos⁡θ2(2 - 2\cos\theta)\cos\frac\theta2 = 2\cos\frac\theta2 - \cos\frac{3\theta}2 - \cos\frac\theta2, the same. For t=nt = n, vn−vn−1=(2−2cos⁡θ)vnv_n - v_{n-1} = (2 - 2\cos\theta)v_n follows in the same way, because cos⁡(πj+θ2)=cos⁡(πj−θ2)\cos(\pi j + \frac\theta2) = \cos(\pi j - \frac\theta2). The λj\lambda_j are distinct, so these are all the eigenvalues. □\square

Lemma 3 (the null law does not depend on b or sigma). For a≠0a \ne 0 and c∈Rpc \in \mathbb R^p, the statistic of ay+Xcay + Xc equals that of yy. Under H0H_0, y=Xb+σε0y = Xb + \sigma\varepsilon_0 with ε0∼N(0,In)\varepsilon_0 \sim N(0, I_n), so

d=ε0⊤MAMε0ε0⊤Mε0,d = \frac{\varepsilon_0^\top MAM\varepsilon_0}{\varepsilon_0^\top M\varepsilon_0},

whose law depends only on XX. Hence the Monte Carlo p-value (1+#{d∗≤d})/(1+B)(1 + \#\{d^* \le d\})/(1 + B) of lines L5 to L7, with d∗d^* computed from standard normal vectors, has P(p≤α)=αP(p \le \alpha) = \alpha under H0H_0 whenever α(B+1)\alpha(B + 1) is an integer.

Proof. M(ay+Xc)=aMy=aeM(ay + Xc) = aMy = ae, and dd is unchanged when ee is multiplied by a≠0a \ne 0. With y=Xb+σε0y = Xb + \sigma\varepsilon_0, e=σMε0e = \sigma M\varepsilon_0, and σ\sigma cancels. The observed dd and the BB simulated d∗d^* are then independent with the same continuous law, so they are exchangeable and have no ties with probability 1. The rank of dd among the B+1B + 1 values is uniform on {1,…,B+1}\{1, \dots, B + 1\}, and p≤αp \le \alpha exactly when that rank is at most α(B+1)\alpha(B + 1). □\square

Lemma 4 (the bounds). Let ν1≤⋯≤νn−p\nu_1 \le \dots \le \nu_{n-p} be the eigenvalues of AA restricted to the orthogonal complement WW of the columns of XX. Then under H0H_0, dd has the law of ∑iνiξi2/∑iξi2\sum_i\nu_i\xi_i^2/\sum_i\xi_i^2 with ξ1,…,ξn−p\xi_1, \dots, \xi_{n-p} independent standard normal, and

λi≤νi≤λi+p−1,i=1,…,n−p.\lambda_i \le \nu_i \le \lambda_{i+p-1}, \qquad i = 1, \dots, n - p.

So with dL=∑iλiξi2/∑iξi2d_L = \sum_i\lambda_i\xi_i^2/\sum_i\xi_i^2 and dU=∑iλi+p−1ξi2/∑iξi2d_U = \sum_i\lambda_{i+p-1}\xi_i^2/\sum_i\xi_i^2 built from the same ξ\xi, dL≤d≤dUd_L \le d \le d_U, and P(dU≤c)≤P(d≤c)≤P(dL≤c)P(d_U \le c) \le P(d \le c) \le P(d_L \le c) for every cc.

Proof. Let UU be an n×(n−p)n \times (n - p) matrix whose orthonormal columns span WW and diagonalize U⊤AU=diag⁡(ν)U^\top AU = \operatorname{diag}(\nu). Then M=UU⊤M = UU^\top, and with ξ=U⊤ε0∼N(0,In−p)\xi = U^\top\varepsilon_0 \sim N(0, I_{n-p}), ε0⊤Mε0=ξ⊤ξ\varepsilon_0^\top M\varepsilon_0 = \xi^\top\xi and ε0⊤MAMε0=ξ⊤U⊤AUξ=∑iνiξi2\varepsilon_0^\top MAM\varepsilon_0 = \xi^\top U^\top AU\xi = \sum_i\nu_i\xi_i^2. Since 1\mathbf 1 is an eigenvector of the symmetric AA, the space 1⊥\mathbf 1^\perp is invariant, and AA on it has the eigenvalues λ1≤⋯≤λn−1\lambda_1 \le \dots \le \lambda_{n-1} by Lemma 2. WW is a subspace of 1⊥\mathbf 1^\perp of codimension p−1p - 1, so the Cauchy interlacing theorem (a consequence of the Courant-Fischer minimax characterization) gives λi≤νi≤λi+p−1\lambda_i \le \nu_i \le \lambda_{i+p-1}. Each ratio is a weighted mean of its eigenvalues with the same weights ξi2/∑ξ2\xi_i^2/\sum\xi^2, so the order carries over to dL≤d≤dUd_L \le d \le d_U, and then to the distribution functions. □\square

The laws of dLd_L and dUd_U depend only on nn and pp, 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 P(∑i(νi−c)ξi2≤0)P(\sum_i(\nu_i - c)\xi_i^2 \le 0) 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 ρ\rho and the design is regular, r1→ρr_1 \to \rho and d→2(1−ρ)d \to 2(1 - \rho) 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 pp steps and one projection, lines L2 to L4 are three sums, and the loop of lines L5 and L6 runs BB times with Θ(np)\Theta(np) work each: Θ(np2+Bnp)\Theta(np^2 + Bnp) operations.

Complexity

The Householder factorization in line L1 costs Θ(np2)\Theta(np^2), and lines L2 to L4 cost Θ(n)\Theta(n). Each of the BB simulated samples needs one projection, Θ(np)\Theta(np), so the total is Θ(np2+Bnp)\Theta(np^2 + Bnp) time and Θ(np)\Theta(np) extra space for Q1Q_1. The statistic alone, without a p-value, costs Θ(np2)\Theta(np^2). The exact law by Imhof's method needs the n−pn - p eigenvalues νi\nu_i, which costs Θ(n3)\Theta(n^3) 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 XX that contains the constant, with no table and no inconclusive region.
  • Invariance. dd is unchanged by y→ay+Xcy \to ay + Xc for a≠0a \ne 0, so the unknown bb and σ\sigma do not matter.
  • Range and centre. 0<d<40 < d < 4. Under H0H_0 the mean of dd is ∑iνi/(n−p)=tr⁡(MA)/(n−p)\sum_i\nu_i/(n - p) = \operatorname{tr}(MA)/(n - p), which is near 2 for large nn.
  • 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 nn; this was not measured here.

Variants and improvements

  • Bounds test. The original form uses the tabulated dLd_L and dUd_U for given nn and pp. It needs no computation of the law but has an inconclusive region, which is wide for small nn, as the example shows.
  • Exact p-value by quadratic forms. Compute the eigenvalues νi\nu_i of MAMMAM and evaluate P(∑i(νi−d)ξi2≤0)P(\sum_i(\nu_i - d)\xi_i^2 \le 0) 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 4−d4 - d against ρ<0\rho < 0, or double the smaller one-sided p-value.
  • Lagged dependent variables. When yt−1y_{t-1} is a regressor, dd is biased toward 2 and the test loses power. Durbin (1970) gave the hh statistic and an alternative test that regresses ete_t on et−1e_{t-1} and the regressors.
  • Higher lags. To test several lags at once, regress ete_t on XX and et−1,…,et−me_{t-1}, \dots, e_{t-m} 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 dd 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 dd is biased toward 2 and can hide strong correlation; use Durbin's hh or the lagged-residual regression.
  • No intercept. The bounds dLd_L and dUd_U in the tables assume a constant column; without it they do not apply. The Monte Carlo version works for any XX, but the range result d>0d > 0 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 XX.
  • A low dd from a wrong mean. A missing trend, a missing seasonal term or a nonlinear effect leaves runs of residuals of the same sign, and dd 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 nn. With n=30n = 30 the power against ρ=0.3\rho = 0.3 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.

durbin_watson_core.pyI0RawGitHub
# 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 dd, showed that its null law under normal errors is that of a ratio of quadratic forms whose weights depend on XX, and bracketed it between two laws that depend only on nn and pp. Their second paper (1951) gave the tables of dLd_L and dUd_U 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 hh statistic for that case.

References

  1. 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)
  2. 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)
  3. 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)
  4. 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.

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