Interrupted time series
Fit a series' level and trend before and after an intervention, and use placebo dates to compare effect sizes, because p-values run too small on short series.
What runs in CodeSplash
- STAT194Durbin–Watson test Runs in CodeSplash
- STAT212Ljung–Box portmanteau test Runs in CodeSplash
- Interrupted time series (segmented regression) Verified in Python and R
You will be able to
- Separate a level change from a change in trend
- Explain why autocorrelation matters here, and what Durbin–Watson and Ljung–Box show
- Use placebo dates to judge size rather than significance
Read first
One series, one date
ReadA hospital introduces a policy in January 2021. There's no comparison hospital, only monthly admissions: 48 months before and 36 after.
An interrupted time seriesInterrupted time seriesFits a series' level and trend before and after an intervention and reports the changes. models what the old trend predicts, and compares:
is the immediate change in level, and is the change in trend.
It's the weakest quasi-experimental design here, since no comparison units rule out anything else that changed that month.
Read both changes
In the applevel change = −6.50, SE = 1.27, p < .001; slope change = −0.352, SE = 0.056, p < .001
- Level change
- −6.500
- 95% CI
- [−9.162, −3.838]
- p
- < .001
- Slope change (per period)
- −0.3519
- p (slope)
- < .001
- Effect at the last period
- −18.816
Plots
View data
| kind | month | admissions |
|---|---|---|
| actual | 1,483,228,800,000 | 121.99 |
| actual | 1,485,907,200,000 | 120.86 |
| actual | 1,488,326,400,000 | 127.16 |
| actual | 1,491,004,800,000 | 131.74 |
| actual | 1,493,596,800,000 | 125.45 |
| actual | 1,496,275,200,000 | 123.03 |
| actual | 1,498,867,200,000 | 123.42 |
| actual | 1,501,545,600,000 | 118.87 |
| actual | 1,504,224,000,000 | 116.91 |
| actual | 1,506,816,000,000 | 117.11 |
| actual | 1,509,494,400,000 | 119.06 |
| actual | 1,512,086,400,000 | 122.21 |
| actual | 1,514,764,800,000 | 124.32 |
| actual | 1,517,443,200,000 | 131.37 |
| actual | 1,519,862,400,000 | 128.61 |
| actual | 1,522,540,800,000 | 134.18 |
| actual | 1,525,132,800,000 | 128.37 |
| actual | 1,527,811,200,000 | 127.08 |
| actual | 1,530,403,200,000 | 125.46 |
| actual | 1,533,081,600,000 | 125.65 |
| actual | 1,535,760,000,000 | 119.58 |
| actual | 1,538,352,000,000 | 116.75 |
| actual | 1,541,030,400,000 | 118.82 |
| actual | 1,543,622,400,000 | 118.93 |
| actual | 1,546,300,800,000 | 124.93 |
| actual | 1,548,979,200,000 | 127.03 |
| actual | 1,551,398,400,000 | 132.45 |
| actual | 1,554,076,800,000 | 133.41 |
| actual | 1,556,668,800,000 | 129.09 |
| actual | 1,559,347,200,000 | 128.35 |
| actual | 1,561,939,200,000 | 128.93 |
| actual | 1,564,617,600,000 | 127.82 |
| actual | 1,567,296,000,000 | 125.22 |
| actual | 1,569,888,000,000 | 121.43 |
| actual | 1,572,566,400,000 | 122.17 |
| actual | 1,575,158,400,000 | 126.23 |
| actual | 1,577,836,800,000 | 129.31 |
| actual | 1,580,515,200,000 | 135.71 |
| actual | 1,583,020,800,000 | 138.57 |
| actual | 1,585,699,200,000 | 136.85 |
| actual | 1,588,291,200,000 | 135.86 |
| actual | 1,590,969,600,000 | 133.59 |
| actual | 1,593,561,600,000 | 129.13 |
| actual | 1,596,240,000,000 | 128.92 |
| actual | 1,598,918,400,000 | 125.94 |
| actual | 1,601,510,400,000 | 125.15 |
| actual | 1,604,188,800,000 | 126.90 |
| actual | 1,606,780,800,000 | 129.71 |
| actual | 1,609,459,200,000 | 127.20 |
| actual | 1,612,137,600,000 | 125.31 |
| actual | 1,614,556,800,000 | 125.49 |
| actual | 1,617,235,200,000 | 131.80 |
| actual | 1,619,827,200,000 | 129.95 |
| actual | 1,622,505,600,000 | 127.84 |
| actual | 1,625,097,600,000 | 125.96 |
| actual | 1,627,776,000,000 | 123.30 |
| actual | 1,630,454,400,000 | 122.38 |
| actual | 1,633,046,400,000 | 119.93 |
| actual | 1,635,724,800,000 | 118.51 |
| actual | 1,638,316,800,000 | 123.43 |
First 60 of 204 rows.
Assumptions
- Enough pre-intervention points — 48 pre-intervention and 36 post-intervention periods.
- Residual autocorrelation — Ljung–Box test on the residuals (lag 10) p = .178; Durbin–Watson 1.45.
- AR(1) describes the errors — Ljung–Box test on the whitened residuals (lag 10) p = .980; estimated ρ = 0.32.
- No co-intervention — A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series.
Segmented regression (AR(1) errors by REML with Satterthwaite df)
| Term | Estimate | SE | t | df | p |
|---|---|---|---|---|---|
| const | 121.00 | 1.054 | 114.79 | 28.228 | 3.074e-39 |
| time | 0.2390 | 0.0305 | 7.843 | 14.274 | 1.518e-6 |
| level_change | −6.500 | 1.265 | −5.138 | 17.627 | 7.346e-5 |
| slope_change | −0.3519 | 0.0557 | −6.322 | 13.283 | 2.401e-5 |
| season_1 | 3.058 | 0.9293 | 3.291 | 56.060 | 0.0017 |
| season_2 | 6.030 | 1.069 | 5.641 | 68.799 | 3.468e-7 |
| season_3 | 7.194 | 1.111 | 6.473 | 62.001 | 1.738e-8 |
| season_4 | 3.466 | 1.126 | 3.079 | 56.535 | 0.0032 |
| season_5 | 1.084 | 1.132 | 0.9571 | 54.002 | 0.3428 |
| season_6 | −0.3090 | 1.136 | −0.2720 | 53.141 | 0.7867 |
| season_7 | −1.629 | 1.139 | −1.431 | 53.436 | 0.1584 |
| season_8 | −4.981 | 1.139 | −4.372 | 55.253 | 5.493e-5 |
| season_9 | −6.473 | 1.133 | −5.715 | 59.799 | 3.695e-7 |
| season_10 | −5.863 | 1.102 | −5.319 | 67.261 | 1.283e-6 |
| season_11 | −3.476 | 0.9868 | −3.523 | 64.504 | 0.0008 |
- Intervention starts at 2021-01-01; 48 periods before and 36 after. Slope change is measured from the first post-intervention period.
- AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives p < .001 for the level change and p < .001 for the slope change, but rejects too often on series this short.
The exact R script · R R version 4.5.1 (2025-06-13)
# Interrupted time series (segmented regression)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.its 1.2.2 · spec 022bd149b9652330
# Dataset: c1_its (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_its.parquet", col_select = c("admissions", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("admissions", "month")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("admissions", "month")) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y <- "admissions"
TIME <- "month"
POST <- NULL
COVARIATES <- c()
TEMPORAL <- TRUE
conf <- 0.95
season <- as.integer(12)
df <- df[order(df[[TIME]], method = "radix"), , drop = FALSE]
times <- if (TEMPORAL) as.Date(df[[TIME]], tz = "UTC") else as.numeric(df[[TIME]])
if (anyDuplicated(times)) stop(sprintf("%s must have one row per period; found repeated periods.", TIME))
n <- nrow(df)
idx <- seq_len(n) - 1 # period index 0 … n − 1 (one row per period)
if (!is.null(POST)) {
post_level <- NULL
levels_post <- levels(df[[POST]])
if (is.null(post_level)) post_level <- if ("true" %in% levels_post) "true" else levels_post[length(levels_post)]
post <- as.character(df[[POST]]) == post_level
if (any(post) && !all(post[which(post)[1]:n])) stop(sprintf("%s must stay on once the intervention starts.", POST))
} else {
start_text <- trimws("2021-01-01")
if (!nzchar(start_text)) stop("Set 'Intervention starts' or choose an 'After intervention' column.")
start <- if (TEMPORAL) as.Date(start_text) else as.numeric(start_text)
post <- times >= start
}
if (all(post) || !any(post)) {
cs_error("CS_E_UNDEFINED", what = "The interrupted time series", reason = "the series needs periods both before and after the intervention")
}
first_post <- which(post)[1] - 1 # 0-based
step <- as.numeric(post)
since <- ifelse(post, idx - first_post, 0) # 0 in the first post-intervention period
X <- data.frame(const = 1, time = idx, level_change = step, slope_change = since)
if (season > 1) {
month <- if (TEMPORAL) as.integer(format(times, "%m")) else NULL
code <- if (TEMPORAL && season == 12) month - 1L else if (TEMPORAL && season == 4) (month - 1L) %/% 3L else as.integer(idx %% season)
for (s in seq_len(season - 1)) if (any(code == s)) X[[paste0("season_", s)]] <- as.numeric(code == s)
}
for (j in seq_along(COVARIATES)) X[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
y <- as.numeric(df[[Y]])
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y) # a flat series fits exactly: no level or slope change to estimate
k <- ncol(X)
hac_lag <- NULL
lag <- if (!is.null(hac_lag)) as.integer(hac_lag) else as.integer(floor(4 * (n / 100)^(2 / 9)))
# %% Fit both ways. OLS with Newey–West standard errors (Bartlett weights, no prewhitening, n/(n − k)), and
# regression with AR(1) errors by REML with Satterthwaite df, which holds its error rate on short series.
fit <- lm(y ~ 0 + ., data = cbind(y = y, X))
b_nw <- coef(fit)
V_nw <- sandwich::NeweyWest(fit, lag = lag, prewhite = FALSE, adjust = TRUE)
names_x <- names(X)
il <- match("level_change", names_x); isl <- match("slope_change", names_x)
dof <- n - k
Xm <- as.matrix(X)
reml <- tryCatch(cs_its_reml_ar1(y, Xm), error = function(e) { warnings <<- c(warnings, paste(conditionMessage(e), "Using Newey–West standard errors instead.")); NULL })
use_reml <- "reml_ar1" == "reml_ar1" && !is.null(reml)
if (use_reml) {
b <- setNames(reml$b, names_x)
V <- matrix(reml$V, k, k, dimnames = list(names_x, names_x))
dfs <- setNames(reml$df, names_x)
} else {
b <- b_nw
V <- V_nw
dfs <- setNames(rep(as.numeric(dof), k), names_x)
}
inference_label <- if (use_reml) "AR(1) errors by REML with Satterthwaite df" else sprintf("Newey–West, lag %d", lag)
coef_row <- function(name) {
est <- unname(b[name]); se <- sqrt(V[name, name]); t <- est / se; df <- unname(dfs[name])
qt_ <- qt(0.5 + conf / 2, df)
c(est = est, se = se, t = t, df = df, p = 2 * pt(-abs(t), df), lo = est - qt_ * se, hi = est + qt_ * se)
}
nw_p <- function(i) 2 * pt(-abs(unname(b_nw[i])) / sqrt(V_nw[i, i]), dof)
lv <- coef_row("level_change")
sl <- coef_row("slope_change")
pre_slope <- unname(b["time"])
# Effect at the last period = level change + slope change × periods since the start.
h <- since[n]
effect_end <- lv[["est"]] + sl[["est"]] * h
effect_end_se <- sqrt(V["level_change", "level_change"] + h * h * V["slope_change", "slope_change"] + 2 * h * V["level_change", "slope_change"])
fitted_v <- drop(Xm %*% unname(b))
counterfactual <- fitted_v - lv[["est"]] * step - sl[["est"]] * since
relative_end <- if (counterfactual[n] != 0) effect_end / counterfactual[n] else NULL
# %% Checks
# Durbin–Watson and Ljung–Box read the least-squares residuals, which show what the errors are like before any model of them.
resid <- unname(residuals(fit))
dw <- sum(diff(resid)^2) / sum(resid^2)
lb_lag <- max(1L, min(10L, n %/% 5L))
lb_p <- Box.test(resid, lag = lb_lag, type = "Ljung-Box")$p.value
# The whitened residuals are independent if AR(1) describes the errors; their null is simulated.
white_lag <- max(2L, lb_lag)
white_p <- if (!is.null(reml) && n > white_lag + 1L) cs_its_white_noise_test(reml$white, Xm, reml$rho, white_lag, 499L, 42)$p else NULL
n_pre <- first_post
n_post <- n - first_post
checks <- list()
if (n_pre < 8) {
checks[[length(checks) + 1]] <- list(id = "pre_points", label = "Enough pre-intervention points", status = "concern", downgrade_to = "L2",
detail = sprintf("Only %d pre-intervention periods; the pre-trend (and so the counterfactual) is poorly estimated — aim for 8 or more.", n_pre))
} else {
checks[[length(checks) + 1]] <- list(id = "pre_points", label = "Enough pre-intervention points", status = "pass",
detail = sprintf("%d pre-intervention and %d post-intervention periods.", n_pre, n_post))
}
if (lb_p < 0.05) {
checks[[length(checks) + 1]] <- list(id = "autocorrelation", label = "Residual autocorrelation", status = "concern",
detail = paste0(sprintf("Ljung–Box test on the residuals (lag %d) %s: errors are autocorrelated; ", lb_lag, cs_fmt_p(lb_p)),
if (use_reml) sprintf("the AR(1) error model (ρ = %.2f) allows for it.", reml$rho) else sprintf("Newey–West standard errors (lag %d) allow for it, but consider an AR(1) error model.", lag)))
} else {
checks[[length(checks) + 1]] <- list(id = "autocorrelation", label = "Residual autocorrelation", status = "pass",
detail = sprintf("Ljung–Box test on the residuals (lag %d) %s; Durbin–Watson %.2f.", lb_lag, cs_fmt_p(lb_p), dw))
}
if (use_reml && !is.null(white_p)) {
if (white_p < 0.05) {
checks[[length(checks) + 1]] <- list(id = "ar1_errors", label = "AR(1) describes the errors", status = "concern",
detail = sprintf("Ljung–Box test on the whitened residuals (lag %d) %s: the errors have structure AR(1) misses, so p-values may run small. Add seasonal terms or covariates if they explain it.", white_lag, cs_fmt_p(white_p)))
} else {
checks[[length(checks) + 1]] <- list(id = "ar1_errors", label = "AR(1) describes the errors", status = "pass",
detail = sprintf("Ljung–Box test on the whitened residuals (lag %d) %s; estimated ρ = %.2f.", white_lag, cs_fmt_p(white_p), reml$rho))
}
}
reml_p_at <- function(i) 2 * pt(-abs(reml$b[i]) / sqrt(reml$V[i, i]), reml$df[i])
if (!use_reml && n < 240) {
checks[[length(checks) + 1]] <- list(id = "short_series", label = "Long enough for Newey–West", status = "concern",
detail = paste0(sprintf("With %d periods, Newey–West level tests reject too often: about 10–27%% at the 5%% level for 24–72 periods in simulations with no effect, still 7–13%% at 240.", n),
if (!is.null(reml)) sprintf(" The AR(1) model gives %s for the level change.", cs_fmt_p(reml_p_at(il))) else ""))
}
checks[[length(checks) + 1]] <- list(id = "cointervention", label = "No co-intervention", status = "info",
detail = "A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series.")
fmt_time <- function(v) if (TEMPORAL) format(v, "%Y-%m-%d") else as.numeric(v)
start_label <- fmt_time(times[first_post + 1])
# %% Robustness: a change at the intervention, the strongest break date, placebo dates
robust_keys <- c("chow_f", "chow_p", "chow_hac_f", "chow_hac_p", "chow_reml_f", "chow_reml_df2", "chow_reml_p", "supf_stat", "supf_p", "supf_crit", "supf_break", "supf_at_intervention", "placebo_n", "placebo_rejected", "placebo_min_p", "placebo_larger")
robust_values <- setNames(vector("list", length(robust_keys)), robust_keys)
set_robust <- function(x) robust_values[names(x)] <<- x
robust_tables <- list(); robust_charts <- list()
if (FALSE) {
common <- which(!(names_x %in% c("level_change", "slope_change")))
chow <- cs_its_chow_at(y, Xm, c(il, isl), V_nw)
set_robust(list(chow_f = chow$f, chow_p = chow$p, chow_hac_f = chow$hac_f, chow_hac_p = chow$hac_p))
wald <- if (!is.null(reml)) cs_its_reml_wald(reml, c(il, isl)) else NULL
if (!is.null(wald)) set_robust(list(chow_reml_f = wald$f, chow_reml_df2 = wald$df2, chow_reml_p = wald$p))
if (use_reml) {
checks[[length(checks) + 1]] <- list(id = "chow", label = "A change at the intervention", status = if (wald$p < 0.05) "pass" else "info",
detail = sprintf("Level and slope together: F(%d, %.1f) = %.2f with AR(1) errors, %s.", wald$df1, wald$df2, wald$f, cs_fmt_p(wald$p)))
} else {
checks[[length(checks) + 1]] <- list(id = "chow", label = "A change at the intervention", status = if (chow$hac_p < 0.05) "pass" else "info",
detail = sprintf("Level and slope together: F(%d, %d) = %.2f with Newey–West errors, %s.", chow$df1, chow$df2, chow$hac_f, cs_fmt_p(chow$hac_p)))
}
search <- tryCatch(cs_its_sup_f(y, Xm[, common, drop = FALSE], 0.15, 999L, 42, if (!is.null(reml)) reml$rho else 0), error = function(e) { warnings <<- c(warnings, conditionMessage(e)); NULL })
if (!is.null(search)) {
near <- abs((search$break_row - 1L) - first_post) <= max(2L, as.integer(ceiling(0.05 * n)))
break_label <- fmt_time(times[search$break_row])
set_robust(list(supf_stat = search$stat, supf_p = search$p, supf_crit = search$crit, supf_break = break_label, supf_at_intervention = near))
if (search$p < 0.05 && !near) {
checks[[length(checks) + 1]] <- list(id = "break_elsewhere", label = "The strongest break is at the intervention", status = "concern", downgrade_to = "L2",
detail = sprintf("The series changes most at %s, not at the intervention (%s): sup-F = %.2f, %s. Something else may be driving the change.", as.character(break_label), as.character(start_label), search$stat, cs_fmt_p(search$p)))
} else {
checks[[length(checks) + 1]] <- list(id = "break_elsewhere", label = "The strongest break is at the intervention", status = "pass",
detail = sprintf("The strongest break is at %s (sup-F = %.2f, %s), %s", as.character(break_label), search$stat, cs_fmt_p(search$p), if (near) "close to the intervention." else "and no break stands out from chance."))
}
robust_charts[[1]] <- cs_chart("break_search", "fstat-sequence", "F for a change in level and slope at each date", list(
x = cs_col(TIME, fmt_time(times[search$candidates]), kind = if (TEMPORAL) "temporal" else "numeric"),
y = cs_col("F", search$f, kind = "numeric")
), controls = list(crit = search$crit))
}
fake <- cs_its_placebos(y, Xm[, common, drop = FALSE], first_post, if (use_reml) "reml_ar1" else "newey_west")
if (!is.null(fake)) {
rows <- fake$rows
ps <- vapply(rows, function(r) r$p, 0)
rejected <- sum(ps < 0.05)
sizes <- abs(vapply(rows, function(r) r$estimate, 0))
larger <- sum(sizes >= abs(lv[["est"]]))
set_robust(list(placebo_n = length(rows), placebo_rejected = rejected, placebo_min_p = min(ps), placebo_larger = larger))
robust_tables[[1]] <- list(key = "placebos", title = "Placebo dates before the intervention",
columns = list(list(key = "date", label = "Placebo date", type = "string"), list(key = "estimate", label = "Level change", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "p", label = "p", type = "p")),
rows = data.frame(date = vapply(rows, function(r) as.character(fmt_time(times[r$row])), ""), estimate = vapply(rows, function(r) r$estimate, 0), se = vapply(rows, function(r) r$se, 0), p = ps, stringsAsFactors = FALSE))
if (larger > 0L) {
checks[[length(checks) + 1]] <- list(id = "placebo", label = "Larger than at placebo dates", status = "concern", downgrade_to = "L2",
detail = sprintf("%d of %d placebo dates before the intervention show a level change at least as large as the intervention's (%.2f): the series moves that much without it.", larger, length(rows), abs(lv[["est"]])))
} else {
checks[[length(checks) + 1]] <- list(id = "placebo", label = "Larger than at placebo dates", status = "pass",
detail = sprintf("The intervention's level change (%.2f) is larger than at any of %d placebo dates before it (largest %.2f).", abs(lv[["est"]]), length(rows), max(sizes)))
}
} else {
checks[[length(checks) + 1]] <- list(id = "placebo", label = "Larger than at placebo dates", status = "info", detail = sprintf("With %d pre-intervention periods there are too few for placebo dates (12 or more are needed).", n_pre))
}
}
# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.its/monthly-date/out-r")
series <- data.frame(time = fmt_time(times), observed = y, fitted = fitted_v,
counterfactual = ifelse(post, counterfactual, NA_real_), post = post)
nanoparquet::write_parquet(series, file.path(out, "its_series.parquet"))
artifacts <- list(list(key = "series", path = file.path(out, "its_series.parquet"), format = "parquet",
title = "Observed, fitted and counterfactual series"))
tvals <- fmt_time(times)
direction <- if (lv[["est"]] > 0) "rose" else "fell"
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf(
"When the intervention started (%s), %s %s by %.2f (%s CI [%.2f, %.2f], %s), and its trend changed by %.3f per period (%s). By the last period the series was %.2f away from the projected pre-intervention trend.",
as.character(start_label), Y, direction, abs(lv[["est"]]), pct, lv[["lo"]], lv[["hi"]], cs_fmt_p(lv[["p"]]), sl[["est"]], cs_fmt_p(sl[["p"]]), effect_end
)
values <- list(
estimate = lv[["est"]], se = lv[["se"]], t = lv[["t"]], p_value = lv[["p"]], ci_low = lv[["lo"]], ci_high = lv[["hi"]], n = n,
slope_change = sl[["est"]], slope_se = sl[["se"]], slope_p = sl[["p"]], slope_ci_low = sl[["lo"]], slope_ci_high = sl[["hi"]],
pre_slope = pre_slope, effect_end = effect_end, effect_end_se = effect_end_se, relative_effect_end = relative_end,
n_pre = n_pre, n_post = n_post, hac_lag = lag, durbin_watson = dw, ljung_box_p = lb_p, df_resid = dof,
inference = if (use_reml) "reml_ar1" else "newey_west", inference_label = inference_label, df_t = unname(dfs[il]), slope_df = unname(dfs[isl]),
ar1_rho = if (!is.null(reml)) reml$rho, ljung_box_white_p = white_p,
nw_estimate = unname(b_nw[il]), nw_se = sqrt(V_nw[il, il]), nw_p = nw_p(il),
nw_slope = unname(b_nw[isl]), nw_slope_se = sqrt(V_nw[isl, isl]), nw_slope_p = nw_p(isl),
estimand = "Change in level at the intervention",
effect_label = sprintf("Immediate change in %s when the intervention started", Y),
claim_level_max = "L3"
)
if (!is.null(reml)) {
values <- c(values, list(reml_estimate = reml$b[il], reml_se = sqrt(reml$V[il, il]), reml_df = reml$df[il], reml_p = reml_p_at(il),
reml_slope = reml$b[isl], reml_slope_se = sqrt(reml$V[isl, isl]), reml_slope_df = reml$df[isl], reml_slope_p = reml_p_at(isl)))
}
values <- c(values, robust_values)
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
coef_rows <- do.call(rbind, lapply(names_x, function(nm) {
r <- coef_row(nm)
data.frame(term = nm, estimate = r[["est"]], se = r[["se"]], t = r[["t"]], df = r[["df"]], p = r[["p"]])
}))
status_map <- c(concern = "warn", fail = "fail", pass = "pass", info = "info")
cs_publish(list(
method = "causal.its",
methodVersion = "1.2.2",
title = "Interrupted time series",
engine = cs_engine_info("stats", "sandwich", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("level change = %s, SE = %s, %s; slope change = %s, SE = %s, %s", cs_fmt_num(lv[["est"]]), cs_fmt_num(lv[["se"]]), cs_fmt_p(lv[["p"]]),
cs_fmt_num(sl[["est"]], 3), cs_fmt_num(sl[["se"]], 3), cs_fmt_p(sl[["p"]])),
statistics = list(
list(key = "estimate", label = "Level change", value = lv[["est"]]),
list(key = "ci", label = paste(pct, "CI"), value = c(lv[["lo"]], lv[["hi"]])),
list(key = "p_value", label = "p", value = lv[["p"]], format = "p"),
list(key = "slope_change", label = "Slope change (per period)", value = sl[["est"]]),
list(key = "slope_p", label = "p (slope)", value = sl[["p"]], format = "p"),
list(key = "effect_end", label = "Effect at the last period", value = effect_end)
),
tables = c(list(list(
key = "coefficients", title = sprintf("Segmented regression (%s)", inference_label),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "p")),
rows = coef_rows
)), robust_tables),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = unname(status_map[c$status]), detail = c$detail)),
checks = checks,
warnings = warnings,
notes = c(list(sprintf("Intervention starts at %s; %d periods before and %d after. Slope change is measured from the first post-intervention period.",
as.character(start_label), n_pre, n_post)),
if (use_reml && n < 240) list(sprintf("AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives %s for the level change and %s for the slope change, but rejects too often on series this short.", cs_fmt_p(nw_p(il)), cs_fmt_p(nw_p(isl)))),
if (n < 24) list("With fewer than 24 periods autocorrelation is poorly estimated: read p-values near .05 cautiously.")),
values = values,
artifacts = artifacts,
charts = c(list(cs_chart("series", "forecast-fan", sprintf("%s: observed, fitted and counterfactual", Y), list(
time = cs_col(TIME, c(tvals, tvals, tvals[post]), kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(Y, c(y, fitted_v, counterfactual[post]), kind = "numeric"),
kind = cs_col("kind", c(rep("actual", n), rep("fitted", n), rep("forecast", sum(post))), kind = "categorical",
levels = c("actual", "fitted", "forecast"))
))), robust_charts)
))
level change = −6.50, SE = 1.27, p < .001; slope change = −0.352, SE = 0.056, p < .001
- Level change
- −6.500
- 95% CI
- [−9.162, −3.838]
- p
- < .001
- Slope change (per period)
- −0.3519
- p (slope)
- < .001
- Effect at the last period
- −18.816
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough pre-intervention points — 48 pre-intervention and 36 post-intervention periods.
- Residual autocorrelation — Ljung–Box test on the residuals (lag 10) p = .178; Durbin–Watson 1.45.
- AR(1) describes the errors — Ljung–Box test on the whitened residuals (lag 10) p = .980; estimated ρ = 0.32.
- No co-intervention — A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series.
Segmented regression (AR(1) errors by REML with Satterthwaite df)
| Term | Estimate | SE | t | df | p |
|---|---|---|---|---|---|
| const | 121.00 | 1.054 | 114.79 | 28.228 | 3.074e-39 |
| time | 0.2390 | 0.0305 | 7.843 | 14.274 | 1.518e-6 |
| level_change | −6.500 | 1.265 | −5.138 | 17.627 | 7.346e-5 |
| slope_change | −0.3519 | 0.0557 | −6.322 | 13.283 | 2.401e-5 |
| season_1 | 3.058 | 0.9293 | 3.291 | 56.060 | 0.0017 |
| season_2 | 6.030 | 1.069 | 5.641 | 68.799 | 3.468e-7 |
| season_3 | 7.194 | 1.111 | 6.473 | 62.001 | 1.738e-8 |
| season_4 | 3.466 | 1.126 | 3.079 | 56.535 | 0.0032 |
| season_5 | 1.084 | 1.132 | 0.9571 | 54.002 | 0.3428 |
| season_6 | −0.3090 | 1.136 | −0.2720 | 53.141 | 0.7867 |
| season_7 | −1.629 | 1.139 | −1.431 | 53.436 | 0.1584 |
| season_8 | −4.981 | 1.139 | −4.372 | 55.253 | 5.493e-5 |
| season_9 | −6.473 | 1.133 | −5.715 | 59.799 | 3.695e-7 |
| season_10 | −5.863 | 1.102 | −5.319 | 67.261 | 1.283e-6 |
| season_11 | −3.476 | 0.9868 | −3.523 | 64.504 | 0.0008 |
- Intervention starts at 2021-01-01; 48 periods before and 36 after. Slope change is measured from the first post-intervention period.
- AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives p < .001 for the level change and p < .001 for the slope change, but rejects too often on series this short.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Interrupted time series (segmented regression)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.its 1.2.2 · spec 022bd149b9652330
# Dataset: c1_its (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.stats.stattools import durbin_watson
import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import its as its_robust
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_its.parquet", columns=["admissions", "month"])
n_input = len(df)
df = df.dropna(subset=["admissions", "month"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["admissions", "month"]) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y, TIME = "admissions", "month"
POST = None
COVARIATES = []
TEMPORAL = True
conf = 0.95
season = int(12)
df = df.sort_values(TIME, kind="mergesort").reset_index(drop=True)
times = pd.to_datetime(df[TIME]) if TEMPORAL else df[TIME].astype(float)
if times.duplicated().any():
raise ValueError(f"{TIME} must have one row per period; found repeated periods.")
n = len(df)
idx = np.arange(n, dtype=float) # period index 0 … n − 1 (one row per period)
if POST:
post_level = None
levels_post = list(df[POST].cat.categories)
post_level = post_level if post_level is not None else ("true" if "true" in levels_post else levels_post[-1])
post = (df[POST].astype(str) == str(post_level)).to_numpy()
if post.any() and not post[np.argmax(post):].all():
raise ValueError(f"{POST} must stay on once the intervention starts.")
else:
start_text = "2021-01-01".strip()
if not start_text:
raise ValueError("Set 'Intervention starts' or choose an 'After intervention' column.")
start = pd.Timestamp(start_text) if TEMPORAL else float(start_text)
post = (times >= start).to_numpy()
if post.all() or not post.any():
cs.cs_error("CS_E_UNDEFINED", what="The interrupted time series", reason="the series needs periods both before and after the intervention")
first_post = int(np.argmax(post))
step = post.astype(float)
since = np.where(post, idx - first_post, 0.0) # 0 in the first post-intervention period
X = pd.DataFrame({"const": 1.0, "time": idx, "level_change": step, "slope_change": since})
if season > 1:
if TEMPORAL and season == 12:
code = times.dt.month.to_numpy() - 1 # month of year
elif TEMPORAL and season == 4:
code = (times.dt.month.to_numpy() - 1) // 3 # quarter
else:
code = (idx % season).astype(int)
for s in range(1, season):
if (code == s).any():
X[f"season_{s}"] = (code == s).astype(float)
for j, c in enumerate(COVARIATES):
X[f"x{j + 1}"] = df[c].astype(float).to_numpy()
y = df[Y].astype(float).to_numpy()
if np.unique(y).size < 2: # a flat series fits exactly: no level or slope change to estimate
cs.cs_error("CS_E_CONSTANT", column=Y)
k = X.shape[1]
hac_lag = None
lag = int(hac_lag) if hac_lag is not None else int(np.floor(4 * (n / 100) ** (2 / 9)))
# %% Fit both ways. OLS with Newey–West standard errors (Bartlett weights, no prewhitening, n/(n − k)), and
# regression with AR(1) errors by REML with Satterthwaite df, which holds its error rate on short series.
ols = sm.OLS(y, X).fit(cov_type="HAC", cov_kwds={"maxlags": lag, "use_correction": True})
b_nw = ols.params.to_numpy()
V_nw = np.asarray(ols.cov_params())
names = list(X.columns)
il, isl = names.index("level_change"), names.index("slope_change")
dof = n - k
Xm = X.to_numpy(dtype=float)
reml = None
try:
reml = its_robust.reml_ar1(y, Xm)
except ValueError as e:
warnings.append(f"{e} Using Newey–West standard errors instead.")
use_reml = "reml_ar1" == "reml_ar1" and reml is not None
if use_reml:
b, V, dfs = reml["b"], reml["V"], reml["df"]
else:
b, V, dfs = b_nw, V_nw, np.full(k, float(dof))
inference_label = "AR(1) errors by REML with Satterthwaite df" if use_reml else f"Newey–West, lag {lag}"
def coef(name):
i = names.index(name)
est, se, df = float(b[i]), float(np.sqrt(V[i, i])), float(dfs[i])
t = est / se
qt = stats.t.ppf(0.5 + conf / 2, df)
return est, se, t, float(2 * stats.t.sf(abs(t), df)), est - qt * se, est + qt * se
def nw_p(i):
return float(2 * stats.t.sf(abs(b_nw[i]) / np.sqrt(V_nw[i, i]), dof))
lvl, lvl_se, lvl_t, lvl_p, lvl_lo, lvl_hi = coef("level_change")
slp, slp_se, slp_t, slp_p, slp_lo, slp_hi = coef("slope_change")
pre_slope = float(b[names.index("time")])
# Effect at the last period = level change + slope change × periods since the start.
h = since[-1]
effect_end = lvl + slp * h
effect_end_se = float(np.sqrt(V[il, il] + h * h * V[isl, isl] + 2 * h * V[il, isl]))
fitted = Xm @ b
counterfactual = fitted - lvl * step - slp * since
relative_end = effect_end / counterfactual[-1] if counterfactual[-1] != 0 else None
# %% Checks
# Durbin–Watson and Ljung–Box read the least-squares residuals, which show what the errors are like before any model of them.
resid = np.asarray(ols.resid)
dw = float(durbin_watson(resid))
lb_lag = max(1, min(10, n // 5))
lb_p = float(acorr_ljungbox(resid, lags=[lb_lag], return_df=True)["lb_pvalue"].iloc[0])
# The whitened residuals are independent if AR(1) describes the errors; their null is simulated.
white_lag = max(2, lb_lag)
white_p = its_robust.white_noise_test(reml["white"], Xm, reml["rho"], white_lag, 499, 42)["p"] if reml is not None and n > white_lag + 1 else None
n_pre, n_post = first_post, n - first_post
checks = []
if n_pre < 8:
checks.append({"id": "pre_points", "label": "Enough pre-intervention points", "status": "concern", "downgrade_to": "L2",
"detail": f"Only {n_pre} pre-intervention periods; the pre-trend (and so the counterfactual) is poorly estimated — aim for 8 or more."})
else:
checks.append({"id": "pre_points", "label": "Enough pre-intervention points", "status": "pass",
"detail": f"{n_pre} pre-intervention and {n_post} post-intervention periods."})
if lb_p < 0.05:
checks.append({"id": "autocorrelation", "label": "Residual autocorrelation", "status": "concern",
"detail": f"Ljung–Box test on the residuals (lag {lb_lag}) {cs.fmt_p(lb_p)}: errors are autocorrelated; " + (f"the AR(1) error model (ρ = {reml['rho']:.2f}) allows for it." if use_reml else f"Newey–West standard errors (lag {lag}) allow for it, but consider an AR(1) error model.")})
else:
checks.append({"id": "autocorrelation", "label": "Residual autocorrelation", "status": "pass",
"detail": f"Ljung–Box test on the residuals (lag {lb_lag}) {cs.fmt_p(lb_p)}; Durbin–Watson {dw:.2f}."})
if use_reml and white_p is not None:
if white_p < 0.05:
checks.append({"id": "ar1_errors", "label": "AR(1) describes the errors", "status": "concern",
"detail": f"Ljung–Box test on the whitened residuals (lag {white_lag}) {cs.fmt_p(white_p)}: the errors have structure AR(1) misses, so p-values may run small. Add seasonal terms or covariates if they explain it."})
else:
checks.append({"id": "ar1_errors", "label": "AR(1) describes the errors", "status": "pass",
"detail": f"Ljung–Box test on the whitened residuals (lag {white_lag}) {cs.fmt_p(white_p)}; estimated ρ = {reml['rho']:.2f}."})
if not use_reml and n < 240:
checks.append({"id": "short_series", "label": "Long enough for Newey–West", "status": "concern",
"detail": f"With {n} periods, Newey–West level tests reject too often: about 10–27% at the 5% level for 24–72 periods in simulations with no effect, still 7–13% at 240." + (f" The AR(1) model gives {cs.fmt_p(float(2 * stats.t.sf(abs(reml['b'][il]) / np.sqrt(reml['V'][il, il]), reml['df'][il])))} for the level change." if reml is not None else "")})
checks.append({"id": "cointervention", "label": "No co-intervention", "status": "info",
"detail": "A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series."})
fmt_time = (lambda v: pd.Timestamp(v).strftime("%Y-%m-%d")) if TEMPORAL else (lambda v: float(v))
start_label = fmt_time(times.iloc[first_post])
# %% Robustness: a change at the intervention, the strongest break date, placebo dates
robust_values = dict.fromkeys(["chow_f", "chow_p", "chow_hac_f", "chow_hac_p", "chow_reml_f", "chow_reml_df2", "chow_reml_p", "supf_stat", "supf_p", "supf_crit", "supf_break", "supf_at_intervention", "placebo_n", "placebo_rejected", "placebo_min_p", "placebo_larger"])
robust_tables, robust_charts = [], []
if False:
common = [j for j, nm in enumerate(names) if nm not in ("level_change", "slope_change")]
chow = its_robust.chow_at(y, Xm, [il, isl], V_nw)
robust_values.update({"chow_f": chow["f"], "chow_p": chow["p"], "chow_hac_f": chow["hac_f"], "chow_hac_p": chow["hac_p"]})
wald = its_robust.reml_wald(reml, [il, isl]) if reml is not None else None
if wald:
robust_values.update({"chow_reml_f": wald["f"], "chow_reml_df2": wald["df2"], "chow_reml_p": wald["p"]})
if use_reml:
checks.append({"id": "chow", "label": "A change at the intervention", "status": "pass" if wald["p"] < 0.05 else "info",
"detail": f"Level and slope together: F({wald['df1']}, {wald['df2']:.1f}) = {wald['f']:.2f} with AR(1) errors, {cs.fmt_p(wald['p'])}."})
else:
checks.append({"id": "chow", "label": "A change at the intervention", "status": "pass" if chow["hac_p"] < 0.05 else "info",
"detail": f"Level and slope together: F({chow['df1']}, {chow['df2']}) = {chow['hac_f']:.2f} with Newey–West errors, {cs.fmt_p(chow['hac_p'])}."})
search = None
try:
search = its_robust.sup_f(y, Xm[:, common], 0.15, 999, 42, reml["rho"] if reml is not None else 0.0)
except ValueError as e:
warnings.append(str(e))
if search:
near = abs(search["break_row"] - first_post) <= max(2, int(np.ceil(0.05 * n)))
break_label = fmt_time(times.iloc[search["break_row"]])
robust_values.update({"supf_stat": search["stat"], "supf_p": search["p"], "supf_crit": search["crit"], "supf_break": break_label if TEMPORAL else float(break_label), "supf_at_intervention": bool(near)})
if search["p"] < 0.05 and not near:
checks.append({"id": "break_elsewhere", "label": "The strongest break is at the intervention", "status": "concern", "downgrade_to": "L2",
"detail": f"The series changes most at {break_label}, not at the intervention ({start_label}): sup-F = {search['stat']:.2f}, {cs.fmt_p(search['p'])}. Something else may be driving the change."})
else:
checks.append({"id": "break_elsewhere", "label": "The strongest break is at the intervention", "status": "pass",
"detail": f"The strongest break is at {break_label} (sup-F = {search['stat']:.2f}, {cs.fmt_p(search['p'])}), " + ("close to the intervention." if near else "and no break stands out from chance.")})
robust_charts.append(cs.chart("break_search", "fstat-sequence", "F for a change in level and slope at each date",
{"x": cs.col(TIME, [fmt_time(times.iloc[r]) for r in search["candidates"]], kind="temporal" if TEMPORAL else "numeric"),
"y": cs.col("F", search["f"], kind="numeric")}, controls={"crit": search["crit"]}))
fake = its_robust.placebos(y, Xm[:, common], first_post, "reml_ar1" if use_reml else "newey_west")
if fake:
rows = fake["rows"]
rejected = sum(1 for r in rows if r["p"] < 0.05)
larger = sum(1 for r in rows if abs(r["estimate"]) >= abs(lvl))
robust_values.update({"placebo_n": len(rows), "placebo_rejected": rejected, "placebo_min_p": min(r["p"] for r in rows), "placebo_larger": larger})
robust_tables.append({"key": "placebos", "title": "Placebo dates before the intervention",
"columns": [{"key": "date", "label": "Placebo date", "type": "string"}, {"key": "estimate", "label": "Level change", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": [{"date": str(fmt_time(times.iloc[r["row"]])), "estimate": r["estimate"], "se": r["se"], "p": r["p"]} for r in rows]})
biggest = max(abs(r["estimate"]) for r in rows)
if larger:
checks.append({"id": "placebo", "label": "Larger than at placebo dates", "status": "concern", "downgrade_to": "L2",
"detail": f"{larger} of {len(rows)} placebo dates before the intervention show a level change at least as large as the intervention's ({abs(lvl):.2f}): the series moves that much without it."})
else:
checks.append({"id": "placebo", "label": "Larger than at placebo dates", "status": "pass",
"detail": f"The intervention's level change ({abs(lvl):.2f}) is larger than at any of {len(rows)} placebo dates before it (largest {biggest:.2f})."})
else:
checks.append({"id": "placebo", "label": "Larger than at placebo dates", "status": "info", "detail": f"With {n_pre} pre-intervention periods there are too few for placebo dates (12 or more are needed)."})
# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.its/monthly-date/out-python")
artifacts = []
series = pd.DataFrame({"time": [fmt_time(v) for v in times], "observed": y, "fitted": fitted,
"counterfactual": np.where(post, counterfactual, np.nan), "post": post})
series.to_parquet(os.path.join(out, "its_series.parquet"), index=False)
artifacts.append({"key": "series", "path": os.path.join(out, "its_series.parquet"), "format": "parquet", "title": "Observed, fitted and counterfactual series"})
tkind = "temporal" if TEMPORAL else "numeric"
tvals = [fmt_time(v) for v in times]
cf_t = [tvals[i] for i in range(n) if post[i]]
cf_v = [float(counterfactual[i]) for i in range(n) if post[i]]
chart_rows = {"time": tvals + tvals + cf_t, "value": list(y) + list(fitted) + cf_v,
"kind": ["actual"] * n + ["fitted"] * n + ["forecast"] * len(cf_t)}
direction = "rose" if lvl > 0 else "fell"
summary = (
f"When the intervention started ({start_label}), {Y} {direction} by {abs(lvl):.2f} ({conf:.0%} CI [{lvl_lo:.2f}, {lvl_hi:.2f}], "
f"{cs.fmt_p(lvl_p)}), and its trend changed by {slp:.3f} per period ({cs.fmt_p(slp_p)}). By the last period the series was "
f"{effect_end:.2f} away from the projected pre-intervention trend."
)
values = {
"estimate": lvl, "se": lvl_se, "t": lvl_t, "p_value": lvl_p, "ci_low": lvl_lo, "ci_high": lvl_hi, "n": n,
"slope_change": slp, "slope_se": slp_se, "slope_p": slp_p, "slope_ci_low": slp_lo, "slope_ci_high": slp_hi,
"pre_slope": pre_slope, "effect_end": effect_end, "effect_end_se": effect_end_se, "relative_effect_end": relative_end,
"n_pre": n_pre, "n_post": n_post, "hac_lag": lag, "durbin_watson": dw, "ljung_box_p": lb_p, "df_resid": dof,
"inference": "reml_ar1" if use_reml else "newey_west", "inference_label": inference_label, "df_t": float(dfs[il]), "slope_df": float(dfs[isl]),
"ar1_rho": reml["rho"] if reml is not None else None, "ljung_box_white_p": white_p,
"nw_estimate": float(b_nw[il]), "nw_se": float(np.sqrt(V_nw[il, il])), "nw_p": nw_p(il),
"nw_slope": float(b_nw[isl]), "nw_slope_se": float(np.sqrt(V_nw[isl, isl])), "nw_slope_p": nw_p(isl),
**({"reml_estimate": float(reml["b"][il]), "reml_se": float(np.sqrt(reml["V"][il, il])), "reml_df": float(reml["df"][il]),
"reml_p": float(2 * stats.t.sf(abs(reml["b"][il]) / np.sqrt(reml["V"][il, il]), reml["df"][il])),
"reml_slope": float(reml["b"][isl]), "reml_slope_se": float(np.sqrt(reml["V"][isl, isl])), "reml_slope_df": float(reml["df"][isl]),
"reml_slope_p": float(2 * stats.t.sf(abs(reml["b"][isl]) / np.sqrt(reml["V"][isl, isl]), reml["df"][isl]))} if reml is not None else {}),
"estimand": "Change in level at the intervention",
"effect_label": f"Immediate change in {Y} when the intervention started",
"claim_level_max": "L3",
**robust_values,
}
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
cs.publish({
"method": "causal.its",
"methodVersion": "1.2.2",
"title": "Interrupted time series",
"engine": cs.engine_info("pandas", "numpy", "statsmodels"),
"n": n,
"summary": summary,
"apa": f"level change = {cs.fmt_num(lvl)}, SE = {cs.fmt_num(lvl_se)}, {cs.fmt_p(lvl_p)}; slope change = {cs.fmt_num(slp, 3)}, SE = {cs.fmt_num(slp_se, 3)}, {cs.fmt_p(slp_p)}",
"statistics": [
{"key": "estimate", "label": "Level change", "value": lvl},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [lvl_lo, lvl_hi]},
{"key": "p_value", "label": "p", "value": lvl_p, "format": "p"},
{"key": "slope_change", "label": "Slope change (per period)", "value": slp},
{"key": "slope_p", "label": "p (slope)", "value": slp_p, "format": "p"},
{"key": "effect_end", "label": "Effect at the last period", "value": effect_end},
],
"tables": [{
"key": "coefficients", "title": f"Segmented regression ({inference_label})",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": [{"term": nm, "estimate": float(b[i]), "se": float(np.sqrt(V[i, i])),
"t": float(b[i] / np.sqrt(V[i, i])), "df": float(dfs[i]), "p": float(2 * stats.t.sf(abs(b[i] / np.sqrt(V[i, i])), dfs[i]))}
for i, nm in enumerate(names)],
}] + robust_tables,
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn", "fail": "fail"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": [f"Intervention starts at {start_label}; {n_pre} periods before and {n_post} after. Slope change is measured from the first post-intervention period."]
+ ([f"AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives {cs.fmt_p(nw_p(il))} for the level change and {cs.fmt_p(nw_p(isl))} for the slope change, but rejects too often on series this short."] if use_reml and n < 240 else [])
+ (["With fewer than 24 periods autocorrelation is poorly estimated: read p-values near .05 cautiously."] if n < 24 else []),
"values": values,
"artifacts": artifacts,
"charts": [cs.chart("series", "forecast-fan", f"{Y}: observed, fitted and counterfactual",
{"time": cs.col(TIME, chart_rows["time"], kind=tkind),
"value": cs.col(Y, chart_rows["value"], kind="numeric"),
"kind": cs.col("kind", chart_rows["kind"], kind="categorical", levels=["actual", "fitted", "forecast"])})] + robust_charts,
})
The level changed by −6.50 right away (p < .001). The trend changed by −0.352 per month (p < .001).
The old trend was rising, at 0.239 per month. So by the last month, the difference from the projection had reached −18.8.
Level or trend?
CheckpointCheck yourself
A policy has no immediate level change, but the slope falls. What does that say?
Show the answer
Answer: b
A gradual effect shows up in the slope. Looking only at the level change would miss it.
Forget the seasons
PredictPredict first
These admissions have a yearly pattern. The first model includes month-of-year terms. Refit without them. What do you expect?
Reveal
Durbin–WatsonDurbin–Watson statisticChecks residuals for first-order autocorrelation. Values near 2 suggest none, and values well below 2 suggest positive correlation. falls from 1.45 to 0.508, far below 2. The level change shrinks from −6.50 to −2.72, and its p-value becomes p = .395. Ljung–BoxLjung–Box testTests whether a series or a model's residuals have leftover autocorrelation up to some lag. goes from p = .178 to p < .001. Seasonality left in the errors looks like autocorrelation.
Why not Newey–West?
ReadErrors in a series are correlated. Newey–WestNewey–West standard errorsStandard errors that allow correlation between nearby observations in a series, up to a chosen lag. standard errors are the classic answer, but on short series they're still too small.
When CodeSplash simulated series with no effect at all, Newey–West level tests rejected about 14–26% of the time at the 5% level at 24 periods, and still 7–13% at 240.
So the method leads with AR(1) errors fitted by REMLAR(1) errors by REMLA regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series., which stayed at about 4–8% on the same series. It shows Newey–West beside it. Without the seasonal terms, the trend change has p = .002 under Newey–West and p = .204 under AR(1).
AR(1) can be wrong too, so the card tests what it leaves behind. Without the seasonal terms that check says concern: a yearly pattern isn't AR(1).
Are the placebo dates a problem?
PredictPredict first
The robustness battery reruns the level test at fake dates before the policy, when nothing happened. 1 of 9 placebo dates reach p < 0.05. How do you read that?
Reveal
Several looks at short stretches of a series can do that, so the check doesn't rest on those p-values. It compares sizes. 0 placebo dates show a change at least as large as the real one, −6.50. The check, Larger than at placebo dates, passes. If some had matched it, the claim would drop a level.
Other checks in the battery
In the applevel change = −6.50, SE = 1.27, p < .001; slope change = −0.352, SE = 0.056, p < .001
- Level change
- −6.500
- 95% CI
- [−9.162, −3.838]
- p
- < .001
- Slope change (per period)
- −0.3519
- p (slope)
- < .001
- Effect at the last period
- −18.816
Plots
View data
| kind | month | admissions |
|---|---|---|
| actual | 1,483,228,800,000 | 121.99 |
| actual | 1,485,907,200,000 | 120.86 |
| actual | 1,488,326,400,000 | 127.16 |
| actual | 1,491,004,800,000 | 131.74 |
| actual | 1,493,596,800,000 | 125.45 |
| actual | 1,496,275,200,000 | 123.03 |
| actual | 1,498,867,200,000 | 123.42 |
| actual | 1,501,545,600,000 | 118.87 |
| actual | 1,504,224,000,000 | 116.91 |
| actual | 1,506,816,000,000 | 117.11 |
| actual | 1,509,494,400,000 | 119.06 |
| actual | 1,512,086,400,000 | 122.21 |
| actual | 1,514,764,800,000 | 124.32 |
| actual | 1,517,443,200,000 | 131.37 |
| actual | 1,519,862,400,000 | 128.61 |
| actual | 1,522,540,800,000 | 134.18 |
| actual | 1,525,132,800,000 | 128.37 |
| actual | 1,527,811,200,000 | 127.08 |
| actual | 1,530,403,200,000 | 125.46 |
| actual | 1,533,081,600,000 | 125.65 |
| actual | 1,535,760,000,000 | 119.58 |
| actual | 1,538,352,000,000 | 116.75 |
| actual | 1,541,030,400,000 | 118.82 |
| actual | 1,543,622,400,000 | 118.93 |
| actual | 1,546,300,800,000 | 124.93 |
| actual | 1,548,979,200,000 | 127.03 |
| actual | 1,551,398,400,000 | 132.45 |
| actual | 1,554,076,800,000 | 133.41 |
| actual | 1,556,668,800,000 | 129.09 |
| actual | 1,559,347,200,000 | 128.35 |
| actual | 1,561,939,200,000 | 128.93 |
| actual | 1,564,617,600,000 | 127.82 |
| actual | 1,567,296,000,000 | 125.22 |
| actual | 1,569,888,000,000 | 121.43 |
| actual | 1,572,566,400,000 | 122.17 |
| actual | 1,575,158,400,000 | 126.23 |
| actual | 1,577,836,800,000 | 129.31 |
| actual | 1,580,515,200,000 | 135.71 |
| actual | 1,583,020,800,000 | 138.57 |
| actual | 1,585,699,200,000 | 136.85 |
| actual | 1,588,291,200,000 | 135.86 |
| actual | 1,590,969,600,000 | 133.59 |
| actual | 1,593,561,600,000 | 129.13 |
| actual | 1,596,240,000,000 | 128.92 |
| actual | 1,598,918,400,000 | 125.94 |
| actual | 1,601,510,400,000 | 125.15 |
| actual | 1,604,188,800,000 | 126.90 |
| actual | 1,606,780,800,000 | 129.71 |
| actual | 1,609,459,200,000 | 127.20 |
| actual | 1,612,137,600,000 | 125.31 |
| actual | 1,614,556,800,000 | 125.49 |
| actual | 1,617,235,200,000 | 131.80 |
| actual | 1,619,827,200,000 | 129.95 |
| actual | 1,622,505,600,000 | 127.84 |
| actual | 1,625,097,600,000 | 125.96 |
| actual | 1,627,776,000,000 | 123.30 |
| actual | 1,630,454,400,000 | 122.38 |
| actual | 1,633,046,400,000 | 119.93 |
| actual | 1,635,724,800,000 | 118.51 |
| actual | 1,638,316,800,000 | 123.43 |
First 60 of 204 rows.
View data
| month | F |
|---|---|
| 1,522,540,800,000 | 15.057 |
| 1,525,132,800,000 | 15.101 |
| 1,527,811,200,000 | 16.043 |
| 1,530,403,200,000 | 16.644 |
| 1,533,081,600,000 | 17.405 |
| 1,535,760,000,000 | 17.658 |
| 1,538,352,000,000 | 19.004 |
| 1,541,030,400,000 | 21.536 |
| 1,543,622,400,000 | 23.957 |
| 1,546,300,800,000 | 29.448 |
| 1,548,979,200,000 | 32.568 |
| 1,551,398,400,000 | 37.844 |
| 1,554,076,800,000 | 40.303 |
| 1,556,668,800,000 | 43.691 |
| 1,559,347,200,000 | 49.061 |
| 1,561,939,200,000 | 52.122 |
| 1,564,617,600,000 | 51.750 |
| 1,567,296,000,000 | 51.582 |
| 1,569,888,000,000 | 50.742 |
| 1,572,566,400,000 | 53.536 |
| 1,575,158,400,000 | 56.638 |
| 1,577,836,800,000 | 57.572 |
| 1,580,515,200,000 | 57.680 |
| 1,583,020,800,000 | 54.930 |
| 1,585,699,200,000 | 53.869 |
| 1,588,291,200,000 | 53.882 |
| 1,590,969,600,000 | 54.459 |
| 1,593,561,600,000 | 56.118 |
| 1,596,240,000,000 | 55.512 |
| 1,598,918,400,000 | 56.073 |
| 1,601,510,400,000 | 57.347 |
| 1,604,188,800,000 | 60.410 |
| 1,606,780,800,000 | 67.903 |
| 1,609,459,200,000 | 81.777 |
| 1,612,137,600,000 | 74.860 |
| 1,614,556,800,000 | 53.783 |
| 1,617,235,200,000 | 37.639 |
| 1,619,827,200,000 | 33.319 |
| 1,622,505,600,000 | 31.429 |
| 1,625,097,600,000 | 29.915 |
| 1,627,776,000,000 | 28.074 |
| 1,630,454,400,000 | 25.350 |
| 1,633,046,400,000 | 24.665 |
| 1,635,724,800,000 | 23.285 |
| 1,638,316,800,000 | 20.660 |
| 1,640,995,200,000 | 19.869 |
| 1,643,673,600,000 | 19.446 |
| 1,646,092,800,000 | 19.857 |
| 1,648,771,200,000 | 21.564 |
| 1,651,363,200,000 | 17.924 |
| 1,654,041,600,000 | 14.770 |
| 1,656,633,600,000 | 13.093 |
| 1,659,312,000,000 | 11.183 |
| 1,661,990,400,000 | 9.866 |
| 1,664,582,400,000 | 8.946 |
Assumptions
- Enough pre-intervention points — 48 pre-intervention and 36 post-intervention periods.
- Residual autocorrelation — Ljung–Box test on the residuals (lag 10) p = .178; Durbin–Watson 1.45.
- AR(1) describes the errors — Ljung–Box test on the whitened residuals (lag 10) p = .980; estimated ρ = 0.32.
- No co-intervention — A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series.
- A change at the intervention — Level and slope together: F(2, 14.9) = 42.23 with AR(1) errors, p < .001.
- The strongest break is at the intervention — The strongest break is at 2021-01-01 (sup-F = 81.78, p = .001), close to the intervention.
- Larger than at placebo dates — The intervention's level change (6.50) is larger than at any of 9 placebo dates before it (largest 3.18).
Segmented regression (AR(1) errors by REML with Satterthwaite df)
| Term | Estimate | SE | t | df | p |
|---|---|---|---|---|---|
| const | 121.00 | 1.054 | 114.79 | 28.228 | 3.074e-39 |
| time | 0.2390 | 0.0305 | 7.843 | 14.274 | 1.518e-6 |
| level_change | −6.500 | 1.265 | −5.138 | 17.627 | 7.346e-5 |
| slope_change | −0.3519 | 0.0557 | −6.322 | 13.283 | 2.401e-5 |
| season_1 | 3.058 | 0.9293 | 3.291 | 56.060 | 0.0017 |
| season_2 | 6.030 | 1.069 | 5.641 | 68.799 | 3.468e-7 |
| season_3 | 7.194 | 1.111 | 6.473 | 62.001 | 1.738e-8 |
| season_4 | 3.466 | 1.126 | 3.079 | 56.535 | 0.0032 |
| season_5 | 1.084 | 1.132 | 0.9571 | 54.002 | 0.3428 |
| season_6 | −0.3090 | 1.136 | −0.2720 | 53.141 | 0.7867 |
| season_7 | −1.629 | 1.139 | −1.431 | 53.436 | 0.1584 |
| season_8 | −4.981 | 1.139 | −4.372 | 55.253 | 5.493e-5 |
| season_9 | −6.473 | 1.133 | −5.715 | 59.799 | 3.695e-7 |
| season_10 | −5.863 | 1.102 | −5.319 | 67.261 | 1.283e-6 |
| season_11 | −3.476 | 0.9868 | −3.523 | 64.504 | 0.0008 |
Placebo dates before the intervention
| Placebo date | Level change | SE | p |
|---|---|---|---|
| 2018-01-01 | −2.331 | 1.977 | 0.2616 |
| 2018-04-01 | −2.021 | 1.481 | 0.2001 |
| 2018-07-01 | −2.703 | 1.316 | 0.0666 |
| 2018-10-01 | −3.184 | 1.132 | 0.0168 |
| 2019-01-01 | −0.5198 | 1.530 | 0.7418 |
| 2019-04-01 | 0.5038 | 1.452 | 0.7362 |
| 2019-07-01 | 2.463 | 1.315 | 0.0910 |
| 2019-10-01 | 0.6833 | 1.569 | 0.6722 |
| 2020-01-01 | 1.598 | 1.774 | 0.3860 |
- Intervention starts at 2021-01-01; 48 periods before and 36 after. Slope change is measured from the first post-intervention period.
- AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives p < .001 for the level change and p < .001 for the slope change, but rejects too often on series this short.
The exact R script · R R version 4.5.1 (2025-06-13)
# Interrupted time series (segmented regression)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.its 1.2.2 · spec 7deb30599712c35c
# Dataset: c1_its (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_its.parquet", col_select = c("admissions", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("admissions", "month")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("admissions", "month")) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y <- "admissions"
TIME <- "month"
POST <- NULL
COVARIATES <- c()
TEMPORAL <- TRUE
conf <- 0.95
season <- as.integer(12)
df <- df[order(df[[TIME]], method = "radix"), , drop = FALSE]
times <- if (TEMPORAL) as.Date(df[[TIME]], tz = "UTC") else as.numeric(df[[TIME]])
if (anyDuplicated(times)) stop(sprintf("%s must have one row per period; found repeated periods.", TIME))
n <- nrow(df)
idx <- seq_len(n) - 1 # period index 0 … n − 1 (one row per period)
if (!is.null(POST)) {
post_level <- NULL
levels_post <- levels(df[[POST]])
if (is.null(post_level)) post_level <- if ("true" %in% levels_post) "true" else levels_post[length(levels_post)]
post <- as.character(df[[POST]]) == post_level
if (any(post) && !all(post[which(post)[1]:n])) stop(sprintf("%s must stay on once the intervention starts.", POST))
} else {
start_text <- trimws("2021-01-01")
if (!nzchar(start_text)) stop("Set 'Intervention starts' or choose an 'After intervention' column.")
start <- if (TEMPORAL) as.Date(start_text) else as.numeric(start_text)
post <- times >= start
}
if (all(post) || !any(post)) {
cs_error("CS_E_UNDEFINED", what = "The interrupted time series", reason = "the series needs periods both before and after the intervention")
}
first_post <- which(post)[1] - 1 # 0-based
step <- as.numeric(post)
since <- ifelse(post, idx - first_post, 0) # 0 in the first post-intervention period
X <- data.frame(const = 1, time = idx, level_change = step, slope_change = since)
if (season > 1) {
month <- if (TEMPORAL) as.integer(format(times, "%m")) else NULL
code <- if (TEMPORAL && season == 12) month - 1L else if (TEMPORAL && season == 4) (month - 1L) %/% 3L else as.integer(idx %% season)
for (s in seq_len(season - 1)) if (any(code == s)) X[[paste0("season_", s)]] <- as.numeric(code == s)
}
for (j in seq_along(COVARIATES)) X[[paste0("x", j)]] <- as.numeric(df[[COVARIATES[j]]])
y <- as.numeric(df[[Y]])
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = Y) # a flat series fits exactly: no level or slope change to estimate
k <- ncol(X)
hac_lag <- NULL
lag <- if (!is.null(hac_lag)) as.integer(hac_lag) else as.integer(floor(4 * (n / 100)^(2 / 9)))
# %% Fit both ways. OLS with Newey–West standard errors (Bartlett weights, no prewhitening, n/(n − k)), and
# regression with AR(1) errors by REML with Satterthwaite df, which holds its error rate on short series.
fit <- lm(y ~ 0 + ., data = cbind(y = y, X))
b_nw <- coef(fit)
V_nw <- sandwich::NeweyWest(fit, lag = lag, prewhite = FALSE, adjust = TRUE)
names_x <- names(X)
il <- match("level_change", names_x); isl <- match("slope_change", names_x)
dof <- n - k
Xm <- as.matrix(X)
reml <- tryCatch(cs_its_reml_ar1(y, Xm), error = function(e) { warnings <<- c(warnings, paste(conditionMessage(e), "Using Newey–West standard errors instead.")); NULL })
use_reml <- "reml_ar1" == "reml_ar1" && !is.null(reml)
if (use_reml) {
b <- setNames(reml$b, names_x)
V <- matrix(reml$V, k, k, dimnames = list(names_x, names_x))
dfs <- setNames(reml$df, names_x)
} else {
b <- b_nw
V <- V_nw
dfs <- setNames(rep(as.numeric(dof), k), names_x)
}
inference_label <- if (use_reml) "AR(1) errors by REML with Satterthwaite df" else sprintf("Newey–West, lag %d", lag)
coef_row <- function(name) {
est <- unname(b[name]); se <- sqrt(V[name, name]); t <- est / se; df <- unname(dfs[name])
qt_ <- qt(0.5 + conf / 2, df)
c(est = est, se = se, t = t, df = df, p = 2 * pt(-abs(t), df), lo = est - qt_ * se, hi = est + qt_ * se)
}
nw_p <- function(i) 2 * pt(-abs(unname(b_nw[i])) / sqrt(V_nw[i, i]), dof)
lv <- coef_row("level_change")
sl <- coef_row("slope_change")
pre_slope <- unname(b["time"])
# Effect at the last period = level change + slope change × periods since the start.
h <- since[n]
effect_end <- lv[["est"]] + sl[["est"]] * h
effect_end_se <- sqrt(V["level_change", "level_change"] + h * h * V["slope_change", "slope_change"] + 2 * h * V["level_change", "slope_change"])
fitted_v <- drop(Xm %*% unname(b))
counterfactual <- fitted_v - lv[["est"]] * step - sl[["est"]] * since
relative_end <- if (counterfactual[n] != 0) effect_end / counterfactual[n] else NULL
# %% Checks
# Durbin–Watson and Ljung–Box read the least-squares residuals, which show what the errors are like before any model of them.
resid <- unname(residuals(fit))
dw <- sum(diff(resid)^2) / sum(resid^2)
lb_lag <- max(1L, min(10L, n %/% 5L))
lb_p <- Box.test(resid, lag = lb_lag, type = "Ljung-Box")$p.value
# The whitened residuals are independent if AR(1) describes the errors; their null is simulated.
white_lag <- max(2L, lb_lag)
white_p <- if (!is.null(reml) && n > white_lag + 1L) cs_its_white_noise_test(reml$white, Xm, reml$rho, white_lag, 499L, 42)$p else NULL
n_pre <- first_post
n_post <- n - first_post
checks <- list()
if (n_pre < 8) {
checks[[length(checks) + 1]] <- list(id = "pre_points", label = "Enough pre-intervention points", status = "concern", downgrade_to = "L2",
detail = sprintf("Only %d pre-intervention periods; the pre-trend (and so the counterfactual) is poorly estimated — aim for 8 or more.", n_pre))
} else {
checks[[length(checks) + 1]] <- list(id = "pre_points", label = "Enough pre-intervention points", status = "pass",
detail = sprintf("%d pre-intervention and %d post-intervention periods.", n_pre, n_post))
}
if (lb_p < 0.05) {
checks[[length(checks) + 1]] <- list(id = "autocorrelation", label = "Residual autocorrelation", status = "concern",
detail = paste0(sprintf("Ljung–Box test on the residuals (lag %d) %s: errors are autocorrelated; ", lb_lag, cs_fmt_p(lb_p)),
if (use_reml) sprintf("the AR(1) error model (ρ = %.2f) allows for it.", reml$rho) else sprintf("Newey–West standard errors (lag %d) allow for it, but consider an AR(1) error model.", lag)))
} else {
checks[[length(checks) + 1]] <- list(id = "autocorrelation", label = "Residual autocorrelation", status = "pass",
detail = sprintf("Ljung–Box test on the residuals (lag %d) %s; Durbin–Watson %.2f.", lb_lag, cs_fmt_p(lb_p), dw))
}
if (use_reml && !is.null(white_p)) {
if (white_p < 0.05) {
checks[[length(checks) + 1]] <- list(id = "ar1_errors", label = "AR(1) describes the errors", status = "concern",
detail = sprintf("Ljung–Box test on the whitened residuals (lag %d) %s: the errors have structure AR(1) misses, so p-values may run small. Add seasonal terms or covariates if they explain it.", white_lag, cs_fmt_p(white_p)))
} else {
checks[[length(checks) + 1]] <- list(id = "ar1_errors", label = "AR(1) describes the errors", status = "pass",
detail = sprintf("Ljung–Box test on the whitened residuals (lag %d) %s; estimated ρ = %.2f.", white_lag, cs_fmt_p(white_p), reml$rho))
}
}
reml_p_at <- function(i) 2 * pt(-abs(reml$b[i]) / sqrt(reml$V[i, i]), reml$df[i])
if (!use_reml && n < 240) {
checks[[length(checks) + 1]] <- list(id = "short_series", label = "Long enough for Newey–West", status = "concern",
detail = paste0(sprintf("With %d periods, Newey–West level tests reject too often: about 10–27%% at the 5%% level for 24–72 periods in simulations with no effect, still 7–13%% at 240.", n),
if (!is.null(reml)) sprintf(" The AR(1) model gives %s for the level change.", cs_fmt_p(reml_p_at(il))) else ""))
}
checks[[length(checks) + 1]] <- list(id = "cointervention", label = "No co-intervention", status = "info",
detail = "A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series.")
fmt_time <- function(v) if (TEMPORAL) format(v, "%Y-%m-%d") else as.numeric(v)
start_label <- fmt_time(times[first_post + 1])
# %% Robustness: a change at the intervention, the strongest break date, placebo dates
robust_keys <- c("chow_f", "chow_p", "chow_hac_f", "chow_hac_p", "chow_reml_f", "chow_reml_df2", "chow_reml_p", "supf_stat", "supf_p", "supf_crit", "supf_break", "supf_at_intervention", "placebo_n", "placebo_rejected", "placebo_min_p", "placebo_larger")
robust_values <- setNames(vector("list", length(robust_keys)), robust_keys)
set_robust <- function(x) robust_values[names(x)] <<- x
robust_tables <- list(); robust_charts <- list()
if (TRUE) {
common <- which(!(names_x %in% c("level_change", "slope_change")))
chow <- cs_its_chow_at(y, Xm, c(il, isl), V_nw)
set_robust(list(chow_f = chow$f, chow_p = chow$p, chow_hac_f = chow$hac_f, chow_hac_p = chow$hac_p))
wald <- if (!is.null(reml)) cs_its_reml_wald(reml, c(il, isl)) else NULL
if (!is.null(wald)) set_robust(list(chow_reml_f = wald$f, chow_reml_df2 = wald$df2, chow_reml_p = wald$p))
if (use_reml) {
checks[[length(checks) + 1]] <- list(id = "chow", label = "A change at the intervention", status = if (wald$p < 0.05) "pass" else "info",
detail = sprintf("Level and slope together: F(%d, %.1f) = %.2f with AR(1) errors, %s.", wald$df1, wald$df2, wald$f, cs_fmt_p(wald$p)))
} else {
checks[[length(checks) + 1]] <- list(id = "chow", label = "A change at the intervention", status = if (chow$hac_p < 0.05) "pass" else "info",
detail = sprintf("Level and slope together: F(%d, %d) = %.2f with Newey–West errors, %s.", chow$df1, chow$df2, chow$hac_f, cs_fmt_p(chow$hac_p)))
}
search <- tryCatch(cs_its_sup_f(y, Xm[, common, drop = FALSE], 0.15, 999L, 42, if (!is.null(reml)) reml$rho else 0), error = function(e) { warnings <<- c(warnings, conditionMessage(e)); NULL })
if (!is.null(search)) {
near <- abs((search$break_row - 1L) - first_post) <= max(2L, as.integer(ceiling(0.05 * n)))
break_label <- fmt_time(times[search$break_row])
set_robust(list(supf_stat = search$stat, supf_p = search$p, supf_crit = search$crit, supf_break = break_label, supf_at_intervention = near))
if (search$p < 0.05 && !near) {
checks[[length(checks) + 1]] <- list(id = "break_elsewhere", label = "The strongest break is at the intervention", status = "concern", downgrade_to = "L2",
detail = sprintf("The series changes most at %s, not at the intervention (%s): sup-F = %.2f, %s. Something else may be driving the change.", as.character(break_label), as.character(start_label), search$stat, cs_fmt_p(search$p)))
} else {
checks[[length(checks) + 1]] <- list(id = "break_elsewhere", label = "The strongest break is at the intervention", status = "pass",
detail = sprintf("The strongest break is at %s (sup-F = %.2f, %s), %s", as.character(break_label), search$stat, cs_fmt_p(search$p), if (near) "close to the intervention." else "and no break stands out from chance."))
}
robust_charts[[1]] <- cs_chart("break_search", "fstat-sequence", "F for a change in level and slope at each date", list(
x = cs_col(TIME, fmt_time(times[search$candidates]), kind = if (TEMPORAL) "temporal" else "numeric"),
y = cs_col("F", search$f, kind = "numeric")
), controls = list(crit = search$crit))
}
fake <- cs_its_placebos(y, Xm[, common, drop = FALSE], first_post, if (use_reml) "reml_ar1" else "newey_west")
if (!is.null(fake)) {
rows <- fake$rows
ps <- vapply(rows, function(r) r$p, 0)
rejected <- sum(ps < 0.05)
sizes <- abs(vapply(rows, function(r) r$estimate, 0))
larger <- sum(sizes >= abs(lv[["est"]]))
set_robust(list(placebo_n = length(rows), placebo_rejected = rejected, placebo_min_p = min(ps), placebo_larger = larger))
robust_tables[[1]] <- list(key = "placebos", title = "Placebo dates before the intervention",
columns = list(list(key = "date", label = "Placebo date", type = "string"), list(key = "estimate", label = "Level change", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "p", label = "p", type = "p")),
rows = data.frame(date = vapply(rows, function(r) as.character(fmt_time(times[r$row])), ""), estimate = vapply(rows, function(r) r$estimate, 0), se = vapply(rows, function(r) r$se, 0), p = ps, stringsAsFactors = FALSE))
if (larger > 0L) {
checks[[length(checks) + 1]] <- list(id = "placebo", label = "Larger than at placebo dates", status = "concern", downgrade_to = "L2",
detail = sprintf("%d of %d placebo dates before the intervention show a level change at least as large as the intervention's (%.2f): the series moves that much without it.", larger, length(rows), abs(lv[["est"]])))
} else {
checks[[length(checks) + 1]] <- list(id = "placebo", label = "Larger than at placebo dates", status = "pass",
detail = sprintf("The intervention's level change (%.2f) is larger than at any of %d placebo dates before it (largest %.2f).", abs(lv[["est"]]), length(rows), max(sizes)))
}
} else {
checks[[length(checks) + 1]] <- list(id = "placebo", label = "Larger than at placebo dates", status = "info", detail = sprintf("With %d pre-intervention periods there are too few for placebo dates (12 or more are needed).", n_pre))
}
}
# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.its/robustness-battery/out-r")
series <- data.frame(time = fmt_time(times), observed = y, fitted = fitted_v,
counterfactual = ifelse(post, counterfactual, NA_real_), post = post)
nanoparquet::write_parquet(series, file.path(out, "its_series.parquet"))
artifacts <- list(list(key = "series", path = file.path(out, "its_series.parquet"), format = "parquet",
title = "Observed, fitted and counterfactual series"))
tvals <- fmt_time(times)
direction <- if (lv[["est"]] > 0) "rose" else "fell"
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf(
"When the intervention started (%s), %s %s by %.2f (%s CI [%.2f, %.2f], %s), and its trend changed by %.3f per period (%s). By the last period the series was %.2f away from the projected pre-intervention trend.",
as.character(start_label), Y, direction, abs(lv[["est"]]), pct, lv[["lo"]], lv[["hi"]], cs_fmt_p(lv[["p"]]), sl[["est"]], cs_fmt_p(sl[["p"]]), effect_end
)
values <- list(
estimate = lv[["est"]], se = lv[["se"]], t = lv[["t"]], p_value = lv[["p"]], ci_low = lv[["lo"]], ci_high = lv[["hi"]], n = n,
slope_change = sl[["est"]], slope_se = sl[["se"]], slope_p = sl[["p"]], slope_ci_low = sl[["lo"]], slope_ci_high = sl[["hi"]],
pre_slope = pre_slope, effect_end = effect_end, effect_end_se = effect_end_se, relative_effect_end = relative_end,
n_pre = n_pre, n_post = n_post, hac_lag = lag, durbin_watson = dw, ljung_box_p = lb_p, df_resid = dof,
inference = if (use_reml) "reml_ar1" else "newey_west", inference_label = inference_label, df_t = unname(dfs[il]), slope_df = unname(dfs[isl]),
ar1_rho = if (!is.null(reml)) reml$rho, ljung_box_white_p = white_p,
nw_estimate = unname(b_nw[il]), nw_se = sqrt(V_nw[il, il]), nw_p = nw_p(il),
nw_slope = unname(b_nw[isl]), nw_slope_se = sqrt(V_nw[isl, isl]), nw_slope_p = nw_p(isl),
estimand = "Change in level at the intervention",
effect_label = sprintf("Immediate change in %s when the intervention started", Y),
claim_level_max = "L3"
)
if (!is.null(reml)) {
values <- c(values, list(reml_estimate = reml$b[il], reml_se = sqrt(reml$V[il, il]), reml_df = reml$df[il], reml_p = reml_p_at(il),
reml_slope = reml$b[isl], reml_slope_se = sqrt(reml$V[isl, isl]), reml_slope_df = reml$df[isl], reml_slope_p = reml_p_at(isl)))
}
values <- c(values, robust_values)
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
coef_rows <- do.call(rbind, lapply(names_x, function(nm) {
r <- coef_row(nm)
data.frame(term = nm, estimate = r[["est"]], se = r[["se"]], t = r[["t"]], df = r[["df"]], p = r[["p"]])
}))
status_map <- c(concern = "warn", fail = "fail", pass = "pass", info = "info")
cs_publish(list(
method = "causal.its",
methodVersion = "1.2.2",
title = "Interrupted time series",
engine = cs_engine_info("stats", "sandwich", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("level change = %s, SE = %s, %s; slope change = %s, SE = %s, %s", cs_fmt_num(lv[["est"]]), cs_fmt_num(lv[["se"]]), cs_fmt_p(lv[["p"]]),
cs_fmt_num(sl[["est"]], 3), cs_fmt_num(sl[["se"]], 3), cs_fmt_p(sl[["p"]])),
statistics = list(
list(key = "estimate", label = "Level change", value = lv[["est"]]),
list(key = "ci", label = paste(pct, "CI"), value = c(lv[["lo"]], lv[["hi"]])),
list(key = "p_value", label = "p", value = lv[["p"]], format = "p"),
list(key = "slope_change", label = "Slope change (per period)", value = sl[["est"]]),
list(key = "slope_p", label = "p (slope)", value = sl[["p"]], format = "p"),
list(key = "effect_end", label = "Effect at the last period", value = effect_end)
),
tables = c(list(list(
key = "coefficients", title = sprintf("Segmented regression (%s)", inference_label),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "p")),
rows = coef_rows
)), robust_tables),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = unname(status_map[c$status]), detail = c$detail)),
checks = checks,
warnings = warnings,
notes = c(list(sprintf("Intervention starts at %s; %d periods before and %d after. Slope change is measured from the first post-intervention period.",
as.character(start_label), n_pre, n_post)),
if (use_reml && n < 240) list(sprintf("AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives %s for the level change and %s for the slope change, but rejects too often on series this short.", cs_fmt_p(nw_p(il)), cs_fmt_p(nw_p(isl)))),
if (n < 24) list("With fewer than 24 periods autocorrelation is poorly estimated: read p-values near .05 cautiously.")),
values = values,
artifacts = artifacts,
charts = c(list(cs_chart("series", "forecast-fan", sprintf("%s: observed, fitted and counterfactual", Y), list(
time = cs_col(TIME, c(tvals, tvals, tvals[post]), kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(Y, c(y, fitted_v, counterfactual[post]), kind = "numeric"),
kind = cs_col("kind", c(rep("actual", n), rep("fitted", n), rep("forecast", sum(post))), kind = "categorical",
levels = c("actual", "fitted", "forecast"))
))), robust_charts)
))
level change = −6.50, SE = 1.27, p < .001; slope change = −0.352, SE = 0.056, p < .001
- Level change
- −6.500
- 95% CI
- [−9.162, −3.838]
- p
- < .001
- Slope change (per period)
- −0.3519
- p (slope)
- < .001
- Effect at the last period
- −18.816
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough pre-intervention points — 48 pre-intervention and 36 post-intervention periods.
- Residual autocorrelation — Ljung–Box test on the residuals (lag 10) p = .178; Durbin–Watson 1.45.
- AR(1) describes the errors — Ljung–Box test on the whitened residuals (lag 10) p = .980; estimated ρ = 0.32.
- No co-intervention — A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series.
- A change at the intervention — Level and slope together: F(2, 14.9) = 42.23 with AR(1) errors, p < .001.
- The strongest break is at the intervention — The strongest break is at 2021-01-01 (sup-F = 81.78, p = .001), close to the intervention.
- Larger than at placebo dates — The intervention's level change (6.50) is larger than at any of 9 placebo dates before it (largest 3.18).
Segmented regression (AR(1) errors by REML with Satterthwaite df)
| Term | Estimate | SE | t | df | p |
|---|---|---|---|---|---|
| const | 121.00 | 1.054 | 114.79 | 28.228 | 3.074e-39 |
| time | 0.2390 | 0.0305 | 7.843 | 14.274 | 1.518e-6 |
| level_change | −6.500 | 1.265 | −5.138 | 17.627 | 7.346e-5 |
| slope_change | −0.3519 | 0.0557 | −6.322 | 13.283 | 2.401e-5 |
| season_1 | 3.058 | 0.9293 | 3.291 | 56.060 | 0.0017 |
| season_2 | 6.030 | 1.069 | 5.641 | 68.799 | 3.468e-7 |
| season_3 | 7.194 | 1.111 | 6.473 | 62.001 | 1.738e-8 |
| season_4 | 3.466 | 1.126 | 3.079 | 56.535 | 0.0032 |
| season_5 | 1.084 | 1.132 | 0.9571 | 54.002 | 0.3428 |
| season_6 | −0.3090 | 1.136 | −0.2720 | 53.141 | 0.7867 |
| season_7 | −1.629 | 1.139 | −1.431 | 53.436 | 0.1584 |
| season_8 | −4.981 | 1.139 | −4.372 | 55.253 | 5.493e-5 |
| season_9 | −6.473 | 1.133 | −5.715 | 59.799 | 3.695e-7 |
| season_10 | −5.863 | 1.102 | −5.319 | 67.261 | 1.283e-6 |
| season_11 | −3.476 | 0.9868 | −3.523 | 64.504 | 0.0008 |
Placebo dates before the intervention
| Placebo date | Level change | SE | p |
|---|---|---|---|
| 2018-01-01 | −2.331 | 1.977 | 0.2616 |
| 2018-04-01 | −2.021 | 1.481 | 0.2001 |
| 2018-07-01 | −2.703 | 1.316 | 0.0666 |
| 2018-10-01 | −3.184 | 1.132 | 0.0168 |
| 2019-01-01 | −0.5198 | 1.530 | 0.7418 |
| 2019-04-01 | 0.5038 | 1.452 | 0.7362 |
| 2019-07-01 | 2.463 | 1.315 | 0.0910 |
| 2019-10-01 | 0.6833 | 1.569 | 0.6722 |
| 2020-01-01 | 1.598 | 1.774 | 0.3860 |
- Intervention starts at 2021-01-01; 48 periods before and 36 after. Slope change is measured from the first post-intervention period.
- AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives p < .001 for the level change and p < .001 for the slope change, but rejects too often on series this short.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Interrupted time series (segmented regression)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.its 1.2.2 · spec 7deb30599712c35c
# Dataset: c1_its (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.stats.stattools import durbin_watson
import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import its as its_robust
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_its.parquet", columns=["admissions", "month"])
n_input = len(df)
df = df.dropna(subset=["admissions", "month"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["admissions", "month"]) # infinite values stop the run (registry/errors.yaml)
# %% Design
Y, TIME = "admissions", "month"
POST = None
COVARIATES = []
TEMPORAL = True
conf = 0.95
season = int(12)
df = df.sort_values(TIME, kind="mergesort").reset_index(drop=True)
times = pd.to_datetime(df[TIME]) if TEMPORAL else df[TIME].astype(float)
if times.duplicated().any():
raise ValueError(f"{TIME} must have one row per period; found repeated periods.")
n = len(df)
idx = np.arange(n, dtype=float) # period index 0 … n − 1 (one row per period)
if POST:
post_level = None
levels_post = list(df[POST].cat.categories)
post_level = post_level if post_level is not None else ("true" if "true" in levels_post else levels_post[-1])
post = (df[POST].astype(str) == str(post_level)).to_numpy()
if post.any() and not post[np.argmax(post):].all():
raise ValueError(f"{POST} must stay on once the intervention starts.")
else:
start_text = "2021-01-01".strip()
if not start_text:
raise ValueError("Set 'Intervention starts' or choose an 'After intervention' column.")
start = pd.Timestamp(start_text) if TEMPORAL else float(start_text)
post = (times >= start).to_numpy()
if post.all() or not post.any():
cs.cs_error("CS_E_UNDEFINED", what="The interrupted time series", reason="the series needs periods both before and after the intervention")
first_post = int(np.argmax(post))
step = post.astype(float)
since = np.where(post, idx - first_post, 0.0) # 0 in the first post-intervention period
X = pd.DataFrame({"const": 1.0, "time": idx, "level_change": step, "slope_change": since})
if season > 1:
if TEMPORAL and season == 12:
code = times.dt.month.to_numpy() - 1 # month of year
elif TEMPORAL and season == 4:
code = (times.dt.month.to_numpy() - 1) // 3 # quarter
else:
code = (idx % season).astype(int)
for s in range(1, season):
if (code == s).any():
X[f"season_{s}"] = (code == s).astype(float)
for j, c in enumerate(COVARIATES):
X[f"x{j + 1}"] = df[c].astype(float).to_numpy()
y = df[Y].astype(float).to_numpy()
if np.unique(y).size < 2: # a flat series fits exactly: no level or slope change to estimate
cs.cs_error("CS_E_CONSTANT", column=Y)
k = X.shape[1]
hac_lag = None
lag = int(hac_lag) if hac_lag is not None else int(np.floor(4 * (n / 100) ** (2 / 9)))
# %% Fit both ways. OLS with Newey–West standard errors (Bartlett weights, no prewhitening, n/(n − k)), and
# regression with AR(1) errors by REML with Satterthwaite df, which holds its error rate on short series.
ols = sm.OLS(y, X).fit(cov_type="HAC", cov_kwds={"maxlags": lag, "use_correction": True})
b_nw = ols.params.to_numpy()
V_nw = np.asarray(ols.cov_params())
names = list(X.columns)
il, isl = names.index("level_change"), names.index("slope_change")
dof = n - k
Xm = X.to_numpy(dtype=float)
reml = None
try:
reml = its_robust.reml_ar1(y, Xm)
except ValueError as e:
warnings.append(f"{e} Using Newey–West standard errors instead.")
use_reml = "reml_ar1" == "reml_ar1" and reml is not None
if use_reml:
b, V, dfs = reml["b"], reml["V"], reml["df"]
else:
b, V, dfs = b_nw, V_nw, np.full(k, float(dof))
inference_label = "AR(1) errors by REML with Satterthwaite df" if use_reml else f"Newey–West, lag {lag}"
def coef(name):
i = names.index(name)
est, se, df = float(b[i]), float(np.sqrt(V[i, i])), float(dfs[i])
t = est / se
qt = stats.t.ppf(0.5 + conf / 2, df)
return est, se, t, float(2 * stats.t.sf(abs(t), df)), est - qt * se, est + qt * se
def nw_p(i):
return float(2 * stats.t.sf(abs(b_nw[i]) / np.sqrt(V_nw[i, i]), dof))
lvl, lvl_se, lvl_t, lvl_p, lvl_lo, lvl_hi = coef("level_change")
slp, slp_se, slp_t, slp_p, slp_lo, slp_hi = coef("slope_change")
pre_slope = float(b[names.index("time")])
# Effect at the last period = level change + slope change × periods since the start.
h = since[-1]
effect_end = lvl + slp * h
effect_end_se = float(np.sqrt(V[il, il] + h * h * V[isl, isl] + 2 * h * V[il, isl]))
fitted = Xm @ b
counterfactual = fitted - lvl * step - slp * since
relative_end = effect_end / counterfactual[-1] if counterfactual[-1] != 0 else None
# %% Checks
# Durbin–Watson and Ljung–Box read the least-squares residuals, which show what the errors are like before any model of them.
resid = np.asarray(ols.resid)
dw = float(durbin_watson(resid))
lb_lag = max(1, min(10, n // 5))
lb_p = float(acorr_ljungbox(resid, lags=[lb_lag], return_df=True)["lb_pvalue"].iloc[0])
# The whitened residuals are independent if AR(1) describes the errors; their null is simulated.
white_lag = max(2, lb_lag)
white_p = its_robust.white_noise_test(reml["white"], Xm, reml["rho"], white_lag, 499, 42)["p"] if reml is not None and n > white_lag + 1 else None
n_pre, n_post = first_post, n - first_post
checks = []
if n_pre < 8:
checks.append({"id": "pre_points", "label": "Enough pre-intervention points", "status": "concern", "downgrade_to": "L2",
"detail": f"Only {n_pre} pre-intervention periods; the pre-trend (and so the counterfactual) is poorly estimated — aim for 8 or more."})
else:
checks.append({"id": "pre_points", "label": "Enough pre-intervention points", "status": "pass",
"detail": f"{n_pre} pre-intervention and {n_post} post-intervention periods."})
if lb_p < 0.05:
checks.append({"id": "autocorrelation", "label": "Residual autocorrelation", "status": "concern",
"detail": f"Ljung–Box test on the residuals (lag {lb_lag}) {cs.fmt_p(lb_p)}: errors are autocorrelated; " + (f"the AR(1) error model (ρ = {reml['rho']:.2f}) allows for it." if use_reml else f"Newey–West standard errors (lag {lag}) allow for it, but consider an AR(1) error model.")})
else:
checks.append({"id": "autocorrelation", "label": "Residual autocorrelation", "status": "pass",
"detail": f"Ljung–Box test on the residuals (lag {lb_lag}) {cs.fmt_p(lb_p)}; Durbin–Watson {dw:.2f}."})
if use_reml and white_p is not None:
if white_p < 0.05:
checks.append({"id": "ar1_errors", "label": "AR(1) describes the errors", "status": "concern",
"detail": f"Ljung–Box test on the whitened residuals (lag {white_lag}) {cs.fmt_p(white_p)}: the errors have structure AR(1) misses, so p-values may run small. Add seasonal terms or covariates if they explain it."})
else:
checks.append({"id": "ar1_errors", "label": "AR(1) describes the errors", "status": "pass",
"detail": f"Ljung–Box test on the whitened residuals (lag {white_lag}) {cs.fmt_p(white_p)}; estimated ρ = {reml['rho']:.2f}."})
if not use_reml and n < 240:
checks.append({"id": "short_series", "label": "Long enough for Newey–West", "status": "concern",
"detail": f"With {n} periods, Newey–West level tests reject too often: about 10–27% at the 5% level for 24–72 periods in simulations with no effect, still 7–13% at 240." + (f" The AR(1) model gives {cs.fmt_p(float(2 * stats.t.sf(abs(reml['b'][il]) / np.sqrt(reml['V'][il, il]), reml['df'][il])))} for the level change." if reml is not None else "")})
checks.append({"id": "cointervention", "label": "No co-intervention", "status": "info",
"detail": "A single series cannot rule out other changes at the same time; attest that nothing else changed, or add a control series."})
fmt_time = (lambda v: pd.Timestamp(v).strftime("%Y-%m-%d")) if TEMPORAL else (lambda v: float(v))
start_label = fmt_time(times.iloc[first_post])
# %% Robustness: a change at the intervention, the strongest break date, placebo dates
robust_values = dict.fromkeys(["chow_f", "chow_p", "chow_hac_f", "chow_hac_p", "chow_reml_f", "chow_reml_df2", "chow_reml_p", "supf_stat", "supf_p", "supf_crit", "supf_break", "supf_at_intervention", "placebo_n", "placebo_rejected", "placebo_min_p", "placebo_larger"])
robust_tables, robust_charts = [], []
if True:
common = [j for j, nm in enumerate(names) if nm not in ("level_change", "slope_change")]
chow = its_robust.chow_at(y, Xm, [il, isl], V_nw)
robust_values.update({"chow_f": chow["f"], "chow_p": chow["p"], "chow_hac_f": chow["hac_f"], "chow_hac_p": chow["hac_p"]})
wald = its_robust.reml_wald(reml, [il, isl]) if reml is not None else None
if wald:
robust_values.update({"chow_reml_f": wald["f"], "chow_reml_df2": wald["df2"], "chow_reml_p": wald["p"]})
if use_reml:
checks.append({"id": "chow", "label": "A change at the intervention", "status": "pass" if wald["p"] < 0.05 else "info",
"detail": f"Level and slope together: F({wald['df1']}, {wald['df2']:.1f}) = {wald['f']:.2f} with AR(1) errors, {cs.fmt_p(wald['p'])}."})
else:
checks.append({"id": "chow", "label": "A change at the intervention", "status": "pass" if chow["hac_p"] < 0.05 else "info",
"detail": f"Level and slope together: F({chow['df1']}, {chow['df2']}) = {chow['hac_f']:.2f} with Newey–West errors, {cs.fmt_p(chow['hac_p'])}."})
search = None
try:
search = its_robust.sup_f(y, Xm[:, common], 0.15, 999, 42, reml["rho"] if reml is not None else 0.0)
except ValueError as e:
warnings.append(str(e))
if search:
near = abs(search["break_row"] - first_post) <= max(2, int(np.ceil(0.05 * n)))
break_label = fmt_time(times.iloc[search["break_row"]])
robust_values.update({"supf_stat": search["stat"], "supf_p": search["p"], "supf_crit": search["crit"], "supf_break": break_label if TEMPORAL else float(break_label), "supf_at_intervention": bool(near)})
if search["p"] < 0.05 and not near:
checks.append({"id": "break_elsewhere", "label": "The strongest break is at the intervention", "status": "concern", "downgrade_to": "L2",
"detail": f"The series changes most at {break_label}, not at the intervention ({start_label}): sup-F = {search['stat']:.2f}, {cs.fmt_p(search['p'])}. Something else may be driving the change."})
else:
checks.append({"id": "break_elsewhere", "label": "The strongest break is at the intervention", "status": "pass",
"detail": f"The strongest break is at {break_label} (sup-F = {search['stat']:.2f}, {cs.fmt_p(search['p'])}), " + ("close to the intervention." if near else "and no break stands out from chance.")})
robust_charts.append(cs.chart("break_search", "fstat-sequence", "F for a change in level and slope at each date",
{"x": cs.col(TIME, [fmt_time(times.iloc[r]) for r in search["candidates"]], kind="temporal" if TEMPORAL else "numeric"),
"y": cs.col("F", search["f"], kind="numeric")}, controls={"crit": search["crit"]}))
fake = its_robust.placebos(y, Xm[:, common], first_post, "reml_ar1" if use_reml else "newey_west")
if fake:
rows = fake["rows"]
rejected = sum(1 for r in rows if r["p"] < 0.05)
larger = sum(1 for r in rows if abs(r["estimate"]) >= abs(lvl))
robust_values.update({"placebo_n": len(rows), "placebo_rejected": rejected, "placebo_min_p": min(r["p"] for r in rows), "placebo_larger": larger})
robust_tables.append({"key": "placebos", "title": "Placebo dates before the intervention",
"columns": [{"key": "date", "label": "Placebo date", "type": "string"}, {"key": "estimate", "label": "Level change", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": [{"date": str(fmt_time(times.iloc[r["row"]])), "estimate": r["estimate"], "se": r["se"], "p": r["p"]} for r in rows]})
biggest = max(abs(r["estimate"]) for r in rows)
if larger:
checks.append({"id": "placebo", "label": "Larger than at placebo dates", "status": "concern", "downgrade_to": "L2",
"detail": f"{larger} of {len(rows)} placebo dates before the intervention show a level change at least as large as the intervention's ({abs(lvl):.2f}): the series moves that much without it."})
else:
checks.append({"id": "placebo", "label": "Larger than at placebo dates", "status": "pass",
"detail": f"The intervention's level change ({abs(lvl):.2f}) is larger than at any of {len(rows)} placebo dates before it (largest {biggest:.2f})."})
else:
checks.append({"id": "placebo", "label": "Larger than at placebo dates", "status": "info", "detail": f"With {n_pre} pre-intervention periods there are too few for placebo dates (12 or more are needed)."})
# %% Result
out = csml.out_dir("target/academy-parity/run-953/causal.its/robustness-battery/out-python")
artifacts = []
series = pd.DataFrame({"time": [fmt_time(v) for v in times], "observed": y, "fitted": fitted,
"counterfactual": np.where(post, counterfactual, np.nan), "post": post})
series.to_parquet(os.path.join(out, "its_series.parquet"), index=False)
artifacts.append({"key": "series", "path": os.path.join(out, "its_series.parquet"), "format": "parquet", "title": "Observed, fitted and counterfactual series"})
tkind = "temporal" if TEMPORAL else "numeric"
tvals = [fmt_time(v) for v in times]
cf_t = [tvals[i] for i in range(n) if post[i]]
cf_v = [float(counterfactual[i]) for i in range(n) if post[i]]
chart_rows = {"time": tvals + tvals + cf_t, "value": list(y) + list(fitted) + cf_v,
"kind": ["actual"] * n + ["fitted"] * n + ["forecast"] * len(cf_t)}
direction = "rose" if lvl > 0 else "fell"
summary = (
f"When the intervention started ({start_label}), {Y} {direction} by {abs(lvl):.2f} ({conf:.0%} CI [{lvl_lo:.2f}, {lvl_hi:.2f}], "
f"{cs.fmt_p(lvl_p)}), and its trend changed by {slp:.3f} per period ({cs.fmt_p(slp_p)}). By the last period the series was "
f"{effect_end:.2f} away from the projected pre-intervention trend."
)
values = {
"estimate": lvl, "se": lvl_se, "t": lvl_t, "p_value": lvl_p, "ci_low": lvl_lo, "ci_high": lvl_hi, "n": n,
"slope_change": slp, "slope_se": slp_se, "slope_p": slp_p, "slope_ci_low": slp_lo, "slope_ci_high": slp_hi,
"pre_slope": pre_slope, "effect_end": effect_end, "effect_end_se": effect_end_se, "relative_effect_end": relative_end,
"n_pre": n_pre, "n_post": n_post, "hac_lag": lag, "durbin_watson": dw, "ljung_box_p": lb_p, "df_resid": dof,
"inference": "reml_ar1" if use_reml else "newey_west", "inference_label": inference_label, "df_t": float(dfs[il]), "slope_df": float(dfs[isl]),
"ar1_rho": reml["rho"] if reml is not None else None, "ljung_box_white_p": white_p,
"nw_estimate": float(b_nw[il]), "nw_se": float(np.sqrt(V_nw[il, il])), "nw_p": nw_p(il),
"nw_slope": float(b_nw[isl]), "nw_slope_se": float(np.sqrt(V_nw[isl, isl])), "nw_slope_p": nw_p(isl),
**({"reml_estimate": float(reml["b"][il]), "reml_se": float(np.sqrt(reml["V"][il, il])), "reml_df": float(reml["df"][il]),
"reml_p": float(2 * stats.t.sf(abs(reml["b"][il]) / np.sqrt(reml["V"][il, il]), reml["df"][il])),
"reml_slope": float(reml["b"][isl]), "reml_slope_se": float(np.sqrt(reml["V"][isl, isl])), "reml_slope_df": float(reml["df"][isl]),
"reml_slope_p": float(2 * stats.t.sf(abs(reml["b"][isl]) / np.sqrt(reml["V"][isl, isl]), reml["df"][isl]))} if reml is not None else {}),
"estimand": "Change in level at the intervention",
"effect_label": f"Immediate change in {Y} when the intervention started",
"claim_level_max": "L3",
**robust_values,
}
for c in checks:
values[f"check[{c['id']}]"] = c["status"]
cs.publish({
"method": "causal.its",
"methodVersion": "1.2.2",
"title": "Interrupted time series",
"engine": cs.engine_info("pandas", "numpy", "statsmodels"),
"n": n,
"summary": summary,
"apa": f"level change = {cs.fmt_num(lvl)}, SE = {cs.fmt_num(lvl_se)}, {cs.fmt_p(lvl_p)}; slope change = {cs.fmt_num(slp, 3)}, SE = {cs.fmt_num(slp_se, 3)}, {cs.fmt_p(slp_p)}",
"statistics": [
{"key": "estimate", "label": "Level change", "value": lvl},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [lvl_lo, lvl_hi]},
{"key": "p_value", "label": "p", "value": lvl_p, "format": "p"},
{"key": "slope_change", "label": "Slope change (per period)", "value": slp},
{"key": "slope_p", "label": "p (slope)", "value": slp_p, "format": "p"},
{"key": "effect_end", "label": "Effect at the last period", "value": effect_end},
],
"tables": [{
"key": "coefficients", "title": f"Segmented regression ({inference_label})",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
{"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
"rows": [{"term": nm, "estimate": float(b[i]), "se": float(np.sqrt(V[i, i])),
"t": float(b[i] / np.sqrt(V[i, i])), "df": float(dfs[i]), "p": float(2 * stats.t.sf(abs(b[i] / np.sqrt(V[i, i])), dfs[i]))}
for i, nm in enumerate(names)],
}] + robust_tables,
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn", "fail": "fail"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": [f"Intervention starts at {start_label}; {n_pre} periods before and {n_post} after. Slope change is measured from the first post-intervention period."]
+ ([f"AR(1) errors by REML with Satterthwaite degrees of freedom (Turner et al. 2021). Newey–West gives {cs.fmt_p(nw_p(il))} for the level change and {cs.fmt_p(nw_p(isl))} for the slope change, but rejects too often on series this short."] if use_reml and n < 240 else [])
+ (["With fewer than 24 periods autocorrelation is poorly estimated: read p-values near .05 cautiously."] if n < 24 else []),
"values": values,
"artifacts": artifacts,
"charts": [cs.chart("series", "forecast-fan", f"{Y}: observed, fitted and counterfactual",
{"time": cs.col(TIME, chart_rows["time"], kind=tkind),
"value": cs.col(Y, chart_rows["value"], kind="numeric"),
"kind": cs.col("kind", chart_rows["kind"], kind="categorical", levels=["actual", "fitted", "forecast"])})] + robust_charts,
})
- A Chow testChow testAn F test of whether a regression's coefficients differ before and after a date fixed in advance. at the intervention tests level and slope together, with the same AR(1) errors: p < .001.
- A search for the strongest breakStructural breakA one-time change in a series' level or trend (a crash, a policy change) that can make a stationary series look like a random walk. anywhere in the series lands on 2021-01-01, the intervention month itself.
If the strongest break sat somewhere else, something else may be driving the change.
Check your understanding
CheckpointCheck yourself
A new admissions policy started the same month a nearby hospital closed. What can the placebo dates and break search tell you?
Show the answer
Answer: b
No co-intervention is an assumption the series can't test. Look for a comparison series, or say plainly that the two are confounded.
Check yourself
Your series has 60 months. The real level change is 4, with p = 0.03. Two of eight placebo dates show changes of about 5. What should you conclude?
Show the answer
Answer: b
Compare sizes. A change no larger than ordinary movement in the series isn't convincing evidence, whatever its p-value.
Check yourself
Durbin–Watson is near 2 and Ljung–Box gives p = 0.18. What does this support?
Show the answer
Answer: a
These are checks on the residuals. They say nothing about cause, and clean residuals don't remove the short-series problem with level tests.
Try it
In the appIn the Causal studio's Design step, answer yes when asked whether there's only one aggregate series with a known intervention date. Turn on Robustness battery in the method's options.
Both tabs fit the Newey–West row by hand. The R tab also fits the AR(1) model with nlme, which gives the card's estimate and standard error; Satterthwaite's degrees of freedom come from the app.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("admissions.csv", parse_dates=["month"])
df["t"] = range(1, len(df) + 1)
start = df.loc[df["month"] == "2021-01-01", "t"].iloc[0]
df["post"] = (df["t"] >= start).astype(int)
df["since"] = (df["t"] - start) * df["post"]
df["moy"] = df["month"].dt.month
fit = smf.ols("admissions ~ t + post + since + C(moy)", df).fit(
cov_type="HAC", cov_kwds={"maxlags": 3, "use_correction": True}
)
print(fit.params[["post", "since"]], fit.bse[["post", "since"]])library(sandwich)
library(lmtest)
df <- read.csv("admissions.csv")
df$month <- as.Date(df$month)
df$t <- seq_len(nrow(df))
start <- df$t[df$month == as.Date("2021-01-01")]
df$post <- as.integer(df$t >= start)
df$since <- (df$t - start) * df$post
df$moy <- factor(format(df$month, "%m"))
fit <- lm(admissions ~ t + post + since + moy, df)
coeftest(fit, vcov = NeweyWest(fit, lag = 3, prewhite = FALSE, adjust = TRUE))
ar1 <- nlme::gls(admissions ~ t + post + since + moy, df,
correlation = nlme::corAR1(form = ~ t), method = "REML")
summary(ar1)$tTable[c("post", "since"), 1:2]Recap
Recap- Report both the level change and the trend change, and the effect at a later date.
- Model seasonality, and check the residuals with Durbin–Watson and Ljung–Box.
- On short series, Newey–West tests reject too often, so lead with AR(1) errors by REML, and check what they leave behind.
- Use placebo dates to compare sizes.
- No check can separate two things that changed on the same date.
Concepts in this lesson