sports updates and live sports added
This commit is contained in:
330
api_caller.py
330
api_caller.py
@@ -121,181 +121,196 @@ def updateStockPrices(symbols):
|
||||
|
||||
|
||||
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'
|
||||
try:
|
||||
symbols_str = ','.join(symbols)
|
||||
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
|
||||
querystring = '?symbols=' + symbols_str +'&token='+iexAPIkey
|
||||
|
||||
last_request_url = host + lastEndpoint + querystring
|
||||
|
||||
|
||||
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
|
||||
print('Request URL = ' + intraday_request_url)
|
||||
intraday_response = requests.get(intraday_request_url)
|
||||
print('Request URL = ' + last_request_url)
|
||||
last_response = requests.get(last_request_url)
|
||||
|
||||
print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
|
||||
print('Response code: %d\n' % intraday_response.status_code)
|
||||
|
||||
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'])
|
||||
|
||||
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 = 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()
|
||||
CSV.write(symbol + ',' + str(current_prices[i]) + ',' + str(opening_prices[i]) + '\n')
|
||||
CSV.close()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
|
||||
def updateCrypto(coins, coin_info, unique_bases):
|
||||
response = coingecko_client.get_price(ids=','.join(coins), vs_currencies = unique_bases, include_24hr_change=True)
|
||||
|
||||
CSV = open('csv/crypto.csv', 'w+')
|
||||
CSV.write('symbol,name,base,current,24hr change\n')
|
||||
|
||||
for coin in coins:
|
||||
info = coin_info[coin]
|
||||
print(info)
|
||||
try:
|
||||
response = coingecko_client.get_price(ids=','.join(coins), vs_currencies = unique_bases, include_24hr_change=True)
|
||||
|
||||
CSV.write(info[0] + ',' + coin + ',' + info[1] + ',' +str(response[coin][info[1]]) + ',' + str(response[coin]['usd_24h_change']) + '\n')
|
||||
CSV.close()
|
||||
CSV = open('csv/crypto.csv', 'w+')
|
||||
CSV.write('symbol,name,base,current,24hr change\n')
|
||||
|
||||
for coin in coins:
|
||||
info = coin_info[coin]
|
||||
print(info)
|
||||
|
||||
CSV.write(info[0] + ',' + coin + ',' + info[1] + ',' +str(response[coin][info[1]]) + ',' + str(response[coin]['usd_24h_change']) + '\n')
|
||||
CSV.close()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
|
||||
def updateNews():
|
||||
|
||||
|
||||
try:
|
||||
#load user settings
|
||||
|
||||
settings = json.load(open('csv/news_settings.json', 'r'))
|
||||
|
||||
print(settings)
|
||||
headlines = newsapi.get_top_headlines(**settings)
|
||||
except:
|
||||
#if no settings just get top headlines
|
||||
headlines = newsapi.get_top_headlines()
|
||||
try:
|
||||
#load user settings
|
||||
|
||||
settings = json.load(open('csv/news_settings.json', 'r'))
|
||||
|
||||
headline_titles = [headline['title'] for headline in headlines['articles']]
|
||||
headline_sources = [headline['source']['name'] for headline in headlines['articles']]
|
||||
headline_times = [headline['publishedAt']for headline in headlines['articles']]
|
||||
print(settings)
|
||||
headlines = newsapi.get_top_headlines(**settings)
|
||||
except:
|
||||
#if no settings just get top headlines
|
||||
headlines = newsapi.get_top_headlines()
|
||||
|
||||
headline_titles = [headline['title'] for headline in headlines['articles']]
|
||||
headline_sources = [headline['source']['name'] for headline in headlines['articles']]
|
||||
headline_times = [headline['publishedAt']for headline in headlines['articles']]
|
||||
|
||||
CSV = open('csv/news.csv', 'w+')
|
||||
CSV.write('headline,source,date,time\n')
|
||||
|
||||
CSV = open('csv/news.csv', 'w+')
|
||||
CSV.write('headline,source,date,time\n')
|
||||
|
||||
for i, title in enumerate(headline_titles):
|
||||
date, time = headline_times[i].split('T')
|
||||
CSV.write(title.replace(',', '^') + ',' + headline_sources[i] + ',' + date + ',' + time + '\n')
|
||||
|
||||
CSV.close()
|
||||
for i, title in enumerate(headline_titles):
|
||||
date, time = headline_times[i].split('T')
|
||||
CSV.write(title.replace(',', '^') + ',' + headline_sources[i] + ',' + date + ',' + time + '\n')
|
||||
|
||||
CSV.close()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
def updateWeather(api_key):
|
||||
f = open( "csv/weather_location.txt", 'r' )
|
||||
location = f.read()
|
||||
f.close()
|
||||
url = "https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}".format(location, api_key)
|
||||
r = requests.get(url)
|
||||
weather = r.json()
|
||||
print(weather)
|
||||
current_weather = {}
|
||||
try:
|
||||
f = open( "csv/weather_location.txt", 'r' )
|
||||
location = f.read()
|
||||
f.close()
|
||||
url = "https://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}".format(location, api_key)
|
||||
r = requests.get(url)
|
||||
weather = r.json()
|
||||
print(weather)
|
||||
current_weather = {}
|
||||
|
||||
coords = weather['coord']
|
||||
lat = coords['lat']
|
||||
lon = coords['lon']
|
||||
url = 'https://api.openweathermap.org/data/2.5/onecall?lat={}&units=metric&lon={}&appid={}'.format(lat, lon, api_key)
|
||||
r = requests.get(url)
|
||||
|
||||
current_weather['main_weather'] = weather['weather'][0]['main']
|
||||
current_weather['description'] = weather['weather'][0]['description']
|
||||
current_weather['temp'] = weather['main']['temp']
|
||||
current_weather['min_temp'] = weather['main']['temp_min']
|
||||
current_weather['max_temp'] = weather['main']['temp_max']
|
||||
current_weather['feels_like'] = weather['main']['feels_like']
|
||||
current_weather['humidity'] = weather['main']['humidity']
|
||||
current_weather['clouds'] = weather['clouds']['all']
|
||||
current_weather['wind_speed'] = weather['wind']['speed']
|
||||
current_weather['wind_direction'] = weather['wind']['deg']
|
||||
current_weather['visibility'] = weather['visibility']
|
||||
current_weather['uv'] = r.json()['current']['uvi']
|
||||
current_weather['rain_chance'] = r.json()['hourly'][0]['pop']
|
||||
|
||||
|
||||
json.dump( current_weather, open( "csv/current_weather.json", 'w+' ))
|
||||
|
||||
|
||||
daily_weather = []
|
||||
daily = r.json()['daily']
|
||||
|
||||
for day in daily:
|
||||
dct = {}
|
||||
dct['main_weather'] = day['weather'][0]['main']
|
||||
dct['description'] = day['weather'][0]['description']
|
||||
dct['min_temp'] = day['temp']['min']
|
||||
dct['max_temp'] = day['temp']['max']
|
||||
daily_weather.append(dct)
|
||||
|
||||
json.dump( daily_weather, open( "csv/daily_weather.json", 'w+' ))
|
||||
|
||||
coords = weather['coord']
|
||||
lat = coords['lat']
|
||||
lon = coords['lon']
|
||||
url = 'https://api.openweathermap.org/data/2.5/onecall?lat={}&units=metric&lon={}&appid={}'.format(lat, lon, api_key)
|
||||
r = requests.get(url)
|
||||
|
||||
current_weather['main_weather'] = weather['weather'][0]['main']
|
||||
current_weather['description'] = weather['weather'][0]['description']
|
||||
current_weather['temp'] = weather['main']['temp']
|
||||
current_weather['min_temp'] = weather['main']['temp_min']
|
||||
current_weather['max_temp'] = weather['main']['temp_max']
|
||||
current_weather['feels_like'] = weather['main']['feels_like']
|
||||
current_weather['humidity'] = weather['main']['humidity']
|
||||
current_weather['clouds'] = weather['clouds']['all']
|
||||
current_weather['wind_speed'] = weather['wind']['speed']
|
||||
current_weather['wind_direction'] = weather['wind']['deg']
|
||||
current_weather['visibility'] = weather['visibility']
|
||||
current_weather['uv'] = r.json()['current']['uvi']
|
||||
current_weather['rain_chance'] = r.json()['hourly'][0]['pop']
|
||||
|
||||
|
||||
json.dump( current_weather, open( "csv/current_weather.json", 'w+' ))
|
||||
|
||||
|
||||
daily_weather = []
|
||||
daily = r.json()['daily']
|
||||
|
||||
for day in daily:
|
||||
dct = {}
|
||||
dct['main_weather'] = day['weather'][0]['main']
|
||||
dct['description'] = day['weather'][0]['description']
|
||||
dct['min_temp'] = day['temp']['min']
|
||||
dct['max_temp'] = day['temp']['max']
|
||||
daily_weather.append(dct)
|
||||
|
||||
json.dump( daily_weather, open( "csv/daily_weather.json", 'w+' ))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
|
||||
def updateCurrencies(api_key):
|
||||
base = 'USD'
|
||||
yesterday = datetime.now() - timedelta(1)
|
||||
|
||||
str_tod = datetime.strftime(datetime.now(), '%Y-%m-%d')
|
||||
str_yest = datetime.strftime(yesterday, '%Y-%m-%d')
|
||||
|
||||
url = 'https://api.frankfurter.app/{}..{}?from={}'.format(str_yest, str_tod, base)
|
||||
r = requests.get(url)
|
||||
all_data = r.json()
|
||||
|
||||
currencies = ['AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY', 'NZD']
|
||||
|
||||
c_dict = {}
|
||||
|
||||
print(all_data)
|
||||
|
||||
|
||||
|
||||
for curr in currencies:
|
||||
try:
|
||||
base = 'USD'
|
||||
yesterday = datetime.now() - timedelta(1)
|
||||
|
||||
current = all_data['rates'][str_tod][curr]
|
||||
yesterday = all_data['rates'][str_yest][curr]
|
||||
str_tod = datetime.strftime(datetime.now(), '%Y-%m-%d')
|
||||
str_yest = datetime.strftime(yesterday, '%Y-%m-%d')
|
||||
|
||||
url = 'https://api.frankfurter.app/{}..{}?from={}'.format(str_yest, str_tod, base)
|
||||
r = requests.get(url)
|
||||
all_data = r.json()
|
||||
|
||||
change = current - yesterday
|
||||
currencies = ['AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'JPY', 'NZD']
|
||||
|
||||
c_dict[curr] = [current, yesterday]
|
||||
c_dict = {}
|
||||
|
||||
print(c_dict)
|
||||
json.dump([base, c_dict], open( "csv/currency.json", 'w+' ))
|
||||
|
||||
|
||||
|
||||
|
||||
for curr in currencies:
|
||||
|
||||
current = all_data['rates'][str_tod][curr]
|
||||
yesterday = all_data['rates'][str_yest][curr]
|
||||
|
||||
change = current - yesterday
|
||||
|
||||
c_dict[curr] = [current, yesterday]
|
||||
|
||||
|
||||
json.dump([base, c_dict], open( "csv/currency.json", 'w+' ))
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
def updateLeagueTable(api_key, league_id):
|
||||
url = 'https://www.thesportsdb.com/api/v1/json/{}/lookuptable.php?l={}&s=2020-2021'.format(api_key, league_id)
|
||||
@@ -306,7 +321,7 @@ def updateLeagueTable(api_key, league_id):
|
||||
|
||||
|
||||
premier_teams = []
|
||||
print(all_data['table'])
|
||||
|
||||
|
||||
for i in range(len(all_data['table'])):
|
||||
team = {}
|
||||
@@ -336,9 +351,10 @@ def updateLeagueEvents(api_key, league_id, time):
|
||||
|
||||
if time == 'past':
|
||||
url ='https://www.thesportsdb.com/api/v1/json/{}/eventspastleague.php?id={}'.format(api_key, league_id) #last 15 events on the league (premium only)
|
||||
else:
|
||||
elif time == 'future':
|
||||
url ='https://www.thesportsdb.com/api/v1/json/{}/eventsnextleague.php?id={}'.format(api_key, league_id) #next 15 events on the league (premium only)
|
||||
|
||||
elif time == 'live':
|
||||
url = 'https://thesportsdb.com/api/v2/json/{}/livescore.php?l={}'.format(api_key, league_id)
|
||||
|
||||
r = requests.get(url)
|
||||
all_data = r.json()
|
||||
@@ -354,12 +370,18 @@ def updateLeagueEvents(api_key, league_id, time):
|
||||
event = {}
|
||||
event['date'] = all_data['events'][i]['dateEvent']
|
||||
|
||||
event['time'] = all_data['events'][i]['strTime']
|
||||
if time == 'live':
|
||||
event['time'] = all_data['events'][i]['strEventTime']
|
||||
event['progess'] = all_data['events'][i]['strProgress']
|
||||
event['status'] = all_data['events'][i]['strStatus']
|
||||
else:
|
||||
event['time'] = all_data['events'][i]['strTime']
|
||||
event['round'] = all_data['events'][i]['intRound']
|
||||
event['home_team'] = all_data['events'][i]['strHomeTeam']
|
||||
event['home_score'] = all_data['events'][i]['intHomeScore']
|
||||
event['away_team'] = all_data['events'][i]['strAwayTeam']
|
||||
event['away_score'] = all_data['events'][i]['intAwayScore']
|
||||
event['round'] = all_data['events'][i]['intRound']
|
||||
|
||||
events.append(event)
|
||||
|
||||
|
||||
@@ -370,8 +392,9 @@ def updateLeagueEvents(api_key, league_id, time):
|
||||
|
||||
json.dump(events, open( "csv/sports/{}/{}_games.json".format(league, time), 'w+' ))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def updateSports(api_key):
|
||||
@@ -381,9 +404,11 @@ def updateSports(api_key):
|
||||
#updateLeagueTable(api_key, prem_id) #prem
|
||||
updateLeagueEvents(api_key, prem_id, 'past')
|
||||
updateLeagueEvents(api_key, NHL_id, 'future')
|
||||
updateLeagueEvents(api_key, NHL_id, 'live')
|
||||
|
||||
updateLeagueTable(api_key, NHL_id)
|
||||
updateLeagueTable(api_key, prem_id)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -407,6 +432,7 @@ def updateSports(api_key):
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
|
||||
newsapi = NewsApiClient(api_key='cf08652bd17647b89aaf469a1a8198a9')
|
||||
|
||||
|
||||
@@ -448,7 +474,9 @@ if __name__ == '__main__':
|
||||
sports_key = '97436974'
|
||||
|
||||
updateSports(sports_key)
|
||||
sys.exit()
|
||||
|
||||
|
||||
|
||||
|
||||
updateCurrencies(currency_key)
|
||||
|
||||
|
Reference in New Issue
Block a user