diff options
author | loit <michael.foiani@gmail.com> | 2025-07-28 22:08:51 -0400 |
---|---|---|
committer | loit <michael.foiani@gmail.com> | 2025-07-28 22:08:51 -0400 |
commit | 2411108fe1783d5f03edaa57dad16804b2ce0445 (patch) | |
tree | 0d126a0fc7af4ef2dfac622d65f26d71d55fe690 /api.py | |
parent | 1ed62b0e315ca1fc97b3ba8752db24e0bebd706f (diff) |
work on functionality to change parameters of charts and refactor some files out
Diffstat (limited to 'api.py')
-rw-r--r-- | api.py | 38 |
1 files changed, 38 insertions, 0 deletions
@@ -0,0 +1,38 @@ +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! +""" +def fetch_chart_data(ticker, period='1y', interval='1d'): + params = { + 'interval' : interval, # 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 4h, 1d, 5d, 1wk, 1mo, 3mo + 'range' : period, # "1d","5d","1mo","3mo","6mo","1y","2y","5y","10y","ytd","max" + 'events' : 'div|split|earn', + 'includePrePost' : 'false' } + 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 + r.raise_for_status() # raises if error before parsing + 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)): + if close_prices[i] == None or close_prices[i] == 0: + del close_prices[i] + del timestamps[i] + i -= 1 + + name = data_obj['chart']['result'][0]['meta']['longName'] + + return {'timestamps': timestamps, 'prices': close_prices, 'name': name}
\ No newline at end of file |