Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 28 ยท Practice and Review

Statsmodels Cheat Sheet

A one-page Statsmodels reference: imports, model classes, formula syntax, results attributes, diagnostics, GLM families, time-series tools and a model-choice guide.

Keep this page open while you work. It summarizes the whole course: which class to use, what to read from the results, and which test checks which assumption.

Imports and the fit pattern

Python
import statsmodels.api as sm
import statsmodels.formula.api as smf
res = smf.ols("y ~ x1 + C(g)", data=df).fit()   # create, fit, inspect

Which model for which outcome

Outcome Model Formula API Lesson
Continuous OLS smf.ols First OLS Model
Continuous, unequal variance WLS / robust SE smf.wls, fit(cov_type="HC3") Weighted and Robust
Continuous with outliers RLM smf.rlm same
Quantiles QuantReg smf.quantreg(...).fit(q=0.5) Quantile Regression
Yes / no Logit, Probit smf.logit, smf.probit Logistic and Probit
Counts Poisson, NegBin smf.poisson, smf.negativebinomial Count Models
Positive skewed Gamma GLM smf.glm(..., family=Gamma(log)) GLM Families
Grouped data MixedLM smf.mixedlm(..., groups=) Mixed-Effects Models
One time series ARIMA, SARIMAX, ETS tsa.arima.model.ARIMA ARIMA Models

Formula syntax

Piece Meaning
y ~ a + b Both predictors plus intercept
- 1 or 0 + No intercept
a * b a + b + a:b
a : b Interaction only
C(g) Categorical; C(g, Treatment(reference="x")) sets the baseline
I(x**2) Literal arithmetic
np.log(x), scale(x), bs(x, df=4) Transformations and splines
Q("my col") Column names with spaces

Results attributes

Attribute Gives
params, bse, pvalues, tvalues Estimates, standard errors, p-values, t statistics
conf_int(alpha=0.05) Confidence intervals
resid, fittedvalues Residuals and fitted values
rsquared, rsquared_adj, aic, bic Fit measures
predict(new) Predictions (use raw columns with formulas)
get_prediction(new).summary_frame() Prediction and confidence intervals
summary() Full report
get_influence().summary_frame() Leverage, Cook's distance, studentized residuals
Python Everything in one small run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Diagnostics and tests

Question Tool
Constant variance? het_breuschpagan, het_white; plot residuals vs fitted
Normal residuals? jarque_bera, sm.qqplot
Autocorrelation? durbin_watson, acorr_ljungbox, acorr_breusch_godfrey
Correct form? linear_reset, residual LOWESS
Collinearity? variance_inflation_factor (above about 5-10)
Influential points? Cook's distance (above 4/n), leverage (above 2p/n)
Two means / proportions? ttest_ind, proportions_ztest
Many groups? anova_lm, pairwise_tukeyhsd
Many p-values? multipletests(method="holm" or "fdr_bh")
Sample size? TTestIndPower().solve_power, NormalIndPower
Stationary series? adfuller (null: unit root), kpss (null: stationary)
Nested models? compare_f_test, compare_lr_test, AIC, BIC

Fixing problems

Symptom Remedy
Funnel in residuals Log y, WLS, cov_type="HC3"
Curved residuals I(x**2), splines, log x
Autocorrelated errors cov_type="HAC", GLSAR, time-series model
Outliers Investigate, then RLM or quantile regression
Collinearity Drop, combine, center, ridge
Overdispersed counts Negative binomial, scaled errors
Perfect separation Remove variable, more data, fit_regularized
Non-convergence Rescale, simplify, change optimizer

Time series quick reference

Python ARIMA in six lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • Seasonal data: SARIMAX(y, order=(1,1,1), seasonal_order=(0,1,1,12)).
  • Smoothing: ExponentialSmoothing(y, trend="add", seasonal="add", seasonal_periods=12).
  • Always split by time, compare with a seasonal naive baseline, check Ljung-Box on residuals.

Habits that prevent mistakes

  1. Add the constant (array API) or use formulas.
  2. Compare res.nobs with len(df).
  3. Read effect sizes and intervals, not only p-values.
  4. Run diagnostics before trusting standard errors.
  5. Validate on held-out data (by time for time series).
  6. Do not extrapolate beyond the data or claim causation from association.
  7. Fix the random seed when you simulate, so results repeat.

See Pitfalls and Debugging for the full list and Predict, Save and Deploy for production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which model suits a count outcome whose variance is much larger than its mean?

    The negative binomial adds a dispersion parameter for overdispersed counts.
  2. 2. Which call gives heteroscedasticity-robust standard errors without changing coefficients?

    cov_type replaces only the covariance estimate.
  3. 3. The ADF test's null hypothesis is what?

    A small ADF p-value rejects the unit root, supporting stationarity.
  4. 4. How many dummy columns does a 5-level category add with treatment coding?

    k levels become k - 1 columns, with one reference level.

Summary

  • Pick the model from the outcome type, read results from attributes, and let diagnostics decide whether the standard errors can be trusted.
  • Remedies map to symptoms: transform, reweight, robust errors, different family, time-series model.
  • Validate honestly and report effect sizes with uncertainty.

Next: Statsmodels tutorial home