-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpairs_trading.py
133 lines (104 loc) · 5.03 KB
/
pairs_trading.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import numpy as np
import statsmodels.api as sm
import pandas as pd
from zipline.utils import tradingcalendar
import pytz
def initialize(context):
# Quantopian backtester specific variables
set_symbol_lookup_date('2014-01-01')
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1))
context.stock_pairs = [(symbol('ABGB'), symbol('FSLR')),
(symbol('CSUN'), symbol('ASTI')),
(symbol('KO'), symbol('PEP')),
(symbol('AAPL'), symbol('IBM')),
(symbol('FB'), symbol('YHOO')),
(symbol('TWTR'), symbol('YHOO'))]
context.stocks = [symbol('ABGB'), symbol('FSLR'), symbol('CSUN'), symbol('ASTI'),\
symbol('KO'), symbol('PEP'), symbol('AAPL'), symbol('IBM'), symbol('FB'),\
symbol('YHOO'),symbol('TWTR')]
context.num_pairs = len(context.stock_pairs)
# strategy specific variables
context.lookback = 20 # used for regression
context.z_window = 20 # used for zscore calculation, must be <= lookback
context.spread = np.ndarray((context.num_pairs, 0))
# context.hedgeRatioTS = np.ndarray((context.num_pairs, 0))
context.inLong = [False] * context.num_pairs
context.inShort = [False] * context.num_pairs
schedule_function(func=check_pair_status, date_rule=date_rules.every_day(),\
time_rule=time_rules.market_close(minutes=90))
def check_pair_status(context, data):
if get_open_orders():
return
prices = data.history(context.stocks, fields='price', bar_count=35, frequency='1d').\
iloc[-context.lookback::]
new_spreads = np.ndarray((context.num_pairs, 1))
for i in range(context.num_pairs):
(stock_y, stock_x) = context.stock_pairs[i]
Y = prices[stock_y]
X = prices[stock_x]
try:
hedge = hedge_ratio(Y, X, add_const=True)
record(hedge=hedge)
except ValueError as e:
log.debug(e)
return
# context.hedgeRatioTS = np.append(context.hedgeRatioTS, hedge)
new_spreads[i, :] = Y[-1] - hedge * X[-1]
if context.spread.shape[1] > context.z_window:
# Keep only the z-score lookback period
spreads = context.spread[i, -context.z_window:]
zscore = (spreads[-1] - spreads.mean()) / spreads.std()
record(zscore=zscore)
if context.inShort[i] and zscore < 0.0:
order_target(stock_y, 0)
order_target(stock_x, 0)
context.inShort[i] = False
context.inLong[i] = False
record(X_pct=0, Y_pct=0)
return
if context.inLong[i] and zscore > 0.0:
order_target(stock_y, 0)
order_target(stock_x, 0)
context.inShort[i] = False
context.inLong[i] = False
record(X_pct=0, Y_pct=0)
return
if zscore < -1.0 and (not context.inLong[i]):
# Only trade if NOT already in a trade
y_target_shares = 1 #long y
X_target_shares = -hedge #short x
context.inLong[i] = True
context.inShort[i] = False
(y_target_pct, x_target_pct) = computeHoldingsPct( y_target_shares,X_target_shares, Y[-1], X[-1] )
order_target_percent( stock_y, y_target_pct * (1.0/context.num_pairs) )
order_target_percent( stock_x, x_target_pct * (1.0/context.num_pairs) )
record(Y_pct=y_target_pct, X_pct=x_target_pct)
return
if zscore > 1.0 and (not context.inShort[i]):
# Only trade if NOT already in a trade
y_target_shares = -1 #short y
X_target_shares = hedge #long x
context.inShort[i] = True
context.inLong[i] = False
(y_target_pct, x_target_pct) = computeHoldingsPct( y_target_shares, X_target_shares, Y[-1], X[-1] )
order_target_percent( stock_y, y_target_pct * (1.0/context.num_pairs))
order_target_percent( stock_x, x_target_pct * (1.0/context.num_pairs))
record(Y_pct=y_target_pct, X_pct=x_target_pct)
context.spread = np.hstack([context.spread, new_spreads])
def hedge_ratio(Y, X, add_const=True):
if add_const:
X = sm.add_constant(X)
model = sm.OLS(Y, X).fit()
return model.params[1]
model = sm.OLS(Y, X).fit()
return model.params.values
def computeHoldingsPct(yShares, xShares, yPrice, xPrice):
yDol = yShares * yPrice
xDol = xShares * xPrice
notionalDol = abs(yDol) + abs(xDol)
y_target_pct = yDol / notionalDol
x_target_pct = xDol / notionalDol
return (y_target_pct, x_target_pct)
def handle_data(context, data):
pass