forked from SingularityMan/vector_stock_market_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
556 lines (469 loc) · 24.8 KB
/
main.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import os
import time
import requests
import json
import robin_stocks.robinhood as r
import datetime
import pytz
import torch
from polygon import RESTClient
from polygon.rest.models import (
TickerNews, MarketStatus, MarketHoliday,
)
def run(user_input, context_length):
if torch.cuda.is_available():
device = torch.cuda.current_device()
temperature = torch.cuda.temperature(device)
print(f"GPU Temperature: {temperature}°C")
if temperature >= 85:
while temperature >= 60:
print("Cooldown initiated. Waiting for cooldown to continue...")
print(f"GPU Temperature: {temperature}°C")
temperature = torch.cuda.temperature(device)
time.sleep(1)
else:
print("No GPU available.")
# Use Ollama's API to generate a response
url = "http://localhost:11434/api/chat"
headers = {
"Content-Type": "application/json"
}
messages = [{"role": "user", "content": user_input}]
# Define the payload
payload = {
"model": "llama3.1:8b-instruct-fp16",
"messages": messages,
"stream": False,
"options": {
"temperature": 0.1,
"num_ctx": context_length
# "stop": []
}
}
# Make the POST request, extract text response
response = requests.post(url, headers=headers, data=json.dumps(payload))
response_data = response.json()
text_response = response_data.get("message", {}).get("content", "No response received")
return text_response
def refresh_token(username, password, token_expires_at, token):
# Check if the token is expired
if time.time() > token_expires_at:
# If the token is expired, refresh it
print("Token expired. Refreshing token.")
r.logout()
login = r.login(username, password, expiresIn=60*60*12)
token_expires_at = time.time()+login['expires_in']
token = login['access_token']
# print("New Token:", token)
else:
print("Token is still valid. Expires in", token_expires_at-time.time(), "seconds.")
# print("Token:", token)
return token_expires_at, token
# No news error
class NoNewsError(Exception):
pass
def get_market_holidays(api_key):
client = RESTClient(api_key)
holidays = client.get_market_holidays()
return holidays
def generate_text(user_input, context_length):
response = ""
while response is None or response.strip() == "" or response == " ":
try:
response = run(user_input, context_length)
if response.startswith('"') and response.endswith('"'):
response = response[1:-1]
response = response.strip()
except Exception as e:
print(e)
print("Error generating text. Trying again.")
continue
return response
# Get ticker info from robinhood
def get_ticker_info(ticker):
info = r.stocks.get_stock_quote_by_symbol(ticker)
return info
# Get advanced ticker info
def get_advanced_ticker_info(ticker):
info = r.stocks.get_fundamentals(ticker)
return info
def get_quarterly_earnings(ticker):
info = r.stocks.get_earnings(ticker)
return info
def make_decision(response, context_length):
user_input = "" \
"Review this information and respond with a one-word response and include the following: [buy], [sell], or [hold].\n" \
"Here is the following information:\n\n" \
"{}\n\n" \
"If there is no text or the information is not clear, respond with [hold].\n" \
"".format(response)
decision = generate_text(user_input, context_length)
while decision is None or decision.strip() == "" or decision == " ":
print("Decision is None. Trying again.")
decision = generate_text(user_input, context_length)
return decision
def yayayayaya():
print("Hey! Hey! Hey! its time to make some CRRRRRRRRRRRRRAAAAAAAAAAAAZY money!")
time.sleep(2.50)
print("Are ya ready?")
time.sleep(0.75)
print("HERE")
time.sleep(0.25)
print("WE")
time.sleep(0.25)
print("GO!")
time.sleep(0.25)
print("$YA!")
time.sleep(0.25)
print("$YA!")
time.sleep(0.25)
print("$YA!")
time.sleep(0.25)
print("$YA!")
time.sleep(0.25)
print("$YA!")
# Login to robinhood
# Your login credentials
username = os.getenv("ROBINHOOD_USERNAME")
password = os.getenv("ROBINHOOD_PASSWORD")
if username and password:
pass
else:
print("Login credentials not found, manual input required.")
username = input("Enter your Robinhood username: ")
password = input("Enter your Robinhood password: ")
# RESTClient for Polygon.io
polygon_api_key = os.getenv('POLYGON_API_KEY')
client = RESTClient(polygon_api_key)
# Login to Robinhood
login = r.login(username, password, expiresIn=60*60*12)
token_expires_at = time.time()+login['expires_in']
token = login['access_token']
all_stock_news = []
history = []
yayayayaya()
if __name__ == '__main__':
history = ['']
# Get ticker list of blue chip stocks and historically successfull index funds
ticker_list = [
'AAPL', 'AGG', 'AMT', 'AMZN', 'ARKK',
'BAC', 'BKX', 'BND', 'BNDX', 'DGRO', 'CNI',
'DKNG', 'DUK', 'EPR', 'F', 'FAS',
'FNGU', 'GOOG', 'GS', 'HDV', 'HRZN',
'IEMG', 'INTC', 'IVR', 'IVV', 'IWM', 'IXJ',
'IYR', 'JNJ', 'JPM', 'KBWB', 'KO',
'KRE', 'LCID', 'LLY', 'LTC', 'MAIN',
'META', 'MS', 'MSFT', 'NEE', 'NOBL',
'NVDA', 'NVO', 'O', 'PFE', 'PG',
'PSEC', 'QQQ', 'SCHD', 'SMCI', 'SLG', 'SOXL',
'SPG', 'SPHD', 'SPXL', 'SPY', 'T',
'TNA', 'TQQQ', 'TSLA', 'UNH', 'UNM', 'UPRO',
'USB', 'VHT', 'VIG', 'VNQ', 'VTI',
'VXUS', 'VYM', 'WFC', 'WMT', 'XLF',
'XLP', 'XLU', 'XLV', 'XOM'
]
valid_tickers = []
print("Ticker list length:", len(ticker_list))
for ticker in ticker_list:
try:
info = r.stocks.get_stock_quote_by_symbol(ticker)
if info is not None:
print(info['symbol'], "found")
valid_tickers.append(ticker)
else:
print("Ticker removed:", ticker)
except Exception as e:
print(e)
print("Ticker removed:", ticker)
ticker_list = valid_tickers
print("Ticker list length:", len(ticker_list))
failed_transactions = []
queued_transactions = {}
ticker_index = 0
"""Main loop for stock bot. This bot will buy, sell, or hold stocks based on the news and the stock's performance.
It will also check if the NYSE is open and if it is 9:30am EST. If it is not exactly 9:30am EST, the bot will skip transactions.
If it is a holiday, the bot will also skip transactions. If the bot fails to make a transaction, it will add the ticker to
a list of failed transactions and try again after the initial loop is complete. If the bot succeeds in making a transaction, it will remove the ticker from the
list of failed transactions if it was added there. The bot will also check if the user has enough buying power to make a transaction. If the user
does not have enough buying power, the bot will skip the transaction."""
while True:
try:
time.sleep(1)
# Refresh the token if it is expired
token_expires_at, token = refresh_token(username, password, token_expires_at, token)
# Check if it is Saturday or Sunday
if datetime.datetime.now(pytz.timezone('America/New_York')).weekday() == 5 or datetime.datetime.now(pytz.timezone('America/New_York')).weekday() == 6:
print("It is the weekend. Skipping transactions.")
continue
# Check if it is before 9:30am EST or after 4:00pm EST
# If so, cancel all pending orders
if (datetime.datetime.now(pytz.timezone('America/New_York')).hour < 9 or (datetime.datetime.now().hour == 9 and datetime.datetime.now().minute < 30)) or datetime.datetime.now(pytz.timezone('America/New_York')).hour >= 16:
print("Not between 9:30am and 4:00pm EST. Cancelling all pending orders, if any")
try:
orders = r.orders.get_all_open_stock_orders()
for order in orders:
for ticker in ticker_list:
if ticker in order:
print("Cancelling order:", order['id'])
r.orders.cancel_stock_order(order['id'])
failed_transactions = []
queued_transactions = {}
time.sleep(30)
except Exception as e:
print(e)
print("Error cancelling orders. Continuing.")
token_expires_at, token = refresh_token(username, password, token_expires_at, token)
continue
continue
# Check if it is 9:30am EST and if there are no failed transactions
if (datetime.datetime.now(pytz.timezone('America/New_York')).hour != 9 or (datetime.datetime.now().hour == 9 and datetime.datetime.now().minute != 30)):
if len(failed_transactions) == 0 and len(queued_transactions) == 0:
print("Not 09:30am EST. Skipping transactions.")
print("Current time:", str(datetime.datetime.now().hour)+":"+str(datetime.datetime.now().minute))
continue
try:
# Check if today is in a stock market holiday in polygon.io
holidays = get_market_holidays(polygon_api_key)
# Use strptime to convert the date string to a date object.
today = datetime.datetime.now(pytz.timezone('America/New_York')).date()
for holiday in holidays:
holiday_date = datetime.datetime.strptime(holiday.date, '%Y-%m-%d').date()
if holiday_date == today:
break
except Exception as e:
print(e)
pass
if holiday_date == today:
print("It is a stock market holiday. Skipping transactions.")
time.sleep(30)
continue
# Wait 60 seconds before making transactions
print("Waiting 60 seconds before making transactions.")
time.sleep(60)
# Get account holdings and buying power
buying_power = None
while isinstance(buying_power, float) is False or buying_power is None:
try:
holdings = r.account.build_holdings()
buying_power = float(r.account.load_phoenix_account(info='account_buying_power')['amount'])
except Exception as e:
print(e)
print("No buying power found. Waiting 30 seconds before trying again.")
time.sleep(30)
continue
print(holdings)
print("Buying power: " + str(buying_power))
day_trades = len(r.account.get_day_trades()['equity_day_trades'])
print("Day trades:", day_trades)
# Loop through the ticker list. This is usually done once a day at 9:30am EST.
# If anything goes wrong, it will add the ticker to the failed transactions list and move on to the next ticker.
# Any tickers in the failed transactions list will be retried as soon as possible after the initial for loop.
# Any successful evaluations will be put in a queue to be executed.
for ticker in ticker_list:
# Indicates attempt to process a ticker
ticker_index += 1
# Checks if all the tickers have been processed before skipping.
# If the tickers have not been processed and the ticker is in the failed transactions list or the queued transaction list, it will skip.
# This is added in the event an error is triggered and the bot needs to continue where it left off.
if ticker_index >= len(ticker_list):
if ticker not in failed_transactions:
continue
elif ticker_index < len(ticker_list):
if ticker in failed_transactions or ticker in queued_transactions:
continue
try:
# Get stock news
all_stock_news = []
# Get ticker info, fundamentals, and quarterly earnings.
info = get_ticker_info(ticker)
ticker_fundamentals = get_advanced_ticker_info(ticker)
ticker_earnings = get_quarterly_earnings(ticker)
try:
polygon_news = client.list_ticker_news(ticker, limit=5)
for i, news in enumerate(polygon_news):
all_stock_news.append(news.description)
except Exception as e:
print("Error:", e, "\nWaiting 60 seconds before continuing.")
time.sleep(60)
# Filter out None values
all_stock_news = [text for text in all_stock_news if text is not None]
# Join all the news together
all_stock_news = "".join(all_stock_news)
# Generate a response to the news
news = generate_text(
f"Summarize this text, highlighting important developments regarding the ticker, such as earnings reports, financials, announcements, events, etc.\n"
f"The ticker is {ticker}.\n"
f"Here is the text:\n\n{all_stock_news}\n"
f"Ticker info: {info}\n"
f"Ticker fundamentals: {ticker_fundamentals}\n"
f"Ticker earnings: {ticker_earnings}",
12000
)
# Save to JSON file
ticker_file_path = os.path.join("ticker_logs", f"{ticker}.json")
# Check if the file exists and load existing data, otherwise initialize an empty list
if os.path.exists(ticker_file_path):
with open(ticker_file_path, "r", encoding="utf-8") as f:
ticker_data = json.load(f)
else:
ticker_data = []
# Append the new generated news
ticker_data.append(news)
# Write updated data back to the file
with open(ticker_file_path, "w", encoding="utf-8") as f:
json.dump(ticker_data, f, indent=4)
joined_ticker_data = ' '.join(ticker_data)
context_length = len(joined_ticker_data.split()*3)
if context_length > 32000:
context_length = 32000
# Evaluate stock news and performance
stock = ticker
stock_price = info['last_trade_price']
user_input = f"You are a stock market expert.\n" \
f"You will review this information on a ticker and make an educated guess on whether to buy, sell or hold:\n\n" \
f"Ticker History: {' '.join(joined_ticker_data)}\n" \
f"Ticker name: {stock}\n" \
f"Ticker price: {stock_price}\n" \
f"Additional ticker info: \n\n{info}\n\n" \
f"Ticker fundamentals: \n\n{ticker_fundamentals}\n\n" \
f"Ticker earnings: \n\n{ticker_earnings}\n\n" \
f"Ticker news: \n\n{news}\n\n" \
f"Give equal weight to both the news and the stock's performance.\n" \
response = generate_text(user_input, context_length)
# Append response to the ticker data
ticker_data.append("\n\n" + response)
# Write updated data back to the file
with open(ticker_file_path, "w", encoding="utf-8") as f:
json.dump(ticker_data, f, indent=4)
try:
#if response.startswith('"') and response.endswith('"'):
#response = response[1:-1]
response = response.strip()
print(ticker+":", response)
# Make a decision to buy, sell, or hold based on the response
decision = make_decision(response, 4096).lower()
print(decision)
except Exception as e:
print(e, "Continuing.")
if ticker not in failed_transactions:
failed_transactions.append(ticker)
continue
try:
print("Decision:", decision)
# Add ticker to the queue based on the decision and available buying power
if ("buy" in decision or "hold" in decision) and ticker not in queued_transactions:
queued_transactions[ticker] = "buy"
elif "sell" in decision and ticker not in queued_transactions:
queued_transactions[ticker] = "sell"
else:
if (ticker not in holdings and buying_power > 1) and ticker not in queued_transactions:
queued_transactions[ticker] = "hold"
except Exception as e:
print("Error:", e, "Continuing.")
if ticker not in failed_transactions:
failed_transactions.append(ticker)
continue
except Exception as e:
print("Error:", e, "Continuing.")
if ticker not in failed_transactions:
failed_transactions.append(ticker)
continue
# Assumes the transaction was successful
if ticker in failed_transactions:
failed_transactions.remove(ticker)
# Check if there are any queued transactions and execute them.
if len(queued_transactions) > 0:
print("Executing queued transactions.")
# Create a list of keys
tickers = list(queued_transactions.keys())
# Sort the list with a custom key function, sorting by sell first.
sorted_tickers = sorted(tickers, key=lambda ticker: (
queued_transactions[ticker] != 'sell', queued_transactions[ticker]))
# Iterate through the sorted list, selling tickers first before buying the rest.
# This ensures no leftover buying power and therefore no missed trades.
for ticker in sorted_tickers:
decision = queued_transactions[ticker]
# Get the currently available buying power
actual_buying_power = None
actual_buying_power = float(r.account.load_phoenix_account(info='account_buying_power')['amount'])
# Day trade check.
# No transactions will be made if the user has made 3 day trades in a 5 day period.
day_trades = len(r.account.get_day_trades()['equity_day_trades'])
# Perform the trade, depending on the decision.
if (decision == "buy" or decision == "hold") and day_trades < 3: # Buy if decision is to buy or hold.
if actual_buying_power > 1:
print("Purchasing {}".format(ticker))
print("Buying power: {}".format(buying_power))
# Determine if the user has enough buying power to buy the stock.
# The purchase is evenly distributed across your portfolio.
if buying_power / len(ticker_list) < 1:
trade = r.orders.order_buy_fractional_by_price(ticker, 1, timeInForce='gfd',
extendedHours=False)
elif buying_power / len(ticker_list) > actual_buying_power:
trade = r.orders.order_buy_fractional_by_price(ticker,
actual_buying_power,
timeInForce='gfd',
extendedHours=False)
elif buying_power / len(ticker_list) < actual_buying_power:
trade = r.orders.order_buy_fractional_by_price(ticker,
buying_power / len(ticker_list),
timeInForce='gfd',
extendedHours=False)
print(trade)
print("Trade id:", trade['id'])
time.sleep(30)
trade = r.orders.get_stock_order_info(trade['id'])
# Check if the trade was filled
# If not, add the ticker to the failed transactions list and try again later.
if trade['state'] != "filled":
print("Trade not filled. Continuing.")
if ticker not in failed_transactions:
failed_transactions.append(ticker)
continue
print("Purchased", ticker)
if ticker in failed_transactions:
failed_transactions.remove(ticker)
else:
print("Not enough buying power. Continuing.")
if ticker in failed_transactions:
failed_transactions.remove(ticker)
# Sell if decision is to sell.
# This will sell all the shares of the stock.
elif decision == "sell" and day_trades < 3:
if ticker in holdings:
print("Selling", ticker)
trade = r.orders.order_sell_fractional_by_quantity(ticker,
float(holdings[ticker]['quantity']),
timeInForce='gfd',
extendedHours=False)
print(trade)
print("Trade id:", trade['id'])
time.sleep(30)
trade = r.orders.get_stock_order_info(trade['id'])
if trade['state'] != "filled":
print("Trade not filled. Continuing.")
if ticker not in failed_transactions:
failed_transactions.append(ticker)
continue
print("Sold", ticker)
if ticker in failed_transactions:
failed_transactions.remove(ticker)
else:
print(ticker, "not in holdings. Continuing.")
if ticker in failed_transactions:
failed_transactions.remove(ticker)
if day_trades >= 3: # Cancel all pending DECISIONS if day trade limit is reached. No transactions will be made.
if ticker in failed_transactions:
failed_transactions.remove(ticker)
print("Day trade limit reached. Continuing.")
# Ticker processed
del queued_transactions[ticker]
# If all transactions, including failed transactions, are processed, reset the ticker index
if len(failed_transactions) == 0 and ticker_index >= len(ticker_list):
print("All transactions successful! Resetting ticker index.")
ticker_index = 0
except Exception as e:
print(e)
print("Error. Continuing.")
token_expires_at, token = refresh_token(username, password, token_expires_at, token)
continue