Skip to content

Instantly share code, notes, and snippets.

@johnpaulhayes
Created February 19, 2015 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnpaulhayes/56985e80f696cbc041f2 to your computer and use it in GitHub Desktop.
Save johnpaulhayes/56985e80f696cbc041f2 to your computer and use it in GitHub Desktop.
Retrieve exchange rates from Central Bank of Ireland and load them into a dictionary
# -*- coding: utf-8 -*-
import urllib
import xlrd
class ExchangeRates():
"""
Class to fetch exchange rate information from the Central Bank of Ireland
Example:
ex = ExchangeRates()
latest_rates = ex.get_latest_rates()
if latest_rates:
for rate in latest_rates:
print rate, latest_rates[rate]
else:
print ex.error
"""
url, workbook, error = None, None, None
def __init__(self, url=None):
self.url = 'http://www.centralbank.ie/polstats/stats/exrates/Documents/Past%205%20days.xls'
if url:
self.url = url
def get_latest_rates(self):
""" Def to open and retreive rate information and
place into dict"""
xls_file = self.download_file()
if not xls_file:
return False
try:
self.workbook = xlrd.open_workbook(xls_file)
except Exception, e:
self.error = 'Failed to retreive data from central bank'
return False
worksheet = self.workbook.sheet_by_index(0)
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
rates, current_row = {}, 0
latest_date = worksheet.cell_value(0,6)
latest_rate = 6
while current_row < num_rows:
current_row += 1
rates[worksheet.cell_value(current_row,0)] = worksheet.cell_value(current_row,6)
return rates
def download_file(self):
excel_file = urllib.URLopener()
try:
excel_file.retrieve(self.url, '/tmp/exchange_rates.xls')
return '/tmp/exchange_rates.xls'
except Exception, e:
self.error = 'Failed to retreive exchange rate file'
return False
@johnpaulhayes
Copy link
Author

It would be nice if the exchange rate file contained the currency code like the european central bank.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment