-
Notifications
You must be signed in to change notification settings - Fork 1
/
alpacaBot.py
217 lines (191 loc) · 7.35 KB
/
alpacaBot.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
import alpaca_trade_api as tradeapi
import pandas as pd
import statistics
import sys
import time
import pickle
from enum import Enum
import json
from datetime import datetime, timedelta, date
from pytz import timezone
import threading
class tradingBot(threading.Thread):
def __init__(self, api, strategy, accountRatio):
self.api = api
self.strategy = strategy
self.accountRatio = accountRatio
self.fredData = []
self.fredLastQueryDate = 0
class Choice(Enum):
LONG = 0
SHORT = 1
HOLD = 2
#tobuy and toSell are in format of stock ticker -> agreement
#returns toBuy and toSell in format ticker -> amount to buy/sell, price
def appendAmountWithPrice(toBuy, toSell, votePercentage):
account = self.api.get_account()
buyingPower = account.buying_power * self.accountRatio
longBudget = 0.7 * buyingPower
shortBudget = (1 - longRatio) * buyingPower
budgets = [longBudget, shortBudget]
dictList = [toBuy, toSell]
for index in range(len(dictList)):
orderDict = dictList[index]
budget = budgets[index]
totalAgreement = 0
for stock in orderDict:#summing agreement
totalAgreement += orderDict[stock]
for stock in orderDict:#putting amount and price onto dict
barset = api.get_barset(stock, 'day', limit=1)
stockPrice = barset[stock].c
stockBudget = budget * orderDict[stock] / totalAgreement
amountToBuy = stockBudget / stockPrice
orderDict[stock] = [amountToBuy, stockPrice]
def getTodaysFredData():
if self.fredLastQueryDate == 0 or self.fredLastQueryDate != date.today():
self.fredData = []
self.fredLastQueryDate = date.today()
fredUrlRoot = 'https://api.stlouisfed.org/fred/series/observations?'
fredseriesOfInterest = ['DTWEXAFEGS','DPRIME', 'TOTCI', 'UNRATE', 'CONSUMER','BUSLOANS','CCLACBW027SBOG','STLFSI2', 'PRS85006092', 'TCU', 'FPCPITOTLZGUSA', 'BOPGSTB', 'IEABC', 'CPIAUCSL']
for series in fredseriesOfInterest:
url = urlRoot + 'series_id='+ series + '&api_key='+ apiKey + '&file_type=json&sort_order=desc'
resp = requests.get(url)
obs = resp.json()['observations']
valueLabel = obs[0]['value']
lastChangeP = (obs[0]['value'] - obs[1]['value']) / obs[1]['value']
fiveTick = statistics.mean([obs[x]['value'] for x in range(5)])
tenTick = statistics.mean([obs[x]['value'] for x in range(5)])
fiveVsTenTickAverage = (fiveTick - tenTick)/ tenTick
average = statistics.mean([obs[x]['value'] for x in range(20)])
upperBand = average + statistics.stdev([obs[x]['value'] for x in range(20)])
lowerBand = average - statistics.stdev([obs[x]['value'] for x in range(20)])
bPercent = (obs[0]['value'] - lowerBand) / (upperBand - lowerBand)
self.fredData.append(valueLabel)
self.fredData.append(lastChangeP)
self.fredData.append(fiveVsTenTickAverage)
self.fredData.append(bPercent)
return self.fredData
#get the data of the stock and generate the values to feed into the strategy forest
def getData(stock):
barset = api.get_barset(stock, 'day', limit=10)
stockBars = barset[stock]
valuesList = []
#calculate and append the values needed to valuesList
tenDayVolume = [x.v for x in stockBars]
volumeMean = sum(tenDayVolume)/len(tenDayVolume)
VolumeZScoreTenDay = 0
if statistics.stdev(tenDayVolume) != 0:
VolumeZScoreTenDay = (stockBars[0].v - volumeMean) / statistics.stdev(tenDayVolume)
highVsLowPerc = (stockBars[0].h - stockBars[0].l) / stockBars[0].l
dayPercentChange = (stockBars[0].c - stockBars[0].o)/stockBars[0].o
fiveDayAverage = (stockBars[0].c + stockBars[1].c + stockBars[2].c + stockBars[3].c + stockBars[4].c) / 5
tenDayAverage = sum([x.c for x in stockBars])/10
fiveVsTenDayAverage = (fiveDayAverage - tenDayAverage) /tenDayAverage
fiveDayWeightedAverage = sum([stockBars[x].c * (5 - x) for x in range(5)])/15
tenDayWeightedAverage = sum([stockBars[x].c * (10 - x) for x in range(10)])/5
fiveVSTenDayWeightedAverage = (fiveDayWeightedAverage - tenDayWeightedAverage) /tenDayWeightedAverage
fiveDaySlopeChange = (stockBars[0].c - stockBars[4].o ) / 5
tenDaySlopeChange = (stockBars[0].c - stockBars[9].o ) / 10
fiveVsTenDaySlopeChange = fiveDaySlopeChange - fiveDaySlopeChange
valuesList.append(VolumeZScoreTenDay)
valuesList.append(highVsLowPerc)
valuesList.append(dayPercentChange)
valuesList.append(fiveVSTenDayWeightedAverage)
valuesList.append(fiveVsTenDaySlopeChange)
valuesList.append(fiveVsTenDayAverage)
fredData = getTodaysFredData()
for x in fredData:
valuesList.append(x)
return valuesList
#decide which stocks to trade and how much, use appendAmountWithPrice
def chooseWhichToTrade():
#get stock data from the past day for stocks in my universe
#get the top 10%, bottom 5%
#sell bottom 5% of stocks, then buy the top 10% based on appendAmountWithPrice
#returns choice, % of votes for that choice, -1 if hold
def choose(votePercentage):
indices = [i for i, x in enumerate(votePercentage) if x == max(votePercentage)]
voteSum = sum(votePercentage)
if len(indices) == 1:
return Choice(indices[0]), indices[0] / voteSum
else:
return Choice.HOLD, -1
tommorowZScorePredictorLoc = ''
fiveDayPredictorLoc = ''
toBuy = dict()
toSell = dict()
for stock in universe: #decide whether to buy/sell and how much along with stoploss/limit price
stockData = getData(stock)
votePercentage = self.strategy.predictProba(stockData)
thisChoice, agreement = choose(votePercentage)
if thisChoice is Choice.LONG:
toBuy[stock] = [agreement]
elif thisChoice is Choice.SHORT:
toSell[stock] = [agreement]
else:#decision was to hold
pass
appendAmountWithPrice(toBuy, toSell)
return toBuy, toSell
#dict of symbol -> amount, price for toBuy
#dict of symbol -> amount, price for toSell
def trade(toBuy, toSell):
takeProftRatio = 1.03
stopLossRatio = .97
for symbol in toSell:
api.submit_order(
symbol=symbol,
qty=toSell[symbol][0],
side='sell',
type='market',
time_in_force='day',
order_class='bracket',
stop_loss = dict(
stop_price = toSell[symbol][1] * takeProftRatio),
take_profit = dict(
limit_price = toSell[symbol][1] * stopLossRatio)
)
for symbol in toBuy:
api.submit_order(
symbol=symbol,
qty=toBuy[symbol][0],
side='buy',
type='market',
time_in_force='day',
order_class = 'bracket',
stop_loss=dict(
stop_price = toBuy[symbol][1] * stopLossRatio),
take_profit = dict(
limit_price = toBuy[symbol][1] * takeProftRatio)
)
#continuously runs
def run(self):
api = self.api
cycle = 1
while True:
clock = api.get_clock()
tradedToday = False
toBuy = None
toSell = None
if clock.is_open: #if can trade
if not tradedToday: #but have not traded
if toBuy == None or toSell == None:#if script was started mid-trading day
toBuy, toSell = chooseWhichToTrade()
time_after_open = clock.next_open - clock.timestamp
#trade a min after market opens
if time_after_open.seconds >= 60:
trade(toBuy, toSell)
tradedToday = True
toBuy = None
toSell = None
else:
if cycle % 10 == 0:
print("Already traded today, waiting for next market day...")
cycle = 1
else: #still waiting for market open
if toBuy == None and toSell == None:
toBuy, toSell = chooseWhichToTrade()
if cycle % 10 == 0:
print("Waiting for next market day...")
cycle = 1
time.sleep(30)
cycle+=1