Sub topic 10
Rolling-window features that exclude future rows
This chapter assumes you can write SQL joins and window functions, use pandas rolling and merge_asof, and know the as-of join from the previous chapters. It covers the second place where future data enters a training set: the aggregate itself. A feature such as avg_spend_30d can leak even when every join is correct.
Where windows leak
An as-of join picks a stored feature row that was valid at the prediction time. That only helps if the stored row was computed without future events. A rolling aggregate is computed from many raw events, so each window boundary has to be checked.
A feature named avg_spend_30d means "average spend over the 30 days before the moment this row describes". Three things commonly break that meaning:
- The window is centered, so it includes days after the row's timestamp.
- The window includes the current event, and that event is the one being predicted or is recorded after the prediction.
- The window is computed over the full dataset, for example with a global
groupby, then joined to rows from earlier dates.
Each of these puts information from after the prediction time into the feature. The model learns to use it, and production never supplies it.
Choosing the window boundary
Decide two things before writing code: whether the window is open or closed at each end, and whether the row at the prediction time itself counts.
For a prediction made at time t with window length W, a safe default is the half-open interval [t - W, t). It includes events from W ago up to, but not including, t. Excluding t is deliberate. An event stamped exactly at the prediction time often is the outcome you are predicting, or arrives in the same batch as it.
If your serving system includes events at exactly t, the training window must do the same. Training and serving have to agree on the boundary, which the training-serving consistency chapter returns to.
Example data
The examples use a small events table. Each row is one purchase.
import pandas as pd
events = pd.DataFrame(
{
"customer_id": ["a", "a", "a", "a", "b", "b"],
"event_ts": pd.to_datetime(
[
"2026-01-01",
"2026-01-10",
"2026-01-20",
"2026-02-05",
"2026-01-03",
"2026-01-25",
]
),
"amount": [10.0, 20.0, 30.0, 100.0, 5.0, 15.0],
}
)
labels = pd.DataFrame(
{
"customer_id": ["a", "b"],
"prediction_ts": pd.to_datetime(["2026-01-21", "2026-01-26"]),
"churned": [0, 1],
}
)
print(events)
print(labels)Customer a has a purchase of 100.0 on 2026-02-05. It happens after the prediction time of 2026-01-21, so it must never reach that label row.
Pattern 1: compute the window per label row
The most direct approach is to compute the aggregate for each label row, filtering events by that row's own prediction time. It is easy to verify, because the filter is visible in the code.
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
AVG(e.amount) AS avg_spend_30d,
COUNT(e.amount) AS n_events_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;The LEFT JOIN keeps customers with no events in the window. For them AVG returns NULL and COUNT returns 0. Keep that distinction. A missing average means "no activity", and your model or imputation step needs to treat it deliberately.
The cost is a join that can grow large. Each label row touches every event in its window. For millions of labels and long windows, this is the pattern that gets slow, which motivates the next one.
Pattern 2: pandas rolling with a closed interval
In pandas, rolling on a time column handles the window for you. The closed argument controls the boundaries, and it is the main place people leak by accident.
import pandas as pd
events = pd.DataFrame(
{
"customer_id": ["a", "a", "a", "a", "b", "b"],
"event_ts": pd.to_datetime(
[
"2026-01-01",
"2026-01-10",
"2026-01-20",
"2026-02-05",
"2026-01-03",
"2026-01-25",
]
),
"amount": [10.0, 20.0, 30.0, 100.0, 5.0, 15.0],
}
)
events = events.sort_values(["customer_id", "event_ts"])
rolled = (
events.set_index("event_ts")
.groupby("customer_id")["amount"]
.rolling("30D", closed="left")
.mean()
.rename("avg_spend_30d")
.reset_index()
)
print(rolled)With closed="left", each row's window is [event_ts - 30D, event_ts). The row's own amount is excluded. The value on a row therefore describes the 30 days before that event. The first event for each customer gets NaN because nothing precedes it.
The default is closed="right", which includes the current row. That is correct only if the feature row is meant to describe the state after the event, and you then join it by event time with the as-of join. Be explicit about which you want.
Two details matter here:
- The data must be sorted by time within each group, and the index must be monotonic for a time-based window.
- Pandas computes the window per event row. It does not produce a value for an arbitrary prediction time. To get a value at a prediction time, you produce the feature history first and then use the as-of join.
Pattern 3: feature history, then the as-of join
Combine the rolling computation with the as-of join. The rolling step creates a feature history with one row per event. The as-of join then selects, for each label, the latest feature row at or before the prediction time.
Because closed="left" already excluded each row's own event, and the as-of join uses direction="backward", the feature row selected for a label never includes events after the prediction time.
import pandas as pd
events = pd.DataFrame(
{
"customer_id": ["a", "a", "a", "a", "b", "b"],
"event_ts": pd.to_datetime(
[
"2026-01-01",
"2026-01-10",
"2026-01-20",
"2026-02-05",
"2026-01-03",
"2026-01-25",
]
),
"amount": [10.0, 20.0, 30.0, 100.0, 5.0, 15.0],
}
)
labels = pd.DataFrame(
{
"customer_id": ["a", "b"],
"prediction_ts": pd.to_datetime(["2026-01-21", "2026-01-26"]),
"churned": [0, 1],
}
)
events = events.sort_values(["customer_id", "event_ts"])
history = (
events.set_index("event_ts")
.groupby("customer_id")["amount"]
.rolling("30D", closed="both")
.mean()
.rename("avg_spend_30d")
.reset_index()
.rename(columns={"event_ts": "feature_ts"})
.sort_values("feature_ts")
)
labels = labels.sort_values("prediction_ts")
train = pd.merge_asof(
labels,
history,
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta("30D"),
)
print(train)Here closed="both" includes the row's own event, so each history row describes the state after that event. For customer a, the row at 2026-01-20 averages 10, 20, and 30, which is 20.0. The 2026-02-05 row, which would include the 100.0 purchase, is later than the prediction time and is never selected.
Note the pairing rule. If the history row includes its own event, the as-of join must use a timestamp at which that event was already known. With <= on feature_ts, an event at exactly the prediction time is included. If that is not what serving does, shift the history timestamp or use allow_exact_matches=False in merge_asof.
Pitfalls specific to windows
Centered windows
rolling(window, center=True) looks equally far backward and forward. It suits smoothing a signal for plotting. It never belongs in a feature pipeline. The same applies to any smoothing function that is not causal, such as a two-sided moving average or a forward fill applied in the wrong direction.
Whole-dataset statistics
A z-score computed with the mean and standard deviation of the full table contains information about later rows. Compute such statistics only from rows before the training cutoff, then apply them to validation and serving. This is a leak of a different form, but it produces the same symptom: strong offline metrics and weaker production metrics.
Windows over late data
A window computed today over raw events includes events that arrived late. The feature value you would have computed on the original prediction date was different. When ingestion time matters, filter on it as well, as covered in the late-data chapter:
SELECT
l.customer_id,
l.prediction_ts,
AVG(e.amount) AS avg_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
AND e.ingested_ts <= l.prediction_ts
GROUP BY l.customer_id, l.prediction_ts;Short windows with sparse data
A 7-day window for a customer who buys once a month is mostly empty. The feature is then NaN or 0 for most rows. Decide whether that means "no activity" and encode it with a count column such as n_events_7d. Without the count, 0.0 average spend and "no data" look the same.
Window and tolerance interact
The window length and the as-of tolerance are separate limits. A 30-day window ending at the last event can describe a period that finished 29 days before the prediction. Pattern 3 uses a 30-day tolerance, so the selected row may be up to 30 days old, and its window reaches 30 days further back. Choose the tolerance with the real update schedule in mind. If features are recomputed daily, a tolerance of a few days is usually enough.
| Choice | Effect | Risk |
|---|---|---|
| `closed="left"` | Excludes the current row | Loses the latest event; first row is NaN |
| `closed="both"` | Includes the current row | Correct only if serving also sees that event |
| `center=True` | Uses past and future rows | Direct leakage |
| Global statistics | Uses all dates | Indirect leakage |
| No ingestion filter | Includes late arrivals | Training values differ from what serving saw |
Verifying a window feature
A quick way to test a window feature is to recompute it by hand for one label row, using only events that qualify. This is a useful check next to the automated tests from the previous chapter.
import pandas as pd
events = pd.DataFrame(
{
"customer_id": ["a", "a", "a", "a"],
"event_ts": pd.to_datetime(
["2026-01-01", "2026-01-10", "2026-01-20", "2026-02-05"]
),
"amount": [10.0, 20.0, 30.0, 100.0],
}
)
prediction_ts = pd.Timestamp("2026-01-21")
window = events[
(events["customer_id"] == "a")
& (events["event_ts"] >= prediction_ts - pd.Timedelta("30D"))
& (events["event_ts"] < prediction_ts)
]
expected = window["amount"].mean()
assert expected == 20.0
assert (window["event_ts"] < prediction_ts).all()
print(expected)A second test is a perturbation check. Add a large event dated after the prediction time and confirm the feature value does not change. If it changes, something in the pipeline reads future rows.
Summary
- Windows leak through centered windows, an included current event, and statistics computed over all dates.
- Use a half-open interval
[t - W, t)unless serving explicitly includest. - In pandas, set
closedexplicitly and sort by time within each group. - Build a feature history, then use the as-of join to pick the row valid at the prediction time.
- Add an ingestion-time filter when late or corrected data exists, and carry an event count alongside each average.
- Test by recomputing one value by hand and by adding future events that must not change the result.
Exercise
A feature orders_7d is computed with events.set_index("event_ts").groupby("customer_id")["order_id"].rolling("7D").count(), then joined to labels with merge_asof(..., direction="backward"). The label for a customer is whether they place an order on the prediction date, and the prediction timestamp is midnight at the start of that day. A teammate says the feature is safe because the join is backward. Is it, and what would you change?
Show answer
It can leak. The default closed="right" includes the row's own event, and the feature row is stamped with that event's time. If an order is placed later on the prediction date, a row stamped after midnight is not selected, so that part is safe. But an order stamped exactly at midnight is included, and the feature then counts the event being predicted. Use closed="left" (or allow_exact_matches=False in merge_asof) so events at the prediction time are excluded, and add a perturbation test that inserts an order after the prediction time and confirms orders_7d does not change.
Exercise
Why should an average-spend feature be paired with a count column such as n_events_30d?
Show answer
An average over an empty window is NaN, and after imputation it often becomes 0.0, which looks like a customer who spent nothing per order. The count separates "no activity in the window" from "activity with a low average", so the model and any later checks can tell them apart.