fintic-tracker/api_caller.py

218 lines
6.5 KiB
Python
Raw Normal View History

2021-05-05 15:22:01 +00:00
import finnhub
import time
import csv
2021-05-05 19:26:56 +00:00
import pytz
from datetime import datetime
2021-05-14 12:02:22 +00:00
2021-05-06 19:59:27 +00:00
import datetime as dt
2021-05-08 11:10:05 +00:00
import sys, os, base64, hashlib, hmac
import requests
2021-05-14 12:02:22 +00:00
from pycoingecko import CoinGeckoAPI
2021-05-05 19:26:56 +00:00
2021-05-14 12:02:22 +00:00
def readCSV(file_path, max_stocks):
2021-05-06 19:59:27 +00:00
symbols = []
stock_info = {}
2021-05-14 12:02:22 +00:00
f = open(file_path, 'r')
2021-05-06 19:59:27 +00:00
CSV = csv.reader(f)
next(CSV)
2021-05-07 18:39:42 +00:00
i = 0
2021-05-06 19:59:27 +00:00
for row in CSV:
2021-05-07 18:39:42 +00:00
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
2021-05-06 19:59:27 +00:00
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()
2021-05-05 19:26:56 +00:00
2021-05-06 19:59:27 +00:00
def updateStockPrices(symbols):
try:
2021-05-08 11:10:05 +00:00
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)
2021-05-14 12:02:22 +00:00
2021-05-07 18:39:42 +00:00
print(current_prices, opening_prices)
2021-05-06 19:59:27 +00:00
CSV = open('csv/tickers.csv', 'w+')
CSV.write('name,current,opening\n')
for i, symbol in enumerate(symbols):
2021-05-07 18:39:42 +00:00
2021-05-06 19:59:27 +00:00
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
2021-05-08 11:10:05 +00:00
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)
2021-05-14 12:02:22 +00:00
def updateCrypto(coins):
response = coingecko_client.get_price(ids=','.join(coins), vs_currencies = 'usd', include_24hr_change=True)
CSV = open('csv/crypto.csv', 'w+')
CSV.write('name,current,24hr change\n')
for coin in coins:
CSV.write(coin+ ',' + str(response[coin]['usd']) + ',' + str(response[coin]['usd_24h_change']) + '\n')
CSV.close()
2021-05-06 19:59:27 +00:00
if __name__ == '__main__':
2021-05-08 11:10:05 +00:00
finnhubAPIkey = "c24qddqad3ickpckgg80" #Finnhub
finnhubsandboxAPIkey = "sandbox_c24qddqad3ickpckgg8g" #Finnhub
sleeptime = 2 #minutes
finnhubClient = finnhub.Client(api_key=finnhubAPIkey)
max_stocks = 200
2021-05-07 18:39:42 +00:00
iexAPIkey = 'pk_68ef6a15902c41f887f0b544a0ca17cf' #IEX
iexSandboxAPIkey = 'Tpk_0078dff413ef4f979137f7111452dc4b'
2021-05-08 11:10:05 +00:00
#updateStockPricesIEX(symbols)
2021-05-05 19:26:56 +00:00
2021-05-08 11:10:05 +00:00
finnhubClient = finnhub.Client(api_key=finnhubAPIkey)
2021-05-14 12:02:22 +00:00
coingecko_client = CoinGeckoAPI()
2021-05-06 19:59:27 +00:00
NY_zone = pytz.timezone('America/New_York')
2021-05-05 19:26:56 +00:00
2021-05-06 19:59:27 +00:00
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)
2021-05-05 19:26:56 +00:00
NY_time = datetime.now(NY_zone)
2021-05-08 11:10:05 +00:00
print(NY_time)
2021-05-14 12:02:22 +00:00
coins, coin_info = readCSV('csv/crypto.csv', max_stocks)
print(coins, coin_info)
updateCrypto(coins)
sys.exit()
2021-05-06 19:59:27 +00:00
while True:
2021-05-05 15:22:01 +00:00
2021-05-08 11:10:05 +00:00
NY_time = datetime.now(NY_zone)
2021-05-14 12:02:22 +00:00
symbols, stock_info = readCSV('csv/tickers.csv', max_stocks)
2021-05-08 11:10:05 +00:00
if opening < NY_time < closing and datetime.today().weekday() < 5: # we need to do real time updating
print('market open')
2021-05-14 12:02:22 +00:00
2021-05-06 19:59:27 +00:00
updateStockPrices(symbols)
updateUpdate(NY_time)
elif emptyInfo(symbols, stock_info): # if theres any empty stocks
2021-05-08 11:10:05 +00:00
2021-05-06 19:59:27 +00:00
updateStockPrices(symbols)
updateUpdate(NY_time)
2021-05-14 12:02:22 +00:00
2021-05-06 19:59:27 +00:00
else:
# update if last update was before the previous days closing
2021-05-14 12:02:22 +00:00
2021-05-06 19:59:27 +00:00
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")
2021-05-05 19:26:56 +00:00
2021-05-06 19:59:27 +00:00
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:
2021-05-08 11:10:05 +00:00
2021-05-06 19:59:27 +00:00
updateStockPrices(symbols)
2021-05-05 19:26:56 +00:00
2021-05-06 19:59:27 +00:00
updateUpdate(NY_time)
2021-05-05 19:26:56 +00:00
2021-05-05 15:22:01 +00:00
time.sleep(sleeptime*60)