Backtest Too Good After Resample: Find the Lookahead Leak
A backtest that looks too good after resample almost always leaks the future: a bar stamped at its start is forward-filled onto lower-timeframe rows, so every minute already knows the bar's close. Shift the signal one bar, then re-test.
- A truncation test (recompute signals on data cut at time T and compare them with the full-data signals before T) proves leakage in about a minute.
- A left-stamped resampled bar holds data up to its end, so it must be shifted by one bar, or relabelled to its close time, before it is mapped onto finer data.
- Use merge_asof with direction='backward' on bar-close (availability) timestamps. 'nearest' and 'forward' always leak.
- Shifting the signal one extra bar and watching the returns collapse is a strong confirmation, and a Sharpe above about 3 on liquid instruments is a red flag.
- Rule out non-leak causes too: overlapping or compounded returns, zero costs, and timezone or session cuts that move the daily boundary.
Is your backtest too good after resample? How do I prove the leak in one minute?
Run the truncation test before reading any theory. A causal signal at time t depends only on rows up to t. If you drop all rows after T and recompute, every signal value at or before T must be identical to the full-data run.
Leaks fail this test because the last resampled bar in a truncated dataset is incomplete, so its value differs from the complete bar in the full run. A leaky pipeline hands that bar's value to earlier rows, and those rows change.
- Wrap your whole signal pipeline (resample, indicator, reindex, ffill) in one function that takes prices and returns a signal on the finest index.
- Pick many cut times T in the middle of higher-timeframe bars, for example every 60 minutes at minute 37 across several days, not at bar boundaries. A single cut can agree with the full run by chance.
- Compute full = fn(prices) and part = fn(prices.loc[:T]) for each cut.
- Compare full.loc[:T] with part. Any difference means the signal at an earlier time used data after it. A leaky pipeline should mismatch on at least one cut, and a clean one on none.
- Shift the signal by one extra bar. If the Sharpe collapses from implausible to near zero, the edge was the leak.
Why does resampling and forward-filling leak the future?
resample('1D') stamps each bar with its start, 00:00. The value in that row, such as close, high, low or any indicator built on them, is only known at 23:59. Reindexing to 1-minute rows with ffill copies that value onto every minute from 00:00, so the 09:31 trade already knows the day's close, high and low.
The same happens with 1h bars at 10:00 holding data through 10:59. The bar must only become visible when it ends, which is its availability time, not its label.
The defaults also bite. Most frequencies use label='left' and closed='left', but end-anchored ones ('M', 'Q', 'Y' and in pandas 2.2+ 'ME', 'QE', 'YE', plus 'W') default to right/right. Mixing a daily and a monthly resample in one pipeline therefore mixes start-stamped and end-stamped bars, which silently shifts one of them by a period.
| resample settings | Bar stamp means | Safe to ffill onto finer bars? | What to do |
|---|---|---|---|
| label='left', closed='left' (default for 1min, 1h, 1D) | Bar start, contents run to the end | No, leaks the whole bar | shift(1) before reindex |
| label='right', closed='left' on open-stamped data | Bar end, contents are [start, end) | Yes, available at the stamp | Fill, then trade at next bar open |
| label='right', closed='right' on open-stamped data | Bar end, but includes the row stamped at the end | No, leaks 1 fine bar | Use closed='left' instead |
| label='right', closed='right' on close-stamped data | Bar end, contents are (start, end] | Yes | Fill, then position = signal.shift(1) |
| 'ME', 'QE', 'YE', 'W' defaults (right/right) | Period end | Only if the data is close-stamped | Set label and closed explicitly |
| Left-labelled bars with shift(1) before ffill | Previous complete bar | Yes | Common daily pattern |
Which causes should I check first, ranked?
Ranked by how often they produce a too-smooth curve in resampled pipelines, with the quickest check for each:
| Rank | Cause | Symptom | Quick check |
|---|---|---|---|
| 1 | Left-stamped bar ffilled without shift | Trades enter at exact bar lows and highs | Truncation test |
| 2 | Indicator on resampled series, reindexed without shift (rolling mean, RSI, pct_change) | Great results on the one timeframe only | Add shift(1) to the resampled indicator |
| 3 | Signal and fill on the same bar | Edge vanishes with a 1-bar delay | position = signal.shift(1) |
| 4 | bfill, interpolate, rolling(center=True), nearest/forward joins | Smooth equity, and signals that change when future rows are removed | Search code for these calls |
| 5 | Day boundary at midnight UTC rather than the exchange close | Daily bar mixes two sessions | Print first and last row of a daily bar |
| 6 | Zero costs, spread and slippage | High turnover looks great | Apply 1 to 5 bps per side as a test |
| 7 | Overlapping or compounded returns on low-frequency data | Smooth curve, inflated Sharpe | Use non-overlapping returns |
What does a leaky vs fixed pipeline look like in pandas?
The script below uses a pure random walk, so there is no real edge and the honest Sharpe should be near zero, within noise. The leaky version trades the sign of the current day's return from midnight onward. The fixed version shifts the daily signal one bar before the fill.
Run it yourself and compare the two printed Sharpe ratios. The leaky one typically comes out absurdly high and the fixed one hovers around zero, and the exact values depend on the seed.
The helper at the bottom runs the truncation test on 720 mid-day cuts, one every 60 minutes across the first 30 days. It counts how many cuts change the signal. The fixed function must show zero mismatches, and the leaky function must show at least one.
import numpy as np
import pandas as pd
def make_close(days=90, seed=0):
idx = pd.date_range('2024-01-01', periods=days * 1440, freq='1min', tz='UTC')
r = np.random.default_rng(seed).normal(0, 0.0004, len(idx))
return pd.Series(100 * np.exp(np.cumsum(r)), index=idx)
def leaky_signal(close):
daily = close.resample('1D', label='left', closed='left').last() # stamped 00:00, holds 23:59 close
sig = np.sign(daily.pct_change())
return sig.reindex(close.index, method='ffill').fillna(0)
def fixed_signal(close):
daily = close.resample('1D', label='left', closed='left').last()
sig = np.sign(daily.pct_change()).shift(1) # known only once the day is over
return sig.reindex(close.index, method='ffill').fillna(0)
def backtest(close, signal, cost_bps=0.0):
pos = signal.shift(1).fillna(0) # signal at t fills at t+1
ret = close.pct_change().fillna(0)
strat = pos * ret - pos.diff().abs().fillna(0) * cost_bps / 1e4
d = strat.resample('1D').sum()
sharpe = d.mean() / d.std() * np.sqrt(365)
return (1 + strat).cumprod(), sharpe
def count_lookahead_mismatches(fn, close, cuts):
"""Number of cuts where the signal before the cut changes when later rows are removed."""
full = fn(close)
bad = 0
for t in cuts:
part = fn(close.loc[:t])
if not full.loc[:t].equals(part):
bad += 1
return bad
close = make_close()
for name, fn in [('leaky', leaky_signal), ('fixed', fixed_signal)]:
curve, sh = backtest(close, fn(close), cost_bps=1.0)
print(name, 'Sharpe', round(sh, 2), 'final equity', round(curve.iloc[-1], 3))
# mid-day cuts: every 60 minutes at minute 37, across the first 30 days (720 cuts)
cuts = close.index[37:30 * 1440:60]
n_fixed = count_lookahead_mismatches(fixed_signal, close, cuts)
n_leaky = count_lookahead_mismatches(leaky_signal, close, cuts)
print('mismatching cuts, fixed:', n_fixed, '| leaky:', n_leaky, 'of', len(cuts))
assert n_fixed == 0, 'fixed_signal should be causal'
assert n_leaky >= 1, 'leaky_signal should change on at least one cut'How do I map higher-timeframe signals onto lower-timeframe bars safely?
There are three safe patterns. The first is the one above: compute on left-stamped bars, shift(1), then reindex with ffill. The second is relabelling bars to their close time.
For open-stamped 1-minute data use label='right', closed='left', so a bar covering [09:00, 10:00) is stamped 10:00. Do not use closed='right' on open-stamped data, because the row stamped 10:00 is a minute that has not happened yet at 10:00 and would leak one fine bar. Use closed='right' only when your fine data is close-stamped.
The third is merge_asof on an explicit availability column. It makes the rule visible: each fine row takes the latest bar that had already ended.
bars = close.resample('1h', label='left', closed='left').agg(['first', 'max', 'min', 'last'])
bars['sig'] = np.sign(bars['last'].pct_change())
bars['avail'] = bars.index + pd.Timedelta('1h') # when the bar is complete
fine = close.rename('px').reset_index().rename(columns={'index': 'ts'})
out = pd.merge_asof(
fine.sort_values('ts'),
bars[['avail', 'sig']].sort_values('avail'),
left_on='ts', right_on='avail',
direction='backward', # never 'nearest' or 'forward'
)
signal = out.set_index('ts')['sig'].fillna(0)
# then: position = signal.shift(1), exactly as in backtest() What about Backtrader, vectorbt, timezones and non-leak causes?
In Backtrader, cerebro.resampledata(data, timeframe=bt.TimeFrame.Days) adds the higher timeframe as a second data feed. The daily bar is delivered only once its period has completed, so reading data1 from next() sees the previous finished day. Orders submitted in next() fill at the next bar's open by default.
In vectorbt, the output of resample_apply must be realigned to the fine index. realign_closing places each higher bar at the time it closes, which is safe. realign_opening places it at its open and leaks completed-bar values. Use ffill=True to carry values forward, and keep the one-bar delay on the position. For the fill-timing rule itself, see the next-bar open article.
Timezone and session cuts matter because resample('1D') cuts at 00:00 in the index timezone. For a US equity it merges the close of one session with the overnight session of the next. Convert with tz_convert('America/New_York') first, or use offset='9h30min' or origin on resample, so the daily bar matches the exchange session. DST handling is covered in the DST article.
After the leaks are gone, two smoothness causes remain. Overlapping returns, such as 20-day returns sampled daily, and compounding on low-frequency data make a curve look smoother than the strategy is. Zero costs also flatter high turnover, so rerun with cost_bps of 1 to 5 per side and check that the curve survives. A Sharpe above about 3 on liquid instruments, or entries sitting at exact bar lows, should send you back to the truncation test.
Common questions
Is resample label='right', closed='right' always the fix?
No. It is safe only when your fine data is close-stamped, so the bar (start, end] contains only rows up to its stamp. On open-stamped minute data, closed='right' pulls in the row stamped at the bar end, so use closed='left' with label='right'. Trade on the following bar either way.
Why does shift(1) on the resampled series work but shift(1) after ffill does not?
After ffill, shift(1) moves the signal by one minute, but every minute in the day still carries the day's close. Shifting before the reindex moves it by a full bar, so the value appears only after the bar ends. Do the bar-level shift first and the execution-level shift second.
Can rolling(center=True), bfill or interpolate ever be used in a backtest?
Not for anything that feeds a trading signal. A centred window reads half its values from the future, bfill pulls later values backward, and interpolate uses both neighbours. They are fine for plotting or for post-hoc analysis that is never fed back into decisions.
Does the truncation test catch every leak?
It catches leaks where a past signal depends on future rows, which covers resample, ffill, centred windows and merge direction mistakes. It cannot catch same-bar execution, because the signal itself is causal there. Cover that with the extra-bar shift test and the position = signal.shift(1) rule.
How do I compare against a loop on expanding data?
For each timestamp t, compute the signal using only prices.loc[:t], keeping the last value, and compare it to the vectorised signal at t. It is slow, so run it on a few hundred sampled timestamps. Any mismatch points to the exact row and the operation that used future data.