Posts tagged ‘ecb’

Reading the ECB fx rates file with Python (pandas)

A while ago (https://www.uweziegenhagen.de/?p=2373) I had an article on how to read the ECB fx rates file with Python. Some time has passed, there are other options in Python 3.

Option 1: Make the Python 2 code run with Python 3

import xml.etree.ElementTree as ET
import urllib.request 
 
root = ET.parse(urllib.request.urlopen('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml')).getroot()
 
for child in root[2][0]:
    curr = child.get('currency')
    rate = child.get('rate')
    print(curr, rate)

Option 2: Use pandas >=1.3

Starting with version 1.3 pandas offers the read_xml command, so upgrade using
pip3 install --upgrade pandas or conda update pandas.

from urllib.request import urlopen
import pandas as pd
 
df = pd.read_xml(urlopen('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'),xpath='//*[@currency]')
 
print(df)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website