I recently found myself in need of the ability to work with multiple currencies within Python and came across Open Exchange Rates – a JSON feed with multiple currencies updated hourly. Best of all there is a free plan which allows you to hit the API up to 1,000 times a month! For my purposes hourly rates were not needed – daily rates were fine and should be for most commerce applications where the rates are only being used to estimate a price.
Unfortunately as of now there is no official Python wrapper to get rates from the API, however as they are delivered in JSON they are simple enough to grab and decode. I wrote a little wrapper, PyExchangeRates, which simplifies access to different currencies and allows you to work with money of different currencies just like you would with regular numbers in Python.
Here’s a little example of how the module works. Firstly the module is imported and an ‘Exchange’ is created using your API key from Open Exchange Rates. This will download the latest rates and save them to a local file. Next time the module is loaded, if the file can be found the rates will be loaded from the local version. If the local version is older than one day old and there is an internet connection is available, the rates will be updated automatically, however the old rates can be used if there isn’t any internet connection available. This saves you from overrunning your free limit of API hits.
import PyExchangeRates # Create an 'Exchange' object, this holds all the information about the currencies and exchange rates # Get a free API key from https://openexchangerates.org/signup/free exchange = PyExchangeRates.Exchange('YOUR API KEY HERE')
Now the exchange is created we can withdraw some currencies. There are over 100 currencies available, all accessible via their standard three letter identifier – the full list is available here.
# Withdraw a few different currencies from the exchange a = exchange.withdraw(1000, 'USD') b = exchange.withdraw(1000, 'EUR')
Now that we have a few different currencies, we can play with them like they are regular numbers in Python. The currencies need not be the same to be added together etc but the result will always be in USD for consistency.
# Money can be added together, the result will be in USD print a + b 2352.363797 USD # Money can be subtracted... print a - b -352.363797 USD # Multiplied... print a * b 1352363.796680 USD # Scaled up... print a * 2 2000.000000 USD # and divided by a constant print b / 2 500.000000 USD
Now that we have a few different currencies, we can play with them like they are regular numbers in Python. The currencies need not be the same to be added together etc but the result will always be in USD for consistency. No need to worry, money can be converted from one currency to another with one li
# Money can also be converted to other currencies print a.convert('AUD') 1061.079000 AUD
Feel free to fork the project on Github if you can think of any improvements, happy coding!