Coverage for jbank/ecb.py: 89%

# Coverage for jbank/ecb.py : 89%

## 18 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 from datetime import datetime

2 from decimal import Decimal

3 import xml.etree.ElementTree as ET # noqa

4 from urllib import request

5

6

7 def parse_euro_exchange_rates_xml(content: str):

8 """

9 Parses Euro currency exchange rates from string.

10 Format is XML from European Central Bank (http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml).

11 Returns list of (record_date: date, currency: str, rate: str) tuples of Euro exchange rates.

12 """

13 out = []

14 root = ET.fromstring(content)

15 cube_tag = '{http://www.ecb.int/vocabulary/2002-08-01/eurofxref}Cube'

16 cube = root.findall(cube_tag)[0]

17 for date_cube in cube.findall(cube_tag):

18 record_date = datetime.strptime(date_cube.attrib['time'], '%Y-%m-%d')

19 for currency_cube in date_cube.findall(cube_tag):

20 currency = currency_cube.attrib['currency']

21 out.append((record_date.date(), currency, Decimal(currency_cube.attrib['rate'])))

22 return out

23

24

25 def download_euro_exchange_rates_xml() -> str:

26 """

27 Downloads Euro currency exchange rates XML file from European Central Bank.

28 Returns XML as str

29 """

30 with request.urlopen('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml') as conn:

31 return conn.read()