# Python backtesting libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [NautilusTrader](#nautilus-trader) | 667.0K | 31.7K | Aug 2026 | LGPL-3.0-or-later |
| [vectorbt](#vectorbt) | 389.4K | 9.9K | Nov 2026 | Apache-2.0 with Commons Clause |
| [Backtesting.py](#backtesting-py) | 245.8K | 9.3K | Jul 2026 | AGPL-3.0 |
| [backtrader](#backtrader) | 229.9K | 23.8K | Apr 2023 | GPL-3.0-or-later |
| [bt](#bt) | 64.4K | 3.0K | Oct 2026 | MIT |
| [Qlib](#pyqlib) | 43.4K | 50.4K | Aug 2025 | MIT |
| [LumiBot](#lumibot) | 22.1K | 2.2K | Nov 2026 | GPL-3.0 |
| [LEAN CLI](#lean) | 21.4K | 336 | Oct 2026 | Apache-2.0 |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[NautilusTrader](#nautilus-trader) has the most monthly downloads in this comparison, at 667.0K.

## Capabilities

| Library | Multi-asset portfolios | Live broker adapters |
| --- | --- | --- |
| [NautilusTrader](#nautilus-trader) | Yes | Yes |
| [vectorbt](#vectorbt) | Yes | Undocumented |
| [Backtesting.py](#backtesting-py) | No | No |
| [backtrader](#backtrader) | Yes | Yes |
| [bt](#bt) | Yes | Undocumented |
| [Qlib](#pyqlib) | Yes | Undocumented |
| [LumiBot](#lumibot) | Yes | Yes |
| [LEAN CLI](#lean) | Via plugin | Via plugin |

## Libraries

### NautilusTrader

[GitHub](https://github.com/nautechsystems/nautilus_trader) · [PyPI](https://pypi.org/project/nautilus-trader) · [Docs](https://pypi.org/project/nautilus-trader/)

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
- Capabilities: [From the NautilusTrader docs](https://pypi.org/project/nautilus-trader/)

```sh
pip install nautilus-trader
```

**Quickstart**

```python
# %% [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()

```

From [backtest_low_level.py](https://github.com/nautechsystems/nautilus_trader/blob/27a8e54e7ac3c57d6cbf8891f0283dfbaee97317/docs/getting_started/backtest_low_level.py) · [Find projects using NautilusTrader →](https://dashboard.exa.ai/playground/search?q=nautilus-trader%20GitHub%20projects)

### vectorbt

[GitHub](https://github.com/polakowo/vectorbt) · [PyPI](https://pypi.org/project/vectorbt) · [Docs](https://pypi.org/project/vectorbt/)

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
- Capabilities: [From the vectorbt docs](https://pypi.org/project/vectorbt/)

**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.

**Watch out for**

- **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.

```sh
pip install vectorbt
```

**finlab-python/finlab_crypto** (293 stars)

[finlab-python/finlab_crypto](https://github.com/finlab-python/finlab_crypto) 

```python
def backtest(self, ohlcv, variables=None, filters=None, lookback=None, plot=False, signals=False,
             side='long', cscv_nbins=10, cscv_objective=lambda r: r.mean(), html=None, compounded=True,
             execution_price='close', k_colors='world', **args):
    """Backtest the strategy with vectorbt.

    Args:
      ohlcv: OHLCV DataFrame.
      variables: Strategy parameters. Lists or arrays are optimised over;
        ``sl_stop``, ``tp_stop``, ``ts_stop`` add stop-loss, take-profit
        and trailing-stop exits.
      filters: {name: Filter.create(...)} conditions for entries.
      lookback: Only use the latest ``lookback`` bars.
      plot: Show the interactive chart (one parameter set) or the
        optimisation dashboard with overfitting analysis (many sets).
      signals: Return ``(entries, exits, figures)`` instead of backtesting.
      side: Only 'long' is supported.
      cscv_nbins: Number of blocks for the overfitting analysis.
      cscv_objective: Performance measure for the overfitting analysis.
      html: Also save the interactive chart to this file.
      compounded: Reinvest profits; otherwise trade a fixed size.
      execution_price: 'close' trades at the signal bar's close, 'open'
        at the next bar's open.
      k_colors: Candle colors, 'world', 'taiwan' or
        {'increasing_line': color, 'decreasing_line': color}.
      **args: Passed to ``vbt.Portfolio.from_signals`` (ex: ``freq='4h'``, ``fees``).

    Returns:
      vbt.Portfolio
    """
    if side == 'short':
        raise NotImplementedError('Shorting is not supported yet')
    if side != 'long':
        raise ValueError("side should be 'long' or 'short'")
    if execution_price not in EXECUTION_PRICES:
        raise ValueError(f'execution_price should be one of {EXECUTION_PRICES}')

    variables = dict(variables or {})
    stop_vars = {name: variables.pop(name) for name in STOP_VARIABLES if name in variables}
    ohlcv = ohlcv.iloc[-lookback:] if lookback else ohlcv

    parameter_sets = enumerate_variables(variables) or [self._default_parameters]
    entries, exits, fig_data = enumerate_signal(ohlcv, self, parameter_sets)
    if filters:
        filter_results = {name: create(ohlcv) for name, create in filters.items()}
        entries, exits, fig_data = self._add_filters(entries, exits, fig_data, filter_results)
    entries, exits = stop_early(ohlcv, entries, exits, stop_vars)
    entries, exits = entries.squeeze(axis=1), exits.squeeze(axis=1)

    if signals:
        return entries, exits, fig_data

    if not compounded:
        args['size'] = vbt.settings.portfolio['init_cash'] / ohlcv.close.iloc[0]
    price = ohlcv.close if execution_price == 'close' else ohlcv.open.shift(-1)
    portfolio = vbt.Portfolio.from_signals(price, _as_bool(entries), _as_bool(exits), **args)

    if isinstance(entries, pd.Series):
        if plot or html is not None:
            plot_strategy(ohlcv, entries, exits, portfolio, fig_data, html=html, k_colors=k_colors)
    elif plot:
        cscv = CSCV(n_bins=cscv_nbins, objective=cscv_objective)
        cscv.add_daily_returns(portfolio.daily_returns())
        plot_combination(portfolio, cscv.estimate_overfitting())
        plt.show()
        variable_visualization(portfolio)

    return portfolio
```

[finlab_crypto/strategy.py](https://github.com/finlab-python/finlab_crypto/blob/2b3305fd6adacdf1732866d3e931e1fa061ebdf8/finlab_crypto/strategy.py#L100-L166) · [More projects using vectorbt →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20vectorbt%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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))


```

From [usage.md](https://vectorbt.dev/getting-started/usage/)

### Backtesting.py

[GitHub](https://github.com/kernc/backtesting.py) · [PyPI](https://pypi.org/project/backtesting) · [Docs](https://kernc.github.io/backtesting.py/doc/backtesting/)

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
- Capabilities: [From the Backtesting.py docs](https://kernc.github.io/backtesting.py/doc/backtesting/)

**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.

**Watch out for**

- **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.

```sh
pip install backtesting
```

**Fincept-Corporation/FinceptTerminal** (33.9K stars)

[Fincept-Corporation/FinceptTerminal](https://github.com/Fincept-Corporation/FinceptTerminal) 

```python
def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:
    """Run parameter optimization via backtesting.py's `bt.optimize`.

    The frontend sweeps strategy params under their *frontend* names (e.g.
    `fastPeriod`); backtesting.py optimizes class-level attribute names
    (e.g. `n1`). `btp_strategies.STRATEGY_OPTIMIZE_PARAM_MAP` translates.

    Returns the same shape as run_backtest (`data.performance`, `data.trades`,
    `data.equity`) so the existing screen renderer works unchanged, plus
    optimization-specific fields under `data.optimization`.
    """
    try:
        self._log('Starting parameter optimization')

        strategy_def = request.get('strategy', {})
        strategy_type = strategy_def.get('type', 'sma_crossover')
        # Frontend canonical name is `paramRanges`; legacy callers used `parameters`.
        param_ranges = request.get('paramRanges', {}) or request.get('parameters', {})
        objective = request.get('optimizeObjective') or request.get('metric', 'sharpe')
        start_date = request.get('startDate')
        end_date = request.get('endDate')
        initial_capital = request.get('initialCapital', 10000)
        max_iterations = int(request.get('maxIterations', 500) or 500)

        # Canonical: `symbols: [str]`. Fallback: `assets: [{symbol, ...}]`.
        symbols = request.get('symbols', [])
        if not symbols:
            assets = request.get('assets', [])
            symbols = [a.get('symbol') for a in assets if isinstance(a, dict) and a.get('symbol')]

        if not param_ranges:
            return self._create_error_result('No parameter ranges supplied (expected paramRanges)')

        symbol = symbols[0] if symbols else 'SPY'
        data = self._load_data(symbol, start_date, end_date, request.get('interval', '1d'))
        if data is None or len(data) == 0:
            return self._create_error_result(f'No data available for {symbol}')

        # Build the strategy class with default params; bt.optimize will
        # sweep class-level attributes from there.
        strategy_class = self._create_strategy_class(strategy_def)

        # Translate frontend param names -> class attribute names per strategy.
        import btp_strategies as _strat
        mapped_ranges = _strat.map_optimize_params(strategy_type, param_ranges)

        # Build python ranges. Drop any range that targets an attribute the
        # strategy class doesn't declare — backtesting.py would reject it
        # otherwise and we'd get the cryptic "missing parameter X" error.
        opt_kwargs = {}
        skipped: List[str] = []
        for cattr, cfg in mapped_ranges.items():
            if not hasattr(strategy_class, cattr):
                skipped.append(cattr)
                continue
            try:
                lo = int(cfg.get('min', 1))
                hi = int(cfg.get('max', 100))
                step = max(1, int(cfg.get('step', 1)))
            except Exception:
                continue
            if hi < lo:
                lo, hi = hi, lo
            opt_kwargs[cattr] = range(lo, hi + 1, step)

        if not opt_kwargs:
            return self._create_error_result(
                f"No optimizable parameters for strategy '{strategy_type}'. "
                f"Mapped attrs not present on class: {skipped}"
            )

        if skipped:
            self._log(f'Skipped non-class attrs during optimize: {skipped}')

        from backtesting import Backtest
        bt = Backtest(
            data, strategy_class,
            cash=initial_capital,
            commission=float(request.get('commission', 0.0) or 0.0) + float(request.get('slippage', 0.0) or 0.0),
        )

        # Map frontend objective to backtesting.py stat key.
        metric_map = {
            'sharpe':  'Sharpe Ratio',
            'sortino': 'Sortino Ratio',
            'calmar':  'Calmar Ratio',
            'return':  'Return [%]',
            # Tolerate human-readable variants for callers outside the screen.
            'Sharpe Ratio': 'Sharpe Ratio',
            'Sortino Ratio': 'Sortino Ratio',
            'Calmar Ratio': 'Calmar Ratio',
            'Total Return': 'Return [%]',
        }
        maximize_metric = metric_map.get(objective, 'Sharpe Ratio')

        self._log(f'Optimizing {len(opt_kwargs)} attrs (max_tries={max_iterations}) maximize={maximize_metric}')
        stats = bt.optimize(**opt_kwargs, maximize=maximize_metric, max_tries=max_iterations)

        # Extract chosen optimal params back under frontend names.
        inverse_map = {cattr: fname for fname, cattr in
                       _strat.STRATEGY_OPTIMIZE_PARAM_MAP.get(strategy_type, {}).items()}
        optimal_params: Dict[str, Any] = {}
        for cattr in opt_kwargs.keys():
            if not hasattr(stats._strategy, cattr):
                continue
            fname = inverse_map.get(cattr, cattr)
            val = getattr(stats._strategy, cattr)
            optimal_params[fname] = int(val) if hasattr(val, '__int__') else val

        # Wire shape: same as run_backtest so display_result() renders performance/trades.
        result_dict = self._convert_results(
            stats, symbol, start_date, end_date, initial_capital
        ).to_dict()

        using_synthetic = not self._has_real_data(symbol)
        result_dict['using_synthetic_data'] = using_synthetic
        result_dict['optimization'] = {
            'objective': objective,
            'objective_value': float(stats.get(maximize_metric, 0)),
            'best_params': optimal_params,
            'iterations': int(max_iterations),
            'attrs_optimized': list(opt_kwargs.keys()),
            'attrs_skipped': skipped,
        }

        self._log(
            f"Optimization done: best {maximize_metric} = "
            f"{result_dict['optimization']['objective_value']:.4f} with {optimal_params}"
        )
        return {'success': True, 'message': 'Optimization completed', 'data': result_dict}

    except Exception as e:
        self._error('Optimization failed', e)
        import traceback
        return self._create_error_result(f'Optimization failed: {str(e)}\n{traceback.format_exc()}')
```

[fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py](https://github.com/Fincept-Corporation/FinceptTerminal/blob/68691b7577ce642009cdf2c1b4b0766ca9e37999/fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py#L349-L483) · [More projects using Backtesting.py →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20backtesting%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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()

```

From [README.md](https://github.com/kernc/backtesting.py/blob/master/README.md)

### backtrader

[GitHub](https://github.com/mementum/backtrader) · [PyPI](https://pypi.org/project/backtrader) · [Docs](https://pypi.org/project/backtrader/)

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
- Capabilities: [From the backtrader docs](https://pypi.org/project/backtrader/)

**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.

**Watch out for**

- **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.

```sh
pip install backtrader
```

**UFund-Me/Qbot** (18.8K stars)

[UFund-Me/Qbot](https://github.com/UFund-Me/Qbot) 

```python
def next(self):
    self.log('Close, %.2f' % self.dataclose[0])
    if self.order:
        return
    if not self.position:
        if (self.rsi[0] < 50 and
                self.rsi[-1] >= 50 and
                self.dataclose[0] > self.sma[0]):
            self.log('BUY CREATE, %.2f' % self.dataclose[0])
            self.order = self.buy()
    else:
        if (self.rsi[0] > 50 and
                self.rsi[-1] <= 50 and
                self.dataclose[0] < self.sma[0]):
            self.log('SELL CREATE, %.2f' % self.dataclose[0])
            self.order = self.sell()
```

[qbot/strategies/multi_strategy_bt.py](https://github.com/UFund-Me/Qbot/blob/f0425ae4ae8bd02b79656b8f7039f4cd6874095e/qbot/strategies/multi_strategy_bt.py#L76-L91) · [More projects using backtrader →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20backtrader%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import backtrader as bt
cerebro = bt.Cerebro()
print(cerebro.broker.getvalue())

```

From [quickstart.md](https://www.backtrader.com/docu/quickstart/quickstart/)

### bt

[GitHub](https://github.com/pmorissette/bt) · [PyPI](https://pypi.org/project/bt) · [Docs](https://pmorissette.github.io/bt/)

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
- Capabilities: [From the bt docs](https://pmorissette.github.io/bt/)

**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.

**Watch out for**

- **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.

```sh
pip install bt
```

**Fincept-Corporation/FinceptTerminal** (33.9K stars)

[Fincept-Corporation/FinceptTerminal](https://github.com/Fincept-Corporation/FinceptTerminal) 

```python
@_register('momentum_topn', 'momentum', 'Momentum Top-N',
           'Select top N assets by momentum, equal weight',
           [{'name': 'topN', 'label': 'Top N', 'default': 5, 'min': 1, 'max': 50},
            {'name': 'lookback', 'label': 'Momentum Lookback', 'default': 60}])
def _build_momentum_topn(params):
    """Momentum top-N selection strategy."""
    top_n = int(params.get('topN', 5))
    lookback = int(params.get('lookback', 60))

    def build(data, name='momentum_topn'):
        if _BT_AVAILABLE:
            algos = [
                # Wait until the lookback window has data (the first rebalance otherwise
                # fails on an empty/NaN estimate). Must precede RunMonthly: placed after
                # it, the counter only advanced on month starts (lookback MONTHS).
                _bt.algos.RunAfterDays(int(lookback) + 2),
                _bt.algos.RunMonthly(),
                _bt.algos.SelectAll(),  # SelectMomentum ranks the current selection
                _bt.algos.SelectMomentum(n=top_n, lookback=pd.DateOffset(days=lookback), lag=_LAG),
                _bt.algos.WeighEqually(),
                _bt.algos.Rebalance(),
            ]
            return _bt.Strategy(name, algos)
        return None
    return build
```

[fincept-qt/scripts/Analytics/backtesting/bt/bt_strategies.py](https://github.com/Fincept-Corporation/FinceptTerminal/blob/68691b7577ce642009cdf2c1b4b0766ca9e37999/fincept-qt/scripts/Analytics/backtesting/bt/bt_strategies.py#L510-L534) · [More projects using bt →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20bt%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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()

```

From [README.md](https://github.com/pmorissette/bt/blob/master/README.md)

### Qlib

[GitHub](https://github.com/microsoft/qlib) · [PyPI](https://pypi.org/project/pyqlib) · [Docs](https://pypi.org/project/pyqlib/)

Provides a quantitative research platform.

- Downloads / mo: 43.4K
- Stars: 50.4K
- Last release: 0.9.7
- License: MIT
- Capabilities: [From the Qlib docs](https://pypi.org/project/pyqlib/)

```sh
pip install pyqlib
```

**Quickstart**

```python
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])

```

From [README.md](https://raw.githubusercontent.com/microsoft/qlib/v0.9.7/README.md) · [Find projects using Qlib →](https://dashboard.exa.ai/playground/search?q=pyqlib%20GitHub%20projects)

### LumiBot

[GitHub](https://github.com/Lumiwealth/lumibot) · [PyPI](https://pypi.org/project/lumibot) · [Docs](https://lumibot.lumiwealth.com/)

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
- Capabilities: [From the LumiBot docs](https://lumibot.lumiwealth.com/)

```sh
pip install lumibot
```

**Quickstart**

```python
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),
    )


```

From [strategy_api_overview.html](https://lumibot.lumiwealth.com/strategy_api_overview.html) · [Find projects using LumiBot →](https://dashboard.exa.ai/playground/search?q=lumibot%20GitHub%20projects)

### LEAN CLI

[GitHub](https://github.com/QuantConnect/lean-cli) · [PyPI](https://pypi.org/project/lean) · [Docs](https://www.lean.io/docs/v2/lean-cli/key-concepts/getting-started)

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
- Capabilities: [From the LEAN CLI docs](https://www.lean.io/docs/v2/lean-cli/key-concepts/getting-started)

```sh
pip install lean
```

**Quickstart**

```python
lean init
lean create-project "Project Name"
lean backtest "Project Name"

```

From [README.md](https://pypi.org/pypi/lean/1.0.233/json#info.description) · [Find projects using LEAN CLI →](https://dashboard.exa.ai/playground/search?q=lean%20GitHub%20projects)

## FAQ

### Which Python backtesting library should I use?

[Backtesting.py](#backtesting-py) suits single-asset strategies with interactive plots. [vectorbt](#vectorbt) suits fast parameter sweeps across many combinations. [NautilusTrader](#nautilus-trader) suits strategies that must run the same code in backtests and live trading.

### What is backtesting?

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.

### What is backtrader?

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

### What is Qlib?

[Qlib](#pyqlib) is a quantitative research platform from Microsoft for building and testing machine learning trading models.

### What is vectorbt?

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

### What is NautilusTrader?

[NautilusTrader](#nautilus-trader) 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.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python backtesting libraries backtrader Backtesting.py vectorbt bt code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
