Exemplo n.º 1
0
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
Exemplo n.º 2
0
def cryptocurrency_exchanges():
	countries = ['AUD', 'BGN', 'BRL', 'CAD', 'CHF', 'CNY', 'CZK', 'DKK', 'EUR', 'GBP', 'HKD', 'HRK', 'HUF', 'IDR', 'ILS', 'INR', 'ISK', 'JPY', 'KRW', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'RON', 'RUB', 'SEK', 'SGD', 'THB', 'TRY', 'USD', 'ZAR']
	bitc = BtcConverter()
	raw_data = []
	for data in countries:
		raw_data.append([data, bitc.get_latest_price(data)])
	return render_template('cryptocurrency_exchanges.html', raw_data = raw_data)
def populate_table():
    conn1 = sqlite3.connect('asset_prices.db')
    c1 = conn1.cursor()
    cur1 = CurrencyRates()
    cur2 = CurrencyRates()
    dollar = cur1.get_rate('USD', 'GBP')
    pound = cur2.get_rate('GBP', 'USD')
    yen = cur1.get_rate('JPY', 'USD')
    euro = cur2.get_rate('EUR', 'USD')

    b = BtcConverter()
    #getting the live updated price of bitcoin from forex python api
    bp = b.get_latest_price('USD')
    v = bp
    #print(bp)
    #print("===============")
    c1.execute(
        "INSERT INTO  PRICES(Bitcoin_value,Dollar_value,Pound_value,Yen_value,Euro_value) VALUES (?,?,?,?,?)",
        (
            bp,
            dollar,
            pound,
            yen,
            euro,
        ))
    conn1.commit()
Exemplo n.º 4
0
 def getprice(self, message=None, match=None, to=None, currency="INR"):
     currency = match.group("currency").upper()
     if "RUPEES" in currency:
         currency = "INR"
     price = BtcConverter()
     return TextMessageProtocolEntity(
         "1BTC = " + str(price.get_latest_price(currency)) + " " + currency,
         to=message.getFrom())
Exemplo n.º 5
0
    def background(self):
        def get_quandl_data(quandl_id):
            '''Download and cache Quandl dataseries'''
            '''
            cache_path = '{}.pkl'.format(quandl_id).replace('/','-')
            try:
                f = open(cache_path, 'rb')
                df = pickle.load(f)   
                #print('Loaded {} from cache'.format(quandl_id))
            except (OSError, IOError) as e:
                #print('Downloading {} from Quandl'.format(quandl_id))
                df = quandl.get(quandl_id, returns="pandas")
                df.to_pickle(cache_path)
                #print('Cached {} at {}'.format(quandl_id, cache_path))
            '''
            df = quandl.get(quandl_id, returns="pandas")
            return df

        b = BtcConverter(
        )  # add "force_decimal=True" parmeter to get Decimal rates
        btc = b.get_latest_price('USD')
        self.btc_rate = btc

        btc_usd_price_kraken = get_quandl_data('BCHARTS/KRAKENUSD')

        X = btc_usd_price_kraken.index
        Y = btc_usd_price_kraken['Weighted Price']

        x = X[-70:]
        y = Y[-70:]

        #print x
        #print y

        height = 14
        width = 70
        range_x = max(x) - min(x)
        range_y = max(y) - min(y)
        #dx = range_x//width
        self.dy = range_y // height

        self.height = height
        self.width = width
        self.max_x = max(x)
        self.min_x = min(x)
        self.max_y = max(y)
        self.min_y = min(y)
        self.coords = [0 for i in x]
        self.x = x
        self.y = y
        #graph = [[" " for j in range(width)] for i in range(height)]
        for i, xx in enumerate(x):
            x_coord = int((x[i] - min(x)).total_seconds() /
                          (range_x.total_seconds()) * (width - 1))
            #from IPython import embed
            #embed()
            y_coord = int((y[i] - min(y)) / range_y * (height - 1))
            self.coords[i] = (x_coord, y_coord)
Exemplo n.º 6
0
def price():
    b = BtcConverter()
    bitcoin_price = b.get_latest_price('USD')
    coinmarketcap = Market()
    y = coinmarketcap.ticker(start=0, limit=2, convert='USD')
    return {
        "btc": bitcoin_price,
        "eth": y["data"]["1027"]["quotes"]['USD']['price']
    }
Exemplo n.º 7
0
 def get(self, request):
     try:
         form = CurrencyForm()
         value = 0
         btc = BtcConverter()
         price = round(btc.get_latest_price('PLN'), 2)
         context = {'form': form, 'value': value, 'price': price}
         return render(request, self.template_name, context)
     except:
         return redirect('/')
Exemplo n.º 8
0
def base():
    """Show base.html."""
    c = CurrencyRates()
    x = c.get_rates("USD")
    res = {item: "{0:.2f}".format(round(x[item], 2)) for item in x}
    session["rates"] = res
    b = BtcConverter()
    bit = {}
    bit["bitcoin_usd"] = round(b.get_latest_price("USD"), 2)
    bit["bitcoin_eur"] = round(b.get_latest_price("EUR"), 2)
    bit["bitcoin_gbp"] = round(b.get_latest_price("GBP"), 2)
    cc = CurrencyCodes()
    bit["name_usd"] = cc.get_currency_name("USD")
    bit["name_eur"] = cc.get_currency_name("EUR")
    bit["name_gbp"] = cc.get_currency_name("GBP")
    bit["symbol"] = b.get_symbol()
    bit["symbol_eur"] = cc.get_symbol("EUR")
    bit["symbol_gbp"] = cc.get_symbol("GBP")
    session["bit"] = bit
    return render_template("base.html", rates=res, bit=bit)
Exemplo n.º 9
0
    def do_update(self):
        from forex_python.bitcoin import BtcConverter
        log.info("fetching currency update")
        bitcoin = BtcConverter()
        try:
            btc = bitcoin.get_latest_price('EUR')

            self.text = "1 Bitcoin = %s%.2f EUR" % (self.get_color_compare(
                btc, self.last_btc), btc)
            self.last_btc = btc
        except requests.exceptions.RequestException as e:
            logging.warning("couldn't get update: %s" % e)
Exemplo n.º 10
0
    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]
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
def get_rate(currency='USD'):
    """
    Return price of 1 currency in BTC
    Supported currencies available at 
    http://forex-python.readthedocs.io/en/latest/currencysource.html#list-of-supported-currency-codes
    :param currency: currency to convert to
    :return: conversion rate from currency to BTC
    """
    if currency is None:
        return None
    b = BtcConverter()
    factor = b.get_latest_price(currency)
    if factor is None:
        factor = 1.0 / fallback_get_rate(currency)
    return 1.0 / factor
Exemplo n.º 13
0
def convert(currency, amount):

    # create a new converter object with standardized date
    b = BtcConverter()
    x = b.get_latest_price(currency)

    cprint('Powered by Coindesk | https://www.coindesk.com/price/', 'green')
    print("[" + str(dts) + "]" + "  " + currency.upper() +
          " for 1.0 Bitcoin (BTC) is " + str(x))

    # convert to BTC
    conversion_amount = b.convert_to_btc(amount, currency.upper())
    print(
        "[{}]  Converting {} to BTC: {} {} is currently worth {} BTC!".format(
            str(dts), currency.upper(), "%0.2f" % (amount), currency.upper(),
            conversion_amount))
Exemplo n.º 14
0
    async def bitcoin(self, ctx, currency="USD"):
        try:
            b = BtcConverter()
            amount = round(b.get_latest_price(currency), 2)
        except:
            embed = discord.Embed(color=self.bot.embed_color,
                                  title="→ Currency error!",
                                  description="• Not a valid currency type!"
                                  "\n• Example: `l!bitcoin CAD`")
            await ctx.send(embed=embed)
        embed = discord.Embed(
            color=self.bot.embed_color,
            title="→ BTC to Currency",
            description=f"• One Bitcoin is: `{amount}` {currency}")
        await ctx.send(embed=embed)

        logger.info(f"Utility | Sent Bitcoin: {ctx.author}")
Exemplo n.º 15
0
 def post(self, request):
     try:
         form = CurrencyForm(request.POST)
         if form.is_valid():
             a = form.cleaned_data['currency_one'].upper()
             amount = form.cleaned_data['amount']
             b = form.cleaned_data['currency_two'].upper()
             value = convert(a, b, amount)
             btc = BtcConverter()
         price = round(btc.get_latest_price('PLN'), 2)
         context = {
             'form': form,
             'value': value,
             'a': a,
             'b': b,
             'amount': amount,
             'price': price
         }
         return render(request, self.template_name, context)
     except:
         return redirect('/')
Exemplo n.º 16
0
def convert2USD_today(cur_name_from: str, amount: float):
    '''
    Use forex_python to convert the currencies found in the dataset into US dollars
    cur_name_from - currency to convert in USD
    amount - float represneting the amount to convert
    '''

    if cur_name_from == 'U.S. dollars ($)':
        return amount

    if cur_name_from == 'Bitcoin (btc)':
        c = BtcConverter()
        btc_rate = c.get_latest_price('USD')
        return amount * btc_rate

    cur_dict = dict(AUD='Australian dollars (A$)',
                    btc='Bitcoin (btc)',
                    BRL='Brazilian reais (R$)',
                    GBP='British pounds sterling (£)',
                    CAD='Canadian dollars (C$)',
                    CNY='Chinese yuan renminbi (¥)',
                    EUR='Euros (€)',
                    INR='Indian rupees (?)',
                    JPY='Japanese yen (¥)',
                    MXN='Mexican pesos (MXN$)',
                    PLN='Polish zloty (zl)',
                    RUB='Russian rubles (?)',
                    SGD='Singapore dollars (S$)',
                    ZAR='South African rands (R)',
                    SEK='Swedish kroner (SEK)',
                    CHF='Swiss francs',
                    USD='U.S. dollars ($)')

    cur_code_from = [
        code for code, name in cur_dict.items() if name == cur_name_from
    ][0]
    c = CurrencyRates()
    return c.convert(cur_code_from, 'USD', amount)
Exemplo n.º 17
0
amount = float(input('Enter the Amount you want to Convert: '))
from_currency = input('From : ').upper()
to_currency = input('To : ').upper()

print('\n' + from_currency + " To " + to_currency, amount)
print('The current conversion rate for {} to {} is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency)))    #Get conversion rate from USD to INR
result = c.convert(from_currency, to_currency, amount)   #Convert the amount
print('Latest Conversion: ',result)

#Get conversion rate as of 2021-01-01
print('\nThe conversion rate from {} to {} as per 1st Jan 2021 is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency, date_obj)))
print('The conversion as per 1st Jan 2021: ', c.convert(from_currency, to_currency, amount, date_obj))

b = BtcConverter()
print('\n\nBitcoin Symbol: ', b.get_symbol())  # get_btc_symbol()
print('Bitcoin Latest Price in USD : ', b.get_latest_price('USD'))     #Get latest Bitcoin price.
print('Convert 10 Million USD to Bitcoin', b.convert_to_btc(10000000, 'USD'))     #Convert Amount to Bitcoins based on latest exchange price.
print('The Equivalent of 10.99 Bitcoin in USD: ',b.convert_btc_to_cur(10.99, 'USD'))         #Convert Bitcoins to valid currency amount based on lates price

print('\nBitcoin price as per 1st Jan 2021: ',b.get_previous_price('USD', date_obj)) #Get price of Bitcoin based on prevois date
print('The conversion of 10 Million Dollars to Bitcoin as of 1st Jan 2021',b.convert_to_btc_on(10000000, 'USD', date_obj))      #Convert Amount to bitcoins based on previous date prices
print('The conversion of 10.99 Bitcoin in USD as of 1st Jan 2021: ',b.convert_btc_to_cur_on(10.99, 'USD', date_obj))       #Convert Bitcoins to valid currency amount based on previous date price

start_date = datetime.datetime(2021, 2, 1, 19, 39, 36, 815417)
end_date = datetime.datetime(2021, 2, 7, 19, 39, 36, 815417)
print('\nBitcoin rates over the week in USD: ',b.get_previous_price_list('USD', start_date, end_date))         #Get list of prices list for given date range

d = CurrencyCodes()
print('\nUS Dollar Symbol:', d.get_symbol('USD'))          #Get currency symbol using currency code
print(d.get_currency_name('USD'))          #Get Currency Name using currency code
Exemplo n.º 18
0
class TestBitCoinForceDecimal(TestCase):
    def setUp(self):
        self.b = BtcConverter(force_decimal=True)

    def test_latest_price_valid_currency(self):
        price = self.b.get_latest_price('USD')
        self.assertEqual(type(price), Decimal)

    def test_latest_price_invalid_currency(self):
        price = self.b.get_latest_price('XYZ')
        self.assertFalse(price)

    def test_previous_price_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        price = self.b.get_previous_price('USD', date_obj)
        self.assertEqual(type(price), Decimal)

    def test_previous_price_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.get_previous_price,
                          'XYZ', date_obj)

    def test_previous_price_list_with_valid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('USD', start_date,
                                                    end_date)
        self.assertTrue(price_list)
        self.assertEqual(type(price_list), dict)

    def test_previous_price_list_with_invalid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('XYZ', start_date,
                                                    end_date)
        self.assertFalse(price_list)
        self.assertEqual(type(price_list), dict)

    def test_convet_to_btc_with_valid_currency(self):
        coins = self.b.convert_to_btc(Decimal('250'), 'USD')
        self.assertEqual(type(coins), Decimal)

    def test_convet_to_btc_with_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc,
                          Decimal('250'), 'XYZ')

    def test_convert_btc_to_cur_valid_currency(self):
        amount = self.b.convert_btc_to_cur(Decimal('2'), 'USD')
        self.assertEqual(type(amount), Decimal)

    def test_convert_btc_to_cur_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur,
                          Decimal('250'), 'XYZ')

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        coins = self.b.convert_to_btc_on(Decimal('300'), 'USD', date_obj)
        self.assertEqual(type(coins), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc_on,
                          Decimal('250'), 'XYZ', date_obj)

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        amount = self.b.convert_btc_to_cur_on(Decimal('250'), 'USD', date_obj)
        self.assertEqual(type(amount), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur_on,
                          Decimal('3'), 'XYZ', date_obj)
Exemplo n.º 19
0
start = dt.datetime(2000, 1, 1)
end = dt.datetime(2017, 12, 1)

df = web.DataReader('GOOGL', 'yahoo', start, end)
print(df.head(3))
print("\n")
print("forex")
t = dt.datetime(2001, 10, 18)
get_rate("USD", "EUR", t)
print("USD to EUR")
print(get_rate("USD", "EUR", t))
print("\n")

b = BtcConverter()
print("bitcoin")
print(b.get_latest_price('USD'))
print("USD\n")

#code starts now
print("code starts now\n")
with open("AllStocks1.csv", "r") as StocksFile:
    StocksFileReader = csv.reader(StocksFile)
    StocksList = []
    for row in StocksFileReader:
        if len(row) != 0:
            StocksList = StocksList + row
            #print(web.DataReader(row[0], 'yahoo', start, end))
            try:
                ddd = web.DataReader(row[0], 'yahoo', start, end)
                #print(ddd)
                thepath = 'C:\\Users\\Ryan\\Desktop\\rawstocks\\'
def bitcoin_to_USD(amount):
    b = BtcConverter()
    latest_price = b.get_latest_price('USD')
    return latest_price * amount
#!/usr/bin/env python
# This program buys some Dogecoins and sells them for a bigger price

import sys
sys.path.append('../../')

from Trader.Bittrex3 import Bittrex3
from forex_python.bitcoin import BtcConverter
import json

b = BtcConverter()

latestBitcoinPrice = b.get_latest_price('USD')
print("Latest Bitcoin Price " + str(latestBitcoinPrice))

dollarsToUSD = b.convert_to_btc(1, "USD")
print("1 USD to bitcoin " + str(dollarsToUSD))


def bitcoin_to_USD(amount):
    b = BtcConverter()
    latest_price = b.get_latest_price('USD')
    return latest_price * amount


print(bitcoin_to_USD(0.00122808))

# Get these from https://bittrex.com/Account/ManageApiKey

with open("secrets.json") as secrets_file:
    secrets = json.load(secrets_file)
Exemplo n.º 22
0
#!/bin/env python

#Find arbitrages:
#betting odds
#foreign exhange markets
#cryptocurrrency markets

#forex-
from forex_python.converter import CurrencyRates
c = CurrencyRates()
c.get_rates('USD')

#bitcoin
from forex_python.bitcoin import BtcConverter
b = BtcConverter()
b.get_latest_price('USD')

'''
A
Mcgreggor: +500
Money: -20

B
McG: +400
Money: -25

12.5 McG A -> 62.5
50 Money B -> 62.5
'''
Exemplo n.º 23
0
with open(r"C:\Users\Lenovo\Desktop\New folder\python\Small Projects\Currency.txt") as f:
    lines = f.readlines()
print(lines)

curr_dict = {}
for line in lines:
    split = line.split("\t")
    curr_dict[split[0]] = split[1]
print(curr_dict)
amount = int(input("Enter the amount: "))
print("Enter Conversion Currency:  \nAvailable Options:\n")
[print(item) for item in curr_dict.keys()]
currency = input("Enter one of these values:")
print(f"{amount} INR is equal to {amount * float(curr_dict[currency])} {currency}")

from forex_python.converter import CurrencyRates, CurrencyCodes
c = CurrencyRates()
print(c.get_rate('INR','USD'))
print(c.convert("INR","USD",500))

print(c.get_rate('USD','INR'))
print(c.convert("USD","INR",500))

curr = CurrencyCodes()
print(curr.get_symbol("INR"))
print(curr.get_currency_name("INR"))

from forex_python.bitcoin import BtcConverter
bt = BtcConverter()
print(bt.get_latest_price("INR"))
Exemplo n.º 24
0
from forex_python.converter import CurrencyRates
from forex_python.bitcoin import BtcConverter

converter = CurrencyRates()
amount = int(input("Zadejte požadovanou částku: "))
price_czk = converter.convert('EUR', 'CZK', amount)
print(f"Pro získání {amount} dolarů potřebujete {price_czk} CZK")

btc = BtcConverter()
amount_btc = int(input("Zadejte požadované množství BTC k převodu do CZK: "))
btc.get_latest_price('CZK')
price_czk_btc = btc.convert_to_btc(amount_btc, 'CZK')
print(f"Pro získání {amount_btc} bitcoinu potřebujete {price_czk_btc} CZK")
Exemplo n.º 25
0
from forex_python.bitcoin import BtcConverter

mena_investice = input("Zadejte kód měny, kterou máte k dispozici: ")
pozadovano_bitcoinu = int(input("Zadejte množství BTC, které chcete koupit: "))

prevodnik = BtcConverter()
mnozstvi_meny = (
    prevodnik.get_latest_price(mena_investice)) * pozadovano_bitcoinu
print(mnozstvi_meny)
Exemplo n.º 26
0
#display Currency Name & Symbol
print('\nThe currency name is: ' + cur_name)
print('The currency symbol is: ' + cur_symbol)

print('\n' + test1.get_symbol('USD'))
print(test1.get_currency_name('USD') + '\n')

test2 = CurrencyRates()

#fetch the Conversion rate
rate = test2.get_rate('USD', 'INR')
print(rate)

#perform conversion
res = test2.convert('USD', 'INR', 10)

#display result
print(res)

#BONUS
print('---------------------------------------')

#fetching BITCOIN details
bitcoin = BtcConverter()

#fetch the lastest price
price = bitcoin.get_latest_price('INR')

#display the output
print(price)
Exemplo n.º 27
0
def pullData():
    t = '{:%H:%M:%S}'.format(datetime.datetime.now() +
                             datetime.timedelta(hours=1))
    #t = time.strftime("%H:%M:%S")
    print("Starting at number: " + str(datetime.datetime.utcnow()))
    # Using forex to get latest data: https://media.readthedocs.org/pdf/forex-python/latest/forex-python.pdf
    c = CurrencyRates()
    b = BtcConverter()
    rates = c.get_rates(config.LOCAL_CURR_CODE)
    pop = False

    # Adapted from: https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu
    chart_data['labels'].append(t)
    # If 20 dates are already currently in the list - pop.
    if len(chart_data['labels']) >= 20:
        chart_data['labels'].pop(0)
        pop = True
    # Loop through array of datasets to append or append and pop.
    if chart_data['datasets']:
        for i, code in enumerate(config.CURR_CODES):
            if code == 'BTC':
                price = round(b.get_latest_price(config.LOCAL_CURR_CODE), 2)
                rate = round(b.convert_to_btc(1, config.LOCAL_CURR_CODE), 5)
            else:
                price = round(c.get_rate(code, config.LOCAL_CURR_CODE), 2)
                rate = round(rates[chart_data['datasets'][i]['label']], 5)
            chart_data['datasets'][i]['data'].append(price)
            latest_currencies['currencies'][i]['data'] = rate
            if pop:
                chart_data['datasets'][i]['data'].pop(0)
    else:
        co = CurrencyCodes()
        # Prepare data objects and pull first prices.
        for i, code in enumerate(config.CURR_CODES):
            if code == 'BTC':
                symbol = b.get_symbol()
                name = 'Bitcoin'
                price = round(b.get_latest_price(config.LOCAL_CURR_CODE), 2)
                rate = round(b.convert_to_btc(1, config.LOCAL_CURR_CODE), 5)
            else:
                name = co.get_currency_name(code)
                symbol = co.get_symbol(code)
                price = round(c.get_rate(code, config.LOCAL_CURR_CODE), 2)
                rate = round(rates[code], 5)
            chart_data['datasets'].append({
                'label':
                code,
                'backgroundColor':
                config.CURR_COLORS[i],
                'data': [price]
            })
            latest_currencies['currencies'].append({
                'code': code,
                'name': name,
                'symbol': symbol,
                'data': rate
            })

    r.set(config.REDIS_CHAN_LIST, latest_currencies)
    r.set(config.REDIS_CHAN_GRAPH, chart_data)

    print("Finishing at number: " + str(datetime.datetime.utcnow()))
Exemplo n.º 28
0
from forex_python.bitcoin import BtcConverter
meny = ["USD", "CZK", "EUR", "GBP", "DKK"]
bprevodnik = BtcConverter()

puvodni_mena = input("Zadejte vaši měnu (umím USD, CZK, EUR, GBP, DKK): ")
if puvodni_mena in meny:
    pozadovano_bitcoinu = int(input(f"Zadejte, kolik Bitcoinů chcete: "))
    cena_za_bitcoiny = bprevodnik.get_latest_price(puvodni_mena) * pozadovano_bitcoinu
    print(f"Na {pozadovano_bitcoinu} Btc potřebujete {round(cena_za_bitcoiny,2)} {puvodni_mena}.")
else:
    print("Vámi zadanou měnu neumím nebo nechci převádět.")
Exemplo n.º 29
0
'''https://www.kurzy.cz/komodity/bitcoin-graf-vyvoje-ceny/'''
'''https://github.com/MicroPyramid/forex-python/blob/master/tests/test_bitcoin.py'''

from forex_python.bitcoin import (get_btc_symbol, convert_btc_to_cur_on,
                                  convert_to_btc_on, convert_btc_to_cur,
                                  convert_to_btc, get_latest_price,
                                  get_previous_price, get_previous_price_list,
                                  BtcConverter)

prevodnik = BtcConverter()

print(prevodnik.get_latest_price('USD'))
print(prevodnik.get_latest_price('CZK'))

kolik = int(input("Jaké množství Kč chcete vyměnit: "))
print(prevodnik.convert_to_btc(kolik, 'CZK'))
Exemplo n.º 30
0
    c.get_rate(base_cur, MXN, date_obj),
    c.get_rate(base_cur, BGN, date_obj),
    c.get_rate(base_cur, HUF, date_obj),
    c.get_rate(base_cur, MYR, date_obj),
    c.get_rate(base_cur, HRK, date_obj),
    c.get_rate(base_cur, THB, date_obj),
    c.get_rate(base_cur, NOK, date_obj),
    c.get_rate(base_cur, PLN, date_obj),
    c.get_rate(base_cur, CZK, date_obj)
]]

tbl_header = (USD, GBP, ZAR, EUR, AUD, SGD, CAD, CNY, JPY, NZD, INR, CHF, MXN,
              BGN, HUF, MYR, HRK, THB, NOK, PLN, CZK)

print(">>Table Results:")
print('>>Base Currency = ', base_cur)
print(tbl(tbl_data, tbl_header, tablefmt="fancy_grid"))
print(">>DOne loading table...")

print("\n::Lets Check Bitcoin now...!")
print("Bitcoin price for => ", base_cur)

print("1 BITCOIN = %(base)s %(price).2F" % {
    'base': base_cur,
    'price': b.get_latest_price(base_cur)
})

print(">>Done checking bitcoin...")
print("Goodbye!")
print("PS, From [[[ElectronSz]]] :)")