Introduction to Zipline in Python

Share on Facebook53Tweet about this on Twitter107Share on LinkedIn22Share on Google+3

Introduction to Zipline in Python

By Priyanka Sah

Introduction

Python has emerged as one of the most popular language for programmers in financial trading, due to its ease of availability, user-friendliness and presence of sufficient scientific libraries like Pandas, NumPy, PyAlgoTrade, Pybacktest and more.

Python serves as an excellent choice for automated trading when the trading frequency is low/medium, i.e. for trades which do not last less than a few seconds. It has multiple APIs/Libraries that can be linked to make it optimal, cheaper and allow greater exploratory development of multiple trade ideas.

It is due to these reasons that Python has a very interactive online community of users, who share, reshare, and critically review each other’s work or codes. The two current popular web-based backtesting systems are Quantopian and QuantConnect.

Quantopian makes use of Python (and Zipline) while QuantConnect utilises C#. Both provide a wealth of historical data. Quantopian currently supports live trading with Interactive Brokers, while QuantConnect is working towards live trading.

Zipline is a Python library for trading applications that powers the Quantopian service mentioned above. It is an event-driven system that supports both backtesting and live-trading.

In this article we will learn how to install Zipline and then how to implement Moving Average Crossover strategy and calculate P&L, Portfolio value etc.

This article is divided into the following four sections:

  • Benefits of Zipline
  • Installation (how to install Zipline on local)
  • Structure (format to write code in Zipline),
  • Coding Moving average crossover strategy with Zipline

Benefits of Zipline

  • Ease of use
  • Zipline comes “batteries included” as many common statistics like moving average and linear regression can be readily accessed from within a user-written algorithm.
  • Input of historical data and output of performance statistics are based on Pandas DataFrames to integrate nicely into the existing PyData ecosystem
  • Statistic and machine learning libraries like matplotlib, scipy, statsmodels, and sklearn support development, analysis, and visualization of state-of-the-art trading systems

Installation

Using pip

Assuming you have all required non-Python dependencies, you can install Zipline with pip via:

Using conda

Another way to install Zipline is via the conda package manager, which comes as part of Anaconda or can be installed via pip install conda.

Once setup, you can install Zipline from our Quantopian channel:

Basic structure

Zipline provide a particular structure to code which includes defining few functions that runs the algorithms over a dataset as mentioned below.

So, first we first have to import some functions we would need to use in the code. Every Zipline algorithm consists of two functions you have to define:

* initialize(context) and * handle_data(context, data)

Before the start of the algorithm, Zipline calls the initialize() function and passes in a context variable. Context is a global variable that provide 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.

All functions commonly used in the algorithm can be found in Zipline.api module. Here we are using order(arg1, arg2) that takes two arguments: a security object, and a number specifying how many stocks you would like to order (if negative, order() will sell/short stocks). In this case we want to order 10 shares of Apple at each iteration.

Now, the second method record() allows you to save the value of a variable at each iteration. You provide it with a name for the variable together with the variable itself. After the algorithm finished running you can all the variables you recorded, we will learn how to do that.

To run the algorithm, you would need to call TradingAlgorithm() that uses two arguments: initialize function, and handle_data.  Then, call run method using data as argument on which algorithm will run (data is panda data frame that stores the stocks prices)

run() first calls the initialize() function, and then streams the historical stock price day-by-day through handle_data(). After each call to handle_data() we instruct Zipline to order 10 stocks of AAPL.

How to code Moving average crossover strategy with Zipline

Moving Averages

It is the simple average of a security over a defined number of time periods.

Crossover

Moving average crossovers are a common way traders can use Moving Averages. A crossover occurs when a faster Moving Average (i.e. a shorter period Moving Average) crosses either above a slower Moving Average (i.e. a longer period Moving Average) which is considered a bullish crossover or below which is considered a bearish crossover.

Now we will learn how to implement this strategy using Zipline. To import libraries and initialize variables that will be used in algorithm.

The code is divided into 5 parts

  • Initialization
  • Initialize method
  • handle_data method
  • Strategy logic
  • Run Algo

Initialization

#code

load_bars_from_yahoo() is the function that takes stock and time period for which you want to fetch the data. here i am using SPY stocks between 2011 to 2012, you can change this according to you.

Initialize method

Now we would define initialize function, context.security represents the stock that we are dealing with, in our case its SPY.

handle_data method

handle_data() contains all the operation we want to do, the main code for out aldorithm. we need to calculate moving averages for diffrent windows, Zipline gives an inbulit function mavg() that takes an integer to define the window size.

Also, Zipline automatically calculates current_price, portfolio_value etc. we can just call the variables, in this algo i have calculated current_positions, price, cash, portfolio_value, pnl.

Strategy logic

Now the logic that will place the order for buy or sell depending upon the condition that compares moving averages.

  1. If short moving average is greater than longer one and your current_positions is 0 then you need to calcuate the no of shares and place an order
  2. If short moving average is smaller than longer one and your current_positions is not 0 then you need to sell all the shares that you have currently.
  3. Third condition is if nothing satisfies then do nothing just record the variables you need to save.

Run

For running this algo, you need the following code:

You can plot the graph also using method plot()

Graph for the strategy

graph of moving crossover strategy using zipline

Snapshot of the screen using Zipline

Snapshot of screen in Zipline

Conclusion

We hope that you found this introduction to zipline and implementing a strategy using the same useful. For building technical indicators using python, here are few examples.

If you are a coder or a tech professional looking to start your own automated trading desk. Learn automated trading from live Interactive lectures by daily-practitioners. Executive Programme in Algorithmic Trading covers training modules like Statistics & Econometrics, Financial Computing & Technology, and Algorithmic & Quantitative Trading. Enroll now!

Share on Facebook53Tweet about this on Twitter107Share on LinkedIn22Share on Google+3

5 thoughts on “Introduction to Zipline in Python

  1. July 20, 2016

    Paska Reply

    A lot easier with a modern library like backtrader


    import datetime
    import backtrader as bt

    class CrossOverStrat(bt.Strategy):
    params = (('stake', 10), ('period1', 50), ('period2', 200))

    def __init__(self):
    sma1 = bt.indicators.SMA(self.data0, period=self.p.period1)
    sma2 = bt.indicators.SMA(self.data0, period=self.p.period2)
    self.signal = bt.indicators.CrossOver(sma1, sma2, plot=False)

    def next(self):
    if self.position:
    if self.signal 0:
    self.buy(size=self.p.stake)

    fromdate = datetime.datetime(2011, 1, 1)
    todate = datetime.datetime(2011, 12, 31)

    cerebro = bt.Cerebro()
    cerebro.addstrategy(CrossOverStrat)

    data0 = bt.feeds.YahooFinanceData(dataname='YHOO',
    fromdate=fromdate, todate=todate)
    cerebro.adddata(data0)
    cerebro.run()
    cerebro.plot()

  2. July 20, 2016

    arun Reply

    Nice post. Is it possible to use zipline live for trading with brokers who provide api access other than IB.

    • July 22, 2016

      priyanka Reply

      Any broker that provides python api, can be integrated with this zipline code. I personally have just worked on IB.

  3. July 21, 2016

    Panda Reply

    Thanks for a great post!
    Is it possible to use ZipLine with Futures or FX data?

    • July 22, 2016

      Priyanka Reply

      Yes, it is possible, you can download the data in csv format and fetch the data in code in panel format.

Leave a Reply

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