EUR exchange rates

Skip to first unread message

Jani Kajala

Feb 28, 2015, 7:03:28 PM2/28/15
A quick Saturday evening fun:

Python (3) script which returns EUR exchange rate (default against USD) on specific date (past 90 days, default: today).

For example, if you are making expense claims to your company, you might want to check is it more favorable for you to use exchange rate of the date when the purchase was done, or exchange rate of today.


# Returns EUR exchange rate (default against USD) on specific date (past 90 days, default: today)
# Usage: python <date as YYYY-MM-DD; default today> <currency; default USD>
# Options: --help, -h
# Note that XML feed has rates only for bank days. For holidays the previous bank day is returned.

import sys
if sys.version_info < (3,0):
    exit("Please upgrade to Python 3")

import xml.etree.ElementTree as ET
from urllib import request
from datetime import datetime, timedelta
import re

    # error checking and argument parsing
    if '--help' in sys.argv or '-h' in sys.argv:
        exit("Usage: <date as YYYY-MM-DD; default today> <currency; default USD>")
    check_date =
    date_fmt = '%Y-%m-%d'
    if len(sys.argv) > 1 and sys.argv[1].lower() != 'today' and sys.argv[1].lower() != 'now':
        check_date = datetime.strptime(sys.argv[1], date_fmt)
        if not check_date:
            raise Exception("Invalid date '{}'".format(check_date_str))
    if - check_date >= timedelta(days=90):
        raise Exception("Date {} too far in the past".format(check_date.strftime(date_fmt)))
    currency = 'USD' if len(sys.argv) < 3 else sys.argv[2]

    # parse data and print exchange rate both ways
    content = request.urlopen('').read()
    root = ET.fromstring(content)
    cubetag = '{}Cube'
    cube = root.findall(cubetag)[0]
    for date_cube in cube.findall(cubetag):
        this_date = datetime.strptime(date_cube.attrib['time'], date_fmt)
        if this_date < check_date:
            for currency_cube in date_cube.findall(cubetag):
                if currency_cube.attrib['currency'] == currency.upper():
                    rate = currency_cube.attrib['rate']
                    print("{}: EUR = {} {}; {} = {:.4f} EUR".format(date_cube.attrib['time'], rate, currency, currency, 1.0/float(rate)))
    raise Exception("Currency {} not found".format(currency))
except Exception as e:
    print('Error: ' + str(e))

Reply all
Reply to author
0 new messages