Skip to content

CCausal inference · causal.its

Interrupted time series (segmented regression)

Did the level or the trend of a series change when an intervention started?

Segmented regression of a single series on time, an intervention step and the post-intervention trend change (optionally with seasonal terms and covariates), with AR(1) errors fitted by REML and Satterthwaite degrees of freedom, or Newey–West (HAC) standard errors. Reports the immediate level change, the slope change and the effect at the end of the series against the projected counterfactual.

Verified in Python and R Python and R agree to 10 decimals Seeded

A real result

Example “Monthly date”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Interrupted time seriesRecorded · Python and R agreeRecorded 2026-11-17 · 65 values compared · largest relative difference 5.7e-14
R

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

Plots

admissions: observed, fitted and counterfactualWhere is the series heading, and how uncertain is the forecast?
View data
kindmonthadmissions
actual1,483,228,800,000121.99
actual1,485,907,200,000120.86
actual1,488,326,400,000127.16
actual1,491,004,800,000131.74
actual1,493,596,800,000125.45
actual1,496,275,200,000123.03
actual1,498,867,200,000123.42
actual1,501,545,600,000118.87
actual1,504,224,000,000116.91
actual1,506,816,000,000117.11
actual1,509,494,400,000119.06
actual1,512,086,400,000122.21
actual1,514,764,800,000124.32
actual1,517,443,200,000131.37
actual1,519,862,400,000128.61
actual1,522,540,800,000134.18
actual1,525,132,800,000128.37
actual1,527,811,200,000127.08
actual1,530,403,200,000125.46
actual1,533,081,600,000125.65
actual1,535,760,000,000119.58
actual1,538,352,000,000116.75
actual1,541,030,400,000118.82
actual1,543,622,400,000118.93
actual1,546,300,800,000124.93
actual1,548,979,200,000127.03
actual1,551,398,400,000132.45
actual1,554,076,800,000133.41
actual1,556,668,800,000129.09
actual1,559,347,200,000128.35
actual1,561,939,200,000128.93
actual1,564,617,600,000127.82
actual1,567,296,000,000125.22
actual1,569,888,000,000121.43
actual1,572,566,400,000122.17
actual1,575,158,400,000126.23
actual1,577,836,800,000129.31
actual1,580,515,200,000135.71
actual1,583,020,800,000138.57
actual1,585,699,200,000136.85
actual1,588,291,200,000135.86
actual1,590,969,600,000133.59
actual1,593,561,600,000129.13
actual1,596,240,000,000128.92
actual1,598,918,400,000125.94
actual1,601,510,400,000125.15
actual1,604,188,800,000126.90
actual1,606,780,800,000129.71
actual1,609,459,200,000127.20
actual1,612,137,600,000125.31
actual1,614,556,800,000125.49
actual1,617,235,200,000131.80
actual1,619,827,200,000129.95
actual1,622,505,600,000127.84
actual1,625,097,600,000125.96
actual1,627,776,000,000123.30
actual1,630,454,400,000122.38
actual1,633,046,400,000119.93
actual1,635,724,800,000118.51
actual1,638,316,800,000123.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)

TermEstimateSEtdfp
const121.001.054114.7928.2283.074e-39
time0.23900.03057.84314.2741.518e-6
level_change−6.5001.265−5.13817.6277.346e-5
slope_change−0.35190.0557−6.32213.2832.401e-5
season_13.0580.92933.29156.0600.0017
season_26.0301.0695.64168.7993.468e-7
season_37.1941.1116.47362.0011.738e-8
season_43.4661.1263.07956.5350.0032
season_51.0841.1320.957154.0020.3428
season_6−0.30901.136−0.272053.1410.7867
season_7−1.6291.139−1.43153.4360.1584
season_8−4.9811.139−4.37255.2535.493e-5
season_9−6.4731.133−5.71559.7993.695e-7
season_10−5.8631.102−5.31967.2611.283e-6
season_11−3.4760.9868−3.52364.5040.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.
Python

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)

TermEstimateSEtdfp
const121.001.054114.7928.2283.074e-39
time0.23900.03057.84314.2741.518e-6
level_change−6.5001.265−5.13817.6277.346e-5
slope_change−0.35190.0557−6.32213.2832.401e-5
season_13.0580.92933.29156.0600.0017
season_26.0301.0695.64168.7993.468e-7
season_37.1941.1116.47362.0011.738e-8
season_43.4661.1263.07956.5350.0032
season_51.0841.1320.957154.0020.3428
season_6−0.30901.136−0.272053.1410.7867
season_7−1.6291.139−1.43153.4360.1584
season_8−4.9811.139−4.37255.2535.493e-5
season_9−6.4731.133−5.71559.7993.695e-7
season_10−5.8631.102−5.31967.2611.283e-6
season_11−3.4760.9868−3.52364.5040.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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Monthly datec1_its · outcome: admissions · time: month
  • Post columnc1_its · outcome: admissions · post: after policy · time: index
  • Robustness batteryc1_its · outcome: admissions · time: month
  • Numeric startc1_its · outcome: admissions · time: index
  • Newey westc1_its · outcome: admissions · time: month
  • Degenerate constantc1_its · outcome: admissions · time: month
  • Degenerate n3c1_its · outcome: admissions · time: month

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?

What you need

Outcomenumeric · 1 column
The series measured before and after the intervention.
Timenumeric / temporal · 1 column
One row per period, in any order (sorted by time).
After interventionboolean / categorical · 0–1 column · 2–2 levels
Marks periods after the intervention. Leave empty and set "Intervention starts" instead.
Covariatesnumeric · 0–10 columns
Other time-varying numbers to adjust for (for example, a control series).

Choices you make

hypothesis

Intervention startsdefault —

The first post-intervention period — a number, or a date (YYYY-MM-DD) for a date column.

After-intervention leveldefault —

The level of the period column that marks rows after the intervention.

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Seasonal perioddefault 0

Adds seasonal dummies: 12 for monthly data (month of year for dates), 4 for quarterly … 0 = none.

Standard errorsdefault reml_ar1

How the regression allows for correlated errors. Newey–West is also shown alongside for comparison.

  • AR(1) errors (REML)(default) — Each error carries part of the last, with Satterthwaite df. Holds its error rate best on series of 24 periods or more.
  • Newey–West — Least squares with autocorrelation-robust errors. Rejects too often on short series; use it to match a published analysis.
Newey–West lagdefault —

Automatic: floor(4 (n / 100)^(2/9)).

Robustness batterydefault off

Adds a Chow test at the intervention, a search for the strongest break date, and placebo dates before the intervention.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • No co-intervention

    Nothing else that affects the outcome changed at the same time; a single series can't rule this out, a control series can.

  • Stable pre-period trendNot checked from data: state why it holds

    Without the intervention, the pre-intervention trend would have continued; the data can't show this after the intervention.

  • Enough pre-intervention points

    The pre-intervention trend stands in for the counterfactual; aim for 8 or more pre-intervention periods.

  • Autocorrelation handled

    AR(1) errors or Newey–West standard errors allow for correlated errors; what's left in the residuals is tested.

  • AR(1) describes the errors

    With AR(1) errors, a Ljung–Box test on the whitened residuals shows structure the model misses.

  • Long enough for Newey–West

    Newey–West tests reject too often in short series; the AR(1) model is safer then.

  • A change at the intervention

    Level and slope changes tested together at the intervention.

  • The strongest break is at the intervention

    A sup-F search over all dates; a bigger break elsewhere suggests something else drives the change.

  • Larger than at placebo dates

    The intervention's level change compared with fake intervention dates before it.

What it reports

  • Tests: Level change at the intervention
  • Tests: Trend change after the intervention
estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
t
An estimate divided by its standard error, compared with a t distribution.
p_value
How surprising your data would be if the null hypothesis were true, as a probability.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
n
How many independent units the analysis used; it sets precision and power.
slope_change
Fits a series' level and trend before and after an intervention and reports the changes.
slope_se
A straight line fitted allowing for measurement error in both methods, given the ratio of their error variances (1 = equally precise).
slope_p
How surprising your data would be if the null hypothesis were true, as a probability.
slope_ci_low
A range of effect values compatible with your data at the chosen confidence level.
slope_ci_high
A range of effect values compatible with your data at the chosen confidence level.
pre_slope
Fits a series' level and trend before and after an intervention and reports the changes.
effect_end
Fits a series' level and trend before and after an intervention and reports the changes.
effect_end_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
relative_effect_end
Fits a series' level and trend before and after an intervention and reports the changes.
n_pre
How many independent units the analysis used; it sets precision and power.
n_post
How many independent units the analysis used; it sets precision and power.
hac_lag
Standard errors that allow correlation between nearby observations in a series, up to a chosen lag.
durbin_watson
Checks residuals for first-order autocorrelation. Values near 2 suggest none, and values well below 2 suggest positive correlation.
ljung_box_p
How surprising your data would be if the null hypothesis were true, as a probability.
inference
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
inference_label
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
df_t
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
slope_df
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
ar1_rho
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
ljung_box_white_p
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
nw_estimate
The same segmented regression by least squares with Newey–West errors, beside the AR(1) fit. Its tests reject too often on short series.
nw_se
The same segmented regression by least squares with Newey–West errors, beside the AR(1) fit. Its tests reject too often on short series.
nw_p
The same segmented regression by least squares with Newey–West errors, beside the AR(1) fit. Its tests reject too often on short series.
nw_slope
The same segmented regression by least squares with Newey–West errors, beside the AR(1) fit. Its tests reject too often on short series.
nw_slope_se
The same segmented regression by least squares with Newey–West errors, beside the AR(1) fit. Its tests reject too often on short series.
nw_slope_p
The same segmented regression by least squares with Newey–West errors, beside the AR(1) fit. Its tests reject too often on short series.
reml_estimate
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_se
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_df
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_p
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_slope
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_slope_se
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_slope_df
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
reml_slope_p
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
chow_f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
chow_p
How surprising your data would be if the null hypothesis were true, as a probability.
chow_hac_f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
chow_hac_p
How surprising your data would be if the null hypothesis were true, as a probability.
chow_reml_f
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
chow_reml_df2
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
chow_reml_p
A regression where each error carries part of the last, fitted by REML. It holds its error rate better than Newey–West on short series.
supf_stat
The largest Chow F over every candidate break date, with a p-value that accounts for having searched for the worst one.
supf_p
How surprising your data would be if the null hypothesis were true, as a probability.
supf_crit
The largest Chow F over every candidate break date, with a p-value that accounts for having searched for the worst one.
supf_break
The largest Chow F over every candidate break date, with a p-value that accounts for having searched for the worst one.
supf_at_intervention
The largest Chow F over every candidate break date, with a p-value that accounts for having searched for the worst one.
placebo_n
Rerun the analysis where no effect should exist. An "effect" there means your method finds things that aren't real.
placebo_rejected
Rerun the analysis where no effect should exist. An "effect" there means your method finds things that aren't real.
placebo_min_p
How surprising your data would be if the null hypothesis were true, as a probability.
placebo_larger
Rerun the analysis where no effect should exist. An "effect" there means your method finds things that aren't real.
estimand
The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
effect_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
claim_level_max
How strong a causal statement the design supports, from association up to a causal effect.

Per group, level or term: check[<id>], df_resid

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, statsmodels, codesplash; R uses sandwich, nanoparquet, codesplashr.

Default traps between the two languages

  • Newey–West level tests reject too often with no effect: simulated AR(1) errors (ρ = 0, .3, .6; 1,500 series each) give 14–26% at 24 periods, 10–19% at 72, 7–13% at 240. AR(1) errors by REML with Satterthwaite df give 4.4–7.8% (level) and 3.5–5.6% (slope) at 24–144 periods (1,000 series each), in line with Turner et al. (2021), who prefer REML on series of 12 or more, so it leads and Newey–West is shown beside it. Under errors AR(1) can't describe (AR(2), ARMA(1,1); 400 series each) both run high, REML less (10–21% against 22–49%); the whitened-residual check flags that.
  • The break search simulates its null with AR(1) errors at the fitted ρ. With an iid null, as a first version did, 31–92% of series with no break reached p < .05 at ρ = .3 and .6 (48–240 periods); with the fitted AR(1), 4.0–6.5%.
  • The whitened-residual check has a Monte Carlo p-value on the shared stream: a chi-square reference rejects about 10% at 48 periods with AR(1) errors in truth, because the step and trend shape the residuals.
  • REML: both engines find ρ as the root of the same restricted score from the same grid (codesplash.causal.its ↔ cs_its_reml_ar1). Coefficients and ρ match nlme::gls(correlation = corAR1(), method = 'REML'), whose optimizer stops earlier (tests/crosscheck/w2o2_its.R).
  • Newey–West pinned in both engines: Bartlett weights 1 − j/(L + 1), no prewhitening, small-sample factor n/(n − k) (statsmodels cov_type='HAC', use_correction=True ↔ sandwich::NeweyWest(prewhite = FALSE, adjust = TRUE)).
Python

The exact script CodeSplash ran for example “Monthly date” · 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,
})
R

The exact script CodeSplash ran for example “Monthly date” · 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)
))

Sources

  • Andrews, D. W. K. (1993). Tests for parameter instability and structural change with unknown change point. Econometrica, 61, 821–856.
  • Linden, A. (2015). Conducting interrupted time-series analysis for single- and multiple-group comparisons. The Stata Journal, 15, 480–500.
  • Bernal, J. L., Cummins, S., & Gasparrini, A. (2017). Interrupted time series regression for the evaluation of public health interventions: a tutorial. International Journal of Epidemiology, 46, 348–355.
  • Newey, W. K., & West, K. D. (1987). A simple, positive semi-definite, heteroskedasticity and autocorrelation consistent covariance matrix. Econometrica, 55, 703–708.
  • Turner, S. L., Forbes, A. B., Karahalios, A., Taljaard, M., & McKenzie, J. E. (2021). Evaluation of statistical methods used in the analysis of interrupted time series studies: a simulation study. BMC Medical Research Methodology, 21, 181.
  • Satterthwaite, F. E. (1946). An approximate distribution of estimates of variance components. Biometrics Bulletin, 2, 110–114.
  • Dufour, J.-M., Farhat, A., Gardiol, L., & Khalaf, L. (1998). Simulation-based finite sample normality tests in linear regressions. The Econometrics Journal, 1, C154–C173.
  • Fai, A. H.-T., & Cornelius, P. L. (1996). Approximate F-tests of multiple degree of freedom hypotheses in generalized least squares analyses of unbalanced split-plot experiments. Journal of Statistical Computation and Simulation, 54, 363–378.

From the CodeSplash method registry · causal.its v1.2.2.