Python enables traders and investors to backtest their strategies so that they can assess whether the strategy is good or not by observing the past performance of the strategy. However, not everyone has a high level of coding skills that can implement their backtesting in the most accurate and efficient way. Thanks to the Backtrader library, everyone can backtest their strategies in an efficient and accurate way.
What is Backtrader?
Backtrader is an open-source Python library that you can use for backtesting, strategy visualisation, and live-trading.
Although it is quite possible to backtest your algorithmic trading strategy in Python without using any special library, Backtrader provides many features that facilitate this process. In general, every complex component of ordinary backtesting can be created with a single line of code by calling special functions.
How to install the Backtrader library?
There is no special requirement for installing the Backtrader library. It also doesn’t have any dependencies. You can install this library by using the package manager “pip”.
To install the Backtrader library by using the “pip” package manager, open the command prompt (or terminal for Mac users) then type the below code:
pip install backtrader
You can check whether it is installed successfully by trying the following code:
Although there are no dependencies, to use plotting features of the Backtrader library, “matplotlib” is required. You can install this library by using the same way.
Please note that the latest version of the matplotlib library may cause some errors while using it with Backtrader. It is compatible with version 3.2.2 of the matplotlib library. Therefore, you need to specify this version while installing.
pip install matplotlib==3.2.2
Now you are ready to use Backtrader with its full functionality.
Create your first code with Backtrader
In this part, you will go through the core components for creating a backtesting framework with the Backtrader library. As with all external libraries, first, you need to import the Backtrader library.
import backtrader as bt
The first thing you need to know about this library is the Cerebro class. It is the core of the library in which most of the works are done. It is an engine that fetches data, simulates the strategy and presents the findings and alternatively plots the inputs and the outputs.
Before going into another important component of Backtrader which is the strategy class, let’s check the ways for fetching the data. In the code above, “adddata()” must include your data as a parameter.
Therefore, before this line, you need to import data online or offline. Here are the two different options for reading data for Backtrader’s Cerebro:
How to backtest a strategy with Backtrader?
To backtest a strategy, you need to define a strategy class and add this strategy to the Cerebro instance by typing the name of the class inside the parenthesis in the above code.
In this part, you will go through the components of the strategy class. These components are the functions used for variable definition, trade actions logging and signal generations.
The first function is log():
This function is used for outputting the information which you would like to save and print. We will exemplify this function while explaining another function of this class, next():
This is a simple example that prints the closing prices. During the backtesting, this function is where you generate signals.
For example, let’s employ a strategy where it sells when the price drops below the 100-day moving average and buys when it crosses above the 100-day moving average.
However, before writing down this strategy, you should know another function of Backtrader, “__init__(self)”. This function is where you define the variables and indicators you use in your strategy. Thanks to Backtrader’s indicators feature, you can easily calculate technical indicators.
For this strategy, we need to calculate 100-day moving average. You can define this indicator by the following code:
Now you can create your custom strategy function to generate orders. Let’s say the entering rule is the one described above and the exit rule is keeping the position for 4 periods.
To summarise so far, we have created 3 functions for our strategy class. The first function is for logging which prints actions when we call it. The second one is the main function (“__init__”) where we define variables and indicators for our strategy. Then, we created the “next()” function to define enter and exit rules.
The last function is for checking whether our order sent via “next()” function is executed or not. This function is called “notify_order()”. This function is called to notify of order status.
Now you are ready to backtest a strategy.
Visit QuantInsti to read the full article: https://blog.quantinsti.com/backtrader/.
Disclosure: Interactive Brokers
Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.
This material is from QuantInsti and is being posted with its permission. The views expressed in this material are solely those of the author and/or QuantInsti and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.