Lab 05
Lab 5: APIs
Section 1: Get API Key
In order to use an API you might need a key. This is the way that the API identifies who is requesting information and whether you have access to the information. For this lab, we’ll be using the Alpha Vantage API, which has data about different financial securities, including stocks, foreign exchange, and cryptocurrencies.
For Alpha Vantage, you can get a free API key at this link.
Make sure to select student
for Which of the following best describes you?
and fill out the rest of the boxes. Then submit the form. After you do, the webpage should display some text with your API Key. Copy this value and save it somewhere - you’ll need it later in the lab!
Section 2: Make a Simple Request
Now, let’s practice making some requests and retrieving information from urls. In Python, the requests
library has all of the functionality you’ll need. Let’s start by installing the requests
library - in your terminal type pip install requests
.
Now we’re going to try and make a request to a cat facts website and get a cat fact. The cat facts website returns a JSON with a fact in it. To see the format of the json, feel free to copy and paste the url into a web browser. The cat facts url we are using is https://catfact.ninja/fact.
Task: Make a get request to the cat facts URL (https://catfact.ninja/fact) and print out the fact!
Hint: We just want the fact to be printed out - don’t just print the json! Remember to access and print just the fact, refer to the slides for more information on accessing elements in a JSON.
CHECKPOINT:
Raise your hand on Zoom to check your request.
Section 3: Hit the Alpha Vantage API
Now, we’re going to use what we learned about requesting information from a URL to get information from the Alpha Vantage API. Specifically, we’ll be looking at daily stock prices using the daily adjusted time series endpoint. For this exercise, pick one company to investigate. You can get a list of the S&P 500 companies and their tickers here, but feel free to use any company. You’ll need one company’s stock ticker.
The documentation for the Alpha Vantage API is here, make sure to click Daily Adjusted
on the sidebar to get the documentation for the correct endpoint. In order to make a request properly, you’ll need to provide a parameters JSON with the symbol, function, and API key specified. The symbol is the stock ticker you just selected and the API key is your key from section 1 of the lab.
Task: Similarly to the cat facts website, make a request to the Alpha Vantage API and get yesterday’s opening price for the selected company’s stock. Print out the value!
Hint: If you want to see the specific format of the response JSON, you can check out this link
Section 4: Integrate API and Graph Results
Just getting one datapoint from one company doesn’t seem that helpful! With our new knowledge of APIs, we’re going to get data for 5 different companies and plot it. To start, we’ve written code to plot financial time series data for you - you’ll just be getting and transforming the data. The code to plot is:
import plotly.graph_objects as go
import requests
from random import randint
def plot_data(data):
fig = go.Figure()
for company in data:
random_rgb = (randint(0, 255), randint(0, 255), randint(0, 255))
company_data = data[company]
fig.add_trace(go.Scatter(
x = [point[0] for point in company_data],
y = [point[1] for point in company_data],
name = company,
line_color = f"rgb({random_rgb[0]}, {random_rgb[1]}, {random_rgb[2]})",
opacity = 0.8)
)
fig.update_layout(
title="Timeseries of high price for day",
xaxis_title="timeseries (daily)",
yaxis_title="stock price (USD)"
)
fig.show()
Copy and paste the above code into a python file. Make sure to also run pip install plotly
, or this code will give you errors! If you have any questions about what this code is doing, feel free to call over a TA.
Task: After you have copied this code into a python file, you should write code below it that calls the API for five different companies (feel free to select five tickers from the link provided in Section 3) and then reshapes the data so that it can be plotted. Below is an outline of what we want you to write:
- create a dictionary to store the company data
- for each ticker:
response = requests.get(<send api request>)
- get the response json, then get the “Time Series (Daily)” entry in the json
- get the first 30 days worth of data. To do this you may need to convert it to a list using
list()
- create a list containing the date and the highest price for each of the 30 days worth of data.
- add the company to the dictionary using the ticker symbol as the key and the list you just created as the value
- call the graphing function and pass in your dictionary as a parameter
CHECKPOINT:
Raise your hand on Zoom so your Lab TA can check your graph.
Section 5: Exploration of API
For this section, we want you to explore another section of the Alpha Vantage API. The only requirements are that you use a different endpoint (though it can still be a stocks endpoint, just don’t use the time series daily endpoint) and that you make at least five different calls to the API. If you are using a stocks endpoint, we’d ask that you get data about five different companies, if you are using a foreign exchange endpoint, get data about five currencies, etc. Print out something interesting about each result.
CHECKPOINT:
Raise your hand on Zoom so your Lab TA can check your code. Congrats! You’ve finished this week’s lab