import finnhub import time import csv import pytz from datetime import datetime import pyEX import datetime as dt import sys, os, base64, hashlib, hmac import requests def readCSV(max_stocks): symbols = [] stock_info = {} f = open('csv/tickers.csv', 'r') CSV = csv.reader(f) next(CSV) i = 0 for row in CSV: if i < max_stocks: i += 1 try: symbol, current_price, opening_price = row symbols.append(symbol) stock_info[symbol] = [current_price, opening_price] except: symbol = row[0] symbols.append(symbol) stock_info[symbol] = [] else: print('max stocks exceeded') break f.close() return symbols, stock_info def emptyInfo(symbols, stock_info): update = False for symbol in symbols: if len(stock_info[symbol]) == 1: # stock with no info update = True return update def updateUpdate(NY_time): NY_str = NY_time.strftime("%d/%m/%Y %H:%M:%S") f = open('csv/last_update.csv', 'w+') f.write(NY_str + '\n') f.close() def updateStockPrices(symbols): try: quotes = [finnhubClient.quote(symbol) for symbol in symbols] current_prices = [quote['c'] for quote in quotes] opening_prices = [quote['o'] for quote in quotes] print(current_prices) print(opening_prices) print(current_prices, opening_prices) CSV = open('csv/tickers.csv', 'w+') CSV.write('name,current,opening\n') for i, symbol in enumerate(symbols): CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n') CSV.close() print('API called successfully') except Exception as e: print("Could not fetch data - API CALLS REACHED? - Will display old image") print(e) apiCalledError = True def updateStockPricesIEX(symbols): symbols_str = ','.join(symbols) method = 'GET' host = 'https://cloud.iexapis.com/stable' lastEndpoint = '/tops/last' querystring = '?symbols=' + symbols_str +'&token='+iexAPIkey last_request_url = host + lastEndpoint + querystring print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++') print('Request URL = ' + last_request_url) last_response = requests.get(last_request_url) if last_response.status_code == 200: print('last success') current_prices = [] for stock in last_response.json(): current_prices.append(stock['price']) for symbol in symbols: symbol = 'MSFT' method = 'GET' host = 'https://cloud.iexapis.com/stable' lastEndpoint = '/tops/last' intradayEndpoint = '/stock/'+ symbol+ '/intraday-prices' querystring = '?chartIEXOnly=true&token='+iexAPIkey intraday_request_url = host + intradayEndpoint + querystring print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++') print('Request URL = ' + intraday_request_url) intraday_response = requests.get(intraday_request_url) print('\nRESPONSE++++++++++++++++++++++++++++++++++++') print('Response code: %d\n' % intraday_response.status_code) print(intraday_response.text) for time_point in intraday_response.json(): print(time_point['date']) print(time_point['open']) CSV = open('csv/tickers.csv', 'w+') CSV.write('name,current,opening\n') for i, symbol in enumerate(symbols): CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n') CSV.close() print(lasts) if __name__ == '__main__': finnhubAPIkey = "c24qddqad3ickpckgg80" #Finnhub finnhubsandboxAPIkey = "sandbox_c24qddqad3ickpckgg8g" #Finnhub sleeptime = 2 #minutes finnhubClient = finnhub.Client(api_key=finnhubAPIkey) max_stocks = 200 iexAPIkey = 'pk_68ef6a15902c41f887f0b544a0ca17cf' #IEX iexSandboxAPIkey = 'Tpk_0078dff413ef4f979137f7111452dc4b' #updateStockPricesIEX(symbols) finnhubClient = finnhub.Client(api_key=finnhubAPIkey) NY_zone = pytz.timezone('America/New_York') NY_time = datetime.now(NY_zone) opening = NY_time.replace(hour=9, minute=30, second=0, microsecond=0) closing = NY_time.replace(hour=16, minute=0, second=0, microsecond=0) NY_time = datetime.now(NY_zone) print(NY_time) while True: NY_time = datetime.now(NY_zone) symbols, stock_info = readCSV(max_stocks) if opening < NY_time < closing and datetime.today().weekday() < 5: # we need to do real time updating print('market open') updateStockPrices(symbols) updateUpdate(NY_time) elif emptyInfo(symbols, stock_info): # if theres any empty stocks updateStockPrices(symbols) updateUpdate(NY_time) else: # update if last update was before the previous days closing f = open('csv/last_update.csv', 'r') CSV = csv.reader(f) last_update_str = next(CSV)[0] print(last_update_str) last_update = datetime.strptime(last_update_str, "%d/%m/%Y %H:%M:%S") yday_closing = closing - dt.timedelta(days=1) yday_str = yday_closing.strftime("%d/%m/%Y %H:%M:%S") yday_closing = datetime.strptime(yday_str, "%d/%m/%Y %H:%M:%S") print(last_update < yday_closing) if last_update < yday_closing: updateStockPrices(symbols) updateUpdate(NY_time) time.sleep(sleeptime*60)