Sub topic 10
Rolling-Window Features That Exclude Future Rows
Assume you know basic supervised machine learning, pandas, SQL joins, window functions, and timestamps. This chapter focuses on one rule: a feature for a prediction at time \(t\) may use only events available before \(t\).
Why ordinary rolling features can leak
A rolling-window feature summarizes recent events. For example, spend_30d might be the total customer spending during the 30 days before a prediction.
A careless implementation can include events that happen after the prediction time. This is temporal data leakage: information from the future enters a training row. Offline metrics then become too optimistic because the model sees facts that production will not know yet.
Use a half-open time interval:
| Feature | Allowed event interval |
|---|---|
| Spending in the previous 30 days | `[prediction_time - 30 days, prediction_time)` |
The closing parenthesis excludes an event exactly at the prediction time. Include such an event only when your production system guarantees that it is available before the prediction is made.
A correct pandas implementation
The following example calculates a 30-day spending feature for each label row. The explicit timestamp filters make the time boundary visible and testable.
import pandas as pd
events = pd.DataFrame(
{
"customer_id": ["c1", "c1", "c1", "c2"],
"event_ts": [
"2026-01-05 10:00",
"2026-01-20 09:00",
"2026-02-05 12:00",
"2026-01-25 15:00",
],
"amount": [20.0, 30.0, 100.0, 50.0],
}
)
labels = pd.DataFrame(
{
"customer_id": ["c1", "c1", "c2"],
"prediction_ts": [
"2026-02-01 00:00",
"2026-02-10 00:00",
"2026-02-01 00:00",
],
"churned": [0, 1, 0],
}
)
events["event_ts"] = pd.to_datetime(events["event_ts"], utc=True)
labels["prediction_ts"] = pd.to_datetime(labels["prediction_ts"], utc=True)
def spending_before(row, window="30D"):
start = row["prediction_ts"] - pd.Timedelta(window)
eligible = (
(events["customer_id"] == row["customer_id"])
& (events["event_ts"] >= start)
& (events["event_ts"] < row["prediction_ts"])
)
return events.loc[eligible, "amount"].sum()
labels["spend_30d"] = labels.apply(spending_before, axis=1)
print(labels)For customer c1 at February 1, the feature is 50.0. The February 5 event is excluded because it occurs after the prediction. At February 10, that event is included.
This row-by-row version favors clarity. For large datasets, compute aggregates in a warehouse or optimized batch job. The same boundaries must remain: filter by entity, restrict the event interval, then aggregate.
SQL window boundaries
A SQL implementation uses the same logic. A correlated subquery is easy to audit:
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
COALESCE(SUM(e.amount), 0) AS spend_30d
FROM labels AS l
LEFT JOIN events AS e
ON e.customer_id = l.customer_id
AND e.event_ts >= l.prediction_ts - INTERVAL '30 days'
AND e.event_ts < l.prediction_ts
GROUP BY l.customer_id, l.prediction_ts, l.churned;Do not replace the final condition with e.event_ts <= l.prediction_ts without deciding whether same-time events are truly available. Timestamp precision and ingestion delays can make that assumption unsafe.
Checks for future rows
After building the feature table, retain the timestamps used for the aggregate when possible. Then assert that no contributing event is newer than its label’s prediction time. Also test a known future event, as in the pandas example, to ensure the feature value does not change when that event is added to a later time only.
Exercise
A customer has events on March 1 and March 20. A prediction is made on March 15 using a 30-day window. Which events belong in the feature, and why?
Show answer
Only the March 1 event belongs. The window starts on February 14 and ends before March 15, so the March 20 event is in the future and must be excluded.