mirror of
https://github.com/wassname/catalyst.git
synced 2026-07-14 11:15:09 +08:00
170 KiB
170 KiB
In [1]:
!tail ../../zipline/examples/buyapple.py # Load price data from yahoo.
data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,
end=end)
# Create and run the algorithm.
algo = TradingAlgorithm(initialize=initialize, handle_data=handle_data,
identifiers=['AAPL'])
results = algo.run(data)
analyze(results=results)
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}] [--source_time_column SOURCE_TIME_COLUMN] [--symbols SYMBOLS]
[--output OUTPUT] [--metadata_path METADATA_PATH] [--metadata_index METADATA_INDEX] [--print-algo] [--no-print-algo]
Zipline version 0.8.0rc1.
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}, -d {yahoo}
--source_time_column SOURCE_TIME_COLUMN, -t SOURCE_TIME_COLUMN
--symbols SYMBOLS
--output OUTPUT, -o OUTPUT
--metadata_path METADATA_PATH, -m METADATA_PATH
--metadata_index METADATA_INDEX, -x METADATA_INDEX
--print-algo, -p
--no-print-algo, -q
In [3]:
!run_algo.py -f ../../zipline/examples/buyapple.py --start 2000-1-1 --end 2014-1-1 --symbols AAPL -o buyapple_out.pickleAAPL [2015-11-04 22:45:32.820166] INFO: Performance: Simulated 3521 trading days out of 3521. [2015-11-04 22:45:32.820314] INFO: Performance: first open: 2000-01-03 14:31:00+00:00 [2015-11-04 22:45:32.820401] INFO: Performance: last close: 2013-12-31 21:00:00+00:00
In [4]:
import pandas as pd
perf = pd.read_pickle('buyapple_out.pickle') # read in perf DataFrame
perf.head()Out [4]:
| 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 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2000-01-03 21:00:00 | 3.738314 | 0.000000e+00 | 0.000000e+00 | -0.065800 | -0.009549 | 0.000000 | 0.000000 | 0.00000 | 10000000.00000 | 0.00000 | ... | 0 | 0 | 0 | 0.000000 | 10000000.00000 | 0.00000 | 0.00000 | 1 | [] | 0.0658 |
| 2000-01-04 21:00:00 | 3.423135 | 3.367492e-07 | -3.000000e-08 | -0.064897 | -0.047528 | 0.323229 | 0.000001 | -34.53135 | 9999965.46865 | 34.23135 | ... | 0 | 0 | 0 | 0.000000 | 10000000.00000 | 0.00000 | 0.00000 | 2 | [{u'order_id': u'513357725cb64a539e3dd02b47da7... | 0.0649 |
| 2000-01-05 21:00:00 | 3.473229 | 4.001918e-07 | -9.906000e-09 | -0.066196 | -0.045697 | 0.329321 | 0.000001 | -35.03229 | 9999930.43636 | 69.46458 | ... | 0 | 0 | 0 | 0.000000 | 9999965.46865 | 34.23135 | 34.23135 | 3 | [{u'order_id': u'd7d4ad03cfec4d578c0d817dc3829... | 0.0662 |
| 2000-01-06 21:00:00 | 3.172661 | 4.993979e-06 | -6.410420e-07 | -0.065758 | -0.044785 | 0.298325 | -0.000006 | -32.02661 | 9999898.40975 | 95.17983 | ... | 0 | 0 | 0 | -12731.780516 | 9999930.43636 | 69.46458 | 69.46458 | 4 | [{u'order_id': u'1fbf5e9bfd7c4d9cb2e8383e1085e... | 0.0657 |
| 2000-01-07 21:00:00 | 3.322945 | 5.977002e-06 | -2.201900e-07 | -0.065206 | -0.018908 | 0.375301 | 0.000005 | -33.52945 | 9999864.88030 | 132.91780 | ... | 0 | 0 | 0 | -12629.274583 | 9999898.40975 | 95.17983 | 95.17983 | 5 | [{u'order_id': u'9ea6b142ff09466b9113331a37437... | 0.0652 |
5 rows × 39 columns
In [5]:
%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 [5]:
Populating the interactive namespace from numpy and matplotlib
<matplotlib.text.Text at 0x7ff5c6147f90>
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)AAPL
In [8]:
perf_ipython.head()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 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2000-01-03 21:00:00 | 3.738314 | 0.000000e+00 | 0.000000e+00 | -0.065800 | -0.009549 | 0.000000 | 0.000000 | 0.00000 | 10000000.00000 | 0.00000 | ... | 0 | 0 | 0 | 0.000000 | 10000000.00000 | 0.00000 | 0.00000 | 1 | [] | 0.0658 |
| 2000-01-04 21:00:00 | 3.423135 | 3.367492e-07 | -3.000000e-08 | -0.064897 | -0.047528 | 0.323229 | 0.000001 | -34.53135 | 9999965.46865 | 34.23135 | ... | 0 | 0 | 0 | 0.000000 | 10000000.00000 | 0.00000 | 0.00000 | 2 | [{u'commission': 0.3, u'amount': 10, u'sid': 0... | 0.0649 |
| 2000-01-05 21:00:00 | 3.473229 | 4.001918e-07 | -9.906000e-09 | -0.066196 | -0.045697 | 0.329321 | 0.000001 | -35.03229 | 9999930.43636 | 69.46458 | ... | 0 | 0 | 0 | 0.000000 | 9999965.46865 | 34.23135 | 34.23135 | 3 | [{u'commission': 0.3, u'amount': 10, u'sid': 0... | 0.0662 |
| 2000-01-06 21:00:00 | 3.172661 | 4.993979e-06 | -6.410420e-07 | -0.065758 | -0.044785 | 0.298325 | -0.000006 | -32.02661 | 9999898.40975 | 95.17983 | ... | 0 | 0 | 0 | -12731.780516 | 9999930.43636 | 69.46458 | 69.46458 | 4 | [{u'commission': 0.3, u'amount': 10, u'sid': 0... | 0.0657 |
| 2000-01-07 21:00:00 | 3.322945 | 5.977002e-06 | -2.201900e-07 | -0.065206 | -0.018908 | 0.375301 | 0.000005 | -33.52945 | 9999864.88030 | 132.91780 | ... | 0 | 0 | 0 | -12629.274583 | 9999898.40975 | 95.17983 | 95.17983 | 5 | [{u'commission': 0.3, u'amount': 10, u'sid': 0... | 0.0652 |
5 rows × 39 columns
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)AAPL
In [10]:
%%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()AAPL