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 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)
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'))
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."))
def check_currency_code(currency_code): c = CurrencyCodes() if c.get_currency_name(currency_code) is None: return False return True
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 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 convert(): """Show index.html.""" c = CurrencyRates() amount = request.form.get('amount') rate_from = request.form.get('rate-from') rate_too = request.form.get('rate-too') cc = CurrencyCodes() name_from = cc.get_currency_name(rate_from) name_to = cc.get_currency_name(rate_too) symbol = cc.get_symbol(rate_too) if not amount: con_rate = "{0:.2f}".format(round(c.get_rate(rate_from, rate_too), 2)) return render_template("convert.html", con_rate=con_rate, name_from=name_from, name_to=name_to, symbol=symbol, rates=session.get("rates"), bit=session.get("bit")) else: con_rate = "{0:.2f}".format( round(c.convert(rate_from, rate_too, amount), 2)) return render_template("convert.html", con_rate=con_rate, name_from=name_from, name_to=name_to, symbol=symbol, rates=session.get("rates"), bit=session.get("bit"))
def append_symbols_names(dataframe): symbols = dataframe.columns cc = CurrencyCodes() named_symbols = [] for symbol in symbols: name = "" try: name = cc.get_currency_name(symbol) except: pass if name != None: named_symbols.append(str(symbol) + " " + str(name)) else: named_symbols.append(str(symbol)) dataframe.columns = named_symbols return dataframe
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 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, )
class Converter(): def __init__(self): self.currency_rates = CurrencyRates() self.currency_codes = CurrencyCodes() def check_valid_code(self, code): """checks to see if currency is valid""" return self.currency_codes.get_currency_name(code) is not None def exchange(self, converting_from, converting_to, amount): """converts currency""" print('PPPPPPPPP') # try: amount = f"{self.currency_rates.convert(converting_from, converting_to, amount):.2f}" print('RRRRRRR: ', amount) return amount
# @date: 19.04.2021 # @author: Şükrü Erdem Gök # @version: Python 3.8 # @os: Windows 10 # @github: https://github.com/SukruGokk # Currency Converter # Lib from forex_python.converter import CurrencyRates as CR from forex_python.converter import CurrencyCodes as CS inputType = input('Input Type: ').upper() amount = int(input('Amount: ')) outputType = input('Output Type: ').upper() cr = CR() cs = CS() # Convert result = round(float(cr.get_rate(inputType, outputType)) * amount, 5) inputName = cs.get_currency_name(inputType) outputName = cs.get_currency_name(outputType) try: print('{} {}({}) = {} {}({})'.format(amount, inputType, inputName, result, outputType, outputName)) except: print('Invalid currency or network error !')
print('\n' + from_currency + " To " + to_currency, amount) print('The current conversion rate for {} to {} is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency))) #Get conversion rate from USD to INR result = c.convert(from_currency, to_currency, amount) #Convert the amount print('Latest Conversion: ',result) #Get conversion rate as of 2021-01-01 print('\nThe conversion rate from {} to {} as per 1st Jan 2021 is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency, date_obj))) print('The conversion as per 1st Jan 2021: ', c.convert(from_currency, to_currency, amount, date_obj)) b = BtcConverter() print('\n\nBitcoin Symbol: ', b.get_symbol()) # get_btc_symbol() print('Bitcoin Latest Price in USD : ', b.get_latest_price('USD')) #Get latest Bitcoin price. print('Convert 10 Million USD to Bitcoin', b.convert_to_btc(10000000, 'USD')) #Convert Amount to Bitcoins based on latest exchange price. print('The Equivalent of 10.99 Bitcoin in USD: ',b.convert_btc_to_cur(10.99, 'USD')) #Convert Bitcoins to valid currency amount based on lates price print('\nBitcoin price as per 1st Jan 2021: ',b.get_previous_price('USD', date_obj)) #Get price of Bitcoin based on prevois date print('The conversion of 10 Million Dollars to Bitcoin as of 1st Jan 2021',b.convert_to_btc_on(10000000, 'USD', date_obj)) #Convert Amount to bitcoins based on previous date prices print('The conversion of 10.99 Bitcoin in USD as of 1st Jan 2021: ',b.convert_btc_to_cur_on(10.99, 'USD', date_obj)) #Convert Bitcoins to valid currency amount based on previous date price start_date = datetime.datetime(2021, 2, 1, 19, 39, 36, 815417) end_date = datetime.datetime(2021, 2, 7, 19, 39, 36, 815417) print('\nBitcoin rates over the week in USD: ',b.get_previous_price_list('USD', start_date, end_date)) #Get list of prices list for given date range d = CurrencyCodes() print('\nUS Dollar Symbol:', d.get_symbol('USD')) #Get currency symbol using currency code print(d.get_currency_name('USD')) #Get Currency Name using currency code print('\nThe latest rate of USD for various currencies\n', c.get_rates('USD')) #list all latest currency rates for "USD" print('\nThe rate of USD for various currencies as per 1st Jan 2021\n',c.get_rates('USD', date_obj)) #List all Currency rates for “USD” on 2021-01-01
choose = int(input(': ')) while True: if choose == 3: print('Come again :@') break elif choose == 1: print( 'To compare rates you must use the currency symbols e.g United State dollar as USD or Indian Ruppes as INR' ) time.sleep(1) compare_1 = str(input('Your currency : ')).upper() compare_2 = str(input('Compared with: ')).upper() # Getting the currency symbol cur_name = c.get_currency_name(compare_2) cur_symbol_1 = c.get_symbol(compare_1) cur_symbol_2 = c.get_symbol(compare_2) time.sleep(1) print('You want to compare ' + cur_symbol_1 + ' against ' + cur_symbol_2) rate = cr.get_rate(compare_1, compare_2) # Addig the cool loading screen before ouput mylist = range(9) for i in tqdm(mylist): time.sleep(1) print('The conversion rate of ' + compare_1 + ' TO ' + compare_2 +
''' Currency Converter using Python Author: Ayushi Rawat ''' #import the necessary module! from forex_python.converter import CurrencyCodes, CurrencyRates from forex_python.bitcoin import BtcConverter test1 = CurrencyCodes() #fetch Currency Symbol cur_symbol = test1.get_symbol('INR') #fetch Currency Name cur_name = test1.get_currency_name('INR') #display Currency Name & Symbol print('\nThe currency name is: ' + cur_name) print('The currency symbol is: ' + cur_symbol) print('\n' + test1.get_symbol('USD')) print(test1.get_currency_name('USD') + '\n') test2 = CurrencyRates() #fetch the Conversion rate rate = test2.get_rate('USD', 'INR') print(rate) #perform conversion
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) #print(m.ticker("bitcoin",convert="EUR")[0]["price_usd"]*100) allcoins=SortedDict(allcoins) wordhash={} credithash={} initialvalue=100000.00
#pip install forex-python #https://forex-python.readthedocs.io/en/latest/usage.html from forex_python.converter import CurrencyCodes,CurrencyRates from forex_python.bitcoin import BtcConverter print('imported') test = CurrencyCodes() cur_symbol = test.get_symbol('INR') cur_name = test.get_currency_name('INR') print("the currency name is:= "+ cur_name) #print(cur_symbol) print(test.get_symbol('CHF')) print(test.get_currency_name('CHF')) c = CurrencyRates() print(c.get_rates('INR'),'/n') print('the cureency rate is ' , c.get_rate('USD','INR')) print('the cureency converted rate is ' , c.convert('USD', 'INR',10)) b = BtcConverter() # force_decimal=True to get Decimal rates print('the bitcon rate for usd is ',b.get_latest_price('USD'))
#it's not work from forex_python.converter import CurrencyCodes, CurrencyRates from forex_python.bitcoin import BtcConverter test = CurrencyCodes() cur_symbol = test.get_symbol('INR') cur_name = test.get_currency_name('INR') print('The currence name is: ' + cur_name) print('The currence symbol is: ' + cur_symbol) print('\n' + test.get_currency_name('USD')) print(test.get_symbol('USD')) test1 = CurrencyRates rate = test1.get_rate('USD', 'INR') # print(rate) res = test1.convert('USD','INR',10) #print(res) print('===================') bitcoin = BtcConverter() price = bitcoin.get_previous_price('INR') print(price)
from forex_python.converter import CurrencyRates, CurrencyCodes c = CurrencyRates() print(c.get_rate('USD', 'INR')) print(c.convert('USD', 'INR', 20)) curr = CurrencyCodes() print(curr.get_symbol('INR')) print(curr.get_currency_name('INR'))
def pullData(): t = '{:%H:%M:%S}'.format(datetime.datetime.now() + datetime.timedelta(hours=1)) #t = time.strftime("%H:%M:%S") print("Starting at number: " + str(datetime.datetime.utcnow())) # Using forex to get latest data: https://media.readthedocs.org/pdf/forex-python/latest/forex-python.pdf c = CurrencyRates() b = BtcConverter() rates = c.get_rates(config.LOCAL_CURR_CODE) pop = False # Adapted from: https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu chart_data['labels'].append(t) # If 20 dates are already currently in the list - pop. if len(chart_data['labels']) >= 20: chart_data['labels'].pop(0) pop = True # Loop through array of datasets to append or append and pop. if chart_data['datasets']: for i, code in enumerate(config.CURR_CODES): if code == 'BTC': price = round(b.get_latest_price(config.LOCAL_CURR_CODE), 2) rate = round(b.convert_to_btc(1, config.LOCAL_CURR_CODE), 5) else: price = round(c.get_rate(code, config.LOCAL_CURR_CODE), 2) rate = round(rates[chart_data['datasets'][i]['label']], 5) chart_data['datasets'][i]['data'].append(price) latest_currencies['currencies'][i]['data'] = rate if pop: chart_data['datasets'][i]['data'].pop(0) else: co = CurrencyCodes() # Prepare data objects and pull first prices. for i, code in enumerate(config.CURR_CODES): if code == 'BTC': symbol = b.get_symbol() name = 'Bitcoin' price = round(b.get_latest_price(config.LOCAL_CURR_CODE), 2) rate = round(b.convert_to_btc(1, config.LOCAL_CURR_CODE), 5) else: name = co.get_currency_name(code) symbol = co.get_symbol(code) price = round(c.get_rate(code, config.LOCAL_CURR_CODE), 2) rate = round(rates[code], 5) chart_data['datasets'].append({ 'label': code, 'backgroundColor': config.CURR_COLORS[i], 'data': [price] }) latest_currencies['currencies'].append({ 'code': code, 'name': name, 'symbol': symbol, 'data': rate }) r.set(config.REDIS_CHAN_LIST, latest_currencies) r.set(config.REDIS_CHAN_GRAPH, chart_data) print("Finishing at number: " + str(datetime.datetime.utcnow()))
break else: print('Какую валюту Вы хотели бы поменять?') currency_from = str(input()) while currency_from not in cr.get_rates('USD'): print('Кажется, Вы ошиблись. Введите валюту еще раз:') currency_from = str(input()) print('Какую валюту Вы хотели бы получить?') currency_to = str(input()) while currency_to not in cr.get_rates('USD'): print('Кажется, Вы ошиблись. Введите валюту еще раз:') currency_to = str(input()) print('Сколько денег (' + cd.get_currency_name(currency_from) + ') Вы хотите поменять?') amount_of_money = float(input()) print('Хотели бы Вы обменять валюту в ретроспективе?') print('Введите "да" или "нет":') yes_or_no = str(input()) while yes_or_no != "да" and yes_or_no != "нет": print('Кажется, Вы ошиблись. Введите ответ еще раз:') yes_or_no = str(input()) if yes_or_no == "нет": print('Вы получите:') final_sum = str( converter(currency_from, currency_to,
with open(r"C:\Users\Lenovo\Desktop\New folder\python\Small Projects\Currency.txt") as f: lines = f.readlines() print(lines) curr_dict = {} for line in lines: split = line.split("\t") curr_dict[split[0]] = split[1] print(curr_dict) amount = int(input("Enter the amount: ")) print("Enter Conversion Currency: \nAvailable Options:\n") [print(item) for item in curr_dict.keys()] currency = input("Enter one of these values:") print(f"{amount} INR is equal to {amount * float(curr_dict[currency])} {currency}") from forex_python.converter import CurrencyRates, CurrencyCodes c = CurrencyRates() print(c.get_rate('INR','USD')) print(c.convert("INR","USD",500)) print(c.get_rate('USD','INR')) print(c.convert("USD","INR",500)) curr = CurrencyCodes() print(curr.get_symbol("INR")) print(curr.get_currency_name("INR")) from forex_python.bitcoin import BtcConverter bt = BtcConverter() print(bt.get_latest_price("INR"))
def currency_name(self, init): """Calcualtes the name of the currency using the initials.""" c2 = CurrencyCodes() c_name = c2.get_currency_name(init) return c_name