Lookahead bias is any place where information enters a backtest decision before the moment it would actually have been available to trade on. It never announces itself: it hides in the default behaviour of dataframes, databases and data vendors, and it is never neutral — it always inflates the result, because the future it leaks is precisely the future you're trying to predict.
The idea
Here is the uncomfortable truth this module is built on: the most dangerous bugs in a backtesting framework don't crash. A crash costs you an afternoon. A lookahead bug hands you a beautiful equity curve, lets you trade real money on it, and only reveals itself as the slow, grinding gap between your backtest and your live P&L — by which point it has cost you months and a chunk of capital. You are a software engineer, so let me put it in your language: lookahead is a race condition between information and time, and like most race conditions it lives in the glue code, not in the logic you were paying attention to.
The single question that kills lookahead is: at the moment this decision was made, was this number knowable? Not "was it dated then" — knowable. Almost every variety below is a gap between a datum's event time (the period it describes) and its knowledge time (the moment a trader could have seen it). Databases index on event time because that's what the data is about. Backtests must join on knowledge time because that's when you could have acted. Every join that confuses the two leaks the future.
Let's walk the taxonomy. For each member I'll tell you exactly where it hides in a framework like the one you've already built, because the abstract definition is useless — you don't have "lookahead bias" in general, you have a specific wrong join on line 214.
1. Restatement lookahead. Companies revise their accounts. Earnings get restated, sometimes dramatically; GDP figures are revised for years after first release. Most convenient fundamentals databases store the final, cleaned-up number under the original period. So your backtest, sorting stocks on "Q1 2015 earnings", is using the version of Q1 2015 that was only settled in a restatement filed that October — and restatements are not random noise. A company that restates earnings downward is often a company about to perform badly; your backtest quietly knew that in advance. The fix is point-in-time (as-first-reported) fundamentals, which store every vintage of every number with the date each vintage became public. Institutional vendors sell exactly this because the bias is large enough that professionals pay for the cure; if you can't get PIT data, at minimum you must know your database is restated and treat any fundamentals-driven result with suspicion proportional to how much it depends on accounting lines that get revised.
2. As-of-date lookahead. Subtler and far more common. Even
never-restated data has two dates: the period it covers and the day it was
published. A vendor's date column on annual fundamentals typically says
December 31 — but the 10-K containing those numbers was filed the following
February or March. If your framework does the obvious thing —
# the sin: joining fundamentals on their period-end date
panel = prices.merge(fundamentals, on=["ticker", "date"])
— then every January and February your backtest trades on accounts that
don't exist yet. The professional convention when release dates are missing
is a conservative fixed lag (a common choice for annual accounts is
several months, in the spirit of the classic Fama-French June-rebalance
timing), but the real fix is structural: every table in your data layer
gets two timestamp columns — event_time and knowledge_time — and every
join in the backtest is an as-of join on knowledge_time:
# the fix: as-of join on the date the information became public
panel = pd.merge_asof(
prices.sort_values("date"),
fundamentals.sort_values("release_date"),
left_on="date", right_on="release_date",
by="ticker", direction="backward",
)
merge_asof(..., direction="backward") means "the latest value whose
knowledge time is on or before now", which is the only join a backtest
should ever perform. If a table lacks a knowledge time, you must invent a
conservative one, in writing, before running anything.
3. Universe lookahead. Deciding which assets to test on is itself a signal, and it's the easiest place to smuggle in the future. Backtesting on the current constituents of an index means backtesting on companies selected — by the index committee, with full hindsight — for having survived and grown. Backtesting "the top 100 coins by market cap today" back through 2017 is the same sin in a louder shirt. The universe at each backtest date must be the universe you could have written down on that date. This one is so important it shares a wall with survivorship bias, and lesson 2.2 gives it a full treatment.
4. Signal-timestamp versus tradeable-timestamp. You compute a signal
from today's close, and your backtest buys… at today's close. That trade is
impossible: by the time the close exists you cannot trade at it. In pandas
this is one missing shift:
# impossible: position held during the return that produced the signal
pnl = signal * returns
# honest: decide after observing, hold over the NEXT period
pnl = signal.shift(1) * returns
One line, and it is the single most consequential line in any vectorised backtest. The classic self-inflicted demo is short-term reversal: build a "buy yesterday's losers" signal and forget the shift, and the strategy appears to earn absurd returns — because without the shift it is literally buying yesterday's losers yesterday, at prices it selected for being low. As an illustration of scale (this is arithmetic, not an empirical claim): a signal that merely picks up mean reversion with a one-day timing error captures the entire bounce instead of the tradeable remainder of it, and daily mean-reversion effects are large gross — misalignment can turn a marginal idea into an apparent Sharpe of 3. Any backtest Sharpe that makes you feel euphoric should make you first suspect this line. Related choices you must make explicitly, not by default: if you observe the close, do you trade the next open or the next close? The gap between those two answers is overnight risk, and your backtest must pick the one your live system will actually do.
5. Intraday sins inside daily bars. A daily bar tells you the open, high, low and close, but not when the high and low happened. Any rule that references the high or low of the bar it's trading within is peeking: "buy at the day's low", stop-losses that fill exactly at the stop price (in reality: gapped through, filled worse), profit targets that assume the high came after your entry rather than before it. If your logic is intraday, backtest on intraday data; if you only have daily bars, the honest convention is to trade at the next bar's open and treat stops as executing at the worse of the stop level or that open.
6. The vectorised-backtest sin: full-sample statistics. The quiet one.
Any quantity computed over the whole sample and then used at every date is
lookahead — even innocuous-seeming normalisations. Z-scoring a signal by
its full-sample mean and standard deviation tells the 2015 version of your
strategy how volatile the signal will be in 2022. Sorting on betas
estimated over the full sample (the exact sin dissected in lesson 5.5).
And for the machine-learning readers: scaler.fit_transform(X) on the
whole matrix before a train/test split leaks the test set's distribution
into training — a bug so common it's practically a rite of passage. The
rule: every statistic a decision depends on must be computed from an
expanding or rolling window that ends strictly before the decision. López
de Prado's backtesting chapters (López de Prado 2018) treat this
family of sins at length, and the pseudo-mathematics paper
(Bailey, Borwein, López de Prado & Zhu 2014) is the reference for
why the resulting inflated backtests are so seductive.
The maths
One formalism earns its place, because it turns "be careful" into a checkable property. Let be the information set at time — everything knowable by then (its knowledge time, not event time). A backtest is honest if and only if two conditions hold for every trade:
Everything in the taxonomy above is a violation of one of these two conditions: sins 1–3 and 6 violate the first (the signal contains un-knowable data), sins 4–5 violate the second (execution slips backward to or before the decision). When you audit a framework, you are checking these two properties, table by table and trade by trade.
Worked example
Take a concrete strategy: monthly, long the cheapest decile of stocks by earnings yield, within an index universe, positions entered at month-end. Here is the audit, sin by sin, as a table you can adapt as a template:
| # | Sin | Where it hides here | The check |
|---|---|---|---|
| 1 | Restatement | Earnings column holds restated values | Does the vendor document as-reported vintages? |
| 2 | As-of date | Earnings joined on fiscal period end | Is the join merge_asof on release/filing date? |
| 3 | Universe | "Index members" = today's list | Is membership point-in-time? |
| 4 | Signal vs trade | Ranked on month-end close, filled at same close | Is there a shift? Fill at next open? |
| 5 | Intraday | Any stop-loss on daily bars | Do stops fill at the worse of stop and next open? |
| 6 | Full-sample stats | Yield z-scored by full-history mean/sd | Are all normalisations rolling/expanding? |
Now the most useful single diagnostic I know: the lag stress test. Run the identical backtest with execution delayed by 0, 1, 2, 5 days and watch the Sharpe:
for lag in [0, 1, 2, 5]:
pnl = signal.shift(1 + lag) * returns # 1 honest day + extra lag
print(lag, sharpe(pnl))Read the resulting curve like a doctor reads an X-ray. A genuine slow-moving edge (value, trend) barely notices a few days of lag. A result that collapses from Sharpe 1.5 to 0.2 with one extra day of delay is telling you its profits live inside a one-day window around the signal — which means either it was leaking (sins 4–6) or it is a genuine but hyper-fast effect that your monthly, retail-latency implementation was never going to capture anyway. Either way, you just learned the truth for the price of a for-loop.
How you'd use it
Make the audit structural, so it doesn't rely on your vigilance at 11pm:
- Two timestamps on every table.
event_timeandknowledge_time, populated at ingestion, withknowledge_timeset conservatively (late) whenever the vendor is vague. This is the single highest-leverage change you can make to a data layer. - One blessed join. All feature construction goes through a single
as-of-join utility that only reads
knowledge_time. Grep your codebase for othermerge/joincalls on data tables and treat each as a bug until proven otherwise. - Execution lag as a first-class parameter. The backtester takes
delayas an argument, defaulting to at least one bar, and the lag stress test runs automatically in every research report. - A shuffle test as the null. Randomly permute your signal's dates and re-run. The permuted backtest should earn nothing; if it earns something, your harness itself leaks, independent of any signal.
- Backtest–live reconciliation (the subject of lesson 10.1) as the final backstop: the live system computes signals with only the data it actually has, and any systematic gap between its decisions and the backtest's decisions on the same dates is a leak alarm.
What goes wrong
The vendor backfills under you. You verified the data in 2024; in 2025 the vendor "improves history" — filling gaps, correcting errors, adding delisted names — and your reproducible backtest silently changes. Snapshot your inputs (or version them) so that every result is pinned to a data vintage. This is ordinary engineering discipline applied where it's unfashionable.
Corporate-action adjustment with today's factors. Adjusted price series bake the full history of splits and dividends into the past. Prices are fine for returns, but any rule referencing price levels — "stocks under $5", round-number effects — must use unadjusted prices as they appeared at the time. An adjusted series can put a 1990s stock "under $5" that traded at $60.
Timezones and closing times. Trading a global universe against a signal built from US data means some markets' "same day" closes happened before your signal existed and some after. Every daily timestamp on a global asset should really be an instant in UTC, and the as-of join handles the rest. If your framework stores naive dates for multi-region data, assume there's a leak until proven otherwise.
The leak that survives because it flatters. The last failure mode is psychological, and it's the reason this lesson is in a module called Not fooling yourself: a leak that inflates results faces no natural predator. A bug that hurts the backtest gets found, because you go hunting for why performance is bad. A bug that helps it gets published, sized up, and traded. The asymmetry means your debugging effort must be deliberately pointed at your winners — the better the backtest, the harder it should be interrogated. Suspicion proportional to beauty is the discipline; the rest of this module builds the tools for it.