Plot Historical Exchange Rates in Python

Gözde Turan
3 min readMay 31, 2020

--

As a weekend hobby project, I visualized the historical exchange rate data.

The first step was to find an API to fetch data. After searching a lot to access historical exchange rates, I found exchangeratesapi.io which provides a free service for current and historical exchange rates published by European Central Bank in JSON format.

The second step is to make request API endpoint and fetch the historical data. For this purpose, I used “requests” library to fetch the data and used “json” library to parse JSON data into a dictionary.

import requests
import json
# Historical data API endpoint
# Used data starting from 01-01-2020 end at 05-30-2020, used EUR as base currency and TRY as symbol currency.
hist_url = 'https://api.exchangeratesapi.io/history?start_at=2020-01-01&end_at=2020-05-30&base=EUR&symbols=TRY'
# Make request to endpoint
response = requests.get(hist_url)
# Parse JSON data into dictionary
hist_rates = json.loads(response.text)

Example response from the endpoint:

{'rates': {'2020-02-11': {'TRY': 6.5775},
'2020-01-09': {'TRY': 6.5331},
'2020-03-09': {'TRY': 7.0002},
'2020-01-03': {'TRY': 6.6587},
'2020-04-07': {'TRY': 7.3562},
'2020-05-19': {'TRY': 7.4448},
......
'2020-02-21': {'TRY': 6.6131},
'2020-04-29': {'TRY': 7.5767},
'2020-04-08': {'TRY': 7.3798}},
'start_at': '2020-01-01',
'base': 'EUR',
'end_at': '2020-05-24'}

In this result set, only date and exchange rate values are needed to visualize the data. So the structure will be like below:

# Desired format:
# [ { date: <value>, exchange_rate: <value> }, ... ]
# Get 'rates' from the result set
rates_by_date = hist_rates['rates']
# Convert the dictionary into desired format
hist_data = []
for key, value in rates_by_date.items():
hist_dict = {'date': key, 'exchange_rate': value['TRY']}
hist_data.append(hist_dict)

Since the response converted into the dictionary, exchange rate values per day are unsorted. To sort the data, “sort” function will be enough.

hist_data.sort(key = lambda x:x['date'])

Now, there is a sorted list of exchange rates by date. Data is ready to visualize. I used “pandas” and “matplotlib” libraries to plot the data.

import matplotlib.pyplot as plt
import pandas as pd
# Create pandas dataframe
df = pd.DataFrame(hist_data)
# Put dates on the x-axis
x = df['date']
# Put exchange rates on the y-axis
y = df['exchange_rate']
# Specify the width and height of a figure in unit inches
fig = plt.figure(figsize=(15,6))
# Rotate the date ticks on the x-axis by degrees
plt.xticks(rotation=90)
# Set title on the axis
plt.xlabel('Date', fontsize=12)
plt.ylabel('Exchange Rates', fontsize=12)
# Plot the data
plt.plot(x,y)
Historical data with overlapped dates

The visualization doesn’t seem good as the dates are overlapped. Fewer dates on the x-axis create better visualization. To do that, I used “numpy” library and added the below code to our visualization.

import numpy as np# Plot the date on x-axis in every 5 day
plt.xticks(np.arange(0, len(hist_data), 5))

Our final code and visualization:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(hist_data)
x = df['date']
y = df['exchange_rate']
fig = plt.figure(figsize=(15,6))
plt.xticks(rotation=90)
plt.xticks(np.arange(0, len(hist_data), 5))
plt.xlabel('Date', fontsize=12)
plt.ylabel('Exchange Rates', fontsize=12)
plt.plot(x,y)

There are several other ways to implement this simple project. My next step is going to be doing an interactive exchange rate graph. I hope you enjoyed reading it.

References:

--

--