From 65cba4a565c0546da0baf6b625f4d0fb369cf409 Mon Sep 17 00:00:00 2001 From: loit Date: Wed, 30 Jul 2025 22:42:32 -0400 Subject: work on expanding api to use periods then create the infrastructure for random trials --- api.py | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 85 insertions(+), 11 deletions(-) (limited to 'api.py') diff --git a/api.py b/api.py index 41e361a..48e8f72 100644 --- a/api.py +++ b/api.py @@ -1,5 +1,20 @@ import requests import json +from datetime import date, date, datetime, timedelta + +# 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() + """ Given the parameters, fetches the data for the corresponding chart using yahoo finance. @@ -51,15 +66,74 @@ def fetch_chart_data(ticker, period='1y', interval='1d'): # 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 +""" +Given the parameters, +fetches the data for the corresponding chart using yahoo finance. +Cosumes period_length as a timedelta and period_end_date as a date +If bad request, returns the previous chart. +""" +def fetch_chart_data_backtest(ticker='ADA-USD', interval='1m', period_end_date=None, period_length=None): + if period_end_date == None: + period_end_date = datetime.now() + if period_length == None: + period_length = timedelta(days=8) -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 + # cast to int to truncate the decimal + period2 = int(datetime.timestamp(period_end_date)) + # find the first period via subtracting the period length + period1 = int(datetime.timestamp(period_end_date - period_length)) + + print(datetime.isoformat(datetime.fromtimestamp(period2)), datetime.isoformat(datetime.fromtimestamp(period1))) + + params = { + 'period1' : period1, # the start date (in epoch time) + 'period2' : period2, # the end time (in epoch time) + 'interval' : interval, # 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 4h, 1d, 5d, 1wk, 1mo, 3mo + 'events' : 'div|split|earn', + 'includePrePost' : 'false', + 'lang' : 'en-US', + 'region' : 'US' } + headers = {'User-agent' : 'fin-backtesting-proj'} + r = requests.get("https://query2.finance.yahoo.com/v8/finance/chart/" + ticker, headers=headers, params=params) + + print(r.url) + print("status_code:\t", r.status_code) + + # decode the JSON response data into a Python object + try: + r.raise_for_status() # raises if error before parsing + except: + print(r.text) + last_data = pull_last_from_file() + last_data['error'] = True + return last_data + + data_obj = r.json() + + # get the specific data we want + if 'timestamp' not in data_obj['chart']['result'][0]: + last_data = pull_last_from_file() + last_data['error'] = True + return last_data + timestamps = data_obj['chart']['result'][0]['timestamp'] + close_prices = data_obj['chart']['result'][0]['indicators']['quote'][0]['close'] + + # clean out null's and 0s from the data + 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'] + + data = {'timestamps': timestamps, 'prices': close_prices, 'name': name, 'error': False} + update_last_file(data) + # save data to file in case necessary + return data + +def test(): + fetch_chart_data_backtest() +test() \ No newline at end of file -- cgit v1.2.3-70-g09d2