aboutsummaryrefslogtreecommitdiff
path: root/api.py
diff options
context:
space:
mode:
authorloit <michael.foiani@gmail.com>2025-07-29 00:21:17 -0400
committerloit <michael.foiani@gmail.com>2025-07-29 00:21:17 -0400
commit00d89073d7802983b11f9e5931f932444806defd (patch)
tree3f4e2c91552aa537204ff636971b254d6e2c38c0 /api.py
parent2411108fe1783d5f03edaa57dad16804b2ce0445 (diff)
worked on updating html elements and fixing some bugs with switching charts
Diffstat (limited to 'api.py')
-rw-r--r--api.py36
1 files changed, 30 insertions, 6 deletions
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