-
Notifications
You must be signed in to change notification settings - Fork 0
/
trader.py
316 lines (241 loc) · 10.4 KB
/
trader.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
from robinhood import Robinhood
import numpy as np
import math
import os
import random
import time
import config
def recommendInitialTarget(portfolioValue,spyAllocationPercentage,tltAllocationPercentage,spyBuyPrice,tltBuyPrice):
spyTargetAllocation = spyAllocationPercentage*portfolioValue
tltTargetAllocation = tltAllocationPercentage*portfolioValue
spyTargetShares = math.floor(spyTargetAllocation/spyBuyPrice)
tltTargetShares = math.floor(tltTargetAllocation/tltBuyPrice)
return spyTargetShares,tltTargetShares
def recommendTarget(portfolioValue,spyAllocationPercentage,tltAllocationPercentage,spyBuyPrice,tltBuyPrice):
allocationRatio = math.floor(spyAllocationPercentage/tltAllocationPercentage)
tltTargetShares = math.floor(portfolioValue/(tltBuyPrice+(spyBuyPrice*allocationRatio)))
spyTargetShares =math.floor(tltTargetShares*allocationRatio)
return spyTargetShares,tltTargetShares
def targetTotalCost(spyTargetShares,tltTargetShares,spyBuyPrice,tltBuyPrice):
targetPurchaseCost = (spyTargetShares*spyBuyPrice)+(tltTargetShares*tltBuyPrice)
return targetPurchaseCost
def allocationPercentage(shares,cost,totalCost):
percentage = (shares*cost)/totalCost
return percentage
def allocationLoss(spyTarget,spyAchieved,tltTarget,tltAchieved):
loss = math.sqrt((spyTarget-spyAchieved)**2+(tltTarget-tltAchieved)**2)
return loss
def calcAlloc(rh):
spyHist = rh.get_historical_quote('SPY','5minute','week')
tltHist = rh.get_historical_quote('TLT','5minute','week')
spyPrices = spyHist[:,4]
spyVolumes = spyHist[:,5]
tltPrices = tltHist[:,4]
tltVolumes = tltHist[:,5]
spyVWAP = np.average(spyPrices, axis=0, weights=spyVolumes)
tltVWAP = np.average(tltPrices, axis=0, weights=tltVolumes)
spyPricesNorm = spyPrices/spyVWAP
tltPricesNorm = tltPrices/tltVWAP
spyVolatility = np.std(spyPricesNorm)
tltVolatility = np.std(tltPricesNorm)
totalVolatility = spyVolatility+tltVolatility
spyRawAllocation = 1-(spyVolatility/totalVolatility)
spyAllocation = 1/(1+math.exp(-20*(spyRawAllocation-.5)))
if spyAllocation > 1:
spyAllocation = 1
if spyAllocation < 0:
spyAllocation = 0
return spyAllocation
success = True
rh = Robinhood()
success = rh.marketOpenCheck()
if not success:
print('markets are closed')
else:
print('markets are open')
if success:
success = rh.login(username=config.rhuser, password=config.rhpass)
if success:
print('login succesful')
else:
print('login unsuccesful')
if success:
#exit extra postions
openPositions = rh.securities_owned()['results']
sellOrders = {}
for position in openPositions:
instrumentURL = position['instrument']
positionTicker = rh.get_url(instrumentURL)['symbol']
positionQuantity = position['quantity']
if (positionTicker != 'SPY') and (positionTicker != 'TLT'):
print('position in ', positionTicker, ' is not needed, selling')
stock_instrument = rh.instruments(positionTicker)[0]
sellOrders[positionTicker] = rh.place_immediate_market_order(instrumentURL,positionTicker,'gfd',positionQuantity,'sell')
if sellOrders == {}:
print('no extra positions found to close')
else:
print(sellOrders)
orderOutcome = 'unresolved'
while orderOutcome != 'resolved':
remainingUnresolved = False
for order in sellOrders:
orderDetail = sellOrders[order]
orderDetail['status'] = rh.check_order_status(orderDetail['url'])
if orderDetail['status'] == 'unresolved':
remainingUnresolved = True
if not remainingUnresolved:
orderOutcome = 'resolved'
else:
print('remaining unresolved orders, waiting')
time.sleep(60)
for order in sellOrders:
orderDetail = sellOrders[order]
if orderDetail['status'] == 'failure':
success = False
if not success:
print('unable to sell extra positions correctly')
if success:
#get portfolio current value
portfolioValue = rh.equity()
print('portfolioValue =', portfolioValue)
#allocate portfolio
spyAllocationPercentage = calcAlloc(rh)
tltAllocationPercentage = 1-spyAllocationPercentage
print('spyAllocationPercentage = ', spyAllocationPercentage)
print('tltAllocationPercentage = ', tltAllocationPercentage)
spyTargetAllocation = spyAllocationPercentage*portfolioValue
tltTargetAllocation = tltAllocationPercentage*portfolioValue
print('spyTargetAllocation = ', spyTargetAllocation)
print('tltTargetAllocation = ', tltTargetAllocation)
#get pricing data
spyAskPrice = rh.ask_price('SPY')
spyBidPrice = rh.bid_price('SPY')
spyAvgCost = (spyAskPrice+spyBidPrice)/2
spyBuyPrice = spyAskPrice+(spyAskPrice - spyBidPrice)
spySellPrice = spyBidPrice-(spyAskPrice - spyBidPrice)
print('spyAskPrice = ', spyAskPrice)
print('spyBidPrice = ', spyBidPrice)
tltAskPrice = rh.ask_price('TLT')
tltBidPrice = rh.bid_price('TLT')
tltAvgCost = (tltAskPrice+tltBidPrice)/2
tltBuyPrice = tltAskPrice+(tltAskPrice - tltBidPrice)
tltSellPrice = tltBidPrice-(tltAskPrice - tltBidPrice)
print('tltAskPrice = ', tltAskPrice)
print('tltBidPrice = ', tltBidPrice)
#recommend position sizes
[spyTargetShares,tltTargetShares] = recommendTarget(portfolioValue,spyAllocationPercentage,tltAllocationPercentage,spyBuyPrice,tltBuyPrice)
print('spyTargetShares = ', spyTargetShares)
print('tltTargetShares = ', tltTargetShares)
targetPurchaseCost = targetTotalCost(spyTargetShares,tltTargetShares,spyBuyPrice,tltBuyPrice)
spyTargetAllocationPercentage = allocationPercentage(spyTargetShares,spyBuyPrice,targetPurchaseCost)
tltTargetAllocationPercentage = allocationPercentage(tltTargetShares,tltBuyPrice,targetPurchaseCost)
print('spyTargetAllocationPercentage = ',spyTargetAllocationPercentage)
print('tltTargetAllocationPercentage = ',tltTargetAllocationPercentage)
targetLoss = allocationLoss(spyTargetAllocationPercentage,spyAllocationPercentage,tltTargetAllocationPercentage,tltAllocationPercentage)
print('target loss = ',targetLoss)
targetRemainingCash = portfolioValue-targetPurchaseCost
print('targetPurchaseCost = ', targetPurchaseCost)
print('targetRemainingCash = ', targetRemainingCash)
#detemine required rebalancing
spyRequired = spyTargetShares
tltRequired = tltTargetShares
for position in openPositions:
instrumentURL = position['instrument']
positionTicker = rh.get_url(instrumentURL)['symbol']
positionQuantity = float(position['quantity'])
if (positionTicker == 'SPY'):
spyRequired = spyTargetShares-positionQuantity
if (positionTicker == 'TLT'):
tltRequired = tltTargetShares-positionQuantity
print('spyRequired = ',spyRequired)
print('tltRequired = ',tltRequired)
spyInstrumentUrl = (rh.instruments('SPY')[0])['url']
tltInstrumentUrl = (rh.instruments('TLT')[0])['url']
if success:
#sell positions
if spyRequired < 0.0:
print('selling ',-spyRequired,' of SPY')
spySellOrder = rh.place_immediate_market_order(spyInstrumentUrl,'SPY','gfd',-spyRequired,'sell')
print(spySellOrder)
orderOutcome = 'unresolved'
while orderOutcome != 'resolved':
remainingUnresolved = False
spySellOrder['status'] = rh.check_order_status(spySellOrder['url'])
if orderResponse['status'] == 'unresolved':
remainingUnresolved = True
if not remainingUnresolved:
orderOutcome = 'resolved'
else:
print('remaining unresolved orders, waiting')
time.sleep(60)
if spySellOrder['status'] == 'failure':
success = False
if not success:
print('unable to sell required spy')
if success:
if tltRequired < 0.0:
print('selling ',-tltRequired,' of TLT')
tltSellOrder = rh.place_immediate_market_order(tltInstrumentUrl,'TLT','gfd',-tltRequired,'sell')
print(tltSellOrder)
orderOutcome = 'unresolved'
while orderOutcome != 'resolved':
remainingUnresolved = False
tltSellOrder['status'] = rh.check_order_status(tltSellOrder['url'])
if orderResponse['status'] == 'unresolved':
remainingUnresolved = True
if not remainingUnresolved:
orderOutcome = 'resolved'
else:
print('remaining unresolved orders, waiting')
time.sleep(60)
if tltSellOrder['status'] == 'failure':
success = False
if not success:
print('unable to sell required tlt')
#buy positions
if success:
if spyRequired > 0.0:
print('buying ',spyRequired,' of SPY')
spyBuyOrder = rh.place_immediate_market_order(spyInstrumentUrl,'SPY','gfd',-spyRequired,'sell',spyBuyPrice)
print(spyBuyOrder)
orderOutcome = 'unresolved'
while orderOutcome != 'resolved':
remainingUnresolved = False
spyBuyOrder['status'] = rh.check_order_status(spyBuyOrder['url'])
if orderResponse['status'] == 'unresolved':
remainingUnresolved = True
if not remainingUnresolved:
orderOutcome = 'resolved'
else:
print('remaining unresolved orders, waiting')
time.sleep(60)
if spyBuyOrder['status'] == 'failure':
success = False
if not success:
print('unable to buy required spy')
if success:
if tltRequired > 0.0:
print('buying ',tltRequired,' of TLT')
tltBuyOrder = rh.place_immediate_market_order(tltInstrumentUrl,'TLT','gfd',-tltRequired,'sell',tltBuyPrice)
print(tltBuyOrder)
orderOutcome = 'unresolved'
while orderOutcome != 'resolved':
remainingUnresolved = False
tltBuyOrder['status'] = rh.check_order_status(tltBuyOrder['url'])
if orderResponse['status'] == 'unresolved':
remainingUnresolved = True
if not remainingUnresolved:
orderOutcome = 'resolved'
else:
print('remaining unresolved orders, waiting')
time.sleep(60)
if tltBuyOrder['status'] == 'failure':
success = False
if not success:
print('unable to buy required tlt')
if success:
success = rh.logout()
if not success:
print('unable to logout')
else:
print('succesfully logged out')