import os.path
import pytz
from collections import OrderedDict
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.figsize(14,8)
from zipline.algorithm import TradingAlgorithm
from zipline.transforms import MovingAverage, batch_transform
import requests
import json
def dataframe_from_bitcoincharts(starttime, endtime, period='15-min', symbol='mtgoxUSD'):
""" Download this set of data from bitcoincharts and return the filled up DataFrame"""
params = {'m': symbol,
'r': '0',
'i': period,
'c': '1',
's': starttime.strftime("%Y-%m-%d"),
'e': endtime.strftime("%Y-%m-%d")
}
response = requests.get('http://bitcoincharts.com/charts/chart.json', params=params)
if response.status_code != 200:
return None
df = pd.DataFrame(json.loads(response.content), columns=['timestamp','open', 'high', 'low', 'close', 'volume', 'volume_quote', 'price'])
df.index = pd.to_datetime(df['timestamp']*1000000000, utc=True)
del df['timestamp']
return df
def panel_from_bitcoincharts(starttime, endtime=datetime.datetime.now(), period='15-min', symbol='mtgoxUSD'):
if period == '1-min':
period_delta = datetime.timedelta(minutes = 1)
elif period == '5-min':
period_delta = datetime.timedelta(minutes = 5)
elif period == '15-min':
period_delta = datetime.timedelta(minutes = 15)
elif period == '30-min':
period_delta = datetime.timedelta(minutes = 30)
elif period == 'Hourly':
period_delta = datetime.timedelta(hours = 1)
elif period == '2-hour':
period_delta = datetime.timedelta(hours = 2)
elif period == '6-hour':
period_delta = datetime.timedelta(hours = 6)
elif period == '12-hour':
period_delta = datetime.timedelta(hours = 12)
elif period == 'Daily':
period_delta = datetime.timedelta(days = 1)
elif period == 'Weekly':
period_delta = datetime.timedelta(days = 7)
API_DATA_LIMIT = 5000
max_period_days = (period_delta * API_DATA_LIMIT).days - 1
max_frame_delta = datetime.timedelta(days = max_period_days)
while starttime != endtime:
frame_starttime = starttime
frame_endtime = endtime
if frame_endtime > frame_starttime + max_frame_delta:
frame_endtime = frame_starttime + max_frame_delta
new_df = dataframe_from_bitcoincharts(frame_starttime, frame_endtime, period, symbol)
print new_df.index
try:
df = df.combine_first(new_df)
except NameError:
df = new_df
starttime = frame_endtime
# export to panel
data = OrderedDict()
data['BTC'] = df
panel = pd.Panel(data)
panel.minor_axis = ['open', 'high', 'low', 'close', 'volume', 'volume_quote', 'price']
panel.major_axis = panel.major_axis.tz_localize(pytz.utc)
return panel
from zipline.finance.slippage import Transaction
class DualMovingAverage(TradingAlgorithm):
"""Dual Moving Average Crossover algorithm.
This algorithm buys bitcoins once its short moving average crosses
its long moving average (indicating upwards momentum) and sells
its shares once the averages cross again (indicating downwards
momentum).
buys and sells use the data['BTC']['price'] which is a Weighted Average
"""
def initialize(self, short_window=10, long_window=20):
# Add 2 mavg transforms, one with a long window, one
# with a short window.
self.add_transform(MovingAverage, 'short_mavg', ['open'],
window_length=short_window)
self.add_transform(MovingAverage, 'long_mavg', ['open'],
window_length=long_window)
# To keep track of whether we invested in the stock or not
self.trade_volume_mode = 'percent' # 'fixed' or 'percent'
self.__trade_volume = 100
#self.__trade_volume_pc = 10.0
self.__trade_volume_pc = 20.0
self.invested = 0
self.TakeProfitEnabled = True
self.TP_pc = 30.0
self.StopLossEnabled = True
self.SL_pc = 2.0
self.BreakEvenEnabled = True
self.BE_pc = 6.0
self.BE_offset_pc = 2.0
self.BreakEvenReached = False
self.TrailingStopEnabled = True
self.TS_pc = 4.0
def trade_volume(self, price):
if self.trade_volume_mode == 'fixed':
return(self.__trade_volume)
elif self.trade_volume_mode == 'percent':
return((self.__trade_volume_pc * self.portfolio.cash / 100.0) / price)
else:
return(0)
def print_portfolio(self):
print "${c} + BTC:{b}".format(c=self.portfolio.cash, b=self.portfolio.positions['BTC'].amount)
def handle_data(self, data):
self.short_mavg = data['BTC'].short_mavg['open']
self.long_mavg = data['BTC'].long_mavg['open']
self.buy = False
self.sell = False
if self.short_mavg > self.long_mavg and self.invested == 0:
self.price_open = data['BTC'].price
price = self.price_open
print "{dt}: Buying {a} BTC shares.".format(dt=data['BTC'].datetime, a=self.trade_volume(price))
self.order('BTC', self.trade_volume(price))
self.print_portfolio()
# portfolio is not updated yet se we have to use the commission object
t = Transaction('BTC', self.trade_volume(price), datetime.datetime.now, data['BTC']['price'])
self.commission.calculate(t)
self.invested = t.amount
self.buy = True
self.direction = 1 # buy = 1 ; sell = -1
self.price_SL = price*(1-self.direction*self.SL_pc/100.0)
self.price_TP = price*(1+self.direction*self.TP_pc/100.0)
self.price_BE = price*(1+self.direction*self.BE_pc/100.0)
self.price_BE_offset = price*(1+self.direction*self.BE_offset_pc/100.0)
elif self.short_mavg < self.long_mavg and self.invested > 0:
print "{dt}: Selling {a} BTC shares.".format(dt=data['BTC'].datetime, a=self.invested)
self.order('BTC', -self.invested)
self.print_portfolio()
self.invested = 0
self.sell = True
if self.invested != 0:
price = data['BTC'].price # ask or bid (?)
if self.StopLossEnabled and self.direction*(self.price_SL - price) >= 0:
print "{dt}: hit StopLoss - Selling {size} BTC shares.".format(size=self.invested, dt=data['BTC'].datetime)
self.order('BTC', -self.invested)
self.invested = 0
self.sell = True
if self.TakeProfitEnabled and self.direction*(price - self.price_TP) >= 0:
print "{dt}: hit TakeProfit - Selling {size} BTC shares.".format(size=self.invested, dt=data['BTC'].datetime)
self.order('BTC', -self.invested)
self.invested = 0
self.sell = True
if self.BreakEvenEnabled and not self.BreakEvenReached:
if self.direction*(price - self.price_BE) >= 0:
new_SL = self.price_BE_offset
if self.direction*(new_SL - self.price_SL) > 0:
print "{dt}: hit BreakEvent - moving Stop Loss from {SL1} to {SL2}".format(size=size, dt=data['BTC'].datetime, SL1=self.price_SL, SL2=self.price_BE_offset)
self.price_SL = new_SL
self.BreakEvenReached = True
if self.TrailingStopEnabled:
if self.direction*(price - self.price_open) >= 0:
new_SL = price*(1-self.direction*self.TS_pc/100.0)
if self.direction*(new_SL - self.price_SL) > 0:
print("Trailing stop enabled - moving StopLoss from {SL1} to {SL2}".format(SL1=self.price_SL, SL2=new_SL))
self.price_SL = new_SL
self.record(short_mavg=self.short_mavg,
long_mavg=self.long_mavg,
buy=self.buy,
sell=self.sell)
# very simple cache - delete the file to reset
cache_filename = 'bitcoincharts-cache.h5'
starttime = datetime.datetime(2012, 1, 1)
if not os.path.isfile(cache_filename):
store = pd.HDFStore(cache_filename)
store['panelM15'] = panel_from_bitcoincharts(starttime, period = '15-min')
store['panelM30'] = panel_from_bitcoincharts(starttime, period = '30-min')
store['panelH1'] = panel_from_bitcoincharts(starttime, period = 'Hourly')
store['panelD1'] = panel_from_bitcoincharts(starttime, period = 'Daily')
store.close()
store = pd.HDFStore(cache_filename)
print store
#panel = store['panelM15']
#panel = store['panelM30']
#panel = store['panelH1']
panel = store['panelD1']
store.close()
<class 'pandas.io.pytables.HDFStore'> File path: bitcoincharts-cache.h5 /panelD1 wide (shape->[1,501,7]) /panelH1 wide (shape->[1,12001,7]) /panelM15 wide (shape->[1,48001,7]) /panelM30 wide (shape->[1,24001,7])
quick_plot_data = panel['BTC'].resample('1D')
top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4, ylabel='USD')
top.plot(quick_plot_data.index, quick_plot_data["close"])
plt.title('Close price')
bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4, ylabel='Volume')
bottom.bar(quick_plot_data.index, quick_plot_data['volume'])
plt.gcf().set_size_inches(15,8)
class MtGoxCommission(object):
"""
Calculates commission for a transaction
"""
def __init__(self, fee=0.6):
"""
fee is the MtGox fee
TODO: Modify fee during run with trade volume
"""
self.fee = float(fee)
def __repr__(self):
return "{class_name}(fee={fee})".format(
class_name=self.__class__.__name__,
fee=self.fee)
def calculate(self, transaction):
"""
returns a tuple of:
(per share commission, total transaction commission)
"""
cost = int(round(transaction.price * transaction.amount))
if transaction.amount > 0:
fee_quote = 0
fee_base = (transaction.amount * (self.fee/100))
# modify the transactio amount - this is a violent hack
transaction.amount -= fee_base
return 0, 0
else:
fee_quote = int(round(cost * (self.fee/100)))
fee_base = 0
return 0, abs(fee_quote)
dma = DualMovingAverage()
dma.set_data_frequency('daily')
dma.commission = MtGoxCommission(0.6)
results = dma.run(panel)
[2013-05-15 11:16] INFO: Transform: Running StatefulTransform [short_mavg] [2013-05-15 11:16] INFO: Transform: Running StatefulTransform [long_mavg]
2012-01-18 00:00:00+00:00: Buying 3346.45346228 BTC shares. $100000.0 + BTC:0 Trailing stop enabled - moving StopLoss from 5.8569468307 to 5.93376072382 2012-01-20 00:00:00+00:00: hit BreakEvent - moving Stop Loss from 5.93376072382 to 6.09600588502 Trailing stop enabled - moving StopLoss from 6.09600588502 to 6.17806826867 2012-01-25 00:00:00+00:00: hit StopLoss - Selling 3326.37474151 BTC shares. 2012-01-26 00:00:00+00:00: Buying 3508.53976198 BTC shares. $98024.2382485 + BTC:-0.076 2012-01-27 00:00:00+00:00: hit StopLoss - Selling 3487.48852341 BTC shares. 2012-01-28 00:00:00+00:00: Buying 3553.18775378 BTC shares. $98997.4330787 + BTC:-0.124 2012-01-31 00:00:00+00:00: Selling 3531.86862725 BTC shares. $79631.0904692 + BTC:3531.558 2012-03-08 00:00:00+00:00: Buying 4111.62300523 BTC shares. $100188.243228 + BTC:0.558 Trailing stop enabled - moving StopLoss from 4.77594751455 to 4.95116146841 Trailing stop enabled - moving StopLoss from 4.95116146841 to 5.15526151236 2012-03-19 00:00:00+00:00: hit StopLoss - Selling 4086.9532672 BTC shares. 2012-03-20 00:00:00+00:00: Buying 4160.43376527 BTC shares. $99729.635652 + BTC:0.892 2012-03-24 00:00:00+00:00: hit StopLoss - Selling 4135.47116268 BTC shares. 2012-03-25 00:00:00+00:00: Buying 4373.14277247 BTC shares. $98405.5105321 + BTC:0.932 Trailing stop enabled - moving StopLoss from 4.41043914361 to 4.46605150352 Trailing stop enabled - moving StopLoss from 4.46605150352 to 4.48314466527 Trailing stop enabled - moving StopLoss from 4.48314466527 to 4.59709996485 2012-03-29 00:00:00+00:00: Selling 4346.90391584 BTC shares. $78175.8497272 + BTC:4347.694 2012-04-14 00:00:00+00:00: Buying 3978.18244296 BTC shares. $99005.461808 + BTC:1.694 Trailing stop enabled - moving StopLoss from 4.87787344914 to 4.94263260739 Trailing stop enabled - moving StopLoss from 4.94263260739 to 5.02064209378 Trailing stop enabled - moving StopLoss from 5.02064209378 to 5.06012062528 2012-04-28 00:00:00+00:00: hit StopLoss - Selling 3954.31334831 BTC shares. 2012-04-29 00:00:00+00:00: Buying 4010.8879829 BTC shares. $98995.4643281 + BTC:1.826 Trailing stop enabled - moving StopLoss from 4.83760979889 to 4.88124379308 Trailing stop enabled - moving StopLoss from 4.88124379308 to 4.89003018816 Trailing stop enabled - moving StopLoss from 4.89003018816 to 4.91139826841 2012-05-09 00:00:00+00:00: Selling 3986.822655 BTC shares. $79276.6335978 + BTC:3987.766 2012-05-25 00:00:00+00:00: Buying 3860.65132632 BTC shares. $99042.2561008 + BTC:1.766 Trailing stop enabled - moving StopLoss from 5.02824019963 to 5.02845518088 Trailing stop enabled - moving StopLoss from 5.02845518088 to 5.0326503147 Trailing stop enabled - moving StopLoss from 5.0326503147 to 5.17303840753 Trailing stop enabled - moving StopLoss from 5.17303840753 to 5.224454444 Trailing stop enabled - moving StopLoss from 5.224454444 to 5.28116838468 Trailing stop enabled - moving StopLoss from 5.28116838468 to 5.39413993584 Trailing stop enabled - moving StopLoss from 5.39413993584 to 5.6222954898 Trailing stop enabled - moving StopLoss from 5.6222954898 to 5.65949134308 Trailing stop enabled - moving StopLoss from 5.65949134308 to 5.87688680499 Trailing stop enabled - moving StopLoss from 5.87688680499 to 6.20245665362 Trailing stop enabled - moving StopLoss from 6.20245665362 to 6.34220335569 2012-06-21 00:00:00+00:00: hit TakeProfit - Selling 3837.48741836 BTC shares. Trailing stop enabled - moving StopLoss from 6.34220335569 to 6.42575164031 2012-06-22 00:00:00+00:00: Buying 3175.10309872 BTC shares. $104539.001544 + BTC:1.606 2012-06-24 00:00:00+00:00: hit StopLoss - Selling 3156.05248013 BTC shares. 2012-06-25 00:00:00+00:00: Buying 3289.9602069 BTC shares. $103904.1596 + BTC:1.556 Trailing stop enabled - moving StopLoss from 6.19010991044 to 6.26696926178 Trailing stop enabled - moving StopLoss from 6.26696926178 to 6.32918463191 Trailing stop enabled - moving StopLoss from 6.32918463191 to 6.36512127616 Trailing stop enabled - moving StopLoss from 6.36512127616 to 6.39340529797 Trailing stop enabled - moving StopLoss from 6.39340529797 to 6.43690728133 Trailing stop enabled - moving StopLoss from 6.43690728133 to 6.50008067874 Trailing stop enabled - moving StopLoss from 6.50008067874 to 6.52065192654 Trailing stop enabled - moving StopLoss from 6.52065192654 to 6.6221128798 Trailing stop enabled - moving StopLoss from 6.6221128798 to 6.81876257036 Trailing stop enabled - moving StopLoss from 6.81876257036 to 6.8209551647 Trailing stop enabled - moving StopLoss from 6.8209551647 to 7.00997848326 Trailing stop enabled - moving StopLoss from 7.00997848326 to 7.32388931823 Trailing stop enabled - moving StopLoss from 7.32388931823 to 7.75751829297 2012-07-17 00:00:00+00:00: hit TakeProfit - Selling 3270.22044566 BTC shares. Trailing stop enabled - moving StopLoss from 7.75751829297 to 8.00506356604 2012-07-18 00:00:00+00:00: Buying 2494.43828248 BTC shares. $112449.497453 + BTC:0.822 2012-07-20 00:00:00+00:00: hit StopLoss - Selling 2479.47165279 BTC shares. 2012-07-21 00:00:00+00:00: Buying 2520.98826097 BTC shares. $111912.110358 + BTC:0.858 2012-07-22 00:00:00+00:00: hit StopLoss - Selling 2505.8623314 BTC shares. 2012-07-23 00:00:00+00:00: Buying 2635.92348686 BTC shares. $111505.665811 + BTC:0.738 Trailing stop enabled - moving StopLoss from 8.29125375145 to 8.41990542044 Trailing stop enabled - moving StopLoss from 8.41990542044 to 8.53784160752 Trailing stop enabled - moving StopLoss from 8.53784160752 to 8.5947259396 Trailing stop enabled - moving StopLoss from 8.5947259396 to 8.87507812772 Trailing stop enabled - moving StopLoss from 8.87507812772 to 9.04891700648 Trailing stop enabled - moving StopLoss from 9.04891700648 to 9.72852502767 Trailing stop enabled - moving StopLoss from 9.72852502767 to 10.3032261138 2012-08-04 00:00:00+00:00: hit TakeProfit - Selling 2620.10794594 BTC shares. Trailing stop enabled - moving StopLoss from 10.3032261138 to 10.5587130693 2012-08-05 00:00:00+00:00: Buying 2197.00606866 BTC shares. $116717.757428 + BTC:-0.0720000000001 Trailing stop enabled - moving StopLoss from 10.4126614771 to 10.4630451959 Trailing stop enabled - moving StopLoss from 10.4630451959 to 10.5941683638 Trailing stop enabled - moving StopLoss from 10.5941683638 to 10.8721380927 Trailing stop enabled - moving StopLoss from 10.8721380927 to 10.9530432765 Trailing stop enabled - moving StopLoss from 10.9530432765 to 11.0410270032 Trailing stop enabled - moving StopLoss from 11.0410270032 to 11.1719944962 Trailing stop enabled - moving StopLoss from 11.1719944962 to 11.318030594 Trailing stop enabled - moving StopLoss from 11.318030594 to 11.6099482492 Trailing stop enabled - moving StopLoss from 11.6099482492 to 12.1050631523 Trailing stop enabled - moving StopLoss from 12.1050631523 to 12.69723936 Trailing stop enabled - moving StopLoss from 12.69723936 to 12.7281702497 2012-08-18 00:00:00+00:00: hit StopLoss - Selling 2183.82403224 BTC shares. 2012-08-19 00:00:00+00:00: Buying 2481.64596531 BTC shares. $112747.729895 + BTC:0.746 Trailing stop enabled - moving StopLoss from 8.90479760947 to 9.1513018028 Trailing stop enabled - moving StopLoss from 9.1513018028 to 9.6254820222 Trailing stop enabled - moving StopLoss from 9.6254820222 to 9.85445012665 Trailing stop enabled - moving StopLoss from 9.85445012665 to 10.0310095907 Trailing stop enabled - moving StopLoss from 10.0310095907 to 10.127321309 Trailing stop enabled - moving StopLoss from 10.127321309 to 10.7320272228 2012-08-28 00:00:00+00:00: Selling 2466.75608952 BTC shares. $89238.8461842 + BTC:2466.86 2012-09-14 00:00:00+00:00: Buying 2003.67560659 BTC shares. $115971.363926 + BTC:0.86 Trailing stop enabled - moving StopLoss from 11.3443449902 to 11.4017231082 Trailing stop enabled - moving StopLoss from 11.4017231082 to 11.4230531943 Trailing stop enabled - moving StopLoss from 11.4230531943 to 11.5818610424 Trailing stop enabled - moving StopLoss from 11.5818610424 to 11.9096003221 Trailing stop enabled - moving StopLoss from 11.9096003221 to 11.9815994798 Trailing stop enabled - moving StopLoss from 11.9815994798 to 12.1248509246 Trailing stop enabled - moving StopLoss from 12.1248509246 to 12.3221020602 Trailing stop enabled - moving StopLoss from 12.3221020602 to 12.3667656479 2012-10-07 00:00:00+00:00: hit StopLoss - Selling 1991.65355295 BTC shares. 2012-10-08 00:00:00+00:00: Buying 2044.09575881 BTC shares. $115034.884666 + BTC:0.842 Trailing stop enabled - moving StopLoss from 11.0302256131 to 11.4885813955 Trailing stop enabled - moving StopLoss from 11.4885813955 to 11.5437804783 Trailing stop enabled - moving StopLoss from 11.5437804783 to 11.5443693261 Trailing stop enabled - moving StopLoss from 11.5443693261 to 11.5675211134 2012-10-15 00:00:00+00:00: Selling 2031.83118426 BTC shares. $90715.9023705 + BTC:2032.578 2012-11-19 00:00:00+00:00: Buying 1957.09876287 BTC shares. $114663.138166 + BTC:1.578 Trailing stop enabled - moving StopLoss from 11.4833116789 to 11.585325863 Trailing stop enabled - moving StopLoss from 11.585325863 to 11.8113258475 Trailing stop enabled - moving StopLoss from 11.8113258475 to 11.8738709718 Trailing stop enabled - moving StopLoss from 11.8738709718 to 11.9877435673 Trailing stop enabled - moving StopLoss from 11.9877435673 to 12.0565221042 Trailing stop enabled - moving StopLoss from 12.0565221042 to 12.0754947253 Trailing stop enabled - moving StopLoss from 12.0754947253 to 12.5049518577 Trailing stop enabled - moving StopLoss from 12.5049518577 to 12.7500708011 Trailing stop enabled - moving StopLoss from 12.7500708011 to 12.8474758694 Trailing stop enabled - moving StopLoss from 12.8474758694 to 12.9252314182 Trailing stop enabled - moving StopLoss from 12.9252314182 to 12.9617888092 Trailing stop enabled - moving StopLoss from 12.9617888092 to 13.0555032479 Trailing stop enabled - moving StopLoss from 13.0555032479 to 13.1509133862 2013-01-01 00:00:00+00:00: Selling 1945.3561703 BTC shares. $91905.0730151 + BTC:1946.836 2013-01-10 00:00:00+00:00: Buying 1676.72076911 BTC shares. $117764.625442 + BTC:1.836 Trailing stop enabled - moving StopLoss from 13.7660766252 to 13.9349401964 Trailing stop enabled - moving StopLoss from 13.9349401964 to 14.5589601266 Trailing stop enabled - moving StopLoss from 14.5589601266 to 15.0535950128 Trailing stop enabled - moving StopLoss from 15.0535950128 to 15.0918203276 Trailing stop enabled - moving StopLoss from 15.0918203276 to 15.7292015827 Trailing stop enabled - moving StopLoss from 15.7292015827 to 16.4667322263 Trailing stop enabled - moving StopLoss from 16.4667322263 to 16.5281409071 Trailing stop enabled - moving StopLoss from 16.5281409071 to 17.0403377609 2013-01-25 00:00:00+00:00: hit StopLoss - Selling 1666.66044449 BTC shares. 2013-01-26 00:00:00+00:00: Buying 1432.11209138 BTC shares. $122816.448608 + BTC:1.78 Trailing stop enabled - moving StopLoss from 16.8087568509 to 16.9475068975 Trailing stop enabled - moving StopLoss from 16.9475068975 to 17.6056305317 Trailing stop enabled - moving StopLoss from 17.6056305317 to 18.4024491436 Trailing stop enabled - moving StopLoss from 18.4024491436 to 18.7008118103 Trailing stop enabled - moving StopLoss from 18.7008118103 to 19.7582810224 Trailing stop enabled - moving StopLoss from 19.7582810224 to 19.8975285255 2013-02-02 00:00:00+00:00: hit StopLoss - Selling 1423.51941883 BTC shares. 2013-02-03 00:00:00+00:00: Buying 1248.72175108 BTC shares. $126506.473946 + BTC:2.188 Trailing stop enabled - moving StopLoss from 19.8565203752 to 20.2452095172 Trailing stop enabled - moving StopLoss from 20.2452095172 to 20.7415034515 Trailing stop enabled - moving StopLoss from 20.7415034515 to 21.5221560155 Trailing stop enabled - moving StopLoss from 21.5221560155 to 22.3059374507 Trailing stop enabled - moving StopLoss from 22.3059374507 to 22.4834566253 Trailing stop enabled - moving StopLoss from 22.4834566253 to 23.1641063567 Trailing stop enabled - moving StopLoss from 23.1641063567 to 24.0848680257 Trailing stop enabled - moving StopLoss from 24.0848680257 to 24.4587073924 2013-02-15 00:00:00+00:00: hit TakeProfit - Selling 1241.22942058 BTC shares. Trailing stop enabled - moving StopLoss from 24.4587073924 to 25.9150992493 2013-02-16 00:00:00+00:00: Buying 992.948193611 BTC shares. $134864.033121 + BTC:1.7 2013-02-17 00:00:00+00:00: hit StopLoss - Selling 986.990504449 BTC shares. 2013-02-18 00:00:00+00:00: Buying 1010.69201016 BTC shares. $135215.240862 + BTC:1.748 Trailing stop enabled - moving StopLoss from 26.2218232088 to 27.0581114465 Trailing stop enabled - moving StopLoss from 27.0581114465 to 28.2932995664 Trailing stop enabled - moving StopLoss from 28.2932995664 to 28.4944321824 Trailing stop enabled - moving StopLoss from 28.4944321824 to 29.2425059262 2013-02-23 00:00:00+00:00: hit StopLoss - Selling 1004.6278581 BTC shares. 2013-02-24 00:00:00+00:00: Buying 918.786403156 BTC shares. $136813.791122 + BTC:1.688 Trailing stop enabled - moving StopLoss from 29.1857856928 to 29.7712254187 Trailing stop enabled - moving StopLoss from 29.7712254187 to 29.9689675786 Trailing stop enabled - moving StopLoss from 29.9689675786 to 31.3866664769 Trailing stop enabled - moving StopLoss from 31.3866664769 to 32.8707195611 Trailing stop enabled - moving StopLoss from 32.8707195611 to 34.0520795792 2013-03-05 00:00:00+00:00: hit TakeProfit - Selling 913.273684737 BTC shares. Trailing stop enabled - moving StopLoss from 34.0520795792 to 37.77466098 2013-03-06 00:00:00+00:00: Buying 666.807913788 BTC shares. $150615.676764 + BTC:1.18 2013-03-07 00:00:00+00:00: hit StopLoss - Selling 662.807066305 BTC shares. 2013-03-08 00:00:00+00:00: Buying 704.767141588 BTC shares. $152087.776459 + BTC:1.184 Trailing stop enabled - moving StopLoss from 42.2965294875 to 43.6192778429 Trailing stop enabled - moving StopLoss from 43.6192778429 to 44.9629776066 Trailing stop enabled - moving StopLoss from 44.9629776066 to 45.7108876015 2013-03-12 00:00:00+00:00: hit StopLoss - Selling 700.538538738 BTC shares. 2013-03-13 00:00:00+00:00: Buying 658.336841453 BTC shares. $152780.679882 + BTC:0.96 Trailing stop enabled - moving StopLoss from 45.4858537019 to 45.5039466756 Trailing stop enabled - moving StopLoss from 45.5039466756 to 47.0242110053 Trailing stop enabled - moving StopLoss from 47.0242110053 to 53.1724604033 2013-03-20 00:00:00+00:00: hit TakeProfit - Selling 654.386820404 BTC shares. Trailing stop enabled - moving StopLoss from 53.1724604033 to 59.5417853999 2013-03-21 00:00:00+00:00: Buying 483.569693324 BTC shares. $167007.502696 + BTC:1.012 Trailing stop enabled - moving StopLoss from 67.6913193285 to 67.8202892582 2013-03-23 00:00:00+00:00: hit StopLoss - Selling 480.668275164 BTC shares. 2013-03-24 00:00:00+00:00: Buying 482.203510606 BTC shares. $166172.127563 + BTC:1.114 Trailing stop enabled - moving StopLoss from 67.5435501525 to 71.2819179253 Trailing stop enabled - moving StopLoss from 71.2819179253 to 74.1570610762 Trailing stop enabled - moving StopLoss from 74.1570610762 to 81.4734392772 Trailing stop enabled - moving StopLoss from 81.4734392772 to 83.9163559748 Trailing stop enabled - moving StopLoss from 83.9163559748 to 85.2262584152 2013-03-30 00:00:00+00:00: hit TakeProfit - Selling 479.310289542 BTC shares. Trailing stop enabled - moving StopLoss from 85.2262584152 to 88.0547425594 2013-03-31 00:00:00+00:00: Buying 377.561348761 BTC shares. $174997.804001 + BTC:1.222 Trailing stop enabled - moving StopLoss from 90.8450234557 to 96.0343640424 Trailing stop enabled - moving StopLoss from 96.0343640424 to 103.303330176 2013-04-03 00:00:00+00:00: hit TakeProfit - Selling 375.295980669 BTC shares. Trailing stop enabled - moving StopLoss from 103.303330176 to 122.777829718 2013-04-04 00:00:00+00:00: Buying 283.96139827 BTC shares. $186865.401339 + BTC:0.96 Trailing stop enabled - moving StopLoss from 128.980977293 to 133.648604237 Trailing stop enabled - moving StopLoss from 133.648604237 to 136.47168006 Trailing stop enabled - moving StopLoss from 136.47168006 to 148.084942053 2013-04-08 00:00:00+00:00: hit TakeProfit - Selling 282.257629881 BTC shares. Trailing stop enabled - moving StopLoss from 148.084942053 to 174.233282436 2013-04-09 00:00:00+00:00: Buying 194.007257232 BTC shares. $208241.127026 + BTC:0.262 2013-04-10 00:00:00+00:00: hit StopLoss - Selling 192.843213689 BTC shares. 2013-04-11 00:00:00+00:00: Buying 255.651106668 BTC shares. $203148.081202 + BTC:1.098 2013-04-12 00:00:00+00:00: hit StopLoss - Selling 254.117200028 BTC shares. 2013-04-13 00:00:00+00:00: Buying 380.10295341 BTC shares. $209451.872316 + BTC:0.568 2013-04-14 00:00:00+00:00: hit StopLoss - Selling 377.82233569 BTC shares. 2013-04-15 00:00:00+00:00: Buying 472.008507975 BTC shares. $205483.105307 + BTC:1.288 2013-04-16 00:00:00+00:00: hit StopLoss - Selling 469.176456927 BTC shares. 2013-04-17 00:00:00+00:00: Buying 503.870140566 BTC shares. $214822.486486 + BTC:1.456 Trailing stop enabled - moving StopLoss from 83.5636088772 to 93.4853509825 2013-04-19 00:00:00+00:00: hit TakeProfit - Selling 500.846919723 BTC shares. Trailing stop enabled - moving StopLoss from 93.4853509825 to 114.653158619 2013-04-20 00:00:00+00:00: Buying 367.905584686 BTC shares. $228145.638034 + BTC:1.438 2013-04-21 00:00:00+00:00: hit StopLoss - Selling 365.698151178 BTC shares. 2013-04-22 00:00:00+00:00: Buying 371.334321855 BTC shares. $228803.3053 + BTC:1.236 Trailing stop enabled - moving StopLoss from 120.768389022 to 129.244540667 2013-04-24 00:00:00+00:00: Selling 369.106315924 BTC shares. $179155.310601 + BTC:370.01 2013-05-02 00:00:00+00:00: Buying 435.630214677 BTC shares. $231948.368187 + BTC:1.01 2013-05-03 00:00:00+00:00: hit StopLoss - Selling 433.016433389 BTC shares. 2013-05-04 00:00:00+00:00: Buying 447.460952523 BTC shares. $238662.988562 + BTC:0.4 Trailing stop enabled - moving StopLoss from 104.540844278 to 108.956431861 Trailing stop enabled - moving StopLoss from 108.956431861 to 112.63127636 2013-05-07 00:00:00+00:00: hit StopLoss - Selling 444.776186808 BTC shares. 2013-05-08 00:00:00+00:00: Buying 420.973997272 BTC shares.
[2013-05-15 11:16] INFO: Transform: Finished StatefulTransform [long_mavg] [2013-05-15 11:16] INFO: Transform: Finished StatefulTransform [short_mavg] [2013-05-15 11:16] INFO: Performance: Simulated 341 trading days out of 341. [2013-05-15 11:16] INFO: Performance: first open: 2012-01-03 14:30:00+00:00 [2013-05-15 11:16] INFO: Performance: last close: 2013-05-13 20:00:00+00:00
$238554.735464 + BTC:0.718 Trailing stop enabled - moving StopLoss from 111.067972022 to 113.309201603 2013-05-11 00:00:00+00:00: Selling 418.448153289 BTC shares. $191937.266277 + BTC:418.198
fig = plt.figure()
ax1 = fig.add_subplot(211, ylabel='portfolio value')
results.portfolio_value.plot(ax=ax1)
ax2 = fig.add_subplot(212)
# results is daily so we have to resample our original data to plot it on the same graph
# but for some reason results are each at 21:00 or 20:00 so we need to offest the resampling
# Might be the time when trading closes in real life excahnges, but I don't know.
offset = datetime.timedelta(hours = 21)
panel['BTC']['open'].resample('1D', loffset=offset, label='open').plot(ax=ax2, color='r')
results[['short_mavg', 'long_mavg']].plot(ax=ax2)
print "Buys"
print results.short_mavg[results.buy]
print "Sells"
print results.short_mavg[results.sell]
ax2.plot(results.ix[results.buy].index, results.short_mavg[results.buy],'^', markersize=10, color='m')
ax2.plot(results.ix[results.sell].index, results.short_mavg[results.sell],'v', markersize=10, color='k')
plt.legend(loc=0)
plt.show()
Buys 2012-01-18 21:00:00 6.456849 2012-01-26 21:00:00 6.386623 2012-03-08 21:00:00 4.885381 2012-03-20 20:00:00 5.061555 2012-05-25 20:00:00 5.059314 2012-06-22 20:00:00 6.074410 2012-06-25 20:00:00 6.264772 2012-07-18 20:00:00 7.273519 2012-07-23 20:00:00 8.072749 2012-09-14 20:00:00 10.834910 2012-10-08 20:00:00 12.428786 2012-11-19 21:00:00 11.097279 2013-01-10 21:00:00 13.476470 2013-03-06 21:00:00 32.488660 2013-03-08 21:00:00 34.176331 2013-03-13 20:00:00 39.768086 2013-03-21 20:00:00 48.742039 2013-04-04 20:00:00 86.730257 2013-04-09 20:00:00 115.118383 2013-04-11 20:00:00 131.311717 2013-04-15 20:00:00 138.839693 2013-04-17 20:00:00 133.751242 2013-04-22 20:00:00 123.179800 2013-05-02 20:00:00 131.360135 2013-05-08 20:00:00 124.995822 Name: short_mavg, dtype: float64 Sells 2012-01-25 21:00:00 6.427290 2012-01-27 21:00:00 6.282623 2012-01-31 21:00:00 5.884649 2012-03-19 20:00:00 5.082296 2012-03-29 20:00:00 4.881934 2012-05-09 20:00:00 5.048841 2012-06-21 20:00:00 5.996619 2012-07-17 20:00:00 7.137517 2012-07-20 20:00:00 7.675179 2012-08-28 20:00:00 10.909949 2012-10-15 20:00:00 12.242572 2013-01-25 21:00:00 15.392498 2013-02-15 21:00:00 22.614217 2013-03-05 21:00:00 31.709202 2013-03-07 21:00:00 33.301166 2013-03-12 20:00:00 38.825947 2013-03-20 20:00:00 47.065703 2013-04-03 20:00:00 81.672924 2013-04-08 20:00:00 102.646515 2013-04-10 20:00:00 125.545050 2013-04-12 20:00:00 133.710383 2013-04-16 20:00:00 137.295836 2013-04-19 20:00:00 129.105527 2013-04-24 20:00:00 112.706585 2013-05-03 20:00:00 131.162992 2013-05-07 20:00:00 127.415456 Name: short_mavg, dtype: float64
from zipline.finance import trading
from zipline.utils.factory import create_returns_from_list
from zipline.finance.risk import RiskMetricsBase
start = results.first_valid_index().replace(tzinfo=pytz.utc)
end = results.last_valid_index().replace(tzinfo=pytz.utc)
env = trading.SimulationParameters(start, end)
returns_risk = create_returns_from_list(results.returns, env)
risk = RiskMetricsBase(start, end, returns_risk)
print risk
algorithm_period_returns:1.39861648149 benchmark_period_returns:0.281184359606 excess_return:1.39535511162 trading_days:340 benchmark_volatility:0.141957916593 algorithm_volatility:0.186233881391 sharpe:7.49248794687 sortino:215.215566173 information:0.148733081281 algorithm_covariance:1.72713947416e-06 benchmark_variance:5.92707355398e-05 beta:0.0291398353408 alpha:1.38725648146 max_drawdown:0.0747610613047 algorithm_returns:2012-01-04 00:00:00+00:00 0.000000 2012-01-05 00:00:00+00:00 0.000000 2012-01-06 00:00:00+00:00 0.000000 2012-01-09 00:00:00+00:00 0.000000 2012-01-10 00:00:00+00:00 0.000000 2012-01-11 00:00:00+00:00 0.000000 2012-01-12 00:00:00+00:00 0.000000 2012-01-13 00:00:00+00:00 0.000000 2012-01-17 00:00:00+00:00 0.000000 2012-01-18 00:00:00+00:00 0.000000 2012-01-19 00:00:00+00:00 -0.000017 2012-01-20 00:00:00+00:00 0.008464 2012-01-23 00:00:00+00:00 -0.004162 2012-01-24 00:00:00+00:00 -0.000319 2012-01-25 00:00:00+00:00 -0.014069 ... 2013-04-23 00:00:00+00:00 0.000061 2013-04-24 00:00:00+00:00 0.028181 2013-04-25 00:00:00+00:00 -0.014142 2013-04-26 00:00:00+00:00 -0.000047 2013-04-29 00:00:00+00:00 0.000044 2013-04-30 00:00:00+00:00 -0.000010 2013-05-01 00:00:00+00:00 -0.000082 2013-05-02 00:00:00+00:00 -0.000063 2013-05-03 00:00:00+00:00 -0.000066 2013-05-06 00:00:00+00:00 0.036071 2013-05-07 00:00:00+00:00 -0.019642 2013-05-08 00:00:00+00:00 0.012507 2013-05-09 00:00:00+00:00 -0.000010 2013-05-10 00:00:00+00:00 0.011162 2013-05-13 00:00:00+00:00 -0.005950 Length: 340, dtype: float64 benchmark_returns:2012-01-04 00:00:00+00:00 0.000211 2012-01-05 00:00:00+00:00 0.002944 2012-01-06 00:00:00+00:00 -0.002436 2012-01-09 00:00:00+00:00 0.002246 2012-01-10 00:00:00+00:00 0.008831 2012-01-11 00:00:00+00:00 0.000356 2012-01-12 00:00:00+00:00 0.002337 2012-01-13 00:00:00+00:00 -0.004425 2012-01-17 00:00:00+00:00 0.002674 2012-01-18 00:00:00+00:00 0.011124 2012-01-19 00:00:00+00:00 0.004916 2012-01-20 00:00:00+00:00 0.000677 2012-01-23 00:00:00+00:00 0.000540 2012-01-24 00:00:00+00:00 -0.000995 2012-01-25 00:00:00+00:00 0.008871 ... 2013-04-23 00:00:00+00:00 0.010419 2013-04-24 00:00:00+00:00 0.000006 2013-04-25 00:00:00+00:00 0.003946 2013-04-26 00:00:00+00:00 -0.001842 2013-04-29 00:00:00+00:00 0.007122 2013-04-30 00:00:00+00:00 0.002504 2013-05-01 00:00:00+00:00 -0.009295 2013-05-02 00:00:00+00:00 0.009363 2013-05-03 00:00:00+00:00 0.010528 2013-05-06 00:00:00+00:00 0.001920 2013-05-07 00:00:00+00:00 0.005199 2013-05-08 00:00:00+00:00 0.004145 2013-05-09 00:00:00+00:00 -0.003687 2013-05-10 00:00:00+00:00 0.004309 2013-05-13 00:00:00+00:00 0.001023 Length: 340, dtype: float64 condition_number:1.72427137724 eigen_values:[ 1.02078679e-04 5.92010520e-05]
Note: