2.7 Stock Market Case
Once you get the hang of APIs, a whole new world of data possibilities will open up to you. Let's apply what you learned in this chapter in a new case to retrieve stock market data from www.polygon.io. Please note that you will need to create a free account with polygon.io to follow along with this example. However, you are not required to use that account beyond retrieving the minimum data required for this example and you can cancel it after completing the assignment for this chapter if you choose. You also do not need to provide them with any personal information beyond an email address. The video below will walk you through the demonstration. The code from the video is also provided below:
import json, requests
key = "yLJlbno91EWcqYDh3Mg8DQUgwJ4qG7ur" # Replace this with your own key; this one no longer works
headers = {"Authorization": "Bearer " + key}
url = "https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2023-08-17/2023-08-18?adjusted=true&sort=asc&limit=120"
req = requests.get(url, headers=headers)
result = json.loads(req.text)
result
# Output:
# {'ticker': 'AAPL',
# 'queryCount': 1,
# 'resultsCount': 1,
# 'adjusted': True,
# 'results': [{'v': 66054482.0,
# 'vw': 174.5857,
# 'o': 177.14,
# 'c': 174,
# 'h': 177.5054,
# 'l': 173.48,
# 't': 1692244800000,
# 'n': 673083}],
# 'status': 'DELAYED',
# 'request_id': '51448a571802f108a65ad9b99e180814',
# 'count': 1}
import json, requests, pandas as pd
dates = ['2023-08-01', '2023-08-02', '2023-08-03', '2023-08-04', '2023-08-05']
key = "yLJlbno91EWcqYDh3Mg8DQUgwJ4qG7ur" # Replace this with your own key; this one no longer works
headers = {"Authorization": "Bearer " + key}
df = pd.DataFrame(columns=['date', 'symbol', 'open', 'high', 'low', 'close', 'volume', 'afterHours', 'preMarket'])
for date in dates:
url = f"https://api.polygon.io/v1/open-close/AAPL/{date}?adjusted=true"
req = requests.get(url, headers=headers)
result = json.loads(req.text)
try:
df.loc[len(df)] = [result['from'], result['symbol'], result['open'], result['high'], result['low'],
result['close'], result['volume'], result['afterHours'], result['preMarket']]
except:
print(result)
df
# Output:
# {'status': 'NOT_FOUND', 'request_id': '69dcb26ce3eac136ad58422b9d660428', 'message': 'Data not found.'}
# Note that you'll only get that message above if you attempt more than 5 API calls in a minute