def handle(self, *args, **options): client = OpenExchangeRatesClient(settings.OPENEXCHANGERATES_KEY) dates = {now().date(): False} updated_recs = 0 created_recs = 0 if options["retrieve_also_annual"]: for year in list( Declaration.objects.exclude(year="").values_list( "year", flat=True).distinct()): year = int(year) dt = date(int(year), 12, 31) if year < 1999: continue if dt > now().date(): continue dates[dt] = True for dt, annual in tqdm(dates.items()): rates = self.transform_rates(client.historical(dt)["rates"]) _, created = ExchangeRate.objects.update_or_create( dt=dt, is_annual=annual, defaults={"rates": rates}) if created: created_recs += 1 else: updated_recs += 1 self.stdout.write("{} records created, {} updated".format( created_recs, updated_recs))
def handle(self, *args, **options): self.verbose = int(options.get('verbosity', 0)) self.options = options client = OpenExchangeRatesClient(APP_ID) if self.verbose >= 1: self.stdout.write("Querying database at %s" % (client.ENDPOINT_CURRENCIES)) try: code = C._default_manager.get(is_base=True).code except C.DoesNotExist: code = 'USD' # fallback to default l = client.latest(base=code) if self.verbose >= 1 and "timestamp" in l: self.stdout.write("Rates last updated on %s" % (d.fromtimestamp( l["timestamp"]).strftime("%Y-%m-%d %H:%M:%S"))) if "base" in l: if self.verbose >= 1: self.stdout.write("All currencies based against %s" % (l["base"])) if not C._default_manager.filter(code=l["base"]): self.stderr.write( "Base currency %r does not exist! Rates will be erroneous without it." % l["base"]) else: base = C._default_manager.get(code=l["base"]) base.is_base = True base.last_updated = d.fromtimestamp(l["timestamp"]) base.save() exception_currencies = { # eg: NMP will be mapped to MXN 'NMP': 'MXN', 'BYR': 'BYN' } for c in C._default_manager.all(): if c.code in exception_currencies: mapped_currency = exception_currencies[c.code] factor = D(l["rates"][mapped_currency]).quantize(D(".000001")) elif c.code not in l[ "rates"] and c.code not in exception_currencies: self.stderr.write("Could not find rates for %s (%s)" % (c, c.code)) continue else: factor = D(l["rates"][c.code]).quantize(D(".000001")) if self.verbose >= 1: self.stdout.write("Updating %s rate to %f" % (c, factor)) C._default_manager.filter(pk=c.pk).update( factor=factor, last_updated=d.fromtimestamp(l["timestamp"]))
class ExchangeRatesPoller(object): API_key = '7cf21b8b9b8f4b7a887a5cde5ae85949' API_fetch_interval = timedelta(hours=1) def __init__(self): self.client = OpenExchangeRatesClient(ExchangeRatesPoller.API_key) self.currencies = self.client.currencies() logging.info( "ExchangeRatesPoller initialized.\nSupported currencies:\n" + "\n".join([c + ": " + self.currencies[c] for c in self.currencies ])) self.last_api_fetch_time = None def poll_data(self): if self.client is None or self.last_api_fetch_time is None \ or (datetime.utcnow() - self.last_api_fetch_time > ExchangeRatesPoller.API_fetch_interval): self.lastest = self.client.latest() self.rates = self.lastest['rates'] self.last_api_fetch_time = datetime.utcnow() logging.info(' '.join( [self.__class__.__name__, ": poll_data() fetched new data at:", self.last_api_fetch_time.isoformat()])) else: logging.info(' '.join([self.__class__.__name__, ( ": poll_data() called within fetch " "interval threshold, use previous " "fetched data at:"), self.last_api_fetch_time.isoformat()])) def trigger_notification(self, message): print message def check_exchange_rates(self, currencies): rates = {} for c in currencies: if c.upper() not in self.rates: logging.error(' '.join([self.__class__.__name__, ": currency:", c, "not found in self.rates dict."])) raise Exception("Currency: %s Not recognized!" % c) rates[c] = float(self.rates[c.upper()]) rates_str_lst = [ "USD exchange rate to " + rc.upper() + ": " + str(rates[rc]) for rc in rates ] rates_str = '\n'.join(rates_str_lst) logging.debug(' '.join([self.__class__.__name__, ": check_exchange_rates()\n", rates_str])) return rates_str_lst
class OpenExchangeRatesAdapter(BaseAdapter): """This adapter uses openexchangerates.org service to populate currency and exchange rate models. """ API_KEY_SETTINGS_KEY = 'OPENEXCHANGERATES_API_KEY' def __init__(self): self.client = OpenExchangeRatesClient( getattr(settings, self.API_KEY_SETTINGS_KEY)) def get_currencies(self): return self.client.currencies().items() def get_exchangerates(self, base): return self.client.latest(base)['rates'].items()
def __init__(self): self.client = OpenExchangeRatesClient(ExchangeRatesPoller.API_key) self.currencies = self.client.currencies() logging.info( "ExchangeRatesPoller initialized.\nSupported currencies:\n" + "\n".join([c + ": " + self.currencies[c] for c in self.currencies ])) self.last_api_fetch_time = None
class OpenExchangeRatesAdapter(BaseAdapter): """This adapter uses openexchangerates.org service to populate currency and exchange rate models. """ API_KEY_SETTINGS_KEY = 'OPENEXCHANGERATES_API_KEY' def __init__(self): self.client = OpenExchangeRatesClient( getattr(settings, self.API_KEY_SETTINGS_KEY)) def get_currencies(self): return self.client.currencies().items() def get_exchangerates(self, code): return self.client.latest(code)['rates'].items()
def get_currency_exchange_rates(): """ Obtain the current-ish exchange rates from OpenExchangeRates. """ from openexchangerates import OpenExchangeRatesClient api_key = app.config.get('OPENEXCHANGERATES_API_KEY', None) if api_key is None: return client = OpenExchangeRatesClient(api_key) # The base is USD, specifying another base results in an # access denied error. result = client.latest() return result['rates']
def handle(self, *args, **options): self.verbose = int(options.get('verbosity', 0)) self.options = options client = OpenExchangeRatesClient(APP_ID) if self.verbose >= 1: self.stdout.write("Querying database at %s" % (client.ENDPOINT_CURRENCIES)) try: code = C._default_manager.get(is_base=True).code except C.DoesNotExist: code = 'USD' # fallback to default l = client.latest(base=code) if self.verbose >= 1 and "timestamp" in l: self.stdout.write("Rates last updated on %s" % ( d.fromtimestamp(l["timestamp"]).strftime("%Y-%m-%d %H:%M:%S"))) if "base" in l: if self.verbose >= 1: self.stdout.write("All currencies based against %s" % (l["base"])) if not C._default_manager.filter(code=l["base"]): self.stderr.write( "Base currency %r does not exist! Rates will be erroneous without it." % l["base"]) else: base = C._default_manager.get(code=l["base"]) base.is_base = True base.save() for c in C._default_manager.all(): if c.code not in l["rates"]: self.stderr.write("Could not find rates for %s (%s)" % (c, c.code)) continue factor = D(l["rates"][c.code]).quantize(D(".0001")) if c.factor != factor: if self.verbose >= 1: self.stdout.write("Updating %s rate to %f" % (c, factor)) C._default_manager.filter(pk=c.pk).update(factor=factor)
class OpenExchangeRateConnector: def __init__(self, api_key): self.client = OpenExchangeRatesClient(api_key) def get_all_rates(self): currencies = self.client.currencies() latest = self.client.latest()['rates'] rates = [] for currency in currencies: short_name = currency if short_name not in settings.CURRENCY_FILTER: continue full_name = currencies[currency] exchange_rate = latest[currency] rates.append(ExchangeRateData(short_name=short_name, full_name=full_name, exchange_rate=exchange_rate)) return rates
def handle(self, *args, **options): self.verbose = int(options.get('verbosity', 0)) self.options = options self.force = self.options['force'] self.imports = [e for e in self.options['import'] if e] client = OpenExchangeRatesClient(APP_ID) if self.verbose >= 1: self.stdout.write("Querying database at %s" % (client.ENDPOINT_CURRENCIES)) symbols = {} with open(self.file_path) as df: symbols = json.load(df) currencies = client.currencies() for code in sorted(currencies.keys()): if (not self.imports) or code in self.imports: if not C._default_manager.filter(code=code) or self.force is True: if self.verbose >= 1: self.stdout.write("Creating %r (%s)" % (currencies[code], code)) c, created = C._default_manager.get_or_create(code=code) if created is True: C._default_manager.filter(pk=c.pk).update(name=currencies[code], is_active=False) if bool(c.symbol) and self.force is False: continue symbol = symbols.get(c.code) if symbol is not None: C._default_manager.filter(pk=c.pk).update(symbol=symbol) else: if self.verbose >= 1: self.stdout.write("Skipping %r (%s)" % (currencies[code], code))
from openexchangerates import OpenExchangeRatesClient #import kresna_email as em import datetime client = OpenExchangeRatesClient('f3aace9f692243aa909eda0e0c35bf32') s = client.latest() #for x in s: # print x x = s["rates"] def print_menu(): print "==================================" print "MONEY CONVERTER" print "==================================" print "Data retrieved at", (datetime.datetime.fromtimestamp( int(s["timestamp"]) ).strftime('%Y-%m-%d %H:%M:%S')) print "type 'P' to print menu" print "type 'USD' to convert USD to IDR" print "type 'SGD' to convert SGD to IDR" print "type 'EUR' to convert EUR to IDR" print "type 'Q' to quit" print "==================================" def USD(money): l = float(x["IDR"]) * money print "USD in IDR = Rp", l text = "USD in IDR = Rp", l em.simple_msg("*****@*****.**","Money Converter Report",text) def SGD(money):
def __init__(self): self.client = OpenExchangeRatesClient( getattr(settings, self.API_KEY_SETTINGS_KEY))
def __init__(self, api_key): self.client = OpenExchangeRatesClient(api_key)