Rolling ETA median, DiD and CUPED uplift on ride-request data
SQL & DataModel answerLast updated
Build a gap-free daily city series with a 7-day rolling median ETA and conversion in PostgreSQL, then estimate uplift with city-level DiD and a CUPED-adjusted, cluster-robust estimate in Python.
You are analysing a ride-hailing A/B test (experiment_id = 42) with PostgreSQL and a little Python. Treat today as 2025-09-01.
Schema
trips(trip_id BIGINT, request_ts TIMESTAMP, city_id INT, rider_id BIGINT, driver_id BIGINT, shown_eta_sec INT, pickup_eta_sec INT, is_completed BOOLEAN, is_canceled BOOLEAN, surge_multiplier NUMERIC, is_treatment BOOLEAN, experiment_id INT)riders(rider_id BIGINT, signup_dt DATE, city_id INT)city_dim(city_id INT, city_name TEXT, tier TEXT)incentives(rider_id BIGINT, offer_start_dt DATE, offer_end_dt DATE, percent_off INT, cap_usd NUMERIC)day_weather(city_id INT, dt DATE, precip_mm NUMERIC, temp_c NUMERIC)
Sample rows
trips
trip_id | request_ts | city_id | rider_id | driver_id | shown_eta_sec | pickup_eta_sec | is_completed | is_canceled | surge_multiplier | is_treatment | experiment_id
1 | 2025-08-01 08:01:00 | 1 | 101 | 9001 | 420 | 480 | t | f | 1.0 | t | 42
2 | 2025-08-01 08:03:00 | 1 | 102 | 9002 | 360 | 360 | f | t | 1.2 | f | 42
3 | 2025-08-15 18:30:00 | 2 | 103 | 9003 | 300 | 420 | t | f | 1.1 | f | 42
4 | 2025-08-20 09:00:00 | 1 | 101 | 9001 | 330 | 360 | t | f | 1.0 | t | 42
5 | 2025-08-28 22:10:00 | 2 | 104 | 9004 | 600 | 660 | f | t | 1.5 | t | 42
riders
rider_id | signup_dt | city_id
101 | 2025-05-01 | 1
102 | 2025-01-15 | 1
103 | 2025-06-20 | 2
104 | 2025-03-10 | 2
city_dim
city_id | city_name | tier
1 | Alpha | T1
2 | Beta | T2
incentives
rider_id | offer_start_dt | offer_end_dt | percent_off | cap_usd
101 | 2025-08-15 | 2025-08-31 | 20 | 10
Tasks
- Daily series (SQL). For each
city_idand calendar date from 2025-08-01 to 2025-09-01, return the 7-day rolling median ofshown_eta_secand the request-to-trip conversion rate (completed / requests). Days with no requests must still appear, with conversionNULL. Keep only riders withsignup_dt < 2025-07-01. Bucket days by truncatingrequest_tsat UTC midnight, and say how you handle time zones. The intent is a median computed withpercentile_cont(0.5)over a 7-day window. - Difference-in-differences (SQL). At city level, compare treated and control conversion for the post period (2025-08-15 to 2025-09-01) against the pre period (2025-08-01 to 2025-08-14). Output
city_id, pre_treat_conv, pre_ctrl_conv, post_treat_conv, post_ctrl_conv, did_uplift, wheredid_uplift = (post_treat_conv - pre_treat_conv) - (post_ctrl_conv - pre_ctrl_conv). A rider who saw both arms must be counted by the exposure of each individual trip. - CUPED (Python, pseudocode acceptable). At rider level, let X be pre-period conversion and Y post-period conversion. Compute
theta = cov(Y, X) / var(X)andY_cuped = Y - theta * (X - mean(X)). Estimate the treated-vs-control uplift onY_cupedand report its standard error, cluster-robust byrider_idorcity_id.
State any assumptions you make (for example, which filters carry over to Tasks 2 and 3), and explain the pitfalls you see.
Hints
Hint 1
Check whether PostgreSQL lets you write percentile_cont(...) WITHIN GROUP (...) OVER (...). If it does not, think about joining each spine row to the trips from the previous 7 calendar days and using it as a plain grouped aggregate.
Hint 2
Fetch 6 extra days of trips before 2025-08-01 so the earliest windows are full, and compute the median over raw trip values, not over daily medians. Medians of medians are not the median of the union.
Hint 3
For DiD, label each trip with its own period and its own is_treatment flag, then use AVG(...) FILTER (WHERE ...) to get the four cells in one pass. For CUPED, decide up front how to treat riders with mixed exposure and riders with no pre-period trips.
Hint 4
In Task 3, fit theta once on the pooled sample, then regress Y_cuped on the treatment indicator with cov_type='cluster'. Think about whether having only two cities makes city-level clustering trustworthy.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
Three things matter here: SQL mechanics (date spine, conditional aggregation, windows), knowing what PostgreSQL does not support, and causal-inference hygiene (DiD assumptions, CUPED, clustering).
Two traps decide most of the score:
- PostgreSQL rejects
percentile_cont(...) OVER (...). It is an ordered-set aggregate, and these cannot be used as window functions. Say so, then compute the rolling median with a range self-join: join each spine row(city, d)to the trips with dates in[d-6, d]and usepercentile_cont ... WITHIN GROUPas an ordinary grouped aggregate. - Time zones.
request_tsis a naiveTIMESTAMP. State the assumption that it is stored in UTC, sorequest_ts::dateis the UTC day. If the column weretimestamptz, use(request_ts AT TIME ZONE 'UTC')::date. ApplyingAT TIME ZONE 'UTC'to a naive timestamp produces atimestamptz, and a later::datecast then uses the session time zone, which can silently shift days.
Task 1: spine, rolling median, conversion
Approach:
- Build a
city x datespine for 2025-08-01 to 2025-09-01 so empty days survive. - Filter trips to experiment 42 and riders with
signup_dt < 2025-07-01. Pull trips from 2025-07-26 so the first windows are full. - Median over trip-level values in
[d-6, d]. Conversion per day iscompleted / NULLIF(requests, 0).
WITH eligible AS (
SELECT t.city_id,
t.request_ts::date AS d, -- UTC day (ts assumed UTC)
t.shown_eta_sec,
COALESCE(t.is_completed, false) AS is_completed
FROM trips t
JOIN riders r ON r.rider_id = t.rider_id
WHERE t.experiment_id = 42
AND r.signup_dt < DATE '2025-07-01'
AND t.request_ts >= TIMESTAMP '2025-07-26'
AND t.request_ts < TIMESTAMP '2025-09-02'
),
spine AS (
SELECT c.city_id, g::date AS d
FROM city_dim c
CROSS JOIN generate_series(DATE '2025-08-01', DATE '2025-09-01', INTERVAL '1 day') g
),
daily AS (
SELECT city_id, d,
COUNT(*) AS requests,
COUNT(*) FILTER (WHERE is_completed) AS completed
FROM eligible
GROUP BY city_id, d
),
rolling AS (
SELECT s.city_id, s.d,
percentile_cont(0.5) WITHIN GROUP (ORDER BY e.shown_eta_sec) AS median_eta_7d
FROM spine s
LEFT JOIN eligible e
ON e.city_id = s.city_id
AND e.d BETWEEN s.d - 6 AND s.d
GROUP BY s.city_id, s.d
)
SELECT s.city_id, s.d,
COALESCE(dl.requests, 0) AS requests,
COALESCE(dl.completed, 0) AS completed,
dl.completed::numeric / NULLIF(dl.requests, 0) AS conversion,
r.median_eta_7d
FROM spine s
LEFT JOIN daily dl ON dl.city_id = s.city_id AND dl.d = s.d
LEFT JOIN rolling r ON r.city_id = s.city_id AND r.d = s.d
ORDER BY s.city_id, s.d;
Notes:
- The window is calendar-based, so gaps in data do not stretch it. A row-based window on sparse data would.
percentile_contignores NULLs, and a window with no trips yields NULL, which is the honest answer.- Cost is roughly 7x the trip count for the join. An index on
trips(experiment_id, request_ts)keeps the scan narrow. - 2025-09-01 is "today", so that day is only partially observed. Flag it.
Task 2: difference-in-differences per city
Label every trip by its own period and its own is_treatment. That is exactly what handles mixed-exposure riders: each trip counts in the arm that actually served it.
WITH labeled AS (
SELECT t.city_id, t.is_treatment,
COALESCE(t.is_completed, false)::int AS conv,
CASE WHEN t.request_ts::date BETWEEN DATE '2025-08-01' AND DATE '2025-08-14' THEN 'pre'
WHEN t.request_ts::date BETWEEN DATE '2025-08-15' AND DATE '2025-09-01' THEN 'post'
END AS period
FROM trips t
JOIN riders r ON r.rider_id = t.rider_id
WHERE t.experiment_id = 42
AND r.signup_dt < DATE '2025-07-01' -- same cohort as Task 1 (stated assumption)
AND t.request_ts >= TIMESTAMP '2025-08-01'
AND t.request_ts < TIMESTAMP '2025-09-02'
),
cells AS (
SELECT city_id,
AVG(conv) FILTER (WHERE period='pre' AND is_treatment) AS pre_treat_conv,
AVG(conv) FILTER (WHERE period='pre' AND NOT is_treatment) AS pre_ctrl_conv,
AVG(conv) FILTER (WHERE period='post' AND is_treatment) AS post_treat_conv,
AVG(conv) FILTER (WHERE period='post' AND NOT is_treatment) AS post_ctrl_conv
FROM labeled
GROUP BY city_id
)
SELECT *, (post_treat_conv - pre_treat_conv) - (post_ctrl_conv - pre_ctrl_conv) AS did_uplift
FROM cells
ORDER BY city_id;
Points to make:
- An empty cell gives NULL for
AVG, sodid_upliftis NULL. That is correct: the effect is unidentified, not zero. - This is trip-weighted, so heavy riders dominate. A rider-averaged estimate answers a different question.
- In a randomized test, the pre-period treated-vs-control gap should be near zero. A large gap suggests a randomization or logging bug, and DiD's parallel-trends assumption does not repair that.
- Tiny cities give noisy cells, so show counts alongside rates.
Task 3: CUPED with clustered standard errors
Design decisions to state:
- Rider arm. Use post-period exposure. Drop riders with mixed post exposure, and report how many were dropped (a high count signals an assignment problem).
- No pre-period trips. X is undefined, so impute
mean(X)(zero adjustment) and optionally add a missing-indicator. - No post-period trips. Y is undefined, so exclude the rider from the outcome.
- Theta. Estimate it once on the pooled data. Using the same theta in both arms keeps the estimator unbiased, because X is pre-treatment. Variance falls by a factor of
1 - rho^2.
import numpy as np, pandas as pd
import statsmodels.formula.api as smf
df = trips_eligible.copy() # same filters as Tasks 1-2
df["day"] = df["request_ts"].dt.normalize() # UTC
df = df[(df.day >= "2025-08-01") & (df.day <= "2025-09-01")]
df["period"] = np.where(df.day <= "2025-08-14", "pre", "post")
X = df[df.period == "pre"].groupby("rider_id")["is_completed"].mean().rename("X")
P = (df[df.period == "post"].groupby("rider_id")
.agg(Y=("is_completed", "mean"), share=("is_treatment", "mean")))
r = P.join(X, how="left").join(riders.set_index("rider_id")["city_id"])
r = r[r.share.isin([0.0, 1.0])].copy() # drop mixed exposure, log the count
r["treat"] = r.share.astype(int)
r["X"] = r["X"].fillna(r["X"].mean())
theta = np.cov(r.Y, r.X, ddof=1)[0, 1] / np.var(r.X, ddof=1)
r["Y_cuped"] = r.Y - theta * (r.X - r.X.mean())
fit = smf.ols("Y_cuped ~ treat", data=r).fit(
cov_type="cluster", cov_kwds={"groups": r["city_id"]})
print(fit.params["treat"], fit.bse["treat"])
Clustering choice:
- With one row per rider, rider-level clustering is essentially a heteroskedasticity-robust SE.
- Cluster by
city_idif outcomes are correlated within a city (shared supply, weather, local events) or if assignment was done by city. - Cluster-robust SEs are unreliable with few clusters, and two cities is far too few. Use a wild cluster bootstrap, or cluster by rider and include city fixed effects.
Common mistakes
- Using
percentile_cont ... OVERand expecting it to run. - Taking a median of daily medians.
- Forgetting the 6-day lookback, so early windows are short.
- Letting
::daterun through the session time zone. - Assigning mixed-exposure riders to one arm in the DiD.
- Using a post-treatment covariate for CUPED, or fitting theta separately per arm.
- Reporting
did_uplift = 0when a cell is empty.