Displaying Historical Exchange Rates with Python
We offer you a brighter future with FREE online courses - Start Now!!
Python is an excellent language for fetching and playing around with data. However, it is also great for visually plotting data on graphs. Unsurprisingly, it is widely used among data scientists and researchers. In this tutorial, we will apply these abilities to fetch and plot historical exchange rates on a graph.
Prerequisites
This project requires basic Python programming experience, and we are going to use two libraries:
- datetime – to handle the date range
- requests – to fetch the data
- json – to handle & select data
- matplotlib – to display the data on a graph
We start by installing both with the following commands:
- pip install requests
- pip install matplotlib
Getting the data
For this tutorial, we will use the /historical endpoint from currencyapi.com. They provide a Python SDK & Python tutorial, but we are going to stick with plain HTTP requests in this tutorial as we want to see what is happening under the hood.
Understanding the data structure
Taking a closer look at the /historical endpoint shows that it provides a set of exchange rates for a single date. The API also provides a /range endpoint that provides rates for a range of dates with a single API call, but the endpoint is only available for paid plans. Hence, we are going the extra mile and will request the rates for each individual date that we have in our date range. By following the documentation, the API response for a specific date looks like this:
{ "meta": { "last_updated_at": "2023-08-08T23:59:59Z" }, "data": { "CAD": { "code": "CAD", "value": 1.3424301825 }, "EUR": { "code": "EUR", "value": 0.9124001388 }, "USD": { "code": "USD", "value": 1 } } }
Since we want to plot the exchange rates between EUR & USD for the full month of January 2023, this will require 31 API requests.
After importing all previously installed libraries, we start by setting our start and end date of the designated time range:
import requests import matplotlib.pyplot as plt from datetime import date, timedelta start_date = date(2023, 1, 1) end_date = date(2023, 1, 31) Instead of simply creating an array containing each individual date, we can now use the timedelta() function to iterate through the date range: delta = timedelta(days=1) while start_date <= end_date: # do stuff for every date Inside the loop, we now request the historical rates by extending our base url with required and optional parameters: request_url = base_url + '?date=' + start_date.strftime("%Y-%m-%d") + '¤cies=EUR' headers = { 'apikey': YOUR-API-KEY } response = requests.request("GET", request_url, headers=headers) print(response.text) start_date += delta
As we plan to plot the USD/EUR exchange rate, we only need the EUR exchange rate. The documentation allows us to pass the desired rates that shall be part of the API response. This makes the API response smaller and easier to handle. Since the base_currency is USD by default, we do not have to manually set the base currency.
Running the script will print the received exchange rates for every date:
As a last step, before moving on to plotting the data, we add the dates & values to a new dictionary:
data[start_date.strftime(“%Y-%m-%d”)] = date_val
We now have everything we need to plot the data.
Plotting the data
Adding the following code will provide us with the final result – a nice plot of historical exchange rates:
plt.plot(data.keys(), data.values()) plt.xlabel('Date') plt.ylabel(f'Exchange rate USD/EUR') plt.title('Historical Exchange Rates') plt.xticks(rotation=45) plt.tight_layout() plt.show()
As a summary, you can find the full code snippet below:
import requests import matplotlib.pyplot as plt from datetime import date, timedelta import json start_date = date(2023, 1, 1) end_date = date(2023, 1, 31) base_url = "https://api.currencyapi.com/v3/historical" delta = timedelta(days=1) data = {} while start_date <= end_date: request_url = base_url + '?date=' + start_date.strftime("%Y-%m-%d") + '¤cies=EUR' headers = { 'apikey': 'YOUR-API-KEY' } response = requests.request("GET", request_url, headers=headers) response_data = json.loads(response.text) date_val = response_data['data']['EUR']['value'] print(response_data) data[start_date.strftime("%Y-%m-%d")] = date_val start_date += delta plt.plot(data.keys(), data.values()) plt.xlabel('Date') plt.ylabel(f'Exchange rate USD/EUR') plt.title('Historical Exchange Rates') plt.xticks(rotation=45) plt.tight_layout() plt.show()
Summary
This was all about Displaying historical exchange rates with python. Hope you liked it.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google