Skip to main content

PyCausalSim

PyCausalSim: data condensing into a causal graph that unrolls into simulated futures

License: Apache 2.0 Python 3.10+ tests Code style: black

PyCausalSim is a Python framework for causal discovery and inference through simulation. It answers two kinds of question with the same machinery.

Backward: what caused the outcome already in your data? Discover the graph, estimate interventions, validate against unmeasured confounding.

Forward: what happens under a policy nobody has tried yet? Specify a graph, unroll it over a horizon, and simulate scenarios far outside observed support, with the extrapolation declared rather than silent.

Most causal libraries do only the first. The second needs time, declared mechanism, interventions on structure rather than value, and a way to score predictions after the fact. That is pycausalsim.futures.

Why PyCausalSim?

Traditional analytics tell you what happened. PyCausalSim tells you why it happened and what would happen if you changed something.

from pycausalsim import CausalSimulator

# Your conversion rate increased after reducing load time
# But did load time CAUSE the increase? Or was it just correlation?

simulator = CausalSimulator(data, target='conversion_rate')
simulator.discover_graph()  # Learn causal structure

# Simulate: What if we reduce load time to 2 seconds?
effect = simulator.simulate_intervention('page_load_time', 2.0)
print(f"Expected conversion lift: {effect.point_estimate:.2%}")
print(f"95% CI: [{effect.ci_lower:.2%}, {effect.ci_upper:.2%}]")

# Rank all causal drivers
drivers = simulator.rank_drivers()
# Returns: [(page_load_time, 0.15), (price, 0.12), (design, 0.03), ...]

Key Features

1. Simulation-Based Causal Discovery

  • Generate synthetic "what-if" scenarios
  • Test interventions before deploying them
  • Understand non-linear and interaction effects

2. Multiple Discovery Methods

  • Constraint-based: PC (PC-stable, Fisher-z tests)
  • Score-based: GES with the BIC score ("fges" is accepted as an alias for the same search)
  • Functional: DirectLiNGAM, for linear models with non-Gaussian noise
  • Continuous optimization: linear NOTEARS
  • Hybrid: the GES graph without the edges PC's independence tests reject

PC, GES and hybrid return an equivalence class: an edge whose direction the data cannot determine is listed in both directions instead of being guessed. What you know about ordering settles more of them:

from pycausalsim.discovery import CausalDiscovery, undirected_edges

graph = CausalDiscovery().discover(
    data, method="ges",
    tiers={"age": 0, "dose": 1, "recovery": 2},   # nothing causes an earlier tier
)
undirected_edges(graph)   # the edges still undetermined

CausalSimulator.discover_graph() passes the declared confounders and target as this ordering, and warns about any edge it then has to orient by assumption.

FCI, which allows for latent confounders, is not implemented yet.

Graded against known answers

benchmarks/known_answers.py simulates data from graphs and channel effects that are known in advance and grades every method against them. It uses only the public API, so any release can be run through it. On 12 random five-node graphs, 0.7.0 recovers the exact equivalence class 10 times with PC, 11 with GES and 11 with hybrid, against 1, 2 and 0 for 0.6.0. Full results, including attribution, are in benchmarks/results/known_answers.md.

3. Structural Causal Models (SCM)

from pycausalsim.models import StructuralCausalModel

scm = StructuralCausalModel()
scm.fit(data)

# Generate counterfactuals
counterfactuals = scm.counterfactual(
    intervention={'price': 0.9 * current_price},
    evidence={'traffic_source': 'paid'}
)

4. Marketing Attribution

from pycausalsim import MarketingAttribution

attr = MarketingAttribution(
    data,
    conversion_col='converted',
    touchpoint_cols=['email', 'display', 'search', 'social'],
    covariate_cols=['prior_purchases'],   # what drives both exposure and conversion
)
attr.fit(method='shapley')

attr.get_attribution()            # shares of the conversions marketing added
attr.get_contributions()          # signed, in conversion-rate points
attr.get_baseline()               # conversion rate with no marketing
attr.incremental_effects_table()  # effect of an exposure, with confidence intervals

The incremental methods (shapley, logistic, linear, uplift) model conversion and ask what would have happened without each channel. Conversions that would have happened anyway are credited to no one, a channel with no effect earns nothing, and a channel that lowers conversion shows a negative contribution. They assume the drivers of both exposure and conversion are measured and passed as covariate_cols; only an experiment removes that assumption.

markov, first_touch and last_touch describe where converting journeys went and are not causal. They use the order in path_col (for example "search > email").

optimize_budget(total_budget) splits a budget in proportion to attribution per unit cost, within any limits you set. It is a rule of thumb: exposure flags say nothing about diminishing returns.

5. A/B Test Analysis

from pycausalsim import ExperimentAnalysis

exp = ExperimentAnalysis(data, treatment='new_feature', outcome='engagement')
effect = exp.estimate_effect(method='dr')  # Doubly robust estimator

# Check for heterogeneous effects
het = exp.analyze_heterogeneity(covariates=['user_tenure', 'activity_level'])

6. Uplift Modeling

from pycausalsim.uplift import UpliftModeler

uplift = UpliftModeler(data, treatment='campaign', outcome='conversion')
uplift.fit()

# Segment users: persuadables, sure_things, lost_causes, sleeping_dogs
segments = uplift.segment_by_effect()

7. Built-in Validation

# Sensitivity analysis
sensitivity = simulator.validate('price')
print(sensitivity.summary())
sensitivity.robustness_value     # confounding needed to explain the effect away (0 fragile, 1 robust)
sensitivity.confounding_bounds   # range of the effect under a hidden confounder of given strength
sensitivity.placebo_results      # a shuffled treatment should show no significant effect
sensitivity.refutation_results   # random common cause, placebo treatment, data subsets

8. Futures and Scenario Simulation

Causal discovery is retrodictive. It learns a graph from existing data and estimates interventions within that data's support. Forecasting inverts both halves, and pycausalsim.futures supplies what the inversion needs.

from pycausalsim.futures import TemporalSCM, Scenario, SI, compare, rank_drivers

scm = TemporalSCM(horizon=range(2026, 2042), draws=4000, seed=7)

scm.parameter("attrition", "normal", loc=0.045, scale=0.008)
scm.lever("apprenticeship", default=0.05)

# lags make the unrolled graph acyclic, so identification carries over
scm.state("senior_stock",
          lambda c: (c.lag("senior_stock", 1) * (1 - c.p.attrition)
                     + c.p.conversion * c.lag("junior", 10)),
          parents=["junior:lag(10)", "senior_stock:lag(1)"],
          init=lambda p: p.conversion / p.attrition * 100.0)

# extrapolation is declared, never silent
scm.mechanism("automation ~ token_price", form="logistic",
              valid_range=(0.0005, 100.0), outside="flag")

# interventions on structure, not only on value
scm.structural_rule(when="automation > 0.55",
                    apply=SI.remove_edge("junior", "senior_stock"),
                    note="training stops being a free byproduct")

funded = Scenario("Funded apprenticeship")
funded.at(2027).set("apprenticeship", ramp_to=0.72, over=4)

cmp = compare(scm, [Scenario("Drift"), funded], target="wellbeing")
print(cmp.table())
rank_drivers(scm, Scenario("Drift"), target="wellbeing")

What it adds

  • TemporalSCM unrolls a graph over a horizon. Parents are written "name" or "name:lag(k)". State variables carry memory. A cycle at lag zero is an error, because feedback in a dynamic system is feedback across time.
  • MechanismPrior requires a declared functional form and validity range on any edge that will be driven outside observed data. Every excursion is recorded, so results report which conclusions rest on data and which rest on assumed mechanism.
  • StructuralIntervention adds, removes and rewires edges, and rules fire per draw. do() sets a value; it does not delete an edge, and the most consequential futures questions are structural.
  • Scenario is a declarative bundle of timed interventions, readable and editable by people who do not write Python.
  • ClaimSet emits dated, checkable claims with probabilities and a named source, exports them to JSON, and scores them later with a Brier score.
  • backtest scores the model against observed anchors and reports whether the stated intervals are calibrated. rolling_backtest does the same from many forecast origins and pools the result.
  • empirical_path resamples whole episodes from history, such as past winters, so the correlation across steps survives. Optional weights let outside probabilities, a seasonal outlook for example, steer the draws.
  • RunResult.window aggregates a node over a span per draw, and claims can test it: "the November to March average settles below the strip."
  • Steps need not be years. Any sortable integer label works, such as 202611 for November 2026, and c.step and scm.steps name them that way.

One habit matters more than any feature: take every quantity for one analysis from one run. Each scm.run() draws fresh parameters, so mixing months from separate runs breaks the correlation inside a draw and makes ranges too narrow. compare and RunResult.window keep you on the right side of this.

Full documentation: pycausalsim/futures/README.md. Worked examples:

  • examples/henry_hub_winter.py: Henry Hub natural gas for winter 2026-27, monthly, anchored on the NYMEX futures curve, with storage surprises as the causal channel, whole-winter weather resampling, LNG and freeze-off scenarios, a hedge-to-budget decision and a leave-one-winter-out backtest on bundled EIA data.
  • examples/postlabor_futures.py: a fifteen-year post-labor transition model with four policy levers and a ten-year apprenticeship lag.

9. Grading marketing mix models (0.5)

from pycausalsim.futures import marketing_worlds, worlds_from_graph, lift_test, leaderboard
from pycausalsim.futures import papilon_estimator, ols_estimator

worlds = marketing_worlds(60, hard=True, seed=7)             # 60 brands, each with an answer key
worlds = marketing_worlds(60, response="s_curve", competitor=True)   # harder: S-curves, competitor shocks
worlds = worlds_from_graph(graph, 60, hide=["launch"])       # your own structure, a driver withheld

test = lift_test(worlds, 0, "paid_search", weeks=8)          # measured return, standard error, truth
leaderboard({"papilon": papilon_estimator(), "ols": ols_estimator()}, worlds, ids=range(12))

An estimator is any function (df, info) -> {"roas": {channel: (estimate, p05, p95)}, "plan": spend}, so a model from any library can be scored on the same brands: interval coverage, error and bias on return, share of the best possible budget gain captured, and share of brands where its plan lost money. worlds_from_graph takes a papilon.MarketingGraph, so the worlds a model is graded on share the structure the analyst declared for the real brand.

The open leaderboard in the Papilon repository is built on these functions and accepts entries for any model.

Installation

pip install pycausalsim

Or the latest from GitHub:

pip install git+https://github.com/Bodhi8/pycausalsim.git

Or clone and install locally:

git clone https://github.com/Bodhi8/pycausalsim.git
cd pycausalsim
pip install -e ".[dev]"

Quick Start

import pandas as pd
from pycausalsim import CausalSimulator

# Load your data
data = pd.read_csv('conversion_data.csv')

# Initialize simulator
simulator = CausalSimulator(
    data=data,
    target='conversion_rate',
    treatment_vars=['page_load_time', 'price', 'design_variant'],
    confounders=['traffic_source', 'device_type', 'time_of_day']
)

# Step 1: Discover causal structure
simulator.discover_graph(method='ges')
simulator.plot_graph()  # Visualize learned causal relationships

# Step 2: Simulate interventions
load_time_effect = simulator.simulate_intervention(
    variable='page_load_time',
    value=2.0,  # seconds
    n_simulations=1000
)
print(load_time_effect.summary())

# Step 3: Rank all causal drivers
drivers = simulator.rank_drivers()
for var, effect in drivers:
    print(f"{var}: {effect:.3f}")

# Step 4: Find optimal policy
optimal = simulator.optimize_policy(
    objective='maximize',
    constraints={'price': (10, 50)}
)

Use Cases

  1. Conversion Rate Optimization: Identify true drivers of conversion vs. correlated factors
  2. Marketing Attribution: Move beyond last-touch to understand true incremental value
  3. Product Feature Impact: Understand which features actually drive engagement
  4. Pricing Optimization: Understand causal price elasticity (not just correlation)
  5. Retention Analysis: Identify causal drivers of churn
  6. Policy Scenario Analysis: Compare interventions over a horizon, rank levers by causal effect, and publish claims that can be scored later
  7. Strategic Forecasting: Simulate futures outside observed support with the extrapolation declared rather than hidden

Why Simulation for Causality?

The Problem with Correlation

# Traditional approach - WRONG!
from sklearn.ensemble import RandomForestRegressor

rf = RandomForestRegressor()
rf.fit(X, y)
feature_importance = rf.feature_importances_

# Feature importance != causal importance
# Tells you what predicts, not what causes
# Fails with confounding, selection bias, reverse causation

The PyCausalSim Approach

from pycausalsim import CausalSimulator

sim = CausalSimulator(data, target='conversion')
sim.discover_graph()  # Learn causal structure

# Explicitly models confounding
# Distinguishes correlation from causation
# Validates assumptions
# Provides counterfactual predictions

drivers = sim.rank_drivers()  # TRUE causal importance

Project Structure

pycausalsim/
├── pycausalsim/
│   ├── __init__.py         # Package exports
│   ├── simulator.py        # Main CausalSimulator class
│   ├── attribution.py      # Marketing Attribution
│   ├── experiment.py       # A/B Test Analysis
│   ├── results.py          # Result classes
│   ├── models/             # Structural Causal Models
│   ├── discovery/          # Causal discovery algorithms
│   ├── uplift/             # Uplift modeling
│   ├── agents/             # Agent-based simulation
│   ├── validation/         # Sensitivity analysis
│   ├── adapters/           # DoWhy/EconML integration
│   ├── futures/            # Temporal SCMs and scenario forecasting
│   │   ├── temporal.py     #   TemporalSCM, Context, RunResult
│   │   ├── mechanism.py    #   MechanismPrior, SupportReport
│   │   ├── structural.py   #   StructuralIntervention, StructuralRule
│   │   ├── scenario.py     #   Scenario language
│   │   ├── results.py      #   Comparison, rank_drivers, ClaimSet
│   │   └── backtest.py     #   Retrodiction scoring
│   ├── utils/              # Utilities
│   └── visualization/      # Plotting
├── tests/                  # Test suite
├── examples/               # Example scripts
├── pyproject.toml          # Package configuration
└── README.md

Roadmap

Shipped in 0.3

  • empirical_path for resampling whole historical episodes, with optional weights
  • choice priors, Scenario.path for step-by-step lever values, RunResult.window and window claims
  • rolling_backtest for pooled multi-origin backtests
  • Monthly and other non-annual horizons, named with c.step and scm.steps
  • A Henry Hub natural gas example with bundled EIA data and a regression test
  • NumPy 2 compatibility for uplift metrics, Python 3.10+, a single version source

Shipped in 0.2

  • Temporal SCMs with lags, state variables and per-draw structural rules
  • Declared mechanism priors with out-of-support reporting
  • Scenario language, paired comparison, driver ranking
  • Falsifiable claim sets with Brier scoring
  • Backtesting against observed anchors

Next

  • Agent layer for futures. agents/ exists but does not yet plug into TemporalSCM. Aggregate models report population means, which cannot distinguish two people with identical material conditions and non-comparable lives. Heterogeneous institution access, geography and cohort would recover that.
  • Geography. No spatial dimension today, which is the largest omission in the post-labor example. Regional bottleneck prices and migration between regions are the first two edges to add.
  • Structural uncertainty. The Monte Carlo covers coefficients, not structure. Sampling over a distribution of graphs is the honest version and is considerably harder.
  • Scenario DSL in YAML, so scenarios can be authored and reviewed without touching Python at all.
  • A public claim ledger. Exported claim sets are only useful if someone scores them. A registry of dated predictions with resolution sources would give forecasting the accountability mechanism it has never had.

Dependencies

Core:

  • numpy >= 1.20.0
  • pandas >= 1.3.0
  • scipy >= 1.7.0
  • scikit-learn >= 1.0.0

Optional:

  • matplotlib, networkx, seaborn (visualization)
  • dowhy, econml (integrations)

pycausalsim.futures needs numpy only. The Henry Hub example also uses pandas. Python 3.10 or later.

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

git clone https://github.com/Bodhi8/pycausalsim.git
cd pycausalsim
pip install -e ".[dev]"
pytest tests/

License

Apache License 2.0, free for commercial use. See LICENSE and NOTICE. Versions 0.4.0 and earlier were released under the MIT License and remain available under it.

PyCausalSim, Papilon and Vector1 are trademarks of Brian Curry. The license covers the code, not the names: see TRADEMARKS.md.

Acknowledgments

PyCausalSim builds on research from:

  • Pearl, J. (2009). Causality: Models, Reasoning and Inference
  • Peters, J., Janzing, D., & Schölkopf, B. (2017). Elements of Causal Inference
  • Imbens, G. W., & Rubin, D. B. (2015). Causal Inference for Statistics, Social, and Biomedical Sciences

And integrates with:

  • DoWhy - Microsoft's causal inference library
  • EconML - Heterogeneous treatment effects
  • CausalML - Uber's uplift modeling library

Citation

@software{pycausalsim2025,
  title = {PyCausalSim: Causal Discovery Through Simulation},
  author = {Brian Curry},
  year = {2025},
  url = {https://github.com/Bodhi8/pycausalsim}
}

Contact

Metadata

Release files for pycausalsim 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pycausalsim 0.7.0
File Size Uploaded Provenance Actions
pycausalsim-0.7.0.tar.gz 145.6 kB With provenance Details for pycausalsim-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pycausalsim 0.7.0
File Interpreter ABI Platform Actions
pycausalsim-0.7.0-py3-none-any.whl Python 3 none any Details for pycausalsim-0.7.0-py3-none-any.whl

Total release size: 278.4 kB

Release files / pycausalsim-0.7.0.tar.gz

Download URL pycausalsim-0.7.0.tar.gz
Size 145.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e3e60dac1a0a3b381ea547b4643d0cf4542e45a1069ab81bbd3c4eec014f9744
BLAKE2b-256 checksum
How to use checksums
bdfb182b7718e3b27ece082d73c8c22eae06707f8095e8313cd387709b3f2ceb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / pycausalsim-0.7.0-py3-none-any.whl

Download URL pycausalsim-0.7.0-py3-none-any.whl
Size 132.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d89c1eba8336a2d9e18c270ad7583a26f6db268bff148787a351e00629d62467
BLAKE2b-256 checksum
How to use checksums
6c99fed0511dbdd8ee022d58f6c3602d2adafb89f64eabaa38a5f199a5c8e764
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for pycausalsim 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pycausalsim-0.7.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page