Built in Kansas City: Causal Discovery You Can Check With PyCausalSim
PyCausalSim is an open-source Python library that finds the causal structure in your data, simulates what happens when you change something, and splits marketing credit by what each channel really adds. Graded on data with known answers, it recovers the right causal graph in 10 to 12 of 12 cases.

What PyCausalSim does
Most analytics answers "what predicts sales?" A budget or product decision needs a different answer: what happens to sales if we change this? PyCausalSim is an open-source Python library I build and maintain at Vector 1 Research in Kansas City for that second question. It does four jobs.
It runs causal discovery: given a table of observational data, it learns which variables drive which, and it tells you which directions the data can't settle. It simulates interventions: set page speed, price or spend to a new value and it estimates the effect on your outcome, with a confidence interval. It splits marketing credit by what each channel adds, not by who happened to see it. And it checks its own answers with sensitivity analysis, so you know how strong a hidden confounder would have to be to change the conclusion.
Version 0.7.0, released today under the Apache 2.0 license, comes with a benchmark that grades every one of those methods on simulated data where the right answer is known in advance. This piece walks through a worked example, then the benchmark, then how to use the library on your own data. Everything here runs with pip install pycausalsim.
A worked example: what a faster site is worth
A retailer wants to know what speeding up its pages would do for conversions. The trap is in who gets the slow pages. Paid traffic lands on heavier pages and also converts better, so in the raw data slow pages and high conversion travel together, and a simple regression understates the value of speed.
The simulation below has 800 sessions and a known answer: every extra second of load time costs 3 points of conversion. PyCausalSim is told the outcome, the levers and the variables that might confound them, and works out the rest.
"""page_speed.py: what a faster site is worth, with PyCausalSim (Brian Curry | Vector 1 Research)."""
import numpy as np
import pandas as pd
from pycausalsim import CausalSimulator # 0.7.0
# 800 sessions. Paid traffic gets slower pages AND converts better, which hides the effect of speed.
rng = np.random.default_rng(42)
n = 800
traffic = rng.choice([0, 1], n, p=[0.6, 0.4]) # 1 = paid traffic
load = 3.0 + 0.5 * traffic + rng.exponential(0.5, n) # page load time, seconds
price = 20 + rng.normal(0, 5, n)
device = rng.choice([0, 1, 2], n)
conv = 15 - 3.0 * load + 2.0 * traffic - 0.5 * (price - 20) + rng.normal(0, 2, n) # true effect: -3 per second
df = pd.DataFrame({"traffic_source": traffic, "page_load_time": load, "price": price,
"device_type": device, "conversion_rate": conv})
sim = CausalSimulator(df, target="conversion_rate", treatment_vars=["page_load_time", "price"],
confounders=["traffic_source", "device_type"], random_state=0)
sim.discover_graph(method="pc") # learn which variables drive which
print({k: v for k, v in sim.graph.items() if v}) # {child: [parents]}
effect = sim.simulate_intervention("page_load_time", 3.2, n_simulations=300, method="backdoor") # every page in 3.2 s
print(round(effect.point_estimate, 2), round(effect.ci_lower, 2), round(effect.ci_upper, 2))
shift = 3.2 - df.page_load_time.mean() # about half a second faster than today
naive = np.polyfit(df.page_load_time, df.conversion_rate, 1)[0] * shift
print("naive", round(naive, 2), "true", round(-3.0 * shift, 2))
report = sim.validate("page_load_time", n_simulations=300) # how strong would a hidden confounder have to be?
print(round(report.robustness_value, 2), report.placebo_results)
{'page_load_time': ['traffic_source'], 'conversion_rate': ['traffic_source', 'page_load_time', 'price']}
1.53 1.23 1.85
naive 1.04 true 1.5
0.37 {'placebo_treatment': 0.9357385146277708, 'subset_stability': 1.0}
Read it from the top. The learned graph is exactly the one that generated the data: traffic source drives both load time and conversion, price drives conversion, and device type drives nothing, so it is left out. With that structure PyCausalSim knows to adjust for traffic source and for nothing else.
Bringing every page down to 3.2 seconds, about half a second faster than today's average of 3.7, would add 1.53 points of conversion, with a 95% interval of 1.23 to 1.85. The true answer is 1.50. The simple regression says 1.04, about a third too low, because it credits part of the speed effect to the paid traffic that happens to get slow pages.
The last line is the check. The robustness value comes from the sensitivity analysis of Cinelli and Hazlett (2020), and it measures how strongly an unmeasured confounder would have to be tied to both the treatment and the outcome to change the conclusion. Here, a hidden variable would have to explain 37% of the leftover variation in both load time and conversion to erase the effect. The placebo test, which swaps the real treatment for random noise, finds no effect, as it should.
The PyCausalSim demo runs this kind of example in your browser, with sliders for the true effect of page speed and the load time you aim for.
Causal discovery you can check
Causal discovery is the step most tools treat as a black box, so it is where checking matters most. PyCausalSim ships five methods: PC (constraint-based, built on conditional independence tests), GES (score-based), DirectLiNGAM and NOTEARS (which assume linear effects and can recover every arrow under those assumptions), and a hybrid of PC and GES.
From observational data alone, some directions can't be recovered by any method. A chain, a causes b and b causes c, produces exactly the same independencies as a fork, b causing both a and c. A collider, a and c both causing b, leaves a different signature, and that one does fix the direction of both arrows. The set of graphs the data can't tell apart is called an equivalence class. PC, GES and the hybrid return that class and say so: an edge whose direction the data can't settle comes back in both directions, and undirected_edges() lists those edges for you.
You can then settle them with what you already know. Naming the outcome, or passing tiers ({variable: tier}, where nothing in a later tier can cause something in an earlier one), orients edges the data alone can't.
"""discovery_check.py: a chain and a diamond with known structure (Brian Curry | Vector 1 Research)."""
import numpy as np
import pandas as pd
from pycausalsim.discovery import CausalDiscovery, undirected_edges # 0.7.0
rng = np.random.default_rng(0)
e = lambda: rng.normal(0, 1, 3000)
a = e(); b = 0.8 * a + e(); c = 0.8 * b + e() # chain: a -> b -> c
chain = pd.DataFrame({"a": a, "b": b, "c": c})
a = e(); b = 0.8 * a + e(); c = 0.8 * a + e(); d = 0.7 * b + 0.7 * c + e()
diamond = pd.DataFrame({"a": a, "b": b, "c": c, "d": d}) # a -> b -> d, a -> c -> d
for name, df in [("chain", chain), ("diamond", diamond)]:
g = CausalDiscovery(random_state=0).discover(df, method="pc") # {child: [parents]}
print(name, g, "undetermined:", undirected_edges(g))
g = CausalDiscovery(random_state=0).discover(chain, method="pc", target="c") # c is the outcome
print("chain, target c:", g, "undetermined:", undirected_edges(g))
chain {'a': ['b'], 'b': ['a', 'c'], 'c': ['b']} undetermined: [('a', 'b'), ('b', 'c')]
diamond {'a': ['b', 'c'], 'b': ['a'], 'c': ['a'], 'd': ['b', 'c']} undetermined: [('a', 'b'), ('a', 'c')]
chain, target c: {'a': ['b'], 'b': ['a'], 'c': ['b']} undetermined: [('a', 'b')]
The chain comes back with both edges open, which is the right answer. The diamond comes back with its collider into d oriented and the two edges out of a left open, which is also right. Telling PyCausalSim that c is the outcome settles b→c, because nothing can be caused by the outcome, and leaves a-b open because nothing settles it.
To grade the methods beyond hand-picked cases, the benchmark draws 12 random graphs on five variables (each edge present with probability 0.4, coefficients between 0.7 and 1.2 on unit-variance noise, 5,000 observations each) and counts how often each method recovers exactly what the data can identify.
| Method | Graded against | Exactly right, of 12 |
|---|---|---|
| PC | equivalence class, Gaussian data | 10 |
| GES | equivalence class, Gaussian data | 11 |
| Hybrid | equivalence class, Gaussian data | 11 |
| DirectLiNGAM | full graph, non-Gaussian data | 12 |
| NOTEARS | full graph, non-Gaussian data | 11 |
The misses are small and reported, not hidden: across the 12 graphs PC points 3 arrows the wrong way, and PC, GES, the hybrid and NOTEARS each miss one true edge. That is the honest error of a statistical test at 5,000 observations. PC is PC-stable (Colombo and Maathuis, 2014), so the result doesn't depend on the order of your columns; GES is greedy equivalence search as Chickering defined it in 2002; DirectLiNGAM follows Shimizu and colleagues (2011) and warns when your data look Gaussian, where it can't identify direction; NOTEARS is the method of Zheng and colleagues (2018) and always returns an acyclic graph.
Marketing attribution that credits what each channel adds
Attribution has the same trap as the page speed example. Channels are shown to people who were going to convert anyway, or to people who also saw a channel that works, and a method that compares the people who saw a channel with the people who didn't hands out credit for the overlap.
The benchmark builds that trap on purpose. In a test of 40,000 simulated users, four channels have effects chosen in advance: email adds 10 points to the chance of converting, search adds 4, display adds nothing and social takes 3 away. Display is shown to 65% of people who saw search and 15% of those who didn't, so display-exposed users convert at 11.4% against 8.7% for everyone else, entirely because of search. Five in every 100 users convert with no marketing at all.
PyCausalSim fits a model of conversion on exposure first, then splits credit with Shapley values computed on that model:
Here v(S) is the model's average conversion rate if every user kept their real exposure to the channels in S and saw none of the others. The empty set gives the baseline, the conversions that would have happened anyway, and no channel is credited for those. With up to eight channels the sum is exact. Contributions are signed, so a channel that hurts shows up as negative, gets a zero share and triggers a warning.
| search | display | social | ||
|---|---|---|---|---|
| True share of credit | 74% | 26% | 0% | 0% |
| PyCausalSim, Shapley | 75% | 22% | 3% | 0% |
| PyCausalSim, logistic | 72% | 24% | 3% | 0% |
| PyCausalSim, linear | 73% | 24% | 3% | 0% |
| PyCausalSim, uplift | 70% | 27% | 3% | 0% |
Display's 3% is its estimated contribution, 0.14 conversions per 100 users, which is sampling noise around a true zero. Here is the Shapley run as code; it takes about a second.
"""attribution_check.py: four channels with known effects, graded (Brian Curry | Vector 1 Research)."""
import numpy as np
import pandas as pd
from pycausalsim import MarketingAttribution # 0.7.0
rng = np.random.default_rng(0)
n = 40_000
search = (rng.random(n) < 0.35).astype(int)
display = (rng.random(n) < 0.15 + 0.5 * search).astype(int) # shown mostly to search users
email = (rng.random(n) < 0.40).astype(int)
social = (rng.random(n) < 0.30).astype(int)
p = 0.05 + 0.10 * email + 0.04 * search + 0.00 * display - 0.03 * social # the answer key
df = pd.DataFrame({"email": email, "search": search, "display": display, "social": social,
"converted": (rng.random(n) < p).astype(int)})
attr = MarketingAttribution(df, "converted", ["email", "search", "display", "social"], random_state=0)
attr.fit("shapley") # warns that social has a negative contribution
print({k: round(v, 3) for k, v in attr.get_attribution().items()}) # shares of credit
print({k: round(v, 4) for k, v in attr.get_contributions().items()}) # conversions added per user
print(round(attr.get_baseline(), 4)) # conversions no channel earned
{'email': 0.755, 'search': 0.219, 'display': 0.027, 'social': 0.0}
{'email': 0.0397, 'search': 0.0115, 'display': 0.0014, 'social': -0.0073}
0.0504
The true contributions, effect times reach, are 0.0400 for email, 0.0137 for search, zero for display and -0.0090 for social, and the true baseline is 0.05.
Using PyCausalSim on your own data
- Install it with
pip install pycausalsim. It needs NumPy, pandas, SciPy and scikit-learn. - Build one table, one row per unit (a session, a store-week, a customer), with your outcome, the levers you could change, and anything that might drive both.
- Create a
CausalSimulatorwith the target, the treatments and the confounders you know about. Those declarations become ordering knowledge for discovery, and the simulator warns, naming the edges, whenever it orients one by assumption rather than from the data. - Run
discover_graph()and readundirected_edges()before trusting any arrow. Addtierswhere you know the order of events. - Run
simulate_intervention()for the change you are considering. Keep the new value inside the range your data covers; the library warns when it isn't, because no model can see beyond the data. - Run
validate()and read the robustness value before you present the number. - For marketing, use
MarketingAttribution, and passcovariate_colsfor anything that drives both exposure and conversion, such as purchase intent.
Check it yourself
The benchmark behind every number above is benchmarks/known_answers.py in the PyCausalSim repository. It uses only the public API, so it grades whichever release you have installed, and it runs in about 20 seconds.
pip install pycausalsim==0.7.0
git clone https://github.com/Bodhi8/pycausalsim && cd pycausalsim/benchmarks
python known_answers.py run --out mine.json
python known_answers.py report mine.json
Its data generators are in the open, so anyone can add a harder graph and see what breaks.
Where it breaks
The benchmark is kinder than real data in ways that matter.
Every graph has no hidden confounders. PC and GES assume every common cause is measured, and when one isn't they can return a confident edge that doesn't exist. That is what validate() is for, and FCI, which allows for latent confounders, is not implemented in PyCausalSim yet.
Effects are linear and strong. Every coefficient is between 0.7 and 1.2 against noise with a standard deviation of 1, with thousands of observations. Weak effects, small samples and nonlinear relationships make independence tests miss edges.
The attribution test uses a model of conversion that is additive in exposure, which is what the fitted model assumes. Real channels interact; interactions=True adds pairwise terms.
I wrote both the tests and the library. That is the reason the benchmark only touches the public API and publishes its generators: a check you can rerun is worth more than my word for it.
Where to go next
PyCausalSim is built at Vector 1 Research in Kansas City, alongside Papilon, the Bayesian marketing mix model that PyCausalSim grades in Marketing Mix Modeling You Can Check. The PyCausalSim demo runs the page speed example in your browser, and more causal inference methods, demos and code are on the causal inference practice page.
Sources
- Cinelli and Hazlett, Making Sense of Sensitivity: Extending Omitted Variable Bias, Journal of the Royal Statistical Society Series B, 2020
- Colombo and Maathuis, Order-Independent Constraint-Based Causal Structure Learning, Journal of Machine Learning Research, 2014
- Chickering, Optimal Structure Identification With Greedy Search, Journal of Machine Learning Research, 2002
- Shimizu, Inazumi, Sogawa, Hyvärinen, Kawahara, Washio, Hoyer and Bollen, DirectLiNGAM: A Direct Method for Learning a Linear Non-Gaussian Structural Equation Model, Journal of Machine Learning Research, 2011
- Zheng, Aragam, Ravikumar and Xing, DAGs with NO TEARS: Continuous Optimization for Structure Learning, NeurIPS 2018
- PyCausalSim, github.com/Bodhi8/pycausalsim, version 0.7.0, with the benchmark in
benchmarks/known_answers.py


