Backtest Next Bar Open Execution: Fix Same-Bar Fills
Backtest next bar open execution means a signal computed at the close of bar t is filled at the open of bar t+1. In pandas, shift the position by one bar. Filling at the signal bar's own close is look-ahead bias.
- A signal built from bar t's close can only be filled at bar t+1's open or later, so the position series must be signal.shift(1).
- shift(-1) on a signal or position pulls future data into the present and is always a leak.
- Backtrader and backtesting.py fill at the next open by default; cheat_on_close (set_coc), cheat_on_open and trade_on_close=True switch to same-bar fills.
- vectorbt from_signals fills at close by default, so you must shift the signals or pass price=open yourself.
- Next-open fills still ignore gaps, auction prints, slippage, fees and partial fills, so test with a shift(2) delay and explicit cost assumptions.
Why is a same-bar close fill look-ahead bias?
A bar's close is only known when the bar ends. If your signal is a function of that close (an SMA cross, an RSI threshold, a breakout of the close), the signal does not exist until the final print has happened. Filling at that same close assumes you traded at a price that you only learned after trading.
The damage is specific. The move from close t-1 to close t is what pushed the indicator across its threshold. A same-bar fill books that move as profit, so the strategy appears to predict the very move that created the signal. That is why results look too good, and why the effect is largest on momentum and breakout rules.
The realistic timeline for a close-based signal on bar t:
| Step | Time | What is known |
|---|---|---|
| Bar t closes | Close of t | Final OHLCV of bar t |
| Signal computed | Just after close of t | Indicator values using data up to t |
| Order submitted | After close of t | Nothing from t+1 |
| Earliest market fill | Open of t+1 | Fill price is the t+1 open plus slippage |
How do I implement backtest next bar open execution in pandas?
The rule is that the position held during bar t may only depend on information available at the close of bar t-1. So you shift the signal forward in time, never backward. Positive shift(1) moves each value to the next row.
Below are the leaky version for comparison, the close-to-close variant and the open-to-open variant.
import pandas as pd
# df has columns: open, high, low, close, indexed by timestamp
fast = df.close.rolling(10).mean()
slow = df.close.rolling(30).mean()
signal = (fast > slow).astype(int) # known at close of bar t
# WRONG (look-ahead): signal at close t earns the return into close t
leaky = signal * df.close.pct_change()
# Close-to-close, one bar delay: position decided at t-1 close
position = signal.shift(1).fillna(0)
ret_cc = position * df.close.pct_change()
# Open-to-open: the signal from close t-1 is filled at open t,
# and the position is held from open t to open t+1.
ret_oo = signal.shift(1).fillna(0) * (df.open.shift(-1) / df.open - 1)What does the shift change? A worked example
Take three bars. Bar 2 closes at 103 after a gap up and rally, which makes the SMA cross. Bar 3 opens at 103.8 and closes at 102.9. Bar 4 opens at 102.5.
The numbers differ sharply by method:
| Bar | Open | Close | Signal at close |
|---|---|---|---|
| 1 | 99.5 | 100.0 | 0 |
| 2 | 101.0 | 103.0 | 1 (cross) |
| 3 | 103.8 | 102.9 | 1 |
| 4 | 102.5 | - |
Same-bar versus next-open results on those bars
Same-bar fill (leak): the position earns close 1 to close 2, which is 103/100 - 1 = +3.00%. That is exactly the move that created the signal.
Shift(1) close-to-close: the position starts at close 2 and earns close 2 to close 3, which is 102.9/103 - 1 = -0.10%. This is only valid if you could trade at close 2, which you could not.
Next-open fill: you buy at 103.8 and, held to the next open, earn 102.5/103.8 - 1 = -1.25%. The 103.8/103 - 1 = +0.78% overnight gap is paid by you, not earned. The same signal swings from +3.00% to -1.25%, and none of that difference is skill.
| Method | Entry price | Period captured | Return |
|---|---|---|---|
| Same-bar close (leak) | 100 to 103 move | Close 1 to close 2 | +3.00% |
| Shift(1), close fill | 103.0 | Close 2 to close 3 | -0.10% |
| Next-open fill | 103.8 | Open 3 to open 4 | -1.25% |
How do Backtrader, backtesting.py, vectorbt and Zipline/Lean handle fills?
Each framework has a default and a switch that reintroduces the same-bar trap. Know both before trusting a result.
Backtrader: a market order issued in next() on bar t executes at the open of bar t+1. The flags cheat_on_open (Cerebro(cheat_on_open=True), with logic in next_open()) and broker.set_coc(True) (cheat on close) fill on the current bar, so leave them off. On daily data, a pitfall is sizing from data.close[0] in next(): the order fills at tomorrow's open, which can be higher, so cash may be insufficient and the order is Margin-rejected. Size with a buffer or a percentage sizer.
backtesting.py: Backtest(data, Strat, trade_on_close=False, exclusive_orders=True) fills at the next bar's open by default. trade_on_close=True fills at the current close, which is the look-ahead trap for close-based signals. exclusive_orders=True makes each new order close the existing position first, avoiding silent stacking of positions.
vectorbt: Portfolio.from_signals defaults to price=close, so entries and fills share a bar. Either shift the signals (entries.vbt.fshift(1)) or pass price=open together with signals shifted by 1. Passing price=open without the shift is still a leak, because the signal bar's open precedes the information.
Zipline and QuantConnect Lean: orders placed in handle_data (Zipline) or OnData (Lean) at bar close fill on the following bar's price. Fill behaviour is configurable: Zipline has slippage models such as FixedSlippage and VolumeShareSlippage plus commission models like PerShare. Lean has fill models per security. Daily-resolution market orders fill at the next available price, but always verify the fill timestamps in the order log.
| Framework | Default fill | Same-bar trap switch | Safe setting |
|---|---|---|---|
| Backtrader | Next bar open | cheat_on_open, set_coc(True) | Both off |
| backtesting.py | Next bar open | trade_on_close=True | False |
| vectorbt | Current close (price=close) | Not shifting signals | fshift(1) or price=open with shifted signals |
| Zipline | Next bar price | Custom same-bar logic | Default slippage and commission models |
| Lean | Next data point | Custom fill model | Review the order event timestamps |
import backtrader as bt
cerebro = bt.Cerebro(cheat_on_open=False)
cerebro.broker.set_coc(False)
from backtesting import Backtest
bt_run = Backtest(data, Strat, trade_on_close=False,
exclusive_orders=True, commission=0.0005)
import vectorbt as vbt
pf = vbt.Portfolio.from_signals(
close=df.close, entries=entries.vbt.fshift(1),
exits=exits.vbt.fshift(1), price=df.open, fees=0.0005) What do next-open fills still get wrong?
Next-open fills remove the leak but not unrealism. The remaining errors are usually smaller than the leak but compound.
Gaps: the open can differ from the prior close in either direction. The example above shows +0.78% against the buyer, and a short or stop would see the mirror case. A stop at 98 that gaps to 96 fills near 96, not 98, so model stop fills at min(open, stop) for longs, never at the stop price when the bar opens through it.
Auction prints: the data's open is often the opening auction price on the primary exchange. Retail market orders submitted at 09:30 typically cannot hit that print, so the realistic fill is the first few seconds of continuous trading, adding spread and slippage.
Costs: use at least commission plus slippage. Common models are a fixed number of ticks per side, a percentage of price (for example 0.05% to 0.10%), a share of bar volume (cap fills to a fraction of volume, as with Zipline's VolumeShareSlippage), or half the quoted spread. Partial fills happen when order size is a meaningful share of volume.
Limit and stop orders: fill a limit buy only if the bar's low trades through it (low < limit; touching it is not a guaranteed fill in a queue). If a stop and a target are both hit inside one OHLC bar, take the conservative path and assume the stop hit first.
Latency and timeframe: with intraday bars the next open is close to the real fill, but on daily bars the delay is a whole session. A finer-timeframe replay (for example, signals on daily, fills simulated on 1-minute bars) models fills better. Execution latency of hundreds of milliseconds matters only for high-frequency strategies.
How do I verify there is no look-ahead?
Run these tests every time you change the signal or fill logic:
- Run the backtest with and without the shift. If the equity curve collapses once you shift, the edge was the leak.
- Run a one-bar-delay test with signal.shift(2). A robust rule degrades gently; one that goes from large profit to loss is fragile to timing.
- Truncation test: compute the signal on the full dataset and on data cut at time T. Values up to T must be identical, otherwise the indicator uses future data.
- Check fill timestamps in the framework's trade log: every entry time must be strictly later than the signal bar's close time.
- Add explicit cost and slippage settings and rerun, noting the change in Sharpe and drawdown.
def no_future_data(compute_signal, df, cut=500):
full = compute_signal(df).iloc[:cut]
part = compute_signal(df.iloc[:cut])
pd.testing.assert_series_equal(full, part, check_names=False)
no_future_data(lambda d: (d.close.rolling(10).mean() >
d.close.rolling(30).mean()).astype(int), df) Common questions
Why does my backtest buy at the close of the signal bar?
The tool is probably filling at the current close because of a setting or default: price=close in vectorbt, trade_on_close=True in backtesting.py, set_coc(True) in Backtrader, or an unshifted position in pandas. Move the fill to the next bar's open or shift the position by one bar.
Is signal.shift(1) enough to remove look-ahead bias?
It fixes the timing of the signal, but not other leaks such as indicators computed on adjusted future data, normalization using the whole sample, or labels that peek ahead. Run the truncation test to confirm that no value changes when later data is removed.
Should I use the next open or the next close for fills?
Next open is the closest fill to a market order placed right after the signal. Next close is only valid if your strategy truly places orders late in the following bar, and it adds a whole bar of delay to the return calculation.
Can I fill at the signal bar's close with market-on-close orders?
Only when the signal is computed from data available before the order cutoff, for example using the price 15 minutes before the close. The backtest must then use the pre-close price for the signal, not the final close.
How big should slippage be in a backtest?
There is no universal value. Base it on spread and liquidity of the instrument, using a fixed tick count or a percentage per side, and test a range of values to see where the strategy stops being profitable.