InterruptedTimeSeries#
- class causalpy.experiments.interrupted_time_series.InterruptedTimeSeries[source]#
The class for interrupted time series analysis.
Supports both two-period (permanent intervention) and three-period (temporary intervention) designs. When
treatment_end_timeis provided, the analysis splits the post-intervention period into an intervention period and a post-intervention period, enabling analysis of effect persistence and decay.- Parameters:
data (
DataFrame) – A pandas dataframe with time series data. The index should be either a DatetimeIndex or numeric (integer/float), with unique values in monotonically increasing order.treatment_time (
int|float|Timestamp) – The time when treatment occurred, should be in reference to the data index. Must match the index type (DatetimeIndex requires pd.Timestamp). INCLUSIVE: Observations at exactlytreatment_timeare included in the post-intervention period (uses>=comparison).formula (
str) – A statistical model formula using patsy syntax (e.g., “y ~ 1 + t + C(month)”).model (
PyMCModel|RegressorMixin|PyMCForecastModel|None) – A PyMC (Bayesian) or sklearn (OLS) model. If None, defaults to a PyMC LinearRegression model. Alternatively, aPyMCForecastModelwrapping apymc_forecastforecasting model can serve as the counterfactual backend (requires the optionalpymc-forecastdependency); seecausalpy.pymc_forecast_modelsfor when to prefer it.treatment_end_time (
int|float|Timestamp|None) – The time when treatment ended, enabling three-period analysis. Must be greater thantreatment_timeand within the data range. If None (default), the analysis assumes a permanent intervention (two-period design). INCLUSIVE: Observations at exactlytreatment_end_timeare included in the post-intervention period (uses>=comparison).**kwargs (
Any) – Additional keyword arguments passed to the model.
Notes
Estimate extraction
The model is fitted to pre-intervention observations and predicts the untreated trajectory after the intervention. Pointwise impact is the observed post-intervention outcome minus that one-sided counterfactual prediction, and cumulative impact is its running sum. Bayesian backends subtract the posterior conditional expectation
murather than noisy posterior-predictive drawsy_hat; OLS subtracts its point prediction.This fit-predict-subtract procedure is a reduced-form estimator. From a Bayesian structural perspective, the same impact can be viewed as the response to an intervention shock in a state-space model of the outcome series; see the knowledgebase page on structural causal models for the reduced-form versus structural distinction.
The three-period design is useful for analyzing temporary interventions such as:
Marketing campaigns with defined start and end dates
Policy trials or pilot programs
Clinical treatments with limited duration
Seasonal interventions
Use
effect_summary(period="intervention")to analyze effects during the intervention, andeffect_summary(period="post")to analyze effect persistence after the intervention ends.Examples
Two-period design (permanent intervention):
>>> import causalpy as cp >>> df = ( ... cp.load_data("its") ... .assign(date=lambda x: pd.to_datetime(x["date"])) ... .set_index("date") ... ) >>> treatment_time = pd.to_datetime("2017-01-01") >>> result = cp.InterruptedTimeSeries( ... df, ... treatment_time, ... formula="y ~ 1 + t + C(month)", ... model=cp.pymc_models.LinearRegression( ... sample_kwargs={"random_seed": 42, "progressbar": False} ... ), ... )
Three-period design (temporary intervention):
>>> treatment_time = pd.to_datetime("2017-01-01") >>> treatment_end_time = pd.to_datetime("2017-06-01") >>> result = cp.InterruptedTimeSeries( ... df, ... treatment_time, ... formula="y ~ 1 + t + C(month)", ... model=cp.pymc_models.LinearRegression( ... sample_kwargs={"random_seed": 42, "progressbar": False} ... ), ... treatment_end_time=treatment_end_time, ... ) >>> # Get period-specific effect summaries >>> intervention_summary = result.effect_summary(period="intervention") >>> post_summary = result.effect_summary(period="post")
Methods
Run the experiment algorithm: fit model, predict, and calculate causal impact.
Analyze effect persistence between intervention and post-intervention periods.
InterruptedTimeSeries.effect_summary(*[, ...])Generate a decision-ready summary of causal effects for Interrupted Time Series.
InterruptedTimeSeries.fit(*args, **kwargs)Fit the underlying model.
InterruptedTimeSeries.generate_report(*[, ...])Generate a self-contained HTML report for this experiment.
InterruptedTimeSeries.get_plot_data([hdi_prob])Recover the data of the experiment along with the prediction and causal impact information.
InterruptedTimeSeries.input_validation(data, ...)Validate the input data and model formula for correctness.
InterruptedTimeSeries.plot(*[, round_to, ...])Plot the interrupted time-series results.
Ask the model to print its coefficients.
Set optional maketables rendering options for this experiment.
InterruptedTimeSeries.summary([round_to])Print summary of main results and model coefficients.
Attributes
datapostData from on or after the treatment time (inclusive).
datapreData from before the treatment time (exclusive).
idataReturn fitted InferenceData when the model backend supports it.
supports_bayessupports_olssupports_pymc_forecastlabelsdata- classmethod __new__(*args, **kwargs)#