Python backtesting libraries

Updated Nov 2026

Python backtesting libraries replay historical market data through a trading strategy to estimate how it would have performed. A vectorized engine computes signals across the whole price history at once rather than stepping through each bar. These libraries let quant developers test a strategy's returns and risk before it trades real money.

Popularity

NautilusTrader has the most monthly downloads in this comparison, at 667.0K.

LibraryMonthly downloadsStarsLast releaseLicense
NautilusTrader
667.0K
31.7KAug 2026LGPL-3.0-or-later
vectorbt
389.4K
9.9KNov 2026Apache-2.0 with Commons Clause
Backtesting.py
245.8K
9.3KJul 2026AGPL-3.0
backtrader
229.9K
23.8KApr 2023GPL-3.0-or-later
bt
64.4K
3.0KOct 2026MIT
Qlib
43.4K
50.4KAug 2025MIT
LumiBot
22.1K
2.2KNov 2026GPL-3.0
LEAN CLI
21.4K
336Oct 2026Apache-2.0
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

Libraries and code examples

NautilusTrader

Runs an event-driven trading engine with a Rust core.

Downloads / mo
667.0K
Stars
31.7K
Last release
1.231.0
License
LGPL-3.0-or-later

Quickstart

From backtest_low_level.py
$ pip install nautilus-trader
# %% [markdown]
# # Backtest (Low-Level API)
#
# Use `BacktestEngine` for direct component access: load market data, wire up
# strategies and execution algorithms, and run backtests with full control over
# every step. This tutorial backtests an EMA cross strategy with a TWAP execution
# algorithm on a simulated Binance Spot exchange using historical trade tick data.
#
# [View source on GitHub](https://github.com/nautechsystems/nautilus_trader/blob/develop/docs/getting_started/backtest_low_level.py).

# %% [markdown]
# ## Prerequisites
# - Python 3.12+
# - [NautilusTrader](https://pypi.org/project/nautilus_trader/) latest release installed (`pip install nautilus_trader`)

# %%
from decimal import Decimal

from nautilus_trader.backtest.config import BacktestEngineConfig
from nautilus_trader.backtest.engine import BacktestEngine
from nautilus_trader.examples.algorithms.twap import TWAPExecAlgorithm
from nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAP
from nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAPConfig
from nautilus_trader.model import BarType
from nautilus_trader.model import Money
from nautilus_trader.model import TraderId
from nautilus_trader.model import Venue
from nautilus_trader.model.currencies import ETH
from nautilus_trader.model.currencies import USDT
from nautilus_trader.model.enums import AccountType
from nautilus_trader.model.enums import OmsType
from nautilus_trader.persistence.wranglers import TradeTickDataWrangler
from nautilus_trader.test_kit.providers import TestDataProvider
from nautilus_trader.test_kit.providers import TestInstrumentProvider

# %% [markdown]
# ## Load data
#
# Load bundled test data (ETHUSDT trades from Binance), initialize the matching
# instrument, and wrangle the raw CSV into Nautilus `TradeTick` objects.

# %%
# Load stub test data
provider = TestDataProvider()
trades_df = provider.read_csv_ticks("binance/ethusdt-trades.csv")

# Initialize the instrument which matches the data
ETHUSDT_BINANCE = TestInstrumentProvider.ethusdt_binance()

# Process into Nautilus objects
wrangler = TradeTickDataWrangler(instrument=ETHUSDT_BINANCE)
ticks = wrangler.process(trades_df)

# %% [markdown]
# See the [Data](../concepts/data.md) concept guide for details on the data processing pipeline.

# %% [markdown]
# ## Initialize the engine
#
# Pass a `BacktestEngineConfig` to configure the engine. Here we set a custom
# `trader_id` to show the pattern.

# %%
# Configure backtest engine
config = BacktestEngineConfig(trader_id=TraderId("BACKTESTER-001"))

# Build the backtest engine
engine = BacktestEngine(config=config)

# %% [markdown]
# ## Add a venue
#
# Set up a simulated venue that matches the market data. Here we configure a
# Binance Spot exchange with a cash account.

# %%
# Add a trading venue (multiple venues possible)
BINANCE = Venue("BINANCE")
engine.add_venue(
    venue=BINANCE,
    oms_type=OmsType.NETTING,
    account_type=AccountType.CASH,  # Spot CASH account (not for perpetuals or futures)
    base_currency=None,  # Multi-currency account
    starting_balances=[Money(1_000_000.0, USDT), Money(10.0, ETH)],
)

# %% [markdown]
# ## Add data
#
# Add the instrument and trade ticks to the engine.

# %%
# Add instrument(s)
engine.add_instrument(ETHUSDT_BINANCE)

# Add data
engine.add_data(ticks)

# %% [markdown]
# :::note
# You can add multiple data types (including custom types) and backtest across multiple venues.
# :::
#

# %% [markdown]
# ## Add strategies
#
# Configure and add an EMA cross strategy with TWAP execution parameters.

# %%
# Configure your strategy
strategy_config = EMACrossTWAPConfig(
    instrument_id=ETHUSDT_BINANCE.id,
    bar_type=BarType.from_str("ETHUSDT.BINANCE-250-TICK-LAST-INTERNAL"),
    trade_size=Decimal("0.10"),
    fast_ema_period=10,
    slow_ema_period=20,
    twap_horizon_secs=10.0,
    twap_interval_secs=2.5,
)

# Instantiate and add your strategy
strategy = EMACrossTWAP(config=strategy_config)
engine.add_strategy(strategy=strategy)

# %% [markdown]
# The strategy config references TWAP parameters, but the execution algorithm
# itself is a separate component.
#
# ## Add execution algorithms
#
# Add a TWAP execution algorithm to the engine.

# %%
# Instantiate and add your execution algorithm
exec_algorithm = TWAPExecAlgorithm()  # Using defaults
engine.add_exec_algorithm(exec_algorithm)

# %% [markdown]
# ## Run the backtest
#
# Call `.run()` to process all available data. The engine replays events in
# timestamp order with deterministic execution semantics.

# %%
# Run the engine (from start to end of data)
engine.run()

# %% [markdown]
# ## Post-run analysis
#
# The engine retains data and execution objects in memory for generating reports.
# It also logs a tearsheet with default statistics; see the
# [Portfolio statistics](../concepts/portfolio.md#portfolio-statistics) guide for
# custom statistics.

# %%
engine.trader.generate_account_report(BINANCE)

# %%
engine.trader.generate_order_fills_report()

# %%
engine.trader.generate_positions_report()

# %% [markdown]
# ## Repeated runs
#
# Reset the engine for repeated runs. Instruments, data, and loaded components
# persist across resets; loaded components have their internal state reset.

# %%
# For repeated backtest runs, reset the engine
engine.reset()

# Clear or remove loaded components before adding replacements.

# %% [markdown]
# Remove and add individual components (actors, strategies, execution algorithms) as required.
#
# See the [Trader](../api_reference/trading.md) API reference for a description of all methods available to achieve this.
#

# %%
# Once done, good practice to dispose of the object if the script continues
engine.dispose()

Simulates portfolios from arrays of orders or signals and compares parameter combinations.

Downloads / mo
389.4K
Stars
9.9K
Last release
1.2.1
License
Apache-2.0 with Commons Clause

Strengths

  • Broadcasts strategy inputs across assets. Pass array inputs across assets and parameter combinations.
  • Models fees and slippage. Set fees and slippage when creating the simulated portfolio.

Limitations

  • Repeated entries require accumulation. Enable accumulate when new entry signals should increase an existing position.
  • Complex orders need custom callbacks. Use from_order_func for complex conditions and multiple orders.

Quickstart

From usage.md
$ pip install vectorbt
import pandas as pd
import vectorbt as vbt

close = pd.Series(
    [100.0, 102.0, 101.0, 104.0, 103.0, 107.0],
    index=pd.date_range("2024-01-01", periods=6, freq="D"),
    name="Close",
)
pf = vbt.Portfolio.from_holding(close, init_cash=1000, fees=0.001, freq="1D")
print(round(float(pf.total_return()) * 100, 2))

vectorbt examples

From open-source projects on GitHub

Runs historical trading strategies with indicators, order simulation, parameter optimization, and interactive plots.

Downloads / mo
245.8K
Stars
9.3K
Last release
0.6.6
License
AGPL-3.0

Strengths

  • Searches parameter combinations. Use optimize to search parameter combinations, with optional constraints.
  • Charges commissions at both ends. Commission applies when trades open and when they close.

Limitations

  • Fractional trading needs another class. Use FractionalBacktest when strategies trade fractional units.
  • Margin types share one setting. The engine does not distinguish initial margin from maintenance margin.

Quickstart

From README.md
$ pip install backtesting
from backtesting import Backtest, Strategy
from backtesting.lib import crossover

from backtesting.test import SMA, GOOG


class SmaCross(Strategy):
    def init(self):
        price = self.data.Close
        self.ma1 = self.I(SMA, price, 10)
        self.ma2 = self.I(SMA, price, 20)

    def next(self):
        if crossover(self.ma1, self.ma2):
            self.buy()
        elif crossover(self.ma2, self.ma1):
            self.sell()


bt = Backtest(GOOG, SmaCross, commission=.002,
              exclusive_orders=True)
stats = bt.run()
bt.plot()

Backtesting.py examples

From open-source projects on GitHub

Simulates trading strategies with multiple data feeds, order types, and broker behavior.

Downloads / mo
229.9K
Stars
23.8K
Last release
1.9.78.123
License
GPL-3.0-or-later

Strengths

  • Combines feeds and timeframes. Run multiple data feeds and timeframes within the same strategy.
  • Searches strategy parameter ranges. Use optstrategy to run a strategy with different parameter values.

Limitations

  • Market orders fill next bar. By default, market orders execute at the following bar’s open.
  • Default fills ignore available volume. Configure a filler when simulated fills must respect available volume.

Quickstart

From quickstart.md
$ pip install backtrader
import backtrader as bt
cerebro = bt.Cerebro()
print(cerebro.broker.getvalue())

backtrader examples

From open-source projects on GitHub

Builds allocation strategies from reusable algorithms and combines them into portfolio trees.

Downloads / mo
64.4K
Stars
3.0K
Last release
1.4.1
License
MIT

Strengths

  • Combines strategies into portfolios. Nest strategies and securities in a common portfolio tree.
  • Models nonlinear transaction costs. Use cost models that account for order size, volume, and volatility.

Limitations

  • Positions default to whole shares. Set integer_positions=False when fractional allocations are required.
  • Impact models need additional data. Supply volume and volatility data when commissions uses a CostModel.

Quickstart

From README.md
$ pip install bt
import numpy as np
import pandas as pd

import bt

prices = pd.DataFrame(
    {
        "asset_a": np.linspace(100, 120, 252),
        "asset_b": np.linspace(100, 110, 252),
    },
    index=pd.bdate_range("2020-01-01", periods=252),
)

strategy = bt.Strategy(
    "equal_weight",
    [
        bt.algos.RunMonthly(),
        bt.algos.SelectAll(),
        bt.algos.WeighEqually(),
        bt.algos.Rebalance(),
    ],
)
result = bt.run(bt.Backtest(strategy, prices))
result.display()

bt examples

From open-source projects on GitHub

Provides a quantitative research platform.

Downloads / mo
43.4K
Stars
50.4K
Last release
0.9.7
License
MIT

Quickstart

From README.md
$ pip install pyqlib
import qlib
from qlib.data import D
from qlib.constant import REG_CN

# Initialization
mount_path = "~/.qlib/qlib_data/cn_data"  # target_dir
qlib.init(mount_path=mount_path, region=REG_CN)

# Get stock data by Qlib
# Load trading calendar with the given time range and frequency
print(D.calendar(start_time='2010-01-01', end_time='2017-12-31', freq='day')[:2])

Backtests and deploys trading strategies with the same code for stocks, options, crypto, futures, and forex.

Downloads / mo
22.1K
Stars
2.2K
Last release
4.6.88
License
GPL-3.0
$ pip install lumibot
from datetime import datetime

from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies import Strategy

class BuyAndHold(Strategy):
    def initialize(self):
        self.sleeptime = "1D"

    def on_trading_iteration(self):
        if self.first_iteration:
            price = self.get_last_price("SPY")
            quantity = int(self.get_cash() // price)
            order = self.create_order("SPY", quantity, "buy")
            self.submit_order(order)

if __name__ == "__main__":
    BuyAndHold.run_backtest(
        YahooDataBacktesting,
        datetime(2025, 1, 1),
        datetime(2025, 2, 1),
    )

Runs the QuantConnect LEAN engine locally and in the cloud.

Downloads / mo
21.4K
Stars
336
Last release
1.0.233
License
Apache-2.0

Quickstart

From README.md
$ pip install lean
lean init
lean create-project "Project Name"
lean backtest "Project Name"

FAQ

Backtesting.py suits single-asset strategies with interactive plots. vectorbt suits fast parameter sweeps across many combinations. NautilusTrader suits strategies that must run the same code in backtests and live trading.

Backtesting runs a trading strategy against historical prices to measure its returns, drawdowns, and trade statistics. Results depend on realistic costs, slippage, and data free of look-ahead bias.

backtrader is an event-driven backtesting framework that simulates strategies with multiple data feeds, order types, and broker behavior.

Qlib is a quantitative research platform from Microsoft for building and testing machine learning trading models.

vectorbt simulates portfolios from arrays of orders or signals with NumPy and Numba. It tests many parameter combinations in one run.

NautilusTrader is a trading engine with a Rust core and a Python API. Its event-driven design runs the same strategy code in backtests and live trading.

For coding agents

Found your backtesting library? Help your agent use it.

Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.

Run in your terminal

claude plugin install exa@claude-plugins-official