Test residuals for leftover autocorrelation with the Ljung-Box statistic

Why it matters Ljung-Box is the standard residual check after fitting ARIMA or any forecaster: a large Q means there is pattern left that the model missed.

After fitting a forecaster, its residuals should look like white noise. The Ljung-Box statistic combines the first few autocorrelations into one number to test that.

Write ljung_box(x, h). x is a 1D series of length n > h. Compute autocorrelations r_k = sum_{t=k}^{n-1} (x_t - mean)(x_{t-k} - mean) / sum (x_t - mean)^2 for k = 1 .. h. Return a float array Q of length h where Q[j] = n (n + 2) * sum_{k=1}^{j+1} r_k^2 / (n - k), the statistic using lags 1 to j + 1.

Signaturedef ljung_box(x, h)

Example

x [1, -1, 1, -1, 1, -1], h 2 gives [6.666667, 12.0].

Understand the idea

A good forecaster leaves residuals that look like random noise. If yesterday's error helps predict today's error, the model missed a pattern. Autocorrelation at lag k measures that link, and Ljung-Box adds up the first h of them into one test number.

Worked example: residuals 1, -1, 1, -1, 1, -1 flip sign every step, an obvious pattern. The lag 1 autocorrelation is -5/6 = -0.833 (five neighbouring pairs, all products -1, over a total of 6). With n = 6, Q at lag 1 is 6 * 8 * 0.694 / 5 = 6.67, which is above the 5% chi-square cutoff of 3.84 for 1 degree of freedom, so the residuals are not white noise.

Rule: Q(h) = n (n + 2) * sum over k = 1 .. h of r_k^2 / (n - k). Under white noise Q is roughly chi-square with h degrees of freedom.

The n (n + 2) / (n - k) weights make the test accurate on short series. Forecasting tools run this check automatically after fitting ARIMA style models.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleljung_box([1, -1, 1, -1, 1, -1], 2)
  • Sample 2: white noiseljung_box(_e, 4)
  • Test 3: trend left in residualsljung_box(np.arange(10, dtype=float), 3)
  • Test 4: weekly patternljung_box([5, 1, 1, 1, 5, 1, 1, 1, 5, 1, 1, 1], 4)