Install the package
Install backtesting.py from PyPI:See the installation guide for full details including dependencies and environment notes.
Import required modules
Open a Python script or Jupyter notebook and import the three things you need:
Backtest— the simulation engine.Strategy— the abstract base class your strategy must extend.crossover— a helper frombacktesting.libthat returnsTrueon the bar where one series crosses above another.SMA— a simple moving average function included for testing.GOOG— a built-in DataFrame of daily Google (Alphabet) OHLCV data from 2004 to 2013, used throughout the documentation examples.
Define a strategy
Subclass
Strategy and implement two methods:init()— called once before the simulation. Declare indicators here usingself.I().next()— called once per bar (candle). Place or close orders here.
self.I(func, *args) wraps an indicator function so the engine reveals its values gradually as the simulation progresses bar-by-bar, matching how a live system would see the data.The strategy buys when the 10-day SMA crosses above the 20-day SMA and sells (goes short or closes) when the 20-day crosses back above the 10-day.Create and run a Backtest
Pass your data and strategy class to
Backtest, then call run():commission=.002— 0.2% round-trip commission per trade.exclusive_orders=True— each newbuy()orsell()automatically closes any open position in the opposite direction before opening the new one, keeping position management simple.
bt.run() returns a pandas.Series containing every performance metric.Read the statistics
Running the example above prints output similar to:The strategy returned 589% over the period versus a buy-and-hold return of 703%, with a CAGR of 16.8%, a Sharpe ratio of 0.66, and a maximum drawdown of -33%. It executed 93 trades with a 53.8% win rate.
stats._trades is a full DataFrame of every individual trade with entry/exit bars, sizes, P&L, and commissions. stats._equity_curve is the equity curve as a time series.Plot the results
Open an interactive Bokeh chart:The chart shows the OHLC candlestick data, your declared indicators overlaid or in sub-panels, trade entry/exit markers, and the equity curve with drawdown periods highlighted.
bt.plot() opens a browser window when run from a standalone script. In a Jupyter notebook it renders inline. If you are running in a non-interactive environment, pass filename="output.html" to save the chart to a file instead.Complete example
Here is the entire working example in one block:Next steps
Now that you have a working backtest, explore the rest of the documentation to go further:- Bring your own OHLCV data as a pandas DataFrame with a
DatetimeIndex. - Add parameters to your strategy and use
bt.optimize()to find the best values. - Use composable base strategies from
backtesting.libsuch asTrailingStrategyorSignalStrategy. - Plug in any indicator library — TA-Lib, pandas-ta, or your own NumPy functions — via
self.I().