A flexible backtesting framework for Python
Actively maintained. Last release 7 weeks ago, commits in 18 of the last 26 weeks. A safe choice.
pip install btbt — Flexible Backtesting for Python
Build, test, and compare investment strategies from reusable Python components. bt combines strategy logic with historical price data, tracks portfolio positions and transactions, and provides performance statistics and charts through ffn.
- Compose strategy logic: combine algorithms for scheduling, security selection, weighting, and rebalancing.
- Build portfolios of strategies: nest strategies and securities in a common tree.
- Model trading costs: configure commissions and transaction cost models.
- Compare results: inspect returns, weights, transactions, drawdowns, and other statistics.
Install
pip install bt
See the installation guide for additional details.
A first backtest
This example uses synthetic prices, so it runs without downloading market data:
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()
The strategy selects both assets, gives each equal weight, and rebalances monthly. Replace the synthetic prices with your own data to explore a strategy. Backtest results depend on data quality and modeling assumptions; they do not predict future performance.