"""Static Currency data.""" import os import pkg_resources from abacus_common_data.xml_parse import yield_currencies CURRENT_ISO_FILE = pkg_resources.resource_filename( 'abacus_common_data', 'data/xml/current_iso_currencies.xml') CURRENT_ISO_PATH = 'CcyTbl/CcyNtry' HISTORICAL_ISO_FILE = pkg_resources.resource_filename( 'abacus_common_data', 'data/xml/historical_iso_currencies.xml') HISTORICAL_ISO_PATH = 'HstrcCcyTbl/HstrcCcyNtry' class Currency: """Currency class.""" currency_map = {} def __init__(self, code): """Find currency by code. Raises KeyError on unknown code.""" Currency._load_xml_data() self.currency = Currency._get_iso_data(code) @staticmethod def parse_iso_xml(file_path, xml_path): """Build a keyed dict of currency code data.""" currency_map = {} for child in yield_currencies(file_path, xml_path): code = child.get('currency_code') currency_map[code] = child return currency_map @classmethod def _get_iso_data(cls, code): """Force a key error if not found.""" return cls.currency_map[code] @classmethod def _load_xml_data(cls): """Initialize the class, loading data in from ISO xml files.""" if cls.currency_map: return cls.currency_map = Currency.parse_iso_xml( CURRENT_ISO_FILE, CURRENT_ISO_PATH) historical_iso_codes = Currency.parse_iso_xml( HISTORICAL_ISO_FILE, HISTORICAL_ISO_PATH) for historical_code in cls._get_user_params(): cls.currency_map[historical_code] = \ historical_iso_codes[historical_code] @classmethod def _get_user_params(cls): """Return an array of user supplied historical codes to honor. Format should be comma-delimited without spaces. """ user_params = os.environ.get( 'HISTORICAL_ISO_CODES', # Default list of supported historical ISO codes. 'BYR,EEK,LTL,LVL,MRO,SKK,STD,TMM,VEF,ZWD' ).split(',') return list(filter(None, user_params)) @property def code(self): """Currency ISO-4217 code.""" return self.currency.get('currency_code') @property def number(self): """Currency ISO-4217 number.""" return self.currency.get('currency_number') @property def currency_name(self): """Currency ISO-4217 name.""" return self.currency.get('currency_name') def get_currency_object_from_code(currency_code): """Return an object formatted like the legacy currency schema.""" currency = Currency(currency_code) return { 'currency_id': currency.number, 'currency_code': currency.code, 'currency_name': currency.currency_name }