typestar

Residual diagnostics in Python

The tests that say whether the OLS assumptions actually held.

import numpy as np
import statsmodels.api as sm
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.stattools import durbin_watson, jarque_bera

rng = np.random.default_rng(6)
x = np.linspace(1, 50, 200)
y = 3 + 0.5 * x + rng.normal(0, x / 10)  # variance grows with x

X = sm.add_constant(x)
model = sm.OLS(y, X).fit()

statistic, pvalue, _, _ = het_breuschpagan(model.resid, X)
print(round(statistic, 3), f"{pvalue:.2e}", "heteroscedastic" if pvalue < 0.05
      else "constant variance")
print(round(durbin_watson(model.resid), 3))
print(round(jarque_bera(model.resid)[1], 4))
print(round(model.get_robustcov_results("HC3").bse[1], 5))

How it works

  1. het_breuschpagan tests for changing variance.
  2. durbin_watson near 2 means no autocorrelation.
  3. jarque_bera tests the normality of the residuals.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
661
Tokens
189
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 103 seconds.

Type this snippet

Step 1 of 2 in Diagnostics & robustness, step 7 of 19 in Statistics with statsmodels.

← Previous Next →