Look-ahead bias in backtesting means the strategy decides on a bar using data that was not available yet when that bar closed. The backtest then trades on information nobody had, so the result looks far better than anything you can get live. The usual cause is a one-line slip: a shift in the wrong direction, a statistic taken over the whole series, or a higher-timeframe bar read before it has closed.
The rule every backtest must keep
Bar i may only use data up to bar i. A decision made when bar i closes can use that close and everything before it. It cannot use bar i+1, and the order it creates cannot fill at a price that has already passed.
Lookahead bias is dangerous because it does not look like a bug. The code runs, the equity curve is smooth, and the numbers are exciting. The five examples below are short on purpose. In each one, o and c are numpy arrays of open and close prices, and the bug is a single line.
1. The shift that goes the wrong way
To compare a bar with its neighbour you shift the series by one. Shift it the wrong way and every bar is compared with the bar after it.
# bug: nxt[i] is the close of bar i+1 nxt = np.roll(c, -1) go = nxt > c # "buy when the next close is higher" # fix: compare with the bar before, never the bar after prev = np.roll(c, 1) prev[0] = np.nan go = c > prev
np.roll(c, -1) moves every value one place earlier, so position i holds tomorrow's close. In pandas the same mistake is shift(-1). A negative shift on price data is almost always lookahead. Note that np.roll also wraps around, so the first value of prev would be the last close of the whole series; that is why the fix overwrites it with NaN.
2. Filling at the close that produced the signal
This one has no future index in it, which is why it survives code review. The signal is computed from the bar's close, and the trade is booked at that same close.
sig = c > ema # true only once bar i has closed # bug: buy at the same close that produced the signal entry = c[sig] # fix: the first tradable price is the next bar's open idx = np.flatnonzero(sig[:-1]) entry = o[idx + 1]
A close is only known once the bar has ended. At that moment the price is gone, and the first price you can really trade is the open of the next bar. The gap looks tiny, but it is paid on every trade, and it always goes one way: breakout and momentum signals fire exactly on the bars that closed far from where they opened. A worse version of the same bug computes the signal from the bar's high or close and fills at that bar's open. On OptAlgo, fills happen at the next bar's prices, never the signal bar's.
3. Normalising with whole-series statistics
Z-scores and min-max scaling need a mean, a standard deviation, a minimum or a maximum. If those are computed over the full history, every bar knows how high and how low price will ever go.
# bug: mean and std are taken over the whole series, future included z = (c - c.mean()) / c.std() # fix: statistics from the trailing n bars only w = np.lib.stride_tricks.sliding_window_view(c, n) z = np.full(len(c), np.nan) z[n - 1:] = (c[n - 1:] - w.mean(axis=1)) / w.std(axis=1)
With the buggy version, a z-score of -2 in 2022 already knows where the 2025 prices are. A mean reversion rule built on it buys bottoms it could not have recognised at the time. The same applies to (c - c.min()) / (c.max() - c.min()), to percentile ranks over the whole array, and to any scaler fitted once on all the data. The fix is always the same: compute the statistic from a trailing window that ends at the current bar.
4. Centred rolling windows
A centred moving average takes half of its bars from the left and half from the right. It looks smoother and turns earlier than a trailing average, and that is the problem: it turns early because it has seen the turn.
k = np.ones(n) / n # bug: mode="same" centres the window, so bar i reads n // 2 future bars smooth = np.convolve(c, k, mode="same") # fix: trailing window that ends at bar i valid = np.convolve(c, k, mode="valid") smooth = np.concatenate([np.full(n - 1, np.nan), valid])
In pandas the same bug is rolling(n, center=True). Many smoothing and peak-finding functions centre by default, and zig-zag style indicators that mark tops and bottoms after the fact do the same thing in a different form. They are fine for drawing a chart of the past. They cannot be used to make a decision.
5. A higher-timeframe bar used before it has closed
A common design trades on 1h bars and filters by the 4h trend. The 4h bar that starts at 00:00 does not close until 04:00. If the 1h bar at 01:00 reads that 4h bar's close, it is reading three hours into the future.
# c: 1h closes; every 4 bars form one 4h bar c4 = c.reshape(-1, 4)[:, -1] # close of each 4h bar # bug: each 1h bar reads the 4h bar it sits inside, before that bar has closed htf = np.repeat(c4, 4) # fix: read the last 4h bar that had already closed htf = np.concatenate([np.full(4, np.nan), np.repeat(c4, 4)[:-4]])
This bug usually arrives through a join: you resample to 4h, then merge back onto the 1h index by the bar's start time. The fix is to align each higher-timeframe value to the moment its bar closed, and to let a lower-timeframe bar read only values that were already complete. The same rule covers daily data in an intraday strategy, and any external series that is published with a delay.
How to detect it: remove the later bars
All five bugs fail one test. A strategy without lookahead makes the same decision at bar i whether the data ends at bar i or continues for another year. So cut the data at bar i, run the same code and compare.
full = signal(c) # decisions on the whole history
for i in sample_bars:
cut = signal(c[: i + 1]) # same code, data ends at bar i
assert cut[i] == full[i], f"bar {i} looks ahead"If the decision at bar i changes when the bars after it are removed, the code was reading those bars. You do not need to know which line is guilty to know the backtest is wrong. Test a sample of bars spread across the history, and always include bars where the strategy traded.
Here is what that looks like in practice. On OptAlgo, a strategy that compared each bar with the next bar's close was built with this line:
nxt = np.concatenate([c[1:], c[-1:]])
Free validation refused it before any backtest ran, with this finding: “the strategy looks ahead: enter at bar 1607 changes when the bars after 1607 are removed (bar i may only use data up to bar i)”. The suggested fix was to “use indicators.shift(x, 1) for the previous bar”. Nothing was charged, and no return figure was ever shown for it.
How OptAlgo runs this check
Every run has to prove that it decides the same with the future removed before its numbers count. The engine runs the strategy again on data cut at 6 evenly spaced and 6 random bars of the last 3,000, and re-decides up to 24 bars where it entered, exited or set a target, on data that ends at that bar. It also runs the same parameters twice to prove the code is deterministic. Any difference is lookahead: the run gets honesty grade D and can never be deployed. Validation runs the same check on synthetic bars for free.
Know its limits too. It samples bars and does not re-run every one, and plots are not checked. Example 2 is handled in a different place: the engine decides where an order fills, so strategy code cannot book a trade at the signal bar's close.
What a lookahead check does not tell you
A strategy with no lookahead can still be worthless. Parameters tuned on one window can look great without reading a single future bar. That is overfitting, and it needs different tools: a walk-forward test, a holdout and a count of how many variants you tried. The backtest overfitting guide covers them. And no check removes the risk of trading: a clean backtest describes the past, not the next month.
A short checklist for your own code
- Search for negative shifts: np.roll(x, -1), shift(-1), x[1:] lined up against x[:-1].
- Search for whole-array statistics: mean(), std(), min(), max(), percentile ranks, scalers fitted on all the data.
- Search for centred windows: center=True, mode="same", smoothing filters, zig-zag and pivot indicators.
- Check every join between timeframes or data sources. Each value must be stamped with the time it became known.
- Check where orders fill. A signal from a bar's close fills at the next bar.
- Run the cut test on sample bars. If a result looks too good, run it first.
Frequently asked questions
What is look-ahead bias in backtesting?
Look-ahead bias is a backtest error where a decision uses data that was not yet available at the time, such as the next bar's price or a statistic computed over the whole history. It inflates the backtest result and disappears in live trading.
What is an example of lookahead bias?
Shifting a price series with a negative shift, so each bar is compared with the bar after it. Other common examples are z-scores that use the mean of the whole series, centred moving averages, and reading a 4-hour bar's close from a 1-hour bar inside it.
How do I detect lookahead bias in my backtest?
Cut the data at a bar, run the same strategy code and compare the decision at that bar with the one from the full history. If it changes when the later bars are removed, the strategy looks ahead. Repeat this for a sample of bars, including bars where it traded.
Is entering at the close of the signal bar lookahead bias?
Yes. The close is only known when the bar has ended, and by then that price can no longer be traded. A realistic backtest fills the order at the next bar.
Is lookahead bias the same as overfitting?
No. Lookahead bias is a coding error that leaks future data into a decision. Overfitting is tuning parameters until they fit past noise, and it can happen with no lookahead at all. A backtest has to be checked for both.