Building Non-Leaky User Features and Interpreting Regression Outputs
SQL & DataModel answerLast updated
Aggregate raw event data into daily user-level features without target leakage using SQL and Python, then fit regression models and interpret coefficients correctly.
You are analyzing user interaction events from an web application to evaluate the effect of an experimental feature assignment (variant) on conversion.
You are given a raw event table named user_metrics:
+---------+-------------+---------+--------+-----------+
| user_id | activity_dt | variant | clicks | purchases |
+---------+-------------+---------+--------+-----------+
| 101 | 2023-05-01 | A | 12 | 1 |
| 102 | 2023-05-01 | B | 4 | 0 |
| 103 | 2023-05-02 | A | 6 | 1 |
| 104 | 2023-05-02 | B | 9 | 2 |
| 105 | 2023-05-03 | A | 3 | 0 |
+---------+-------------+---------+--------+-----------+
Tasks
-
SQL Feature Engineering: Write a SQL query that aggregates raw event data to one row per
(user_id, activity_dt)pair. Calculate the target variableconverted($1$ ifpurchases > 0, else $0$), along with rolling feature calculations that avoid target leakage:- Total clicks within the prior 7 calendar days (excluding the current day).
- Number of prior active days (excluding the current day).
- Days elapsed since the user's previous active date.
-
Python Implementation & Interpretation:
- Write Python code (using
pandasandstatsmodels) to fit appropriate regression models (e.g., Logistic Regression or OLS). - Explain how to interpret the regression coefficients for numeric metrics and categorical predictors.
- Highlight potential pitfalls in feature selection (e.g., controlling for post-treatment variables in experimental analysis).
- Write Python code (using
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural & Technical Approach
The task involves a two-stage data science pipeline:
- Data Aggregation & Feature Engineering (SQL): Summarizing raw event logs into a modeling panel structured at the user-day grain. Preventing data leakage is critical here—historical features generated for day $t$ must strictly incorporate data prior to $t$.
- Modeling & Inference (Python): Fitting parametric regression models and properly translating estimated parameters into actionable product insights while addressing standard causal inference traps.
Step 1: SQL Data Pipeline
Leakage Prevention Mechanics
- Current Day Exclusion: Features like
clicks_prev_7dmust exclude the current record (AND 1 PRECEDING). Including same-day events in historical activity metrics leaks information about the target variable. - Calendar Range vs. Active Rows: Using
ROWS BETWEEN 7 PRECEDING AND 1 PRECEDINGcalculates rolling metrics over the last 7 active rows, not the last 7 calendar days. If a user is inactive for two weeks,ROWSwill reach back into the past. Using aRANGEframe with calendar intervals enforces true physical time bounds.
WITH daily_base AS (
-- Guarantee exactly one record per (user_id, activity_dt)
SELECT
user_id,
activity_dt,
MAX(variant) AS variant, -- Fixed assignment per user
SUM(clicks) AS daily_clicks,
SUM(purchases) AS daily_purchases
FROM user_metrics
GROUP BY user_id, activity_dt
)
SELECT
user_id,
activity_dt,
variant,
daily_clicks,
daily_purchases,
CASE WHEN daily_purchases > 0 THEN 1 ELSE 0 END AS converted,
-- Prior 7 calendar days (excluding current day)
COALESCE(
SUM(daily_clicks) OVER (
PARTITION BY user_id
ORDER BY activity_dt
RANGE BETWEEN INTERVAL '7 days' PRECEDING
AND INTERVAL '1 day' PRECEDING
), 0
) AS clicks_prev_7d,
-- Cumulative active days prior to today
COUNT(*) OVER (
PARTITION BY user_id
ORDER BY activity_dt
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) AS prior_active_days,
-- Days elapsed since last active date
activity_dt - LAG(activity_dt) OVER (
PARTITION BY user_id
ORDER BY activity_dt
) AS days_since_last_active
FROM daily_base
ORDER BY user_id, activity_dt;
Step 2: Python Modeling & Fitting
Below is the Python implementation using standard libraries to create equivalent features and fit downstream models.
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
def prepare_features(df: pd.DataFrame) -> pd.DataFrame:
df["activity_dt"] = pd.to_datetime(df["activity_dt"])
# 1. Aggregate to user-day level
daily = (
df.groupby(["user_id", "activity_dt"], as_index=False)
.agg(
variant=("variant", "first"),
clicks=("clicks", "sum"),
purchases=("purchases", "sum"),
)
.sort_values(["user_id", "activity_dt"])
)
daily["converted"] = (daily["purchases"] > 0).astype(int)
# 2. Compute non-leaky rolling 7-day clicks per user
def compute_rolling_7d(group):
# Set date index to use calendar rolling windows
s = group.set_index("activity_dt")["clicks"]
# Rolling 7D including today minus today's value = prior 7D
rolling_prior = s.rolling("7D", closed="left").sum().fillna(0)
return rolling_prior.values
daily["clicks_prev_7d"] = (
daily.groupby("user_id", group_keys=False)
.apply(compute_rolling_7d)
)
# 3. Cumulative active days
daily["prior_active_days"] = daily.groupby("user_id").cumcount()
return daily
def fit_models(daily_df: pd.DataFrame):
# Model 1: Logistic Regression for Binary Conversion
# Standard error clustering by user_id to account for repeated user observations
logit_fit = smf.logit(
"converted ~ C(variant, Treatment('A')) + clicks_prev_7d + prior_active_days",
data=daily_df
).fit(cov_type="cluster", cov_kwds={"groups": daily_df["user_id"]}, disp=False)
# Model 2: Linear Probability / OLS Model for Expected Daily Revenue/Purchases
ols_fit = smf.ols(
"purchases ~ C(variant, Treatment('A')) + clicks_prev_7d",
data=daily_df
).fit(cov_type="cluster", cov_kwds={"groups": daily_df["user_id"]})
return logit_fit, ols_fit
Step 3: Coefficient Interpretation & Statistical Theory
1. Logistic Regression Coefficients
In the logistic model: $$\ln\left(\frac{P(Y=1)}{1 - P(Y=1)}\right) = \beta_0 + \beta_1 \cdot \text{Variant}_B + \beta_2 \cdot \text{clicks_prev_7d}$$
- Continuous Predictor ($\beta_2$): A 1-unit increase in
clicks_prev_7dincreases the expected log-odds of converting by $\beta_2$, holding all other factors constant. Exponentiating the coefficient ($\exp(\beta_2)$) yields the Odds Ratio (OR). If $\beta_2 = 0.05$, then $\exp(0.05) \approx 1.051$, meaning each extra click increases conversion odds by $\approx 5.1%$. - Categorical Predictor ($\beta_1$): Represents the difference in baseline log-odds between
Variant Band the reference groupVariant A. $\exp(\beta_1)$ is the odds ratio of conversion for Variant B relative to Variant A. - Marginal Effects: Because odds ratios are non-linear, business stakeholders often prefer marginal effect sizes on probability space. This can be derived via average marginal effects:
logit_fit.get_margeff().summary().
2. Linear Probability / OLS Models
In the linear model: $$\mathbb{E}[\text{purchases}] = \alpha + \beta_1 \cdot \text{Variant}_B + \beta_2 \cdot \text{clicks_prev_7d}$$
- $\beta_1$ represents the absolute expected increase in purchases for a user assigned to Variant B relative to Variant A on a given day, holding baseline engagement constant.
Step 4: Causal Inference Pitfalls
Post-Treatment Bias (Bad Control)
When evaluating an A/B test variant effect, including same-day clicks as a covariate introduces severe bias if the treatment (variant) impacts click volume.
same_day_clicksis a post-treatment variable (or mediator).- Controlling for mediators blocks the primary pathway through which the treatment influences the outcome, leaving only the "direct effect". This understates the total impact of the treatment.
Best Practices for Causal Analysis
- Total Treatment Effect (ATE): Regress outcome directly on
variantwithout post-treatment covariates: $$\text{converted} \sim \text{variant}$$ - Variance Reduction (CUPED): Control only for strictly pre-treatment metrics (such as
clicks_prev_7dmeasured before the treatment assignment or experiment start) to decrease variance without conditioning on intermediate variables: $$\text{converted} \sim \text{variant} + \text{clicks_pre_experiment}$$