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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 to . 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 , a weighted sum of the squared sample autocorrelations. Under the null it is approximately chi-squared with degrees of freedom for a raw series, and with for the residuals of an ARMA(, ) fit. It tests all lags at once, so it is called a portmanteau test. It replaces the older Box-Pierce statistic , 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 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 delays, so you do not have to look at each one alone.
The problem
Model. A series . In the main use, are the residuals of an ARMA(, ) model fitted by maximum likelihood or least squares, and coefficients were estimated. For a raw series, .
Hypotheses. : the errors of the model are IID with finite variance (for a raw series, are IID). The alternative is any autocorrelation at lags to . The test has no power against dependence that leaves all these autocorrelations at 0.
Statistic. With the mean and ,
Null distribution. Asymptotic only. For an IID series with finite variance and fixed , , so both statistics tend to (proved in proofs/correctness.md). For residuals of a fitted ARMA(, ) model, the law of is approximately when is large and is small (Box and Pierce 1970). This is an approximation, not a limit theorem for fixed .
Rejection rule and size. Reject when , the upper point. The size tends to for a raw IID series. For finite it is not controlled: the measured sizes below show a little above and below it.
P-values. , the upper tail only.
Sensitivity and power. The test spreads its power over lags. Against a departure at lag 1 alone, a large adds noise from lags that carry no signal, and the power falls. A small misses seasonal or long-lag structure. A common choice is near or , and or for seasonal period , but there is no rule that is best for all alternatives.
The algorithm
LJUNG-BOX(e[1..n], h, s)- 1
ē ← (e[1] + ... + e[n]) / n - 2
c0 ← Σ_{t=1}^{n} (e[t] - ē)² - 3
for k ← 1 to h do r[k] ← Σ_{t=k+1}^{n} (e[t] - ē)(e[t-k] - ē) / c0 - 4
Q ← n(n + 2) · Σ_{k=1}^{h} r[k]² / (n - k) ▷ Box-Pierce: Q ← n · Σ r[k]² - 5
df ← h - s ▷ s = p + q fitted ARMA coefficients - 6
return (Q, df, P(χ²_df > Q))
The caller passes the residuals and the number of fitted ARMA coefficients (fitted in the code). The mean, a regression intercept or a drift is not counted in . 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 . The code raises an error if , if , or if the series is constant.
Example
Take the ten values as a raw series and test lags. The mean is and .
| Ljung-Box weight | Box-Pierce weight | |||
|---|---|---|---|---|
| 1 | 0.2429 | 13.33 | 10 | |
| 2 | 0.1010 | 15.00 | 10 | |
| 3 | 0.3877 | 17.14 | 10 |
Then on 3 degrees of freedom, with , and , with . The Ljung-Box test rejects at and the Box-Pierce test does not. With 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 with mean and variance , the products , , form a stationary martingale difference sequence with covariance . The martingale central limit theorem gives , after showing that replacing by changes nothing in the limit. So , and in probability. The proof also gives the reason for the weights: for IID normal data with known mean 0 (no centering), exactly and the are uncorrelated, so exactly, while . For and , instead of 10, so its size is too small. The degrees of freedom 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. is a series and . Write , , , , and
Claim 1 (lines L1 to L6 compute the statistic). Line L1 computes , line L2 computes and line L3 computes . Line L4 computes (or ), line L5 sets , and line L6 returns 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 , and , for which some .
Claim 2 (exact moments for normal noise with known mean). Let be IID and define , the autocorrelation without centering. Then , , and for . Hence, with in place of ,
Proof. The vector has a spherically symmetric law, so is uniform on the unit sphere of , and . The law of does not change when one coordinate changes sign, so a moment is 0 unless every index appears an even number of times. For the uniform law on the sphere, for . (Proof: by symmetry and do not depend on . From , . For a standard normal vector , with independent of and , so and .) Each term has two different indices, so . In
a term is nonzero only if as sets. The case , gives , which is impossible. The case , needs . So the covariance is 0 for , and for the terms with each give . Then , and .
This is the reason for the weights . The code centres the series at , which changes the moments by terms of order , so for the centred statistic the claim is an approximation. For and , , far below the mean 10 of .
Claim 3 (joint limit of the autocorrelations). Let be IID with mean and variance , and fix . Then in distribution.
Proof. Put . Fix and let for . The sequence is strictly stationary and -dependent, because is a function of . Its mean is 0, since is independent of the other factors. Its variance is . For , , because appears once in the product and is independent of all the other factors, whose indices are smaller. The central limit theorem for strictly stationary -dependent sequences with finite variance (Brockwell and Davis 1991, Chapter 6) gives . The terms with in are a fixed number of terms, so by the Cramér-Wold device
Next, the centering. With ,
By Chebyshev's inequality, and the two partial sums are , so the last two terms are and vanish after division by . Finally almost surely by the strong law of large numbers. By Slutsky's lemma, has the joint limit .
Claim 4 (the size tends to for a raw series). Under the hypotheses of Claim 3, and in distribution. So with , the test that rejects when has size tending to , for either statistic.
Proof. is a continuous function of , so by Claim 3 and the continuous mapping theorem it tends to the squared length of an vector, which is . Next,
where and . So the difference tends to 0 in probability, and has the same limit. The law is continuous, so .
The tests check Claim 1 against an exact Fraction computation of and 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(, ) model fitted by an efficient method, tends to a normal law with covariance , where is a projection of rank when is large. Hence is approximately (Box and Pierce 1970; Brockwell and Davis 1991, Section 9.4). For fixed the limit is a weighted sum of chi-square variables, not exactly . The page measures the size of this approximation for AR(1) residuals.
Complexity
Lines L1 and L2 take time and L3 takes , so the test takes time. The code keeps the centred series, extra space. For many lags, all autocorrelations can be computed in 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 series, , 10 degrees of freedom, , 4000 series per row (seed 11). The Monte Carlo standard error is about 0.0035.
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 , and the Box-Pierce test is conservative.
-
Residuals of a fitted AR(1) (measured). AR(1) series with , fitted by the Yule-Walker equations, , (seed 12):
true 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 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 (measured). Raw AR(1) series with , , (seed 13): the power was 0.461 for , 0.263 for , 0.207 for and 0.199 for . 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 , so does not depend on or .
-
Not consistent against all dependence. A process with but dependence in the squares, such as an ARCH or GARCH process, has power close to . Apply the test to the squared residuals to detect it.
Variants and improvements
- Box-Pierce statistic. , 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 , Hosking (1980) and Li and McLeod (1981) replaced by , with 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 , and use . This removes the error of the chi-square approximation at the cost of 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 , 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 to . 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 for the residuals of an ARMA(, ) fit, not . The mean, a constant and regression coefficients on exogenous variables are not counted, and the rule is itself only an approximation that needs well above .
- 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 . Reporting the smallest p-value over is a multiple-testing problem. Choose before looking, or adjust with a Bonferroni correction.
- Too large an . The power falls as grows, and the chi-square approximation needs much smaller than .
- 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 in . The formula above uses the divisor , as in Ljung and Box (1978). Other conventions change 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.
# 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 is approximately when 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 by , using the exact variance of 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
- 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)
- 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)
- 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)
- 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.
| 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 NPBB3C Edit this page History Report an error Markdown