backtesting
Backtest trading strategies in Python
What it is and what it does
Backtesting.py is a Python framework for testing trading strategies against historical OHLC candlestick data. You define a strategy class with entry and exit logic, pass it historical price data (from any source), and the framework simulates trades, calculates performance metrics (Sharpe ratio, Sortino ratio, max drawdown, win rate, etc.), and generates interactive visualizations via bokeh. It handles position sizing, commissions, and order management automatically.
The package is built on numpy and pandas for fast numerical computation and data handling. It includes a built-in optimizer for parameter tuning, a library of common technical indicators and base strategies, and produces detailed trade-by-trade results as DataFrames. It's designed to be indicator-agnostic—you bring your own indicators or use the provided utilities—and supports any financial instrument with candlestick data (stocks, crypto, forex, futures, etc.).
Use it for:
- Test a moving-average crossover or other rule-based strategy on years of historical stock or crypto data to measure profitability and risk.
- Optimize strategy parameters (e.g., moving-average periods) by running the built-in optimizer across a grid or search space.
- Compare multiple strategy variants side-by-side to see which has the best Sharpe ratio, lowest drawdown, or highest win rate.
- Generate equity curves and trade logs as pandas DataFrames for further analysis or reporting in Jupyter notebooks.
- Validate a trading idea before committing capital by simulating it on historical data with realistic commission and slippage assumptions.
Worth the install?
AI-flagged interpretation of the facts on this page — verify before relying
Backtesting.py lets you define and test trading strategies against historical price data, then visualize results and performance metrics like Sharpe ratio, drawdown, and win rate.
Yes, if you are developing or researching trading strategies and want a lightweight, well-maintained framework with low install friction. The AGPL-3.0 license is a blocker for closed-source commercial use unless you obtain a separate license; for open-source or internal research, it poses no issue. No known security vulnerabilities. Active maintenance and a large user base make it a reliable choice for backtesting.
Install
backtesting on PyPI
pip
pip install backtestinguv
uv add backtestingpoetry
poetry add backtestingInstalling backtesting
Before you install
Low friction install with just three runtime dependencies (numpy, pandas, bokeh). Active maintenance with recent commits and a substantial user base; last release was 23 days ago.
License in practice
Licensed under AGPL-3.0, which requires that any modifications or derivative works you distribute must also be open-source under the same license. Suitable for internal research or open-source projects, but commercial closed-source use requires careful review or a separate license.
Quickstart
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)
stats = bt.run()
bt.plot()
Requires Python 3.9 or later.
Verify before relying
- Whether the built-in optimizer (SAMBO-based) is suitable for your strategy complexity or parameter space size
- Performance characteristics when backtesting very large datasets or high-frequency strategies
- Whether the package supports live trading or only historical backtesting
Package facts
| License | AGPL-3.0 (agpl) |
| Python support | supports the current Python release (>=3.9) |
| Install friction | low — pure-Python wheel |
| Runtime dependencies | 3 — numpy, pandas, bokeh |
| Maintenance | actively maintained — 23 days since the last release |
| Last repo commit | |
| First released | |
| Downloads | 183,712/month — #10,062 on PyPI (30-day window, as of 2026-08-14) |
| Known vulnerabilities | none known (OSV.dev, checked 2026-08-14) |
Evidence: backtesting-0.6.6-py3-none-any.whl
Keywords: algo, algorithmic, ashi, backtest, backtesting, bitcoin, bokeh, bonds, candle, candlestick, cboe, chart, cme, commodities, crash, crypto, currency, doji, drawdown, equity, etf, ethereum, exchange, finance, financial, forecast, forex, fund, futures, fx, fxpro, gold, heiken, historical, indicator, invest, investing, investment, macd, market, mechanical, money, oanda, ohlc, ohlcv, order, price, profit, quant, quantitative, rsi, silver, simulation, stocks, strategy, ticker, trader, trading, tradingview, usd
Tags
More Visualization packages
matplotlib creates static, animated, and…
permissive · top 1,000 on PyPI
contourpyContourPy calculates contours of 2D…
permissive · top 1,000 on PyPI
plotlyPlotly is an interactive, browser-based…
permissive · top 1,000 on PyPI
graphvizGenerates DOT language source code for graph…
permissive · top 1,000 on PyPI
streamlitStreamlit transforms Python scripts into…
permissive · top 1,000 on PyPI
leatherLeather is a lightweight Python charting…
permissive · top 1,000 on PyPI
backtraderBacktrader is a Python backtesting and live…
copyleft · top 15,000 on PyPI
finlabBacktest trading strategies on Taiwan stock…
copyleft · top 15,000 on PyPI
lumibotLumibot is a Python framework for building,…
permissive · top 15,000 on PyPI
mplfinancemplfinance provides matplotlib-based…
permissive · top 15,000 on PyPI
vectorbtVectorized backtesting engine that packs…
unclear · top 15,000 on PyPI
nautilus_traderNautilusTrader is a Rust-native event-driven…
copyleft · top 15,000 on PyPI
gs-quantGS Quant is a Python toolkit for quantitative…
permissive · top 15,000 on PyPI
freqtradeFreqtrade is a Python-based cryptocurrency…
copyleft · top 15,000 on PyPI
quantstatsQuantStats computes portfolio performance…
permissive · top 15,000 on PyPI
empyrical-reloadedComputes financial return and risk…
permissive · top 15,000 on PyPI