Zipline Beginner Tutorial

Basics

Zipline is an open-source algorithmic trading simulator written in Python.

The source can be found at: https://github.com/quantopian/zipline

Some benefits include:

  • Realistic: slippage, transaction costs, order delays.
  • Stream-based: Process each event individually, avoids look-ahead bias.
  • Batteries included: Common transforms (moving average) as well as common risk calculations (Sharpe).
  • Developed and continuously updated by Quantopian which provides an easy-to-use web-interface to Zipline, 10 years of minute-resolution historical US stock data, and live-trading capabilities. This tutorial is directed at users wishing to use Zipline without using Quantopian. If you instead want to get started on Quantopian, see here.

This tutorial assumes that you have zipline correctly installed, see the installation instructions if you haven't set up zipline yet.

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. For more information on these functions, see the relevant part of the Quantopian docs.

My first algorithm

Lets take a look at a very simple algorithm from the examples directory, buyapple.py:


In [1]:
# assuming you're running this notebook in zipline/docs/notebooks
import os

if os.name == 'nt':
    # windows doesn't have the cat command, but uses 'type' similarly
    ! type "..\..\zipline\examples\buyapple.py"
else:
    ! cat ../../zipline/examples/buyapple.py


#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from zipline.api import order, record, symbol


def initialize(context):
    context.asset = symbol('AAPL')


def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))


# Note: this function can be removed if running
# this algorithm on quantopian.com
def analyze(context=None, results=None):
    import matplotlib.pyplot as plt
    # Plot the portfolio and asset data.
    ax1 = plt.subplot(211)
    results.portfolio_value.plot(ax=ax1)
    ax1.set_ylabel('Portfolio value (USD)')
    ax2 = plt.subplot(212, sharex=ax1)
    results.AAPL.plot(ax=ax2)
    ax2.set_ylabel('AAPL price (USD)')

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()


def _test_args():
    """Extra arguments to use when zipline's automated tests run this example.
    """
    import pandas as pd

    return {
        'start': pd.Timestamp('2014-01-01', tz='utc'),
        'end': pd.Timestamp('2014-11-01', tz='utc'),
    }

As you can see, we first have to import some functions we would like to use. All functions commonly used in your algorithm can be found in zipline.api. Here we are using order() which 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. For more documentation on order(), see the Quantopian docs.

Finally, the record() function 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: varname=var. After the algorithm finished running you will have access to each variable value you tracked with record() under the name you provided (we will see this further below). You also see how we can access the current price data of the AAPL stock in the data event frame (for more information see here).

Ingesting data for your algorithm

Before we can run the algorithm, we'll need some historical data for our algorithm to ingest, which we can get through a data bundle. A data bundle is a collection of pricing data, adjustment data, and an asset database. Bundles allow us to preload all of the data we will need to run backtests and store the data for future runs. Quantopian provides a default bundle called quantopian-quandl, which uses the Quandl WIKI Dataset. You can ingest that data by running:


In [2]:
! zipline ingest


Downloading Bundle: quantopian-quandl  [####################################]  100%          le: quantopian-quandl  [------------------------------------]    1%Downloading Bundle: quantopian-quandl  [####################----------------]   57%  00:00:08Downloading Bundle: quantopian-quandl  [###############################-----]   87%  00:00:03
Writing data to /Users/freddiev4/.zipline/data/quantopian-quandl/2017-06-15T20;02;11.957695.

For more information on data bundles, such as building custom data bundles, you can look at the zipline docs.

Running the algorithm

To now test this algorithm on financial data, zipline provides two interfaces. A command-line interface and an IPython Notebook interface.

Command line interface

After you installed zipline you should be able to execute the following from your command line (e.g. cmd.exe on Windows, or the Terminal app on OSX):


In [3]:
!zipline run --help


Usage: zipline run [OPTIONS]

  Run a backtest for the given algorithm.

Options:
  -f, --algofile FILENAME         The file that contains the algorithm to run.
  -t, --algotext TEXT             The algorithm script to run.
  -D, --define TEXT               Define a name to be bound in the namespace
                                  before executing the algotext. For example
                                  '-Dname=value'. The value may be any python
                                  expression. These are evaluated in order so
                                  they may refer to previously defined names.
  --data-frequency [daily|minute]
                                  The data frequency of the simulation.
                                  [default: daily]
  --capital-base FLOAT            The starting capital for the simulation.
                                  [default: 10000000.0]
  -b, --bundle BUNDLE-NAME        The data bundle to use for the simulation.
                                  [default: quantopian-quandl]
  --bundle-timestamp TIMESTAMP    The date to lookup data on or before.
                                  [default: <current-time>]
  -s, --start DATE                The start date of the simulation.
  -e, --end DATE                  The end date of the simulation.
  -o, --output FILENAME           The location to write the perf data. If this
                                  is '-' the perf will be written to stdout.
                                  [default: -]
  --print-algo / --no-print-algo  Print the algorithm to stdout.
  --help                          Show this message and exit.

Note that you have to omit the preceding '!' when you call run_algo.py, this is only required by the IPython Notebook in which this tutorial was written.

As you can see there are a couple of flags that specify where to find your algorithm (-f) as well as the time-range (--start and --end). Finally, you'll want to save the performance metrics of your algorithm so that you can analyze how it performed. This is done via the --output flag and will cause it to write the performance DataFrame in the pickle Python file format.

Thus, to execute our algorithm from above and save the results to buyapple_out.pickle we would call run_algo.py as follows:


In [4]:
!zipline run -f ../../zipline/examples/buyapple.py --start 2003-1-1 --end 2014-1-1 -o buyapple_out.pickle


[2017-06-15 20:02:48.124773] WARNING: Loader: Refusing to download new benchmark data because a download succeeded at 2017-06-15 19:24:35+00:00.
[2017-06-15 20:02:52.210861] INFO: Performance: after split: asset: Equity(0 [AAPL]), amount: 10820.0, cost_basis: 15.3, last_sale_price: 88.99
[2017-06-15 20:02:52.211007] INFO: Performance: returning cash: 0.0
[2017-06-15 20:03:03.540372] INFO: Performance: Simulated 2769 trading days out of 2769.
[2017-06-15 20:03:03.540581] INFO: Performance: first open: 2003-01-02 14:31:00+00:00
[2017-06-15 20:03:03.540732] INFO: Performance: last close: 2013-12-31 21:00:00+00:00
<matplotlib.figure.Figure at 0x10f8948d0>

run_algo.py first outputs the algorithm contents. It then uses historical price and volume data of Apple from the quantopian-quandl bundle in the desired time range, 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. After the call of the order() function, zipline enters the ordered stock and amount in the order book. After the handle_data() function has finished, zipline looks for any open orders and tries to fill them. If the trading volume is high enough for this stock, the order is executed after adding the commission and applying the slippage model which models the influence of your order on the stock price, so your algorithm will be charged more than just the stock price * 10. (Note, that you can also change the commission and slippage model that zipline uses, see the Quantopian docs for more information).

Note that there is also an analyze() function printed. run_algo.py will try and look for a file with the ending with _analyze.py and the same name of the algorithm (so buyapple_analyze.py) or an analyze() function directly in the script. If an analyze() function is found it will be called after the simulation has finished and passed in the performance DataFrame. (The reason for allowing specification of an analyze() function in a separate file is that this way buyapple.py remains a valid Quantopian algorithm that you can copy&paste to the platform).

Lets take a quick look at the performance DataFrame. For this, we use pandas from inside the IPython Notebook and print the first ten rows. Note that zipline makes heavy usage of pandas, especially for data input and outputting so it's worth spending some time to learn it.


In [5]:
import pandas as pd
perf = pd.read_pickle('buyapple_out.pickle') # read in perf DataFrame
perf.head()


Out[5]:
AAPL algo_volatility algorithm_period_return alpha benchmark_period_return benchmark_volatility beta capital_used ending_cash ending_exposure ... short_exposure short_value shorts_count sortino starting_cash starting_exposure starting_value trading_days transactions treasury_period_return
2003-01-02 21:00:00+00:00 14.80 NaN 0.000000e+00 NaN 0.032189 NaN NaN 0.0 10000000.0 0.0 ... 0 0 0 NaN 10000000.0 0.0 0.0 1 [] 0.0407
2003-01-03 21:00:00+00:00 14.90 1.122497e-06 -1.000000e-07 -0.000028 0.035362 0.326804 0.000003 -150.0 9999850.0 149.0 ... 0 0 0 -11.224972 10000000.0 0.0 0.0 2 [{'order_id': 'b60cc6d4547f4188bedab1f249840b4... 0.0405
2003-01-06 21:00:00+00:00 14.90 9.165152e-07 -2.000000e-07 -0.000032 0.053610 0.231086 0.000003 -150.0 9999700.0 298.0 ... 0 0 0 -12.961481 9999850.0 149.0 149.0 3 [{'order_id': 'f892e80e346b4b94b2276b6e0fbf691... 0.0409
2003-01-07 21:00:00+00:00 14.85 1.296148e-06 -4.000000e-07 -0.000040 0.051003 0.247106 0.000005 -149.5 9999550.5 445.5 ... 0 0 0 -12.961481 9999700.0 298.0 298.0 4 [{'order_id': 'b525d7b4410c42ea86e4cc564e8afb3... 0.0404
2003-01-08 21:00:00+00:00 14.55 6.487221e-06 -1.400000e-06 -0.000102 0.035815 0.287550 0.000017 -146.5 9999404.0 582.0 ... 0 0 0 -9.653623 9999550.5 445.5 445.5 5 [{'order_id': '08ce3a9c085346cd91b92e6c4f86926... 0.0400

5 rows × 39 columns

As you can see, there is a row for each trading day, starting on the first business day of 2000. In the columns you can find various information about the state of your algorithm. The very first column AAPL was placed there by the record() function mentioned earlier and allows us to plot the price of apple. For example, we could easily examine now how our portfolio value changed over time compared to the AAPL stock price.


In [6]:
%pylab inline
figsize(12, 12)
import matplotlib.pyplot as plt

ax1 = plt.subplot(211)
perf.portfolio_value.plot(ax=ax1)
ax1.set_ylabel('portfolio value')
ax2 = plt.subplot(212, sharex=ax1)
perf.AAPL.plot(ax=ax2)
ax2.set_ylabel('AAPL stock price')


Populating the interactive namespace from numpy and matplotlib
Out[6]:
<matplotlib.text.Text at 0x113efc160>

As you can see, our algorithm performance as assessed by the portfolio_value closely matches that of the AAPL stock price. This is not surprising as our algorithm only bought AAPL every chance it got.

IPython Notebook

The IPython Notebook is a very powerful browser-based interface to a Python interpreter (this tutorial was written in it). As it is already the de-facto interface for most quantitative researchers zipline provides an easy way to run your algorithm inside the Notebook without requiring you to use the CLI.

To use it you have to write your algorithm in a cell and let zipline know that it is supposed to run this algorithm. This is done via the %%zipline IPython magic command that is available after you run %load_ext zipline in a separate cell. This magic takes the same arguments as the command line interface described above.


In [7]:
%load_ext zipline

In [8]:
%%zipline --start 2003-1-1 --end 2014-1-1 -o perf_ipython.pickle

from zipline.api import symbol, order, record

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))


Out[8]:
AAPL algo_volatility algorithm_period_return alpha benchmark_period_return benchmark_volatility beta capital_used ending_cash ending_exposure ... short_exposure short_value shorts_count sortino starting_cash starting_exposure starting_value trading_days transactions treasury_period_return
2003-01-02 21:00:00+00:00 14.800 NaN 0.000000e+00 NaN 0.032189 NaN NaN 0.00 10000000.00 0.00 ... 0 0 0 NaN 10000000.00 0.00 0.00 1 [] 0.0407
2003-01-03 21:00:00+00:00 14.900 1.122497e-06 -1.000000e-07 -0.000028 0.035362 0.326804 0.000003 -150.00 9999850.00 149.00 ... 0 0 0 -11.224972 10000000.00 0.00 0.00 2 [{'order_id': 'ff44e20a559e4e3db144108f7ba46dd... 0.0405
2003-01-06 21:00:00+00:00 14.900 9.165152e-07 -2.000000e-07 -0.000032 0.053610 0.231086 0.000003 -150.00 9999700.00 298.00 ... 0 0 0 -12.961481 9999850.00 149.00 149.00 3 [{'order_id': '69bef39efa0d437bbe9b20f7ce89a32... 0.0409
2003-01-07 21:00:00+00:00 14.850 1.296148e-06 -4.000000e-07 -0.000040 0.051003 0.247106 0.000005 -149.50 9999550.50 445.50 ... 0 0 0 -12.961481 9999700.00 298.00 298.00 4 [{'order_id': 'a886f93cf25541eda5b12af134b319e... 0.0404
2003-01-08 21:00:00+00:00 14.550 6.487221e-06 -1.400000e-06 -0.000102 0.035815 0.287550 0.000017 -146.50 9999404.00 582.00 ... 0 0 0 -9.653623 9999550.50 445.50 445.50 5 [{'order_id': '86b76c0a11f84db494c94b30da347af... 0.0400
2003-01-09 21:00:00+00:00 14.680 7.365274e-06 -9.800000e-07 -0.000085 0.051910 0.262817 0.000020 -147.80 9999256.20 734.00 ... 0 0 0 -6.168756 9999404.00 582.00 582.00 6 [{'order_id': '342d63c9e3bc4f55abbb5d44848764d... 0.0419
2003-01-10 21:00:00+00:00 14.720 6.906697e-06 -8.800000e-07 -0.000069 0.054743 0.242507 0.000019 -148.20 9999108.00 883.20 ... 0 0 0 -5.128386 9999256.20 734.00 734.00 7 [{'order_id': '25eee63295da484e905221f460e174c... 0.0416
2003-01-13 21:00:00+00:00 14.630 7.015645e-06 -1.520000e-06 -0.000083 0.054403 0.229034 0.000021 -147.30 9998960.70 1024.10 ... 0 0 0 -7.037188 9999108.00 883.20 883.20 8 [{'order_id': '9278e8193e88447da812761fc6fe5e0... 0.0415
2003-01-14 21:00:00+00:00 14.610 6.567866e-06 -1.760000e-06 -0.000082 0.057803 0.215045 0.000021 -147.10 9998813.60 1168.80 ... 0 0 0 -7.536048 9998960.70 1024.10 1024.10 9 [{'order_id': 'd9abf24cc2db4a6dad0afab4e303bb5... 0.0410
2003-01-15 21:00:00+00:00 14.430 9.159358e-06 -3.300000e-06 -0.000118 0.047263 0.218652 0.000029 -145.30 9998668.30 1298.70 ... 0 0 0 -8.389742 9998813.60 1168.80 1168.80 10 [{'order_id': '09c5ec8d662a48b4ae309d2c069633c... 0.0410
2003-01-16 21:00:00+00:00 14.620 1.271714e-05 -1.690000e-06 -0.000058 0.042956 0.211689 0.000019 -147.20 9998521.10 1462.00 ... 0 0 0 -4.096605 9998668.30 1298.70 1298.70 11 [{'order_id': '7917f2a185db46068b1f34f73a7a783... 0.0410
2003-01-17 21:00:00+00:00 14.100 2.651814e-05 -6.990000e-06 -0.000181 0.027542 0.219259 0.000058 -142.00 9998379.10 1551.00 ... 0 0 0 -5.663535 9998521.10 1462.00 1462.00 12 [{'order_id': '1ded69c18934412ea4920e5a4ce39d8... 0.0405
2003-01-21 21:00:00+00:00 14.020 2.544943e-05 -7.970000e-06 -0.000168 0.011561 0.224239 0.000054 -141.20 9998237.90 1682.40 ... 0 0 0 -6.113142 9998379.10 1551.00 1551.00 13 [{'order_id': '3edf4ce8f2434c5ca7885bcb6288251... 0.0401
2003-01-22 21:00:00+00:00 13.880 2.494722e-05 -9.750000e-06 -0.000176 -0.000680 0.222471 0.000056 -139.80 9998098.10 1804.40 ... 0 0 0 -6.883062 9998237.90 1682.40 1682.40 14 [{'order_id': '19d1240c46ce45fe975f417e8bb7557... 0.0395
2003-01-23 21:00:00+00:00 14.170 2.997029e-05 -6.080000e-06 -0.000110 0.005780 0.215989 0.000065 -142.70 9997955.40 1983.80 ... 0 0 0 -4.146648 9998098.10 1804.40 1804.40 15 [{'order_id': 'f68c56748e2f4a35b7b6ce0a5f04d1b... 0.0398
2003-01-24 21:00:00+00:00 13.800 3.482240e-05 -1.136000e-05 -0.000151 -0.020968 0.234687 0.000089 -139.00 9997816.40 2070.00 ... 0 0 0 -5.635616 9997955.40 1983.80 1983.80 16 [{'order_id': '9af53395def0433399c027631b986b9... 0.0394
2003-01-27 21:00:00+00:00 14.130 3.993833e-05 -6.510000e-06 -0.000064 -0.034342 0.232227 0.000067 -142.30 9997674.10 2260.80 ... 0 0 0 -3.133117 9997816.40 2070.00 2070.00 17 [{'order_id': '2f6050222a434f5ea729d0341ec7c69... 0.0398
2003-01-28 21:00:00+00:00 14.580 4.780349e-05 5.900000e-07 0.000039 -0.027202 0.227992 0.000084 -146.80 9997527.30 2478.60 ... 0 0 0 0.275991 9997674.10 2260.80 2260.80 18 [{'order_id': '227efa14266b4953b3b0bea90c9043b... 0.0400
2003-01-29 21:00:00+00:00 14.580 4.645916e-05 4.900000e-07 0.000026 -0.019835 0.223983 0.000082 -146.80 9997380.50 2624.40 ... 0 0 0 0.223088 9997527.30 2478.60 2478.60 19 [{'order_id': '5d89bb3dc54c41f6ab1185ea331ec63... 0.0406
2003-01-30 21:00:00+00:00 14.320 4.833069e-05 -4.290000e-06 -0.000003 -0.043069 0.232479 0.000097 -144.20 9997236.30 2720.80 ... 0 0 0 -1.633945 9997380.50 2624.40 2624.40 20 [{'order_id': '24416b47554143aebb664ef21435477... 0.0400
2003-01-31 21:00:00+00:00 14.360 4.720423e-05 -3.630000e-06 -0.000019 -0.024595 0.238414 0.000092 -144.60 9997091.70 2872.00 ... 0 0 0 -1.349243 9997236.30 2720.80 2720.80 21 [{'order_id': '8662df3c7ec340bfbb2c3326cdd71b9... 0.0400
2003-02-03 21:00:00+00:00 14.660 5.044377e-05 2.270000e-06 0.000049 -0.022668 0.232897 0.000096 -147.60 9996944.10 3078.60 ... 0 0 0 0.824399 9997091.70 2872.00 2872.00 22 [{'order_id': 'b66ac50e37c040b8a1b2bf3dd8d0408... 0.0401
2003-02-04 21:00:00+00:00 14.600 4.952140e-05 9.100000e-07 0.000042 -0.032302 0.229450 0.000097 -147.00 9996797.10 3212.00 ... 0 0 0 0.319857 9996944.10 3078.60 3078.60 23 [{'order_id': 'dfa64445fc634aa194d99599effb75f... 0.0396
2003-02-05 21:00:00+00:00 14.450 4.969875e-05 -2.490000e-06 0.000012 -0.038309 0.224963 0.000100 -145.50 9996651.60 3323.50 ... 0 0 0 -0.805752 9996797.10 3212.00 3212.00 24 [{'order_id': '17c396b1d53d4e1eaa64f2b35f79bcb... 0.0402
2003-02-06 21:00:00+00:00 14.430 4.867390e-05 -3.050000e-06 0.000011 -0.042843 0.220458 0.000100 -145.30 9996506.30 3463.20 ... 0 0 0 -0.965524 9996651.60 3323.50 3323.50 25 [{'order_id': '3596b10c0e5d471f94709afa05db7b4... 0.0397
2003-02-07 21:00:00+00:00 14.150 5.205011e-05 -9.870000e-06 -0.000037 -0.054517 0.218482 0.000112 -142.50 9996363.80 3537.50 ... 0 0 0 -2.533578 9996506.30 3463.20 3463.20 26 [{'order_id': '44f9d4436c074197a8b67682787843d... 0.0396
2003-02-10 21:00:00+00:00 14.350 5.352736e-05 -4.970000e-06 0.000006 -0.047830 0.216049 0.000120 -144.50 9996219.30 3731.00 ... 0 0 0 -1.251902 9996363.80 3537.50 3537.50 27 [{'order_id': '60ed7b77c24b4fc18129f5b68b598c2... 0.0399
2003-02-11 21:00:00+00:00 14.350 5.252737e-05 -5.070000e-06 0.000012 -0.054403 0.212579 0.000119 -144.50 9996074.80 3874.50 ... 0 0 0 -1.254037 9996219.30 3731.00 3731.00 28 [{'order_id': '01c6249b8d3c4e628c88bbe0ae54d40... 0.0398
2003-02-12 21:00:00+00:00 14.390 5.169428e-05 -4.090000e-06 0.000032 -0.069478 0.212807 0.000111 -144.90 9995929.90 4029.20 ... 0 0 0 -0.994036 9996074.80 3874.50 3874.50 29 [{'order_id': '1aab13fb02b84229969eacbd6413765... 0.0393
2003-02-13 21:00:00+00:00 14.540 5.226124e-05 1.000000e-08 0.000064 -0.066644 0.209699 0.000115 -146.40 9995783.50 4216.60 ... 0 0 0 0.002427 9995929.90 4029.20 4029.20 30 [{'order_id': '3f282f1112c844e09fbe4f13b7cdcbe... 0.0389
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2013-11-18 21:00:00+00:00 518.629 1.184981e-01 1.147260e+00 0.072016 1.033549 0.585165 0.026923 -5187.29 4456380.72 17016217.49 ... 0 0 0 0.935983 4461568.01 17219704.80 17219704.80 2740 [{'order_id': 'fb89c09004384919b52df5735fff993... 0.0267
2013-11-19 21:00:00+00:00 519.549 1.184769e-01 1.150278e+00 0.072125 1.029128 0.585059 0.026922 -5196.49 4451184.23 17051598.18 ... 0 0 0 0.937377 4456380.72 17016217.49 17016217.49 2741 [{'order_id': '23dfbe95a41045c1a4582f19668bc47... 0.0271
2013-11-20 21:00:00+00:00 515.000 1.184757e-01 1.135348e+00 0.071466 1.022781 0.584953 0.026930 -5151.00 4446033.23 16907450.00 ... 0 0 0 0.929177 4451184.23 17051598.18 17051598.18 2742 [{'order_id': '6c28fc29412f48d7bbf9a08466ea398... 0.0280
2013-11-21 21:00:00+00:00 521.135 1.184864e-01 1.155489e+00 0.072283 1.039102 0.584851 0.026947 -5212.35 4440820.88 17114073.40 ... 0 0 0 0.939499 4446033.23 16907450.00 16907450.00 2743 [{'order_id': '854085d9e4b2434d85dcd4859183653... 0.0279
2013-11-22 21:00:00+00:00 519.799 1.184669e-01 1.151102e+00 0.072058 1.049303 0.584745 0.026945 -5198.99 4435621.89 17075397.15 ... 0 0 0 0.937038 4440820.88 17114073.40 17114073.40 2744 [{'order_id': '60ecb48f2141403296ba00d6726e6dd... 0.0275
2013-11-25 21:00:00+00:00 523.740 1.184580e-01 1.164048e+00 0.072588 1.047263 0.584639 0.026942 -5238.40 4430383.49 17210096.40 ... 0 0 0 0.943559 4435621.89 17075397.15 17075397.15 2745 [{'order_id': '2648c384187c44dd87f32a1c89c56d7... 0.0274
2013-11-26 21:00:00+00:00 533.400 1.185163e-01 1.195791e+00 0.073907 1.047830 0.584533 0.026940 -5335.00 4425048.49 17532858.00 ... 0 0 0 0.959692 4430383.49 17210096.40 17210096.40 2746 [{'order_id': 'd0a5d2f34863480d967fd8144ad3cb1... 0.0271
2013-11-27 21:00:00+00:00 545.960 1.186269e-01 1.237075e+00 0.075597 1.052817 0.584426 0.026948 -5460.60 4419587.89 17951164.80 ... 0 0 0 0.980414 4425048.49 17532858.00 17532858.00 2747 [{'order_id': '9fe22091626d4457b6411184d58cfae... 0.0274
2013-11-29 18:00:00+00:00 556.070 1.186870e-01 1.270317e+00 0.076935 1.051456 0.584320 0.026942 -5561.70 4414026.19 18289142.30 ... 0 0 0 0.996747 4419587.89 17951164.80 17951164.80 2748 [{'order_id': 'f1760fbd434f419da34b4ccf83f478c... 0.0275
2013-12-02 21:00:00+00:00 551.230 1.186862e-01 1.254398e+00 0.076270 1.046129 0.584215 0.026949 -5513.30 4408512.89 18135467.00 ... 0 0 0 0.988449 4414026.19 18289142.30 18289142.30 2749 [{'order_id': '5cb6ae4fdf2d429481328a917d24fd1... 0.0281
2013-12-03 21:00:00+00:00 566.322 1.188463e-01 1.304051e+00 0.078277 1.037289 0.584110 0.026919 -5664.22 4402848.67 18637657.02 ... 0 0 0 1.012726 4408512.89 18135467.00 18135467.00 2750 [{'order_id': 'd701460b18ad4306bf0d7bcb125235d... 0.0279
2013-12-04 21:00:00+00:00 565.000 1.188266e-01 1.299700e+00 0.078075 1.037062 0.584004 0.026920 -5651.00 4397197.67 18599800.00 ... 0 0 0 1.010421 4402848.67 18637657.02 18637657.02 2751 [{'order_id': '047820fb9482466c81a20f44edb684f... 0.0284
2013-12-05 21:00:00+00:00 567.901 1.188106e-01 1.309250e+00 0.078439 1.028108 0.583900 0.026914 -5680.01 4391517.66 18700979.93 ... 0 0 0 1.014847 4397197.67 18599800.00 18599800.00 2752 [{'order_id': '3a21d5837b274deaa6b722b7d859f8a... 0.0288
2013-12-06 21:00:00+00:00 560.020 1.188406e-01 1.283298e+00 0.077361 1.050776 0.583803 0.026881 -5601.20 4385916.46 18447058.80 ... 0 0 0 1.001340 4391517.66 18700979.93 18700979.93 2753 [{'order_id': '4e754b61dead4bbe8e10d939a4d4152... 0.0288
2013-12-09 21:00:00+00:00 566.430 1.188496e-01 1.304412e+00 0.078172 1.055990 0.583697 0.026885 -5665.30 4380251.16 18663868.50 ... 0 0 0 1.011410 4385916.46 18447058.80 18447058.80 2754 [{'order_id': 'defcec5cb8f84144bb5cd27d1166b32... 0.0286
2013-12-10 21:00:00+00:00 565.550 1.188290e-01 1.301512e+00 0.078037 1.048623 0.583592 0.026887 -5656.50 4374594.66 18640528.00 ... 0 0 0 1.009821 4380251.16 18663868.50 18663868.50 2755 [{'order_id': '44f05e0a2f3444fda4ba580f7166a19... 0.0281
2013-12-11 21:00:00+00:00 561.360 1.188229e-01 1.287702e+00 0.077484 1.025615 0.583498 0.026906 -5614.60 4368980.06 18508039.20 ... 0 0 0 1.002745 4374594.66 18640528.00 18640528.00 2756 [{'order_id': '7ec236513d3b4aa2879ae007f2b581f... 0.0286
2013-12-12 21:00:00+00:00 560.540 1.188022e-01 1.284998e+00 0.077355 1.018928 0.583393 0.026908 -5606.40 4363373.66 18486609.20 ... 0 0 0 1.001245 4368980.06 18508039.20 18508039.20 2757 [{'order_id': '909b4bde34d240e69a61725fd84fef9... 0.0289
2013-12-13 21:00:00+00:00 554.430 1.188128e-01 1.264847e+00 0.076521 1.018701 0.583287 0.026910 -5545.30 4357828.36 18290645.70 ... 0 0 0 0.990779 4363373.66 18486609.20 18486609.20 2758 [{'order_id': '368ea1677170481f82dd9e73e5f95ab... 0.0288
2013-12-16 21:00:00+00:00 557.500 1.187979e-01 1.274975e+00 0.076886 1.031282 0.583184 0.026916 -5576.00 4352252.36 18397500.00 ... 0 0 0 0.995549 4357828.36 18290645.70 18290645.70 2759 [{'order_id': '5752e4c8061b4b058f0b0beda6dda4f... 0.0289
2013-12-17 21:00:00+00:00 554.990 1.187824e-01 1.266692e+00 0.076532 1.024821 0.583080 0.026920 -5550.90 4346701.46 18320219.90 ... 0 0 0 0.991251 4352252.36 18397500.00 18397500.00 2760 [{'order_id': 'e10a480555e94f8b8bc5b7eceedc971... 0.0285
2013-12-18 21:00:00+00:00 550.770 1.187770e-01 1.252762e+00 0.075908 1.059390 0.582995 0.026890 -5508.70 4341192.76 18186425.40 ... 0 0 0 0.984024 4346701.46 18320219.90 18320219.90 2761 [{'order_id': '17d031025779448984f519d3d1a1c19... 0.0289
2013-12-19 21:00:00+00:00 544.460 1.187907e-01 1.231926e+00 0.075038 1.057010 0.582889 0.026895 -5445.60 4335747.16 17983513.80 ... 0 0 0 0.973060 4341192.76 18186425.40 18186425.40 2762 [{'order_id': '417e912da2a34d9aa7b7ff9ed7836f2... 0.0294
2013-12-20 21:00:00+00:00 549.020 1.187850e-01 1.246988e+00 0.075626 1.057803 0.582784 0.026894 -5491.20 4330255.96 18139620.80 ... 0 0 0 0.980341 4335747.16 17983513.80 17983513.80 2763 [{'order_id': 'e3d4971889124c7f9361a827236de2f... 0.0289
2013-12-23 21:00:00+00:00 570.090 1.191238e-01 1.316603e+00 0.078403 1.068797 0.582680 0.026931 -5701.90 4324554.06 18841474.50 ... 0 0 0 1.014391 4330255.96 18139620.80 18139620.80 2764 [{'order_id': '15599a46990b42d58b6515571b7ce52... 0.0294
2013-12-24 18:00:00+00:00 567.670 1.191077e-01 1.308605e+00 0.078055 1.073331 0.582575 0.026930 -5677.70 4318876.36 18767170.20 ... 0 0 0 1.010313 4324554.06 18841474.50 18841474.50 2765 [{'order_id': '23b59f81e6e24ce59c2d3a566035cd0... 0.0299
2013-12-26 21:00:00+00:00 563.900 1.190988e-01 1.296141e+00 0.077523 1.083872 0.582471 0.026923 -5640.00 4313236.36 18648173.00 ... 0 0 0 1.003973 4318876.36 18767170.20 18767170.20 2766 [{'order_id': '41c735d6567b4bef8c87b82ccc9dafc... 0.0300
2013-12-27 21:00:00+00:00 560.090 1.190902e-01 1.283541e+00 0.076996 1.083645 0.582366 0.026925 -5601.90 4307634.46 18527777.20 ... 0 0 0 0.997533 4313236.36 18648173.00 18648173.00 2767 [{'order_id': '6e6fdd1b8b664cb0a6cdf8b6c3dcdbd... 0.0302
2013-12-30 21:00:00+00:00 554.520 1.190956e-01 1.265116e+00 0.076233 1.083418 0.582260 0.026927 -5546.20 4302088.26 18349066.80 ... 0 0 0 0.988019 4307634.46 18527777.20 18527777.20 2768 [{'order_id': 'e387e2f1de96492dab78ec64db876dd... 0.0299
2013-12-31 21:00:00+00:00 561.020 1.191062e-01 1.286624e+00 0.077056 1.093279 0.582156 0.026936 -5611.20 4296477.06 18569762.00 ... 0 0 0 0.998312 4302088.26 18349066.80 18349066.80 2769 [{'order_id': '1f01bd0d0fda4e27a5d0de609e02948... 0.0304

2769 rows × 39 columns

Note that we did not have to specify an input file as above since the magic will use the contents of the cell and look for your algorithm functions there.


In [9]:
pd.read_pickle('perf_ipython.pickle').head()


Out[9]:
AAPL algo_volatility algorithm_period_return alpha benchmark_period_return benchmark_volatility beta capital_used ending_cash ending_exposure ... short_exposure short_value shorts_count sortino starting_cash starting_exposure starting_value trading_days transactions treasury_period_return
2003-01-02 21:00:00+00:00 14.80 NaN 0.000000e+00 NaN 0.032189 NaN NaN 0.0 10000000.0 0.0 ... 0 0 0 NaN 10000000.0 0.0 0.0 1 [] 0.0407
2003-01-03 21:00:00+00:00 14.90 1.122497e-06 -1.000000e-07 -0.000028 0.035362 0.326804 0.000003 -150.0 9999850.0 149.0 ... 0 0 0 -11.224972 10000000.0 0.0 0.0 2 [{'order_id': 'ff44e20a559e4e3db144108f7ba46dd... 0.0405
2003-01-06 21:00:00+00:00 14.90 9.165152e-07 -2.000000e-07 -0.000032 0.053610 0.231086 0.000003 -150.0 9999700.0 298.0 ... 0 0 0 -12.961481 9999850.0 149.0 149.0 3 [{'order_id': '69bef39efa0d437bbe9b20f7ce89a32... 0.0409
2003-01-07 21:00:00+00:00 14.85 1.296148e-06 -4.000000e-07 -0.000040 0.051003 0.247106 0.000005 -149.5 9999550.5 445.5 ... 0 0 0 -12.961481 9999700.0 298.0 298.0 4 [{'order_id': 'a886f93cf25541eda5b12af134b319e... 0.0404
2003-01-08 21:00:00+00:00 14.55 6.487221e-06 -1.400000e-06 -0.000102 0.035815 0.287550 0.000017 -146.5 9999404.0 582.0 ... 0 0 0 -9.653623 9999550.5 445.5 445.5 5 [{'order_id': '86b76c0a11f84db494c94b30da347af... 0.0400

5 rows × 39 columns

Access to previous prices using data.history()

Working example: Dual Moving Average Cross-Over

The Dual Moving Average (DMA) is a classic momentum strategy. It's probably not used by any serious trader anymore but is still very instructive. The basic idea is that we compute two rolling or moving averages (mavg) -- one with a longer window that is supposed to capture long-term trends and one shorter window that is supposed to capture short-term trends. Once the short-mavg crosses the long-mavg from below we assume that the stock price has upwards momentum and long the stock. If the short-mavg crosses from above we exit the positions as we assume the stock to go down further.

As we need to have access to previous prices to implement this strategy we need a new concept: History

data.history() is a convenience function that keeps a rolling window of data for you. The first argument is the asset or iterable of assets you're using, the second argument is the field you're looking for i.e. price, open, volume, the third argument is the number of bars, and the fourth argument is your frequency (either '1d' for '1m' but note that you need to have minute-level data for using 1m).

For a more detailed description of data.history()'s features, see the Quantopian docs. Let's look at the strategy which should make this clear:


In [10]:
%%zipline --start 2003-1-1 --end 2014-1-1 -o perf_dma.pickle

from zipline.api import order_target, record, symbol
import numpy as np
import matplotlib.pyplot as plt

def initialize(context):
    context.i = 0
    context.asset = symbol('AAPL')


def handle_data(context, data):
    # Skip first 300 days to get full windows
    context.i += 1
    if context.i < 300:
        return

    # Compute averages
    # data.history() has to be called with the same params
    # from above and returns a pandas dataframe.
    short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean()
    long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()

    # Trading logic
    if short_mavg > long_mavg:
        # order_target orders as many shares as needed to
        # achieve the desired number of shares.
        order_target(context.asset, 100)
    elif short_mavg < long_mavg:
        order_target(context.asset, 0)

    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           short_mavg=short_mavg,
           long_mavg=long_mavg)


def analyze(context, perf):
    fig = plt.figure()
    ax1 = fig.add_subplot(211)
    perf.portfolio_value.plot(ax=ax1)
    ax1.set_ylabel('portfolio value in $')
    ax1.set_xlabel('time in years')

    ax2 = fig.add_subplot(212)

    perf['AAPL'].plot(ax=ax2)
    perf[['short_mavg', 'long_mavg']].plot(ax=ax2)

    perf_trans = perf.ix[[t != [] for t in perf.transactions]]
    buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]
    sells = perf_trans.ix[[t[0]['amount'] < 0 for t in perf_trans.transactions]]
    ax2.plot(buys.index, perf.short_mavg.ix[buys.index], '^', markersize=10, color='m')
    ax2.plot(sells.index, perf.short_mavg.ix[sells.index],'v', markersize=10, color='k')
    ax2.set_ylabel('price in $')
    ax2.set_xlabel('time in years')
    plt.legend(loc=0)
    plt.show()


Out[10]:
AAPL algo_volatility algorithm_period_return alpha benchmark_period_return benchmark_volatility beta capital_used ending_cash ending_exposure ... short_mavg short_value shorts_count sortino starting_cash starting_exposure starting_value trading_days transactions treasury_period_return
2003-01-02 21:00:00+00:00 NaN NaN 0.000000 NaN 0.032189 NaN NaN 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 1 [] 0.0407
2003-01-03 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.035362 0.326804 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 2 [] 0.0405
2003-01-06 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.053610 0.231086 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 3 [] 0.0409
2003-01-07 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.051003 0.247106 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 4 [] 0.0404
2003-01-08 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.035815 0.287550 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 5 [] 0.0400
2003-01-09 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.051910 0.262817 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 6 [] 0.0419
2003-01-10 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.054743 0.242507 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 7 [] 0.0416
2003-01-13 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.054403 0.229034 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 8 [] 0.0415
2003-01-14 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.057803 0.215045 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 9 [] 0.0410
2003-01-15 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.047263 0.218652 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 10 [] 0.0410
2003-01-16 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.042956 0.211689 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 11 [] 0.0410
2003-01-17 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.027542 0.219259 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 12 [] 0.0405
2003-01-21 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.011561 0.224239 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 13 [] 0.0401
2003-01-22 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.000680 0.222471 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 14 [] 0.0395
2003-01-23 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 0.005780 0.215989 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 15 [] 0.0398
2003-01-24 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.020968 0.234687 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 16 [] 0.0394
2003-01-27 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.034342 0.232227 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 17 [] 0.0398
2003-01-28 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.027202 0.227992 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 18 [] 0.0400
2003-01-29 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.019835 0.223983 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 19 [] 0.0406
2003-01-30 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.043069 0.232479 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 20 [] 0.0400
2003-01-31 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.024595 0.238414 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 21 [] 0.0400
2003-02-03 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.022668 0.232897 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 22 [] 0.0401
2003-02-04 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.032302 0.229450 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 23 [] 0.0396
2003-02-05 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.038309 0.224963 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 24 [] 0.0402
2003-02-06 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.042843 0.220458 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 25 [] 0.0397
2003-02-07 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.054517 0.218482 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 26 [] 0.0396
2003-02-10 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.047830 0.216049 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 27 [] 0.0399
2003-02-11 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.054403 0.212579 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 28 [] 0.0398
2003-02-12 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.069478 0.212807 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 29 [] 0.0393
2003-02-13 21:00:00+00:00 NaN 0.000000 0.000000 0.000000 -0.066644 0.209699 0.000000 0.0 1.000000e+07 0.0 ... NaN 0 0 NaN 1.000000e+07 0.0 0.0 30 [] 0.0389
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2013-11-18 21:00:00+00:00 518.629 0.000732 0.004041 0.000345 1.033549 0.585165 0.000133 0.0 1.004041e+07 0.0 ... 476.44448 0 0 0.717994 1.004041e+07 0.0 0.0 2740 [] 0.0267
2013-11-19 21:00:00+00:00 519.549 0.000732 0.004041 0.000345 1.029128 0.585059 0.000133 0.0 1.004041e+07 0.0 ... 477.72355 0 0 0.717863 1.004041e+07 0.0 0.0 2741 [] 0.0271
2013-11-20 21:00:00+00:00 515.000 0.000732 0.004041 0.000345 1.022781 0.584953 0.000133 0.0 1.004041e+07 0.0 ... 478.83179 0 0 0.717732 1.004041e+07 0.0 0.0 2742 [] 0.0280
2013-11-21 21:00:00+00:00 521.135 0.000732 0.004041 0.000345 1.039102 0.584851 0.000133 0.0 1.004041e+07 0.0 ... 479.90982 0 0 0.717601 1.004041e+07 0.0 0.0 2743 [] 0.0279
2013-11-22 21:00:00+00:00 519.799 0.000732 0.004041 0.000344 1.049303 0.584745 0.000133 0.0 1.004041e+07 0.0 ... 480.95168 0 0 0.717471 1.004041e+07 0.0 0.0 2744 [] 0.0275
2013-11-25 21:00:00+00:00 523.740 0.000731 0.004041 0.000344 1.047263 0.584639 0.000133 0.0 1.004041e+07 0.0 ... 482.06633 0 0 0.717340 1.004041e+07 0.0 0.0 2745 [] 0.0274
2013-11-26 21:00:00+00:00 533.400 0.000731 0.004041 0.000344 1.047830 0.584533 0.000133 0.0 1.004041e+07 0.0 ... 483.30099 0 0 0.717209 1.004041e+07 0.0 0.0 2746 [] 0.0271
2013-11-27 21:00:00+00:00 545.960 0.000731 0.004041 0.000344 1.052817 0.584426 0.000133 0.0 1.004041e+07 0.0 ... 484.58915 0 0 0.717079 1.004041e+07 0.0 0.0 2747 [] 0.0274
2013-11-29 18:00:00+00:00 556.070 0.000731 0.004041 0.000344 1.051456 0.584320 0.000133 0.0 1.004041e+07 0.0 ... 485.99441 0 0 0.716948 1.004041e+07 0.0 0.0 2748 [] 0.0275
2013-12-02 21:00:00+00:00 551.230 0.000731 0.004041 0.000344 1.046129 0.584215 0.000133 -55124.0 9.985291e+06 55123.0 ... 487.28650 0 0 0.716800 1.004041e+07 0.0 0.0 2749 [{'order_id': '95434c7c2a2040389ec85f731ba9cc1... 0.0281
2013-12-03 21:00:00+00:00 566.322 0.000732 0.004192 0.000358 1.037289 0.584110 0.000133 0.0 9.985291e+06 56632.2 ... 488.73719 0 0 0.743360 9.985291e+06 55123.0 55123.0 2750 [] 0.0279
2013-12-04 21:00:00+00:00 565.000 0.000732 0.004179 0.000356 1.037062 0.584004 0.000133 0.0 9.985291e+06 56500.0 ... 490.16548 0 0 0.740865 9.985291e+06 56632.2 56632.2 2751 [] 0.0284
2013-12-05 21:00:00+00:00 567.901 0.000732 0.004208 0.000359 1.028108 0.583900 0.000133 0.0 9.985291e+06 56790.1 ... 491.59557 0 0 0.745858 9.985291e+06 56500.0 56500.0 2752 [] 0.0288
2013-12-06 21:00:00+00:00 560.020 0.000732 0.004129 0.000351 1.050776 0.583803 0.000133 0.0 9.985291e+06 56002.0 ... 492.94571 0 0 0.731022 9.985291e+06 56790.1 56790.1 2753 [] 0.0288
2013-12-09 21:00:00+00:00 566.430 0.000732 0.004193 0.000357 1.055990 0.583697 0.000133 0.0 9.985291e+06 56643.0 ... 494.34565 0 0 0.742203 9.985291e+06 56002.0 56002.0 2754 [] 0.0286
2013-12-10 21:00:00+00:00 565.550 0.000732 0.004185 0.000356 1.048623 0.583592 0.000133 0.0 9.985291e+06 56555.0 ... 495.80403 0 0 0.740506 9.985291e+06 56643.0 56643.0 2755 [] 0.0281
2013-12-11 21:00:00+00:00 561.360 0.000732 0.004143 0.000352 1.025615 0.583498 0.000133 0.0 9.985291e+06 56136.0 ... 497.20708 0 0 0.732760 9.985291e+06 56555.0 56555.0 2756 [] 0.0286
2013-12-12 21:00:00+00:00 560.540 0.000732 0.004134 0.000351 1.018928 0.583393 0.000133 0.0 9.985291e+06 56054.0 ... 498.67422 0 0 0.731173 9.985291e+06 56136.0 56136.0 2757 [] 0.0289
2013-12-13 21:00:00+00:00 554.430 0.000732 0.004073 0.000346 1.018701 0.583287 0.000133 0.0 9.985291e+06 55443.0 ... 499.86772 0 0 0.719810 9.985291e+06 56054.0 56054.0 2758 [] 0.0288
2013-12-16 21:00:00+00:00 557.500 0.000732 0.004104 0.000348 1.031282 0.583184 0.000133 0.0 9.985291e+06 55750.0 ... 501.11177 0 0 0.725088 9.985291e+06 55443.0 55443.0 2759 [] 0.0289
2013-12-17 21:00:00+00:00 554.990 0.000732 0.004079 0.000346 1.024821 0.583080 0.000133 0.0 9.985291e+06 55499.0 ... 502.30613 0 0 0.720458 9.985291e+06 55750.0 55750.0 2760 [] 0.0285
2013-12-18 21:00:00+00:00 550.770 0.000732 0.004037 0.000342 1.059390 0.582995 0.000133 0.0 9.985291e+06 55077.0 ... 503.39112 0 0 0.712680 9.985291e+06 55499.0 55499.0 2761 [] 0.0289
2013-12-19 21:00:00+00:00 544.460 0.000732 0.003974 0.000336 1.057010 0.582889 0.000133 0.0 9.985291e+06 54446.0 ... 504.35840 0 0 0.700970 9.985291e+06 55077.0 55077.0 2762 [] 0.0294
2013-12-20 21:00:00+00:00 549.020 0.000732 0.004019 0.000340 1.057803 0.582784 0.000133 0.0 9.985291e+06 54902.0 ... 505.37908 0 0 0.708864 9.985291e+06 54446.0 54446.0 2763 [] 0.0289
2013-12-23 21:00:00+00:00 570.090 0.000735 0.004230 0.000359 1.068797 0.582680 0.000133 0.0 9.985291e+06 57009.0 ... 506.56951 0 0 0.745787 9.985291e+06 54902.0 54902.0 2764 [] 0.0294
2013-12-24 18:00:00+00:00 567.670 0.000735 0.004206 0.000357 1.073331 0.582575 0.000133 0.0 9.985291e+06 56767.0 ... 507.67782 0 0 0.741325 9.985291e+06 57009.0 57009.0 2765 [] 0.0299
2013-12-26 21:00:00+00:00 563.900 0.000735 0.004168 0.000353 1.083872 0.582471 0.000133 0.0 9.985291e+06 56390.0 ... 508.68018 0 0 0.734389 9.985291e+06 56767.0 56767.0 2766 [] 0.0300
2013-12-27 21:00:00+00:00 560.090 0.000735 0.004130 0.000349 1.083645 0.582366 0.000133 0.0 9.985291e+06 56009.0 ... 509.68593 0 0 0.727384 9.985291e+06 56390.0 56390.0 2767 [] 0.0302
2013-12-30 21:00:00+00:00 554.520 0.000735 0.004074 0.000344 1.083418 0.582260 0.000133 0.0 9.985291e+06 55452.0 ... 510.63864 0 0 0.717095 9.985291e+06 56009.0 56009.0 2768 [] 0.0299
2013-12-31 21:00:00+00:00 561.020 0.000735 0.004139 0.000350 1.093279 0.582156 0.000133 0.0 9.985291e+06 56102.0 ... 511.66550 0 0 0.728372 9.985291e+06 55452.0 55452.0 2769 [] 0.0304

2769 rows × 41 columns

Here we are explicitly defining an analyze() function that gets automatically called once the backtest is done (this is not possible on Quantopian currently).

Although it might not be directly apparent, the power of history (pun intended) can not be under-estimated as most algorithms make use of prior market developments in one form or another. You could easily devise a strategy that trains a classifier with scikit-learn which tries to predict future market movements based on past prices (note, that most of the scikit-learn functions require numpy.ndarrays rather than pandas.DataFrames, so you can simply pass the underlying ndarray of a DataFrame via .values).

We also used the order_target() function above. This and other functions like it can make order management and portfolio rebalancing much easier. See the Quantopian documentation on order functions fore more details.

Conclusions

We hope that this tutorial gave you a little insight into the architecture, API, and features of zipline. For next steps, check out some of the examples.

Feel free to ask questions on our mailing list, report problems on our GitHub issue tracker, get involved, and checkout Quantopian.