#The code below will buy preselected stocks (See StockList.csv) if 1. they have not already been purchased during the trading day #and 2. have fallen more than 4.5% from the opening price for the day. #Data sources are twelvedata.com (price quotes) and Robinhood for account information (holdings and purchase history). import requests import time import pandas as pd import json from datetime import datetime import robin_stocks.robinhood as rs import credsetting from datetime import date import pygetwindow as pw #----------------------------------------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------------------- # This section pulls in the preselected stocks that will be rebought if they meet the 4.5% single day value drop. def get_market_status(): url = f"https://api.twelvedata.com/quote?symbol=AAPL&apikey={credsetting.twelvedata_API_Key}" response = requests.get(url).json() market_flag = response['is_market_open'] return market_flag print(type(get_market_status())) while get_market_status() == True: csv_stocklist = pd.read_csv('C:\\Users\\rleva\\Desktop\\StockList.csv') stocklist = csv_stocklist['Ticker'].values.tolist() #----------------------------------------------------------------------------------------------------------------------------------- # This section defines the ticker variable initially. for ticker in stocklist: pass #----------------------------------------------------------------------------------------------------------------------------------- # This section logs into RH and pulls the summary account information. rs.login(username= credsetting.robinhood_username, password= credsetting.robinhood_password, expiresIn=86400, by_sms=True) summary = rs.account.get_all_positions() #----------------------------------------------------------------------------------------------------------------------------------- # This section builds the table with Ticker IDs in column 1 and formatted last purchase Dates in column 2. Ticker_IDs = [] Updated_Dates = [] for i in summary: Ticker_IDs.append(i['instrument_id']) for i in summary: Updated_Dates.append(i['updated_at']) Updated_Dates_Formated = [] for i in Updated_Dates: Updated_Dates_Formated.append(i[:10]) Ticker_IDs_Dates = {} for key in Ticker_IDs: for value in Updated_Dates_Formated: Ticker_IDs_Dates[key] = value Updated_Dates_Formated.remove(value) break panda_IDS_Dates = pd.DataFrame(Ticker_IDs_Dates.items(), columns = ['Ticker ID','Date']) #print(panda_IDS_Dates[:20]) #----------------------------------------------------------------------------------------------------------------------------------- # This section builds the table that has Ticker IDs in column 1 and Ticker Symbol in Column 2 csv_stocklist = pd.read_csv('C:\\Users\\rleva\\Desktop\\Ticker_ID_and_Ticker.csv') Ticker_ID_List = csv_stocklist['Ticker ID'].values.tolist() print(len(Ticker_ID_List)) Ticker_List = csv_stocklist['Ticker'].values.tolist() print(len(Ticker_List)) Ticker_IDs_Tickers = {} for key in Ticker_ID_List: for value in Ticker_List: Ticker_IDs_Tickers[key] = value Ticker_List.remove(value) break panda_IDS_Tickers = pd.DataFrame(Ticker_IDs_Tickers.items(), columns = ['Ticker ID','Ticker']) print(len(Ticker_IDs_Tickers)) print(panda_IDS_Tickers[:20]) #----------------------------------------------------------------------------------------------------------------------------------- # This section builds the joined table that includes Ticker IDs, Last Purchase Dates, and Tickers in a single table. Tickers_Added = pd.merge(panda_IDS_Dates, panda_IDS_Tickers, on ='Ticker ID', how ='left') Tickers_Added.set_index("Ticker",inplace=True) print(Tickers_Added[201:250]) #***print(Tickers_Added.loc['AAN']['Date']) #----------------------------------------------------------------------------------------------------------------------------------- # This section is the first evaluation of the selected stocks against the criteria: 1. Has stock been bought yet? 2. Is it down 4.5% from open? today = date.today() def get_price_change() : url = f"https://api.twelvedata.com/quote?symbol={ticker}&apikey={credsetting.twelvedata_API_Key}" response = requests.get(url).json() symbol = response['symbol'] open_quote = float(response['open']) current_quote = float(response['close']) return (round((current_quote/open_quote),2)) for ticker in stocklist: if Tickers_Added.loc[ticker]['Date'] != today.strftime("%Y-%m-%d") and get_price_change() < .965: rs.orders.order_buy_fractional_by_quantity(ticker, 1, timeInForce='gtc', extendedHours=False) print("Buy",ticker) print(Tickers_Added.loc[ticker]['Date']) print(get_price_change()) print(today) else: print("Criteria not met") time.sleep(30) else: print("Market is Closed")