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
het_breuschpagantests for changing variance.durbin_watsonnear 2 means no autocorrelation.jarque_beratests the normality of the residuals.
Keywords and builtins used here
aselseifprintround
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.
Step 1 of 2 in Diagnostics & robustness, step 7 of 19 in Statistics with statsmodels.