Skip to main content
v2026.11,986 entries · CC-BY 4.0

Stats OLS: Python Linear Regression Guide

Stats OLS guide: run ordinary least squares in Python with statsmodels, interpret diagnostic tables, resolve collinearity, and compute robust errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In empirical research, stats ols refers to running Ordinary Least Squares (OLS) linear regression using the Python statsmodels library. Researchers rely on OLS to estimate linear relationships between independent predictor variables and a continuous dependent outcome. While machine learning packages prioritize prediction speed, statsmodels provides complete inferential statistics: parameter estimates (β coefficients), standard errors, hypothesis tests, confidence intervals, and residual diagnostics essential for peer-reviewed academic publication.

What it is used for in research

Ordinary Least Squares regression remains the foundational workhorse for quantitative methodology across economics, epidemiology, psychology, and public policy. In empirical studies, researchers employ OLS to achieve three primary analytical objectives:

  • Parameter Estimation: Quantifying the direction and magnitude of the relationship between predictors and an outcome variable while holding other covariates constant.
  • Hypothesis Testing: Assessing whether estimated coefficients differ significantly from zero using two-tailed t-tests and evaluating overall model goodness-of-fit through F-tests.
  • Specification and Diagnostic Auditing: Evaluating whether Gauss-Markov assumptions hold—specifically homoskedasticity, absence of serial correlation, and normality of residuals—to ensure unbiased estimation and protect against omitted variable bias.

Unlike algorithms designed solely for predictive accuracy, OLS in statsmodels produces structured outputs tailored for academic reporting, enabling seamless translation into journal tables following standard reporting conventions detailed in our guide to interpreting standard regression output tables.

How to install or access it

The statsmodels package is distributed openly via official Python repository channels. It requires Python 3.9 or newer alongside foundational scientific computing packages (numpy, scipy, pandas, and patsy).

To install or update statsmodels using the official Python Package Index (PyPI), run the following command in your terminal:

pip install --upgrade statsmodels pandas numpy scipy

If your institution uses Anaconda or Miniconda environments, install the package from the community-maintained conda-forge channel:

conda install -c conda-forge statsmodels

To confirm that your installation is functional and verify the installed release version, execute this command:

python -c "import statsmodels.api as sm; print(sm.__version__)"

Step-by-step task

The following numbered workflow demonstrates how to prepare data, specify the regression design matrix, fit the OLS model, and generate robust covariance corrections using both the array interface and the formula interface.

Step 1: Import core modules

Import the standard scientific libraries alongside both the array-based API (sm) and the formula API (smf):

import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

Step 2: Prepare and clean research data

Load your observational dataset into a pandas DataFrame. When working with survey or experimental data containing missing entries, configure missing-value handling explicitly. The missing='drop' argument automatically drops any observations containing NaN values across the selected variables:

df = pd.DataFrame({
    'wage': [25.5, 30.2, 19.8, 45.0, 32.1, 28.4, 38.6, 22.0],
    'education': [14, 16, 12, 18, 16, 14, 18, 12],
    'experience': [5, 8, 3, 15, 9, 6, 12, 2],
    'training': [1, 1, 0, 1, 0, 0, 1, 0]
})

Step 3: Add an explicit intercept in the array API

A critical technical distinction in statsmodels.api.OLS is that it does not include an intercept by default. To estimate a model with an intercept (β₀), you must explicitly prepend a constant column of ones to your exogenous design matrix using sm.add_constant():

y = df['wage']
X = df[['education', 'experience', 'training']]
X = sm.add_constant(X)

Step 4: Instantiate and fit the OLS model

Initialize the sm.OLS class with the endogenous response variable (endog) and exogenous regressors (exog), then invoke the .fit() method to estimate model parameters:

model = sm.OLS(y, X, missing='drop')
results = model.fit()
print(results.summary())

Step 5: Alternative formula interface (R-style syntax)

For researchers accustomed to R or handling categorical factors, statsmodels.formula.api.ols provides an intuitive string formula interface. Unlike the array interface, formulas automatically include an intercept and support factor encoding with C():

formula_model = smf.ols('wage ~ education + experience + C(training)', data=df)
formula_results = formula_model.fit()
print(formula_results.summary())

Step 6: Compute heteroskedasticity-consistent robust standard errors

When regression disturbances violate the constant variance assumption, conventional standard errors underestimate sampling variability. Apply heteroscedasticity-consistent robust standard errors (HC0–HC3) directly to your fitted model:

# Compute MacKinnon and White (1985) HC3 standard errors
robust_results = results.get_robustcov_results(cov_type='HC3')
print(robust_results.summary())

Output and how to read it

Printing results.summary() produces a comprehensive three-part diagnostic report. Understanding each section is vital for empirical verification and methodology reporting:

Table 1: Overall model fit and specification

  • R-squared / Adj. R-squared: The proportion of variance in the dependent variable explained by the regressors. Adjusted R² penalizes the addition of non-informative predictors.
  • F-statistic and Prob (F-statistic): The omnibus test evaluating the null hypothesis that all slope coefficients are simultaneously equal to zero. A p-value below 0.05 indicates overall statistical significance.
  • Log-Likelihood, AIC, and BIC: Information criteria used for model selection. Lower Akaike (AIC) and Bayesian (BIC) values indicate superior trade-offs between goodness-of-fit and model complexity.

Table 2: Parameter estimates and coefficient tests

  • coef: The estimated regression coefficient (β). In a multiple linear model, this represents the expected change in the dependent variable per one-unit increase in the predictor, holding all other variables constant.
  • std err: The standard error of the coefficient estimate, measuring sampling variability.
  • t and P>|t|: The t-statistic and corresponding two-tailed p-value testing the null hypothesis H₀: β = 0. Values with P < 0.05 are conventionally considered statistically significant.
  • [0.025 0.975]: The 95% confidence interval for the true population coefficient. If zero falls outside this interval, the coefficient is statistically significant at the 5% level.

Table 3: Residual diagnostics and specification checks

  • Omnibus & Prob(Omnibus): Tests the null hypothesis that regression residuals are normally distributed based on skewness and kurtosis. A significant p-value (p < 0.05) indicates non-normal residuals.
  • Durbin-Watson: Tests for first-order autocorrelation in residuals. Values near 2.0 indicate no autocorrelation; values substantially below 1.5 suggest positive serial correlation.
  • Jarque-Bera (JB) & Prob(JB): A complementary normality test based on asymptotic sample distributions.
  • Cond. No. (Condition Number): Measures collinearity among predictors. Values exceeding 30 indicate potential numerical instability due to severe multicollinearity, warranting formal checks of variance inflation factors (VIF).

Troubleshooting

Researchers encountering numerical warnings or unexpected statistics in statsmodels OLS can resolve common issues using these verified protocols:

1. Inflated R² approaching 0.99 with no constant term

Cause: Forgetting to call sm.add_constant(X) when using sm.OLS. Without an intercept, statsmodels computes the uncentered R², which measures total variation rather than variation around the mean, yielding artificially high values.

Solution: Always pass your exogenous array through X = sm.add_constant(X) before model fitting, or use smf.ols() which includes the constant term automatically.

2. LinAlgError: Singular matrix or extremely large condition number

Cause: Perfect multicollinearity between two or more predictors, or inclusion of a zero-variance constant column when sm.add_constant() is applied twice. Perfect collinearity prevents matrix inversion of (XᵀX).

Solution: Inspect correlations among predictors, drop redundant dummy variables (the “dummy variable trap”), or apply shrinkage methods such as Ridge versus LASSO penalized regression for high-dimensional feature spaces.

3. ValueError: missing=’none’ cannot handle missing values

Cause: The input data contains NaN, null, or infinite values while the missing parameter remains at its default value 'none'.

Solution: Pass missing='drop' during model instantiation (sm.OLS(y, X, missing='drop')), or pre-filter your DataFrame using df.dropna(subset=['y', 'x1', 'x2']).

4. Severe heteroskedasticity violating OLS assumptions

Cause: The variance of the error terms varies systematically across levels of the predictor variables, causing conventional standard errors to be biased downward.

Solution: Refit the model with heteroskedasticity-consistent standard errors using results.get_robustcov_results(cov_type='HC3') or cov_type='HC1'. Point estimates remain identical, while standard errors and p-values are adjusted for heteroskedasticity.

Free alternatives

Researchers seeking linear regression capabilities across different programming languages and statistical environments can evaluate several free, open-source alternatives:

Tool / Package Environment Interface Multi-Variable Support Built-in Diagnostics Best Research Application
statsmodels (OLS) Python Array & Formula Yes Comprehensive (3-table summary) Econometrics, social science research, and inferential regression in Python
stats::lm R Formula Yes Standard summary & plot diagnostics Biostatistics, academic psychology, and standard statistical modeling
scipy.stats.linregress Python Two 1-D arrays No (Univariate only) Minimal (slope, intercept, r, p, stderr) Fast bivariate linear fits and simple calibration curves
numpy.linalg.lstsq Python Matrix / Array Yes None (raw residuals & rank only) High-speed numerical linear algebra and inner loops of simulation algorithms
GLM.jl (lm) Julia Formula Yes Standard coefficient table High-performance scientific computing and large-scale econometric simulations

FAQ

What is the difference between sm.OLS and smf.ols in statsmodels?

sm.OLS belongs to the array API (statsmodels.api) and requires explicit numeric arrays or DataFrames for endog and exog, requiring the caller to manually add an intercept with sm.add_constant(). In contrast, smf.ols belongs to the formula API (statsmodels.formula.api), accepts an R-style formula string (such as 'y ~ x1 + x2') alongside a pandas DataFrame, includes an intercept by default, and automatically encodes categorical factors wrapped in C().

Why does statsmodels OLS not include an intercept by default?

The array interface sm.OLS is designed as a direct mathematical representation of matrix least squares, fitting the equation y = Xβ + ε. In matrix algebra, an intercept is simply a column of ones in the design matrix X. Omitting an automatic constant gives researchers complete control over whether the model runs through the origin (no-intercept regression) or includes custom fixed-effects structures.

How do I extract robust standard errors from statsmodels OLS?

You can obtain heteroskedasticity-robust standard errors by calling results.get_robustcov_results(cov_type='HC3') on your fitted results object, or by passing cov_type='HC3' directly into the fit method: model.fit(cov_type='HC3'). Available options include HC0 (White 1980), HC1, HC2, and HC3 (MacKinnon and White 1985 recommended for small-to-moderate samples).

How do I handle missing values in statsmodels regression?

By default, statsmodels sets missing='none', which raises an error if input arrays contain missing data. To drop missing values automatically, instantiate your model with sm.OLS(y, X, missing='drop') or smf.ols('y ~ x1', data=df, missing='drop'). Alternatively, clean your DataFrame beforehand using df.dropna().

What does a Condition Number above 30 mean in the summary table?

The Condition Number in Table 3 evaluates the ratio of the largest to smallest singular values of the design matrix X. A condition number exceeding 30 indicates moderate-to-severe multicollinearity between independent variables, meaning two or more regressors are highly correlated. This inflates standard errors and makes individual coefficient estimates sensitive to minor data perturbations.

Sources

The syntax, mathematical implementations, and diagnostic criteria in this guide are verified against official documentation and primary reference manuals:

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Stats OLS: Python Linear Regression Guide

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →