PyCausalSim
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
- Score-based: GES (
"fges"is accepted as an alias for the same search) - Functional: LiNGAM for non-Gaussian data
- Continuous optimization: NOTEARS
- Hybrid: Combine methods for robustness
FCI, which allows for latent confounders, is not implemented yet.
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')
attr.fit(method='shapley') # Causal Shapley values
weights = attr.get_attribution()
# {'email': 0.25, 'display': 0.15, 'search': 0.35, 'social': 0.20, 'direct': 0.05}
optimal_budget = attr.optimize_budget(total_budget=100000)
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()
sensitivity.confounding_bounds() # Test unmeasured confounding
sensitivity.placebo_test() # Placebo tests
sensitivity.refute() # Multiple refutation methods
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
TemporalSCMunrolls 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.MechanismPriorrequires 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.StructuralInterventionadds, 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.Scenariois a declarative bundle of timed interventions, readable and editable by people who do not write Python.ClaimSetemits dated, checkable claims with probabilities and a named source, exports them to JSON, and scores them later with a Brier score.backtestscores the model against observed anchors and reports whether the stated intervals are calibrated.rolling_backtestdoes the same from many forecast origins and pools the result.empirical_pathresamples 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.windowaggregates 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
202611for November 2026, andc.stepandscm.stepsname 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_conversion',
constraints={'price': (10, 50)}
)
Use Cases
- Conversion Rate Optimization: Identify true drivers of conversion vs. correlated factors
- Marketing Attribution: Move beyond last-touch to understand true incremental value
- Product Feature Impact: Understand which features actually drive engagement
- Pricing Optimization: Understand causal price elasticity (not just correlation)
- Retention Analysis: Identify causal drivers of churn
- Policy Scenario Analysis: Compare interventions over a horizon, rank levers by causal effect, and publish claims that can be scored later
- 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_pathfor resampling whole historical episodes, with optional weightschoicepriors,Scenario.pathfor step-by-step lever values,RunResult.windowand window claimsrolling_backtestfor pooled multi-origin backtests- Monthly and other non-annual horizons, named with
c.stepandscm.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 intoTemporalSCM. 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
- GitHub: github.com/Bodhi8/pycausalsim
- Email: brian@vector1.ai
- Website: Vector1 AI
Metadata
Release files for pycausalsim 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pycausalsim-0.6.0.tar.gz | 111.0 kB | With provenance | Details for pycausalsim-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pycausalsim-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for pycausalsim-0.6.0-py3-none-any.whl |
Total release size: 224.1 kB
Release files / pycausalsim-0.6.0.tar.gz
| Download URL | pycausalsim-0.6.0.tar.gz |
|---|---|
| Size | 111.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a96ffd0a01b41645668bff13ffa7c691b6d56b0313795207a99b1ae1892d5023
|
|
BLAKE2b-256 checksum How to use checksums |
bd3e4d398afaac6fe43d97d26acf5bc8d78ecf6113a348523d7383df9163c5ae
|
| 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 12, 2026.
Transparency logRelease files / pycausalsim-0.6.0-py3-none-any.whl
| Download URL | pycausalsim-0.6.0-py3-none-any.whl |
|---|---|
| Size | 113.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c3e02a17c685b60f680c312879098f196146ff866978095fc9d26eb4269f13bd
|
|
BLAKE2b-256 checksum How to use checksums |
7a766749a30656ccc99060a1d12090b957e407cb7c5af6a92d85152f92518c3a
|
| 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 12, 2026.
Transparency logSecurity for pycausalsim 0.6.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.
Attestation for pycausalsim-0.6.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 12, 2026.
Transparency logA 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.