def rate(): if not is_form_valid(request.args): flash("Make sure all fields are filled") return redirect("/") currency_from = request.args.get('from') currency_to = request.args.get('to') amount = float(request.args.get('amount')) codes = CurrencyCodes() if not is_code_valid(currency_from) or not is_code_valid(currency_to): flash_invalid_currencies(currency_from, currency_to) return redirect("/") print("party over here") result = run_conversion(currency_from, currency_to, amount) token = codes.get_symbol(currency_to) token_from = codes.get_symbol(currency_from) return render_template("/result.html", token=token, result=result, token_from=token_from, amount=amount)
def getConversionRate(fromcur, tocur, amount): c = CurrencyRates() codes = CurrencyCodes() converted = c.convert(fromcur, tocur, amount) fromSymbol = codes.get_symbol(fromcur) toSymbol = codes.get_symbol(tocur) conversion_result = "%s %0.2f = %s %0.2f" % (fromSymbol, amount, toSymbol, converted) return conversion_result
class TestCurrencySymbol(TestCase): """ test currency symbols from currency codes """ def setUp(self): self.c = CurrencyCodes() def test_with_valid_currency_code(self): self.assertEqual(str(self.c.get_symbol('USD')), 'US$') def test_with_invalid_currency_code(self): self.assertFalse(self.c.get_symbol('XYZ'))
class TestCurrencySymbol(TestCase): """ test currency symbols from currency codes """ def setUp(self): self.c = CurrencyCodes() def test_with_valid_currency_code(self): self.assertEqual(str(self.c.get_symbol('USD')), 'US$') def test_with_invalid_currency_code(self): self.assertFalse(self.c.get_symbol('XYZ'))
class Currency(): def __init__(self): self.c = CurrencyRates() self.currency_codes = self.c.get_rates('USD').keys() self.symbols = CurrencyCodes() def validate_code(self, start, end, amount): """Return entered currency code if the input is invalid""" start_err = False end_err = False amount_err = False if start.upper() not in self.currency_codes: start_err = True if end.upper() not in self.currency_codes: end_err = True try: Decimal(amount) except: amount_err = True return start_err, end_err, amount_err def calculate_currency(self, start, end, amount): """Calculate the currency and return the currency with its given symbol""" start = start.upper() end = end.upper() converted_amount = self.c.convert(start, end, Decimal(amount)) converted_amount = '%.2f' % converted_amount symbol = self.symbols.get_symbol(end) currency_name_start = self.symbols.get_currency_name(start) currency_name_end = self.symbols.get_currency_name(end) symbol_and_amount = symbol + " " + converted_amount return currency_name_start, symbol_and_amount, currency_name_end
def __get_currency_code_and_symbol(self, currency): """ Checks the currency code, then the symbol and returns the ode and the symbol :return: The currency code and currency symbol (if set, otherwise None) """ # Load the currency codes cc = CurrencyCodes() if cc.get_symbol(currency) is None: # Currency code (e.g. EUR) is not recognized if cc.get_currency_code_from_symbol(currency) is None: # Currency symbol (e.g. $) is not recognized print("Currency " + currency + " not recognized.") sys.exit(1) else: # Currency symbol recognized file_path = os.path.dirname(os.path.abspath(__file__)) with open(file_path + '/raw_data/currencies_symbols.json') as f: self.currencies_symbols = json.loads(f.read()) # Saves the list of codes for given symbol to variable codes_for_symbol = self.get_codes_for_symbol(currency) if codes_for_symbol is None: # The symbol is valid just for one currency # Returns the currency code and symbol return cc.get_currency_code_from_symbol(currency), currency else: # The symbol is valid for multiple currencies # Returns the first currency code from the list and the currency symbol return codes_for_symbol[0], currency # Returns currency code and no symbol (was not set) return currency, None
def currency_check(): source = [ 'GBP', 'HKD' 'IDR', 'ILS', 'DKK', 'INR', 'CHF', 'MXN', 'CZK', 'SGD', 'THB', 'THB', 'HRK', 'EUR', 'MYR', 'NOK', 'CNY', 'BGN', 'PHP', 'PLN', 'ZAR', 'CAD', 'ISK', 'BRL', 'RON', 'NZD', 'TRY', 'JPY', 'RUB', 'KRW', 'USD', 'AUD', 'HUF', 'SEK' ] origin = request.form['origin'].upper() travel = request.form['travel'].upper() amount = int(request.form['amount']) print(origin not in source) # print(origin) # print(type(origin)) if origin not in source: flash(f'{origin} input not valid') return redirect('/') elif travel not in source: flash(f'{travel} input not valid') return redirect('/') else: c = CurrencyRates() currency_change = c.get_rates(origin)[travel] currency_final = currency_change * amount c_code = CurrencyCodes() currency_code = c_code.get_symbol(travel) return render_template('currency.html', origin=origin, travel=travel, amount=amount, currency_code=currency_code, currency_final=currency_final)
def home(): """Default home route with conversion form""" form = CurrencyForm() if form.validate_on_submit(): session.clear() convert_from = form.convert_from.data.upper() convert_to = form.convert_to.data.upper() amount = form.amount.data cc = CurrencyCodes() for curr in (convert_from, convert_to): if not cc.get_currency_name(curr): flash(f'Incorrect currency code: {curr}', 'error') return redirect(url_for('home')) if amount < 1: flash('Not a valid amount', 'error') return redirect(url_for('home')) symbol = cc.get_symbol(convert_to) cr = CurrencyRates() session['symbol'] = symbol session[ 'amount'] = f"{cr.convert(convert_from, convert_to, amount):.2f}" return redirect(url_for('converted')) else: return render_template('home.html', form=form)
def currency_convertor(request): c = CurrencyRates() s = CurrencyCodes() currency_list = { 'USD', 'EUR', 'JPY', 'GBP', 'AUD', 'CAD', 'CHF', 'CNY', 'SEK', 'NZD', 'MXN', 'SGD', 'HKD', 'INR' } if request.method == "POST": trade_size1_3 = request.POST['trade_size1_3'] if trade_size1_3 is '': trade_size1_3 = 1 else: trade_size1_3 = float(trade_size1_3) cur_1 = request.POST['sel1_1'] cur_2 = request.POST['sel1_2'] if cur_2 == cur_1: cur_2 = 'INR' cur_1 = 'USD' symbol = s.get_symbol(cur_2) rate = c.get_rate(cur_1, cur_2) value = rate * trade_size1_3 one = 1 return render( request, 'currency_convertor.html', { 'currencyList': currency_list, 'value': value, 'symbol': symbol, 'from_currency': cur_1, 'to_currency': cur_2, 'rate': rate, 'one': one }) return render(request, 'currency_convertor.html', {'currencyList': currency_list})
def get_currency_symbol(currency_code): curr_codes = CurrencyCodes() symbol = curr_codes.get_symbol(currency_code) if symbol == None: return "" else: return symbol
def convert(): cr = CurrencyRates() cc = CurrencyCodes() from_currency = request.form["from_currency"].upper() to_currency = request.form["to_currency"].upper() valid_from_cn = cc.get_currency_name(from_currency) valid_to_cn = cc.get_currency_name(to_currency) symbol = cc.get_symbol(to_currency) try: amount = float(request.form["amount"]) except: amount = None try: result = cr.convert(from_currency, to_currency, amount) except: if valid_from_cn == None: flash(f"Currency unavailable: {from_currency}") # return render_template("/index.html") if valid_to_cn == None: flash(f"Currency unavailable: {to_currency}") # return render_template("/index.html") if amount == None: flash("Please enter valid amount.") # return render_template("/index.html") return render_template("/index.html") return render_template("/results.html", symbol=symbol, result=round(result,2), from_currency=from_currency, to_currency=to_currency)
def test_currency_symbol(self): """Test for currency_symbol() method in Currency class.""" init = 'USD' c2 = CurrencyCodes() c_symbol = c2.get_symbol(init) self.assertEqual(c_symbol, 'US$')
def main(): r = CurrencyRates() c = CurrencyCodes() transaction_amount = float(sys.argv[1]) base_currency = 'ZAR' quote_currency = 'ZAR' if len(sys.argv) >= 3: base_currency = sys.argv[2] if len(sys.argv) == 4: quote_currency = sys.argv[3] converted_amount = r.convert(base_currency, quote_currency, transaction_amount) fees = converted_amount * 0.02 print('Transaction Amount', c.get_symbol(quote_currency), '{:.2f}'.format(converted_amount)) print('Transaction Fees ', c.get_symbol(quote_currency), truncate(fees, 2))
def flash_conversion(firstCurr, secondCurr, amount): s = CurrencyCodes() c = CurrencyRates() symbol = s.get_symbol(secondCurr) result = c.convert(firstCurr, secondCurr, Decimal(amount)) formatted_result = "{:,.2f}".format(result) flash_message = f'{symbol} {formatted_result}' flash(flash_message, 'success')
def supported_currencies(self): currency_rates = CurrencyRates() # get all supported currencies from Forex codes = dict(currency_rates.get_rates('USD')) symbols = CurrencyCodes() codes['USD'] = '' # get symbols for supported currencies for code in codes.keys(): codes[code] = symbols.get_symbol(code) return codes
def convert_curr(curr1, curr2, amount): currencies = {'1':'USD', '2':'EUR', '3':'RUB'} symb = CurrencyCodes() c = CurrencyRates() result = round(c.convert(currencies[curr1], currencies[curr2], amount), 2) symb_curr1 = symb.get_symbol(currencies[curr1]) symb_curr2 = symb.get_symbol(currencies[curr2]) return "\t{} {} to {} is {} {}".format(amount, symb_curr1, currencies[curr2], result, symb_curr2)
def get_symbol(code): """ Get the symbol of currency code >>> get_symbol("USD") 'US$' >>> get_symbol("ABC") """ c = CurrencyCodes() return c.get_symbol(code)
def country_currency_code(lb_country): country_name = lb_country.strip() for currency, data in moneyed.CURRENCIES.iteritems(): if country_name.upper() in data.countries: symb = CurrencyCodes() symbol = symb.get_symbol(str(currency)) new_symbol = symbol if new_symbol == "None": return currency else: return symbol
def convert(amount_from, amount_to, amount): """ converts from USD to INR >>> convert('USD','INR',10) ₹ 725.06 """ currency = CurrencyRates() codes=CurrencyCodes() result = currency.convert(amount_from, amount_to, int(amount)) result = str(round(result, 2)) return codes.get_symbol(amount_to) + ' ' + result
def currency_code_and_symbol(self, code_or_symbol): if code_or_symbol.upper() in ('BTC', '₿'): return 'BTC', '₿' c = CurrencyCodes() code = c.get_currency_code_from_symbol(code_or_symbol) if code: return code, code_or_symbol code_or_symbol = code_or_symbol.upper() symbol = c.get_symbol(code_or_symbol) if symbol: return code_or_symbol, symbol return None
class Currency(): def __init__(self): self.cr = CurrencyRates() self.codes = CurrencyCodes() self.curr_codes = [ 'EUR', 'IDR', 'BGN', 'ILS', 'GBP', 'DKK', 'CAD', 'JPY', 'HUF', 'RON', 'MYR', 'SEK', 'SGD', 'HKD', 'AUD', 'CHF', 'KRW', 'CNY', 'TRY', 'HRK', 'NZD', 'THB', 'USD', 'NOK', 'RUB', 'INR', 'MXN', 'CZK', 'BRL', 'PLN', 'PHP', 'ZAR' ] self.results = {'frm': '', 'to': '', 'amount': ''} def check_valid_code(self, frm, to, amount): results = self.results if frm in self.curr_codes: results['frm'] = 'ok' else: results['frm'] = 'no' if to in self.curr_codes: results['to'] = 'ok' else: results['to'] = 'no' if amount == '': results['amount'] = 'no' else: results['amount'] = 'ok' return self.handle_results(results, frm, to, amount) def handle_results(self, results, frm, to, amount): if 'no' in results.values(): return self.give_error(results, frm, to) else: return self.conversion(frm, to, amount) def give_error(self, results, frm, to): if results['frm'] == 'no': flash(f'Not a valid code: {frm}') if results['to'] == 'no': flash(f'Not a valid code: {to}') if results['amount'] == 'no': flash('Not a valid amount.') return 'error' def conversion(self, frm, to, amount): x = self.codes.get_symbol(to) conv = self.cr.convert(frm, to, float(amount)) conv = round(conv, 2) conv = (f'{x}{conv}') return conv
def converter_forex_python(coin, amount, Cdict, dict_rate2): if amount <= 0: return 0 coin = coin.upper() try: if coin in Cdict.keys(): return amount / Cdict.get(coin) else: symbolDict = dict() symbol = CurrencyCodes() for key in Cdict.keys(): symbolDict[symbol.get_symbol(key)] = key return amount / Cdict.get(symbolDict.get(coin)) except: return converter_fixerio(coin, amount,dict_rate2)
def check_currency_code_and_transform_symbol(self, currency): '''Checks if the currency code is known and transforms symbol into currency code''' if not currency: return None c = CurrencyCodes() if currency in self.rates: return currency else: for code in self.rates: symbol = c.get_symbol(code) if symbol == currency: return code raise data_format_exceptions.CurrencyNotRecognized( 'Didn\'t recognize "' + currency + '" currency')
class Convert(): def __init__(self): self.c = CurrencyRates() self.code = CurrencyCodes() self.currency_list = self.c.get_rates('USD') def exchange(self, ch_from, ch_to, amount): """ converts the currency amount by the user specifed chang from currency to the specifes change to currency """ return "{:.2f}".format(self.c.convert(ch_from, ch_to, int(amount))) def all_true(self, ch_from, ch_to, amount): """ validates all index.html /convert from user inputs """ ch_from = self.check_valid_currency(ch_from) ch_to = self.check_valid_currency(ch_to) amount = self.check_valid_amount(amount) if ch_from and ch_to and amount: return True def get_currency_code(self, ch_to): """ gets the currency symbol based on the user specifed ch_to input """ code = self.code.get_symbol(ch_to) return code def check_valid_currency(self, curr): """ checks if user entered currency type is in the correct format""" if curr in self.currency_list: return True else: flash(f"{curr}: is not a valid currency format") def check_amount_data_type(self, amount): try: if isinstance(int(amount), int): return True except ValueError: flash(f"{amount}: is not a valid numerical value") def check_valid_amount(self, amount): if self.check_amount_data_type(amount): if int(amount) > 0: return True else: flash(f"{amount}: is not a possative numerical value")
def margin(request): c = CurrencyRates() s = CurrencyCodes() leverage = {1, 0.5} currency_list = { 'GBP', 'AUD', 'CAD', 'CHF', 'CNY', 'SEK', 'NZD', 'MXN', 'SGD', 'HKD', 'INR', 'USD', 'EUR', 'JPY' } if request.method == "POST": margin = 0 base_currency = request.POST['sel4_1'] counter_currency = request.POST['sel4_2'] account_currency = request.POST['sel4_3'] leverage = float(request.POST['sel4_4']) print leverage trade_size4_5 = request.POST['trade_size4_5'] if trade_size4_5 is '': trade_size4_5 = 10000 else: trade_size4_5 = float(trade_size4_5) if base_currency == account_currency: mp = 1.0 else: mp = c.get_rate(base_currency, account_currency) symbol = s.get_symbol(counter_currency) margin = (trade_size4_5 * leverage) * mp return render( request, 'margin.html', { 'symbol': symbol, 'currencyList': currency_list, 'margin': margin, 'base_currency': base_currency, 'counter_currency': counter_currency, 'account_currency': account_currency, 'mp': mp }) return render(request, 'margin.html', { 'currencyList': currency_list, 'leverage': leverage })
def current(): """Show current.html.""" rate_sel = request.form["rate"] c = CurrencyRates() x = c.get_rates(rate_sel) res2 = {item: "{0:.2f}".format(round(x[item], 2)) for item in x} cc = CurrencyCodes() name = cc.get_currency_name(rate_sel) symbol = cc.get_symbol(rate_sel) return render_template( "current.html", rates=session.get("rates"), bit=session.get("bit"), rates2=res2, selected=rate_sel, name=name, symbol=symbol, )
def update_currencies(currencies): print("Update currencies", file=sys.stderr) Currency = Model.get('currency.currency') codes = CurrencyCodes() records = [] for currency in _progress(pycountry.currencies): code = currency.alpha_3 if code in currencies: record = currencies[code] else: record = Currency(code=code) record.name = currency.name record.numeric_code = currency.numeric record.symbol = codes.get_symbol(currency.alpha_3) or currency.alpha_3 records.append(record) Currency.save(records) return {c.code: c for c in records}
def convert(): convert_to = request.form.get('convert-to') convert_from = request.form.get('convert-from') old_amount = request.form.get('amount', 0) try: #read about this and update amount = float('0' + old_amount) c = CurrencyRates(force_decimal=True) resultOne = c.convert(convert_from, convert_to, Decimal(amount)) resultTwo = round(resultOne, 2) cc = CurrencyCodes() symbol = cc.get_symbol(convert_to) return render_template('result.html', resultTwo=resultTwo, symbol=symbol) except: flash("please enter an integer") return render_template('/flash_homepage.html')
def base(): """Show base.html.""" c = CurrencyRates() x = c.get_rates("USD") res = {item: "{0:.2f}".format(round(x[item], 2)) for item in x} session["rates"] = res b = BtcConverter() bit = {} bit["bitcoin_usd"] = round(b.get_latest_price("USD"), 2) bit["bitcoin_eur"] = round(b.get_latest_price("EUR"), 2) bit["bitcoin_gbp"] = round(b.get_latest_price("GBP"), 2) cc = CurrencyCodes() bit["name_usd"] = cc.get_currency_name("USD") bit["name_eur"] = cc.get_currency_name("EUR") bit["name_gbp"] = cc.get_currency_name("GBP") bit["symbol"] = b.get_symbol() bit["symbol_eur"] = cc.get_symbol("EUR") bit["symbol_gbp"] = cc.get_symbol("GBP") session["bit"] = bit return render_template("base.html", rates=res, bit=bit)
def pip(request): c = CurrencyRates() s = CurrencyCodes() decimal = 0.0001 currency_list = { 'GBP', 'AUD', 'CAD', 'CHF', 'CNY', 'SEK', 'NZD', 'MXN', 'SGD', 'HKD', 'INR', 'USD', 'EUR', 'JPY' } if request.method == "POST": pip = 0 base_currency = request.POST['sel2_1'] counter_currency = request.POST['sel2_2'] account_currency = request.POST['sel2_3'] trade_size2_4 = request.POST['trade_size2_4'] if trade_size2_4 is '': trade_size2_4 = 10000 else: trade_size2_4 = float(trade_size2_4) if counter_currency == account_currency: mp = 1.0 else: mp = c.get_rate(account_currency, counter_currency) if (base_currency == 'JPY') or (counter_currency == 'JPY'): decimal = 0.01 symbol = s.get_symbol(counter_currency) pip = (decimal * trade_size2_4) / mp return render( request, 'pip.html', { 'symbol': symbol, 'currencyList': currency_list, 'pip': pip, 'base_currency': base_currency, 'counter_currency': counter_currency, 'account_currency': account_currency, 'mp': mp }) return render(request, 'pip.html', {'currencyList': currency_list})
def __check_format(self, value: str): from forex_python.converter import CurrencyCodes currency_codes = CurrencyCodes() value = value.upper() try: # First, think of input currency argument as symbol and try to find it in dictionary self.code = CURRENCY_SYMBOL_DICT[value] # When symbol found in dictionary, we already saved its code, so now just setup symbol member field self.symbol = value except KeyError: # When symbol not found in dictionary, input currency argument is rather code self.code = value # Now try to get its symbol self.symbol = currency_codes.get_symbol(self.code) if not self.symbol: # When it cannot find its symbol, it must be invalid raise ValueError(f'\'{value}\' is not valid currency name or symbol')