Loads the exchange rates and recalculates stock holding values into 
        base currency
169788
def recalculate_stock_values_into_base(self):
        
        from .currency import CurrencyConverter

        conv = CurrencyConverter()
        cash = self.model.get_cash_asset_class()

        for stock in self.model.stocks:
            if stock.currency != self.base_currency:
                # Recalculate into base currency
                conv.load_currency(stock.currency)
                assert isinstance(stock.value, Decimal)
                val_base = stock.value * conv.rate.value
            else:
                # Already in base currency.
                val_base = stock.value

            stock.value_in_base_currency = val_base
390224
def get_rate(self, currency, date):
        
        if str(currency) == defaults.INTERNAL_CURRENCY:
            return Decimal(1)

        cached = cache.get(_cache_key(currency, date))
        if cached:
            return Decimal(cached)
        else:
            # Expect self._get_rate() to implement caching
            return Decimal(self._get_rate(currency, date))
661859
def convert_currency(amount, from_currency, to_currency):
    '''
    

    '''
    try:
        rate = CurrencyRate.objects.get(
            from_currency__iso_code=from_currency,
            to_currency__iso_code=to_currency)
    except CurrencyRate.DoesNotExist:
        return _('n/a')
    try:
        history = rate.history.all()[0]
    except IndexError:
        return _('n/a')
    return amount * history.value
222045
public function getExchangeRate()
    {
        try {
            $currentCurrency = $this->storeManager->getStore()->getCurrentCurrency()->getCode();
            $baseCurrency = $this->storeManager->getStore()->getBaseCurrency()->getCode();
            return (float)$this->currencyFactory->create()->load($baseCurrency)->getAnyRate($currentCurrency);
        } catch (\Exception $e) {
            throw $e;
        }
    }
617676
def loads(cls, s: str) -> 'Money':
        """"""
        try:
            currency, amount = s.strip().split()
            return cls(amount, currency)
        except ValueError as err:
            raise ValueError("failed to parse string "
                             " '{}': {}".format(s, err))
1227322
def currency(s=''):
    ''
    if isinstance(s, str):
        s = ''.join(ch for ch in s if ch in floatchars)
    return float(s) if s else TypedWrapper(float, None)
1224321
private function calculateProductsPriceByPercent(float $spread_value, $stock_price, $currency)
    {
        $calculatedPriceByCurrencyRate =  $this->getCalculatedPriceByCurrencyRate($stock_price, $currency);

        return $calculatedPriceByCurrencyRate +  ( $calculatedPriceByCurrencyRate * $spread_value / 100);
    }
104816
def __store_cash_balances_per_currency(self, cash_balances):
        
        cash = self.model.get_cash_asset_class()

        for cur_symbol in cash_balances:
            item = CashBalance(cur_symbol)
            item.parent = cash
            
            quantity = cash_balances[cur_symbol]["total"]
            item.value = Decimal(quantity)
            item.currency = cur_symbol

            # self.logger.debug(f"adding {item}")
            cash.stocks.append(item)
            self.model.stocks.append(item)
603103
def convert_currency(self, base_fiat, base_amount, target_fiat):
        
        url = "http://api.fixer.io/latest?base=%s" % base_fiat
        data = self.get_url(url).json()
        try:
            return data['rates'][target_fiat.upper()] * base_amount
        except KeyError:
            raise Exception("Can not convert %s to %s" % (base_fiat, target_fiat))
97231
public function load($sourceCurrencyCode, $destinationCurrencyCode)
    {
        $rate = null;

        $exchangeRates = $this->loadAll();

        if (isset($exchangeRates[$sourceCurrencyCode][$destinationCurrencyCode])) {
            $rate = $exchangeRates[$sourceCurrencyCode][$destinationCurrencyCode];
        } // Conversion rates are two-way. If a reverse rate is unavailable, set it.
        elseif (isset($exchangeRates[$destinationCurrencyCode][$sourceCurrencyCode])) {
            $rate = bcdiv(1,
              $exchangeRates[$destinationCurrencyCode][$sourceCurrencyCode],
              6);
        }

        if ($rate) {
            return new ExchangeRate($sourceCurrencyCode,
              $destinationCurrencyCode, $rate);
        }

        return null;
    }
891498
function updatePrices()
    {
        $productCollection = $this->attribute( 'productcollection' );
        if ( $productCollection )
        {
            $currencyCode = '';
            $items = $this->items();

            $db = eZDB::instance();
            $db->begin();
            foreach( $items as $itemArray )
            {
                $item = $itemArray['item_object'];
                $productContentObject = $item->attribute( 'contentobject' );
                $priceObj = null;
                $price = 0.0;
                $attributes = $productContentObject->contentObjectAttributes();
                foreach ( $attributes as $attribute )
                {
                    $dataType = $attribute->dataType();
                    if ( eZShopFunctions::isProductDatatype( $dataType->isA() ) )
                    {
                        $priceObj = $attribute->content();
                        $price += $priceObj->attribute( 'price' );
                        break;
                    }
                }
                if ( !is_object( $priceObj ) )
                    break;

                $currency = $priceObj->attribute( 'currency' );
                $optionsPrice = $item->calculatePriceWithOptions( $currency );

                $price += $optionsPrice;
                $item->setAttribute( "price", $price );
                if ( $priceObj->attribute( 'is_vat_included' ) )
                {
                    $item->setAttribute( "is_vat_inc", '1' );
                }
                else
                {
                    $item->setAttribute( "is_vat_inc", '0' );
                }
                $item->setAttribute( "vat_value", $priceObj->VATPercent( $productContentObject ) );
                $item->setAttribute( "discount", $priceObj->attribute( 'discount_percent' ) );
                $item->store();

                $currencyCode = $priceObj->attribute( 'currency' );
            }

            $productCollection->setAttribute( 'currency_code', $currencyCode );
            $productCollection->store();
            $db->commit();

            // update prices that are related to shipping values.
            eZShippingManager::updateShippingInfo( $productCollection->attribute( 'id' ) );
        }
    }
926886
public static void reinitializeCurrencySettings ()
  {
    s_aRWLock.writeLocked ( () -> {
      s_aSettingsMap.clear ();
      for (final ECurrency e : ECurrency.values ())
      {
        s_aSettingsMap.put (e, new PerCurrencySettings (e));

        for (final Locale aLocale : e.matchingLocales ())
          if (!localeSupportsCurrencyRetrieval (aLocale))
            throw new IllegalArgumentException ("Passed locale " + aLocale + " does not support currency retrieval!");
      }
    });
  }
1049986
def base_convert_money(amount, currency_from, currency_to):
    
    source = get_rate_source()

    # Get rate for currency_from.
    if source.base_currency != currency_from:
        rate_from = get_rate(currency_from)
    else:
        # If currency from is the same as base currency its rate is 1.
        rate_from = Decimal(1)

    # Get rate for currency_to.
    rate_to = get_rate(currency_to)

    if isinstance(amount, float):
        amount = Decimal(amount).quantize(Decimal('.000001'))

    # After finishing the operation, quantize down final amount to two points.
    return ((amount / rate_from) * rate_to).quantize(Decimal("1.00"))
165315
private function retrieveExchangeRateFor(Currency $currency): void
    {
        $conversion = sprintf('%s_%s', $this->baseCurrency->getCode(), $currency->getCode());

        $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/api/v6/convert', [
            'query' => ['q' => $conversion]
        ]);

        $data = json_decode($response->getBody(), true);

        if (! array_key_exists($conversion, $data['results'])) {
            throw CurrencyConverterApiException::currencyNotFound($currency->getCode());
        }

        $this->exchangeRates[$currency->getCode()] = (float) $data['results'][$conversion]['val'];
    }
76680
def get_rate(currency):
    """"""
    source = get_rate_source()
    try:
        return Rate.objects.get(source=source, currency=currency).value
    except Rate.DoesNotExist:
        raise CurrencyConversionException(
            "Rate for %s in %s do not exists. "
            "Please run python manage.py update_rates" % (
                currency, source.name))
587152
def import_fx_rates(self, rates: List[PriceModel]):
        
        have_new_rates = False

        base_currency = self.get_default_currency()

        for rate in rates:
            assert isinstance(rate, PriceModel)

            currency = self.get_by_symbol(rate.symbol)
            amount = rate.value

            # Do not import duplicate prices.
            # todo: if the price differs, update it!
            # exists_query = exists(rates_query)
            has_rate = currency.prices.filter(Price.date == rate.datetime.date()).first()
            # has_rate = (
            #     self.book.session.query(Price)
            #     .filter(Price.date == rate.date.date())
            #     .filter(Price.currency == currency)
            # )
            if not has_rate:
                log(INFO, "Creating entry for %s, %s, %s, %s",
                    base_currency.mnemonic, currency.mnemonic, rate.datetime.date(), amount)
                # Save the price in the exchange currency, not the default.
                # Invert the rate in that case.
                inverted_rate = 1 / amount
                inverted_rate = inverted_rate.quantize(Decimal('.00000000'))

                price = Price(commodity=currency,
                              currency=base_currency,
                              date=rate.datetime.date(),
                              value=str(inverted_rate))
                have_new_rates = True

        # Save the book after the prices have been created.
        if have_new_rates:
            log(INFO, "Saving new prices...")
            self.book.flush()
            self.book.save()
        else:
            log(INFO, "No prices imported.")
1014989
def get_bulkcurrencies(self):
        
        start = r'YAHOO\.Finance\.CurrencyConverter\.addCurrencies\('
        _json = r'\[[^\]]*\]'
        try:
            resp = get(self.currencies_url)
            resp.raise_for_status()
        except exceptions.RequestException as e:
            self.log(logging.ERROR, "%s Deprecated: API withdrawn in February 2018:\n%s", self.name, e)
        else:
            # Find the javascript that contains the json object
            soup = BS4(resp.text, 'html.parser')
            re_start = re.compile(start)
            try:
                jscript = soup.find('script', type='text/javascript', text=re_start).string
            except AttributeError:
                self.log(logging.WARNING, "%s: Live currency data not found, using cached copy.", self.name)
            else:
                # Separate the json object
                re_json = re.compile(_json)
                match = re_json.search(jscript)
                if match:
                    json_str = match.group(0)
                    with open(self._cached_currency_file, 'w') as fd:
                        fd.write(json_str.encode('utf-8'))

        # Parse the json file
        try:
            with open(self._cached_currency_file, 'r') as fd:
                j = json.load(fd)
        except FileNotFoundError:
            j = None
        if not j:
            raise RuntimeError("%s: JSON not found at endpoint or as cached file:\n%s" % (
                self.name, self._cached_currency_file))
        return j