Backtesting.py

0.6.5 · active · verified Wed Apr 15

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.

Warnings

Install

Imports

Quickstart

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)

view raw JSON →