Backtrader for Backtesting (Python): All You Need to Know


Source Link: https://algotrading101.com/learn/backtrader-for-backtesting/

If you want to backtest a trading strategy using Python, you can either build your own backtester, use a cloud trading platform, or run the backtests using pre-existing libraries like Backtrader and Zipline.

In this article, we will use Backtrader as our pre-existing library. This option gets the job done, and you can store everything safely on your local computer.

What is Backtrader?

Backtrader is a Python library that helps traders in strategy development and testing. Backtrader is an open-source framework that helps traders test strategies based on historical data. Also, it can be used to optimize strategies and make visual plots, and you can even use it for live trading.

Reasons to use Backtrader

Aside from being time-efficient when testing market strategies, here are a few reasons why you should use Backtrader:

  • Backtesting – Backtrader eliminates the long and tiresome process of cleaning up your data to test strategies. Importing data is easier because it comes with built-in templates that you can use for different data sources.
  • Optimizing – With Backtrader, you can easily optimize strategies after running a backtest by changing a few lines of code. Very convenient!
  • Plotting – Visual plotting can easily be done with Backtrader. You can create a complex chart with a single line of code.
  • Indicators – In the Backtrader platform, popular indicators are already programmed. Thus, you can easily test it out easily.
  • Support for complex strategies – No matter how complex the strategies are, Backtrader has extensive support. Whether you want data resampling or multiple timeframes on your strategy, Backtrader can help you with that.
  • Open-source – Since it is an open-source platform, you can have full access to all the individual components. There is no limit; you can build on them if you want.
  • Active development – Backtrader was originally developed in 2015, and since then, improvements to the platforms have been implemented. The platform excels in this area.
  • Live trading – If you are happy with the backtesting results, you can migrate them to live trading within Backtrader.
Reasons NOT to use Backtrader
  • Steep learning curve – Because of the comprehensive things you need to learn, it will take some time to understand the logic and syntax used.
  • Understanding the Library – You need to understand the library to understand the framework. You need to extract 470 items when decompressing the source code. There are a lot of datasets and scripts to go through.
  • Create your own framework – Some people prefer to build their own backtesting platform. Creating your own platform is better than learning the library if you are only looking to get a general idea about a simple strategy.
How Backtrader Works: An Overview

In simpler terms, Backtrader will show you how your strategy might perform in the market by testing it against past price data. 

Some of the things that you can also do with the platform are the following:

  • The analyzer function of Backtrader can also be used to provide useful statistics.
  • The optimization option speeds up the testing of strategies with different parameters.
  • The platform utilizes matplotlib library to create charts at the end of your backtest if needed.
How to Install Backtrader

Install Backtrader using the command line: pip install backtrader

For charting functionality, install matplotlib (the minimum version requirement for matplotlib is 1.4.1).

To show the installed Python packages, type pip list t from the command line.

If you need to install it, you can do so either via pip install backtrader[plotting] or pip install matplotlib.

How to Configure the Basic Backtrader Setup

Here’s the script to configure the basic setup:

How to Get and Import Data

There are different ways to import data into Backtrader. If you signed up with a broker, you might have API access to the data. If not, you can use the third-party APIs available that allow you to download historical data from within your Python console.

Ex: We will download data in CSV format directly from the Yahoo Finance website.

  • Navigate Yahoo Finance website
  • Enter the data you are looking for.
  • Click on the historical data tab.
  • Select time period and click Apply.
  • Download data.

We can add our data to Backtrader using the built-in feeds template specifically for Yahoo Finance. 

data = bt.feeds.YahooFinanceCSVData(dataname=’TSLA.csv’) cerebro.adddata(data) 

Adding data can be done at any point between instantiating Cerebro and calling the cerebro.run() command.

How to Print or Log Data

The first thing we will do is create a new class called PrintClose.

Create a logging function.

Log the closing price.

The output should be:

How to Run A Backtest

The strategies script will be appropriately named strategies.py.

Here is our updated main script, which will be called btmain.py:

Let’s get started on our strategy!

The next item we will overwrite is the notify_order function.

Lastly, we have the next function, which contains our trade logic.

How to use the built-in crossover indicator

Here’s how:

Instantiate it in the __init__ function as follows: self.crossover = bt.indicators.CrossOver(self.fast_sma, self.slow_sma)

How to Run Optimization

Here is the code for the updated main script:

The result should be like this:

Now it’s time to run some backtests on the out-of-sample data. All it takes is a simple change to the data parameters.

The result should be:

How to build a stock screener

Start by creating a subclass of the Backtrader Analyzer class.

Iterate through the list to add the corresponding CSV files to cerebro.

Next, we add our newly created screener class to Cerebro as an analyzer.

Call the cerebro.run command with a few additional parameters. 

  • writer=True parameter calls the built-in writer functionality to display the ouput. 
  • stdstats=False removes some of the standard output (more on this later). 
  • runonce=False ensures that data remains synchronized.

Here are the results:

How to code an indicator

Here is an example:

Here’s the result:

How to plot in Backtrader

All you need to do is add cerebro.plot() to your code after calling cerebro.run().

Here’s an example:

This code will create a chart with TSLA and AAPL price data overlaid on top of each other.

Chart will be like this:

Here is a code example that will show TSLA price data with a 20-day moving average.

The chart will be like this:

How to use alternative data

Here is the code:

Here is our strategy class:

After running the backtest, here are our results:

How to add visual stats

We need to add the following line of code:

Save the results from our backtest, similar to what we did in the Sharpe Ratio example.

Import

Create a stats tearsheet.

Output should be like this:

How to save backtest data to a CSV file

Simply add the following line to your script.

There are other options as well if you’d like a more customized approach. Within the strategy class, we can overwrite the stop() function to save any variable within the class. 

Here is an example.

In the __init__ function, we’ve initialized a variable called log_pnl as a list.

Save the list to a file once the backtest is finished running.

We can save the returns data, or any of the other files by using the built-in to_csv() method from Pandas.

Download Code

https://github.com/PythonForForex/Backtrader-for-backtesting

want to learn how to algo trade so you can remove all emotions from trading and automate it 100%? click below to join the free discord and then join the bootcamp to get started today.


Leave a Reply

Your email address will not be published. Required fields are marked *