Created
February 19, 2015 17:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be nice if the exchange rate file contained the currency code like the european central bank.