Interrupted Time Series Segmented Regression: Centering, Seasonality, and Autocorrelation
Evaluating policy interventions without randomized controls requires segmented regression with centered time parameters. Here is how to estimate immediate level and slope changes while correcting serial correlation and seasonality.
HumanPen Team
· 12 min read
How Does Interrupted Time Series Segmented Regression Identify Policy Impacts?
Interrupted Time Series (`ITS`) segmented regression estimates immediate level shifts and post-intervention slope changes by modeling pre-existing trends, an intervention indicator `X_t`, and centered post-intervention elapsed time `(T - T_0) × X_t`. Autocorrelation is diagnosed via Breusch-Godfrey tests and corrected using Newey-West `HAC` robust standard errors or Prais-Winsten Generalized Least Squares (`GLS`), while recurring cycles are controlled through Fourier harmonics or calendar indicators.
| Estimation Method | Point Estimates vs Standard Errors | Autocorrelation & Seasonality Strategy | Recommended Applied Setting |
|---|---|---|---|
| OLS with Newey-West HAC | Standard OLS coefficients remain unchanged; standard errors adjust asymptotically for heteroskedasticity and autocorrelation | Nonparametric Bartlett kernel across prespecified lag L; seasonality controlled via exogenous Fourier harmonics | Continuous outcomes with moderate-to-large sample size where maintaining standard linear regression coefficients is required |
| Prais-Winsten AR(1) GLS | Transforms outcome and predictors via estimated autocorrelation parameter rho; preserves initial observation | Directly models stationary first-order autoregressive error process; combined with seasonal indicators or harmonics | Short-to-moderate time series with verified first-order AR(1) residual dependence where maximum estimator efficiency is needed |
| Count GLM (Poisson / NB) + Harmonics | Estimates multiplicative rate ratios via log link; accounts for overdispersion with negative binomial dispersion parameter | Fourier sine-cosine harmonics absorb smooth annual cycles; robust standard errors correct residual temporal dependence | Discrete event counts such as hospital admissions, adverse drug events, or monthly infection counts with non-negative bounds |
Quasi-experimental evaluations in epidemiology, public health, health economics, and public administration often evaluate interventions implemented at a specific calendar date across an entire jurisdiction or hospital network where randomized control groups are unfeasible. By tracking a consistent cohort or population across evenly spaced time intervals before and after the event, ITS establishes a baseline trajectory and projects the counterfactual path—the expected outcome if the intervention had not occurred. Comparing observed post-intervention observations against this counterfactual isolates the intervention's impact from underlying historical trends.
Causal identification in interrupted time series regression rests on establishing a valid pre-intervention secular trend to project the counterfactual; centering time at the intervention threshold ensures the level change parameter reflects the immediate policy impact rather than an arbitrary backward extrapolation.
Centered Level and Slope Parameterization: The Bernal et al. Corrigendum
The standard linear segmented regression model specifies the outcome as: `Y_t = β_0 + β_1 T + β_2 X_t + β_3 (T - T_0) X_t + e_t`. In this specification, `Y_t` represents the continuous aggregate outcome measured at equally spaced time point `t`; `T` is a continuous time index counting sequentially from the beginning of the study (`1, 2, ..., N`); `X_t` is a binary indicator set to `0` prior to the intervention and `1` from the intervention onset onward; `T_0` denotes the specific time point marking the start of the intervention; `(T - T_0) × X_t` represents the centered time elapsed since the intervention onset; and `e_t` represents the error term. Under this parameterization, `β_0` captures the baseline level at the start of the series (`T = 0`), `β_1` reflects the secular pre-intervention trend per time unit, `β_2` measures the immediate level jump at the moment of intervention (`T = T_0`), and `β_3` captures the slope change representing the trajectory divergence following the policy.
The necessity of time centering was formally highlighted in the corrigendum published by Bernal, Cummins, and Gasparrini in the International Journal of Epidemiology (`PMCID: PMC7750921`, `DOI: 10.1093/ije/dyaa118`). In their original 2017 tutorial (`PMC5407170`), the model was initially formulated with an uncentered interaction term `β_3 T X_t`. In that uncentered formulation, evaluating the model at `T = T_0` yields an interaction value of `β_3 T_0`, forcing `β_2` to capture the level difference extrapolated backward to `T = 0` (the start of the historical study window) rather than the immediate level shift at the policy onset. Centering time as `(T - T_0) × X_t` ensures the interaction evaluates to zero at `T = T_0`, correctly isolating `β_2` as the direct, immediate step change relative to the pre-existing secular trend.
Pay close attention to index coding: if post-intervention time (T - T_0) × X_t is coded as 0, 1, 2, ... starting at 0 on the first post-intervention observation T_0, β_2 represents the exact level jump at T_0; if coded as 1, 2, 3, ... per Wagner et al. (2002), the predicted jump at T_0 equals β_2 + β_3.
- 1. Ensure time interval regularity: Verify that observations are spaced at strictly equal calendar intervals (such as consecutive months or quarters) without missing time slices or irregular gaps.
- 2. Define the exact intervention onset `T_0`: Explicitly pinpoint the boundary period where the intervention became operational, coding `X_t = 0` for all baseline periods and `X_t = 1` for all post-intervention periods.
- 3. Construct centered post-intervention elapsed time: Calculate `(T - T_0) × X_t` so that elapsed time remains zero prior to `T_0` and begins counting sequentially from the policy date.
- 4. Avoid dogmatic sample size rules: Dispel the misconception that ITS requires a rigid minimum of 8 or 12 points before and after; as Bernal et al. (2017) emphasize, statistical power depends on outcome variability, effect size, balanced pre/post allocation, and spanning multiple full seasonal cycles.
Diagnosing Autocorrelation, Seasonality, and Implementation Phase-In Windows
In longitudinal time series, consecutive observations frequently exhibit temporal correlation. When positive serial correlation is present, ordinary least squares residual errors violate the independence assumption, causing standard OLS formulas to underestimate standard errors, narrow confidence intervals, and inflate test statistics. This can lead researchers to declare policy effects statistically significant when observed changes are merely routine temporal fluctuations. Validating an interrupted time series design requires systematically inspecting residual time series plots, the sample Autocorrelation Function (`ACF`), and the Partial Autocorrelation Function (`PACF`) across multiple seasonal lags.
The classic Durbin-Watson statistic implemented in `statsmodels.stats.stattools.durbin_watson` measures first-order serial correlation as `sum((e_t - e_{t-1})^2) / sum(e_t^2)`. Values near 2 indicate no first-order serial correlation, values towards 0 indicate positive correlation, and values towards 4 indicate negative correlation. However, Durbin-Watson only checks first-order `AR(1)` processes and does not provide p-values in `statsmodels`. In contrast, the Breusch-Godfrey Lagrange Multiplier test—called via `statsmodels.stats.diagnostic.acorr_breusch_godfrey(res, nlags=12, result_object=True)` in Python or `lmtest::bgtest(model, order = 12)` in R—regresses residuals on lagged residuals and exogenous regressors, providing a formal hypothesis test for higher-order serial correlation and 12-month seasonal persistence.
- 1. Control calendar seasonality via Fourier terms: Model recurring monthly cycles using harmonic sine and cosine pairs `sin(2 × pi × k × t / 12)` and `cos(2 × pi × k × t / 12)` for harmonics `k = 1, 2`, which smoothly absorb annual temperature or operational cycles while preserving degrees of freedom compared to 11 individual month indicator dummies.
- 2. Quarantine implementation and transition lags: When institutional rollouts involve phase-in grace periods, training lags, or anticipatory stockpiling, exclude or model the transition window separately to avoid contaminating the immediate jump parameter `β_2`.
- 3. Project counterfactual trajectories: Compute and plot the counterfactual path setting `X_t = 0` for all post-intervention periods alongside historical observations, displaying the divergence between actual outcomes and the expected secular trend.
- 4. Strengthen causal validity with controlled ITS (`CITS`): If concurrent external shocks (such as simultaneous regulatory changes or macroeconomic disruptions) cannot be ruled out, incorporate an unaffected comparison series or negative-control outcome in a comparative ITS framework.
In many public health and administrative time series, apparent serial correlation is driven primarily by unmodeled seasonal oscillations; once Fourier harmonic pairs or calendar controls are incorporated into the specification, residual autocorrelation is frequently reduced or eliminated.
Correcting Serial Correlation in Python and R: Newey-West HAC, Prais-Winsten, and CITS
When residual autocorrelation persists after controlling for seasonality, empirical researchers must apply appropriate econometric remedies. Newey-West Heteroskedasticity and Autocorrelation Consistent (`HAC`) standard errors leave OLS parameter estimates unchanged while adjusting covariance matrices asymptotically. In Python `statsmodels`, calling `.fit(cov_type='HAC', cov_kwds={'maxlags': L})` or `OLSResults.get_robustcov_results(cov_type='HAC', maxlags=L, use_t=True)` requires passing `use_t=True` because the default evaluation uses standard normal critical values, which produce anti-conservative p-values in typical short ITS datasets where sample sizes are below 50 time points.
| Analysis Task | Python statsmodels Implementation | R Package Implementation | Methodological Notes |
|---|---|---|---|
| Baseline Segmented OLS | `smf.ols('y ~ time + post + time_after', data=df).fit()` | `lm(y ~ time + post + time_after, data=df)` | Requires centered time parameterization to isolate immediate level jump at intervention onset |
| Autocorrelation Diagnostic | `acorr_breusch_godfrey(res, nlags=12, result_object=True)` | `lmtest::bgtest(model, order = 12)` | Checks higher-order and seasonal lag correlation; opt in to result_object in statsmodels 0.15.0 |
| Newey-West HAC Standard Errors | `res.get_robustcov_results(cov_type='HAC', maxlags=L, use_t=True)` | `lmtest::coeftest(model, vcov = sandwich::NeweyWest(model, lag = L))` | Preserves OLS point estimates; passing use_t=True enforces Student t inference in small samples |
| Prais-Winsten AR(1) GLS | `sm.GLSAR(endog, exog, rho=1).iterative_fit()` | `prais::prais_winsten(formula, data=df, index='time')` | Transforms data to eliminate AR(1) errors; preserves initial observation unlike Cochrane-Orcutt |
| Count Data with Overdispersion | `smf.negativebinomial('y ~ time + post + time_after', data=df, offset=np.log(df['pop'])).fit()` | `MASS::glm.nb(y ~ time + post + time_after + offset(log(pop)), data=df)` | Ensures non-negative predictions and models overdispersion with log link and population offset |
While Cochrane-Orcutt estimation discards the initial observation `t = 1`, Prais-Winsten Generalized Least Squares (implemented in R via `prais::prais_winsten` or Python `GLSAR`) preserves the full sample by applying the stationary transformation `sqrt(1 - rho^2) × Y_1` to the first time point. When residual processes involve mixed autoregressive and moving average dynamics, researchers estimate regression with ARMA errors via `nlme::gls(..., correlation = corARMA(p = p, q = q))` in R or `SARIMAX(endog, exog=..., order=(p, 0, q))` via maximum likelihood in Python. For count outcomes such as hospital infection counts or emergency visits, fitting Generalized Linear Models (`GLM`) with Poisson or Negative Binomial distributions and log link functions ensures strictly non-negative predictions.
Choosing between Newey-West HAC and Prais-Winsten GLS depends on modeling objectives: Newey-West preserves standard OLS regression coefficients while inflating standard errors to reflect serial dependence, whereas Prais-Winsten transforms the underlying data structure to yield more efficient parameter estimates under a verified AR(1) error process.
Generating Counterfactual Plots and Reproducible ITS Pipelines in HumanPen Start Project
Translating longitudinal tracking records into publication-grade empirical chapters requires coordinating data cleaning, centered parameterizations, autocorrelation diagnostics, and publication figures. In HumanPen Start Project, researchers can upload time series data alongside study protocols to generate verified segmented regression pipelines. Attach your data and papers, describe what you need, approve the plan before work starts, and get the reviewed report, charts, and code ready to preview online or download.
File uploads accommodate Excel spreadsheets, CSV tables, Word manuscripts, PDF protocols, and zip archives up to 2 GB total per project. Computations run inside private, isolated sandboxes executing native Python or R environments. Legacy time series analyses previously performed in SPSS or Stata are re-implemented into reproducible Python or R code with matched standard error formulas. If your project utilizes institutional data from commercial portals such as CNKI or Wind, raw series must be exported and uploaded directly by the user. GPU training is not supported. Projects are encrypted in transit, never used to train public models, and retained for 6 months (180 days) after the last activity with an advance 3-day expiration alert, with permanent user deletion supported at any time.
Applied researchers frequently evaluate whether an interrupted time series is preferable to a staggered difference-in-differences panel (when policies roll out across multiple jurisdictions at different times), a regression discontinuity design (when intervention assignment follows a continuous eligibility threshold), or an end-to-end public microdata empirical paper. For an illustrative example of large-scale panel harmonization, inspect the public 311 urban microdata empirical paper on the example projects page, which demonstrates how multi-source temporal records are matched with environmental covariates to evaluate policy mechanisms.
Deliverables produced in Start Project serve as a reproducible methodological and learning reference scaffold; researchers must independently verify underlying data, inspect diagnostic residual plots, disclose analytical tools in accordance with journal policies, and assume full responsibility for academic integrity.
Frequently Asked Questions About Interrupted Time Series Regression
When should I choose OLS with Newey-West standard errors over Prais-Winsten GLS? Use Ordinary Least Squares with Newey-West HAC standard errors when your primary goal is to retain standard OLS point estimates while ensuring hypothesis tests are robust to arbitrary heteroskedasticity and residual autocorrelation up to lag L. Opt for Prais-Winsten Generalized Least Squares when residual diagnostics demonstrate pure first-order autoregressive AR(1) errors and you require maximum estimator efficiency in small or moderate samples.
How many time points before and after an intervention are required for a credible ITS study? There is no single universal cutoff such as a rigid rule of 8 or 12 points. As Bernal et al. (2017) emphasize, statistical power depends on effect magnitude, outcome variance, balanced allocation across pre- and post-intervention periods, and whether the sample spans multiple full annual cycles (typically at least 24 to 36 monthly observations) to separate seasonal harmonics from secular trends.
How should I handle a gradual rollout where an intervention takes several months to implement? When policy implementation involves an institutional rollout delay or an adaptation period, treating the transition phase as an immediate jump distorts both level and slope parameters. Researchers should quarantine the transition window by either defining an explicit phase-in dummy, modeling a polynomial ramp function, or temporarily excluding the transition months from the baseline regression to estimate clean pre- and post-adaptation trajectories.
How does HumanPen Start Project protect sensitive institutional and clinical time series? Data uploaded to Start Project is encrypted in transit and isolated within dedicated virtual execution environments. Files are never shared across users or used to train public machine learning models. Project records are retained for 6 months (180 days) after the last activity with an automated alert sent 3 days prior to expiration, and users can trigger immediate permanent deletion at any time.
Sources
- Bernal, Cummins & Gasparrini (2017, International Journal of Epidemiology) — Interrupted time series regression for the evaluation of public health interventions: a tutorial — Foundational tutorial establishing the three-variable parameterization, counterfactual trend projection, Fourier seasonality controls, and power considerations.
- Bernal, Cummins & Gasparrini (2021, International Journal of Epidemiology) — Corrigendum to: Interrupted time series regression for the evaluation of public health interventions: a tutorial — Official corrigendum rectifying the segmented regression equation to center post-intervention elapsed time at (T - T_0), ensuring β_2 measures the immediate level change.
- Wagner et al. (2002, Journal of Clinical Pharmacy and Therapeutics) — Segmented regression analysis of interrupted time series studies in medication use research — Classic clinical and health services framework defining level and trend changes and segmented regression reporting conventions.
- Statsmodels Development Team — Breusch-Godfrey Lagrange Multiplier Test Documentation (acorr_breusch_godfrey) — Technical reference for residual autocorrelation diagnostics and the version 0.15.0 result_object parameter specification.
- Statsmodels Development Team — Robust Covariance Estimation Documentation (get_robustcov_results) — Technical specification for Newey-West HAC covariance kernels, lag selection, and the use_t small-sample inference flag.
KEEP READING
Linear Mixed-Effects Models: lme4, Singular Fits, and REML Guide
14 min read
Tools & workflowOrdinal vs Multinomial Logistic Regression: Proportional Odds, Brant Test, and Sign Traps
13 min read
Tools & workflowPoisson vs Negative Binomial vs Zero-Inflated Count Regression Guide
16 min read