EUR exchange rates

26 views
Skip to first unread message

Jani Kajala

unread,
Feb 28, 2015, 7:03:28 PM2/28/15
to pi...@googlegroups.com
A quick Saturday evening fun:

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

http://kajala.com/eur.py.txt

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 eur.py <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

try:
    # 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 = datetime.now()
    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 datetime.now() - 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('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml').read()
    root = ET.fromstring(content)
    cubetag = '{http://www.ecb.int/vocabulary/2002-08-01/eurofxref}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)))
                    exit()
    raise Exception("Currency {} not found".format(currency))
except Exception as e:
    print('Error: ' + str(e))
    exit(1)

Reply all
Reply to author
Forward
0 new messages