Vectorbt vs Backtrader Different Results: Reconcile Them
Vectorbt vs backtrader different results almost always come from fill timing: vectorbt fills at the signal bar's close, Backtrader at the next open. Then check fees, sizing, share rounding, indicator seeding and data.
- Match fill timing first: shift vectorbt signals one bar and use price=open, or set Backtrader set_coc(True); this usually explains most of the trade-by-trade gap.
- Reconcile in a fixed order (data hash, indicators, signals, trade list, fill price, fees, size, equity) and add one factor at a time, starting from zero fees, size 1 and no slippage.
- Backtrader trades whole shares from a FixedSize stake of 1 by default, while vectorbt defaults to size=inf (all cash, fractional), so set size explicitly on both.
- Compare trade lists by timestamp, not final equity; two engines can reach the same final number through different trades.
- Gap handling, cash rejections, volume limits and slippage capping to the bar's range are legitimate Backtrader modelling that vectorbt does not do.
Why do vectorbt and Backtrader give different results?
The two engines make different default assumptions, and none of them is a bug. Vectorbt is vectorized: every signal is an array element, and `Portfolio.from_signals` fills at `price`, which defaults to the close of the same bar. Backtrader is event-driven: `next()` runs after a bar closes, `buy()` creates a pending order, and the broker fills it at the next bar's open.
A plain pandas backtest (`position.shift(1) * close.pct_change()`) is a third convention. It earns the close-to-close return, so it implicitly fills at the prior close. Whichever engine you call right, you are really asking which fill assumption you intended.
Use this table to guess the cause from the symptom before bisecting.
| Symptom | Likely cause | Fix |
|---|---|---|
| Same trade count, every fill price slightly different | Fill timing (signal-bar close vs next open) | Shift signals one bar and use price=open, or Backtrader set_coc(True) |
| Different number of trades | Indicator warm-up, crossover definition, reversal or pending-order overlap | Diff indicator arrays, then signals |
| Same trades, PnL differs by a constant ratio | Position size (stake=1 vs all cash) or fractional vs whole shares | Set size and size_type explicitly on both |
| Equity gap grows with trade count | Fees or slippage applied differently, or on one side only | Zero them, then re-add one at a time |
| Backtrader has fewer fills than expected | Order rejected for insufficient cash at the next open | Inspect notify_order for Margin or Rejected statuses |
| Only the last few bars differ | Open position handling at the end of data | Compare trade lists including Open status |
What is the setting-by-setting mapping between Backtrader, vectorbt and pandas?
Most reconciliation work is translating one parameter vocabulary into the other. Set every value explicitly on both sides, because the defaults differ: Backtrader starts with 10,000 cash and vectorbt with `init_cash=100`.
| Concept | Backtrader | vectorbt from_signals | pandas formula |
|---|---|---|---|
| Fill price | Next open (default); broker.set_coc(True) fills at the signal bar close | price=close default; price=open with shifted signals for next open | Close-to-close: position.shift(1) * close.pct_change() |
| Commission | broker.setcommission(commission=0.001), a fraction per side on trade value; margin/mult/stocklike for futures | fees=0.001 per order, fixed_fees= for a cash amount per order | Subtract fee * abs(position.diff()) from returns |
| Slippage | broker.set_slippage_perc(0.0005) or set_slippage_fixed; slip_open, slip_limit, slip_match | slippage=0.0005, adverse on both sides | Add slip * abs(position.diff()) to costs |
| Sizing | Sizer, default FixedSize stake=1; PercentSizer, AllInSizer | size=np.inf default; size_type='amount', 'percent', 'value' | Position is 0 or 1 (fully invested) |
| Whole shares | Always integer | size_granularity=1 (fractional otherwise) | Not modelled |
| Warm-up | Minimum period propagates; next() waits for all indicators | NaN from rolling windows; comparisons are False | NaN from rolling windows |
| Reversal | order_target_size, or close() then buy() | direction='both', upon_opposite_entry | position = signal.shift(1) |
| Repeat entries | Guard with if not self.position | accumulate=False ignores entries while in position | Position is a state, not an event |
How do I bisect the difference step by step?
Bisection works because each factor can be switched off. Start with the most idealized configuration on both engines, confirm they match exactly, then add one factor per run. The first factor that breaks the match owns the gap.
The script below builds deterministic synthetic OHLC data, runs a 10/30 SMA crossover in both engines at size 1, zero fees and next-open fills, exports both order lists and finds the first divergent row. Prices are rounded to 2 decimals so float noise cannot hide a real difference.
- Hash the data fed to both engines (for example `pd.util.hash_pandas_object(df).sum()`). Strip timezones from both, and feed the same adjusted or raw columns.
- Diff indicator arrays numerically with `np.allclose` on the overlapping non-NaN region before looking at any trades.
- Diff the entry and exit signal timestamps after applying the one-bar shift.
- Run the script below at size 1, zero fees, no slippage, and diff the order lists by timestamp.
- Add fees, then slippage, then real sizing, one per run. Re-run the diff each time and record the first divergence.
- Only when the trade lists match, compare equity curves and final value.
import numpy as np, pandas as pd, vectorbt as vbt, backtrader as bt
rng = np.random.default_rng(7)
idx = pd.bdate_range("2021-01-04", periods=600)
c = 100 * np.exp(np.cumsum(rng.normal(0, 0.01, 600)))
o = np.r_[c[0], c[:-1]] * np.exp(rng.normal(0, 0.004, 600))
df = pd.DataFrame({"open": o, "high": np.maximum(o, c) * 1.003,
"low": np.minimum(o, c) * 0.997, "close": c,
"volume": 1e6}, index=idx).round(2)
# ---- vectorbt: signals computed on close, filled next open ----
f = df.close.rolling(10).mean(); s = df.close.rolling(30).mean()
up = (f > s) & (f.shift() <= s.shift())
dn = (f < s) & (f.shift() >= s.shift())
pf = vbt.Portfolio.from_signals(
df.close,
entries=up.shift(1, fill_value=False),
exits=dn.shift(1, fill_value=False),
price=df.open, size=1, size_type="amount",
init_cash=1e6, fees=0.0, slippage=0.0, freq="D")
vo = pf.orders.records_readable[["Timestamp", "Side", "Size", "Price", "Fees"]]
# ---- Backtrader: default next-open fill ----
class X(bt.Strategy):
def __init__(self):
self.x = bt.ind.CrossOver(bt.ind.SMA(period=10), bt.ind.SMA(period=30))
self.rows = []
def next(self):
if self.x > 0 and not self.position:
self.buy(size=1)
elif self.x < 0 and self.position:
self.close()
def notify_order(self, o):
if o.status == o.Completed:
self.rows.append(dict(
Timestamp=pd.Timestamp(bt.num2date(o.executed.dt)).normalize(),
Side="Buy" if o.isbuy() else "Sell",
Size=abs(o.executed.size), Price=o.executed.price,
Fees=o.executed.comm))
cb = bt.Cerebro()
cb.adddata(bt.feeds.PandasData(dataname=df))
cb.addstrategy(X)
cb.broker.setcash(1e6)
cb.broker.setcommission(commission=0.0)
res = cb.run()[0]
bo = pd.DataFrame(res.rows)
m = pd.concat([vo.reset_index(drop=True).add_prefix("vbt_"),
bo.add_prefix("bt_")], axis=1)
bad = ((m.vbt_Timestamp != m.bt_Timestamp)
| ((m.vbt_Price - m.bt_Price).abs() > 1e-9)
| (m.vbt_Size != m.bt_Size))
print("orders:", len(vo), len(bo))
print(m[bad].head(1)) # first divergence, empty if identical
print(pf.final_value(), cb.broker.getvalue())How big is each effect, and what does fill timing look like numerically?
Take a signal at the close of day t of 100.00. The next open is 101.00 and the next close is 102.00. A pandas close-to-close backtest credits the move 100 to 102, which is +2.00%. An open-fill engine earns 101 to 102, which is +0.99%. The 1.01 point difference comes entirely from a fill price you could not have had at the signal bar's close.
That gap repeats on every trade and tends to bias in one direction when signals follow momentum, so it usually dominates every other effect. The table gives an order-of-magnitude guide for diagnosis, using formulas rather than universal numbers.
| Factor | Per-trade effect | How to measure |
|---|---|---|
| Fill timing | abs(open[t+1] / close[t] - 1), often the largest term | Mean of that series on signal bars |
| Fees (fraction f, both sides) | About 2f of notional per round trip; f=0.001 gives about 0.2% | Compare Fees columns, entry and exit |
| Slippage (fraction s, adverse) | About 2s per round trip | Fill price minus bar open on each order |
| Whole-share rounding | Unused cash = cash mod price; up to one share's value | cash / price vs floor(cash / price) |
| EMA seed | Weight (1-alpha)^n, alpha = 2/(span+1); span 20 after 100 bars is about 4.5e-5 | Diff arrays after the warm-up |
| Last-bar handling | One open position's unrealized PnL | Compare Status Open rows |
Which sizing, indicator and signal differences should I check?
Sizing: Backtrader's default sizer is `FixedSize` with `stake=1`, so with no sizer configured it buys 1 share per order, while vectorbt's default `size=np.inf` invests all cash. To compare like with like, the example below assumes Backtrader is set to `cerebro.addsizer(bt.sizers.AllInSizer)`, which spends all available cash on whole shares. A 10,000 account at 480.00 per share then buys 20 whole shares in Backtrader (9,600 used, 400 idle) but about 20.83 shares in vectorbt unless you set `size_granularity=1`. On small accounts and high-priced tickers this is a large, systematic gap.
Cash compounding differs too. Backtrader's `AllInSizer` or `PercentSizer` computes size from cash at the signal bar's close, but the fill happens at the next open. After a gap up, the order can cost more than available cash and the broker rejects it, so Backtrader shows a missing trade where vectorbt shows one. Look for Margin or Rejected in `notify_order`, and size with a buffer such as `PercentSizer(percents=95)` if you need to avoid it.
Indicators: Backtrader delays the first `next()` until every indicator has data (minperiod propagation), so a 30-bar SMA means no signals before bar 30. Vectorbt and pandas give NaN there, which compares as False, and that matches. EMA does not match by default: Backtrader seeds with an SMA of the first `period` values, while `ewm(span=n, adjust=False)` seeds with the first price and `adjust=True` (the pandas default) uses a weighted form. RSI and ATR have the same trap: Wilder smoothing is an EMA with alpha = 1/n, not 2/(n+1), and a simple rolling mean gives different values. Always compare indicator arrays with `np.allclose` after the warm-up before touching signals.
Signals: Backtrader's `CrossOver` fires only on the bar of the cross, while `fast > slow` is a state that stays True. Convert the state to an event (`state & ~state.shift(fill_value=False)`) or in vectorbt rely on `accumulate=False`, which ignores entries while a position is open. For reversals, vectorbt with `direction='both'` and `upon_opposite_entry` flips in one order. In Backtrader, `close()` followed by `sell()` in the same `next()` creates two pending orders, so use `order_target_size` or track a pending-order handle and skip while one is outstanding.
Data: confirm both engines use the same adjusted or raw prices, because splits and dividends change the fill price and share count. Strip timezones and align the calendar so the same bars exist in both. At the end of data, neither engine force-closes by default; vectorbt lists the position with Status Open and Backtrader leaves it marked to market. That is why final equity can match while closed-trade counts differ.
Which differences are legitimate, and when is each engine the right tool?
Some gaps should remain after you reconcile. Backtrader simulates a broker: gaps change fill prices, orders can be rejected for cash, stops and limits fill against the bar's high and low, and `slip_match` with `slip_out=False` caps slippage inside the bar's range. A volume filter can also produce partial fills. Vectorbt fills the full size at the stated price, with slippage added on top without any cap.
These are modelling choices, not errors. Once both engines agree on the idealized configuration, enable the realistic features in Backtrader and treat the remaining gap as the cost of realism.
Vectorbt is the right tool for parameter sweeps over thousands of combinations, where array speed matters and next-open fills with a flat fee are a good enough approximation. Backtrader fits path-dependent logic: staged exits, order types, cash rejections and live-trading code that shares the strategy class. A common workflow is to sweep in vectorbt, then confirm the shortlisted candidates in Backtrader with the reconciled configuration.
Common questions
Does Backtrader cheat_on_close make it match vectorbt's default?
Yes for fill timing. With `cerebro.broker.set_coc(True)`, a market order placed in `next()` fills at that bar's close, which is what `from_signals` does with `price=close`. Both then assume you could trade at a close that you only knew after it printed, so this is useful for reconciliation but optimistic as a model.
Why does my pandas backtest beat both engines?
The `position.shift(1) * close.pct_change()` formula credits the close-to-close return, so the entry is effectively at the previous close, and it usually charges no fees, no slippage and no rounding. Add costs as `fee * position.diff().abs()` and use open-to-close returns on entry bars to approximate next-open fills.
Do vectorbt fees and Backtrader commission both apply on entry and exit?
Both charge on every order, so a round trip pays the rate twice: 0.001 is about 0.2% per round trip. Check the Fees columns of both order exports to confirm. Backtrader's `setcommission` also behaves differently for futures when `margin` and `mult` are set, because the commission becomes a fixed amount per contract rather than a percentage.
Why are the trade counts different even with identical signals?
Three Backtrader behaviours usually cause it. Rejected orders happen when cash after a gap up cannot cover the next-open fill, so check for Margin or Rejected in `notify_order` and size with a buffer such as `PercentSizer(percents=95)`. Repeated entries while in position come from a missing guard, so add `if not self.position` (and set `accumulate=False` in vectorbt), and pending-order overlap, such as `close()` plus `buy()` in one `next()`, is fixed with `order_target_size` or by skipping while an order handle is still outstanding.
How close can the two engines get on a toy strategy?
With identical data, size 1, zero fees, zero slippage and next-open fills, order timestamps and prices should match exactly and final value should agree to float precision. If they do not, one of the earlier checklist steps (data hash, indicators or signals) still has a diff.