From 00d89073d7802983b11f9e5931f932444806defd Mon Sep 17 00:00:00 2001 From: loit Date: Tue, 29 Jul 2025 00:21:17 -0400 Subject: worked on updating html elements and fixing some bugs with switching charts --- api.py | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) (limited to 'api.py') diff --git a/api.py b/api.py index 0625f1a..00c2733 100644 --- a/api.py +++ b/api.py @@ -1,10 +1,9 @@ import requests import json - """ Given the parameters, fetches the data for the corresponding chart using yahoo finance. -Expect it to raise an error on bad params! +If bad request, returns the previous chart. """ def fetch_chart_data(ticker, period='1y', interval='1d'): params = { @@ -19,20 +18,45 @@ def fetch_chart_data(ticker, period='1y', interval='1d'): print("status_code:\t", r.status_code) # decode the JSON response data into a Python object - r.raise_for_status() # raises if error before parsing + try: + r.raise_for_status() # raises if error before parsing + except: + last_data = pull_last_from_file() + last_data['error'] = True + return last_data + data_obj = r.json() # get the specific data we want timestamps = data_obj['chart']['result'][0]['timestamp'] close_prices = data_obj['chart']['result'][0]['indicators']['quote'][0]['close'] - print('close_price len: ', len(close_prices), 'timestamps len: ', len(timestamps)) + # clean out null's and 0s from the data - for i in range(len(timestamps)): + i = 0 + while i < len(timestamps): if close_prices[i] == None or close_prices[i] == 0: del close_prices[i] del timestamps[i] i -= 1 + i += 1 name = data_obj['chart']['result'][0]['meta']['longName'] - return {'timestamps': timestamps, 'prices': close_prices, 'name': name} \ No newline at end of file + data = {'timestamps': timestamps, 'prices': close_prices, 'name': name, 'error': False} + + update_last_file(data) + # save data to file in case necessary + return data + +# helper function to pull most recent chart data on failure +def pull_last_from_file(): + fd = open('last_chart_data.json', 'r') + d = json.loads(fd.read()) + fd.close() + return d + +def update_last_file(data): + fd = open('last_chart_data.json', 'w') + fd.truncate(0) + fd.write(json.dumps(data)) + fd.close() \ No newline at end of file -- cgit v1.2.3-70-g09d2