def test_conversion(): dict_rates = {'USD': 1.0, 'EUR': 0.94, 'GBP': 0.80} c = CurrencyConverter(dict_rates) assert c.convert(a, "USD") == Currency("5.00", "USD") assert c.convert(d, "EUR") == Currency(0.94, "EUR") assert c.convert(i, "USD") == Currency(1, "USD") assert c.convert(j, "USD") != Currency(1, "USD")
def index(request): c = CurrencyConverter() market = coinmarketcap.Market() coin = market.ticker('stellar') cena = coin[0]['price_usd'] market_cap = float(coin[0]['market_cap_usd']) x24h_volume = float(coin[0]['24h_volume_usd']) x1h_change = coin[0]['percent_change_1h'] x24h_change = coin[0]['percent_change_24h'] x7d_change = coin[0]['percent_change_7d'] price_btc = coin[0]['price_btc'] rank = coin[0]['rank'] market_cap = format(round(int(market_cap)), ',d') x24h_volume = format(round(int(x24h_volume)), ',d') cena_eur = c.convert(cena, 'USD', 'EUR') cena_eur = float("{0:.5f}".format(cena_eur)) cena_yen = c.convert(cena, 'USD', 'CNY') cena_yen = float("{0:.5f}".format(cena_yen)) up_green = "#2ECC40" down_red = "#FF4136" if float(x1h_change) < 0: change_1h = down_red elif float(x1h_change) > 0: change_1h = up_green if float(x24h_change) < 0: change_24h = down_red elif float(x24h_change) > 0: change_24h = up_green if float(x7d_change) < 0: change_7d = down_red elif float(x7d_change) > 0: change_7d = up_green return render( request, 'watcher/home.html', { "change_1h": change_1h, "change_24h": change_24h, "change_7d": change_7d, 'cena': cena, 'cena_eur': cena_eur, 'cena_yen': cena_yen, 'market_cap': market_cap, '24h_volume': x24h_volume, '1h_change': x1h_change, '24h_change': x24h_change, '7d_change': x7d_change, 'price_btc': price_btc, 'rank': rank, "x1h_change": x1h_change, "x24h_change": x24h_change, "x7d_change": x7d_change })
def test_raise_error_unknown(): converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = "GBP" with assert_raises(UnknownCurrencyCodeError): converter.convert(currency, convert_to_code)
def test_convert_with_unknown_code_raises_error(): # Arrange converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'FOO' with assert_raises(UnknownCurrencyCodeError): converter.convert(currency, convert_to_code)
def _format_currency_data(self, data, fiat): """ Formats the data fetched @param currency - the cryptocurrency to search for (i.e. 'bitcoin', 'ethereum') @param fiat - desired fiat currency (i.e. 'EUR', 'USD') @return - formatted currency data """ try: price = CurrencyConverter() isPositivePercent = True formatted_data = '' hour_trend = '' if float(data['percent_change_1h']) >= 0: hour_trend = '<:small_green_triangle:396586561413578752>' else: hour_trend = ':small_red_triangle_down:' isPositivePercent = False formatted_data += '__**#{}. {} ({})**__ {}\n'.format( data['rank'], data['name'], data['symbol'], hour_trend) if fiat is not "USD": converted_price = float( price.convert(float(data['price_usd']), 'USD', fiat)) converted_price = "{:,.6f}".format(converted_price).rstrip('0') if converted_price.endswith('.'): converted_price = converted_price.replace('.', '') if fiat in fiat_suffix: formatted_data += 'Price ({}): **{} {}**\n'.format( fiat, converted_price, fiat_currencies[fiat]) else: formatted_data += 'Price ({}): **{}{}**\n'.format( fiat, fiat_currencies[fiat], converted_price) formatted_data += 'Price (BTC): **{:,}**\n'.format( float(data['price_btc'])) if (data['market_cap_usd'] is None): formatted_data += 'Market Cap ({}): Unknown\n'.format(fiat) else: converted_price = float( price.convert(float(data['market_cap_usd']), 'USD', fiat)) formatted_data += 'Market Cap ({}): **${:,}**\n'.format( fiat, converted_price) if (data['available_supply'] is None): formatted_data += 'Available Supply: Unknown\n' else: formatted_data += 'Available Supply: **{:,}**\n'.format( float(data['available_supply'])) formatted_data += 'Percent Change (1H): **{}%**\n'.format( data['percent_change_1h']) formatted_data += 'Percent Change (24H): **{}%**\n'.format( data['percent_change_24h']) formatted_data += 'Percent Change (7D): **{}%**\n'.format( data['percent_change_7d']) return formatted_data, isPositivePercent except Exception as e: raise CoinMarketException("Failed to format data: {}".format(e))
def btcsgd(self): btc = self.getbtc() btcli = [] btc_buy_price = btc['bid'] btc_sell_price = btc['ask'] c = CurrencyConverter() converted_btc_buy_price = c.convert(float(btc_buy_price),'USD','SGD') converted_btc_sell_price = c.convert(float(btc_sell_price),'USD','SGD') btcli.append({"bbuysgd":converted_btc_buy_price}) btcli.append({"bsellsgd":converted_btc_sell_price}) return btcli
def ethsgd(self): eth = self.geteth() ethli = [] eth_buy_price = eth['bid'] eth_sell_price = eth['ask'] c = CurrencyConverter() converted_eth_buy_price = c.convert(float(eth_buy_price),'USD','SGD') converted_eth_sell_price = c.convert(float(eth_sell_price),'USD','SGD') ethli.append({"ebuysgd":converted_eth_buy_price}) ethli.append({"esellsgd":converted_eth_sell_price}) return ethli
def pip_value_cal(symbol, account_currency, price, position_size): if account_currency!=symbol[:3]: if symbol[3:]=='JPY': c = CurrencyConverter() return c.convert((0.01/price)*position_size, symbol[:3], account_currency) else: c = CurrencyConverter() return c.convert((0.0001/price)*position_size, symbol[:3], account_currency) else: if symbol[3:]=='JPY': return (0.01/price)*position_size else: return (0.0001/price)*position_size
def fillTable(bittrexApi, dataWallet): global totalBtcCmp table_content = [] totalInBtc = 0 totalInUSDT = 0 c = CurrencyConverter() try: btcPrice = bittrexApi.get_market_summary( "USDT-BTC")["result"][0]["Bid"] except: return None marketSummaries = getCoinsInfo( bittrexApi) # marketSummaries get all coins information if marketSummaries == None: return None for key, value in dataWallet.iteritems(): if isinstance(value[0], types.FloatType) or isinstance( value[0], types.IntType): try: coinInfo = getCoinInfo( key, marketSummaries) # coinInfo get specific coin information except: continue if coinInfo != None: totalCoinInBtc = (value[0] * coinInfo["Bid"]) totalUSDT = btcPrice * totalCoinInBtc totalInBtc += totalCoinInBtc totalInUSDT += totalUSDT if value[1] == 0: totalUSDT = "" totalCoinInBtc = "" elif value[1] < coinInfo["Bid"]: totalUSDT = totalUSDT totalCoinInBtc = totalCoinInBtc else: totalUSDT = totalUSDT totalCoinInBtc = totalCoinInBtc totalEUR = c.convert(totalUSDT, 'USD', 'EUR') table_content.append([ key, coinInfo["Bid"], coinInfo["Bid"] * btcPrice, value[0], value[1], totalCoinInBtc, totalUSDT, totalEUR, coinInfo["High"], coinInfo["Low"] ]) totalInEUR = c.convert(totalInUSDT, 'USD', 'EUR') table_content.append([ "Total", None, None, None, None, totalInBtc, totalInUSDT, totalInEUR, None, None ]) return table_content
def conversion(amount, input_currency, output_currency): """Converts amount of money to different currency Input: amount FLOAT input_currency STRING output_currency STRING Output: JSON { "input": { "amount": "100", "currency": "CZK" }, "output": { "USD": 22.38 } """ c = CurrencyConverter() input_currency = validate(input_currency) json_output = {} data_input_currency = {} data_output_currency = {} data_input_currency['amount'] = amount data_input_currency['currency'] = input_currency if output_currency == 'ALL': # change set to list and sort it ascending currencies = list(c.currencies) currencies.sort() for currency in currencies: try: converted_amount = round( c.convert(amount, input_currency, currency), 2) data_output_currency[currency] = converted_amount except: #if currency present exchange rate was not found, we ignore it to prevent failure pass else: output_currency = validate(output_currency) converted_amount = round( c.convert(amount, input_currency, output_currency), 2) data_output_currency[output_currency] = converted_amount json_output['input'] = data_input_currency json_output['output'] = data_output_currency return (json.dumps(json_output, indent=4))
def convert_t_curr_and_set(currency): global min_profit_n global max_profit_n if min_profit_n != 0.0: c = CurrencyConverter() min_profit_n = c.convert(min_profit_n, curr, currency) config.set('settings', 'min_profit_n', str(min_profit_n)) save_config() if max_profit_n != 0.0: c = CurrencyConverter() max_profit_n = c.convert(max_profit_n, curr, currency) config.set('settings', 'max_profit_n', str(max_profit_n)) save_config() set_currency(currency)
def test_result_print(self): str(eur1) self.assertEqual('1 EUR', str(eur1)) self.assertEqual('1.12 USD', str(usd1 + 0.12)) self.assertEqual('3 USD', str(usd1 + 2*usd1)) self.assertEqual('{:.2f} BGN or {:.2f} USD'.format( (bgn1+usd1).value, CurrencyConverter .convert((bgn1 + usd1).value, 'BGN', 'USD')), str(bgn1 + usd1)) self.assertEqual('{:.2f} EUR or {:.2f} USD or {:.2f} BGN'.format( (4 * (eur1 - usd1) + bgn1/2).value, CurrencyConverter.convert( (4 * (eur1 - usd1) + bgn1/2).value, 'EUR', 'USD' ), CurrencyConverter.convert((4*(eur1-usd1)+bgn1/2 ).value, 'EUR', 'BGN')), str(4*(eur1-usd1)+bgn1/2))
def Extract_Budget_UserReview(self, imdbID): c = CurrencyConverter() CurrencyDict = { '$': 'USD', '£': 'GBP', '¥': 'JPY', '€': 'EUR', '₹': 'INR' } url = 'http://www.imdb.com/title/{}/?ref_=fn_al_nm_1a'.format(imdbID) data = requests.get(url) soup = BeautifulSoup(data.text, 'html.parser') Budget = 0 userReview = "" #Extracting the user Review of the movie movie = soup.findAll('div', {'class': 'user-comments'}) for res in movie: userReview = res.span.strong.text if userReview is None: userReview = 'N/A' #Extracting the Budget of the movie for h4 in soup.find_all('h4'): if "Budget:" in h4: Budget = h4.next_sibling match = re.search(r'([\D]+)([\d,]+)', Budget) output = (match.group(1).replace('\xa0', ''), match.group(2).replace(',', '')) if len(output[0]) == 1: Budget = round( (c.convert(output[1], CurrencyDict[output[0]], 'USD') / 1000000), 2) elif len(output[0]) == 3 and output[0] == 'XAF': Budget = round((float(output[1]) * 0.00174637) / 1000000, 2) elif len(output[0]) == 3 and output[0] == 'FRF': Budget = round((float(output[1]) * 0.17) / 1000000, 2) elif len(output[0]) == 3 and output[0] == 'IRR': Budget = round((float(output[1]) * 0.0000237954) / 1000000, 2) elif len(output[0]) == 3 and output[0] == 'PKR': Budget = round((float(output[1]) * 0.007225614) / 1000000, 2) elif len(output[0]) == 3 and output[0] == 'NPR': Budget = round((float(output[1]) * 87.0521) / 1000000, 2) elif len(output[0]) == 3 and output[0] != 'FRF': Budget = round( c.convert(output[1], output[0], 'USD') / 1000000, 2) return Budget, userReview
def _format_coinmarket_stats(self, stats, fiat): """ Receives and formats coinmarket stats @param fiat - desired fiat currency (i.e. 'EUR', 'USD') @return - formatted stats """ try: c = CurrencyConverter() formatted_stats = '' if stats['data']['quote']['USD']['total_market_cap'] is None: formatted_stats += "Total Market Cap (USD): Unknown" else: converted_price = int( c.convert( float( stats['data']['quote']['USD']['total_market_cap']), 'USD', fiat)) if fiat in fiat_suffix: formatted_stats += "Total Market Cap ({}): **{:,} {}**\n".format( fiat, converted_price, fiat_currencies[fiat]) else: formatted_stats += "Total Market Cap ({}): **{}{:,}**\n".format( fiat, fiat_currencies[fiat], converted_price) if stats['data']['quote']['USD']['total_volume_24h'] is None: formatted_stats += "Total Volume 24h (USD): Unknown" else: converted_price = int( c.convert( float( stats['data']['quote']['USD']['total_volume_24h']), 'USD', fiat)) if fiat in fiat_suffix: formatted_stats += "Total Volume 24h ({}): **{:,} {}**\n".format( fiat, converted_price, fiat_currencies[fiat]) else: formatted_stats += "Total Volume 24h ({}): **{}{:,}**\n".format( fiat, fiat_currencies[fiat], converted_price) formatted_stats += "Bitcoin Dominance: **{}%**\n".format( stats['data']['btc_dominance']) formatted_stats += "Ethereum Dominance: **{}%**\n".format( stats['data']['eth_dominance']) formatted_stats += "Active Exchanges: **{:,}**\n".format( stats['data']['active_exchanges']) formatted_stats += "Active Currencies: **{:,}**\n".format( stats['data']['active_cryptocurrencies']) return formatted_stats except Exception as e: raise CoinMarketException("Failed to format data: `{}`".format(e))
def currency_trans(self): c = CurrencyConverter() old_currency_unit = self.stock_info['currency_unit'] new_currency = 'SGD' try: self.stock_info['natural_currency'] = old_currency_unit self.stock_info['natural_price'] = self.stock_info['discount_price'] self.stock_info['natural_discount_price'] = self.stock_info['discount_price'] new_price = c.convert(float(self.stock_info['price']), old_currency_unit, new_currency) new_discount = c.convert(float(self.stock_info['discount_price']), old_currency_unit, new_currency) self.stock_info['price'] = new_price self.stock_info['discount_price'] = new_discount self.stock_info['currency_unit'] = new_currency except: pass
def currency_converter(price, curr1="SEK", curr2="EUR"): """конвертер валют . Работает медленно""" c = CurrencyConverter() try: return c.convert(price, curr1, curr2) except ValueError or RateNotFoundError as err: return str(err)
def total_currency_converter(user, object, accounts, profile_currency, year=None, month=None, category=None): total_sum = 0 converter = CurrencyConverter() for account in accounts: if not year and not month: filtered_objects = object.objects.filter(user=user, account=account) elif not category: filtered_objects = object.objects.filter(user=user, account=account, created_date__year=year, created_date__month=month) else: filtered_objects = object.objects.filter(user=user, account=account, created_date__year=year, created_date__month=month, category=category) total_filtered_objects = assembly(filtered_objects) total_sum += converter.convert(total_filtered_objects, account.currency, profile_currency) return round(total_sum, 2)
def currency_conversion(cash_total): """Converts total cash injected into portfolio to USD Args: cash_total (dict): Keys = cash injection, Values = currency of cash injection Returns: sum_total_cash_in_usd [list]: total cash in USD """ c = CurrencyConverter() cash_currency = list(cash_total.values()) total_cash = list(cash_total.keys()) #* Else ensure that all inputted currencies are in uppercase cash_currency = [i.upper() for i in cash_currency] #* Converts all cash currency to USD sum_total_cash_in_usd = [] for i in range(len(cash_currency)): try: sum_total_cash_in_usd.append( c.convert(total_cash[i], cash_currency[i], "USD")) except ValueError as error: print(error) sum_total_cash_in_usd = [sum(sum_total_cash_in_usd)] print() return sum_total_cash_in_usd
def currency_converter(value, source, target): logging.debug('Currency converter started') source = source.upper() target = target.upper() result = 0.0 if hasattr(ssl, '_create_unverified_context'): logging.debug('SSL unverified context') ssl._create_default_https_context = ssl._create_unverified_context logging.debug('Value: {} - ' \ 'Source currency: {} - ' \ 'Target currency: {}'.format(value, source, target)) if (source not in 'VND' and target not in 'VND'): c = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') result = c.convert(value, source, target) else: url = 'https://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx' r = requests.get(url) if r.status_code == 200: root = ET.fromstring(r.content) for element in root: symbol = str(element.attrib.get('CurrencyCode')) if symbol in source: quote = float(element.attrib.get('Transfer')) result = value * quote if symbol in target: quote = float(element.attrib.get('Transfer')) result = value / quote else: logging.warning('Request time out.') return result
def position_size_stop_loss(self, position_type): try: ''' Lot Number of unit Standard 100,000 Mini 10,000 Micro 1,000 Nano 100 Position size = ((account value x risk per trade) / pips risked)/ pip value per standard lot Margin Requirement = Current Price × Units Traded × Margin ''' data=self.db.query_price_data(self.symbol, self.timeframe, self.atr_period*2) data['atr']=atr(list(data.bidclose), self.atr_period) last_atr=data.atr.iloc[-1] price=data.bidclose.iloc[-1] fxcm_info=self.get_account_info()[0] balance=fxcm_info[2] stop_loss, limit, stop_loss_pip, limit_pip=self.stop_loss_limit(price, last_atr, position_type) leverage=leverage_cal(self.symbol, balance) standard_lot_pip_value=pip_value_cal(self.symbol, self.account_currency, price, 100000) position_size=int(((((balance*self.risk_percent/100)/stop_loss_pip)/standard_lot_pip_value)*100)*1000) required_margin=int(price*position_size/leverage) c = CurrencyConverter() required_margin=int(c.convert(required_margin, self.symbol[:3], self.account_currency)) if self.symbol[3:]=='JPY': required_margin=required_margin/100 return position_size/1000, required_margin, stop_loss, limit, stop_loss_pip, limit_pip except Exception as e: print(e, 'position_size_stop_loss')
def __arithmetic_helper(cls, param1, param2, operation): ''' Is used by magic methods for arithmetical operations ''' # magic functions make sure param1 is always a Ccy object cls.__currencies_to_display.append(param1.currency) if isinstance(param2, Ccy): cls.__currencies_to_display.append(param2.currency) if param1.currency == param2.currency: result_value = operation(param1.value, param2.value) if operation is operator.truediv: cls.__currencies_to_display = [] return result_value return Ccy(result_value, param1.currency) else: value1 = param1.value value2 = CurrencyConverter.convert( param2.value, param2.currency, param1.currency) result_value = operation(value1, value2) if operation is operator.truediv: cls.__currencies_to_display = [] return result_value return Ccy(result_value, param1.currency) elif type(param2) in [float, int]: return Ccy(operation(param1.value, param2), param1.currency) else: try: return Ccy(operation(param1.value, float(param2)), param1.currency) except ValueError: raise ValueError('Args must be numbers or Ccy class objects')
def predict_wine_rating(): country = request.args.get('country', 'Spain') description = request.args.get('description', 'wine') # conversion rates - create a drop down with EUR and GBR conversion_factor = request.args.get('conversion', 'EUR') c = CurrencyConverter() price_raw = float(request.args.get('price', 0)) price = c.convert(price_raw, conversion_factor, 'USD') # province always has to be provided province = request.args.get('province', 'Other') # region defaults to Other in all cases region = 'Other' variety = request.args.get('variety', 'Other') year = request.args.get('year', '2019') winery = request.args.get('winery', 'Other') title = f"{winery} {year} {variety} ({province})" # dataframe has to be in this format df = pd.DataFrame( dict(country=[country], description=[description], price=[price], province=[province], region_1=[region], title=[title], variety=[variety], winery=[winery])) print('feature engineering') feat = joblib.load('model/feature_eng.joblib') print('model') model = joblib.load('model/model.joblib') feat_eng_x = feat.transform(df) prediction = model.predict(feat_eng_x) return {'prediction': str(prediction[0])}
def _format_coinmarket_stats(self, stats, fiat): """ Receives and formats coinmarket stats @param fiat - desired fiat currency (i.e. 'EUR', 'USD') @return - formatted stats """ try: c = CurrencyConverter() formatted_stats = '' if (stats['total_market_cap_usd'] is None): formatted_stats += "Total Market Cap (USD): Unknown" else: converted_price = int( c.convert(float(stats['total_market_cap_usd']), 'USD', fiat)) if fiat in fiat_suffix: formatted_stats += "Total Market Cap ({}): **{:,} {}**\n".format( fiat, converted_price, fiat_currencies[fiat]) else: formatted_stats += "Total Market Cap ({}): **{}{:,}**\n".format( fiat, fiat_currencies[fiat], converted_price) formatted_stats += "Bitcoin Percentage of Market: **{:,}%**\n".format( stats['bitcoin_percentage_of_market_cap']) formatted_stats += "Active Markets: **{:,}**\n".format( stats['active_markets']) formatted_stats += "Active Currencies: **{:,}**\n".format( stats['active_currencies']) formatted_stats += "Active Assets: **{:,}**\n".format( stats['active_assets']) return formatted_stats except Exception as e: raise CoinMarketException("Failed to format data: `{}`".format(e))
def send_invoice(user_id): user = User.get(user_id) violations = user.get_fines() title = 'Штрафы' if user.language_code == 'ru' else 'Fines' prices = [] description = '' currency = 'rub' if user.language_code == 'ru' else 'usd' converter = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') for violation in violations: label, datetime_native, fine = violation amount = int(converter.convert(fine, 'USD', 'RUB') * 100) if \ user.language_code == 'ru' else fine * 100 prices.append( LabeledPrice(label=f'{datetime_native} {label}', amount=amount)) description += f'{datetime_native} {label} ${fine}\n\n' bot.send_invoice( user_id, title=title, description=description, provider_token=provider_token, currency=currency, photo_url= 'https://safety4sea.com/wp-content/uploads/2016/06/fine-e1522744870402.png', photo_height=512, # !=0/None or picture won't be shown photo_width=512, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='fines-payment', invoice_payload='FINES PAYMENT')
def converter(self): c = CurrencyConverter() input_currency = self.ui.input_currency.text() output_currency = self.ui.output_currency.text() input_amount = int(self.ui.input_amount.text()) output_amount = round(c.convert(input_amount, '%s' % (input_currency), '%s' % (output_currency)), 2) self.ui.output_amount.setText(str(output_amount))
def format_price(self, price, fiat, symbol=True): """ Formats price under the desired fiat @param price - price to format @param fiat - desired fiat currency (i.e. 'EUR', 'USD') @param symbol - if True add currency symbol to fiat if False symbol will not be added @return - formatted price under fiat """ c = CurrencyConverter() ucase_fiat = fiat.upper() price = float(c.convert(float(price), "USD", fiat)) if symbol: if ucase_fiat in fiat_suffix: formatted_fiat = "{:,.6f} {}".format( float(price), fiat_currencies[ucase_fiat]) else: formatted_fiat = "{}{:,.6f}".format( fiat_currencies[ucase_fiat], float(price)) else: formatted_fiat = str(price) formatted_fiat = formatted_fiat.rstrip('0') if formatted_fiat.endswith('.'): formatted_fiat = formatted_fiat.replace('.', '') return formatted_fiat
def backtest(self, position_type, data, margin): try: ''' Lot Number of unit Standard 100,000 Mini 10,000 Micro 1,000 Nano 100 Position size = ((account value x risk per trade) / pips risked)/ pip value per standard lot Margin Requirement = Current Price × Units Traded × Margin ''' data['atr']=atr(list(data.bidclose), self.atr_period) last_atr=data.atr.iloc[-1] price=data.bidclose.iloc[-1] stop_loss, limit, stop_loss_pip, limit_pip=self.stop_loss_limit(price, last_atr, position_type) leverage=leverage_cal(self.symbol, margin) standard_lot_pip_value=pip_value_cal(self.symbol, self.account_currency, price, 100000) position_size=int(((((margin*self.risk_percent/100)/stop_loss_pip)/standard_lot_pip_value)*100)*1000) required_margin=int(price*position_size/leverage) c = CurrencyConverter() required_margin=int(c.convert(required_margin, self.symbol[:3], self.account_currency)) pip_value=pip_value_cal(self.symbol, self.account_currency, price, position_size) if self.symbol[3:]=='JPY': required_margin=required_margin/100 return position_size, required_margin, stop_loss, limit, stop_loss_pip, limit_pip, pip_value except Exception as e: print(e, 'backtest')
def _get_monthly_price(self, location, plan, size): """Translates a monthly cost value for a given adapter to a ServerSpec value.""" c = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') return c.convert(float(size.extra.get('monthly', 0) or 0), 'EUR', 'USD') or None
def test_currency_code_that_is_equal_to_passed_in(): converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'USD' result = converter.convert(currency, convert_to_code) assert result == Currency(1, 'USD')
def my_form_post(): c = CurrencyConverter() euros = request.form["euros"] usd = round(c.convert(euros, "EUR", "USD"), 2) return render_template("form.html", euros=euros, usd=usd)
def test_diff_currency_code_that_passed_in(): converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'JPY' result = converter.convert(currency, convert_to_code) assert result == Currency(106, 'JPY')
def play(difficulty): game_res = False c = CurrencyConverter() curr_rate = c.convert(1, 'USD', 'ILS') rnd_num = random.randint(MIN_NUM, MAX_NUM) print("---------- Amount -------------------------------") print("Amount = " + str(rnd_num) + "$") rnd_amount = round(curr_rate * rnd_num, 2) print(str(rnd_amount) + " ILS") # gwt interval intv = get_money_interval(difficulty, rnd_amount) # ---------------------------------------------------- if len(intv) == 2: while True: # get user guess guess = get_guess_from_user() # check value if float(guess) >= float(intv[0]) and float(guess) <= float( intv[1]): print("You Won! In Interval range...") game_res = True break else: print("Wrong Guess = " + str(guess) + " ... Try again ...") else: print("Unexpected Error....Try Later") # ---------------------------------------------------- return game_res
def convert_currency(convert_to): c = CurrencyConverter(decimal=True) base = 1 try: return c.convert(base, 'USD', convert_to) except: return base
def get_money_interval(difficulty_level): random_usd_amount = randint(1, 100) currency_converter = CurrencyConverter() t = currency_converter.convert(random_usd_amount, 'USD', 'ILS') d = difficulty_level generated_interval = t - (5 - d), t + (5 - d) return random_usd_amount, generated_interval
def test_convert_with_different_code_returns_converted_currency(): # Arrange converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'JPY' # Act result = converter.convert(currency, convert_to_code) # Assert assert result == Currency(120, 'JPY')
def test_convert(): rate_chart = CurrencyConverter({'USD': 1.0, 'EUR': .9, 'JPY': 106.18 }) amount1 = Currency('USD', 2) converted1 = rate_chart.convert(amount1, 'USD') amount2 = Currency('EUR', 1) converted2 = rate_chart.convert(amount2, 'EUR') amount3 = (2 * .9) # $2 to Euros converted3 = rate_chart.convert(Currency('USD', 2), 'EUR') amount4 = (400 * .0084) # ¥400 to Euros converted4 = rate_chart.convert(Currency('JPY', 400), 'EUR') assert converted1 == amount1 assert converted2 == amount2 assert converted3.value == amount3
def test_convert_with_same_code_returns_itself(): # Arrange converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'USD' # Act result = converter.convert(currency, convert_to_code) # Assert assert result == Currency(1, 'USD')
def test_convert_to_unknown_currency(): converter = CurrencyConverter({'USD': 1.0, 'EUR': 0.74}) converter.convert(Currency('USD', 1), 'XXX')
def test_convert_one_currency_to_another_non_usd(): currency1 = CurrencyConverter(4.0, 'EUR') new_code = 'JPY' assert CurrencyConverter.convert(currency1, new_code) == Currency(469.24557684341573, 'JPY')
def test_convert_one_cunnecy_code_to_same_currency_code(): currency = Currency(4.0, 'USD') new_code = 'USD' assert CurrencyConverter.convert(currency, new_code) == Currency(4.0, 'USD')
def test_convert_one_currency_to_another(): currency = CurrencyConverter(4.0, 'USD') new_code = 'EUR' assert CurrencyConverter.convert(currency, new_code) == Currency(3.611448, 'EUR')
def test_convert_to_same_currency(): converter = CurrencyConverter({'USD': 1.0, 'EUR': 0.74}) assert converter.convert(Currency('USD', 1), 'USD') == Currency('USD', 1)
def test_convert_to_different_currency_big_dict(): converter = CurrencyConverter(CURRENCY_CONVERSIONS) assert converter.convert(Currency('BBD', 2), 'GHS') == Currency('GHS', 3.969829297340214)
def test_convert_to_different_currency_small_dict(): converter = CurrencyConverter({'USD': 1.0, 'EUR': 0.74}) assert converter.convert(Currency('USD', 1), 'EUR') == Currency('EUR', 0.74)
def test_can_convert_currency_to_its_original_type(): currency_converter = CurrencyConverter({'USD' : 1, 'EUR' : 0.74}) assert currency_converter.convert(Currency(1,'USD'), 'USD') == Currency(1, 'USD')
def extract_Data_FromYahoo(YahooStockURL): try: webPage = urlopen(YahooStockURL) soup = BeautifulSoup(webPage, "html.parser") # HTML SPECIFIC CODE. NEEDS TO BE FIXED IF GOOGLE/YAHOO CHANGES HTML!!! #====================================================================== #Infer currency from URL (assumes all symbols ending in .L are quoted in GBP) CurrencyOnPage = "" YahooSymbol = dataSrc.get_YahooSymbolFromURL(YahooStockURL) if YahooSymbol != "": if ".L" in YahooSymbol: CurrencyOnPage = 'GBX' if ".AS" in YahooSymbol: CurrencyOnPage = 'EUR' #Get daily volume #Format to look for in HTML is: #<b data-sq="AAAP.L:volume" class="Fl-end Fw-b">75.0k</b> data_sq_val = YahooSymbol + ":volume" day_vol = soup.find('b', attrs={"data-sq": data_sq_val}) #Check if data was extracted/found #if ((len(day_vol) > 1) and ('-' not in str(day_vol))): if ((day_vol != None) and ("-" not in day_vol)): day_vol = day_vol.contents[0] #day_vol = day_vol.replace(',','').partition('/')[0] day_vol_Currency = CurrencyOnPage try: if (("m" in day_vol) or ("k" in day_vol)): if "m" in day_vol: day_vol = float(day_vol.replace("m",'') + "0") * 1000000.0 elif "k" in day_vol: day_vol = float(day_vol.replace("k",'')) * 1000.0 else: day_vol = float(day_vol) #Convert currency to EUR if not already in EUR if day_vol_Currency == 'GBP': c = CurrencyConverter() day_vol = c.convert(day_vol, day_vol_Currency, 'EUR') if day_vol_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP day_vol = day_vol / 100.0 #Convert to EUR day_vol = c.convert(day_vol, 'GBP', 'EUR') except Exception as e: day_vol = "Conversion Error with " + str(day_vol) + " " + str(e) else: day_vol = "No data." #====================================================================== #Get last price #Extract from (example): """ <td class="Ta-start Pstart-8 P-4 Pend-8"> <b class="C-darkGrey">Prev Close</b> <b class="Fl-end Fw-b">0.57</b> </td> """ Lprice = soup.find_all('b') try: Lprice = Lprice[3].contents[0] Lprice = Lprice.replace(',','') Lprice_Currency = CurrencyOnPage try: Lprice = float(Lprice) #Convert currency to EUR if not already in EUR if Lprice_Currency == 'GBP': c = CurrencyConverter() Lprice = c.convert(Lprice, Lprice_Currency, 'EUR') if Lprice_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP Lprice = Lprice / 100 #Convert to EUR Lprice = c.convert(Lprice, 'GBP', 'EUR') except: Lprice = "Conversion Error with " + str(Lprice) except: Lprice = "No data." #====================================================================== # calculate turnover. This is already in EUR try: turnOver = Lprice * day_vol except: turnOver = "No data." except Exception as e: print("Error retreiving Yahoo Finance webpage(s). Check connection. \n Try to change IP if problem persists. Error was: " + str(e)) day_vol = "Conn error." Lprice = "Conn error." turnOver = "Conn error." return [day_vol, Lprice, turnOver]
def extract_Data_FromGoogle(GoogleStockURL): try: webPage = urlopen(GoogleStockURL) soup = BeautifulSoup(webPage, "html.parser") # HTML SPECIFIC CODE. NEEDS TO BE FIXED IF GOOGLE/YAHOO CHANGES HTML!!! #====================================================================== #Infer currency from finance stock page #GBX = penny sterling unless price has * divStrings = soup.find_all('div') CurrencyOnPage = "" for div in soup.find_all('div'): try: divContent = div.text #print(str(divContent)) if "Currency in GBX" in divContent: CurrencyOnPage = 'GBX' if "Currency in EUR" in divContent: CurrencyOnPage = 'EUR' if "Currency in GBP" in divContent: CurrencyOnPage = 'GBP' except: pass #Get daily volume day_vol = soup.find_all('td', attrs={"class": "val"}) try: day_vol = day_vol[3].contents[0] day_vol = day_vol.replace(',','').partition('/')[0] day_vol_Currency = CurrencyOnPage #check currency #check if day_vol is in GBX or GBP if ((CurrencyOnPage == 'GBX') and ("*" in day_vol)): #this means day_vol is in GBP day_vol_Currency = 'GBP' day_vol = day_vol.replace('*','') try: if "M" in day_vol: day_vol = float(day_vol.replace('M','')) * 1000000 else: day_vol = float(day_vol) #Convert currency to EUR if not already in EUR if day_vol_Currency == 'GBP': c = CurrencyConverter() day_vol = c.convert(day_vol, day_vol_Currency, 'EUR') if day_vol_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP day_vol = day_vol / 100 #Convert to EUR day_vol = c.convert(day_vol, 'GBP', 'EUR') except: day_vol = "Conversion Error with " + str(day_vol) except: day_vol = "No data." #====================================================================== #Get last price Lprice = soup.find(attrs={"class": "pr"}) #print(str(Lprice)) try: Lprice = Lprice.contents[1].contents[0] Lprice = Lprice.replace(',','') Lprice_Currency = CurrencyOnPage #check currency #check if day_vol is in GBX or GBP if ((CurrencyOnPage == 'GBX') and ("*" in Lprice)): #this means day_vol is in GBP Lprice_Currency = 'GBP' Lprice = Lprice.replace('*','') try: Lprice = float(Lprice) #Convert currency to EUR if not already in EUR if Lprice_Currency == 'GBP': c = CurrencyConverter() Lprice = c.convert(Lprice, Lprice_Currency, 'EUR') if Lprice_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP Lprice = Lprice / 100 #Convert to EUR Lprice = c.convert(Lprice, 'GBP', 'EUR') except: Lprice = "Conversion Error with " + str(Lprice) except: Lprice = "No data." #====================================================================== # calculate turnover. This is in EUR try: turnOver = Lprice * day_vol except: turnOver = "No data." except Exception as e: print("Error retreiving Google Finance webpage(s). Check connection. \n Try to change IP if problem persists. Error was: " + str(e)) day_vol = "Conn error." Lprice = "Conn error." turnOver = "Conn error." return [day_vol, Lprice, turnOver]
def test_can_convert_currency_to_any_type_in_instance_of_CurrencyConverter(): currency_converter = CurrencyConverter({'USD' : 1, 'EUR' : 0.74}) assert currency_converter.convert(Currency(10,'USD'), 'EUR') == Currency(7.4, 'EUR')