Skip to content

statspai.causal_impact

causal_impact

Causal Impact module for StatsPAI.

Estimates the causal effect of an intervention on a time series by constructing a synthetic counterfactual from control series using a structural time-series model.

Equivalent to Google's R CausalImpact package.

References

Brodersen, K.H., Gallusser, F., Koehler, J., Remy, N., and Scott, S.L. (2015). "Inferring Causal Impact Using Bayesian Structural Time-Series Models." Annals of Applied Statistics, 9(1), 247-274. [@brodersen2015inferring]

CausalImpactEstimator

Causal Impact estimator using structural time-series model.

fit

fit() -> CausalResult

Fit the structural time-series model and estimate causal impact.

causal_impact

causal_impact(data: DataFrame, y: str, time: str, intervention_time: Any, covariates: Optional[List[str]] = None, alpha: float = 0.05, n_seasons: Optional[int] = None) -> CausalResult

Estimate the causal impact of an intervention on a time series.

Parameters:

Name Type Description Default
data DataFrame

Time-series data (one row per time period).

required
y str

Outcome variable (the series that was intervened upon).

required
time str

Time column (used for ordering; can be int, date, etc.).

required
intervention_time any

First period of the intervention (inclusive).

required
covariates list of str

Control time series (not affected by the intervention). If None, uses a local-level model without covariates.

None
alpha float

Significance level for credible intervals.

0.05
n_seasons int

Seasonal period (e.g., 7 for weekly, 12 for monthly).

None

Returns:

Type Description
CausalResult

Examples:

>>> # Effect of a marketing campaign starting week 50
>>> result = causal_impact(df, y='sales', time='week',
...                        intervention_time=50,
...                        covariates=['competitor_sales', 'ad_spend'])
>>> print(result.summary())
>>> result.plot()

impactplot

impactplot(result: CausalResult, type: str = 'all', ax=None, figsize: tuple = (12, 9), title=None)

Causal Impact visualization (Google-style 3-panel plot).

Parameters:

Name Type Description Default
result CausalResult

Result from causal_impact().

required
type str

'all': 3-panel (original + pointwise + cumulative). 'original': actual vs counterfactual. 'pointwise': pointwise causal effect. 'cumulative': cumulative effect.

'all'
ax matplotlib Axes

Only for single-panel types.

None
figsize tuple
(12, 9)
title str
None

Returns:

Type Description
(fig, ax) or (fig, axes)