def save(self, *args, **kwargs): c = CurrencyRates() self.total = c.convert('USD','KRW',self.usd)+\ c.convert('CNY','KRW',self.cny)+\ self.krw super(CashAccount, self).save(*args, **kwargs)
async def execute(self, args, msg): amount, origin, destination = args try: amount = Decimal(amount) except Exception as _: raise ValueError(f'Cannot parse decimal: {amount}') try: o_code, o_symbol = self.currency_code_and_symbol(origin) except TypeError: raise ValueError(f'Unknown currency: {origin}') try: d_code, d_symbol = self.currency_code_and_symbol(destination) except TypeError: raise ValueError(f'Unknown currency: {destination}') c = CurrencyRates() if o_code == 'BTC': b = BtcConverter() res = b.convert_btc_to_cur(amount, 'USD') if d_code != 'USD': res = c.convert('USD', d_code, res) elif d_code == 'BTC': b = BtcConverter() if o_code != 'USD': amount = c.convert(o_code, 'USD', amount) res = b.convert_to_btc(amount, o_code) else: res = c.convert(o_code, d_code, amount) res = self.format_number(res, 4, 2) await msg.channel.send(f'{amount: f} {o_code} = {res or 0} {d_code}')
def build_json(us, ger, it): c = CurrencyRates() amazon_us_usd = us if (not us == "error" and not us == False): amazon_us_ils = round(c.convert('USD', 'ILS', us), 2) else: amazon_us_ils = False amazon_ger_eur = ger if (not ger == "error" and not ger == False): amazon_ger_ils = round(c.convert('EUR', 'ILS', ger), 2) else: amazon_ger_ils = False amazon_it_eur = it if (not it == "error" and not us == False): amazon_it_ils = round(c.convert('EUR', 'ILS', it), 2) else: amazon_it_ils = False j = json.dumps({ 'amazon_us': { 'usd': amazon_us_usd, 'ils': amazon_us_ils }, 'amazon_ger': { 'eur': amazon_ger_eur, 'ils': amazon_ger_ils }, 'amazon_it': { 'eur': amazon_it_eur, 'ils': amazon_it_ils } }) return j
class TestForceDecimalAmountConvert(TestCase): """ Test the force_decimal=True type enforcing """ def setUp(self): self.c = CurrencyRates(force_decimal=True) def test_amount_decimal_convert(self): amount = self.c.convert('USD', 'INR', Decimal('10.45')) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_convert_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() amount = self.c.convert('USD', 'INR', Decimal('10.45'), date_obj) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_invalid_type(self): self.assertRaises(DecimalFloatMismatchError, self.c.convert, 'USD', 'INR', 10.45) def test_decimal_get_rates_valid_code(self): all_rates = self.c.get_rates('USD') # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() all_rates = self.c.get_rates('USD', date_obj) # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_invalid_code(self): self.assertRaises(RatesNotAvailableError, self.c.get_rates, 'XYZ') def test_decimal_get_rate_with_valid_codes(self): rate = self.c.get_rate('USD', 'INR') # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() rate = self.c.get_rate('USD', 'INR', date_obj) # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_invalid_codes(self): # raise exception for invalid currency codes self.assertRaises(RatesNotAvailableError, self.c.get_rate, 'ABCD', 'XYZ')
class TestForceDecimalAmountConvert(TestCase): """ Test the force_decimal=True type enforcing """ def setUp(self): self.c = CurrencyRates(force_decimal=True) def test_amount_decimal_convert(self): amount = self.c.convert('USD', 'INR', Decimal('10.45')) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_convert_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() amount = self.c.convert('USD', 'INR', Decimal('10.45'), date_obj) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_invalid_type(self): self.assertRaises(DecimalFloatMismatchError, self.c.convert, 'USD', 'INR', 10.45) def test_decimal_get_rates_valid_code(self): all_rates = self.c.get_rates('USD') # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() all_rates = self.c.get_rates('USD', date_obj) # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_invalid_code(self): self.assertRaises(RatesNotAvailableError, self.c.get_rates, 'XYZ') def test_decimal_get_rate_with_valid_codes(self): rate = self.c.get_rate('USD', 'INR') # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() rate = self.c.get_rate('USD', 'INR', date_obj) # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_invalid_codes(self): # raise exception for invalid currency codes self.assertRaises(RatesNotAvailableError, self.c.get_rate, 'ABCD', 'XYZ')
def convert(self): """ Converts the input currency to the output currency. Raises RatesNotAvailableException if data for conversion is not available. :return: Currency conversion in JSON format """ # Load the currency rates using Forex Python Converter cr = CurrencyRates() # Prepare the json format for printing the result of the conversion data = {} data['input'] = {'amount': self.amount, 'currency': self.input_code} data['output'] = {} file_path = os.path.dirname( os.path.abspath(forex_python.converter.__file__)) with open(file_path + '/raw_data/currencies.json') as f: # Load the currency data to variable currency_data = json.loads(f.read()) if self.output_code == "": # Output currency is not set - convert to all known currencies for item in currency_data: for k, v in item.items(): if k == "cc": try: data['output'].update({ v: cr.convert(self.input_code, v, self.amount) }) except RatesNotAvailableError: # Data for this currency conversion is not available, skip this conversion. continue else: # Output currency is set try: data['output'] = { self.output_code: cr.convert(self.input_code, self.output_code, self.amount) } except RatesNotAvailableError: raise RatesNotAvailableException( "Data for this currency conversion is not available.") if self.get_codes_for_symbol(self.input_symbol): # There is more currencies available for the input symbol data['symbol_currencies'] = {} self.__add_available_currencies_for_the_symbol( self.input_symbol, data) if self.get_codes_for_symbol(self.output_symbol): # There is more currencies available for the output symbol data['symbol_currencies'] = {} self.__add_available_currencies_for_the_symbol( self.output_symbol, data) return data
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 currency_change(country, countries): currency = CurrencyRates() data = [] for change in countries: if pycountry.currencies.get(alpha_3=change) is not None: data.append(currency.convert(country, change, 1)) return data
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 calc(should_print=False): print(""" Name:Currency Calculator Operation : cuurency calculation Inputs : a->string,b->string,x->int/float Outputs: y=>conversion of currency ->float Author : Apoorva-Datir \n """) c = CurrencyRates() a=input("enter original currency(e.g. USD): ") b=input("enter second currency(e.g. INR): ") x= float(input("enter amount: ")) y=c.convert(a, b, x) print("{} {} = {} {}".format(x,a,y,b)) result = {} result['inputs'] = [a, b, x] result['outputs'] = [y] if should_print: print(f"Solution {result['outputs'][0]}") else: return result
def conversion(args): c = CurrencyRates() if (args['output_currency'] == None): app_output = { "input": { "amount": args['amount'], "currency": args['input_currency'] }, "output": {} } all_currency_rates = c.get_rates(args['input_currency']) for key in all_currency_rates: app_output["output"][key] = round( all_currency_rates[key] * args['amount'], 3) return app_output else: app_output = { "input": { "amount": args['amount'], "currency": args['input_currency'] }, "output": { args['output_currency']: round( c.convert(args['input_currency'], args['output_currency'], args['amount']), 3), } } return app_output
def standardize_currency(from_curr, amount): c = CurrencyRates() # print(amount) convertedAmount = c.convert(from_curr, 'INR', amount) # convertedAmount = str(convertedAmount) # convertedAmount = '0' if convertedAmount[:1] == '0' else convertedAmount return '{0:.2f}'.format(convertedAmount)
def average_forex(event): c = CurrencyRates() year = int(year_start.get()) month = int(month_start.get()) day = int(day_start.get()) date_obj = datetime(int(year), int(month), int(day)) #result = c.convert('USD', 'THB', 1, date_obj) sum = 0 totalday = 0 while date_obj != datetime(int(year_end.get()), int(month_end.get()), int(day_end.get())): try: date_obj = datetime(int(year), int(month), int(day)) result = c.convert(forex1.get(), forex2.get(), 1, date_obj) totalday += 1 sum += result print(date_obj, " , ", result) day += 1 except: day = 1 month += 1 if (month > 12): month = 1 year += 1 print(sum) print(totalday) sum = sum / totalday labelResult.configure(text=sum)
def currency_conversion(article_price: float): if 'currency' in params[item].keys(): if params[item]['currency'] != 'EUR': converter = CurrencyRates() article_price = converter.convert(params[item]['currency'], 'EUR', article_price) return article_price
def convertcurr(rate): x = amount.get() y = currency_from.get() z = currency_to.get() curr = CurrencyRates() f = curr.convert(y,z,x) final.set(format(f, '.2f'))
def convert_amount(self, init, new_currency, amount): """Converts an amount from the currency at hand to a new currency.""" curr = CurrencyRates() curr_conversion = curr.convert(init, new_currency, amount) return curr_conversion
def clicked(): from forex_python.converter import CurrencyRates c = CurrencyRates() # force_decimal=True uin = int(txt.get()) sum = c.convert('USD', 'INR', uin) l2.configure(text="The Amount in INR:" + str(sum))
def get_exchange_rate(self,rate_from,rate_to,rate_cu): converter = CurrencyRates() result = converter.convert(rate_from,rate_to,rate_cu) db_sql = ("INSERT INTO cny_to_jpy_rate VALUES(?,?,?,?)") db_data = (rate_from, rate_to, result, current_date) jarvis.cidb_write(self,db_sql,db_data) return result
def conversion(): cr = CurrencyRates() from_curr = entry1.get() #Currency to be converted to_curr = entry2.get() #Currency to be converted In value = amount.get() #Value to be converted if (value == ""): tk.messagebox.showinfo("Warning", "No Amount Entered!") elif (from_curr == "" or to_curr == ""): tk.messagebox.showinfo("Warning", "Currency not Entered!") else: new_amt = cr.convert(from_curr, to_curr, float(value)) new_amount = float("{:.4f}".format(new_amt)) #-----OVERWIRTING final_amt.delete(0, tk.END) #-----END RESULT final_amt.insert(0, str(value)) final_amt.insert(10, str(" ")) final_amt.insert(20, str(from_curr)) final_amt.insert(10, str(" = ")) final_amt.insert(30, str(new_amount)) final_amt.insert(40, str(" ")) final_amt.insert(50, str(to_curr)) curr_codes()
def currency_exchange(string): return_str = "" try: l = [] print(string) string = string.strip() string = re.sub(" +", " ", string) l = string.split(" ") l = [x.upper() for x in l] print(l) l = [x.replace(' ', '') for x in l] if "BITCOIN" in l: b = BtcConverter() if (l[0]).upper() == "BITCOIN": return_str = str(float(l[2]) * b.get_latest_price(l[1])) elif (l[1]).upper() == "BITCOIN": return_str = str(float(l[2]) / b.get_latest_price(l[0])) else: return_str = "Result Not found" else: c = CurrencyRates() return_str = str(c.convert(l[0], l[1], float(l[2]))) except Exception as e: return_str = "Give proper input" print(e) return return_str
async def currency(self, ctx, amount, currency1, currency2): try: c = CurrencyRates() amount = float(amount) except: embed = discord.Embed(color=self.bot.embed_color, title="→ Money Error!", description="• Not a valid amount of money!") await ctx.send(embed=embed) try: amount2 = float(c.convert(currency1, currency2, amount)) except: embed = discord.Embed(color=self.bot.embed_color, title="→ Currency Error!", description="• Not a valid currency type!" "\n• Example: `l!currency 10 USD CAD`") await ctx.send(embed=embed) embed = discord.Embed( color=self.bot.embed_color, title="→ Currency Converting", description= f"• {amount} {currency1} is about {truncate(amount2, 2)} {currency2}!" ) await ctx.send(embed=embed) logger.info(f"Utility | Sent Currency: {ctx.author}")
def convert(): try: # get data from form amount = request.form["amount"] to = request.form["to"] from_code = request.form["from-code"] # convert rates c = CurrencyRates() converted = c.convert(from_code, to, float(amount)) # get currency name and symbol def get_name_symbol(code): return next((item for item in currency_data if item["cc"] == code), None) from_name = get_name_symbol(from_code)['name'] to_symb = get_name_symbol(to)['symbol'] to_name = get_name_symbol(to)['name'] # flash result message flash( f"{amount} {from_name} equals {to_symb}{round(converted, 2)} {to_name}", 'success') except forex_python.converter.RatesNotAvailableError: flash(f"{from_code} to {to} conversion is currently not available.", 'error') return redirect('/convert')
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 convert(): """convert amount from base to target currency""" form = ConvertForm(request.form) has_result = False target_amount = False has_csrf_token = hasattr(form, 'csrf_token') if request.method == 'POST': if form.validate_on_submit(): has_result = True try: CR = CurrencyRates() target_amount = CR.convert(form.base_currency.data, form.target_currency.data, form.base_amount.data) except Exception: # TODO: test with testing framework flash('currency conversion API failed', 'warning') else: flash('Form could not be validated. See below', 'warning') return render_template('convert.html', form=form, has_result=has_result, target_amount=target_amount, has_csrf_token=has_csrf_token)
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 convert(c1, c2, amount): try: if amount == "": messagebox.showerror("Error", "Amount not specified") elif c1 == "Select" or c2 == "Select": messagebox.showinfo("Error", "Currency not selected") else: try: amount = float(amount) b = BtcConverter() c = CurrencyRates() if c1 == c2: result = amount elif c1 == "BTC": result = b.convert_btc_to_cur(amount, c2) elif c2 == "BTC": result = b.convert_to_btc(amount, c1) else: result = c.convert(c1, c2, int(amount)) print(result) label_down[ "text"] = f"Conversion Result: {amount} {c2}\n{amount} {c1} = {result} {c2}" except ValueError: messagebox.showerror("Error", "Invalid amount") clear() except Exception: messagebox.showerror("Error", "Please try again")
def change_money(val1, val2, money, tup, history): c = CurrencyRates() if tup == (): a = c.convert(val1, val2, money) s = 'Конвертировал ' + str(money) + ' ' + val1 + ' в ' + val2 s += ' по курсу ' + str(c.get_rate(val1, val2)) + ' и получил ' s += str(a) + ' ' + val2 history.append(s) return a else: a = c.convert(val1, val2, money, tup) s = 'Конвертировал ' + str(money) + ' ' + val1 + ' в ' + val2 s += ' по курсу ' + str(c.get_rate(val1, val2, tup)) + ' и получил ' s += str(a) + ' ' + val2 history.append(s) return a
def val_input(input_str, input_dat): c = CurrencyRates() rates = c.get_rates("NOK", input_dat) keys = rates.keys() #parse input string to find numbers val_num = re.findall("\d+.\d+", input_str) #the regex search above doesn't like single digit numbers, but this one does: if not val_num: val_num = re.findall("\d+", input_str) #Checks the input string for which currency to convert for key in keys: x = re.search(key, input_str) if x != None: val_key = x.group() break #if no currency code is written, the program assumes NOK else: val_key = "NOK" #if no conversion is needed if val_key == "NOK": val_result = float(val_num[0]) #forex conversion according to the date input else: val_result = c.convert(val_key, "NOK", float(val_num[0]), input_dat) return round(val_result, 2)
def currency_convert(from_currency_code, to_currency_code, amount): try: currency_rate_obj = CurrencyRates() return currency_rate_obj.convert(from_currency_code.upper(), to_currency_code.upper(), float(amount)) except Exception as e: return None
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 TestAmountConvert(TestCase): """ test amount conversion from one currency to other """ def setUp(self): self.c = CurrencyRates() def test_amount_convert_valid_currency(self): amount = self.c.convert('USD', 'INR', 10) # test if amount returned in float self.assertTrue(isinstance(amount, float)) def test_amount_convert_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() amount = self.c.convert('USD', 'INR', 10, date_obj) # test if amount returned in float self.assertTrue(isinstance(amount, float)) def test_amount_convert_invalid_currency(self): # test if amount returned in float self.assertRaises(RatesNotAvailableError, self.c.convert, 'ABC', 'XYZ', 10)
def currencyconv(self, jarvis, amount, fr, to): """ currencyconv converts the given amount to another currency using fore-python """ b = BtcConverter(force_decimal=True) c = CurrencyRates(force_decimal=True) if (to == "BTC"): result = b.convert_to_btc(Decimal(amount), fr) elif (fr == "BTC"): result = b.convert_btc_to_cur(Decimal(amount), to) else: result = c.convert(fr, to, Decimal(amount)) outputText = str(amount) + " " + fr + \ " are equal to " + str(result) + " " + to jarvis.say(outputText)
def forex(from_currency, to_currency, amount): try: currency_rates = CurrencyRates() return currency_rates.convert(from_currency, to_currency, amount) except: return amount