def form_handler(): fromCurr = request.form.get('fromCurr') toCurr = request.form.get('toCurr') amt = request.form.get('amt') to_curr_symbol = CurrencyCodes().get_symbol(toCurr) from_curr_symbol = CurrencyCodes().get_symbol(fromCurr) resAmt = converter(fromCurr, toCurr, amt) return render_template( 'index.html', currency=currencys, result= f"You could get {to_curr_symbol}{resAmt} {toCurr} with {from_curr_symbol}{amt} {fromCurr}" )
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 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 prepare_currency_data(): """ Prepare currency data for showing in the dropdown list by following steps: 1. Call get_rates() by USD, the output will be dictionary 2. Collect all keys into currency_list 3. Collect currency name by using keys in currency_list 4. return result :return currency list as dictionary """ # declare a returned parameter curr_list = {} # Prepare data: step 1 cr = CurrencyRates() exchange_rate = cr.get_rates('USD') # Prepare data: step 2 currency_code = list(exchange_rate.keys()) currency_code.append("USD") # Prepare data: step 3 cc = CurrencyCodes() for code in currency_code: curr_list[str(code)] = code + " - " + cc.get_currency_name(str(code)) # Prepare data: step 4 return curr_list
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 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 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 get_currency_symbol(currency_code): curr_codes = CurrencyCodes() symbol = curr_codes.get_symbol(currency_code) if symbol == None: return "" else: return symbol
def setup(self): tw = TransferWise() self.set_profile_id() rate = self.quote_rate(self.source_currency, self.target_currency) print( f"Current Exchange Rate: 1 {self.target_currency} = \033[1;32;40m{rate} {self.source_currency}\033[0;37;40m" ) c = CurrencyCodes() threshold = float( input( f"\nTransfer money when 1 {self.target_currency} drops below {c.get_symbol(self.source_currency)} " )) self.set_threshold(format(threshold, ".5f")) amount = float( input( f"How much {self.source_currency} you want to send? (without commas, e.g. 12000) " )) self.set_amount(amount) print( "\nWe have Upper and Lower Bounds to GUARANTEE that you get the best Exchange Rate possible.\nOnce a new threshold is reached, we create a new transfer and cancel your previous one to refresh it" ) self.set_recipient()
def __init__(self, name, interval, amount, currency='NGN', plan_code=None, id=None, send_sms=None, send_invoices=None, description=None): super().__init__() #Check if currency supplied is valid if not CurrencyCodes().get_symbol(currency.upper()): raise ValueError("Invalid currency supplied") if interval.lower() not in self.__interval_values: raise ValueError("Interval should be one of 'hourly'," "'daily', 'weekly', 'monthly','annually'") try: amount = int(amount) except ValueError: raise ValueError("Invalid amount") else: self.interval = interval.lower() self.name = name self.interval = interval self.amount = amount self.currency = currency self.plan_code = plan_code self.id = id self.send_sms = send_sms self.send_invoices = send_invoices self.description = description
def test_currency_name(self): """Test for currency_name() method in Currency class.""" init = 'USD' curr = Currency(init) c2 = CurrencyCodes() self.assertEqual(curr.currency_name, 'United States dollar')
class MoneyRates(): c = CurrencyRates() cc = CurrencyCodes() dates = [] def make_money_list(self, start_date): # Get names of the money valute = self.c.get_rates('USD', start_date) valuteNames = valute.copy() # Make clear dict with keys is list for key in valute: valuteNames[key] = self.cc.get_currency_name(key) valute[key] = [] return valute, valuteNames def find_all_rates(self, start_date, end_date, valute, step): # Fill course_all_time data dates = [] while start_date <= end_date: dates.append(start_date) #.strftime('%d.%m.%Y')) course = self.c.get_rates('USD', start_date) for key in valute: try: valute.get(key).append(course.get(key)) except AttributeError: valute.get(key).append(0) start_date += step return valute, dates
async def to_currency(self, ctx): args = ctx.message.content.split(" ") if len(args) < 4: await ctx.send( "Please provide all necessary arguments. !currency <from> <to> <$amount>" ) return # Takes in args like USD, SGD, CAD, EUR currency_from = args[1].upper() currency_to = args[2].upper() try: amount = Decimal(args[3]) except Exception as e: print(e) await ctx.send("Please provide a valid amount.") return c = CurrencyRates() s = CurrencyCodes() try: converted_amount = round( c.convert(currency_from, currency_to, amount), 2) except Exception as e: print(e) await ctx.send( "Please provide a valid currency code (I.E. USD, SGD, CAD)") return await ctx.send( f"{currency_from} to {currency_to}: {s.get_symbol(currency_to)}{converted_amount}" )
def convert(): c = CurrencyRates() con_from = request.form["convert-from"] con_to = request.form["convert-to"] err_flashes = 0 try: c.get_rates(con_from) except: flash(f"{con_from} is not a valid currency.", "error") err_flashes = err_flashes + 1 try: c.get_rates(con_to) except: flash(f"{con_to} is not a valid currency.", "error") err_flashes = err_flashes + 1 try: float(request.form["amount"]) except: flash("Invalid amount entered.", "error") err_flashes = err_flashes + 1 if err_flashes > 0: return redirect(url_for("home")) sym = CurrencyCodes().get_symbol(request.form["convert-to"]) amt = round(c.convert(con_from, con_to, float(request.form["amount"])), 2) flash(f"{sym}{amt}", "conversion") return redirect(url_for("home"))
def main(): print("*" * 60) print("Welcome to Currency Converter") CRate, CCode = CurrencyRates(), CurrencyCodes() k = 1 while input("Continue? (Y/N): ").upper() == 'Y': print("=" * 25 + " Round " + str(k) + ' ' + "=" * 25) # Input amount = input("Enter the amount you wish to convert: ") base = input("Input the base currency: ").upper() target = input("Input the target currency: ").upper() try: result = CRate.convert(base, target, float(amount)) print("{} {}({}) is {} {}({})".format(amount, base, CCode.get_symbol(base), round(result, 2), target, CCode.get_symbol(target))) except RatesNotAvailableError: print( 'The base or target currency are not supported, please refer to ' 'https://forex-python.readthedocs.io/en/latest/currencysource.html' ) except ValueError: print('Please enter correct amount! Only number!') print("=" * 60, '\n') k += 1 print("*" * 60) print("Thanks for your support! Welcome come to use next time!")
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 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 check_currency_code(currency_code): c = CurrencyCodes() if c.get_currency_name(currency_code) is None: return False return True
def get_result(convert_from, convert_to, amount): amount = float(amount) rates = CurrencyRates(force_decimal=True) result_amount = rates.convert(convert_from, convert_to, Decimal(amount)) symbol = CurrencyCodes().get_symbol(convert_to) return f'{symbol} {result_amount:.2f}'
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
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 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 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 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 __init__(self, convert_from, convert_to, amount): """This method Converts from one currency to another given the amount""" self.convert_from = convert_from.upper() self.convert_to = convert_to.upper() self.amount = amount self.supported_currency_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.c = CurrencyRates() self.cc = CurrencyCodes()
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
def convert(amount, base, target): CRate, CCode = CurrencyRates(), CurrencyCodes() try: result = CRate.convert(base, target, float(amount)) return "{} {}({}) is {} {}({})".format(amount, base, CCode.get_symbol(base), round(result, 2), target, CCode.get_symbol(target)) except RatesNotAvailableError: return 'The base or target currency are not supported, please refer to '\ 'https://forex-python.readthedocs.io/en/latest/currencysource.html' except ValueError: return 'Please enter correct amount! Only number!'