Exemplo n.º 1
0
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
Exemplo n.º 2
0
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 __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
Exemplo n.º 4
0
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 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$')
Exemplo n.º 6
0
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 get_currency_symbol(currency_code):
    curr_codes = CurrencyCodes()
    symbol = curr_codes.get_symbol(currency_code)
    if symbol == None:
        return ""
    else:
        return symbol
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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})
Exemplo n.º 10
0
def check_currency_code(currency_code):
    c = CurrencyCodes()

    if c.get_currency_name(currency_code) is None:
        return False

    return True
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
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 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
Exemplo n.º 14
0
 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': ''}
Exemplo n.º 15
0
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')
Exemplo n.º 16
0
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 __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()
Exemplo n.º 18
0
def get_symbol(code):
    """
    Get the symbol of currency code
        >>> get_symbol("USD") 
        'US$'

        >>> get_symbol("ABC")
        
    """
    c = CurrencyCodes()
    return c.get_symbol(code)
Exemplo n.º 19
0
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
Exemplo n.º 20
0
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'))
Exemplo n.º 21
0
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'))
Exemplo n.º 22
0
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
Exemplo n.º 23
0
 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
Exemplo n.º 24
0
class TestCurrencyName(TestCase):
    """
    test currency name from currency codes
    """
    def setUp(self):
        self.c = CurrencyCodes()

    def test_with_valid_currency_code(self):
        self.assertEqual(str(self.c.get_currency_name('USD')), 'United States dollar')

    def test_with_invalid_currency_code(self):
        self.assertFalse(self.c.get_currency_name('XYZ'))
Exemplo n.º 25
0
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}"
    )
Exemplo n.º 26
0
class TestCurrencyName(TestCase):
    """
    test currency name from currency codes
    """
    def setUp(self):
        self.c = CurrencyCodes()

    def test_with_valid_currency_code(self):
        self.assertEqual(str(self.c.get_currency_name('USD')),
                         'United States dollar')

    def test_with_invalid_currency_code(self):
        self.assertFalse(self.c.get_currency_name('XYZ'))
def curr_codes():
    cn = CurrencyCodes()

    from_curr = entry1.get()  #Currency to be converted
    to_curr = entry2.get()  #Currency to be converted In

    new_code = cn.get_currency_name(from_curr)
    new_code1 = cn.get_currency_name(to_curr)

    final_codes.delete(0, tk.END)

    final_codes.insert(0, str(new_code))
    final_codes.insert(20, str(" to "))
    final_codes.insert(25, str(new_code1))
    final_codes.insert(45, str(" Conversion."))
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
    def __init__(self):
        self.currency_rates_last_update = time.time()
        self.currency_rates = self._get_all_currency_rates()
        self.currency_codes = CurrencyCodes()
        self.currency_shortcuts_to_symbols = {}
        self.request_currency_shortcuts_and_symbols()

        self.currency_symbols = [
            currency_symbol
            for currency_symbol in self.currency_shortcuts_to_symbols.values()
        ]

        self.currency_shortcuts = [
            currency_shortcut
            for currency_shortcut in self.currency_shortcuts_to_symbols.keys()
        ]
Exemplo n.º 30
0
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!")
Exemplo n.º 31
0
def validate_ticker(ctx, param, value):
    try:
        if re.fullmatch(r"^[A-Z]{3}$",
                        value):  # Проверяем соответствует ли тикер формату
            c = CurrencyCodes()
            if c.get_currency_name(
                    value):  # Если можем получить название по тикеру
                return value  # то выходим, иначе бросаем эксепшн
            else:
                raise BadParameter('такого тикера нет')
        else:
            raise BadParameter('тикер не соответствует формату ААА')
    except BadParameter as error:  # В случае ошибки
        click.echo(f'Ошибка: {error}')  # выводим ее
        value = click.prompt(param.prompt)  # и делаем магию с колбэками
        return validate_ticker(ctx, param, value)  # которую возвращаем обратно
    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')
Exemplo n.º 33
0
 def setUp(self):
     self.c = CurrencyCodes()
Exemplo n.º 34
0
import xml.etree.ElementTree as ET
from decimal import *
import collections
from sopel.module import commands, example, NOLIMIT
from sortedcontainers import SortedDict
from forex_python.converter import CurrencyCodes
from forex_python.converter import CurrencyRates
from forex_python.bitcoin import BtcConverter
from pymarketcap import Pymarketcap
from coinmarketcap import Market
import coinmarketcap
c = CurrencyRates()
b=BtcConverter()
m=Market()
cc=CurrencyCodes()
allcoins={}
curlist=list(c.get_rates("USD").keys())
#print(c.get_rates("USD"))
curlist.append("USD")
curlist.sort()
for cur in curlist:
    allcoins[cur]=cc.get_currency_name(cur)
altcoinmap={}
#print (coinmarketcap.price("BTC"))
json=m.ticker(convert='EUR')
#print(json)
for currency in json:
    altcoinmap[currency["symbol"]]=currency["id"]
    allcoins[currency["symbol"]]=currency["name"]
#print(altcoinmap)
#print(json)