The Story So Far
In our first article in this series, we looked at what APIs are and what they are used for. In the second article, we wrote a simple Python program that fetches some data from an API.
In this article, we will introduce a loop, so that we can get historical data over a period of time, then we will use this historical data and matplotlib to create a chart.
We are using the API from ExchangeRatesAPI.io because their free plan allows us to fetch historical data.
In previous steps, we already created an account at ExchangeRatesAPI.io and got a free API Key. We also installed the requests library and matplotlib, and imported them into the program we wrote. The program fetches exchange rate data for a specified date and gives us the data in JSON format, which we then convert into a nested Python dictionary.
Here is the program we developed in the last article.
import requests
import matplotlib.pyplot as plt
my_key = "my_very_secret_key:-)"
my_url="http://api.exchangeratesapi.io/v1/2022-06-15?access_key="+my_key
response = requests.get(my_url)
my_dict = response.json()
print(my_dict)
# Get the rates nested dictionary
my_dict['rates']
# Get the Kenya Shilling rate from the rates dictionary
my_dict['rates']['KES'] # Of course, you can change this to a currency of your choice.
The Task Now
Now, the URL that we use in our request is similar to the one below.
my_url=”http://api.exchangeratesapi.io/v1/2022-06-15?access_key=”+my_key
Notice that it has a date hard-coded in it, in this example, it is 2022-06-15, in the format specified by the API provider.
We are interested in getting values for different years. That means we need to send several requests, each with a different date. It also means that we need to replace the fixed date in our URL with a variable one.
We will use a for loop to do these two things.
Before we do that, though, we will need two lists: one that will contain the years we are interested in, and another that will contain the exchange rate values.
my_years = []
exch_rates = []
Now we can create our loop.
for my_year in range(2000, 2024):
my_url="http://api.exchangeratesapi.io/v1/"+str(my_year)+"-06-15?access_key="+my_key
We have replaced the hard-coded year with a variable that ranges from 2000 to 2023.
(The range function stops 1 number before the number specified in the second argument).
Get the response, convert it to a dictionary and pick out the exchange rate we want.
response = requests.get(my_url)
my_dict = response.json()
exch_rate = my_dict['rates']['KES']
We append the current year in our loop and the exchange rate to the lists we created.
my_years.append(my_year)
exch_rates.append(exch_rate)
That’s really it for retrieving the data.
In case you are wondering why we retrieve all the exchange rates when we are only interested in one, it’s because the free plan on ExchangeratesAPI.io does not allow us to retrieve data for only specified currencies.
Now we use Matplotlib to draw a chart of the exchange rate trend, display the chart and also save it as an image file.
# Set the figure size and create the plot
plt.figure(figsize=(8, 6))
plt.plot(my_years, exch_rates, color='red')
# Customize the plot
plt.title("Euro to KES Rates (Years 2000 to 2023)", fontsize='16')
plt.xlabel("Year", fontsize='13', color='green')
plt.ylabel("Euro-KES Rate", fontsize='13', color='blue')
plt.minorticks_on()
plt.grid(True, which='major', linestyle='-', linewidth=0.5)
plt.grid(True, which='minor', linestyle=':', linewidth=0.5)
# Save and show the plot
plt.savefig('EuroExRatesAPI_io.png')
plt.show()
I will not describe the matplotlib commands. They are fairly straightforward, and you can always look up the documentation.
Conclusion and Next Steps
And there it is! We have modified our program to get data for multiple dates, store them, draw a chart, show the chart and also save it as a file.
I hope you found the articles useful.
You could now try a little arithmetic and use this info that was retrieved (for exchange rates against the Euro) to get the exchange rate against a different currency, such as KES to USD.
Or you could simply look for an API that is based on the US Dollar and allow you to retrieve historical data.
You could also learn a bit more about matplotlib and plot different currencies on the same chart.
Or, of course, you could fetch data for something entirely different.
Here is the list of APIs that I shared earlier.
APIsList.
Enjoy your coding!