Skip to content
svgljung-box-p

Ljung–Box p-values by lag

Up to which lag is the series (or a model's residuals) indistinguishable from white noise?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each point as the test of all autocorrelations up to that lag.
  2. Points below the 5% line: some autocorrelation remains.
  3. For a model's residuals, you want points above the line.
  1. Callout 1: Below the line: not white noise up to this lag.
  2. Callout 2: The 5% reference line.

Watch out

  • The points overlap in the lags they test, so they aren't independent results.
  • A high p doesn't prove the residuals are white noise, only that this test didn't detect otherwise.

Defaults

Max lag (0 = R default)
0
How many lags to show; 0 uses R's rule based on the series length.
Range 0 to 200, step 1
Model degrees of freedom (p + q)
0
For ARMA residuals: the χ² df become lag − fitdf.
Range 0 to 20, step 1

Pinned in the code

  • Q(L) = n(n + 2) Σ_{k=1…L} r_k²/(n − k), referred to χ²(L − fitdf) (R Box.test type = 'Ljung-Box'); r_k uses denominator n.
  • Lags with df < 1 are not tested. Default max lag: max(⌊10 log₁₀ n⌋, fitdf + 5), capped at n − 2.
  • Each point is a separate test of all lags up to L; they are strongly dependent, not independent evidence.
# Ljung–Box p-values by lag — Codesplash Chart Lab (recipe "ljung-box-p")
# controls: lagMax=0, fitdf=0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("ljung-box-p-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
def ljung_box_by_lag(v, L, fitdf=0):
    """Q(k) = n(n+2) Σ_{j≤k} r_j²/(n−j) with r_j on denominator n; p from χ²(k − fitdf)."""
    n = len(v)
    x = v - v.mean()
    den = (x * x).sum()
    r = np.array([(x[j:] * x[:n - j]).sum() / den for j in range(1, L + 1)])
    q = n * (n + 2) * np.cumsum(r * r / (n - np.arange(1, L + 1)))
    df_ = np.arange(1, L + 1) - fitdf
    p = np.where(df_ >= 1, stats.chi2.sf(q, np.maximum(df_, 1)), np.nan)
    return np.arange(1, L + 1), q, p
X = None
Y = "residual"
LAG_MAX, FITDF = 0, 0  # 0 = max(⌊10 log₁₀ n⌋, fitdf + 5)
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
L = min(LAG_MAX, n - 2) if LAG_MAX > 0 else max(max(1, min(n - 1, int(np.floor(10 * np.log10(n))))), FITDF + 5)
lags, q, p = ljung_box_by_lag(v, max(1, L), FITDF)
fig, ax = plt.subplots(figsize=(7, 4))
ax.axhspan(0, 0.05, color="#ce5342", alpha=0.08, lw=0)
ax.axhline(0.05, color=REF, linestyle="--", linewidth=1)
ax.scatter(lags, p, c=np.where(p < 0.05, "#ce5342", PALETTE[0]), s=18, zorder=3)
ax.set_ylim(0, 1)
ax.set_xlabel("lags included")
ax.set_ylabel("Ljung–Box p-value")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads ljung-box-p-demo.csv · app theme from the optional codesplash helper