aboutsummaryrefslogtreecommitdiff
path: root/api.py
blob: 00c2733f3a8317d3c39e7db4e652c14f1dbdc5ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import requests
import json
"""
Given the parameters, 
fetches the data for the corresponding chart using yahoo finance.
If bad request, returns the previous chart.
"""
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
    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']
    
    # 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

# 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()