Registry / data / backtesting

backtesting

JSON →
library0.6.5pypypi✓ verified 85d ago

Backtesting.py is a Python framework for backtesting trading strategies on historical candlestick data. It provides a fast, lightweight, and user-friendly API to define strategies, run simulations, inspect detailed statistics, and explore interactive charts. It is currently at version 0.6.5 and is actively maintained with regular releases.

pip install backtesting
INSTALL
IMPORT
SIG · BACKTESTING
B
backtesting
datapythonv0.6.5
Install
10.2s avg
Import
2734ms
Disk
234MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.6.5 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 2.828s · 233.7MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 10.2s · import 2.641s · 224MB
234MB installed
● package 234MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Backtest
from backtesting import Backtest
Strategy
from backtesting import Strategy
crossover
from backtesting.lib import crossover
SMA
from backtesting.test import SMA
SMA is a test utility; for real strategies, users typically import from other indicator libraries (e.g., pandas_ta, TA-Lib).
GOOG
from backtesting.test import GOOG
GOOG is a built-in test dataset; users typically provide their own pandas DataFrames.

This quickstart defines a simple Moving Average Crossover strategy. It initializes two Simple Moving Averages (SMAs) in `init()` using `self.I()` to prevent look-ahead bias, and then places buy/sell orders in `next()` based on their crossover. The `Backtest` instance is run with historical Google stock data, and performance statistics are printed, followed by an interactive plot.

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() # Prepare data (using built-in test data for quickstart) # In a real scenario, you'd load your own pandas.DataFrame # with columns 'Open', 'High', 'Low', 'Close', 'Volume' (optional) # and a DatetimeIndex. # For example: from pandas_datareader import data as yf # data = yf.DataReader('SPY', start='2000', end='2020') bt = Backtest(GOOG, SmaCross, cash=10000, commission=.002, exclusive_orders=True) stats = bt.run() print(stats) bt.plot(open_browser=False)
Debug
Known issues
breakingThe `Backtest(commission=)` parameter in versions 0.6.0 and later now applies commission *twice* per trade (at both entry and exit). If you intend for costs to be applied only once at entry (e.g., for spread/slippage), use the new `Backtest(spread=)` parameter instead.
fix
Review existing strategies using `commission` and adjust if needed, or migrate to `spread` for one-time entry costs.
affects: 0.6.0+
breakingVersion 0.2.0 introduced a completely new `Order / Trade / Position API`. Strategies written for versions prior to 0.2.0 are incompatible and require significant updates to use the new API.
fix
Consult the changelog and documentation for the 0.2.0 release to update strategy logic and order management to the new API.
affects: <0.2.0
gotchaBokeh versions 3.0.x and 3.2.x are known to have incompatibilities with `backtesting.py`'s interactive plotting feature, potentially leading to errors.
fix
Force a compatible Bokeh version during installation: `pip install "bokeh>=3.1,!=3.2.*"`.
affects: All versions depending on Bokeh 3.0.x or 3.2.x
gotchaTrading decisions made in the `next()` method are typically executed on the *next* bar's open price (or current bar's close if `trade_on_close=True`). This simulation characteristic means immediate execution at the exact candle price that triggered a signal is not guaranteed, which can impact profitability, especially for high-frequency or tight stop-loss/take-profit strategies.
fix
Understand and account for this execution model. For more granular control or intra-candle trading, use higher-frequency data.
affects: All
gotchaWhen defining indicators within `Strategy.init()`, it's crucial to wrap indicator functions with `self.I()`. This ensures that indicator values are revealed gradually, bar-by-bar, simulating real-time data availability and preventing look-ahead bias. Failing to do so (e.g., directly computing indicators on `self.data.Close` for the full dataset outside `self.I()`) will lead to unrealistic, overly optimistic backtest results.
fix
Always use `self.I(indicator_func, data_series, *args)` for all technical indicators in your `init()` method.
affects: All
gotchaIf a trading position is opened with `self.buy()` or `self.sell()` but never explicitly closed (e.g., with `self.position.close()`, `self.sell()`, or `self.buy()`), it will remain open until the end of the backtest. This can lead to misleading or `NaN`/`0` values in performance statistics because trades are not fully realized within the backtesting period.
fix
Ensure your strategy includes logic to close positions, either explicitly with an opposing order or `self.position.close()`, or by using `exclusive_orders=True` in `Backtest` constructor to automatically close previous positions on new opposing orders.
affects: All
Errors
Common errors & fixes
ValueError: OHLC data is incomplete. Index, 'Open', 'High', 'Low', 'Close' must not contain NaN values.
The input DataFrame provided to `Backtest` contains missing (NaN) values in the required 'Open', 'High', 'Low', 'Close' columns or has a non-DatetimeIndex, which `backtesting.py` requires for valid OHLCV data.
fix
Ensure your DataFrame has a `pd.DatetimeIndex` and all 'Open', 'High', 'Low', 'Close' columns are free of NaN values by using methods like `df.dropna()` or `df.interpolate()` before passing it to `Backtest`.
TypeError: Strategy.__init__() missing 1 required positional argument: 'broker'
When defining a custom strategy and overriding its `init` method, `super().__init__()` is called without the necessary 'broker' argument, which `backtesting.py`'s `Strategy` class constructor expects internally.
fix
The `super().__init__()` call within your `Strategy.init` method should not explicitly pass 'data' or 'params' and should be called without arguments if you are simply initializing the base Strategy. The `Backtest` class handles passing these to your strategy. You typically implement `self.I()` for indicators and `self.data` to access the OHLCV data.
AttributeError: 'mtrand.RandomState' object has no attribute 'random'
This error typically occurs during `Backtest.optimize()` and is due to an incompatibility with certain versions of NumPy, where `np.random.RandomState` no longer has a method named `random`.
fix
Upgrade `backtesting.py` to a version where this bug has been addressed (e.g., version 0.6.5 or newer, which includes a fix for this) or downgrade your NumPy version if an upgrade is not immediately possible. Check the `backtesting.py` GitHub issues for the specific fix version.
Backtest results show 0 trades or all NaN values in statistics.
This often happens when the trading logic within the `Strategy.next()` method does not correctly trigger `buy()` or `sell()` orders, or if positions are opened but never closed, leading to incomplete trade data. It can also be caused by incorrect access to `self.data` or indicators.
fix
Carefully review your `Strategy.next()` method. Ensure `self.buy()` and `self.sell()` conditions are met, and that positions are explicitly closed (`self.position.close()`) when appropriate, especially if new opposing trades are intended. Also, verify that indicators and data are accessed correctly using `self.data` or `self.I()`.
Upgrade
Version history
0.6.5latest on PyPI · released Jul 30, 2025
Audit
Dependencies
numpyrequiredNumerical array operations and indicator computation.
pandasrequiredDataFrame-based OHLCV data handling and results.
bokehrequiredInteractive HTML chart output. Specific versions (3.0.x and 3.2.x) are known to be incompatible.
Agent activity
56 hits · last 30 days
node
52
OpenAI (training)
1
Resources
backtesting — pip install backtesting · libregistry