Backtesting Trading Strategies for Beginners: A Guide to Using Backtrader
What actually is backtesting?
In my personal opinion learning this skill is a superpower, because if you’re able to find a golden nugget that has consistently produced strong returns.. well then you’ve basically found a money printer.
Put simply, backtesting is the ability to apply a trading strategy to historical data and see how it would have performed.
You may have seen people attempt to do this with lines on charts but the major hedge funds all use backtesting frameworks.
There are a variety of tools out there but today we’re going to be looking at backtrader. Backtrader is a framework in python that provides a straightforward solution to backtesting strategies.
How to setup backtrader
Step 1 we need to install and import the backtrader framework and yfinance to supply it the historical data to test on.
What is a framework? Well its a package of software tools designed for you to build something in a specific way. It provides the guidelines and structure of how you should do it. This differs from a package in the sense that a package is a small building block which you can use in your desired way.
You will notice this comes into play in the way in which you have to design your strategy class. This is one downfall to using a framework like backtrader, is you have to rewrites your strategy code to suit the framework. You do get a lot of benefits in return though.
Step 2 we need to create a custom strategy class which will inherit from backtrader’s ‘Strategy’ class
Step 3 we need to create an instance of the cerebro engine
The cerebro engine is the brains of the whole operation. You supply the brain the strategy and the data and it does all the work for you.
Step 4 we need to download our data of choice and supply it to the cerebro engine
In this instance, we’ve used yfinance to easily get yahoo finance data as a dataframe and supply it to the engine, but you can use any data you want.
Finally, we add the strategy we built earlier and run the engine! And there we have it. You now the ability to go and explore as many strategies as you want, as simple or as complex as your brain desires, and just keep trying until you find that golden nugget or money printer.
Now of course, previous performance does not guarantee future performance, and we still might want to take some extra measures following a successful backtest such as paper trading. But, it is a great step in the right direction for finding a successful strategy.
How to:
Create folder
Pipenv install backtrader
Create file
import backtrader as bt
Create a strategy class that inherits from bt.Strategys
** You can use
self.data
to access the data you provide,
self.buy
and self.sell()
feed the cerebro engine your data, strategy and run it!