def returnConversion(location): c = CurrencyRates() with open('common_currencies.json') as currency_file: currencies = json.load(currency_file) for code, info in currencies.iteritems(): if info['capital'] == location: if code == 'EUR': return 1. conversion = c.get_rate(code, 'EUR') break else: conversion = 1. return conversion
def __init__(self): self.df_path = 'Pickles/classifiedDF.pickle' self.df = pd.read_pickle(self.df_path) self.c = CurrencyRates() self.funding_overview = None self.funding_overview_df = None self.uni_funding_dict = None self.GBP_groups = ['EPSRC', 'Industrial'] self.EUR_groups = ['5GPPP', 'FIRE', 'Other EU']
def do_update(self): from forex_python.converter import CurrencyRates cr = CurrencyRates() log.info("fetching currency update %s to %s" % (self.conv_from, self.conv_to)) try: conv = cr.get_rate(self.conv_from, self.conv_to) self.text = "1 %s = %s%.2f %s" % ( self.conv_from, self.get_color_compare( conv, self.last_conv), conv, self.conv_to) self.last_conv = conv except requests.exceptions.RequestException as e: logging.warning("couldn't get update: %s" % e)
def create_europe_gfinity_friday(self, contents): contents = self.create_tournament(contents) currency_converter = CurrencyRates() gbp_exchange_rate = currency_converter.get_rate('GBP', 'USD') contents = contents.replace("VOGANBOT_PRIZE_1", str(200 * gbp_exchange_rate)) contents = contents.replace("VOGANBOT_PRIZE_2", str(50 * gbp_exchange_rate)) contents = contents.replace("VOGANBOT_TOTAL_PRIZE", str(250 * gbp_exchange_rate)) return contents
def get_conversion(): try: c = CurrencyRates() current_rate = c.get_rate('USD', 'CAD') except: # Where USD is the base currency you want to use url = 'https://api.exchangerate-api.com/v4/latest/USD' # Making our request response = requests.get(url) data = response.json() current_rate = data['rates']['CAD'] return float(current_rate)
def convert(amount, input_currency, output_currency): input_currency_code = get_currency_code(input_currency) if input_currency_code is None: # Input currency code was not found - unknown currency raise UnknownCurrencyError if output_currency is not None: output_currency_code = get_currency_code(output_currency) if output_currency_code is None: # Output currency code was not found - unknown currency raise UnknownCurrencyError currency_data = [{'cc': output_currency_code}] else: # Getting currency data from file currency_data = get_currency_data() c = CurrencyRates() b = BtcConverter() output_currencies = dict( ) # Dictionary to store converted amounts for each currency # Converting currency for item in currency_data: if item['cc'] == input_currency_code: # Out currency == in currency if output_currency is None: continue else: raise SameCurrencyError try: if input_currency_code == "BTC": # Bitcoin is input currency output_currencies[item['cc']] = round( b.convert_btc_to_cur(amount, item['cc']), 2) elif item['cc'] == "BTC": # Bitcoin is output currency output_currencies[item['cc']] = round( b.convert_to_btc(amount, input_currency_code), 5) else: # Other currencies than bitcoin output_currencies[item['cc']] = round( c.convert(input_currency_code, item['cc'], amount), 2) except RatesNotAvailableError: if output_currency is None: # Output currency not entered, currencies without available rates are skipped pass else: # Output currency entered => not available currency rate yields error raise RatesNotAvailableError output_data = dict() output_data['input'] = {'amount': amount, 'currency': input_currency_code} output_data['output'] = output_currencies return json.dumps(output_data, indent='\t')
def load_wallstreet(self): with pymongo.MongoClient('localhost', 27017) as client: db = client['drug_database'] table = db['wallstreet'] docs = list(table.find()) docs = add_scraping_session(docs) docs = {(doc['vendor'], doc['title'], doc['scraping_session'], doc['price']): doc for doc in docs}.values() #remove duplicates counts = sorted(Counter(d['scraping_session'] for d in docs).items()) bad_dates = [date for date, count in counts if count < 3200] docs = [d for d in docs if d['scraping_session'] not in bad_dates] c = CurrencyRates() find_unit = re.compile(r'(\d+\.?\d*)\s*({})'.format('|'.join(self.units)), re.IGNORECASE) find_multi = re.compile(r'(\d+)\s*x', re.IGNORECASE) for doc in docs: del doc['_id'] doc['market'] = 'wallstreet' doc['ships_from'] = ' '.join(s.replace('Ships from:', '').strip() for s in doc['ships_from'].split('\n')).strip() stripped = ' '.join(s.replace('Only ships to certain countries', '').strip() for s in doc['ships_to'].split('\n')).strip() doc['ships_to'] = [s.replace('Ships Worldwide', 'WW').replace('WW WW', 'WW').strip() for s in stripped.split(',')] match = find_unit.search(doc['title']) doc['price_unit'] = doc['price_unit'].lower().strip().replace('/', '') if doc['price_unit'] == 'piece': doc['price_unit'] = match.group(2).lower() if match else None multi = find_multi.search(doc['title']) doc['amount'] = float(match.group(1)) if match and float(match.group(1)) != 0 else 1 if multi and int(multi.group(1)) != 0: doc['amount'] *= int(multi.group(1)) is_dollar = '$' in doc['price'] if doc['price_unit'] not in self.gram_factors: self.bad_docs.append(doc) else: doc['price'] = to_float(doc['price'].strip('$').strip('€')) / doc['amount'] / self.gram_factors[doc['price_unit']] doc['date_mid'] = dt.datetime.combine(doc['scraping_session'].date(), dt.datetime.min.time()) # transfer dates to midnight if is_dollar: date = doc['date_mid'] if not date in self.rates: self.rates[date] = c.get_rate('USD', 'EUR', date) doc['price'] *= self.rates[date] self.docs.append(doc)
def get_currency(list_codes, sleeping=0): print('Lazy-search for real time rates') c = CurrencyRates() rate_matrix = np.zeros((len(list_codes), len(list_codes))) for n, currency in enumerate(list_codes): print(f'Rate {n+1} out of {len(list_codes)}') for m, other_currency in enumerate(list_codes): rate = c.get_rate(currency, other_currency) time.sleep(sleeping) rate_matrix[m][n] = rate df_rates = pd.DataFrame(rate_matrix, index=list_codes, columns=list_codes) return df_rates
def get_options(cls): browser = cls._create_browser() browser.open(cls.OPTIONS_URL) soup = browser.get_current_page() p = soup.select("p.hero-description") string = p[1].get_text() # Calculate the price in USD eur = float(string[string.index("€") + 1:string.index("/")]) price = round(CurrencyRates().convert("EUR", "USD", eur), 2) name, _ = cls.get_metadata() option = VpnOption(name, "OpenVPN", price, sys.maxsize, sys.maxsize) return [option]
def RealTimeCurrencyConversion(): from forex_python.converter import CurrencyRates c = CurrencyRates() from_currency = variable1.get() to_currency = variable2.get() new_amount = c.convert(from_currency, to_currency, float(Amount1_field.get())) # insert method inserting the # value in the text entry box. new_value = str(new_amount) Amount2_field.insert(0, new_value)
def load_currency(self, input_amount, input_curr, output_curr): self.input['amount'] = input_amount self.input['currency'] = input_curr self.output = dict() currency_rates = CurrencyRates() if output_curr == 'ALL' or output_curr == 'None': self.output = dict(currency_rates.get_rates(input_curr)) self.output.update( (result_key, result_value * input_amount) for result_key, result_value in self.output.items()) else: self.output[output_curr] = currency_rates.get_rate( input_curr, output_curr) * input_amount
def play_me(difficult): c = CurrencyRates() convert = c.get_rate('USD', 'ILS') d = int(difficult) interval = get_money_interval() aaa = get_guess_from_user_currency(interval) conversion = float(convert) * int(interval) low_interval = (int(conversion) - (5 - d)) high_interval = (int(conversion) + (5 - d)) if high_interval >= int(aaa) and int(aaa) >= low_interval: print(True) score_calc(difficult) else: print(False)
def currency_Exchange(country, visa_list) -> list: """ Pulls the currency data """ final_list = [] c = CurrencyRates() for visa in visa_list: symbol = get_currency(visa) try: rate = c.get_rate(country, symbol) except Exception: rate = "??" final_list.append([visa, str(rate)]) return final_list
def __init__(self, loc='20211220.csv'): dt = loc.split('.')[-2] dt = dt if '/' not in dt else dt.split('/')[-1] self.yr, self.mth, self.day = int(dt[:4]), int(dt[4:6]), int(dt[6:]) self.c = CurrencyRates() self.cryptos = ['BTC', 'ETH'] df = pd.read_csv(loc) arr = [] for _, row in df.iterrows(): arr.append([ row['bank'], self._2usd(row['amount'], row['currency']), row['currency'] ]) self.df = pd.DataFrame(arr, columns=['bank', 'usd', 'orig'])
def _parse_kvm_option(plan, name): elements = plan.findAll("div", {'class': 'info'}) eur = float(plan.find('div', {'class': 'plans-price'}).span.text.replace('\u20AC', '')) option = VpsOption( name=name, storage=elements[0].text.split(' GB')[0], cores=elements[1].text.split(' vCore')[0], memory=elements[3].text.split(' GB')[0], bandwidth='unmetered', connection=int(elements[4].text.split(' GB')[0]) * 1000, price=round(CurrencyRates().convert("EUR", "USD", eur), 2), purchase_url=plan.a['href'], ) return option
def db_price_func(stock_ticker): """ This function provides most recent price of the given stock. Args: stock_ticker: Stock Ticker Returns: Latest price of the given stock (in $). """ stock_price = float(si.get_live_price(stock_ticker)) if ".NS" in stock_ticker or ".BO" in stock_ticker: stock_price = stock_price / CurrencyRates().get_rate("USD", "INR") return stock_price
def combine_data(current_holdings_df, api_data_return): """ Function to combine the data for the book values in the original Excel workbook (holdings.xlsx) and the data from the IEX Cloud API, Yahoo Finance API and Forex API. Parameters ---------- current_holdings_df : dict dictionary of the Excel sheets (keys) and the associated data rows appearing on that sheet (values). The values are key:value pairs, with the key being the column header and the value being the corresponding data for that row. api_return_data : dict dictionary of the Excel sheets (keys) and the associated data rows appearing on that sheet (values). The values are key:value pairs, with the key being the column header and the value being the corresponding data for that row. Returns ------- combined_holdings_dict : dict dictionary of the combined data. """ combined_holdings_dict = api_data_return for keys, values in current_holdings_df.items(): for key_part, value_part in values.items(): temp = [] if key_part == 'purchase_date' or key_part == 'book_price' or key_part == 'purchase_currency' or key_part == 'qty': for i in value_part.values(): temp.append(i) combined_holdings_dict[keys][key_part] = temp if key_part == 'purchase_date': temp_FX = [] for i in value_part.values(): date_obj = i.to_pydatetime() USD_CAD_purchase = CurrencyRates() USD_CAD_purchase = USD_CAD_purchase.get_rate( 'USD', 'CAD', date_obj) temp_FX.append(USD_CAD_purchase) combined_holdings_dict[keys][ 'fx_USDCAD_purchase'] = temp_FX return combined_holdings_dict
def index(): c = CurrencyRates() btc_converter = BtcConverter() price_json = c.get_rates('INR') result = [None, None, None] if (request.method == 'POST'): stock_name = request.form['stock_name'] if (stock_name != ""): result = callback(stock_name) else: result = [None, None, None, None] prices = [] for key, value in price_json.items(): prices.append((key, value, btc_converter.get_latest_price(key))) print('No of Supported Currencies: ', len(price_json), '||||File Type: ', type(price_json)) legend = 'BitCoin Price Index' temperatures = [ 73.7, 73.4, 73.8, 72.8, 68.7, 65.2, 61.8, 58.7, 58.2, 58.3, 60.5, 65.7, 70.2, 71.4, 71.2, 70.9, 71.3, 71.1 ] times = [ time(hour=11, minute=14, second=15), time(hour=11, minute=14, second=30), time(hour=11, minute=14, second=45), time(hour=11, minute=15, second=00), time(hour=11, minute=15, second=15), time(hour=11, minute=15, second=30), time(hour=11, minute=15, second=45), time(hour=11, minute=16, second=00), time(hour=11, minute=16, second=15), time(hour=11, minute=16, second=30), time(hour=11, minute=16, second=45), time(hour=11, minute=17, second=00), time(hour=11, minute=17, second=15), time(hour=11, minute=17, second=30), time(hour=11, minute=17, second=45), time(hour=11, minute=18, second=00), time(hour=11, minute=18, second=15), time(hour=11, minute=18, second=30) ] links = ['a', 'b', 'c'] return render_template('index.html', values=temperatures, labels=times, legend=legend, links=links, current_prices=prices, result=result)
def findRate(self): c = CurrencyRates() print('hi') currency = str(self.comboBox.currentText()) currency2 = str(self.comboBox_2.currentText()) currentDay = datetime.now().day currentMonth = datetime.now().month currentYear = datetime.now().year print('hello') new2 = float(self.plainTextEdit.toPlainText()) print(new2) timing = datetime(2016, 1, 1, 18, 36, 28, 151012) print(timing) exchange = c.convert(currency, currency2, new2, timing) self.textEdit.setText(str(exchange))
def currency_nxgraph(list_codes, sleeping=0, adjmatrix=False): print('Lazy-search for real time rates') c = CurrencyRates() d = {} for currency in list_codes: print(f'Checking for {currency}') d[currency] = {} remaining_codes = [i for i in list_codes if i not in list(d.keys())] for other_currency in remaining_codes: log_rate = np.log(c.get_rate(currency, other_currency)) d[currency][other_currency] = {} d[currency][other_currency]['weights'] = log_rate time.sleep(0.5) G = nx.from_dict_of_dicts(d) return G
async def conversor(ctx, moeda1, moeda2, quantidade=None): """Vê o valor da moeda 1 em moeda 2""" try: channel = ctx.channel await channel.trigger_typing() c = CurrencyRates() msg = c.get_rate(f'''{moeda1.upper()}''', f'''{moeda2.upper()}''') if quantidade is None: await ctx.send('Esse é o valor da cotacao atual do ``{}`` em ``{}``: **{}**'.format(moeda1.upper(), moeda2.upper(), msg)) else: msg = msg * quantidade await ctx.send('Esse é o valor de {} ``{}`` em ``{}``: **{}**'.format(quantidade, moeda1.upper(), moeda2.upper(), msg)) except: msg = await ctx.send('Tente utilizar o codigo de uma moeda existente. **Por exemplo: $conversor usd brl**') await msg.add_reaction('❤')
def findVolatility(self): currency1 = str(self.comboBox_7.currentText()) currency2 = str(self.comboBox_8.currentText()) startYear = str(self.comboBox_9.currentText()) endYear = str(self.comboBox_10.currentText()) c = CurrencyRates() listX = [] for x in range(int(startYear), int(endYear) + 1): for y in range(1, 13): timing = datetime(x, y, 1, 18, 36, 28, 151012) exchange = c.convert(currency1, currency2, 1, timing) listX.append(exchange) print(listX) v = statistics.stdev(listX) self.textEdit_3.setText(str(v))
def calculateNets(df, Currency, session_id=session_id): from forex_python.converter import CurrencyRates c = CurrencyRates().get_rate('USD', Currency) df['upfrontCommissionAmount'] = df['upfrontCommission'] / 100 * df[ 'baseFare'] df['backendCommissionAmount'] = df['backendCommission'] / 100 * df[ 'baseFare'] df['segmentEarningsAmount'] = (df['segmentEarnings'] * c) * df['numberOfSegments'] df['netPrice'] = round( df['totalPrice'] - (df['upfrontCommissionAmount'] + df['backendCommissionAmount'] + df['segmentEarningsAmount']), 2) return df
def index(request): """ This is the view which represents the dashboard page. It indexes every other app on the platform :param request: Django request :return: redirect to dashboard """ table = boto3.resource('dynamodb', region_name='us-east-2').Table handle_auth(request, table) for coin_id in range(1, 6): coin = shortcuts.get_object_or_404(CoinPrices, pk=coin_id) if is_crypto(coin_id): curr_price = CryptoApi.get_prices(str(coin.ticker), "usd")['last'] CoinPrices.objects.filter(pk=coin_id).update( current_price=curr_price) else: last_price = CurrencyRates().get_rates('USD')['GBP'] CoinPrices.objects.filter(pk=5).update(current_price=last_price) response, response_charts = get_response_data(coin, coin_id, table) json_data = json.loads((json.dumps(response['Item'], indent=4, cls=DecimalEncoder))) json_data_charts = json.loads((json.dumps(response_charts['Item'], indent=4, cls=DecimalEncoder))) update_current_trend(coin, coin_id, json_data, json_data_charts) all_coins = CoinPrices.objects.all() for c in all_coins: sentiment = sum(Scraper.analyze_tweets_numerical(c.ticker)[0:3]) CoinPrices.objects.filter(ticker=c.ticker).update( sentiment_score=round(sentiment, 2)) tables.RequestConfig(request).configure(CoinTable(all_coins)) return shortcuts.render( request, 'dashboard/index.html', { 'all_coins': all_coins, 'table': table, 'equity': round(CryptoApi.get_equity(), 2) })
def get_currencies_range(since_date, to_date, step=1): c = CurrencyRates() currencies, dates = [], [] time_delta = dt.timedelta(days=step) index = 0 while since_date < to_date: try: currency = c.get_rates("USD", since_date) currencies.append(currency) dates.append(since_date) since_date = since_date + time_delta print(index, currencies[index], since_date, to_date) index += 1 except: pass return currencies, dates
def convert(): c = CurrencyRates() value = amountInput.get() fromCurrency = in1.get() toCurrency = in2.get() if value == '': messagebox.showerror('Error', 'please enter value you want to convert it') elif (fromCurrency == "Select" or toCurrency == "Select"): messagebox.showerror('Error', 'please select option') else: res = c.convert(fromCurrency, toCurrency, float(value)) result = float('{:.4f}'.format(res)) #print(result) output.delete(0, END) output.insert(0, str(result))
def __init__(self, account, instrument, mode, quantity, margin): self.account = account self.instrument = instrument self.mode = mode self.quantity = quantity self.open_price = account.price_tables[instrument][INVERTED_MODE[ mode.value]] self.target_price = account.price_tables[instrument][mode.value] self.spread = abs(self.open_price - self.target_price) self.margin = margin c = CurrencyRates() eur_mult = c.get_rate('EUR', instrument.value[:3]) self.conv_rate = eur_mult * \ c.get_rate(instrument.value[:3], instrument.value[3:]) self.used_funds = margin * quantity / \ self.conv_rate * self.target_price
def RealTimeCurrencyConversion(): c = CurrencyRates() from_currency = FromCurrency_option.get() to_currency = ToCurrency_option.get() if (value.get() == ""): tkinter.messagebox.showerror("Error", "Amount not entered") elif (from_currency == "Select" or to_currency == "Select"): tkinter.messagebox.showerror("Error", "Currency not selected") else: new_amt = c.convert(from_currency, to_currency, float(value.get())) new_amount = float("{:.4f}".format(new_amt)) output.insert(0, str(new_amount))
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 get_coinbase_values(): """Get totals for each crypto from binance and convert to USD/GBP""" mydict = lambda: defaultdict(mydict) result = mydict() currency = CurrencyRates() all_accounts = {} with restrict_timeout(5, name="coinbase accounts"): # allow to run for only 5 seconds all_accounts = CLIENT.get_accounts() if not all_accounts: raise ReadTimeout json_accounts = json.loads(str(all_accounts)) gbp_totals = 0 usd_totals = 0 btc_totals = 0 rates = CLIENT.get_exchange_rates()["rates"] for account in json_accounts["data"]: if "0.00" not in account["balance"]["amount"]: #if account has a balance current_count = account["balance"]["amount"] # count of current currency result["coinbase"][account["currency"]]["count"] = current_count # amount in GBP current_gbp = account["native_balance"]["amount"] gbp_totals += float(current_gbp) result["coinbase"][account["currency"]]["GBP"] = current_gbp # amount in USD current_usd = float(currency.get_rate("GBP", "USD")) * float(current_gbp) usd_totals += float(current_usd) result["coinbase"][account["currency"]]["USD"] = current_usd # amount in BTC current_btc = current_count if account["currency"] == "BTC" else \ float(current_usd) * float(rates["BTC"]) # USD -> BTC btc_totals += float(current_btc) result["coinbase"][account["currency"]]["BTC"] = current_btc result["coinbase"]["TOTALS"]["BTC"] = btc_totals result["coinbase"]["TOTALS"]["USD"] = usd_totals result["coinbase"]["TOTALS"]["GBP"] = gbp_totals result["coinbase"]["TOTALS"]["count"] = "" #print json.dumps(json_accounts["data"][3]) return default_to_regular(result)