Install

The easiest way to install it is with pip:

pip install backtest-pro

There are a lot of dependencies that are optionals, but useful to have:

  • TA-Lib: A technical analysis library that is used to calculate technical indicators.
  • Plotly: A plotting library that is used to render charts during the production of reports.
  • WeasyPrint: A library that converts html to pdf. It is used to render the reports in pdf format.
  • kaleido: An optional library of Plotly that is used to render the charts in the reports.
  • schedule: A library that is used to schedule the run of the strategy in production.
  • python-crontab: A library that is used to schedule the run of the strategy in production.

To install all the optional dependencies with backtest-pro, you can run the following command:

pip install backtest-pro[optional]

Build from source

To get access to the latest features of the framework, you can build it from source. Note that it is not recommended to do this for a production project as the api might change without warning and some features might be unstable.

To install backtest-pro from source, you can clone the repository and install it using pip:

git clone https://github.com/anthol42/backtestPro.git

Move to the cloned repository:

cd backtestPro

Then, install the package:

pip install .

Example

This example shows how to backtest a simple strategy based on technical analysis. The strategy buys long when the MACD crosses over the signal line and sells when the MACD crosses under it. It is also required that the MACD is below 0 to trigger a buy. All default backtest parameters are used. The backtest is executed on the Magnificent 7 stocks from 2010 to 2020.

from backtest import Strategy, Backtest
from backtest.indicators import IndicatorSet, TA
from backtest.data import FetchCharts, ToTSData, Cache, PadNan
import backtest.engine.functional as F
from datetime import datetime

class MyStrategy(Strategy):
    def run(self, data, timestep):
        for ticker in data.main.tickers:
            chart = data.main[ticker].chart
            if len(chart) > 2 and F.crossover(chart["MACD"], chart["MACD_SIGNAL"]) and chart["MACD"].iloc[-1] < 0:
                if ticker not in self.broker.portfolio.long:
                    self.broker.buy_long(ticker, 500)
            if ticker in self.broker.portfolio.long and F.crossunder(chart["MACD"], chart["MACD_SIGNAL"]):
                self.broker.sell_long(ticker, 500)

# The magnificent 7 tickers
TICKERS = ["META", "AMZN", "AAPL", "NVDA", "GOOGL", "MSFT", "TSLA"]
data_pipeline = FetchCharts(TICKERS, auto_adjust=False) | PadNan() | ToTSData() | Cache()
bt = Backtest(data_pipeline.get(datetime(2010, 1, 1), datetime(2020, 1, 1)),
              strategy=MyStrategy(),
              indicators=IndicatorSet(TA.MACD()))
results = bt.run()
print(results)

For more examples, please check our Tutorials section.