Automating Exchange Rate Data

It is often useful to be able to retrieve and update exchange rates in an automated manner. Fortunately, the European Central Bank publishes its foreign exchange reference rates on a daily basis, and they're kind enough to provide an XML file with the data. Although the data uses the Euro as the base currency, we can easily recalculate the rates with US Dollars as the base currency.

For example, to get the current exchange rate for Euros to US Dollars, we can run the following:

curl --silent | grep -e 'USD' | cut -d \' -f 4

As of May 22, 2009, the reference rate returned for US Dollars was 1.3972. To turn the USD per Euro rate of $1.3972/€ into Euro per USD (USD as the base rate), we simply take the inverse. To do so, we calculate 1/$1.3972, which equals €0.7157/$. To perform the calculation programatically and return the Euro per USD value:

echo "scale=4; 1/`curl --silent | grep -e 'USD' | cut -d \' -f 4`" |bc -l

When calculating foreign exchange rates, one must consider the principle of arbitrage, which is expressed mathematically as A-to-C = (A-to-B)*(B-to-C). Therefore, GBP per USD = (GBP per EU)*(EU per USD). To perform the calculation programatically and return the GBP per USD value:

USD_EU=`curl --silent | grep -e 'USD' | cut -d \' -f 4`
GBP_EU=`curl --silent | grep -e 'GBP' | cut -d \' -f 4`
EU_USD=`echo "scale=5; 1/$USD_EU" | bc -l`
GBP_USD=`echo "scale=5; $GBP_EU*$EU_USD" | bc -l`
echo $GBP_USD

For example, using the reference rates provided by the European Central Bank as of May 22, 2009, running our script to calculate the GBP per USD rate yields £0.62846/$.

Leave a Reply

Your email address will not be published. Required fields are marked *