Mathematical Formulation of CausalImpact Analysis Using Structural Time Series and Gibbs Sampling
The state-space model, priors, and Gibbs sampling steps behind CausalImpact, plus how to turn posterior samples into a causal effect estimate.
This post contains affiliate links for tools I use in production. If you buy through them I earn a commission at no extra cost to you. Recommendations are based on my own experience.
Table of Contents
- 1. Overview
- 2. Structural Time Series (STS) Model
- 3. Priors and Hyperparameters
- 4. Bayesian Inference via Gibbs Sampling
- 5. Posterior Predictive Inference
- 6. Causal Effect Estimation
- 7. Matrix Operations and Linear Algebra
- 8. Data Standardization and Scaling
- 9. Seasonal Effects Handling
- 10. Summary
- 11. Appendix
1. Overview
CausalImpact Analysis estimates the causal effect of an intervention by comparing observed data against a counterfactual: what would have happened without the intervention. It builds that counterfactual with a Structural Time Series (STS) model, then fits the model with Gibbs Sampling, a Bayesian inference technique, to get posterior distributions over the model parameters.
2. Structural Time Series (STS) Model
The Structural Time Series (STS) model offers a robust framework for modeling time-series data by decomposing it into various components such as trend, seasonality, and regression effects.
2.1. State-Space Representation
The STS model is formulated within a state-space framework, comprising two primary equations: the State Transition Equation and the Observation Equation.
a. State Vector ()
The state vector encapsulates all latent (unobserved) components influencing the observed data at time :
Components:
- : Local Level capturing the underlying trend at time .
- : Seasonal Component at time for .
- : Regression Coefficients representing the influence of covariates at time .
b. State Transition Equation
The evolution of the state vector over time is governed by:
Where:
- : State Transition Matrix dictating how each state evolves.
- : State Noise Vector, modeled as:
Detailed Structure:
Assuming independent evolution of each component:
-
Local Level:
-
Seasonal Components:
-
Regression Coefficients:
Thus, the transition matrices are defined as:
Parameters:
- : Variance of the local level noise.
- : Variance of the -th seasonal component noise.
- : Covariance matrix for the regression coefficients.
- : Identity matrix of appropriate dimension.
2.2. Observation Equation
The Observation Equation links the latent state vector to the observed data:
Where:
- : Observation Matrix, defined as:
- : Covariate vector at time .
- : Variance of the observation noise.
3. Priors and Hyperparameters
In Bayesian analysis, priors represent initial beliefs about the model parameters before observing the data. Proper specification of priors is essential as they influence the posterior distributions.
3.1. Local Level Variance Prior
- : Shape parameter.
- : Scale parameter.
3.2. Observation Noise Variance Prior
- : Shape parameter.
- : Scale parameter.
3.3. Regression Weights Prior
Assuming a multivariate normal prior for regression coefficients :
- : Precision matrix, often derived from the design matrix :
- : Number of observations.
3.4. Initial State Priors
- : Initial observed value.
- : Variance of the initial level.
- : Variance of the initial seasonal component .
- : Covariance matrix for the initial regression coefficients.
4. Bayesian Inference via Gibbs Sampling
Gibbs Sampling is a Markov Chain Monte Carlo (MCMC) method used to sample from the joint posterior distribution of model parameters and latent states.
4.1. Posterior Distribution
The objective is to sample from the joint posterior distribution:
Where:
- : State vectors from time to .
- : Model parameters (e.g., ).
- : Observed data from time to .
Using Bayes’ theorem:
4.2. Gibbs Sampling Steps
Gibbs Sampling iteratively samples each parameter conditioned on the current values of all other parameters.
Step 1: Sample Local Level Variance ()
Where:
Step 2: Sample Observation Noise Variance ()
Where:
Step 3: Sample Regression Weights ()
Assuming time-invariant regression coefficients:
Where:
Step 4: Sample State Vectors ()
Utilize Forward-Backward Sampling or similar algorithms to sample the latent states given current parameter estimates and observed data.
4.3. Multiple MCMC Chains
To ensure convergence and robustness:
- Run Multiple Gibbs Chains ( chains): Each with different initializations.
- Combine Samples Across Chains: Aggregate after convergence to form the posterior distribution.
5. Posterior Predictive Inference
With posterior samples, derive predictions for the counterfactual scenario () and assess the impact of the intervention.
5.1. Posterior Means
For each time , the posterior mean prediction is:
In matrix form:
5.2. Credible Intervals
Compute the -credible intervals (e.g., 95%) for :
6. Causal Effect Estimation
Assess the intervention’s impact by comparing observed data with model predictions.
6.1. Point Effects
The immediate difference at time :
6.2. Cumulative Effects
Total impact from intervention start to time :
6.3. Summary Statistics
Over the post-intervention period :
-
Average Predicted Outcome:
-
Cumulative Predicted Outcome:
-
Absolute Effect:
-
Relative Effect:
-
P-value Calculation:
Where is the total number of posterior samples.
7. Matrix Operations and Linear Algebra
Efficient computation and representation of the STS model rely heavily on matrix operations.
7.1. State Transition Matrix ()
- Diagonal elements set to 1 for identity transitions.
- Off-diagonal elements are 0, except for potential seasonal dependencies.
7.2. Observation Matrix ()
- Incorporates the local level and seasonal components directly.
- Includes regression coefficients via .
7.3. Covariance Matrices ()
- Diagonal matrix with variances for each state component.
- represents the covariance matrix for regression weights.
7.4. Precision Matrix for Regression Weights ()
- Derived from the design matrix (covariates).
- Controls the prior variance of regression weights.
7.5. Likelihood Function
For the entire dataset, the likelihood is:
7.6. Posterior Distribution
Using Bayes’ theorem:
Where:
- : Likelihood.
- : Prior on states.
- : Priors on parameters.
8. Data Standardization and Scaling
Proper data preprocessing ensures that the model accurately captures patterns without being skewed by varying scales.
8.1. Standardizing Data
- : Mean of the pre-intervention data.
- : Standard deviation of the pre-intervention data.
8.2. Scaling Priors
-
Level Scale ():
-
Seasonal Drift Scales ():
9. Seasonal Effects Handling
Seasonality is a common feature in time-series data, representing periodic fluctuations.
9.1. Seasonal Components ()
- Number of Seasons (): Defines the periodicity (e.g., for monthly data with yearly seasonality).
- Steps per Season (): Granularity within each season (e.g., weekly steps within a yearly cycle).
9.2. Seasonal Drift ()
Allows seasonal trends to gradually change over time:
10. Summary
A CausalImpact implementation is a Bayesian STS model with these pieces:
- State-space model: the dynamics of latent states, local level, seasonal components, and regression coefficients, that drive the observed data.
- Priors: Inverse-Gamma priors for variances, Normal priors for regression weights and initial states, which bring in domain knowledge and regularize the fit.
- Gibbs sampling: iterative sampling from each parameter’s conditional posterior, converging to the joint posterior over parameters and latent states.
- Posterior predictive inference: posterior mean predictions and credible intervals for the counterfactual.
- Causal effect estimation: point and cumulative effects from comparing observed data against the counterfactual.
- Matrix operations: the linear algebra that makes state transitions, observations, and parameter updates tractable at scale.
Written out in full mathematical detail like this, the model is easier to extend, whether that means adding covariates, changing the seasonal structure, or swapping in a different sampler.
11. Appendix
Derivation of Sampling the Local Level Variance ()
This section provides a detailed mathematical derivation of the sampling step for the Local Level Variance () within the Gibbs Sampling procedure.
1. Model Setup
1.1. State Transition Equation
The evolution of the Local Level component is given by:
1.2. Prior for
An Inverse-Gamma prior is assumed:
2. Likelihood Function
Given the state transition, the likelihood of observed states is:
Expanding the Normal density:
3. Posterior Distribution
Applying Bayes’ theorem:
Substituting the likelihood and prior:
Combining like terms:
4. Identifying the Posterior Distribution
Recognizing the form of the Inverse-Gamma distribution:
We identify the posterior parameters:
Thus, the conditional posterior is:
Summary of the Sampling Step:
This conjugate relationship between the Normal likelihood and the Inverse-Gamma prior facilitates efficient Gibbs Sampling, enabling straightforward updates of in each iteration.
References:
- Harvey, A. C. (1990). Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press.
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
- Gelman, A., et al. (2013). Bayesian Data Analysis (3rd ed.). CRC Press.
If you are putting a model like this into production, the next steps below cover the data and observability layer, and the newsletter is where the production playbook for generative and statistical models ships first.
Next steps: scaling to production
If you take this into production, these are the pieces I would add first.
- Supabase Supabase is a hosted Postgres platform with authentication and storage built in. Postgres with pgvector for embeddings, so you do not run a separate vector store.
- Datadog Datadog aggregates metrics, logs, and traces for infrastructure monitoring. Traces and cost metrics across model calls, so latency and spend are visible per request.
- Vercel Vercel hosts frontend applications with a global edge network and CI/CD. Deploys the frontend and edge functions that sit in front of the model API.
Deploying generative AI models to production
Get the free playbook on shipping generative AI models to production.