How I caught look-ahead bias in my own backtests — and built a free checker

A backtest that looks too good is usually telling you something about the backtest, not about the market.

I learned this the boring way, by auditing our own research pipeline. The code looked fine. Every signal had its lag and every join had a date filter. The audit still found a leak: our fundamentals were filtered by SEC filing date, and a filing date is just a calendar day. Treated as midnight, a report that was actually published after the close that evening looked "known" from the start of the day, hours before anyone could have read it. The same audit flagged two neighbours of that bug. The daily bars were raw, so a stock split looks like a giant one-day move unless it is handled separately. And a stock list can't prove it still contains the companies that later delisted.

None of these show up when you read the code line by line. They are about time, what was known when, and code review is bad at seeing time. So we started checking timestamps instead of reading code, and eventually turned that check into a small free API.

This article walks through:

  1. what look-ahead bias is, in plain words
  2. why it makes backtests look so good
  3. a small runnable example where one missing .shift(1) turns a random walk into a "Sharpe 3.28" strategy
  4. how to catch it automatically by auditing timestamps, using the free NorthStar Backtest Audit API
  5. the before/after comparison
  6. where to get the code

Everything below runs on synthetic prices. Nothing here is a trading idea, a recommendation or a performance claim.

1. What look-ahead bias is (plain version)

Look-ahead bias is when a backtest makes a decision using information that did not exist yet at the moment the decision was made.

In real life you only know the past. At 09:30 on a Monday you know Friday's close, but not Monday's. A backtest is just a loop over historical rows, though, and every row is in memory, including future ones. Nothing stops the code from reading tomorrow's newspaper. It takes one index that is off by one.

Common ways it sneaks in:

2. Why it makes the backtest look so good

Markets are noisy. A real edge, if there is one, is small, and most of each day's move is unpredictable. Look-ahead bias swaps part of that unpredictable move for the answer.

If the signal can see even part of the bar it trades, it is right more often than chance, losses shrink and the equity curve smooths out. Every number you would normally use to judge a strategy gets better together: return, Sharpe ratio, hit rate, drawdown. That is what makes it dangerous. A leaky backtest does not look broken. It looks excellent, and excellent results are the ones we are least motivated to question.

Then the strategy goes live, where the future really is unavailable, and performance falls back to whatever the honest version would have shown.

A useful rule of thumb: when a simple idea on daily bars shows a Sharpe ratio above 2 or 3, check the timing before anything else.

3. A real example: bad_backtest.py

To make this concrete, the companion GitHub repository has a deliberately broken backtest in sample_data/bad_backtest.py.

The setup is intentionally boring:

Here is the core of it:

sma = prices["close"].rolling(20).mean()
above = prices["close"] > sma          # uses close[t] and the SMA up to t

if leak:
    # BUG: row t already contains information from 16:00 on day t,
    # but we act on it at 09:30 on day t.
    signal = above
    feature_ts = prices["close_ts"]
else:
    # FIX: at the open of day t we only know close[t-1].
    signal = above.shift(1)
    feature_ts = prices["close_ts"].shift(1)

session_ret = prices["close"] / prices["open"] - 1
strat_ret = signal * session_ret

The leaky version decides whether to hold during day t by checking whether day t's close is above its average, and then pretends to enter at day t's open, six and a half hours earlier. If today's close is above the average, today was more likely an up day, so the strategy "knows" to be in on up days.

The fix is one .shift(1).

On the same synthetic prices, the leaky backtest reports:

LeakyFixed
Total return82.2%0.5%
Annualized Sharpe3.280.07
Hit rate63.0%50.8%

A Sharpe of 3.28 on a driftless random walk. Every bit of it comes from the bug. The fixed version looks exactly like noise, which is what the data is.

The part that matters: a decision log

Notice that the backtest also records feature_ts. Besides P&L, each run writes a decision log, one row per decision:

decision_log = [
    {"event_time": prices.loc[d, "open_ts"].isoformat(),
     "feature_time": feature_ts.loc[d].isoformat()}
    for d in position.index
]

A decision is only honest if feature_time < event_time. In the leaky run, row 0 says "acted at 2022-01-28 09:30 using data stamped 2022-01-28 16:00". Written down like that, the bug is obvious. Buried in a pandas expression, it was not.

This is the main idea of the article: you can't easily review code for time, but you can check timestamps. If every decision writes down when it acted and when its newest input became known, catching look-ahead becomes a simple comparison.

One detail is easy to get wrong: feature_time should be when the data became available, not the label it carries. A daily bar dated 2022-01-28 is available at 16:00 that day, not at midnight. A quarterly report for the period ending March 31 is available on its filing date, not on March 31.

4. Checking it with the NorthStar Backtest Audit API

You could write that comparison yourself in five lines, and for a single script you probably should. We built a small, free API for it anyway, for two reasons:

  1. Independence. If the code that has the bug also checks for it, the same mistake can easily hide in both places. A separate checker that only sees your timestamps can't share your bug.
  2. More than one rule. Besides the per-row timing rule, it checks train/test label overlap (purging), an optional minimum lag, and an embargo after test folds. Those are easy to get slightly wrong by hand.

It is a plain HTTP endpoint with no API key and no sign-up. The limit is 100 requests per IP per day, up to 2000 rows and 64 KB per request. A minimal call:

import requests

rows = [
    # acted Monday 09:30 using Monday's 16:00 close: impossible
    {"event_time": "2024-03-01T09:30:00-05:00", "feature_time": "2024-03-01T16:00:00-05:00"},
    # acted Monday 09:30 using the previous Friday's close: fine
    {"event_time": "2024-03-04T09:30:00-05:00", "feature_time": "2024-03-01T16:00:00-05:00"},
]
r = requests.post("https://app.xuanduzhixuan.com/audit/lookahead", json={"rows": rows})
print(r.json())

Trimmed response:

{
  "ok": true,
  "status": "failed",
  "feature_status": "failed",
  "purge_status": "not_checked",
  "violations": [{"row": 0, "reason": "feature_not_available_in_time"}],
  "rows": 2,
  "disclaimer": "Data tool only. Not investment advice."
}

Row 0 is flagged, row 1 passes. purge_status is not_checked because these rows have no train/test fold information, so for pure signal timing the field to read is feature_status.

Timestamps must include a timezone (or be Unix seconds). A naive 2024-03-01 09:30 is rejected instead of guessed, because guessing the timezone is a classic way to introduce exactly the bug you are looking for.

Running it on the example

audit_demo.py in the repo runs both backtests, sends each decision log to the endpoint and prints what the backtest claims next to what the audit finds. This is real output against the live API:

LEAKY backtest (uses today's close at today's open)
  backtest says : total return 82.2%, Sharpe 3.28, hit rate 63.0%
  audit says    : feature_status = 'failed', 481 of 481 decisions used data from the future
  e.g. row 0: acted at 2022-01-28T09:30:00-05:00 using data stamped 2022-01-28T16:00:00-05:00

FIXED backtest (signal shifted by one bar)
  backtest says : total return 0.5%, Sharpe 0.07, hit rate 50.8%
  audit says    : feature_status = 'passed', 0 of 480 decisions used data from the future

Every single decision in the leaky run fails, and the audit points to the exact row and the two timestamps that conflict.

The ML version: label overlap

The second half of the demo covers a bug that is subtler and very common in ML backtests. Each sample's label is the return over the next 5 sessions. The data is split 70/30 into train and test by time. That looks clean, but the last few training samples have labels that are only known after the test period has started.

For this check, each row also carries label_end (when the label is fully known), split (train or test) and a fold id:

NAIVE  split: 346 train rows, 149 test rows
  audit says    : status = 'failed', purge_status = 'failed'
  4 training rows have labels that overlap the test period (10 train/test pairs, reason: 'label_overlap')
  e.g. train row 345: label known only at 2023-05-08T16:00:00-04:00, test starts at 2023-05-03T09:30:00-04:00

PURGED split: 342 train rows, 149 test rows
  audit says    : status = 'passed', purge_status = 'passed'

Dropping the four overlapping training rows (purging) fixes it. Four rows out of 346 sounds harmless, but with more overlap, longer horizons or many folds, this kind of leak can inflate cross-validation scores noticeably.

5. Before and after

Here is everything side by side. Same synthetic prices, same strategy idea, same code apart from the fixes:

Leaky backtestFixed backtest
The fixnonesignal.shift(1)
Total return82.2%0.5%
Annualized Sharpe3.280.07
Hit rate63.0%50.8%
Timing audit (feature_status)failed: 481 of 481 decisionspassed: 0 of 480
Naive ML splitPurged ML split
The fixnonedrop the 4 training rows whose labels reach into the test period
Train / test rows346 / 149342 / 149
Purge audit (purge_status)failed: 10 overlapping train/test pairspassed

Two things are worth noticing.

The fixes are tiny. One .shift(1). Four dropped rows. Neither change would stand out in a code review, and neither original bug did either. With timing bugs, the size of the code change tells you nothing about the size of the effect.

The honest result is the boring one. After the fix, the "strategy" looks exactly like what it is: a coin flip on a random walk. If your fixed backtest still shows an edge, good, but that is not proof. The audit only says that the timestamps you logged are consistent. It does not say the strategy works.

What "passed" does and does not mean

The checker is deliberately narrow:

A practical habit that came out of this: put the timing check in CI. Every backtest run writes its decision log, and the build fails if any row has feature_time >= event_time. It costs a few lines and catches the next missing .shift(1) before anyone gets excited about a chart.

6. Get the code

Everything in this article is in one small repository:

GitHub: northstar-backtest-audit-demo

git clone https://github.com/xiaoxue-cyber/northstar-backtest-audit-demo.git
cd northstar-backtest-audit-demo
pip install -r requirements.txt
python audit_demo.py

The demo makes 4 requests to the free API, out of 100 per IP per day.

Further reading:

If you find a mistake in the demo, open an issue. I would rather fix the example than have it teach the wrong thing.


Disclosure: I'm part of the NorthStar team, which runs the Backtest Audit API. The API is free and needs no key. All data in this article and the repository is synthetic. This is a data-tool article, not investment advice.