
Chris Parmer
2026-11-16
statsmodels demo
Statistical models and forecasting in Python, with Dash and Plotly
TL;DR
- statsmodels is the Python package for statistical models you need to explain and test, from regressions and mixed models to time series models such as SARIMAX and vector autoregressions (VARs), with the standard errors and tests that go with them. It began as the models module of SciPy, written by Jonathan Taylor, and became its own package during Google Summer of Code 2009.
- Coding agents know it well, so you can name the model in plain words and get working code. This demo shows what's possible through Macro Desk, a Dash app with five statsmodels models on public economic data, each refit when you change an input.
- Version 0.15.0 (August 27, 2026) adds a Diebold-Mariano test for comparing forecasts, accepts polars DataFrames and returns named results instead of bare tuples.
What is statsmodels?
Many analytical questions need an answer you can defend in a review: how much a price change moves demand, whether a treatment effect holds up across repeated patient visits, or whether a new forecast is really better than the old one. For those you need the estimate's standard error, its confidence interval and tests of the model's assumptions, and statsmodels reports all of them.
Every model works the same way: you fit it from arrays or from an R-style formula such as "sales ~ price + promo", and get back a results object with summary(), params, pvalues and predict(). That pattern covers linear and generalized linear models, mixed effects, survival analysis and time series, so the package turns up in many fields:
- Economics and finance: regressions with corrected standard errors, factor models, VARs and cointegration tests.
- Energy and utilities: seasonal decomposition and load or price forecasts with weather as an input.
- Pharma and life sciences: logistic regression, mixed models for repeated measurements and Poisson models for counts.
- Science and engineering: ANOVA for designed experiments, trend tests and autocorrelation checks on sensor residuals.
You don't need to know the API by heart. Name the model and the data, a coding agent writes the statsmodels code, and Dash turns it into an app where a colleague changes an input and the model refits. The app below runs on public economic data, and the same prompts work on load, sales or lab data. It's one of the apps in our guide to Python packages for data.
Demo App: Macro Desk
Macro Desk is a Dash app with five pages, one per model. It runs on eight monthly and daily series from FRED, the public database of the Federal Reserve Bank of St. Louis, and each page refits its model in a callback when you move a control. We deployed it privately to Plotly Cloud.
Start the build with one prompt for the shell and the data:
Prompt: Build a Dash app called Macro Desk with five tabs. Download these FRED series as CSV from https://fred.stlouisfed.org/graph/fredgraph.csv?id=<ID>: T10Y3M, T10Y2Y, USREC, CPIAUCSL, CPILFESL, DCOILWTICO, DCOILBRENTEU, IPG2211A2N. Average daily series to months, keep complete months only, and save one monthly and one daily Parquet file. Each tab gets a control bar, four KPI cards and Plotly charts in Inter on a white background. Every model runs with statsmodels inside a callback.
1. Probit regression: a probability from a leading indicator

A probit model turns a yes/no outcome into a probability. On this page the input is the yield curve, the spread between 10-year and 3-month Treasury yields, and the outcome is whether the economy is in a recession 12 months later, as dated by the National Bureau of Economic Research (NBER). The same setup fits any yes/no question with a leading indicator, such as whether a patient responds to a dose or a batch passes inspection.
Prompt: Recession odds tab: fit a probit with statsmodels.formula.api.probit, "ahead ~ spread", where ahead is USREC shifted forward by N months. Controls: which spread (T10Y3M or T10Y2Y) and N (3 to 18). Plot the predicted probability with recessions shaded, and the spread below it with a zero line. Cards: probability now, peak since 2022, spread now, McFadden pseudo R².
2. Vector autoregression: how oil prices move inflation

A VAR models several series that drive each other, and its impulse responses trace how a surprise in one moves the others month by month. This page fits one to monthly changes in West Texas Intermediate (WTI) crude oil, the headline Consumer Price Index (CPI) and core CPI, which leaves out food and energy. Headline inflation reacts in the month oil jumps and settles within about four months, while core barely moves.
Prompt: Oil shock tab: build monthly % changes of DCOILWTICO, CPIAUCSL and CPILFESL, fit statsmodels.tsa.api.VAR(...).fit(lags) with a lags slider (1-12) and a sample-start dropdown. Plot orthogonalized impulse responses to an oil shock with 95% bands from irf.stderr(orth=True), headline and core side by side on the same y-axis, and a bar chart of the forecast error variance decomposition (fevd) share from oil at 1, 3, 6, 12 and 24 months.
3. Cointegration: the Brent-WTI spread

Brent, the North Sea benchmark, and WTI price nearly the same oil, so each price wanders but the gap between them keeps coming back. Two series that behave like that are cointegrated. The page tests for that, estimates how fast the gap closes (half of it in 7.1 days since 2021) and marks the days when it's unusually wide. Traders run the same tests on pairs of stocks and on power and gas prices.
Prompt: Brent-WTI tab: daily DCOILBRENTEU and DCOILWTICO from a window-start dropdown. Run statsmodels.tsa.stattools.coint(brent, wti), fit sm.OLS(brent, add_constant(wti)) for the hedge ratio, and an AR(1) on the residual's changes for the half-life. Plot both prices, then the residual as a z-score with a threshold slider and points beyond it in pink.
Tip: start the window after April 20, 2020, when WTI settled below zero. With that day in the sample, it dwarfs every other gap.
4. STL decomposition: how seasonal is utility output?

Seasonal-Trend decomposition using LOESS (STL) splits a series into a trend, a seasonal pattern and a remainder. This page runs it on the Federal Reserve's index of electric and gas utilities output, with a slider for how fast the seasonal pattern may change. Almost all of the movement around the trend is the calendar (a seasonal strength of 0.93), with a winter heating peak, a smaller summer cooling peak and a low in spring.
Prompt: Seasonality tab: statsmodels.tsa.seasonal.STL(series, period=12, seasonal=<slider 7-35>, robust=<outliers checkbox>).fit() on IPG2211A2N since 1990. Plot observed, trend, seasonal and remainder as four stacked panels, plus a bar chart of the average seasonal effect by calendar month for the last three years. Card for seasonal strength, 1 - var(remainder) / var(seasonal + remainder).
5. SARIMAX: a forecast that beats "same month last year"

For a seasonal series, repeating the value from the same month last year is a hard forecast to beat. This page fits a seasonal ARIMA (SARIMA) model with statsmodels' SARIMAX class and backtests it by refitting month by month. The Diebold-Mariano test, new in 0.15, then checks whether the model's lower error could be luck, and here it says no, with a p-value of 0.0004.
Prompt: Forecast tab: SARIMAX on log(IPG2211A2N) since 1990 with a dropdown of three orders, including the airline model (0,1,1)(0,1,1,12). Plot history since 2019 and get_forecast(h) with 80% and 95% conf_int bands. Precompute a rolling backtest (refit monthly from 2021, one month ahead) and compare it with same-month-last-year using statsmodels.tsa.stattools.diebold_mariano_test with harvey_adj=True. Cards: next month with its interval, both errors, the DM p-value.
The test itself is one call:
from statsmodels.tsa.stattools import diebold_mariano_testdm = diebold_mariano_test(actual, model_fc, naive_fc, harvey_adj=True)dm.statistic, dm.pvalue # (-3.70, 0.0004): the model wins
What's possible
These are the statsmodels capabilities worth naming in a prompt, with the function names an agent will recognize:
- Regression tables: smf.ols("y ~ x1 + x2", data=df), with cov_type="HAC" when the errors are autocorrelated.
- Yes/no and count outcomes: smf.logit, smf.probit, and smf.glm with a Poisson family.
- Repeated measurements: smf.mixedlm with a random effect per patient, site or machine.
- Series that drive each other: VAR with irf() and fevd(), or VECM when they're cointegrated.
- Prices that move together: coint, adfuller and kpss.
- Seasonality and forecasts: STL, MSTL for several cycles, and SARIMAX with outside regressors such as temperature, then get_forecast(h).conf_int().
- Checking models and forecasts: acorr_ljungbox for leftover autocorrelation and diebold_mariano_test to compare two forecasts.
Other apps you can build with statsmodels
- Energy: an hourly load forecast with SARIMAX on temperature and MSTL for the daily and weekly cycles.
- Finance: a factor model explorer that runs rolling OLS of fund returns on market, size and value factors.
- Pharma: a trial readout app with mixedlm for repeated measurements per patient.
- Manufacturing: a drift monitor with Ljung-Box tests on sensor residuals.
- Public health: STL and Poisson GLMs on weekly case counts to flag unusual weeks.
What's new in statsmodels 0.15
statsmodels 0.15.0 came out on August 27, 2026, with work from 171 contributors over three years:
- Forecast tests: diebold_mariano_test and pesaran_timmermann. The Forecast page uses the first.
- polars input: models and the formula API accept polars DataFrames, so data loaded as in our polars demo goes straight in.
- Named results: coint, q_stat and others return NamedTuples, so res.pvalue works and unpacking still does.
- A second formula engine: formulaic can stand in for patsy.
- One rng keyword for randomness, replacing seed and random_state, which still work with a FutureWarning.
pip install -U statsmodels
Running statsmodels on Plotly Cloud and Dash Enterprise
What we learned deploying Macro Desk applies the same way on Dash Enterprise:
- Fit small models live and precompute the rest. The probit, VAR, cointegration and STL fits rerun on every change, while the backtest's SARIMA refits take minutes, so we ran them once and ship the result as Parquet.
- Ship Parquet, not raw downloads. The eight FRED series fit in 0.2 MB, and the app never calls FRED at run time.
- Set the index frequency (y.index.freq = "MS") so SARIMAX doesn't fill the logs with warnings.