Algorithm Search⌘K

Algorithmcore

Ljung-Box test

Also called Ljung-Box Q test, portmanteau test.

Tests whether the first h autocorrelations of a series or of model residuals are jointly zero by a weighted sum of their squares, which is approximately chi-squared under IID noise.

Time
Θ(n h) worst · best
Space
Θ(n) extra
Where
h = the number of lags tested; n = the length of the series
Properties
deterministicnot exactofflineiterative
Origin
Greta M. Ljung, George E. P. Box, David A. Pierce, 1978

The Ljung-Box test asks whether a series has no autocorrelation at lags 11 to hh. Its main use is to check the residuals of a fitted ARMA model: if the model is right, the residuals should look like IID noise. The statistic is Q=n(n+2)∑k=1hr^k2/(n−k)Q = n(n + 2)\sum_{k=1}^{h} \hat r_k^2/(n - k), a weighted sum of the squared sample autocorrelations. Under the null it is approximately chi-squared with hh degrees of freedom for a raw series, and with h−p−qh - p - q for the residuals of an ARMA(pp, qq) fit. It tests all hh lags at once, so it is called a portmanteau test. It replaces the older Box-Pierce statistic n∑r^k2n\sum \hat r_k^2, whose size is too small for short series. Both tests are approximate.

In plain words

If a model has captured all the structure in a series, what is left over should be pure noise: knowing one leftover value should tell you nothing about the next one, or the one after that. Measure how strongly the leftovers are related at each delay from 1 to hh steps. Square these numbers so that positive and negative relations both count, and add them up with a slightly larger weight on the longer delays. If the total is much larger than chance would give, the model has missed something. A single test covers all hh delays, so you do not have to look at each one alone.

The problem

Model. A series e1,…,ene_1, \ldots, e_n. In the main use, ete_t are the residuals of an ARMA(pp, qq) model fitted by maximum likelihood or least squares, and s=p+qs = p + q coefficients were estimated. For a raw series, s=0s = 0.

Hypotheses. H0H_0: the errors of the model are IID with finite variance (for a raw series, e1,…,ene_1, \ldots, e_n are IID). The alternative is any autocorrelation at lags 11 to hh. The test has no power against dependence that leaves all these autocorrelations at 0.

Statistic. With eˉ\bar e the mean and r^k=∑t=k+1n(et−eˉ)(et−k−eˉ)/∑t=1n(et−eˉ)2\hat r_k = \sum_{t=k+1}^{n}(e_t - \bar e)(e_{t-k} - \bar e)/\sum_{t=1}^n (e_t - \bar e)^2,

QLB=n(n+2)∑k=1hr^k2n−k,QBP=n∑k=1hr^k2.Q_{\mathrm{LB}} = n(n + 2)\sum_{k=1}^{h}\frac{\hat r_k^2}{n - k}, \qquad Q_{\mathrm{BP}} = n\sum_{k=1}^{h}\hat r_k^2 .

Null distribution. Asymptotic only. For an IID series with finite variance and fixed hh, n(r^1,…,r^h)→N(0,Ih)\sqrt{n}(\hat r_1, \ldots, \hat r_h) \to N(0, I_h), so both statistics tend to χh2\chi^2_h (proved in proofs/correctness.md). For residuals of a fitted ARMA(pp, qq) model, the law of QQ is approximately χh−p−q2\chi^2_{h - p - q} when hh is large and h/nh/n is small (Box and Pierce 1970). This is an approximation, not a limit theorem for fixed hh.

Rejection rule and size. Reject when Q≥χ(h−s, 1−α)2Q \ge \chi^2_{(h - s,\ 1 - \alpha)}, the upper α\alpha point. The size tends to α\alpha for a raw IID series. For finite nn it is not controlled: the measured sizes below show QLBQ_{\mathrm{LB}} a little above α\alpha and QBPQ_{\mathrm{BP}} below it.

P-values. p=P(χh−s2>Q)p = P(\chi^2_{h - s} > Q), the upper tail only.

Sensitivity and power. The test spreads its power over hh lags. Against a departure at lag 1 alone, a large hh adds noise from lags that carry no signal, and the power falls. A small hh misses seasonal or long-lag structure. A common choice is hh near log⁡n\log n or min⁡(10,n/5)\min(10, n/5), and h=2sh = 2s or 3s3s for seasonal period ss, but there is no rule that is best for all alternatives.

The algorithm

  1. LJUNG-BOX(e[1..n], h, s)
  2. 1ē ← (e[1] + ... + e[n]) / n
  3. 2c0 ← Σ_{t=1}^{n} (e[t] - ē)²
  4. 3for k ← 1 to h do r[k] ← Σ_{t=k+1}^{n} (e[t] - ē)(e[t-k] - ē) / c0
  5. 4Q ← n(n + 2) · Σ_{k=1}^{h} r[k]² / (n - k) ▷ Box-Pierce: Q ← n · Σ r[k]²
  6. 5df ← h - s ▷ s = p + q fitted ARMA coefficients
  7. 6return (Q, df, P(χ²_df > Q))

The caller passes the residuals and the number ss of fitted ARMA coefficients (fitted in the code). The mean, a regression intercept or a drift is not counted in ss. The code computes the Box-Pierce statistic with statistic="box-pierce". Line L6 uses chi2_sf from the shared helper module, the regularized upper incomplete gamma function Q(df/2,Q/2)Q(\mathrm{df}/2, Q/2). The code raises an error if h≥nh \ge n, if h≤sh \le s, or if the series is constant.

Example

Take the ten values e=(3,5,6,4,2,1,3,6,7,5)e = (3, 5, 6, 4, 2, 1, 3, 6, 7, 5) as a raw series and test h=3h = 3 lags. The mean is eˉ=4.2\bar e = 4.2 and ∑(et−eˉ)2=33.6\sum (e_t - \bar e)^2 = 33.6.

kk r^k\hat r_k r^k2\hat r_k^2 Ljung-Box weight n(n+2)/(n−k)n(n + 2)/(n - k) Box-Pierce weight nn
1 69/140=0.492969/140 = 0.4929 0.2429 13.33 10
2 −89/280=−0.3179-89/280 = -0.3179 0.1010 15.00 10
3 −523/840=−0.6226-523/840 = -0.6226 0.3877 17.14 10

Then QLB=11.3998Q_{\mathrm{LB}} = 11.3998 on 3 degrees of freedom, with p=0.0097p = 0.0097, and QBP=7.3160Q_{\mathrm{BP}} = 7.3160, with p=0.0625p = 0.0625. The Ljung-Box test rejects at α=0.05\alpha = 0.05 and the Box-Pierce test does not. With n=10n = 10 neither chi-square approximation is reliable; the example only shows how much the weights matter for a short series. The tests check the three autocorrelations against these fractions, and both statistics against an exact Fraction computation on random integer series.

Correctness

The full proof is in proofs/correctness.md. For IID ete_t with mean μ\mu and variance σ2\sigma^2, the products (et−μ)(et−k−μ)(e_t - \mu)(e_{t-k} - \mu), k=1,…,hk = 1, \ldots, h, form a stationary martingale difference sequence with covariance σ4Ih\sigma^4 I_h. The martingale central limit theorem gives n(r^1,…,r^h)→N(0,Ih)\sqrt{n}(\hat r_1, \ldots, \hat r_h) \to N(0, I_h), after showing that replacing μ\mu by eˉ\bar e changes nothing in the limit. So QBP→χh2Q_{\mathrm{BP}} \to \chi^2_h, and QLB−QBP→0Q_{\mathrm{LB}} - Q_{\mathrm{BP}} \to 0 in probability. The proof also gives the reason for the weights: for IID normal data with known mean 0 (no centering), Var(r^k)=(n−k)/(n(n+2))\mathrm{Var}(\hat r_k) = (n - k)/(n(n + 2)) exactly and the r^k\hat r_k are uncorrelated, so E[QLB]=h\mathbb{E}[Q_{\mathrm{LB}}] = h exactly, while E[QBP]=∑k=1h(n−k)/(n+2)<h\mathbb{E}[Q_{\mathrm{BP}}] = \sum_{k=1}^{h}(n - k)/(n + 2) < h. For n=30n = 30 and h=10h = 10, E[QBP]=245/32=7.66\mathbb{E}[Q_{\mathrm{BP}}] = 245/32 = 7.66 instead of 10, so its size is too small. The degrees of freedom h−p−qh - p - q for residuals are cited from Box and Pierce (1970), not proved.

Proof: For an IID series the Ljung-Box and Box-Pierce statistics tend to chi-square with h degrees of freedom, and the Ljung-Box weights make the mean exactly h for normal noisefull

Setting. e1,…,ene_1, \ldots, e_n is a series and 1≤h<n1 \le h < n. Write eˉ=1n∑tet\bar e = \frac1n\sum_t e_t, c0=∑t=1n(et−eˉ)2c_0 = \sum_{t=1}^n (e_t - \bar e)^2, ck=∑t=k+1n(et−eˉ)(et−k−eˉ)c_k = \sum_{t=k+1}^{n}(e_t - \bar e)(e_{t-k} - \bar e), r^k=ck/c0\hat r_k = c_k/c_0, and

QLB=n(n+2)∑k=1hr^k2n−k,QBP=n∑k=1hr^k2.Q_{\mathrm{LB}} = n(n + 2)\sum_{k=1}^{h}\frac{\hat r_k^2}{n - k}, \qquad Q_{\mathrm{BP}} = n\sum_{k=1}^{h}\hat r_k^2 .

Claim 1 (lines L1 to L6 compute the statistic). Line L1 computes eˉ\bar e, line L2 computes c0c_0 and line L3 computes r^1,…,r^h\hat r_1, \ldots, \hat r_h. Line L4 computes QLBQ_{\mathrm{LB}} (or QBPQ_{\mathrm{BP}}), line L5 sets df=h−s\mathrm{df} = h - s, and line L6 returns P(χdf2>Q)P(\chi^2_{\mathrm{df}} > Q) from the regularized upper incomplete gamma function of the helper module.

Proof. Each line is the formula above. The sums use math.fsum, so the only rounding is in the individual terms. The code rejects a constant series, for which c0=0c_0 = 0, and h≥nh \ge n, for which some n−k≤0n - k \le 0. □\square

Claim 2 (exact moments for normal noise with known mean). Let e1,…,ene_1, \ldots, e_n be IID N(0,σ2)N(0, \sigma^2) and define rk=∑t=k+1netet−k/∑t=1net2r_k = \sum_{t=k+1}^n e_t e_{t-k} / \sum_{t=1}^n e_t^2, the autocorrelation without centering. Then E[rk]=0\mathbb{E}[r_k] = 0, Var(rk)=(n−k)/(n(n+2))\mathrm{Var}(r_k) = (n - k)/(n(n + 2)), and Cov(rj,rk)=0\mathrm{Cov}(r_j, r_k) = 0 for j≠kj \ne k. Hence, with rkr_k in place of r^k\hat r_k,

E[QLB]=h,E[QBP]=∑k=1hn−kn+2=h(2n−h−1)2(n+2)<h.\mathbb{E}[Q_{\mathrm{LB}}] = h, \qquad \mathbb{E}[Q_{\mathrm{BP}}] = \sum_{k=1}^{h}\frac{n - k}{n + 2} = \frac{h(2n - h - 1)}{2(n + 2)} < h.

Proof. The vector ee has a spherically symmetric law, so U=e/∥e∥U = e/\lVert e \rVert is uniform on the unit sphere of Rn\mathbb{R}^n, and rk=∑t=k+1nUtUt−kr_k = \sum_{t=k+1}^n U_t U_{t-k}. The law of UU does not change when one coordinate changes sign, so a moment E[UaUbUcUd]\mathbb{E}[U_a U_b U_c U_d] is 0 unless every index appears an even number of times. For the uniform law on the sphere, E[Ua2Ub2]=1/(n(n+2))\mathbb{E}[U_a^2 U_b^2] = 1/(n(n + 2)) for a≠ba \ne b. (Proof: by symmetry E[Ua4]=A\mathbb{E}[U_a^4] = A and E[Ua2Ub2]=B\mathbb{E}[U_a^2U_b^2] = B do not depend on a≠ba \ne b. From ∥U∥=1\lVert U \rVert = 1, nA+n(n−1)B=1nA + n(n - 1)B = 1. For a standard normal vector ZZ, Z=∥Z∥UZ = \lVert Z \rVert U with ∥Z∥\lVert Z \rVert independent of UU and E∥Z∥4=n(n+2)\mathbb{E}\lVert Z \rVert^4 = n(n + 2), so 3=EZa4=n(n+2)A3 = \mathbb{E}Z_a^4 = n(n + 2)A and 1=EZa2Zb2=n(n+2)B1 = \mathbb{E}Z_a^2 Z_b^2 = n(n + 2)B.) Each term UtUt−kU_t U_{t-k} has two different indices, so E[rk]=0\mathbb{E}[r_k] = 0. In

E[rjrk]=∑t=k+1n∑s=j+1nE[UtUt−kUsUs−j],\mathbb{E}[r_j r_k] = \sum_{t=k+1}^{n}\sum_{s=j+1}^{n}\mathbb{E}[U_t U_{t-k} U_s U_{s-j}],

a term is nonzero only if {t,t−k}={s,s−j}\{t, t-k\} = \{s, s-j\} as sets. The case t=s−jt = s - j, t−k=st - k = s gives j+k=0j + k = 0, which is impossible. The case t=st = s, t−k=s−jt - k = s - j needs j=kj = k. So the covariance is 0 for j≠kj \ne k, and for j=kj = k the n−kn - k terms with s=ts = t each give 1/(n(n+2))1/(n(n + 2)). Then E[QLB]=n(n+2)∑kn−kn(n+2)(n−k)=h\mathbb{E}[Q_{\mathrm{LB}}] = n(n + 2)\sum_k \frac{n - k}{n(n + 2)(n - k)} = h, and E[QBP]=n∑kn−kn(n+2)\mathbb{E}[Q_{\mathrm{BP}}] = n\sum_k \frac{n - k}{n(n + 2)}. □\square

This is the reason for the weights (n+2)/(n−k)(n + 2)/(n - k). The code centres the series at eˉ\bar e, which changes the moments by terms of order 1/n1/n, so for the centred statistic the claim is an approximation. For n=30n = 30 and h=10h = 10, E[QBP]=245/32=7.66\mathbb{E}[Q_{\mathrm{BP}}] = 245/32 = 7.66, far below the mean 10 of χ102\chi^2_{10}.

Claim 3 (joint limit of the autocorrelations). Let e1,e2,…e_1, e_2, \ldots be IID with mean μ\mu and variance σ2∈(0,∞)\sigma^2 \in (0, \infty), and fix hh. Then n(r^1,…,r^h)→N(0,Ih)\sqrt{n}(\hat r_1, \ldots, \hat r_h) \to N(0, I_h) in distribution.

Proof. Put dt=et−μd_t = e_t - \mu. Fix λ∈Rh\lambda \in \mathbb{R}^h and let Yt=dt∑k=1hλkdt−kY_t = d_t \sum_{k=1}^h \lambda_k d_{t-k} for t>ht > h. The sequence (Yt)(Y_t) is strictly stationary and hh-dependent, because YtY_t is a function of dt−h,…,dtd_{t-h}, \ldots, d_t. Its mean is 0, since dtd_t is independent of the other factors. Its variance is E[dt2] E[(∑kλkdt−k)2]=σ4∥λ∥2\mathbb{E}[d_t^2]\,\mathbb{E}[(\sum_k \lambda_k d_{t-k})^2] = \sigma^4\lVert\lambda\rVert^2. For j≥1j \ge 1, E[YtYt+j]=0\mathbb{E}[Y_t Y_{t+j}] = 0, because dt+jd_{t+j} appears once in the product and is independent of all the other factors, whose indices are smaller. The central limit theorem for strictly stationary mm-dependent sequences with finite variance (Brockwell and Davis 1991, Chapter 6) gives n−1/2∑t=h+1nYt→N(0,σ4∥λ∥2)n^{-1/2}\sum_{t=h+1}^{n} Y_t \to N(0, \sigma^4\lVert\lambda\rVert^2). The terms with t≤ht \le h in ∑tdtdt−k\sum_t d_t d_{t-k} are a fixed number of Op(1)O_p(1) terms, so by the Cramér-Wold device

n−1/2(∑t=k+1ndtdt−k)k=1h→N(0,σ4Ih).n^{-1/2}\Big(\sum_{t=k+1}^n d_t d_{t-k}\Big)_{k=1}^{h} \to N(0, \sigma^4 I_h).

Next, the centering. With δ=eˉ−μ\delta = \bar e - \mu,

ck=∑t=k+1ndtdt−k−δ(∑t=k+1ndt+∑t=1n−kdt)+(n−k)δ2.c_k = \sum_{t=k+1}^n d_t d_{t-k} - \delta\Big(\sum_{t=k+1}^n d_t + \sum_{t=1}^{n-k} d_t\Big) + (n - k)\delta^2 .

By Chebyshev's inequality, δ=Op(n−1/2)\delta = O_p(n^{-1/2}) and the two partial sums are Op(n1/2)O_p(n^{1/2}), so the last two terms are Op(1)O_p(1) and vanish after division by n\sqrt{n}. Finally c0/n=1n∑tdt2−δ2→σ2c_0/n = \frac1n\sum_t d_t^2 - \delta^2 \to \sigma^2 almost surely by the strong law of large numbers. By Slutsky's lemma, n r^k=(n−1/2ck)/(c0/n)\sqrt{n}\,\hat r_k = (n^{-1/2}c_k)/(c_0/n) has the joint limit N(0,σ4Ih)/σ2=N(0,Ih)N(0, \sigma^4 I_h)/\sigma^2 = N(0, I_h). □\square

Claim 4 (the size tends to α\alpha for a raw series). Under the hypotheses of Claim 3, QBP→χh2Q_{\mathrm{BP}} \to \chi^2_h and QLB→χh2Q_{\mathrm{LB}} \to \chi^2_h in distribution. So with s=0s = 0, the test that rejects when Q≥χ(h, 1−α)2Q \ge \chi^2_{(h,\,1-\alpha)} has size tending to α\alpha, for either statistic.

Proof. QBP=∥n r^∥2Q_{\mathrm{BP}} = \lVert \sqrt{n}\,\hat r \rVert^2 is a continuous function of n r^\sqrt{n}\,\hat r, so by Claim 3 and the continuous mapping theorem it tends to the squared length of an N(0,Ih)N(0, I_h) vector, which is χh2\chi^2_h. Next,

QLB−QBP=∑k=1hnr^k2(n+2n−k−1)=∑k=1hnr^k2 k+2n−k,Q_{\mathrm{LB}} - Q_{\mathrm{BP}} = \sum_{k=1}^h n\hat r_k^2\Big(\frac{n + 2}{n - k} - 1\Big) = \sum_{k=1}^h n\hat r_k^2\,\frac{k + 2}{n - k},

where nr^k2=Op(1)n\hat r_k^2 = O_p(1) and (k+2)/(n−k)→0(k + 2)/(n - k) \to 0. So the difference tends to 0 in probability, and QLBQ_{\mathrm{LB}} has the same limit. The χh2\chi^2_h law is continuous, so P(Q≥χ(h, 1−α)2)→αP(Q \ge \chi^2_{(h,\,1-\alpha)}) \to \alpha. □\square

The tests check Claim 1 against an exact Fraction computation of QLBQ_{\mathrm{LB}} and QBPQ_{\mathrm{BP}} on random integer series and on the worked example, the helper chi2_sf against the closed forms for 1 and 2 degrees of freedom, and Claim 4 by Monte Carlo sizes for IID normal series.

Cited, not proved here. For the residuals of an ARMA(pp, qq) model fitted by an efficient method, n(r^1,…,r^h)\sqrt{n}(\hat r_1, \ldots, \hat r_h) tends to a normal law with covariance Ih−JI_h - J, where JJ is a projection of rank p+qp + q when hh is large. Hence QQ is approximately χh−p−q2\chi^2_{h - p - q} (Box and Pierce 1970; Brockwell and Davis 1991, Section 9.4). For fixed hh the limit is a weighted sum of chi-square variables, not exactly χh−p−q2\chi^2_{h - p - q}. The page measures the size of this approximation for AR(1) residuals.

Complexity

Lines L1 and L2 take Θ(n)\Theta(n) time and L3 takes Θ(nh)\Theta(n h), so the test takes Θ(nh)\Theta(n h) time. The code keeps the centred series, Θ(n)\Theta(n) extra space. For many lags, all n−1n - 1 autocorrelations can be computed in O(nlog⁡n)O(n \log n) with a fast Fourier transform of the zero-padded series. The p-value is one evaluation of the incomplete gamma function. In practice the cost of the test is small next to the cost of fitting the model.

Properties

  • Size for a raw IID series (measured). IID N(0,1)N(0, 1) series, h=10h = 10, 10 degrees of freedom, α=0.05\alpha = 0.05, 4000 series per row (seed 11). The Monte Carlo standard error is about 0.0035.

    nn size of Ljung-Box size of Box-Pierce
    30 0.0785 0.0270
    50 0.0668 0.0353
    100 0.0553 0.0370
    200 0.0535 0.0455

    Both sizes approach 0.05. The Ljung-Box test is a little liberal for small nn, and the Box-Pierce test is conservative.

  • Residuals of a fitted AR(1) (measured). AR(1) series with n=100n = 100, fitted by the Yule-Walker equations, h=10h = 10, α=0.05\alpha = 0.05 (seed 12):

    true ϕ\phi Ljung-Box, df 9 Ljung-Box, df 10 Box-Pierce, df 9
    0.5 0.0450 0.0295 0.0278
    0.9 0.0498 0.0333 0.0338

    With the correct h−p=9h - p = 9 degrees of freedom, the Ljung-Box size is close to 0.05. With the raw-series value of 10, the test is conservative, because fitting a parameter makes the residual autocorrelations at small lags smaller than for IID noise.

  • Power depends on hh (measured). Raw AR(1) series with ϕ=0.2\phi = 0.2, n=100n = 100, α=0.05\alpha = 0.05 (seed 13): the power was 0.461 for h=1h = 1, 0.263 for h=5h = 5, 0.207 for h=10h = 10 and 0.199 for h=20h = 20. All the signal is at lag 1, so each extra lag only adds noise.

  • Invariant to scale and location. Adding a constant to the series or multiplying it by a nonzero constant does not change r^k\hat r_k, so QQ does not depend on μ\mu or σ\sigma.

  • Not consistent against all dependence. A process with ρ(1)=⋯=ρ(h)=0\rho(1) = \cdots = \rho(h) = 0 but dependence in the squares, such as an ARCH or GARCH process, has power close to α\alpha. Apply the test to the squared residuals to detect it.

Variants and improvements

  • Box-Pierce statistic. n∑r^k2n \sum \hat r_k^2, the original form. It has the same limit, but its size is too small in short series. The code computes it with statistic="box-pierce".
  • McLeod-Li test. The same statistic computed on the squared residuals, as a check for conditional heteroscedasticity (McLeod and Li 1983).
  • Multivariate portmanteau test. For vector series of dimension dd, Hosking (1980) and Li and McLeod (1981) replaced r^k2\hat r_k^2 by tr⁡(C^k⊤C^0−1C^kC^0−1)\operatorname{tr}(\hat C_k^\top \hat C_0^{-1} \hat C_k \hat C_0^{-1}), with C^k\hat C_k the residual autocovariance matrices, and $h d^2 - $ (number of fitted coefficients) degrees of freedom.
  • Partial autocorrelation form. Monti (1994) used the residual partial autocorrelations in the same weighted sum. It can have more power against MA alternatives.
  • Lagrange multiplier test. The score test of the fitted model against a larger ARMA model is aimed at one direction and is often more powerful against that direction. Breusch and Godfrey gave a regression form for the residuals of a regression model.
  • Monte Carlo p-value. For a short series, simulate the fitted model many times, refit it to each simulated series, compute QQ, and use (1+count)/(1+B)(1 + \text{count})/(1 + B). This removes the error of the chi-square approximation at the cost of BB refits.

When to use it

Use it as the standard residual check in the Box-Jenkins method, together with a plot of the residual autocorrelations with bands of ±1.96/n\pm 1.96/\sqrt{n}, and as a quick test that a raw series has no autocorrelation. A large p-value says only that the test did not detect a misfit at lags 11 to hh. For regression residuals with a fixed design and no lagged dependent variable, the Durbin-Watson test tests lag 1, and its null law can be computed exactly for the given design. For volatility clustering, test the squared residuals.

Pitfalls

  • Degrees of freedom. Use h−p−qh - p - q for the residuals of an ARMA(pp, qq) fit, not hh. The mean, a constant and regression coefficients on exogenous variables are not counted, and the h−p−qh - p - q rule is itself only an approximation that needs hh well above p+qp + q.
  • Residuals of a regression with a lagged dependent variable. The chi-square approximation can be poor. A Lagrange multiplier test is better there.
  • Looking at many values of hh. Reporting the smallest p-value over h=1,…,20h = 1, \ldots, 20 is a multiple-testing problem. Choose hh before looking, or adjust with a Bonferroni correction.
  • Too large an hh. The power falls as hh grows, and the chi-square approximation needs hh much smaller than nn.
  • Reading a large p-value as proof of the model. Many models can pass the test, and the test does not see dependence in the squares, a change of variance over time, or a nonlinear structure.
  • Using the divisor n−kn - k in r^k\hat r_k. The formula above uses the divisor nn, as in Ljung and Box (1978). Other conventions change QQ for short series.

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.

ljung_box.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ljung-box-test/. The authors are listed in prov/NPBB3C.jsonl.

"""The Ljung-Box portmanteau test, with the Box-Pierce statistic as an option.

The sample autocorrelations use the divisor-n autocovariances, as in Ljung and Box (1978).
The p-value is the upper tail of the chi-square law with h - fitted degrees of freedom,
from the shared helper module.
"""

from __future__ import annotations

import math
from typing import Sequence

from stdist import chi2_sf


def residual_autocorrelations(e: Sequence[float], h: int) -> list[float]:
    """r_1, ..., r_h of the series e, centred at its mean, with the divisor-n convention."""
    n = len(e)
    if not 1 <= h < n:
        raise ValueError("need 1 <= h < n")
    m = math.fsum(e) / n  # @line L1
    d = [x - m for x in e]
    c0 = math.fsum(x * x for x in d)  # @line L2
    if c0 == 0.0:
        raise ValueError("the series is constant")
    return [math.fsum(d[t] * d[t - k] for t in range(k, n)) / c0 for k in range(1, h + 1)]  # @line L3


def ljung_box(e: Sequence[float], h: int, fitted: int = 0,
              statistic: str = "ljung-box") -> tuple[float, int, float]:
    """Return (Q, df, p) for the first h residual autocorrelations.

    fitted is the number of ARMA coefficients p + q estimated before the residuals were
    formed (0 for a raw series). statistic is "ljung-box" or "box-pierce".
    """
    n = len(e)
    r = residual_autocorrelations(e, h)
    if statistic == "ljung-box":
        q = n * (n + 2) * math.fsum(r[k - 1] ** 2 / (n - k) for k in range(1, h + 1))  # @line L4
    elif statistic == "box-pierce":
        q = n * math.fsum(rk * rk for rk in r)
    else:
        raise ValueError("statistic must be 'ljung-box' or 'box-pierce'")
    df = h - fitted  # @line L5
    if df < 1:
        raise ValueError("need h > fitted")
    return q, df, chi2_sf(q, df)  # @line L6
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
ljung_box_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ljung-box-test/. The authors are listed in prov/NPBB3C.jsonl.

"""Entry point named after the slug. The code lives in ljung_box.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from ljung_box import ljung_box, residual_autocorrelations

__all__ = ["ljung_box", "residual_autocorrelations"]
test_ljung_box_test.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ljung-box-test/. The authors are listed in prov/NPBB3C.jsonl.

import math
import random
from fractions import Fraction

import pytest

from ljung_box_test import ljung_box, residual_autocorrelations
from stdist import chi2_ppf, chi2_sf


def exact_q(x: list[int], h: int) -> tuple[Fraction, Fraction]:
    """Ljung-Box and Box-Pierce statistics in exact rational arithmetic (the reference)."""
    n = len(x)
    m = Fraction(sum(x), n)
    d = [Fraction(v) - m for v in x]
    c0 = sum(v * v for v in d)
    r = [sum(d[t] * d[t - k] for t in range(k, n)) / c0 for k in range(1, h + 1)]
    lb = n * (n + 2) * sum(r[k - 1] ** 2 / (n - k) for k in range(1, h + 1))
    bp = n * sum(v * v for v in r)
    return lb, bp


def simulate_ar1(phi: float, n: int, rng: random.Random, burn: int = 200) -> list[float]:
    x, prev = [], 0.0
    for t in range(n + burn):
        prev = phi * prev + rng.gauss(0.0, 1.0)
        if t >= burn:
            x.append(prev)
    return x


def test_statistic_matches_exact_rational_value():
    rng = random.Random(1)
    for _ in range(200):
        n = rng.randint(4, 30)
        x = [rng.randint(-9, 9) for _ in range(n)]
        if len(set(x)) == 1:
            continue
        h = rng.randint(1, n - 1)
        lb, bp = exact_q(x, h)
        assert ljung_box([float(v) for v in x], h)[0] == pytest.approx(float(lb), rel=1e-12)
        assert ljung_box([float(v) for v in x], h, statistic="box-pierce")[0] == pytest.approx(float(bp), rel=1e-12)
        assert lb >= bp


def test_worked_example():
    x = [3.0, 5.0, 6.0, 4.0, 2.0, 1.0, 3.0, 6.0, 7.0, 5.0]
    r = residual_autocorrelations(x, 3)
    assert r == pytest.approx([69 / 140, -89 / 280, -523 / 840], rel=1e-12)
    q, df, p = ljung_box(x, 3)
    assert df == 3
    assert q == pytest.approx(11.399778304178811, rel=1e-12)
    assert p == pytest.approx(chi2_sf(q, 3), rel=1e-15)
    assert p == pytest.approx(0.00974936528681176, rel=1e-9)


def test_helper_closed_forms():
    for x in (0.1, 1.0, 3.0, 12.5):
        assert chi2_sf(x, 2) == pytest.approx(math.exp(-x / 2), rel=1e-12)
        assert chi2_sf(x, 1) == pytest.approx(math.erfc(math.sqrt(x / 2)), rel=1e-10)
    assert chi2_ppf(0.95, 1) == pytest.approx(3.841458821, abs=1e-8)


def test_monte_carlo_size_iid_normal():
    # Measured, not proved: r = 2000 series of n = 100 iid N(0, 1), h = 10, seed 2.
    rng = random.Random(2)
    r, rej = 2000, 0
    for _ in range(r):
        x = [rng.gauss(0.0, 1.0) for _ in range(100)]
        rej += ljung_box(x, 10)[2] <= 0.05
    # 4 standard errors are 4 sqrt(0.05 * 0.95 / 2000) = 0.0195.
    assert abs(rej / r - 0.05) < 0.025


def test_monte_carlo_size_ar1_residuals_with_df_h_minus_1():
    # Measured: AR(1) with phi = 0.5, n = 100, Yule-Walker fit, h = 10, df = 9, seed 3.
    rng = random.Random(3)
    r, rej = 1500, 0
    for _ in range(r):
        x = simulate_ar1(0.5, 100, rng)
        m = math.fsum(x) / 100
        d = [v - m for v in x]
        c0 = math.fsum(v * v for v in d)
        a = math.fsum(d[t] * d[t - 1] for t in range(1, 100)) / c0
        res = [d[t] - a * d[t - 1] for t in range(1, 100)]
        rej += ljung_box(res, 10, fitted=1)[2] <= 0.05
    assert abs(rej / r - 0.05) < 0.025


def test_power_against_ar1():
    rng = random.Random(4)
    rej = sum(ljung_box(simulate_ar1(0.5, 100, rng), 5)[2] <= 0.05 for _ in range(300))
    assert rej / 300 > 0.9


def test_errors():
    with pytest.raises(ValueError):
        ljung_box([1.0, 1.0, 1.0, 1.0], 2)
    with pytest.raises(ValueError):
        ljung_box([1.0, 2.0, 3.0], 3)
    with pytest.raises(ValueError):
        ljung_box([1.0, 2.0, 0.0, 5.0], 2, fitted=2)
    with pytest.raises(ValueError):
        ljung_box([1.0, 2.0, 0.0, 5.0], 2, statistic="other")

History

Box and Pierce (1970) studied the residual autocorrelations of a fitted ARIMA model. They showed that these have a smaller variance than the autocorrelations of IID noise at small lags, and that n∑k=1hr^k2n\sum_{k=1}^h \hat r_k^2 is approximately χh−p−q2\chi^2_{h - p - q} when hh is moderately large. The statistic became part of the diagnostic stage of the Box-Jenkins method published the same year. Simulations in the 1970s showed that its size is much too small in series of the usual length. Ljung and Box (1978) replaced r^k2\hat r_k^2 by r^k2(n+2)/(n−k)\hat r_k^2 (n + 2)/(n - k), using the exact variance of r^k\hat r_k for normal noise, and showed that the new statistic has a law much closer to chi-square. The Ljung-Box statistic is now the default portmanteau test in most statistical software. McLeod and Li (1983) applied it to squared residuals, and Hosking (1980) extended it to vector series.

References

  1. Greta M. Ljung and George E. P. Box, On a measure of lack of fit in time series models, Biometrika 65(2), 1978, pp. 297 to 303 (the modified statistic and its small-sample behaviour)
  2. George E. P. Box and David A. Pierce, Distribution of residual autocorrelations in autoregressive-integrated moving average time series models, Journal of the American Statistical Association 65(332), 1970, pp. 1509 to 1526 (the asymptotic law of residual autocorrelations and the portmanteau statistic)
  3. Peter J. Brockwell and Richard A. Davis, Time Series: Theory and Methods, second edition, Springer, 1991, Section 9.4 (diagnostic checking, pp. 306 to 313)
  4. Peter J. Brockwell and Richard A. Davis, Introduction to Time Series and Forecasting, third edition, Springer, 2016, Section 1.6 (testing the estimated noise sequence, p. 30) and Section 5.3 (diagnostic checking, p. 144)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example