Skip to content

statsmodels

statsmodels fits statistical models with full inference: standard errors, p-values and confidence intervals. This page covers the formula API, reading results, robust standard errors, proportions tests, power analysis and the first time-series tools. The examples use data/houses.csv, the A/B test in data/ab_test.csv and the daily visits in data/web_traffic.csv. The blocks share one session:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
houses = pd.read_csv("data/houses.csv")
ab = pd.read_csv("data/ab_test.csv")
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")
I want to… Use… Notes
a linear regression with inference smf.ols("y ~ x1 + x2", data=df).fit()
the same with arrays sm.OLS(y, sm.add_constant(X)).fit() no intercept unless you add it
a logistic regression smf.logit("y ~ x", data=df).fit(disp=0) y is 0/1
a count model smf.poisson(...) or smf.glm(..., family=sm.families.Poisson())
any GLM smf.glm(f, data=df, family=sm.families.Binomial()) Gamma, NegativeBinomial, Tweedie
weighted least squares smf.wls(f, data=df, weights=w)
a median regression smf.quantreg(f, data=df).fit(q=0.5) robust to outliers
random effects per group smf.mixedlm(f, data=df, groups=df["g"])
a categorical predictor C(cat) in the formula dummies; first level is the reference
choose the reference level C(cat, Treatment(reference="B"))
an interaction x1 * x2 or x1:x2 * adds the main effects too
a transform in the formula np.log(y) ~ np.log(x), I(x ** 2)
coefficients res.params a Series
standard errors, p-values res.bse, res.pvalues
95% CIs of the coefficients res.conf_int(alpha=0.05) columns 0 and 1
R² res.rsquared, res.rsquared_adj OLS; prsquared for logit
AIC, BIC res.aic, res.bic lower is better
rows used res.nobs rows with NaN are dropped
check for unequal error variance het_breuschpagan(res.resid, res.model.exog) p < 0.05: use HC3
check for collinearity variance_inflation_factor(res.model.exog, i) above 5–10 is a problem
find influential rows res.get_influence().cooks_distance[0] compare with 4 / n
robust standard errors .fit(cov_type="HC3") same coefficients
clustered standard errors .fit(cov_type="cluster", cov_kwds={"groups": g}) many clusters needed
autocorrelation-robust SE .fit(cov_type="HAC", cov_kwds={"maxlags": 7}) time series
predictions with intervals res.get_prediction(new).summary_frame(alpha=0.05) mean CI and prediction interval
odds ratios np.exp(logit_res.params)
marginal effects logit_res.get_margeff().summary_frame() in probability units
test “coefficient = value” res.t_test("x = 0.5") f_test for several
an ANOVA table sm.stats.anova_lm(res, typ=2)
compare two conversion rates proportions_ztest(counts, nobs) statsmodels.stats.proportion
a CI for a difference of rates confint_proportions_2indep(k1, n1, k2, n2) Newcombe, Wilson
a CI for one rate proportion_confint(k, n, method="wilson")
a sample size for an A/B test NormalIndPower().solve_power(effect_size=h, power=0.8) h = proportion_effectsize(p1, p2)
a sample size for a t-test TTestIndPower().solve_power(effect_size=d, power=0.8) per group
adjust many p-values multipletests(p, method="fdr_bh") "holm", "bonferroni"
test for a unit root adfuller(y, result_object=True) H0: not stationary
decompose a series STL(y, period=7).fit() trend, seasonal, remainder
fit a (seasonal) ARIMA SARIMAX(y, order=..., seasonal_order=...).fit(disp=False)

statsmodels.formula.api (smf) builds the design matrix from a formula string and a DataFrame. It adds an intercept, makes dummy variables and keeps the column names.

Formula Meaning
y ~ x intercept + slope
y ~ x1 + x2 two predictors
y ~ C(cat) one dummy per level except the first (the reference)
y ~ C(cat, Treatment(reference="B")) B is the reference level
y ~ C(num) treat a numeric column (such as a 1–5 rating) as categories
y ~ x1 * x2 x1 + x2 + x1:x2
y ~ x1:x2 the interaction only
y ~ C(cat) * x one slope of x per category
np.log(y) ~ np.log(x) NumPy functions work inside the formula
y ~ I(x ** 2) arithmetic needs I(...); a bare x ** 2 means something else
y ~ x - 1 or y ~ 0 + x no intercept
y ~ Q("my col") a column name that is not a Python name
y ~ scale(x) / center(x) standardize or center inside the formula
Function Model y
smf.ols linear regression numeric
smf.wls weighted linear regression numeric
smf.logit, smf.probit binary outcome 0/1
smf.mnlogit several unordered classes integer codes
smf.poisson, smf.negativebinomial counts integers ≥ 0
smf.glm any GLM: pass family=sm.families.Gaussian(), Binomial(), Poisson(), Gamma()… depends on the family
smf.quantreg a quantile of y; .fit(q=0.9) numeric
smf.mixedlm random intercepts or slopes per group numeric
formula = "np.log(price) ~ np.log(sqft) + has_pool + C(neighborhood)"
ols = smf.ols(formula, data=houses).fit()
coefs = pd.DataFrame({"coef": ols.params, "se": ols.bse, "p": ols.pvalues})
coefs[["low", "high"]] = ols.conf_int(alpha=0.05) # 95% CI per coefficient
print(coefs.loc[["np.log(sqft)", "has_pool", "C(neighborhood)[T.Lakeview]"]].round(4))
print(round(ols.rsquared, 3), round(ols.rsquared_adj, 3), int(ols.nobs), ols.df_model)
print(f"pool: {100 * (np.exp(ols.params['has_pool']) - 1):+.1f}% price") # log outcome
Output
coef se p low high
np.log(sqft) 0.7556 0.0124 0.0 0.7312 0.7800
has_pool 0.0972 0.0138 0.0 0.0700 0.1243
C(neighborhood)[T.Lakeview] 0.8952 0.0176 0.0 0.8607 0.9297
0.819 0.818 3000 9.0
pool: +10.2% price
Result member Gives
params, bse, tvalues, pvalues coefficients, standard errors, t statistics, p-values (Series)
conf_int(alpha=0.05) a DataFrame with columns 0 and 1
rsquared, rsquared_adj share of variance explained (OLS)
fvalue, f_pvalue the F-test of “all slopes are 0”
aic, bic, llf information criteria, log-likelihood
nobs, df_model, df_resid rows used, number of slopes, residual degrees of freedom
resid, fittedvalues residuals and fitted values of the training rows
predict(new_df) point predictions; the formula is applied to new_df
get_prediction(new_df) predictions with standard errors and intervals
model.exog_names the design-matrix column names
t_test("x = 0"), f_test("x1 = x2 = 0") tests of linear restrictions
summary() the full report as text

summary() prints the full report. Its header contains the date and time of the call, so it changes on every run:

print(ols.summary()) # header, coefficient table and residual diagnostics
print(ols.summary().tables[1]) # only the coefficient table

In a model of np.log(y), a coefficient β\beta of a 0/1 predictor changes yy by 100(eβ−1)%100(e^{\beta} - 1)\%. The coefficient of np.log(x) is an elasticity: +1% of x gives about β\beta% of y.

Reference levels, interactions and missing rows

Section titled “Reference levels, interactions and missing rows”
ref = "C(neighborhood, Treatment(reference='Downtown'))"
m_ref = smf.ols(f"np.log(price) ~ np.log(sqft) + {ref}", data=houses).fit()
levels = [name.split("[T.")[1][:-1] for name in m_ref.model.exog_names[1:3]]
print(levels) # these dummies are now relative to Downtown
inter = smf.ols("np.log(price) ~ np.log(sqft) * has_pool", data=houses).fit()
print(inter.params.round(3).to_dict()) # has_pool: the effect at log(sqft) = 0
lot = smf.ols("np.log(price) ~ lot_sqft", data=houses).fit()
print(houses["lot_sqft"].isna().sum(), int(lot.nobs)) # 90 NaN rows dropped
Output
['Cedar Park', 'Lakeview']
{'Intercept': 6.281, 'np.log(sqft)': 0.886, 'has_pool': -3.193, 'np.log(sqft):has_pool': 0.455}
90 2910

The last line shows the silent row drop: 90 rows with a missing lot_sqft leave 2,910 rows in the model.

new = pd.DataFrame(
{"sqft": [1500, 2500], "has_pool": [0, 1], "neighborhood": ["Old Town", "Lakeview"]}
)
frame = ols.get_prediction(new).summary_frame(alpha=0.05) # on the log scale
print(frame.columns.tolist())
print(np.exp(frame[["mean", "obs_ci_lower", "obs_ci_upper"]]).round(-3))
Output
['mean', 'mean_se', 'mean_ci_lower', 'mean_ci_upper', 'obs_ci_lower', 'obs_ci_upper']
mean obs_ci_lower obs_ci_upper
0 346000.0 223000.0 536000.0
1 952000.0 613000.0 1477000.0

mean_ci_* is the CI of the average price of such houses. obs_ci_* is the prediction interval for one house: much wider. np.exp of a log-scale prediction gives the median, not the mean.

Check the model before you trust its p-values. Each check below tests one assumption of OLS.

Check Function A problem looks like Then
linearity, unequal variance plot res.fittedvalues vs res.resid a curve, or a fan shape transform y or x; cov_type="HC3"
unequal variance, as a test het_breuschpagan(res.resid, res.model.exog) p < 0.05 cov_type="HC3"
normal residuals sm.qqplot(res.resid, line="45", fit=True) points bend away from the line matters for small samples and prediction intervals
collinearity variance_inflation_factor(res.model.exog, i) VIF above 5–10 drop or combine predictors
influential rows res.get_influence().cooks_distance[0] a few values far above 4 / n inspect those rows; refit without them to compare
autocorrelated errors durbin_watson(res.resid) far from 2 (below 1.5 or above 2.5) cov_type="HAC", or a time-series model
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.stattools import durbin_watson
bp_p = het_breuschpagan(ols.resid, ols.model.exog)[1]
print(f"Breusch-Pagan p = {bp_p:.4f}") # small: the spread is not constant
X, names = ols.model.exog, ols.model.exog_names
vif = {n: round(float(variance_inflation_factor(X, i)), 2)
for i, n in enumerate(names) if n in ("np.log(sqft)", "has_pool")}
print(vif) # near 1: no collinearity problem
cooks = ols.get_influence().cooks_distance[0]
print(round(cooks.max(), 4), houses.loc[cooks.argmax(), "house_id"],
int((cooks > 4 / ols.nobs).sum())) # largest, its row, count above 4/n
print(round(durbin_watson(ols.resid), 3)) # near 2: no autocorrelation
Output
Breusch-Pagan p = 0.0000
{'np.log(sqft)': 1.3, 'has_pool': 1.11}
0.0199 H0542 158
1.989
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2, figsize=(9, 3.5), layout="constrained")
axs[0].scatter(ols.fittedvalues, ols.resid, s=5, alpha=0.4) # residuals vs fitted
axs[0].axhline(0, color="gray")
sm.qqplot(ols.resid, line="45", fit=True, ax=axs[1]) # residuals vs a normal
plt.show()

The small Breusch–Pagan p-value is the reason to use the HC3 standard errors below.

cov_type Use when Extra argument
"nonrobust" (default) constant error variance, independent errors
"HC3" the residual spread changes (a fan shape)
"HC0", "HC1" as HC3; HC1 matches Stata’s robust
"cluster" errors correlate within groups (users, stores, schools) cov_kwds={"groups": df["g"]}
"HAC" autocorrelated errors in a time series cov_kwds={"maxlags": 7}
robust = smf.ols(formula, data=houses).fit(cov_type="HC3")
compare = pd.DataFrame({"classic": ols.bse, "HC3": robust.bse})
print(compare.loc[["np.log(sqft)", "has_pool"]].round(4))
print(np.allclose(ols.params, robust.params)) # only the standard errors change
Output
classic HC3
np.log(sqft) 0.0124 0.0148
has_pool 0.0138 0.0152
True

Clustered standard errors need many clusters (dozens or more). With the 8 neighborhoods of houses.csv, they would be unreliable.

logit = smf.logit("converted ~ C(group) + C(device)", data=ab).fit(disp=0) # quiet
print(logit.params.round(4))
print(np.exp(logit.params).round(3)["C(group)[T.treatment]"]) # odds ratio
print(round(logit.prsquared, 4), f"{logit.llr_pvalue:.1e}") # pseudo R², LR test
effects = logit.get_margeff().summary_frame() # average marginal effects
print(effects["dy/dx"].round(4))
new_users = pd.DataFrame({"group": ["control", "treatment"], "device": "desktop"})
print(logit.predict(new_users).round(4).tolist()) # probabilities
Output
Intercept -1.9621
C(group)[T.treatment] 0.1597
C(device)[T.mobile] -0.4035
C(device)[T.tablet] -0.1155
dtype: float64
1.173
0.0061 4.2e-09
C(group)[T.treatment] 0.0154
C(device)[T.mobile] -0.0390
C(device)[T.tablet] -0.0112
Name: dy/dx, dtype: float64
[0.1232, 0.1416]

The treatment raises the odds of a purchase by about 17%. The marginal effect says the same in probability units: about +1.5 percentage points. smf.glm("converted ~ C(group) + C(device)", data=ab, family=sm.families.Binomial()) fits the same model as a GLM.

two_way = smf.ols("np.log(price) ~ C(neighborhood) + C(condition)", data=houses).fit()
print(sm.stats.anova_lm(two_way, typ=2).round(3)) # Type II sums of squares
Output
sum_sq df F PR(>F)
C(neighborhood) 468.911 7.0 661.803 0.0
C(condition) 39.635 4.0 97.894 0.0
Residual 302.444 2988.0 NaN NaN
typ Tests each term Use for
1 after the terms before it (the order matters) nested, ordered models
2 after all other main effects models without interactions (the usual choice)
3 after all other terms models with interactions; needs Sum contrasts

All in statsmodels.stats.proportion.

Function Gives
proportions_ztest(count, nobs) z and p for two (or one) rates; pooled variance
proportions_chisquare(count, nobs) chi-square test of several rates
test_proportions_2indep(k1, n1, k2, n2) a test of two rates with a choice of method and of compare="diff", "ratio", "odds-ratio"
confint_proportions_2indep(k1, n1, k2, n2, method="newcomb") a CI for p1 - p2; compare="ratio" for the lift
proportion_confint(k, n, method="wilson") a CI for one rate; also "beta" (exact), "agresti_coull"
proportion_effectsize(p1, p2) Cohen’s h, the input of the power functions
binom_test(k, n, prop=p) an exact test of one rate
from statsmodels.stats.proportion import (
confint_proportions_2indep,
proportion_confint,
proportions_ztest,
)
counts = ab.groupby("group")["converted"].agg(["sum", "count"])
k = counts.loc[["treatment", "control"], "sum"].to_numpy()
n = counts.loc[["treatment", "control"], "count"].to_numpy()
z, p = proportions_ztest(k, n) # two-sided by default
print(f"rates {k[0] / n[0]:.4f} vs {k[1] / n[1]:.4f}, z = {z:.3f}, p = {p:.4f}")
lo, hi = confint_proportions_2indep(k[0], n[0], k[1], n[1], method="newcomb")
print(f"difference: {100 * lo:.2f} to {100 * hi:.2f} pp")
lo, hi = confint_proportions_2indep(k[0], n[0], k[1], n[1], compare="ratio")
print(f"ratio: {lo:.3f} to {hi:.3f}") # relative lift +3% to +29%
print(np.round(proportion_confint(k[0], n[0], method="wilson"), 4))
Output
rates 0.1166 vs 0.1012, z = 2.486, p = 0.0129
difference: 0.33 to 2.77 pp
ratio: 1.030 to 1.290
[0.108 0.1258]

Plan the sample size before a study. Fix three of effect size, α, power and n; solve_power finds the one you leave out (pass it as None or leave it out).

Class Test Effect size
NormalIndPower() two proportions (z-test) Cohen’s h: proportion_effectsize(p1, p2)
TTestIndPower() two independent means Cohen’s d
TTestPower() paired or one-sample mean d of the differences
FTestAnovaPower() one-way ANOVA; returns the total n Cohen’s f; pass k_groups
GofChisquarePower() chi-square goodness of fit Cohen’s w
from statsmodels.stats.power import NormalIndPower, TTestIndPower, TTestPower
from statsmodels.stats.proportion import proportion_effectsize
h = proportion_effectsize(0.12, 0.10) # detect 10% -> 12%
print(round(h, 4), int(np.ceil(NormalIndPower().solve_power(h, alpha=0.05, power=0.8))))
print(round(NormalIndPower().power(h, nobs1=5_000, alpha=0.05), 3)) # power at 5,000
mde = NormalIndPower().solve_power(nobs1=5_000, alpha=0.05, power=0.8) # smallest h
print(round(mde, 4))
d_power = {"effect_size": 0.3, "alpha": 0.05, "power": 0.8} # Cohen's d = 0.3
print(int(np.ceil(TTestIndPower().solve_power(**d_power)))) # per group
print(int(np.ceil(TTestPower().solve_power(**d_power)))) # paired: number of pairs
Output
0.064 3835
0.892
0.056
176
90

The ratio=n2/n1 argument plans unequal groups; nobs1 is the size of the first group.

from statsmodels.stats.multitest import multipletests
p = np.array([0.001, 0.008, 0.039, 0.041, 0.042, 0.060, 0.074, 0.205])
for method in ["bonferroni", "holm", "fdr_bh"]:
reject, p_adj, _, _ = multipletests(p, alpha=0.05, method=method)
print(f"{method:<10}", reject.sum(), p_adj.round(3)[:3])
Output
bonferroni 1 [0.008 0.064 0.312]
holm 1 [0.008 0.056 0.234]
fdr_bh 2 [0.008 0.032 0.067]

Bonferroni and Holm control the chance of any false positive (family-wise error rate). fdr_bh controls the share of false positives among the discoveries and keeps more power.

The time-series module covers these in depth.

Task Function Note
unit-root test adfuller(y, result_object=True) H0: a unit root (not stationary)
stationarity test kpss(y, result_object=True) H0: stationary; the reverse of ADF
autocorrelation acf(y, nlags=14), pacf(y, nlags=14) statsmodels.tsa.stattools
ACF and PACF plots plot_acf(y, lags=28, ax=ax), plot_pacf statsmodels.graphics.tsaplots
decomposition STL(y, period=7, robust=True).fit() .trend, .seasonal, .resid
classical decomposition seasonal_decompose(y, period=7) NaN at both ends
(seasonal) ARIMA SARIMAX(y, order=(p, d, q), seasonal_order=(P, D, Q, s)) statsmodels.tsa.statespace.sarimax
exponential smoothing ExponentialSmoothing(y, trend="add", seasonal="add", seasonal_periods=7) statsmodels.tsa.holtwinters
forecast with intervals res.get_forecast(steps=28) .predicted_mean, .conf_int()
autocorrelation of residuals acorr_ljungbox(res.resid, lags=[7, 14]) statsmodels.stats.diagnostic
from statsmodels.tsa.stattools import adfuller
visits = traffic["visits"].interpolate() # ADF needs a series without gaps
for name, series in [("level", visits), ("first difference", visits.diff().dropna())]:
res = adfuller(series, result_object=True)
print(f"{name:<17} stat = {res.statistic:7.2f}, p = {res.pvalue:.2g}", end=", ")
print(f"lags = {res.lags}") # lagged differences chosen by AIC
Output
level stat = -2.51, p = 0.11, lags = 21
first difference stat = -10.89, p = 1.2e-19, lags = 20

The level shows no evidence of stationarity (p > 0.05); the ADF test rejects a unit root for the first difference (p < 0.05). That suggests d = 1 in an ARIMA model.

from statsmodels.tsa.statespace.sarimax import SARIMAX
model = SARIMAX(np.log(y_train), order=(1, 1, 1), seasonal_order=(0, 1, 1, 7))
result = model.fit(disp=False, maxiter=200) # disp=False: no optimizer printout
print(result.mle_retvals["converged"], round(result.aic, 1)) # check convergence
forecast = result.get_forecast(steps=28)
point = np.exp(forecast.predicted_mean) # back from the log scale
band = np.exp(forecast.conf_int(alpha=0.05))
Trap Symptom Fix
sm.OLS(y, X) without a constant the line goes through 0; R² is uncentered and too high sm.add_constant(X) or use smf.ols
missing values nobs is lower than len(df), without a message check res.nobs; impute or drop on purpose
y ~ x ** 2 not a square term I(x ** 2)
a numeric code such as a 1–5 rating one slope instead of one effect per level C(rating)
comparing coefficients across scales a big coefficient on a small unit standardize with scale(x) or compare effects in real units
the default nonrobust SE with a fan-shaped residual plot standard errors too small cov_type="HC3"
repeated rows per user or store standard errors far too small cov_type="cluster" with the group, or mixedlm
logit(...).fit() an optimizer message on stdout fit(disp=0)
PerfectSeparationWarning, ConvergenceWarning, huge logit coefficients a predictor splits the classes perfectly drop or merge the predictor, or regularize (fit_regularized)
logit coefficients read as probabilities wrong effect sizes np.exp(params) for odds ratios; get_margeff() for probabilities
summary() in a report or a test output changes with the date summary().tables[1] or build a table from params, bse, pvalues
get_margeff().summary_frame() columns the upper CI column is named Cont. Int. Hi. select by position or rename
np.exp of a log-scale forecast treated as the mean it is the median; the mean is a little higher
anova_lm(typ=1) results depend on the order of the terms typ=2 (or typ=3 with Sum contrasts)
FTestAnovaPower().solve_power n looks too large it returns the total over all groups
solve_power(effect_size=0.3, power=0.8) ValueError: need exactly one keyword that is None alpha has no default: pass alpha=0.05
NormalIndPower with two rates an error or a wrong n pass Cohen’s h from proportion_effectsize, not the difference
proportions_ztest(k, n) order the sign of z flips z > 0 when the first rate is the larger one; keep k and n in the same order
adfuller(y) or kpss(y) without result_object=True a FutureWarning in statsmodels 0.15 pass result_object=True; read .statistic, .pvalue
kpss p-value at 0.01 or 0.1 InterpolationWarning: the statistic is outside the table report “p < 0.01” or “p > 0.1” from the critical values
a large ADF p-value read as “the series has a unit root” it only means no evidence of stationarity
SARIMAX(...).fit() ConvergenceWarning a simpler model, the log of the series, maxiter=200; check mle_retvals["converged"]
a time series with NaN adfuller raises MissingDataError fill gaps first (interpolate, asfreq)
a formula with a column such as floor area SyntaxError Q("floor area"), or rename the column