Converting currencies
Another quite common preprocessing step you might encounter while working on financial tasks is converting currencies. Imagine you have a portfolio of multiple assets, priced in different currencies and you would like to arrive at a total portfolio’s worth. The simplest example might be American and European stocks.
In this recipe, we show how to easily convert stock prices from USD to EUR. However, the very same steps can be used to convert any pair of currencies.
How to do it…
Execute the following steps to convert stock prices from USD to EUR:
- Import the libraries:
import pandas as pd import yfinance as yf from forex_python.converter import CurrencyRates
- Download Apple’s OHLC prices from January 2020:
df = yf.download("AAPL", start="2020-01-01", end="2020-01-31", progress=False) df = df.drop(columns=["Adj Close", "Volume"])
- Instantiate the
CurrencyRates
object:c = CurrencyRates()
- Download the USD/EUR rate for each required date:
df["usd_eur"] = [c.get_rate("USD", "EUR", date) for date in df.index]
- Convert the prices in USD to EUR:
for column in df.columns[:-1]: df[f"{column}_EUR"] = df[column] * df["usd_eur"] df.head()
Running the snippet generates the following preview:
Figure 2.11: Preview of the DataFrame containing the original prices in USD and the ones converted to EUR
We can see that we have successfully converted all four columns with prices into EUR.
How it works…
In Step 1, we have imported the required libraries. Then, we downloaded Apple’s OHLC prices from January 2020 using the already covered yfinance
library.
In Step 3, we instantiated the CurrencyRates
object from the forex-python
library. Under the hood, the library is using the Forex API (https://theforexapi.com), which is a free API for accessing current and historical foreign exchange rates published by the European Central Bank.
In Step 4, we used the get_rate
method to download the USD/EUR exchange rates for all the dates available in the DataFrame with stock prices. To do so efficiently, we used list comprehension and stored the outputs in a new column. One potential drawback of the library and the present implementation is that we need to download each and every exchange rate individually, which might not be scalable for large DataFrames.
While using the library, you can sometimes run into the following error: RatesNotAvailableError: Currency Rates Source Not Ready
. The most probable cause is that you are trying to get the exchange rates from weekends. The easiest solution is to skip those days in the list comprehension/for
loop and fill in the missing values using one of the approaches covered in the previous recipe.
In the last step, we iterated over the columns of the initial DataFrame (all except the exchange rate) and multiplied the USD price by the exchange rate. We stored the outcomes in new columns, with _EUR
subscript.
There’s more…
Using the forex_python
library, we can easily download the exchange rates for many currencies at once. To do so, we can use the get_rates
method. In the following snippet, we download the current exchange rates of USD to the 31 available currencies. We can naturally specify the date of interest, just as we have done before.
- Get the current USD exchange rates to 31 available currencies:
usd_rates = c.get_rates("USD") usd_rates
The first five entries look as follows:
{'EUR': 0.8441668073611345, 'JPY': 110.00337666722943, 'BGN': 1.651021441836907, 'CZK': 21.426641904440316, 'DKK': 6.277224379537396, }
In this recipe, we have mostly focused on the
forex_python
library, as it is quite handy and flexible. However, we might download historical exchange rates from many different sources and arrive at the same results (accounting for some margin of error depending on the data provider). Quite a few of the data providers described in Chapter 1, Acquiring Financial Data, provide historical exchange rates. Below, we show how to get those rates using Yahoo Finance.
- Download the USD/EUR exchange rate from Yahoo Finance:
df = yf.download("USDEUR=X", start="2000-01-01", end="2010-12-31", progress=False) df.head()
Running the snippet results in the following output:
In Figure 2.12, we can see one of the limitations of this data source—the data for this currency pair is only available since December 2003. Also, Yahoo Finance is providing the OHLC variant of the exchange rates. To arrive at a single number used for conversion, you can pick any of the four values (depending on the use case) or calculate the mid-value (the middle between low and high values).
See also
- https://github.com/MicroPyramid/forex-python—the GitHub repo of the
forex-python
library