Trading Systems

Why Do Two Python Backtesters Disagree About the Same Strategy?

Ionut Claudiu Fratila · Published Dec 5, 2026 · 7 min read · —
PythonBacktestingBacktesting.pybacktraderStrategy Testing
Printed candlestick chart viewed through a magnifying glass

A backtester is a program that replays historical prices and works out which trades a set of rules would have made. Python has several popular open-source ones, and strategies often move between them. When the list of trades changes along the way, the first suspicion is a bug. More often, the two tools simply made different choices on the user’s behalf.

This article looks at those choices in widely used tools and how to make them visible. It is about process and tooling only; it says nothing about whether any strategy is worth trading.

Two Ways to Build a Backtester

Backtesting tools fall into two broad families. A vectorised tool works on whole columns of data at once. vectorbt, for example, “operates entirely on pandas and NumPy objects”, the standard Python libraries for tables and arrays of numbers, and is built to test many variations of a strategy in one go (vectorbt documentation).

An event-driven tool works the way time does: it hands the strategy one step of data, lets it react, processes any orders, then moves on. LEAN’s documentation describes an algorithm manager that “synchronizes the data your algorithm requests, injects the data into your algorithm so you can place trades, processes your orders” (QuantConnect, LEAN algorithm engine). NautilusTrader describes research, simulation and live trading within “a single event-driven architecture” (NautilusTrader, Overview). Backtesting.py and backtrader also work step by step, calling the strategy’s next() method once for each bar.

The line is not absolute: vectorbt’s Portfolio.from_order_func() runs custom logic step by step, and its documentation lists as an advantage of this method “Realistic simulation as it follows the event-driven approach - less risk of exposure to the look-ahead bias” (vectorbt, Portfolio API).

Look-Ahead Hides Most Easily in Array Code

Look-ahead bias means a test uses information that was not available when the decision was made, such as a day’s closing price used to trade at that day’s open. An event-driven engine hands over only the data seen so far. Backtesting.py’s reference says that inside next(), data arrays “are only as long as the current iteration, simulating gradual price point revelation” (Backtesting.py API reference).

In array code nothing enforces that. Every row of history sits in memory at once, and it is up to the author to line each signal up with the bar where it could really have been acted on. vectorbt’s own documentation example does this openly, shifting its signal one bar forward under the comment “Don’t look into the future” (vectorbt, Portfolio API). Leaving that line out causes no error; the test simply runs with knowledge it could not have had.

Event-driven tools make the mistake harder, not impossible, as the section on indexing below shows.

When Does a Market Order Fill?

A market order says “buy or sell now, at whatever price is available”. In a backtest built from bars (a bar is the open, high, low and close prices for one period, such as a day), “now” has to be turned into one of those prices, and tools choose differently.

Backtesting.py’s reference states: “Unless you’re running Backtest(…, trade_on_close=True), market orders are filled on next bar’s open”. With that setting switched on, they fill at the current bar’s closing price instead (Backtesting.py API reference).

backtrader also fills a market order at the “Opening price of the next set of Open/High/Low/Close prices”, on the reasoning that the bar the strategy has just examined “has already happened” (backtrader, Order creation and execution). Its cheat-on-open option, switched on with Cerebro(cheat_on_open=True) (Cerebro is backtrader’s main engine), adds next_open() methods for users who decide after a bar closes but “expect to be matched against the open price”. The documentation keeps them separate from the regular methods, which assume “the future is unknown” (backtrader, Cheat-On-Open).

NautilusTrader documents fill prices, matching and bar-based execution on separate pages (NautilusTrader, Bar-based execution), and asks users to match the detail of their data to the exchange or broker’s order book type (NautilusTrader, Backtesting).

Costs are a second quiet difference. In Backtesting.py, spread and commission both default to zero. When commission is set, it “is applied twice: at trade entry and at trade exit”; before version 0.6.0 it was applied only once (Backtesting.py changelog). Different cost settings mean different results, even when signals agree exactly.

A Small Test: One Decision, Two Fills

This Backtesting.py script buys once, on the 20th bar of the sample Google share data that ships with the library (the same data its Quick Start guide uses), and runs the test twice: once with the default and once with trade_on_close=True. Costs are set to zero explicitly, so nothing is left to a default. We ran it with Backtesting.py 0.6.6.

from backtesting import Backtest, Strategy
from backtesting.test import GOOG  # sample price data that ships with the library


class BuyOnce(Strategy):
    def init(self):
        pass

    def next(self):
        # Decide to buy once, on the 20th bar of data
        if len(self.data) == 20 and not self.position:
            self.buy()


for fill_on_close in (False, True):
    bt = Backtest(
        GOOG, BuyOnce,
        cash=10_000,
        spread=0.0,                     # written down on purpose,
        commission=0.0,                 # not left to the defaults
        trade_on_close=fill_on_close,   # False: next open; True: this close
        finalize_trades=True,           # close the open trade on the last bar
    )
    stats = bt.run()
    print("trade_on_close =", fill_on_close)
    print(stats["_trades"][["EntryBar", "EntryTime", "EntryPrice"]])

Bars in the printed table are numbered from zero, so the decision, made on the 20th bar of data, is on bar 19. In the first run the trade is entered on bar 20, the bar after the decision, at its opening price. In the second it is entered on bar 19, the decision bar itself, at its closing price. Same rule, same data, a different entry bar and price, all from one setting. Printing one known trade like this is a cheap first check whenever two tools disagree.

”The Previous Bar” Is Not the Same Everywhere

Indexing, the way code points at a particular bar, also changes meaning between tools. In backtrader, [0] is the current bar and [-1] is the one before it, and the platform deliberately “doesn’t support slicing” of its data lines because of that scheme (backtrader, Platform concepts).

In Backtesting.py, inside next(), “the last array value (e.g. data.Close[-1]) is always the most recent value” (Backtesting.py API reference). So data.Close[-1] means the current bar in Backtesting.py, while close[-1] means the previous bar in backtrader. Inside Backtesting.py’s init(), where data arrays “are available in full length” for preparing indicators (same page), the same [-1] points at the very last bar of all the data. Copied code can run without error while reading a different bar, or one from the future.

Can the Test Code Become the Live Code?

Some engines are built so the same strategy code runs in testing and in live trading. NautilusTrader says “The same strategy and execution-algorithm code can run across backtest and live systems, reducing deployment divergence”, and adds straight away that live execution “still introduces venue, transport, timing, persistence, external-activity, and reconciliation behavior that a simulation may not reproduce” (NautilusTrader, Overview). In plain terms, brokers, networks and timing behave in ways a replay of history does not.

LEAN is open source, takes algorithms in Python 3.11 or C#, and can be run “with your own infrastructure, data, and brokerage connections” rather than only on QuantConnect’s platform (QuantConnect, LEAN algorithm engine). backtrader has supported live data and live trading since release 1.5.0, listing Interactive Brokers, Visual Chart and Oanda (backtrader, Live trading).

Sharing code means the strategy logic is not rewritten, but the fill and cost assumptions above still shape the backtest half.

Limits and Caveats

Documentation and defaults change between versions, as Backtesting.py’s commission change shows, so record the exact library version with every test. Check maintenance status too: Zipline Reloaded is now maintained “for bug, security and compatibility fixes”, with new features moving to ML4T Backtest (Zipline Reloaded documentation). The example above isolates one setting in one tool; it is not a full comparison. Matching fill and cost settings across two tools still will not make them identical, because each has its own documented rules for stop and limit orders, the order of events within a bar and similar details. Nothing here says which tool or strategy is better; the aim is only to know what a test assumed.

Conclusion

Why do two Python backtesters disagree about the same strategy? Usually because each made an assumption the user never chose: when a market order fills, whether costs start at zero, and which bar [-1] points to. The fix is a matter of process rather than cleverness: set every fill, cost and indexing choice on purpose, record the library version, and check one known trade by hand before trusting a comparison.

Choosing, configuring and checking backtesting tools in this way is part of our Strategy Optimisation & Testing work, and turning a tested strategy into a live system falls under our Algorithm Development and Trading Automation services.

Drafted with AI assistance; reviewed, edited and approved by Ionut Claudiu Fratila.