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 get_rate(conn): """ 美元汇率查看 :param conn: :return: """ now = datetime.datetime.now() current_time = now.strftime("%Y-%m-%d %H:%M:%S") stamp_current_time = datetime.datetime.strptime(current_time, '%Y-%m-%d %H:%M:%S') c = CurrencyRates() c.get_rates('USD') # 查看美元最新汇率 stock_price = c.get_rate('USD', 'CNY') # 人民币汇率 stock_time = str(current_time) stock_name = '人民币汇率' stock_applies = None spider_data = stamp_current_time # 更新美元汇率 sql_update = """ UPDATE public.stock_code SET stock_time = %s, spider_data = %s, stock_name= %s, stock_price= %s, stock_applies= %s WHERE stock_name = '人民币汇率' """ sql_params = [ stock_time, spider_data, stock_name, stock_price, stock_applies ] logger.debug(sql_update) logger.debug(sql_params) execute_sql(conn, sql_update, sql_params)
def get_currency_rates(currency): """ The flask API for getting the rate of the currency. :param currency: :return: """ cur_rates_obj = CurrencyRates() target_cur = request.args.get('target') finding_date = request.args.get('date') if currency and target_cur and finding_date: date_obj = datetime.datetime.strptime(finding_date, '%d-%m-%Y,%H:%M:%S') rate_value = cur_rates_obj.get_rate(currency, target_cur, date_obj) elif currency and target_cur and not finding_date: rate_value = cur_rates_obj.get_rate(currency, target_cur) elif currency and not target_cur and finding_date: date_obj = datetime.datetime.strptime(finding_date, '%d-%m-%Y,%H:%M:%S') rate_value = cur_rates_obj.get_rates(currency, date_obj) else: rate_value = cur_rates_obj.get_rates(currency) return jsonify({ 'source_currency': currency, 'exchange_value': rate_value, 'status_code': 200 })
class TestGetRates(TestCase): """ Test get_rates with valid(ex: USD) and invalid(ex: XYZ) currency code """ def setUp(self): self.c = CurrencyRates() def test_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 float value self.assertTrue(isinstance(all_rates.get('INR'), float)) def test_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 float value self.assertTrue(isinstance(all_rates.get('INR'), float)) def test_get_rates_invalid_code(self): self.assertRaises(RatesNotAvailableError, self.c.get_rates, '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 inputCurrency(self): c = CurrencyRates() x = c.get_rates('USD') for key in x: self.comboBox.addItem(str(key)) self.comboBox_2.addItem(str(key)) self.comboBox_3.addItem(str(key)) self.comboBox_4.addItem(str(key)) self.comboBox_7.addItem(str(key)) self.comboBox_8.addItem(str(key)) self.comboBox_11.addItem(str(key)) self.comboBox_12.addItem(str(key)) self.comboBox_13.addItem(str(key)) self.comboBox_14.addItem(str(key)) self.comboBox.addItem(str('USD')) self.comboBox_2.addItem(str('USD')) self.comboBox_3.addItem(str('USD')) self.comboBox_4.addItem(str('USD')) self.comboBox_7.addItem(str('USD')) self.comboBox_8.addItem(str('USD')) self.comboBox_11.addItem(str('USD')) self.comboBox_12.addItem(str('USD')) self.comboBox_13.addItem(str('USD')) self.comboBox_14.addItem(str('USD'))
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 fetch_exchange_rates( target_currency: str, currencies: Iterable[str], amount: float = 1.0, bitcoin_proxy: str = 'USD', ) -> Dict[str, Optional[float]]: """ Given an amount and a base currency, returns the exchange rates for a set of currencies. """ rates: Dict[str, Optional[float]] = {} rates_select: Dict[str, Optional[float]] = {} is_bitcoin: bool = False # Special case if base currency is BitCoin if target_currency == 'BTC': is_bitcoin = True target_currency = bitcoin_proxy # Instantiate converter converter = CurrencyRates() converter_btc = BtcConverter() # Get rates for base currency try: rates = converter.get_rates(target_currency) except ConnectionError: logger.warning( f"Could not connect to currency rates service. No exchange rates " \ f"available." ) return rates_select # Get Bitcoin rate for base currency try: rates['BTC'] = converter_btc.convert_to_btc(amount=amount, currency=bitcoin_proxy) except ConnectionError: logger.warning( f"Could not connect to currency rates service. No BitCoin " \ f"exchange rate available." ) return rates_select # Select rates for currency in currencies: if currency in rates: rates_select[currency] = rates[currency] else: rates_select[currency] = None # Convert to base BitCoin if BitCoin was base currency if is_bitcoin: rate_btc = rates_select['BTC'] for currency in rates_select.keys(): if rates_select[currency]: rates_select[currency] = rates_select[currency] / rate_btc return rates_select
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 display_for_currency(request, name="USD"): c = CurrencyRates() c = c.get_rates(name) return render(request, 'currency/currency.html', { 'currency': name, 'rates': c })
def main(): c = CurrencyRates() today = date.today() currency = "CNY" csvfile = join(DIR, currency + ".csv") pre = None if exists(csvfile): with open(csvfile) as f: for i in f: i = i.strip("\n") if i: pre = i if not pre: pre = date(2008, 1, 1) else: pre = date(*map(int, pre.split(",", 1)[0].split("-"))) if today > pre: with open(csvfile, "a") as f: while today > pre: pre = pre + timedelta(days=1) cny = c.get_rates('USD', pre)['CNY'] f.write(f"{str(pre)},{cny}\n") f.flush() print(pre, cny)
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 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_check(): source = [ 'GBP', 'HKD' 'IDR', 'ILS', 'DKK', 'INR', 'CHF', 'MXN', 'CZK', 'SGD', 'THB', 'THB', 'HRK', 'EUR', 'MYR', 'NOK', 'CNY', 'BGN', 'PHP', 'PLN', 'ZAR', 'CAD', 'ISK', 'BRL', 'RON', 'NZD', 'TRY', 'JPY', 'RUB', 'KRW', 'USD', 'AUD', 'HUF', 'SEK' ] origin = request.form['origin'].upper() travel = request.form['travel'].upper() amount = int(request.form['amount']) print(origin not in source) # print(origin) # print(type(origin)) if origin not in source: flash(f'{origin} input not valid') return redirect('/') elif travel not in source: flash(f'{travel} input not valid') return redirect('/') else: c = CurrencyRates() currency_change = c.get_rates(origin)[travel] currency_final = currency_change * amount c_code = CurrencyCodes() currency_code = c_code.get_symbol(travel) return render_template('currency.html', origin=origin, travel=travel, amount=amount, currency_code=currency_code, currency_final=currency_final)
def parse_currency(currencyname : str) -> float: """ Функция принимает на вход название валюты Функция возвращает ее стоимость (по отношению к USD) """ converter = CurrencyRates() currency = converter.get_rates(currencyname)['RUB'] return currency
def getCurrencyList(): c = CurrencyRates() currencies = [] curRates = c.get_rates('GBP') for item in curRates.keys(): currencies.append(item) currencies.append('GBP') return sorted(currencies)
def get_exchange_rate(curr_from, date_str=None): rates = CurrencyRates() date_of_rates = datetime.strptime( date_str, '%Y-%m-%d') if date_str else datetime.now() try: result = rates.get_rates(curr_from, date_of_rates) except Exception as e: result = None return result
def searching_conversion(self, args): """ According to input parameters this method finds out exchange rate(s) between currency/currencies. :param args: Namespace with arguments from command line or from z web api url :return: We return conversion from input currency to output currency/currencies in string prepared for json """ curr_rates = CurrencyRates() # Test if input currency is entered as symbol. If yes, we find out currency code transformed_input_code = self.get_code_from_symbol(args.input_currency) if transformed_input_code: args.input_currency = transformed_input_code # Is output currency entered? if args.output_currency: # Test if input currenci is entered as symbol. If yes, we find out currency code transformed_output_code = self.get_code_from_symbol( args.output_currency) if transformed_output_code: args.output_currency = transformed_output_code try: # We try to find out exchange rate. If currency not known, throw an error. output_amount = curr_rates.convert(args.input_currency, args.output_currency, args.input_amount) except RatesNotAvailableError: return f'{args.input_currency} or {args.output_currency} is not known currency.' adjusted_output_amount = { args.output_currency: round(output_amount, 3) } else: try: # We try to find out exchange rate. If currency not known, throw an error. output_amount_dict = curr_rates.get_rates(args.input_currency) except RatesNotAvailableError: return f'{args.input_currency} is not known currency.' adjusted_output_amount = { key: round(value * args.input_amount, 3) for key, value in output_amount_dict.items() } # Complete string with output data res = { 'input': { 'amount': args.input_amount, 'currency': args.input_currency }, 'output': adjusted_output_amount } return res
def update_rates(): c = CurrencyRates() rates = c.get_rates('USD') current_rates = Currency.objects.all() for currency in current_rates: currency.usd_price = rates.get(currency.name) currency.save() with open('test.txt', 'a+') as test_file: test_file.write(str(datetime))
def getstockValue(stock, country): df = investpy.get_stock_recent_data(stock=stock, country=country, as_json=False, order='ascending') a = df.last('1D')['Close'].item() b = df.last('1D')['Currency'].item() c = CurrencyRates() try: rate = c.get_rates(b)['EUR'] return a*rate except: return a
def supported_currencies(self): currency_rates = CurrencyRates() # get all supported currencies from Forex codes = dict(currency_rates.get_rates('USD')) symbols = CurrencyCodes() codes['USD'] = '' # get symbols for supported currencies for code in codes.keys(): codes[code] = symbols.get_symbol(code) return codes
async def ccyconvert(ctx, amount: float, ccy_pair: str): ccy_pair = ccy_pair.upper() if len(ccy_pair) == 6: cr = CurrencyRates() rate = cr.get_rates(ccy_pair[3:])[ccy_pair[:3]] await ctx.send('```{} {} is {} {}.```'.format( ccy_pair[:3], round(amount, 2), ccy_pair[3:], round((amount * 1 / rate), 2)))
def get_rates(pool): c = CurrencyRates() rates = c.get_rates("USD") pipe = pool.pipeline() for (currency, value) in rates.items(): pipe.set(currency, 1 / value) pipe.set('USD', 1) pipe.execute()
def background(self): ''' possible_rates = ['GBPJPY=X','GBPAUD=X','GBPCNY=X','GBPBTC=X','GBPBND=X','GBPMXN=X','GBPCLP=X','GBPETB=X','GBPTRY=X','GBPCHF=X','GBPCAD=X','GBPXAU=X','BZJ16.NYM'] possible_symbols_before = [u'¥', 'A$|', u'CN¥|', u'฿', 'B$|', 'MX$|', 'CL$|', 'ETB|', u'₺', 'CHF|', 'C$|', '',''] possible_symbols_after = ['','','','','','','','','','','',u'㎎ gold','L oil'] possible_multiple = [1,1,1,1000,1,1,1,1,1,1,1,31103,1] possible_format = ['{:.0f}','{:.2f}','{:.2f}','{:.2f}','{:.2f}','{:.2f}','{:.0f}','{:.2f}','{:.2f}','{:.2f}','{:.2f}','{:.0f}','{:.2f}'] from random import randint random_rate1 = randint(0,len(possible_rates)-1) random_rate2 = random_rate1 random_rate3 = random_rate1 while random_rate2 == random_rate1: random_rate2 = randint(0,len(possible_rates)-1) while random_rate3 == random_rate1 or random_rate3 == random_rate2: random_rate3 = randint(0,len(possible_rates)-1) ask_for_rates = ['GBPUSD=X', 'GBPEUR=X', possible_rates[random_rate1], possible_rates[random_rate2], possible_rates[random_rate3]] self.currency_symbol_before = ['$',u"€",possible_symbols_before[random_rate1],possible_symbols_before[random_rate2],possible_symbols_before[random_rate3]] self.currency_symbol_after = ['','',possible_symbols_after[random_rate1],possible_symbols_after[random_rate2],possible_symbols_after[random_rate3]] self.currency_multiple = [1,1,possible_multiple[random_rate1],possible_multiple[random_rate2],possible_multiple[random_rate3]] self.currency_format = ['{:.2f}','{:.2f}',possible_format[random_rate1],possible_format[random_rate2],possible_format[random_rate3]] self.currency_rate = [] self.currency_change = [] results = url_handler.load('http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1p2d1t1&s='+','.join(ask_for_rates)) for i in range(len(ask_for_rates)): try: self.currency_rate.append(float(results.split(",")[4*i+1])) except: self.currency_rate.append(1) try: self.currency_change.append(float(results.split(",")[4*i+2][1:-2])) except: self.currency_change.append(0) # result = "USDNOK=X",5.9423,"5/3/2010","12:39pm" if random_rate1 == 12: #oil self.currency_rate[2] = 1./self.currency_rate[2]*158.987*self.currency_rate[0] self.currency_change[2] = "" if random_rate2 == 12: #oil self.currency_rate[3] = 1./self.currency_rate[3]*158.987*self.currency_rate[0] self.currency_change[3] = "" if random_rate3 == 12: #oil self.currency_rate[4] = 1./self.currency_rate[4]*158.987*self.currency_rate[0] self.currency_change[4] = "" ''' c = CurrencyRates() rates = c.get_rates('GBP') b = BtcConverter() # add "force_decimal=True" parmeter to get Decimal rates btc = b.get_latest_price('GBP') self.currency_rate = [rates['USD'], rates['EUR'], rates['CHF'], rates['JPY'], btc]
def display_all_currencies(request): c = CurrencyRates() c = c.get_rates('USD') l = [] for el, el2 in c.items(): l.append(el) users_data = list( Currency_owned.objects.values().filter(user=request.user)) owned_currency = users_data[0] owned_currency.pop('id') owned_currency.pop('user_id') return render(request, 'currency/currencies_main.html', {'owned_currency': owned_currency})
def _fetch_all_rates(self, provider: converter.CurrencyRates, base_currency: str, date_obj: date) -> []: try: _rates = provider.get_rates(base_cur=base_currency, date_obj=date_obj) return [ self.serializer(base_currency=base_currency, currency=key, date=date_obj, value=value) for key, value in _rates.items() ] except converter.RatesNotAvailableError as e: logging.error(e) raise RatesNotAvailableError
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 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 extract_historical_currency_rates(Start_date, Current_date): date_value_df = pd.date_range(start=Start_date, end=Current_date) #print(date_value_df) currency_df = pd.DataFrame(columns=('Date', 'USD_to_INR_Rate', 'GBP_to_INR_Rate')) #,'INR_symbol')) USD_to_INR_Rate = [] GBP_to_INR_Rate = [] #print(currency_df) for i in range(len(date_value_df)): c = CurrencyRates() #print(date_value_df[i]) USD_to_INR_Rate = round( c.get_rates('USD', date_value_df[i]).get('INR'), 2) GBP_to_INR_Rate = round( c.get_rates('GBP', date_value_df[i]).get('INR'), 2) dict_rates = { 'Date': date_value_df[i], 'USD_to_INR_Rate': USD_to_INR_Rate, 'GBP_to_INR_Rate': GBP_to_INR_Rate } currency_df = currency_df.append(dict_rates, ignore_index=True) #print("USD_to_INR_Rate = ",USD_to_INR_Rate) #print("GBP_to_INR_Rate = ", GBP_to_INR_Rate) c = CurrencyCodes() #currency_df['INR_symbol'] = c.get_symbol('INR') currency_df['Date'] = currency_df['Date'].dt.strftime('%m/%d/%Y') currency_df['Date'] = pd.to_datetime(currency_df.Date, format='%m/%d/%Y') #print("symbol = ",currency_df['INR_symbol']) currency_df.index = currency_df['Date'] # currency_df.drop(['Date'], axis=1,inplace=True) # activate this line to do Graph plotting print(currency_df) return currency_df
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
from decimal import * import collections from sopel.module import commands, example, NOLIMIT from sortedcontainers import SortedDict from forex_python.converter import CurrencyCodes from forex_python.converter import CurrencyRates from forex_python.bitcoin import BtcConverter from pymarketcap import Pymarketcap from coinmarketcap import Market import coinmarketcap c = CurrencyRates() b=BtcConverter() m=Market() cc=CurrencyCodes() allcoins={} curlist=list(c.get_rates("USD").keys()) #print(c.get_rates("USD")) curlist.append("USD") curlist.sort() for cur in curlist: allcoins[cur]=cc.get_currency_name(cur) altcoinmap={} #print (coinmarketcap.price("BTC")) json=m.ticker(convert='EUR') #print(json) for currency in json: altcoinmap[currency["symbol"]]=currency["id"] allcoins[currency["symbol"]]=currency["name"] #print(altcoinmap) #print(json) #print(m.ticker("bitcoin",convert="EUR")[0]["price_usd"]*100)