def converter(self): c = CurrencyConverter() input_currency = self.ui.input_currency.text() output_currency = self.ui.output_currency.text() input_amount = int(self.ui.input_amount.text()) output_amount = round(c.convert(input_amount, '%s' % (input_currency), '%s' % (output_currency)), 2) self.ui.output_amount.setText(str(output_amount))
def __init__(self, regNo, finalAmount): self.c = CurrencyConverter() self.window = Tk() self.window.title('Confirm to sale') self.window.geometry('350x300+200+250') self.lbl_regNo = Label(self.window, text='Car reg_no') self.fld_regNo = Entry(self.window) self.fld_regNo.insert(END, regNo) self.lbl_finalAmount = Label(self.window, text='Final amount') self.fld_finalAmount = Entry(self.window) self.fld_finalAmount.insert(END, finalAmount) self.lbl_selectCurrencyType = Label(self.window, text='Select Currency Type') self.combo_selectCurrencyType = Combobox( self.window, postcommand=self.selectCurrencyType) self.btn_confirm = Button(self.window, text='Confirm', command=self.confirm) self.lbl_regNo.grid(row=0, column=0, padx=8, pady=8) self.fld_regNo.grid(row=0, column=1, padx=8, pady=8) self.lbl_finalAmount.grid(row=1, column=0, padx=8, pady=8) self.fld_finalAmount.grid(row=1, column=1, padx=8, pady=8) self.lbl_selectCurrencyType.grid(row=2, column=0, padx=8, pady=8) self.combo_selectCurrencyType.grid(row=2, column=1, padx=8, pady=8) self.btn_confirm.grid(row=3, column=1, padx=8, pady=8) self.window.mainloop()
def currency_converter(price, curr1="SEK", curr2="EUR"): """конвертер валют . Работает медленно""" c = CurrencyConverter() try: return c.convert(price, curr1, curr2) except ValueError or RateNotFoundError as err: return str(err)
def get_money_interval(difficulty_level): random_usd_amount = randint(1, 100) currency_converter = CurrencyConverter() t = currency_converter.convert(random_usd_amount, 'USD', 'ILS') d = difficulty_level generated_interval = t - (5 - d), t + (5 - d) return random_usd_amount, generated_interval
def backtest(self, position_type, data, margin): try: ''' Lot Number of unit Standard 100,000 Mini 10,000 Micro 1,000 Nano 100 Position size = ((account value x risk per trade) / pips risked)/ pip value per standard lot Margin Requirement = Current Price × Units Traded × Margin ''' data['atr']=atr(list(data.bidclose), self.atr_period) last_atr=data.atr.iloc[-1] price=data.bidclose.iloc[-1] stop_loss, limit, stop_loss_pip, limit_pip=self.stop_loss_limit(price, last_atr, position_type) leverage=leverage_cal(self.symbol, margin) standard_lot_pip_value=pip_value_cal(self.symbol, self.account_currency, price, 100000) position_size=int(((((margin*self.risk_percent/100)/stop_loss_pip)/standard_lot_pip_value)*100)*1000) required_margin=int(price*position_size/leverage) c = CurrencyConverter() required_margin=int(c.convert(required_margin, self.symbol[:3], self.account_currency)) pip_value=pip_value_cal(self.symbol, self.account_currency, price, position_size) if self.symbol[3:]=='JPY': required_margin=required_margin/100 return position_size, required_margin, stop_loss, limit, stop_loss_pip, limit_pip, pip_value except Exception as e: print(e, 'backtest')
def predict_wine_rating(): country = request.args.get('country', 'Spain') description = request.args.get('description', 'wine') # conversion rates - create a drop down with EUR and GBR conversion_factor = request.args.get('conversion', 'EUR') c = CurrencyConverter() price_raw = float(request.args.get('price', 0)) price = c.convert(price_raw, conversion_factor, 'USD') # province always has to be provided province = request.args.get('province', 'Other') # region defaults to Other in all cases region = 'Other' variety = request.args.get('variety', 'Other') year = request.args.get('year', '2019') winery = request.args.get('winery', 'Other') title = f"{winery} {year} {variety} ({province})" # dataframe has to be in this format df = pd.DataFrame( dict(country=[country], description=[description], price=[price], province=[province], region_1=[region], title=[title], variety=[variety], winery=[winery])) print('feature engineering') feat = joblib.load('model/feature_eng.joblib') print('model') model = joblib.load('model/model.joblib') feat_eng_x = feat.transform(df) prediction = model.predict(feat_eng_x) return {'prediction': str(prediction[0])}
def position_size_stop_loss(self, position_type): try: ''' Lot Number of unit Standard 100,000 Mini 10,000 Micro 1,000 Nano 100 Position size = ((account value x risk per trade) / pips risked)/ pip value per standard lot Margin Requirement = Current Price × Units Traded × Margin ''' data=self.db.query_price_data(self.symbol, self.timeframe, self.atr_period*2) data['atr']=atr(list(data.bidclose), self.atr_period) last_atr=data.atr.iloc[-1] price=data.bidclose.iloc[-1] fxcm_info=self.get_account_info()[0] balance=fxcm_info[2] stop_loss, limit, stop_loss_pip, limit_pip=self.stop_loss_limit(price, last_atr, position_type) leverage=leverage_cal(self.symbol, balance) standard_lot_pip_value=pip_value_cal(self.symbol, self.account_currency, price, 100000) position_size=int(((((balance*self.risk_percent/100)/stop_loss_pip)/standard_lot_pip_value)*100)*1000) required_margin=int(price*position_size/leverage) c = CurrencyConverter() required_margin=int(c.convert(required_margin, self.symbol[:3], self.account_currency)) if self.symbol[3:]=='JPY': required_margin=required_margin/100 return position_size/1000, required_margin, stop_loss, limit, stop_loss_pip, limit_pip except Exception as e: print(e, 'position_size_stop_loss')
def test_currency_code_that_is_equal_to_passed_in(): converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'USD' result = converter.convert(currency, convert_to_code) assert result == Currency(1, 'USD')
def __init__(self, master): frame = Frame(master) frame.grid() self.currency = CurrencyConverter() self.options = ["EUR", "USD", "CAD", "NZD", "CNY", "AUD", "DKK", "GBP"] self.amount_label = Label(root, text="Amount: ") self.amount_label.grid(column=0, row=0) self.amount_entry = Entry(root) self.amount_entry.grid(column=1, row=0) self.selection_frame = LabelFrame(root, text="Currencies") self.selection_frame.grid(column=0, row=1, columnspan=2) self.from_label = Label(self.selection_frame, text="From: ") self.from_label.grid(column=0, row=0) self.to_label = Label(self.selection_frame, text="To: ") self.to_label.grid(column=1, row=0) self.from_menu = ttk.Combobox(self.selection_frame, values=self.options) self.from_menu.grid(column=0, row=1) self.from_menu.current(1) self.to_menu = ttk.Combobox(self.selection_frame, values=self.options) self.to_menu.grid(column=1, row=1) self.to_menu.current(1) self.result_label = Label(root, text=f"") self.result_label.grid(column=0, row=2, columnspan=2) self.convert_button = Button(root, text="Convert!", command=self.converter) self.convert_button.grid(column=0, row=3, columnspan=2)
def __init__(self, master): frame = Frame(master) frame.grid() tabControl = ttk.Notebook(root) tabControl.configure(width=500, heigh=260) self.phrase_tab = ttk.Frame(tabControl) tabControl.add(self.phrase_tab, text="Language") tabControl.grid() self.phrase_tab.grid_propagate(0) self.currency_tab = ttk.Frame(tabControl) tabControl.add(self.currency_tab, text="Currency") tabControl.grid() self.languages = { 'Arabic':'ar','Belarusian':'br','Bengali':'bn','Bosnian':'bs','Bulgarian':'bg','Chinese':'zh-cn', 'Croatian':'hr','Czech':'cs','Danish':'da','English':'en','Finnish':'fi','French':'fr','German':'de', 'Gujarati':'gu','Greek':'el','Haitian':'ht','Hebew':'he','Hindi':'hi','Irish':'ga','Italian':'it', 'Japanese':'ja','Korean':'ko','Malayalam':'ml','Marathi':'mr','Nepali':'ne','Persian':'fa','Punjabi':'pa', 'Romanian':'ro', 'Russian':'ru','Sindhi':'sd','Spanish':'es','Swedish':'sv','Tamil':'ta', 'Telugu':'te','Thai':'th','Turkish':'tr','Urdu':'ur' } self.currency = CurrencyConverter() self.options = ["AUD","CAD","CNY","DKK","EUR","GBP","INR","JPY","NZD","USD"] self.language_page() self.currency_page()
def _format_coinmarket_stats(self, stats, fiat): """ Receives and formats coinmarket stats @param fiat - desired fiat currency (i.e. 'EUR', 'USD') @return - formatted stats """ try: c = CurrencyConverter() formatted_stats = '' if (stats['total_market_cap_usd'] is None): formatted_stats += "Total Market Cap (USD): Unknown" else: converted_price = int( c.convert(float(stats['total_market_cap_usd']), 'USD', fiat)) if fiat in fiat_suffix: formatted_stats += "Total Market Cap ({}): **{:,} {}**\n".format( fiat, converted_price, fiat_currencies[fiat]) else: formatted_stats += "Total Market Cap ({}): **{}{:,}**\n".format( fiat, fiat_currencies[fiat], converted_price) formatted_stats += "Bitcoin Percentage of Market: **{:,}%**\n".format( stats['bitcoin_percentage_of_market_cap']) formatted_stats += "Active Markets: **{:,}**\n".format( stats['active_markets']) formatted_stats += "Active Currencies: **{:,}**\n".format( stats['active_currencies']) formatted_stats += "Active Assets: **{:,}**\n".format( stats['active_assets']) return formatted_stats except Exception as e: raise CoinMarketException("Failed to format data: `{}`".format(e))
def my_form_post(): c = CurrencyConverter() euros = request.form["euros"] usd = round(c.convert(euros, "EUR", "USD"), 2) return render_template("form.html", euros=euros, usd=usd)
def currency(): try: c = CurrencyConverter() while True: print("what amount do you want to converted") speak("what amount do you want to converted") AMOUNT = takeCommand().isnumeric if 'none' not in AMOUNT: break while True: print("from which currency do you want to convert") speak("from which currency do you want to convert") FROM = takeCommand().upper() if 'none' not in FROM: break while True: print("to which currency do you want to convert") speak("to which currency do you want to convert") TO = takeCommand().upper() if 'none' not in TO: break print(c.convert(AMOUNT, FROM, TO)) speak(f"{AMOUNT} {FROM} is {c.convert(AMOUNT,FROM,TO)} {TO} ") except Exception as e: print("Say that again Please") speak("Say that again please")
def currency_conversion(cash_total): """Converts total cash injected into portfolio to USD Args: cash_total (dict): Keys = cash injection, Values = currency of cash injection Returns: sum_total_cash_in_usd [list]: total cash in USD """ c = CurrencyConverter() cash_currency = list(cash_total.values()) total_cash = list(cash_total.keys()) #* Else ensure that all inputted currencies are in uppercase cash_currency = [i.upper() for i in cash_currency] #* Converts all cash currency to USD sum_total_cash_in_usd = [] for i in range(len(cash_currency)): try: sum_total_cash_in_usd.append( c.convert(total_cash[i], cash_currency[i], "USD")) except ValueError as error: print(error) sum_total_cash_in_usd = [sum(sum_total_cash_in_usd)] print() return sum_total_cash_in_usd
def test_conversion(): dict_rates = {'USD': 1.0, 'EUR': 0.94, 'GBP': 0.80} c = CurrencyConverter(dict_rates) assert c.convert(a, "USD") == Currency("5.00", "USD") assert c.convert(d, "EUR") == Currency(0.94, "EUR") assert c.convert(i, "USD") == Currency(1, "USD") assert c.convert(j, "USD") != Currency(1, "USD")
def __init__(self): QWidget.__init__(self) self.c = CurrencyConverter(fallback_on_wrong_date=True) self.setWindowTitle('Converter') self.activefirstChoice = QLabel("", self) self.activelastChoice = QLabel("", self) self.firstValue = QLineEdit("0", self) self.lastValue = QLineEdit("0", self) self.firstChoice = QComboBox() self.lastChoice = QComboBox() layout = QHBoxLayout() layout.addWidget(self.firstChoice) layout.addWidget(self.firstValue) layout.addWidget(self.lastChoice) layout.addWidget(self.lastValue) self.setLayout(layout) for key in sorted(self.c.currencies): self.firstChoice.addItem(key) self.lastChoice.addItem(key) self.firstChoice.activated[str].connect(self.onchangefirstChoice) self.firstValue.textChanged[str].connect(self.onchangefirstValue) self.lastChoice.activated[str].connect(self.onchangelastChoice) self.lastValue.textChanged[str].connect(self.onchangelastValue)
def index(request): c = CurrencyConverter() market = coinmarketcap.Market() coin = market.ticker('stellar') cena = coin[0]['price_usd'] market_cap = float(coin[0]['market_cap_usd']) x24h_volume = float(coin[0]['24h_volume_usd']) x1h_change = coin[0]['percent_change_1h'] x24h_change = coin[0]['percent_change_24h'] x7d_change = coin[0]['percent_change_7d'] price_btc = coin[0]['price_btc'] rank = coin[0]['rank'] market_cap = format(round(int(market_cap)), ',d') x24h_volume = format(round(int(x24h_volume)), ',d') cena_eur = c.convert(cena, 'USD', 'EUR') cena_eur = float("{0:.5f}".format(cena_eur)) cena_yen = c.convert(cena, 'USD', 'CNY') cena_yen = float("{0:.5f}".format(cena_yen)) up_green = "#2ECC40" down_red = "#FF4136" if float(x1h_change) < 0: change_1h = down_red elif float(x1h_change) > 0: change_1h = up_green if float(x24h_change) < 0: change_24h = down_red elif float(x24h_change) > 0: change_24h = up_green if float(x7d_change) < 0: change_7d = down_red elif float(x7d_change) > 0: change_7d = up_green return render( request, 'watcher/home.html', { "change_1h": change_1h, "change_24h": change_24h, "change_7d": change_7d, 'cena': cena, 'cena_eur': cena_eur, 'cena_yen': cena_yen, 'market_cap': market_cap, '24h_volume': x24h_volume, '1h_change': x1h_change, '24h_change': x24h_change, '7d_change': x7d_change, 'price_btc': price_btc, 'rank': rank, "x1h_change": x1h_change, "x24h_change": x24h_change, "x7d_change": x7d_change })
def test_raise_error_unknown(): converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = "GBP" with assert_raises(UnknownCurrencyCodeError): converter.convert(currency, convert_to_code)
def test_diff_currency_code_that_passed_in(): converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'JPY' result = converter.convert(currency, convert_to_code) assert result == Currency(106, 'JPY')
def __init__(self, name): self.player_name = WorldOfGames.welcome(name) self.clear = "\n" * 1000 self.load_game = WorldOfGames.load_game() self.gamedifficulty = int(WorldOfGames.get_difficulty()) self.valuesdict = [None] * self.gamedifficulty self.userlist = [None] * self.gamedifficulty self.c = CurrencyConverter() self.current_usd_to_ils = self.c.convert(1, 'USD', 'ILS') # i use print here only for test # print (self.player_name+' choose game number '+str(self.load_game)+' with difficulty level '+str(self.gamedifficulty)) if (self.load_game == 2): self.lostorwon = GuessGame.play(self) if (self.lostorwon == 1): print('you win') else: print('you lose') elif (self.load_game == 1): self.lostorwon = MemoryGame.play(self, self.gamedifficulty) if (self.lostorwon == 1): print('you win') else: print('you lose') elif (self.load_game == 3): self.lostorwon = CurrencyRoulette.play(self, self.gamedifficulty) if (self.lostorwon == 1): print('you win') else: print('you lose') print('end')
def currency_converter(): amount = request.args.get('amount', default=None, type=float) input_currency = request.args.get('input_currency', default=None) output_currency = request.args.get('output_currency', default=None) if amount is None: return make_response("Amount arguments is missing !") if input_currency is None: return make_response("Input currency argument is missing!") converter = CurrencyConverter() input_currency = converter.convert_to_code(input_currency) if output_currency is not None: output_currency = converter.convert_to_code(output_currency) output = { 'input': { 'amount': amount, 'currency': input_currency }, 'output': output_currency } output = converter.compute(output) return make_response(jsonify(output), 200)
def format_price(self, price, fiat, symbol=True): """ Formats price under the desired fiat @param price - price to format @param fiat - desired fiat currency (i.e. 'EUR', 'USD') @param symbol - if True add currency symbol to fiat if False symbol will not be added @return - formatted price under fiat """ c = CurrencyConverter() ucase_fiat = fiat.upper() price = float(c.convert(float(price), "USD", fiat)) if symbol: if ucase_fiat in fiat_suffix: formatted_fiat = "{:,.6f} {}".format( float(price), fiat_currencies[ucase_fiat]) else: formatted_fiat = "{}{:,.6f}".format( fiat_currencies[ucase_fiat], float(price)) else: formatted_fiat = str(price) formatted_fiat = formatted_fiat.rstrip('0') if formatted_fiat.endswith('.'): formatted_fiat = formatted_fiat.replace('.', '') return formatted_fiat
def on_event(self, data): if data["type"] == "donation": try: sub_data = data["message"][0] amount = float(str(sub_data["amount"])) username = str(sub_data["from"]) currency = str(sub_data["currency"]) c = CurrencyConverter() log.info(username) amount = round(c.convert(amount, currency, "USD"), 2) with DBManager.create_session_scope() as db_session: user = User.find_by_user_input(db_session, username) if user is not None: log.info(f"User {user} donated ${amount}") HandlerManager.trigger("on_donate", user=user, amount=amount) except Exception as e: log.error(e) if "message" in data and "event" in data["message"]: if data["message"][ "event"] == "pop": # new song request pause : pause spotify username = data["message"]["media"]["action_by"] title = data["message"]["media"]["media_title"] HandlerManager.trigger("pause_spotify", title=title) elif data["message"]["event"] == "play": # on resume: HandlerManager.trigger("change_state", state=False) elif data["message"]["event"] == "pause": # on pause: HandlerManager.trigger("change_state", state=True) elif (data["message"]["event"] == "next" and data["message"]["media"] is None): # no new songs requested : resume spotify HandlerManager.trigger("resume_spotify")
def play(difficulty): game_res = False c = CurrencyConverter() curr_rate = c.convert(1, 'USD', 'ILS') rnd_num = random.randint(MIN_NUM, MAX_NUM) print("---------- Amount -------------------------------") print("Amount = " + str(rnd_num) + "$") rnd_amount = round(curr_rate * rnd_num, 2) print(str(rnd_amount) + " ILS") # gwt interval intv = get_money_interval(difficulty, rnd_amount) # ---------------------------------------------------- if len(intv) == 2: while True: # get user guess guess = get_guess_from_user() # check value if float(guess) >= float(intv[0]) and float(guess) <= float( intv[1]): print("You Won! In Interval range...") game_res = True break else: print("Wrong Guess = " + str(guess) + " ... Try again ...") else: print("Unexpected Error....Try Later") # ---------------------------------------------------- return game_res
def convertcal(amount, from_, to): c = CurrencyConverter(decimal=True) try: final = c.convert(amount, from_.upper(), to.upper()) return True, final except Exception as e: return False, e
def convert_currency(convert_to): c = CurrencyConverter(decimal=True) base = 1 try: return c.convert(base, 'USD', convert_to) except: return base
def total_currency_converter(user, object, accounts, profile_currency, year=None, month=None, category=None): total_sum = 0 converter = CurrencyConverter() for account in accounts: if not year and not month: filtered_objects = object.objects.filter(user=user, account=account) elif not category: filtered_objects = object.objects.filter(user=user, account=account, created_date__year=year, created_date__month=month) else: filtered_objects = object.objects.filter(user=user, account=account, created_date__year=year, created_date__month=month, category=category) total_filtered_objects = assembly(filtered_objects) total_sum += converter.convert(total_filtered_objects, account.currency, profile_currency) return round(total_sum, 2)
def test_converted_amount(self): success, result = CurrencyConverter().converted_amount('India', 25) self.assertTrue(success) self.assertEquals(result, '1500₹','Currency conversion is incorrect') self.assertEquals(result, '1584.25₹','Currency conversion is incorrect') success, result = CurrencyConverter().converted_amount('India', '25') self.assertFalse(success)
def __init__(self): super().__init__() self.c = CurrencyConverter() self.setWindowTitle("Convertisseur de devises") self.create_layout() self.handler()
def __init__(self, dataBaseCon, maxFeedBack, minFeedBack, maxSales, minSales, minWeekSales, minPrice, maxPrice, pagesToSearch, numPages, numThreads): self.dataBaseCon = dataBaseCon self.maxFeedBack = maxFeedBack self.minFeedBack = minFeedBack self.maxSales = maxSales self.minSales = minSales self.minWeekSales = minWeekSales self.minPrice = minPrice self.maxPrice = maxPrice self.linkList = [] self.resultLinks = [] self.ThreadNum = numThreads self.numPages = numPages # מס' עמודים לחיפוש פר לינק self.pagesToSearch = pagesToSearch self.currentDateStr = datetime.now().__format__('%b-%d-%y') self.currentDate = datetime.now() self.currencyCheck = CurrencyConverter() selectQuery = "SELECT Link FROM [Ebay].[dbo].[EbayData]" self.Tablelinks = [] for link in selectFromDB(self.dataBaseCon, selectQuery): self.Tablelinks.append(link[0]) self.Tablelinks = selectFromDB(self.dataBaseCon, selectQuery) self.createPagesLinks()
def send_invoice(user_id): user = User.get(user_id) violations = user.get_fines() title = 'Штрафы' if user.language_code == 'ru' else 'Fines' prices = [] description = '' currency = 'rub' if user.language_code == 'ru' else 'usd' converter = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') for violation in violations: label, datetime_native, fine = violation amount = int(converter.convert(fine, 'USD', 'RUB') * 100) if \ user.language_code == 'ru' else fine * 100 prices.append( LabeledPrice(label=f'{datetime_native} {label}', amount=amount)) description += f'{datetime_native} {label} ${fine}\n\n' bot.send_invoice( user_id, title=title, description=description, provider_token=provider_token, currency=currency, photo_url= 'https://safety4sea.com/wp-content/uploads/2016/06/fine-e1522744870402.png', photo_height=512, # !=0/None or picture won't be shown photo_width=512, photo_size=512, is_flexible=False, # True If you need to set up Shipping Fee prices=prices, start_parameter='fines-payment', invoice_payload='FINES PAYMENT')
def currency_converter(value, source, target): logging.debug('Currency converter started') source = source.upper() target = target.upper() result = 0.0 if hasattr(ssl, '_create_unverified_context'): logging.debug('SSL unverified context') ssl._create_default_https_context = ssl._create_unverified_context logging.debug('Value: {} - ' \ 'Source currency: {} - ' \ 'Target currency: {}'.format(value, source, target)) if (source not in 'VND' and target not in 'VND'): c = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') result = c.convert(value, source, target) else: url = 'https://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx' r = requests.get(url) if r.status_code == 200: root = ET.fromstring(r.content) for element in root: symbol = str(element.attrib.get('CurrencyCode')) if symbol in source: quote = float(element.attrib.get('Transfer')) result = value * quote if symbol in target: quote = float(element.attrib.get('Transfer')) result = value / quote else: logging.warning('Request time out.') return result
def _get_monthly_price(self, location, plan, size): """Translates a monthly cost value for a given adapter to a ServerSpec value.""" c = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') return c.convert(float(size.extra.get('monthly', 0) or 0), 'EUR', 'USD') or None
def test_convert_with_unknown_code_raises_error(): # Arrange converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'FOO' with assert_raises(UnknownCurrencyCodeError): converter.convert(currency, convert_to_code)
def test_convert_with_different_code_returns_converted_currency(): # Arrange converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'JPY' # Act result = converter.convert(currency, convert_to_code) # Assert assert result == Currency(120, 'JPY')
def test_convert_with_same_code_returns_itself(): # Arrange converter = CurrencyConverter(conversion_rates) currency = Currency(1, 'USD') convert_to_code = 'USD' # Act result = converter.convert(currency, convert_to_code) # Assert assert result == Currency(1, 'USD')
def parseAllCurrencies(self, inputCurrency, value, expectedCurrencies, expectedValues): converter = CurrencyConverter(useCache = True) jsonResult = converter.convertIntoJson(inputCurrency, None, 1) self.assertEqual(jsonResult['input']['amount'], 1) self.assertEqual(jsonResult['input']['currency'], inputCurrency) for index in range(len(expectedCurrencies)): expectedCurrency = expectedCurrencies[index] expectedValue = expectedValues[index] self.assertEqual(jsonResult['output'][expectedCurrency], expectedValue)
def currency_trans(self): c = CurrencyConverter() old_currency_unit = self.stock_info['currency_unit'] new_currency = 'SGD' try: self.stock_info['natural_currency'] = old_currency_unit self.stock_info['natural_price'] = self.stock_info['discount_price'] self.stock_info['natural_discount_price'] = self.stock_info['discount_price'] new_price = c.convert(float(self.stock_info['price']), old_currency_unit, new_currency) new_discount = c.convert(float(self.stock_info['discount_price']), old_currency_unit, new_currency) self.stock_info['price'] = new_price self.stock_info['discount_price'] = new_discount self.stock_info['currency_unit'] = new_currency except: pass
def main(): currency_dict = {'USD':1.0, 'EUR':1.14, 'JPY':0.009} #takes input in amount (needs to differentiate type from string IE $, € [option + shift + 2]) while True: user_amount = input("Please enter an amount to convert: ") if '$' in user_amount: code1 = 'USD' user_amount = user_amount.replace('$', '') break elif '€' in user_amount: code1 = 'EUR' user_amount = user_amount.replace('€', '') break elif '¥' in user_amount: code1 = 'JPY' user_amount = user_amount.replace('¥', '') break else: print("Please enter dollars, euros, or yen only!") continue user_amount = float(user_amount) currency_class_variable = Currency(code1, user_amount) print(str(currency_class_variable)) while True: code2 = input("Please enter a currency to convert to ($, €, ¥): ") #takes second input for conversion to another currency if code2 == '$': code2 = 'USD' break elif code2 == '€': code2 = 'EUR' break elif code2 == '¥': code2 = 'JPY' break else: print("Please enter dollars, euros, or yen only!") continue print(code2) currency_converter = CurrencyConverter(currency_dict) converted_currency = currency_converter.convert2(currency_class_variable, code2) converted_amount = converted_currency.amount print("The converted amount is: {} {}".format((float("{0:.2f}".format(converted_amount))), code2)) print('Current exchange rate: {}'.format(currency_converter.get_rate(currency_class_variable.code, code2)))
def test_convert(): rate_chart = CurrencyConverter({'USD': 1.0, 'EUR': .9, 'JPY': 106.18 }) amount1 = Currency('USD', 2) converted1 = rate_chart.convert(amount1, 'USD') amount2 = Currency('EUR', 1) converted2 = rate_chart.convert(amount2, 'EUR') amount3 = (2 * .9) # $2 to Euros converted3 = rate_chart.convert(Currency('USD', 2), 'EUR') amount4 = (400 * .0084) # ¥400 to Euros converted4 = rate_chart.convert(Currency('JPY', 400), 'EUR') assert converted1 == amount1 assert converted2 == amount2 assert converted3.value == amount3
def test_convert_one_currency_to_another(): currency = CurrencyConverter(4.0, 'USD') new_code = 'EUR' assert CurrencyConverter.convert(currency, new_code) == Currency(3.611448, 'EUR')
def test_convert_one_cunnecy_code_to_same_currency_code(): currency = Currency(4.0, 'USD') new_code = 'USD' assert CurrencyConverter.convert(currency, new_code) == Currency(4.0, 'USD')
def test_can_convert_currency_to_any_type_in_instance_of_CurrencyConverter(): currency_converter = CurrencyConverter({'USD' : 1, 'EUR' : 0.74}) assert currency_converter.convert(Currency(10,'USD'), 'EUR') == Currency(7.4, 'EUR')
def test_convert_to_same_currency(): converter = CurrencyConverter({'USD': 1.0, 'EUR': 0.74}) assert converter.convert(Currency('USD', 1), 'USD') == Currency('USD', 1)
def test_can_convert_currency_to_its_original_type(): currency_converter = CurrencyConverter({'USD' : 1, 'EUR' : 0.74}) assert currency_converter.convert(Currency(1,'USD'), 'USD') == Currency(1, 'USD')
def test_convert_to_different_currency_big_dict(): converter = CurrencyConverter(CURRENCY_CONVERSIONS) assert converter.convert(Currency('BBD', 2), 'GHS') == Currency('GHS', 3.969829297340214)
def test_convert_to_different_currency_small_dict(): converter = CurrencyConverter({'USD': 1.0, 'EUR': 0.74}) assert converter.convert(Currency('USD', 1), 'EUR') == Currency('EUR', 0.74)
def test_convert_to_unknown_currency(): converter = CurrencyConverter({'USD': 1.0, 'EUR': 0.74}) converter.convert(Currency('USD', 1), 'XXX')
def parseDataFromCache(self, inputCurrency, outputCurrency, value, expectedValue): converter = CurrencyConverter(useCache = True) jsonResult = converter.convertIntoJson(inputCurrency, outputCurrency, value) self.assertEqual(jsonResult['input']['amount'], value) self.assertEqual(jsonResult['input']['currency'], inputCurrency) self.assertEqual(jsonResult['output'][outputCurrency], expectedValue)
def test_convert_one_currency_to_another_non_usd(): currency1 = CurrencyConverter(4.0, 'EUR') new_code = 'JPY' assert CurrencyConverter.convert(currency1, new_code) == Currency(469.24557684341573, 'JPY')
def extract_Data_FromGoogle(GoogleStockURL): try: webPage = urlopen(GoogleStockURL) soup = BeautifulSoup(webPage, "html.parser") # HTML SPECIFIC CODE. NEEDS TO BE FIXED IF GOOGLE/YAHOO CHANGES HTML!!! #====================================================================== #Infer currency from finance stock page #GBX = penny sterling unless price has * divStrings = soup.find_all('div') CurrencyOnPage = "" for div in soup.find_all('div'): try: divContent = div.text #print(str(divContent)) if "Currency in GBX" in divContent: CurrencyOnPage = 'GBX' if "Currency in EUR" in divContent: CurrencyOnPage = 'EUR' if "Currency in GBP" in divContent: CurrencyOnPage = 'GBP' except: pass #Get daily volume day_vol = soup.find_all('td', attrs={"class": "val"}) try: day_vol = day_vol[3].contents[0] day_vol = day_vol.replace(',','').partition('/')[0] day_vol_Currency = CurrencyOnPage #check currency #check if day_vol is in GBX or GBP if ((CurrencyOnPage == 'GBX') and ("*" in day_vol)): #this means day_vol is in GBP day_vol_Currency = 'GBP' day_vol = day_vol.replace('*','') try: if "M" in day_vol: day_vol = float(day_vol.replace('M','')) * 1000000 else: day_vol = float(day_vol) #Convert currency to EUR if not already in EUR if day_vol_Currency == 'GBP': c = CurrencyConverter() day_vol = c.convert(day_vol, day_vol_Currency, 'EUR') if day_vol_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP day_vol = day_vol / 100 #Convert to EUR day_vol = c.convert(day_vol, 'GBP', 'EUR') except: day_vol = "Conversion Error with " + str(day_vol) except: day_vol = "No data." #====================================================================== #Get last price Lprice = soup.find(attrs={"class": "pr"}) #print(str(Lprice)) try: Lprice = Lprice.contents[1].contents[0] Lprice = Lprice.replace(',','') Lprice_Currency = CurrencyOnPage #check currency #check if day_vol is in GBX or GBP if ((CurrencyOnPage == 'GBX') and ("*" in Lprice)): #this means day_vol is in GBP Lprice_Currency = 'GBP' Lprice = Lprice.replace('*','') try: Lprice = float(Lprice) #Convert currency to EUR if not already in EUR if Lprice_Currency == 'GBP': c = CurrencyConverter() Lprice = c.convert(Lprice, Lprice_Currency, 'EUR') if Lprice_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP Lprice = Lprice / 100 #Convert to EUR Lprice = c.convert(Lprice, 'GBP', 'EUR') except: Lprice = "Conversion Error with " + str(Lprice) except: Lprice = "No data." #====================================================================== # calculate turnover. This is in EUR try: turnOver = Lprice * day_vol except: turnOver = "No data." except Exception as e: print("Error retreiving Google Finance webpage(s). Check connection. \n Try to change IP if problem persists. Error was: " + str(e)) day_vol = "Conn error." Lprice = "Conn error." turnOver = "Conn error." return [day_vol, Lprice, turnOver]
def extract_Data_FromYahoo(YahooStockURL): try: webPage = urlopen(YahooStockURL) soup = BeautifulSoup(webPage, "html.parser") # HTML SPECIFIC CODE. NEEDS TO BE FIXED IF GOOGLE/YAHOO CHANGES HTML!!! #====================================================================== #Infer currency from URL (assumes all symbols ending in .L are quoted in GBP) CurrencyOnPage = "" YahooSymbol = dataSrc.get_YahooSymbolFromURL(YahooStockURL) if YahooSymbol != "": if ".L" in YahooSymbol: CurrencyOnPage = 'GBX' if ".AS" in YahooSymbol: CurrencyOnPage = 'EUR' #Get daily volume #Format to look for in HTML is: #<b data-sq="AAAP.L:volume" class="Fl-end Fw-b">75.0k</b> data_sq_val = YahooSymbol + ":volume" day_vol = soup.find('b', attrs={"data-sq": data_sq_val}) #Check if data was extracted/found #if ((len(day_vol) > 1) and ('-' not in str(day_vol))): if ((day_vol != None) and ("-" not in day_vol)): day_vol = day_vol.contents[0] #day_vol = day_vol.replace(',','').partition('/')[0] day_vol_Currency = CurrencyOnPage try: if (("m" in day_vol) or ("k" in day_vol)): if "m" in day_vol: day_vol = float(day_vol.replace("m",'') + "0") * 1000000.0 elif "k" in day_vol: day_vol = float(day_vol.replace("k",'')) * 1000.0 else: day_vol = float(day_vol) #Convert currency to EUR if not already in EUR if day_vol_Currency == 'GBP': c = CurrencyConverter() day_vol = c.convert(day_vol, day_vol_Currency, 'EUR') if day_vol_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP day_vol = day_vol / 100.0 #Convert to EUR day_vol = c.convert(day_vol, 'GBP', 'EUR') except Exception as e: day_vol = "Conversion Error with " + str(day_vol) + " " + str(e) else: day_vol = "No data." #====================================================================== #Get last price #Extract from (example): """ <td class="Ta-start Pstart-8 P-4 Pend-8"> <b class="C-darkGrey">Prev Close</b> <b class="Fl-end Fw-b">0.57</b> </td> """ Lprice = soup.find_all('b') try: Lprice = Lprice[3].contents[0] Lprice = Lprice.replace(',','') Lprice_Currency = CurrencyOnPage try: Lprice = float(Lprice) #Convert currency to EUR if not already in EUR if Lprice_Currency == 'GBP': c = CurrencyConverter() Lprice = c.convert(Lprice, Lprice_Currency, 'EUR') if Lprice_Currency == 'GBX': c = CurrencyConverter() #convert GBX to GBP Lprice = Lprice / 100 #Convert to EUR Lprice = c.convert(Lprice, 'GBP', 'EUR') except: Lprice = "Conversion Error with " + str(Lprice) except: Lprice = "No data." #====================================================================== # calculate turnover. This is already in EUR try: turnOver = Lprice * day_vol except: turnOver = "No data." except Exception as e: print("Error retreiving Yahoo Finance webpage(s). Check connection. \n Try to change IP if problem persists. Error was: " + str(e)) day_vol = "Conn error." Lprice = "Conn error." turnOver = "Conn error." return [day_vol, Lprice, turnOver]