Doc/Alternatives
Alternatives
------------
The thing with backtesting is, unless you dug into the dirty details yourself,
you can't rely on execution correctness, and you risk losing your house.
In addition, everyone has their own preconveived ideas about how a mechanical
trading strategy should be conducted, so everyone (and their brother)
just rolls their own backtesting frameworks.
Nowaday, that even means close to zero effort expended.
If after reviewing the docs and examples perchance you find
_Backtesting.py_ not your cup of tea,
welcome to have a look at some similar alternative Python backtesting frameworks
as proposed by the wider community:
- AwesomeQuant -
A somewhat curated list of libraries, packages, and resources for quants.
- QTradeX -
A powerful and flexible Python framework for designing, backtesting,
optimizing, and deploying algotrading bots.
- bt -
a framework based on reusable and flexible blocks of
strategy logic that support multiple instruments and
output detailed statistics and useful charts.
- vectorbt -
a pandas-based library for quickly analyzing trading strategies at scale.
- Basana -
A fork of PyAlgoTrade; async and event driven framework with focus on cryptos.
- Pinkfish -
a lightweight backtester for intraday strategies on daily data.
- finmarketpy -
a library for analyzing financial market data.
- pysystemtrade -
the open-source version of Robert Carver's backtesting engine that
implements systems according to his book _Systematic Trading:
A unique new method for designing trading and investing systems_.
- optopsy -
a nimble backtesting library for options trading.
- RQalpha -
a complete solution for programmatic traders from data acquisition,
algorithmic trading, backtesting, real-time simulation, live trading
to mere data analysis. Documentation in Chinese.
- zvt -
a quant trading platform which includes data recorder, factor calculation,
stock picking, backtesting, and unified visualization. Documentation partly in Chinese.
- Nautilus Trader -
high-performance, production-grade algorithmic trading platform written in Rust/Python,
with event-driven engine to backtest portfolios of automated trading strategies,
and also deploy those same strategies live, with no code changes.
#### Obsolete / Unmaintained / Hall of Fame
The following projects are mainly old, stale, incomplete, incompatible,
build-failing, abandoned, and here for posterity reference mostly:
- Backtrader -
a pure-python feature-rich framework for backtesting
and live algotrading with a few brokers.
- Zipline -
the backtesting and live-trading engine powering Quantopian — the
community-centered, hosted platform for building and executing strategies.
- PyAlgoTrade -
event-driven algorithmic trading library with focus on
backtesting and support for live trading.
- QTPyLib -
a versatile, event-driven algorithmic trading library.
- AlephNull -
extends the features of Zipline, for use within an institutional environment.
- ProfitPy -
a set of libraries and tools for the development, testing, and execution of
automated stock trading systems.
- prophet -
a microframework for financial markets, focusing on modeling
strategies and portfolio management.
- pybacktest -
a vectorized pandas-based backtesting framework,
designed to make backtesting compact, simple and fast.
- quant -
a technical analysis tool for trading strategies with a particularily
simplistic view of the market.
- QuantSoftware Toolkit -
a toolkit by the guys that soon after went to form Lucena Research.
- QuantStart QSForex -
an event-driven backtesting and live-trading platform for use in
the foreign exchange markets,
- QuantStart QSTrader -
a modular schedule-driven backtesting framework for long-short equities
and ETF-based systematic trading strategies.
- tia: Toolkit for integration and analysis -
a toolkit providing Bloomberg data access, PDF generation,
technical analysis and backtesting functionality.
- TradingWithPython -
boiler-plate code for the (no longer active) course _Trading With Python_.
- Ultra-Finance -
real-time financial data collection, analyzing and backtesting trading strategies.
- visualize-wealth -
a library to construct, backtest, analyze, and evaluate portfolios
and their benchmarks, with comprehensive documentation illustrating
all underlying methodologies and statistics.
- Quantdom -
a Qt-based framework that lets you focus on modeling financial strategies,
portfolio management, and analyzing backtests.
- Clairvoyant -
software for identifying and monitoring social / historical cues
for short-term stock movement.
- Gemini -
a backtester namely focusing on cryptocurrency markets.
- AutoTrader -
an automated trading framework with an emphasis on cryptocurrency markets
that includes a robust backtesting API
- LiuAlgoTrader -
A scalable, multi-process ML-ready framework for effective algorithmic trading.
---
Doc/README
Backtesting.py Documentation
============================
After installing documentation dependencies:
pip install .[doc,test]
build HTML documentation by running:
./build.sh
When submitting pull requests that change example notebooks,
commit example _.py_ files too
(build.sh should tell you how to make them).
---
CHANGELOG
What's New
==========
These were the major changes contributing to each release:
0.x.x
0.6.6
(2026-07-22)
* Bug fixes:
* Fix read-only array error in FractionalBacktest with Pandas 3.0
* Fix CAGR and annualized return calculations (#1346)
* Preserve stop-loss value in stats._trades when SL is gapped through (#1369)
* Fix inactive filterwarnings filter in FractionalBacktest
* Fix "Indicators must return ... same length as data" ValueError in some edge cases
* Fix MultiBacktest error with some runs making no trades (#1366)
* Perfomance improvements:
* Keep multiprocessing start method "fork" on GNU/Linux
* Vectorize trade resampling in plot() for ~9x speedup (#1350)
(Note, one always needs to account for Amdahl's law.)
* Speed Enhancements by influencer Chad Thackray 🤘 (#1330)
* Minor enhancement:
* Format NaN fields as "--" in stats series
* Various other small fixes and documentation improvements.
0.6.5
(2025-07-30)
* Include 'Commission' column in stats._trades DataFrame (#1277), thanks to Abhirath Mahipal.
* Bug fixes:
* Fix computing commissions when specified with relative amount.
* Fix sometimes cleared SL value in stats._trades data frame
* Ensure order size is integer to avoid weird rounding errors.
* Account for commissions in Trade.pl and Trade.pl_pct (#1279), thanks to Abhirath Mahipal.
* functools.partial objects do not always have a __module__ attr in Python 3.9
* Plotting:
* Return long/short triangles to P&L section!
* Do plot plot=False, overlay=True indicators, but muted.
0.6.4
(2025-03-30)
* Bug fixes:
* Fix optimization hanging on MS Windows under some conditions,
primarily missing a if __name__ == '__main__' guard.
* Restore original scale in FractionalBacktest plot (#1247)
* Fix "'CAGR [%]' must match a key in pd.Series result of bt.run()" error
* Fix grid optimization on data with timezone-aware datetime index
0.6.3
(2025-03-11)
* Enhancements:
* backtesting.lib.TrailingStrategy supports setting trailing stop-loss by percentage.
* backtesting.lib.MultiBacktest
multi-dataset backtesting wrapper.
* Backtest.run() wrapped in tqdm()
* Rename parameter lib.FractionalBacktest(fractional_unit=).
* Add market alpha & market beta stats (#1221)
* Plot improvements:
* Plot trade duration lines in the P&L plot section.
* Simplify PL section, use circular markers.
* Only plot trades when some trades are present.
* Set fig.yaxis.ticker.desired_num_ticks=3 for indicator subplots.
* Single legend item for indicators with singular/default names.
* Make "OHLC" itself a togglable legend item.
* Add xwheel_pan tool, conditioned on activation for now
(upvote Bokeh issue).
* Reduce height of indicator charts, introduce an overridable private
global backtesting._plotting._INDICATOR_HEIGHT.
* Bug fixes:
* Fixed Position.pl occasionally not matching Position.pl_pct in sign.
* SL _always_ executes before TP when hit in the same bar.
* Fix functools.partial objects do not always have a __module__ attr in Python 3.9 (#1233)
* Fix stop-market and TP hit within the same bar.
* Documentation improvements (warnings, links, ...)
0.6.2
(2025-02-19)
* Enhancements:
* Grid optimization with mp.Pool & mp.shm.SharedMemory (#1222)
* backtesting.lib.FractionalBacktest
that supports fractional trading
backtesting.__all__ for better from backtesting import and suggestions
* Bugs fixed:
* Fix remaining issues with trade_on_close=True
* Fix trades reported in reverse chronological order when finalize_trades=True
* Fix crosshair not linked across subplots
* Cast datetime_arr.astype(np.int64) to avoid Windos error
0.6.1
(2025-02-04)
Enhancement: Use joblib.Parallel for optimization.
This should vastly improve performance on Windows while not
affecting other platforms too much.
0.6.0
(2025-02-04)
* Enhancements:
* Add Backtest(spread=); change Backtest(commission=) to apply twice per trade
* Show paid "Commissions [$]" key in trade stats
* Allow multiple names for vector indicators (#980)
* Add columns SL and TP to stats['trades'] (#1039)
* Add entry/exit indicator values to stats['trades'] (#1116)
* Optionally finalize trades at the end of backtest run (#393)
* Bug fixes, including for some long-standing bugs:
* Fix bug in Sharpe ratio with non-zero risk-free rate (#904)
* Change price comparisons to lte/gte to align with TradingView
* Reduce optimization memory footprint (#884)
* Fix annualized stats with weekly/monthly data
* Fix AssertionError on for o in self.orders: o.cancel()
* Fix plot not shown in VSCode Jupyter
* Buy&Hold duration now matches trading duration
* Fix bt.plot(resample=True) with categorical indicators
* Several other small bug fixes, deprecations and docs updates.
0.5.0
(2025-01-21)
* Enhancements:
* New Backtest.optimize(method="sambo");
uses SAMBO:
to replace method="skopt".
* New 'CAGR [%]' (compound annual growth rate) statistic.
* Bug fixes:
* "stop-loss executed at a higher than market price".
* Bug with buy/sell size=0.
* Order.__repr__ issue with non-numeric Order.tag.
* Other small fixes, deprecations and docs updates.
0.4.0
(2025-01-21)
* Enhancements:
* 'Kelly Criterion' statistic (#640)
* Backtest.plot(plot_trades=) parameter
* Order.tag for tracking orders and trades (#200)
* Small bug fixes, deprecation removals and documentation updates.
0.3.3
(2021-12-13)
* Fix random generation with recent NumPy.
* Fix Pandas deprecation warnings.
* Replace Bokeh 3.0 deprecations.
0.3.2
(2021-08-03)
* New strategy performance method backtesting.lib.compute_stats (#281)
* Improve plotting speed (#329) and optimization performance (#295) on large datasets.
* Commission constraints now allow for market-maker's rebates.
* Backtest.plot
now returns the bokeh figure object for further processing.
* Other small bugs and fixes.
0.3.1
(2021-01-25)
* Avoid some pandas.Index deprecations
* Fix Backtest.plot(show_legend=False) for recent Bokeh
0.3.0
(2020-11-24)
* Faster model-based optimization using scikit-optimize (#154)
* Optionally faster optimization by randomized grid search (#154)
* _Annualized_ Return/Volatility/Sharpe/Sortino/Calmar stats (#156)
* Auto close open trades on backtest finish
* Add Backtest.plot(plot_return=), akin to plot_equity=
* Update Expectancy formula (#181)
0.2.4
(2020-10-27)
* Add lib.random_ohlc_data() OHLC data generator
* Aggregate Equity on 'last' when plot resampling
* Update stats calculation for Buy & Hold to be long-only (#152)
0.2.3
(2020-09-10)
* Link hover crosshairs across plots
* Clicking plot legend glyph toggles indicator visibility
* Fix Bokeh tooltip showing literal '\ '
0.2.2
(2020-08-21)
0.2.1
(2020-08-03)
* Add Trade.entry_time/.exit_time
* Handle SL/TP hit on the same day the position was opened
0.2.0
(2020-07-15)
* New Order/Trade/Position API (#47)
* Add data pandas accessors .df and .s
* Add Backtest(..., exclusive_orders=) that closes previous trades on new orders
* Add Backtest(..., hedging=) that makes FIFO trade closing optional
* Add bt.plot(reverse_indicators=) param
* Add bt.plot(resample=) and auto-downsample large data
* Use geometric mean return in Sharpe/Sortino stats computation
0.1.8
(2020-07-14)
* Add Profit Factor statistic (#85)
0.1.7
(2020-03-23)
* Fix support for 2-D indicators
* Fix tooltip Date field formatting with Bokeh 2.0.0
0.1.6
(2020-03-09)
0.1.5
(2020-03-02)
0.1.4
(2020-02-25)
0.1.3
(2020-02-24)
* Show number of trades on OHLC plot legend
* Add parameter agg= to lib.resample_apply()
* Reset position price (etc.) after closing position
* Fix pandas insertion error on Windos
0.1.2
(2019-09-23)
* Make plot span 100% of browser width
0.1.1
(2019-09-23)
* Avoid multiprocessing trouble on Windos (#6)
* Add scatter plot indicators
0.1.0
(2019-01-15)
* Initial release
---
CONTRIBUTING
Contributing guidelines
=======================
Issues
------
Before reporting an issue, see if a similar issue is already open.
Also check if a similar issue was recently closed — your bug might
have been fixed already.
To have your issue dealt with promptly, it's best to construct a
[minimal working example] that exposes the issue in a clear and
reproducible manner. Review [how to report bugs effectively][bugs]
and, particularly, how to
[craft useful bug reports][bugs2] in Python.
In case of bugs, please submit full tracebacks.
Remember that GitHub Issues supports [markdown] syntax, so
please wrap verbatim example code/traceback in
triple-backtick-[fenced code blocks],
such as:
~~~markdown
def foo():
...~~~
and use the post preview function before posting!
Many thanks from the maintainers!
Note, In most cases, the issues are most readily dealt with when
accompanied by [respective fixes/PRs].
[minimal working example]: https://en.wikipedia.org/wiki/Minimal_working_example
[bugs]: https://www.chiark.greenend.org.uk/~sgtatham/bugs.html
[bugs2]: https://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports
[markdown]: https://www.markdownguide.org/cheat-sheet/
[fenced code blocks]: https://www.markdownguide.org/extended-syntax/#syntax-highlighting
[respective fixes/PRs]: https://github.com/kernc/backtesting.py/blob/master/CONTRIBUTING.md#pull-requests
Installation
------------
To install a _developmental_ version of the project,
first [fork the project]. Then:
git clone [email protected]:YOUR_USERNAME/backtesting.py
cd backtesting.py
pip install -e '.[doc,test,dev]'
[fork the project]: https://help.github.com/articles/fork-a-repo/
Testing
-------
Please write reasonable unit tests for any new / changed functionality.
See _backtesting/test_ directory for existing tests.
Before submitting a PR, ensure the tests pass:
python -m backtesting.test
Also ensure that idiomatic code style is respected by running:
flake8 backtesting
mypy backtesting
Documentation
-------------
See _doc/README.md_. Besides Jupyter Notebook examples, all documentation
is generated from [pdoc]-compatible markdown docstrings in code.
[pdoc]: https://pdoc3.github.io/pdoc
Pull requests
-------------
A general recommended reading:
[How to make your code reviewer fall in love with you][code-review].
Use explicit commit messages — see [NumPy's development workflow]
for inspiration.
Every new feature must be accompanied by a unit test.
Please help review [existing PRs] you wish to see included.
[code-review]: https://mtlynch.io/code-review-love/
[NumPy's development workflow]: https://numpy.org/doc/stable/dev/development_workflow.html
[existing PRs]: https://github.com/kernc/backtesting.py/pulls
---
README
[](https://kernc.github.io/backtesting.py/)
Backtesting.py
==============
[](https://github.com/kernc/backtesting.py/actions)
[](https://codecov.io/gh/kernc/backtesting.py)
[](https://ghloc.vercel.app/kernc/backtesting.py)
[](https://pypi.org/project/backtesting)
[](https://pypistats.org/packages/backtesting)
[](https://pypistats.org/packages/backtesting)
[](https://github.com/kernc/backtesting.py)
[](https://github.com/sponsors/kernc)
Backtest trading strategies with Python.
Project website + [Documentation] | [YouTube]
[Documentation]: https://kernc.github.io/backtesting.py/doc/backtesting/
[YouTube]: https://www.youtube.com/results?q=%22backtesting.py%22
Installation
------------
$ pip install backtesting
Or if you prefer the bleeding edge:
$ pip install git+https://github.com/kernc/backtesting.py
Usage
-----
from backtesting import Backtest, Strategy
from backtesting.lib import crossoverfrom 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()
Results in:
/ Detailed source-code truncated for AI context efficiency. /[](https://kernc.github.io/backtesting.py/#example)
Find more usage examples in the [documentation].
Features
--------
* Simple, well-documented API
* Blazing fast execution
* Built-in optimizer
based on SAMBO
* Library of composable base strategies
and related utilities
* Indicator-library-agnostic (BYO)
* Supports _any_ financial instrument with OHLC(V) candlestick data
* Detailed trade results
provided as simple Series/DataFrame objects
* Interactive visualizations
Bugs
----
Before reporting bugs or posting to the
discussion board,
please read contributing guidelines, particularly the section
about crafting useful bug reports and ``` ` ```-fencing your code.
The maintainers thank you!
Alternatives
------------
See [alternatives.md] for a list of alternative Python
backtesting frameworks and related packages.
[alternatives.md]: https://github.com/kernc/backtesting.py/blob/master/doc/alternatives.md
---