Correlation Understates It: A Causal Inference Python Example on Page Speed With PyCausalSim
On 200,000 simulated sessions where each extra second of load time costs 0.98 points of conversion, the raw correlation finds 0.35, about a third, because paid traffic gets slower pages and converts better. Adjusting for traffic source with PyCausalSim recovers 0.97; adding pages viewed as a control cuts the answer to 0.48. The code, the bias formula and the dollar gap.

This is a causal inference Python example with a known answer. I simulated 200,000 sessions on an online store where every extra second of page load time costs 0.98 points of conversion, then asked the data what speed is worth. The raw correlation says 0.35 points per second, about a third of the truth. Adjusting for traffic source with PyCausalSim, the open-source library I maintain at Vector 1 Research in Kansas City, recovers 0.97. Adding pages viewed as a control, which feels like the careful thing to do, cuts the answer to 0.48.
All three numbers come from the same table of sessions. The difference is which variables you hold fixed, and the data alone won't tell you which choice is right. The time order of a session does.
Why the correlation understates the effect of page speed
Paid traffic is the trap. Campaign landing pages carry heavier scripts, video and tag managers, so in the simulation paid sessions load in 3.60 seconds on average against 3.00 for organic. Paid visitors also arrive with intent and convert at 3.42% against 2.08%. Slow pages and high conversion travel together for a reason that has nothing to do with speed, and a regression of conversion on load time credits part of the speed penalty to the visitors who happen to get slow pages.
Pages viewed is the second trap. A slow first page means fewer pages viewed, and fewer pages viewed means fewer purchases. That path is part of the effect of speed. Hold pages viewed fixed and you compare a slow session and a fast session that browsed the same amount, which removes the share of the speed penalty that works through browsing.
The Nov 18 PyCausalSim release article used a small page speed example to show the library recover one effect. This piece is about the choices around it: what the correlation misses as the confounding grows, why a reasonable-looking control makes it worse, and where PyCausalSim catches that mistake and where it trusts you.
The causal inference Python example, start to finish
The simulation draws traffic source first, then load time, then pages viewed, then a purchase, which is the order these happen in a real session. The known answer comes from rerunning the same 200,000 sessions with every page half a second faster and counting the extra purchases.
"""page_speed_causal.py: the real effect of page speed on conversion, with PyCausalSim.
Brian Curry | Vector 1 Research, Kansas City. Runs with pycausalsim 0.7.0."""
import warnings
import numpy as np
import pandas as pd
from pycausalsim import CausalSimulator
from pycausalsim.discovery import CausalDiscovery
def conv_prob(load, paid, noise_pages):
pages = 5.0 - 0.8 * load + 0.8 * paid + noise_pages # pages viewed: a mediator
p = 0.02 + 0.006 * pages - 0.005 * load + 0.015 * paid # conversion probability
return pages, np.clip(p, 0.002, 1)
def simulate(n=200_000, gap=0.6, seed=7):
"""Sessions for one retailer. Paid traffic lands on heavier pages (gap seconds slower) and converts better."""
rng = np.random.default_rng(seed)
paid = rng.binomial(1, 0.4, n)
load = 1.8 + gap * paid + rng.gamma(4, 0.3, n) # page load time, seconds
noise = rng.normal(0, 0.7, n)
pages, p = conv_prob(load, paid, noise)
conv = rng.binomial(1, p)
df = pd.DataFrame({"traffic_source": paid, "page_load_time": load,
"pages_viewed": pages, "converted": conv})
# The known answer: rerun the same sessions with every page 0.5 s faster, do(load = load - 0.5).
_, p_fast = conv_prob(load - 0.5, paid, noise)
truth = 100 * (p_fast - p).mean() # points gained from 0.5 s
return df, truth
def ols_slope(df, controls=()):
X = np.column_stack([np.ones(len(df)), df.page_load_time] + [df[c] for c in controls])
return 100 * np.linalg.lstsq(X, df.converted.to_numpy(float), rcond=None)[0][1] # points per second
df, truth = simulate()
print(f"sessions {len(df):,}; conversion {100*df.converted.mean():.2f}%; mean load {df.page_load_time.mean():.2f} s")
print(f"paid: {100*df.traffic_source.mean():.0f}% of sessions, load {df[df.traffic_source==1].page_load_time.mean():.2f} s vs "
f"{df[df.traffic_source==0].page_load_time.mean():.2f} s, conversion {100*df[df.traffic_source==1].converted.mean():.2f}% vs "
f"{100*df[df.traffic_source==0].converted.mean():.2f}%")
print(f"true effect of a 0.5 s faster site: {truth:+.2f} points ({2*truth:.2f} points per second)")
# 1. Three regressions, three answers.
for name, ctrl in [("no controls (the correlation)", []),
("traffic source (the confounder)", ["traffic_source"]),
("traffic source + pages viewed (a mediator)", ["traffic_source", "pages_viewed"])]:
print(f"{name:45s} {ols_slope(df, ctrl):+.2f} points per second")
# 2. PyCausalSim: learn the graph with the time order as background knowledge, then estimate.
tiers = {"traffic_source": 0, "page_load_time": 1, "pages_viewed": 2, "converted": 3}
graph = CausalDiscovery(random_state=0).discover(df, method="pc", tiers=tiers)
print("graph:", {k: v for k, v in graph.items() if v})
sim = CausalSimulator(df, target="converted", treatment_vars=["page_load_time"], random_state=0).set_graph(graph)
target = df.page_load_time.mean() - 0.5
eff = sim.simulate_intervention("page_load_time", target, n_simulations=300, method="backdoor")
print(f"PyCausalSim, 0.5 s faster: {100*eff.point_estimate:+.2f} points "
f"(95% CI {100*eff.ci_lower:+.2f} to {100*eff.ci_upper:+.2f}); truth {truth:+.2f}")
# 3. The guardrail: declare the mediator a confounder by mistake.
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
bad = CausalSimulator(df, target="converted", treatment_vars=["page_load_time"],
confounders=["traffic_source", "pages_viewed"], random_state=0).set_graph(graph)
eff2 = bad.simulate_intervention("page_load_time", target, n_simulations=300, method="backdoor")
print(f"mediator declared as a confounder: {100*eff2.point_estimate:+.2f} points")
for c in caught:
print("warning:", c.message)
# 3b. The same mistake, but letting the declared roles place the variables: PyCausalSim believes you.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
told = CausalSimulator(df, target="converted", treatment_vars=["page_load_time"],
confounders=["traffic_source", "pages_viewed"], random_state=0).discover_graph(method="pc")
eff3 = told.simulate_intervention("page_load_time", target, n_simulations=300, method="backdoor")
print("graph from declared roles:", {k: v for k, v in told.graph.items() if v})
print(f"mediator declared, roles place it: {100*eff3.point_estimate:+.2f} points")
sessions 200,000; conversion 2.62%; mean load 3.24 s
paid: 40% of sessions, load 3.60 s vs 3.00 s, conversion 3.42% vs 2.08%
true effect of a 0.5 s faster site: +0.49 points (0.98 points per second)
no controls (the correlation) -0.35 points per second
traffic source (the confounder) -0.97 points per second
traffic source + pages viewed (a mediator) -0.48 points per second
graph: {'page_load_time': ['traffic_source'], 'pages_viewed': ['traffic_source', 'page_load_time'], 'converted': ['traffic_source', 'page_load_time', 'pages_viewed']}
PyCausalSim, 0.5 s faster: +0.48 points (95% CI +0.44 to +0.54); truth +0.49
mediator declared as a confounder: +0.48 points
warning: Not adjusting for ['pages_viewed']: downstream of 'page_load_time' in the graph.
graph from declared roles: {'page_load_time': ['traffic_source', 'pages_viewed'], 'pages_viewed': ['traffic_source'], 'converted': ['traffic_source', 'page_load_time', 'pages_viewed']}
mediator declared, roles place it: +0.24 points
| What the regression holds fixed | Estimated effect, points per second |
|---|---|
| Nothing (the correlation) | -0.35 |
| Traffic source and pages viewed | -0.48 |
| Traffic source | -0.97 |
| The true effect | -0.98 |
Discovery found the graph that generated the data: traffic source drives load time, pages viewed and conversion; load time drives pages viewed and conversion; pages viewed drives conversion. With that graph PyCausalSim adjusts for traffic source only and estimates that a site half a second faster converts 0.48 points better, with a 95% interval of 0.44 to 0.54. The truth is 0.49.
The tiers argument carries the one thing the data can't: what happens before what. Nothing in a later tier can cause something in an earlier one. Traffic source is settled before the first byte arrives, and pages viewed can only be counted after the page loads.
Pages viewed is a bad control
Cinelli, Forney and Pearl's "A Crash Course in Good and Bad Controls" (Sociological Methods & Research, 2024) works through this case: controlling for a variable on the causal path blocks part of the effect you want to measure. In web analytics the list of such variables is long. Bounce, pages viewed, time on site, scroll depth and add to cart all happen after the page loads, and all of them are on the path from speed to purchase.
PyCausalSim has a guardrail for it. When the graph puts a declared confounder downstream of the treatment, the library refuses to adjust for it and says so: "Not adjusting for ['pages_viewed']: downstream of 'page_load_time' in the graph." The half-second estimate stays at 0.48 points, the right answer.
The guardrail depends on where the graph comes from. When I declare pages viewed a confounder and let discover_graph place the variables from the declared roles, the library treats the declaration as background knowledge, puts pages viewed upstream of load time, and adjusts for it. The half-second estimate drops to 0.24 points, half the truth of 0.49. Declared roles are a claim about the world, and the software believes them. State the time order with tiers and use confounders only for variables you know come first.
How much the correlation misses, and the formula behind it
The size of the miss depends on how much slower paid pages are. The rest of the same script reruns the simulation with the gap between paid and organic load times set from zero to 1.5 seconds.
# 4. How much the correlation understates it, as the speed gap between paid and organic grows.
print("gap_s correlation adjusted truth (points per second)")
for gap in [0.0, 0.3, 0.6, 0.9, 1.2, 1.5]:
d, t = simulate(gap=gap)
print(f"{gap:.1f} {ols_slope(d):+.2f} {ols_slope(d, ['traffic_source']):+.2f} {-2*t:+.2f}")
# 5. The omitted-variable formula reproduces the correlation's answer.
d, t = simulate()
paid_effect = 100 * (0.015 + 0.006 * 0.8) # points, paid vs organic at the same load time
ratio = np.cov(d.page_load_time, d.traffic_source)[0, 1] / d.page_load_time.var()
print(f"paid effect at fixed load {paid_effect:.2f} points; cov/var {ratio:.3f}; "
f"bias {paid_effect*ratio:+.2f}; formula naive {-1.0 + paid_effect*ratio:+.2f}")
# 6. What the gap is worth for a retailer with 200,000 sessions a month and an $85 average order (illustrative).
orders_true = t / 100 * len(d)
orders_naive = -0.5 * ols_slope(d) / 100 * len(d)
print(f"0.5 s faster: {orders_true:,.0f} extra orders (${85*orders_true:,.0f}) vs the correlation's "
f"{orders_naive:,.0f} (${85*orders_naive:,.0f})")
gap_s correlation adjusted truth (points per second)
0.0 -0.96 -0.97 -0.98
0.3 -0.59 -0.96 -0.98
0.6 -0.35 -0.97 -0.98
0.9 -0.21 -0.95 -0.97
1.2 -0.17 -0.94 -0.97
1.5 -0.18 -0.91 -0.97
paid effect at fixed load 1.98 points; cov/var 0.323; bias +0.64; formula naive -0.36
0.5 s faster: 975 extra orders ($82,877) vs the correlation's 346 ($29,433)
With no gap the correlation is right, because traffic source no longer moves load time. At a 0.3 second gap it finds 60% of the effect, and from 0.9 seconds on it finds less than a quarter. The adjusted estimate stays within 0.06 points of the truth across the range; the small drift at large gaps comes from a floor on conversion probability for the slowest sessions, which a straight-line model can't follow.
The correlation's answer is not noise. It follows the omitted-variable bias formula:
Here β is the effect of load time, -1.00 points per second in the model's equation, and γ is how much better paid traffic converts at the same load time, 1.98 points. The ratio is 0.323 in the simulated data, so the bias is 1.98 × 0.323 = +0.64 and the formula predicts -0.36. The regression returned -0.35. The model's coefficient is -1.00 while the effect measured by rerunning the sessions is -0.98 because of the same floor on conversion probability.
What the gap is worth to a Kansas City retailer
Take a mid-size Kansas City online retailer with 200,000 sessions a month and an $85 average order. These are illustrative numbers, not any company's. Making the site half a second faster adds 975 orders a month in the simulation, about $82,877 in revenue. The correlation says 346 orders, about $29,433. A team that budgets from the correlation turns down speed work that pays for itself nearly three times over.
The simulated effect is modest on purpose. Half a second lifts conversion from 2.62% by 0.49 points, about 19%. A study commissioned by Google and run by 55 and Deloitte across 37 brand sites and more than 30 million sessions reported that a 0.1 second improvement in mobile speed raised retail conversion rates by 8.4%. That study is observational too, which is the point of this piece: a speed effect read from field data carries whatever confounding the traffic mix brings with it.
Running it on your own sessions
The pieces are already in most analytics exports. You need one row per session with load time, a purchase flag, and the variables that are set before the page loads: traffic source or campaign, device, region, new or returning visitor, day of week. Those are your confounders. Anything recorded after the page starts loading stays out of the adjustment, however predictive it is.
Measure load time the way users feel it. Google's guidance on Largest Contentful Paint calls 2.5 seconds or less good and more than 4.0 seconds poor, measured at the 75th percentile of page loads and split by mobile and desktop. Field data from real users beats a lab test here, because the lab test runs every page under the same conditions and erases the traffic mix you need to adjust for.
When you can run an experiment, run one. Slowing a random share of sessions on purpose, or speeding a random set of pages, removes the confounding by design. The SEO split test power simulator sizes that kind of test, and Did the AI Pilot Work? shows difference-in-differences for a rollout you can't randomize. The PyCausalSim demo runs a page speed graph in the browser, and the causal inference research hub collects the rest of the causal inference work from Vector 1 in Kansas City.
Limits of these numbers
Every figure here comes from a simulation with parameters I chose: one confounder, a linear effect of load time, and a known graph. Real traffic has many confounders, some of them unlogged. A consent banner that strips campaign tags turns some paid sessions into organic ones in the data, and the adjustment then removes only part of the bias. Real speed effects are rarely straight lines. Discovery found the right graph here with 200,000 sessions and four variables; with more variables and fewer sessions it will leave some directions open, and the time order has to settle them. The dollar figures depend on the illustrative traffic and order value and are there to show the size of the gap, not to forecast any site.
The paid edition
The paid edition on Substack extends this example: a grid of how much the correlation recovers across load time gaps and paid conversion premiums, including the settings where it gets the sign wrong; what happens to the adjusted estimate when 10% to 50% of paid sessions arrive with their campaign tags stripped; a threshold model where speed only matters above 2.5 seconds, and what a straight line says about projects on either side of it; and a script that runs the whole audit on your own session export. Subscribe free for new articles by email, or get a Team License for the whole analytics team.
Sources
- Carlos Cinelli, Andrew Forney and Judea Pearl, A Crash Course in Good and Bad Controls, Sociological Methods & Research, 2024, vol. 53, no. 3, pp. 1071 to 1104
- Philip Walton and Barry Pollard, Largest Contentful Paint (LCP), web.dev, last updated September 4, 2025
- web.dev, Milliseconds make millions, June 24, 2020 (study commissioned by Google and conducted by 55 and Deloitte)
- PyCausalSim 0.7.0 on PyPI and its source on GitHub


