Algorithmic Trading Simulations Part II
Build and Backtest Trading Strategies using Zipline-Reloaded
In this articel we are going to look at how to run an algorithm on financial data. We are going to use the data that we ingested in the previous articel. Backtesting is basically evaluating the performance of a trading strategy on historical data. If we used a given strategy on a set of assets in the past, how well/bad would it have performed. Of course, there is no guarantee that past performance is indicative of the future one, but we can still investigate!
There are a few available frameworks for backtesting in Python. In this article we are going to use zipline-reloaded.
Build Trading Strategies using Zipline
Trading strategies can be defined as a method of buy and selling assets in markets that is based on predefined rules. These rules can be based on e.g. machine learning models. Backtesting is basically evaluating the performance of a trading strategy on historical data.
If we used a given strategy on a set of assets in the past, how well/bad would it have performed?
How to construct an algorithm
Every Zipline algorithm consists of two functions you have to define:
initialize(context)
handle_data(context, data)
Before the start of the algorithm, Zipline calls the initialize()
function and passes in a context
variable. context
is a persistent namespace for you to store variables you need to access from one algorithm iteration to the next. After the algorithm has been initialized, Zipline calls the handle_data()
function once for each event. At every call, it passes the same context
variable and an event-frame called data
containing the current trading bar with open, high, low, and close (OHLC) prices as well as volume for each stock in your universe.
How to run the Algortihm
Zipline provides three interfaces for running an algorithm on financial data:
- Command Line via the zipline command
- Jupyter Notebook via Zipline Magic
- Zipline in your IDE via
run_algorithm()
We are going to use all the three zipline interfaces for running an buy and hold strategy with zipline.
The Buy And Hold Strategy
The idea is that we buy a certain asset and do not do anything for the entire duration of the investment horizon. The Buy and hold strategy is a simple trading strategy with a boring performance. This simple strategy can also be considered a benchmark for more advanced ones because there is no point in using a very complex strategy that generates less money (for example due to transaction costs) than buying and doing nothing.
1. Command Line via Zipline Command
After you installed zipline you should be able to execute the following from your command line (e.g. Terminal app on OSX):
To execute an algorithm we call zipline run as follows:
2. Jupyter Notebook via Zipline Magic
We write the algorithm within a Notebook cell and indicate that zipline is supposed to run it. This is done via the %%zipline IPython magic command. This magic takes the same arguments as the CLI mentioned above . Also one important thing, all imports required for the algorithm to run (such as numpy
, sklearn
, etc.) must be specified in the algorithm cell, even if they were previously imported elsewhere.
Final portfolio value (including cash): 523.92$
Well we had a capital-base of 300 $ and bought 2 shares of Apple on the 04–01-2019. Two years later the final portfolio value is 523,92$.
3. Zipline in your IDE via run_algorithm()
To execute an algorithm like a Python script in your favorite IDE, use the run_algorithm()
function.
We can plot the results nicely.
If we bought two shares of Apple back in 2012 and just hold it until November 2021 we have a final portfolio value (including cash) of 528.41$.
To view the transactions we need to transform the transactions column from the performance DataFrame.
By inspecting the columns of the performance DataFrame
we can see all the available metrics.
To get an overview and some info we use .info(null_counts=True).
Simple Moving Average Strategy
A strategy that is also really common for trading equities is the simple moving average strategy (sma).