Objective
A feature is valid only if, at the moment the trade is decided, every input had its value as it was known then. This lesson covers the three main ways that fails: revised data, membership lists built from today's knowledge, and features that overlap the target. You should be able to name the bias, predict its direction, and write the join that removes it.
Revisions and restatements
Many numbers change after first publication:
- Macro data. GDP, payrolls and inflation are released as an advance estimate and revised for months or years. A model trained on the final vintage has seen numbers that no one had at the time, and revisions are partly predictable from information that arrived later.
- Company fundamentals. Earnings are restated after errors, accounting changes or acquisitions. Standard fundamental databases often overwrite the original value with the restated one.
- Vendor backfill. When a vendor adds a company or a new data field, it often fills in history. A record that appears in a 2015 row today may not have existed in the 2015 database.
The fix is a point-in-time (bitemporal) store: one row per version of each number, with the period it describes and the time it became known. To build a feature for a decision at time , take the latest version known at or before .
Membership and universe
Index constituents, the list of listed stocks, "the 500 largest companies", sector classifications and credit ratings all change. Using today's list for a past date is look-ahead in two ways: dead stocks are missing (survivorship), and the stocks that were later added to an index were added because they had grown, so today's members are selected on future success. A universe must be rebuilt for every date from data known on that date.
Target leakage
The target is what you are trying to predict, typically the return over . Leakage happens when a feature contains any part of that window. Common sources:
- A window that ends one bar too late, because of a timestamp convention or a time-zone shift (lesson 2).
shift(-1),bfill(),rolling(..., center=True), or interpolation, each of which pulls later values backwards.- Normalising or fitting with full-sample statistics (lesson 5).
- Labels that use information known only at the end of the horizon, such as "stock was in the top decile this year", used as a feature for the same year.
- In cross-validation, overlapping targets: a random train/test split of daily rows with 20-day forward returns puts nearly identical targets on both sides. Split by time, and leave a gap at least as long as the horizon between training and test data (purging and embargo).
Worked example
an as-of join that respects restatements
A company reported Q4 2023 EPS of 1.10 on 8 February 2024 after the close, and Q1 2024 EPS of 1.20 on 25 April after the close. On 1 August before the open it restated Q1 to 0.95. What EPS should a backtest see at 15:59 on 25 April, 09:30 on 26 April, 09:30 on 15 May and 09:30 on 1 August? What does a table of "latest values by period" give instead?
Show solutionHide solution
Store every version with its knowledge time, then join on knowledge time:
import pandas as pd
# One row per VERSION of a number, stamped with when it became public.
eps = pd.DataFrame({
"period_end": pd.to_datetime(["2023-12-31", "2024-03-31", "2024-03-31"]),
"known_at": pd.to_datetime(["2024-02-08 16:05", "2024-04-25 16:05", "2024-08-01 07:00"]),
"eps": [1.10, 1.20, 0.95], # Q1 2024 first reported 1.20, restated to 0.95
})
dates = pd.DataFrame({"decision_time": pd.to_datetime(
["2024-04-25 15:59", "2024-04-26 09:30", "2024-05-15 09:30", "2024-08-01 09:30"])})
pit = pd.merge_asof(dates, eps.sort_values("known_at"),
left_on="decision_time", right_on="known_at", direction="backward")
print(pit[["decision_time", "period_end", "eps"]].to_string(index=False))
# The usual mistake: a "latest vintage" table keyed by period end.
latest = eps.sort_values("known_at").groupby("period_end", as_index=False).last()
wrong = pd.merge_asof(dates, latest, left_on="decision_time", right_on="period_end")
print(wrong[["decision_time", "period_end", "eps"]].to_string(index=False))
decision_time period_end eps
2024-04-25 15:59:00 2023-12-31 1.10
2024-04-26 09:30:00 2024-03-31 1.20
2024-05-15 09:30:00 2024-03-31 1.20
2024-08-01 09:30:00 2024-03-31 0.95
decision_time period_end eps
2024-04-25 15:59:00 2024-03-31 0.95
2024-04-26 09:30:00 2024-03-31 0.95
2024-05-15 09:30:00 2024-03-31 0.95
2024-08-01 09:30:00 2024-03-31 0.95
The point-in-time version sees Q4's 1.10 until the Q1 release, then the originally reported 1.20, and the restated 0.95 only from 1 August. The wrong version makes two errors at once: it keys on the period end, so Q1's number is "available" on 31 March, almost four weeks before it was published; and it uses the restated value, so the backtest knew in April about a downward revision that came out in August. A strategy that shorts companies whose earnings will later be restated would look brilliant on that table.
Worked example
a leaking feature on pure noise
Daily returns are independent noise. The target is the 5-day forward return, from to . A researcher builds a "5-day momentum" feature, but because of a timestamp convention the window ends at instead of . What correlation with the target do the honest and the leaky features have, what hit rate does the leaky one show, and what is the rule for predicting the size of the leak?
Show solutionHide solution
import numpy as np, pandas as pd
rng = np.random.default_rng(1)
r = pd.Series(rng.normal(0, 0.01, 100_000)) # pure noise: nothing is predictable
target = r.rolling(5).sum().shift(-5) # return over t+1 .. t+5
honest = r.rolling(5).sum() # return over t-4 .. t
leaky = r.rolling(5).sum().shift(-1) # t-3 .. t+1: one day too late
print("honest corr:", round(honest.corr(target), 3))
print("leaky corr:", round(leaky.corr(target), 3))
hit = (np.sign(leaky) == np.sign(target))[target.notna() & leaky.notna()].mean()
print("leaky hit rate:", round(hit, 3))
honest corr: -0.004
leaky corr: 0.2
leaky hit rate: 0.569
Predicting the leak. With i.i.d. returns of variance , two sums over windows of and days that share days have covariance and correlation . Here and the windows share one day (), so the correlation is , exactly what the simulation shows.
Hit rate. For jointly normal variables with correlation , the probability their signs agree is . With that is ; the simulation's is within sampling error (the 5-day windows overlap, so the effective sample is much smaller than 100,000).
A correlation of 0.2 between a feature and a 5-day return is far beyond anything real in liquid markets. The diagnostic habits that catch this: (1) the signal decays to nothing when lagged by one extra day, (2) the information coefficient is implausibly high, (3) the feature's timestamps, when printed next to the raw data for a single row, include a value dated after the decision.
Knowledge check
With independent daily returns, a feature is the sum of returns over days t−2 to t+2 (a 5-day window) and the target is the sum over t+1 to t+5. What correlation would you expect between them?
Knowledge check
Which pandas operation, applied to a feature series before aligning it with forward returns, does NOT introduce look-ahead?
Knowledge check
A backtest from 2005 to 2024 uses the current S&P 500 constituents as its universe throughout. Which statement is most accurate?
How to discuss this in an interview
When shown a backtest or a model with surprisingly good results, go through the information set out loud: "For a decision at time : which universe was known? Which version of each fundamental? When was each input published, in which time zone, and how long did it take to arrive? Does any window, fill or normalisation touch data after ? Do training and test targets overlap?" Then suggest the cheapest test: lag every feature by one more period and see whether the result survives.
Key takeaways
- Store every version of a number with the time it became known; join on knowledge time, never on period end.
- Revised macro data, restated fundamentals and vendor backfill are all look-ahead if you use the latest vintage.
- Rebuild the universe and index membership for every date.
- Overlapping windows leak: correlation for shared days of i.i.d. returns.
- Use
ffill(with a limit), neverbfill, interpolation or centred windows, in features; split time series by time with a gap at least as long as the target horizon.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).