mirror of
https://github.com/wassname/catalyst.git
synced 2026-07-14 11:15:09 +08:00
203 KiB
203 KiB
In [1]:
!tail ../zipline/examples/buyapple.pyfrom zipline.api import order, record, symbol
def initialize(context):
pass
def handle_data(context, data):
order(symbol('AAPL'), 10)
record(AAPL=data[symbol('AAPL')].price)
In [2]:
!run_algo.py --helpusage: run_algo.py [-h] [-c FILE] [--algofile ALGOFILE] [--data-frequency {minute,daily}] [--start START] [--end END]
[--capital_base CAPITAL_BASE] [--source {yahoo}] [--symbols SYMBOLS] [--output OUTPUT]
Zipline version 0.6.1.
optional arguments:
-h, --help show this help message and exit
-c FILE, --conf_file FILE
Specify config file
--algofile ALGOFILE, -f ALGOFILE
--data-frequency {minute,daily}
--start START, -s START
--end END, -e END
--capital_base CAPITAL_BASE
--source {yahoo}
--symbols SYMBOLS
--output OUTPUT, -o OUTPUT
In [14]:
!run_algo.py -f ../zipline/examples/buyapple.py --start 2000-1-1 --end 2014-1-1 --symbols AAPL -o buyapple_out.pickleAAPL [37m#!/usr/bin/env python[39;49;00m [37m#[39;49;00m [37m# Copyright 2014 Quantopian, Inc.[39;49;00m [37m#[39;49;00m [37m# Licensed under the Apache License, Version 2.0 (the "License");[39;49;00m [37m# you may not use this file except in compliance with the License.[39;49;00m [37m# You may obtain a copy of the License at[39;49;00m [37m#[39;49;00m [37m# http://www.apache.org/licenses/LICENSE-2.0[39;49;00m [37m#[39;49;00m [37m# Unless required by applicable law or agreed to in writing, software[39;49;00m [37m# distributed under the License is distributed on an "AS IS" BASIS,[39;49;00m [37m# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.[39;49;00m [37m# See the License for the specific language governing permissions and[39;49;00m [37m# limitations under the License.[39;49;00m [34mfrom[39;49;00m [39;49;00m[04m[36mzipline.api[39;49;00m [39;49;00m[34mimport[39;49;00m [39;49;00morder[39;49;00m,[39;49;00m [39;49;00mrecord[39;49;00m,[39;49;00m [39;49;00msymbol[39;49;00m [34mdef[39;49;00m [39;49;00m[32minitialize[39;49;00m([39;49;00mcontext[39;49;00m)[39;49;00m:[39;49;00m [39;49;00m[34mpass[39;49;00m [34mdef[39;49;00m [39;49;00m[32mhandle_data[39;49;00m([39;49;00mcontext[39;49;00m,[39;49;00m [39;49;00mdata[39;49;00m)[39;49;00m:[39;49;00m [39;49;00morder[39;49;00m([39;49;00msymbol[39;49;00m([39;49;00m[33m'[39;49;00m[33mAAPL[39;49;00m[33m'[39;49;00m)[39;49;00m,[39;49;00m [39;49;00m[34m10[39;49;00m)[39;49;00m [39;49;00mrecord[39;49;00m([39;49;00mAAPL[39;49;00m=[39;49;00mdata[39;49;00m[[39;49;00msymbol[39;49;00m([39;49;00m[33m'[39;49;00m[33mAAPL[39;49;00m[33m'[39;49;00m)[39;49;00m][39;49;00m.[39;49;00mprice[39;49;00m)[39;49;00m [34mimport[39;49;00m [39;49;00m[04m[36mmatplotlib.pyplot[39;49;00m [39;49;00m[34mas[39;49;00m [39;49;00m[04m[36mplt[39;49;00m [34mdef[39;49;00m [39;49;00m[32manalyze[39;49;00m([39;49;00mcontext[39;49;00m,[39;49;00m [39;49;00mperf[39;49;00m)[39;49;00m:[39;49;00m [39;49;00max1[39;49;00m [39;49;00m=[39;49;00m [39;49;00mplt[39;49;00m.[39;49;00msubplot[39;49;00m([39;49;00m[34m211[39;49;00m)[39;49;00m [39;49;00mperf[39;49;00m.[39;49;00mportfolio_value[39;49;00m.[39;49;00mplot[39;49;00m([39;49;00max[39;49;00m=[39;49;00max1[39;49;00m)[39;49;00m [39;49;00max2[39;49;00m [39;49;00m=[39;49;00m [39;49;00mplt[39;49;00m.[39;49;00msubplot[39;49;00m([39;49;00m[34m212[39;49;00m,[39;49;00m [39;49;00msharex[39;49;00m=[39;49;00max1[39;49;00m)[39;49;00m [39;49;00mperf[39;49;00m.[39;49;00mAAPL[39;49;00m.[39;49;00mplot[39;49;00m([39;49;00max[39;49;00m=[39;49;00max2[39;49;00m)[39;49;00m [39;49;00mplt[39;49;00m.[39;49;00mgcf[39;49;00m([39;49;00m)[39;49;00m.[39;49;00mset_size_inches[39;49;00m([39;49;00m[34m18[39;49;00m,[39;49;00m [39;49;00m[34m8[39;49;00m)[39;49;00m [39;49;00mplt[39;49;00m.[39;49;00mshow[39;49;00m([39;49;00m)[39;49;00m [2014-07-25 17:50] INFO: Performance: Simulated 3521 trading days out of 3521. [2014-07-25 17:50] INFO: Performance: first open: 2000-01-03 14:31:00+00:00 [2014-07-25 17:50] INFO: Performance: last close: 2013-12-31 21:00:00+00:00
In [15]:
import pandas as pd
perf = pd.read_pickle('buyapple_out.pickle') # read in perf DataFrame
perf.head()Out [15]:
| AAPL | capital_used | ending_cash | ending_value | orders | period_close | period_open | pnl | portfolio_value | positions | returns | starting_cash | starting_value | transactions | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2000-01-03 21:00:00 | 3.82 | 0.0 | 10000000.0 | 0.0 | [{u'status': 0, u'limit_reached': False, u'cre... | 2000-01-03 21:00:00+00:00 | 2000-01-03 14:31:00+00:00 | 0.0 | 10000000.0 | [] | 0.000000e+00 | 10000000.0 | 0.0 | [] |
| 2000-01-04 21:00:00 | 3.50 | -35.3 | 9999964.7 | 35.0 | [{u'status': 1, u'limit_reached': False, u'cre... | 2000-01-04 21:00:00+00:00 | 2000-01-04 14:31:00+00:00 | -0.3 | 9999999.7 | [{u'amount': 10, u'last_sale_price': 3.5, u'co... | -3.000000e-08 | 10000000.0 | 0.0 | [{u'order_id': u'a52893c358834d60a09c7865d6779... |
| 2000-01-05 21:00:00 | 3.55 | -35.8 | 9999928.9 | 71.0 | [{u'status': 1, u'limit_reached': False, u'cre... | 2000-01-05 21:00:00+00:00 | 2000-01-05 14:31:00+00:00 | 0.2 | 9999999.9 | [{u'amount': 20, u'last_sale_price': 3.55, u'c... | 2.000000e-08 | 9999964.7 | 35.0 | [{u'order_id': u'0e6af58f1f6b4cc9b55f896b05532... |
| 2000-01-06 21:00:00 | 3.24 | -32.7 | 9999896.2 | 97.2 | [{u'status': 1, u'limit_reached': False, u'cre... | 2000-01-06 21:00:00+00:00 | 2000-01-06 14:31:00+00:00 | -6.5 | 9999993.4 | [{u'amount': 30, u'last_sale_price': 3.24, u'c... | -6.500000e-07 | 9999928.9 | 71.0 | [{u'order_id': u'f27eb86362e641b7a7ba2b8e76e33... |
| 2000-01-07 21:00:00 | 3.40 | -34.3 | 9999861.9 | 136.0 | [{u'status': 1, u'limit_reached': False, u'cre... | 2000-01-07 21:00:00+00:00 | 2000-01-07 14:31:00+00:00 | 4.5 | 9999997.9 | [{u'amount': 40, u'last_sale_price': 3.4, u'co... | 4.500003e-07 | 9999896.2 | 97.2 | [{u'order_id': u'9e5ef91c4c3c40cdbb49220e10dd5... |
In [16]:
%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')Out [16]:
Populating the interactive namespace from numpy and matplotlib
<matplotlib.text.Text at 0x7f6ab416b250>
In [6]:
import ziplineIn [7]:
%%zipline --start 2000-1-1 --end 2014-1-1 --symbols AAPL -o perf_ipython
from zipline.api import symbol, order, record
def initialize(context):
pass
def handle_data(context, data):
order(symbol('AAPL'), 10)
record(AAPL=data[symbol('AAPL')].price)[2014-07-25 17:11] INFO: Performance: Simulated 3019 trading days out of 3019. [2014-07-25 17:11] INFO: Performance: first open: 2000-01-03 14:31:00+00:00 [2014-07-25 17:11] INFO: Performance: last close: 2011-12-30 21:00:00+00:00
AAPL
In [8]:
perf_ipython.head()Out [8]:
| AAPL | capital_used | ending_cash | ending_value | orders | period_close | period_open | pnl | portfolio_value | positions | returns | starting_cash | starting_value | transactions | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2000-01-03 21:00:00 | 26.75 | 0.0 | 10000000.0 | 0.0 | [{u'status': 0, u'created': 2000-01-03 00:00:0... | 2000-01-03 21:00:00+00:00 | 2000-01-03 14:31:00+00:00 | 0.0 | 10000000.0 | [] | 0.000000e+00 | 10000000.0 | 0.0 | [] |
| 2000-01-04 21:00:00 | 24.49 | -245.2 | 9999754.8 | 244.9 | [{u'status': 1, u'created': 2000-01-03 00:00:0... | 2000-01-04 21:00:00+00:00 | 2000-01-04 14:31:00+00:00 | -0.3 | 9999999.7 | [{u'amount': 10, u'last_sale_price': 24.49, u'... | -3.000000e-08 | 10000000.0 | 0.0 | [{u'commission': 0.3, u'amount': 10, u'sid': u... |
| 2000-01-05 21:00:00 | 24.85 | -248.8 | 9999506.0 | 497.0 | [{u'status': 1, u'created': 2000-01-04 00:00:0... | 2000-01-05 21:00:00+00:00 | 2000-01-05 14:31:00+00:00 | 3.3 | 10000003.0 | [{u'amount': 20, u'last_sale_price': 24.85, u'... | 3.300000e-07 | 9999754.8 | 244.9 | [{u'commission': 0.3, u'amount': 10, u'sid': u... |
| 2000-01-06 21:00:00 | 22.70 | -227.3 | 9999278.7 | 681.0 | [{u'status': 1, u'created': 2000-01-05 00:00:0... | 2000-01-06 21:00:00+00:00 | 2000-01-06 14:31:00+00:00 | -43.3 | 9999959.7 | [{u'amount': 30, u'last_sale_price': 22.7, u'c... | -4.329999e-06 | 9999506.0 | 497.0 | [{u'commission': 0.3, u'amount': 10, u'sid': u... |
| 2000-01-07 21:00:00 | 23.78 | -238.1 | 9999040.6 | 951.2 | [{u'status': 1, u'created': 2000-01-06 00:00:0... | 2000-01-07 21:00:00+00:00 | 2000-01-07 14:31:00+00:00 | 32.1 | 9999991.8 | [{u'amount': 40, u'last_sale_price': 23.78, u'... | 3.210013e-06 | 9999278.7 | 681.0 | [{u'commission': 0.3, u'amount': 10, u'sid': u... |
In [9]:
import pytz
from datetime import datetime
from zipline.algorithm import TradingAlgorithm
from zipline.utils.factory import load_bars_from_yahoo
# Load data manually from Yahoo! finance
start = datetime(2000, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime(2012, 1, 1, 0, 0, 0, 0, pytz.utc)
data = load_bars_from_yahoo(stocks=['AAPL'], start=start,
end=end)
# Define algorithm
def initialize(context):
pass
def handle_data(context, data):
order(symbol('AAPL'), 10)
record(AAPL=data[symbol('AAPL')].price)
# Create algorithm object passing in initialize and
# handle_data functions
algo_obj = TradingAlgorithm(initialize=initialize,
handle_data=handle_data)
# Run algorithm
perf_manual = algo_obj.run(data)[2014-07-25 17:12] INFO: Performance: Simulated 3019 trading days out of 3019. [2014-07-25 17:12] INFO: Performance: first open: 2000-01-03 14:31:00+00:00 [2014-07-25 17:12] INFO: Performance: last close: 2011-12-30 21:00:00+00:00
AAPL
In [19]:
%%zipline --start 2000-1-1 --end 2014-1-1 --symbols AAPL -o perf_dma
from zipline.api import order_target, record, symbol, history, add_history
import numpy as np
def initialize(context):
# Register 2 histories that track daily prices,
# one with a 100 window and one with a 300 day window
add_history(100, '1d', 'price')
add_history(300, '1d', 'price')
context.i = 0
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
# Trading logic
if short_mavg[0] > long_mavg[0]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(symbol('AAPL'), 100)
elif short_mavg[0] < long_mavg[0]:
order_target(symbol('AAPL'), 0)
# Save values for later inspection
record(AAPL=data[symbol('AAPL')].price,
short_mavg=short_mavg[0],
long_mavg=long_mavg[0])
def analyze(context, perf):
fig = plt.figure()
ax1 = fig.add_subplot(211)
perf.portfolio_value.plot(ax=ax1)
ax1.set_ylabel('portfolio value in $')
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 $')
plt.legend(loc=0)
plt.show()[2014-07-25 17:59] INFO: Performance: Simulated 3521 trading days out of 3521. [2014-07-25 17:59] INFO: Performance: first open: 2000-01-03 14:31:00+00:00 [2014-07-25 17:59] INFO: Performance: last close: 2013-12-31 21:00:00+00:00
AAPL