Ejemplo n.º 1
0
 def convert_t_curr_and_set(currency):
     global min_profit_n
     global max_profit_n
     if min_profit_n != 0.0:
         c = CurrencyConverter()
         min_profit_n = c.convert(min_profit_n, curr, currency)
         config.set('settings', 'min_profit_n', str(min_profit_n))
         save_config()
     if max_profit_n != 0.0:
         c = CurrencyConverter()
         max_profit_n = c.convert(max_profit_n, curr, currency)
         config.set('settings', 'max_profit_n', str(max_profit_n))
         save_config()
     set_currency(currency)
Ejemplo n.º 2
0
async def cc(event):
    args_from_event = event.pattern_match.group(1).split(" ", 2)
    if len(args_from_event) == 3:
        amount, c_from_iso, c_to_iso = args_from_event
    elif len(args_from_event) == 2:
        amount, c_from_iso = args_from_event
        c_to_iso = "USD"  # default
    else:
        await event.edit(msgRep.NOT_EGH_ARGS)
        return

    try:
        amount = "{:.2f}".format(float(amount.replace(",", ".")))
    except:
        await event.edit(msgRep.INVALID_AMOUNT_FORMAT)
        return

    c_from_iso = c_from_iso.upper()
    c_to_iso = c_to_iso.upper()

    try:
        try:
            update_currency_data()
            c = CurrencyConverter(currency_file=CC_CSV_PATH)
        except Exception as e:
            log.warning(f"Unable to read updated data history: {e}. "
                        "Falling back to default currency data.")
            c = CurrencyConverter()
        if c_from_iso not in c.currencies:
            await event.edit(msgRep.CC_ISO_UNSUPPORTED.format(c_from_iso))
            return
        if c_to_iso not in c.currencies:
            await event.edit(msgRep.CC_ISO_UNSUPPORTED.format(c_to_iso))
            return
        date = c.bounds[c_from_iso]
        result = "{:.2f}".format(
            c.convert(amount=amount,
                      currency=c_from_iso,
                      new_currency=c_to_iso))
        strings = f"**{msgRep.CC_HEADER}**\n\n"
        strings += msgRep.CFROM_CTO.format(c_from_iso, c_to_iso) + "\n"
        strings += f"{amount} {c_from_iso} = {result} {c_to_iso}\n\n"
        strings += f"__{msgRep.CC_LAST_UPDATE}: {date.last_date}__"
        await event.edit(strings)
    except ValueError as ve:
        await event.edit(f"`{msgRep.INVALID_INPUT}: {ve}`")
    except Exception as e:
        log.warning(f"Failed to convert currency: {e}")
        await event.edit(msgRep.UNABLE_TO_CC)
    return
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
0
    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()
Ejemplo n.º 5
0
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
        })
Ejemplo n.º 6
0
    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')
Ejemplo n.º 7
0
    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')
Ejemplo n.º 8
0
    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
Ejemplo n.º 9
0
def convert_currency(convert_to):
    c = CurrencyConverter(decimal=True)
    base = 1
    try:
        return c.convert(base, 'USD', convert_to)
    except:
        return base
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
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 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 books_scraper(dataset_dir, max_pages=333):
    '''
	Top Book Depository scraper function. Call this function to start the whole scraping process.

	:params:
	dataset_dir - String, Path to the folder where all data will be saved
	max_page - Integer, Number of pages scraped for a category NOTE: After page 333 Book Depository is not showing more books, so the default value here is 333
	'''

    all_books = []
    converter = CurrencyConverter()

    #Iterate through all links found in the bookdepository_categories.py file
    for link in links:
        print("Scraping: ", link)
        category = link.split("/")[5]
        category_folder = dataset_dir + category

        #Create a sub folder for the category (if it does not exists)
        if not os.path.exists(category_folder):
            os.mkdir(category_folder)

        #Begin the scraping process for the current category
        category_csv = category_scraper(link,
                                        converter=converter,
                                        max_page=max_pages)
        category_csv.to_csv(category + ".csv", index=False)
        all_books.append(category_csv)

    complete_csv = pd.concat(all_books)
    complete_csv.to_csv(dataset_dir + "dataset.csv", index=False)
Ejemplo n.º 18
0
 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()
Ejemplo n.º 19
0
    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 __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()
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
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')
Ejemplo n.º 23
0
    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
Ejemplo n.º 24
0
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
Ejemplo n.º 25
0
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")
Ejemplo n.º 26
0
    def __init__(self):
        super().__init__()
        self.c = CurrencyConverter()
        self.setWindowTitle("Convertisseur de devises")
        self.create_layout()

        self.handler()
Ejemplo n.º 27
0
 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))
Ejemplo n.º 28
0
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])}
Ejemplo n.º 29
0
def RentIndexAdjust(
        prices,  # np array 
        city,  # str
        original_currency,  # eg INR
        target_currency='USD',  # eg USD
        log_transform=False):

    # apply city rent index factor
    index_type = 'Rent Index'
    city_factor = 100 / rent_index[rent_index['City'] ==
                                   city][index_type].values[0]

    prices = city_factor * prices

    # convert to USD
    cc = CurrencyConverter()

    def ConvertCurrency(x):
        try:
            return round(cc.convert(x, original_currency, target_currency))
        except:
            return np.nan

    prices = prices.apply(ConvertCurrency)

    # log transform
    if log_transform == True:
        prices = prices.apply(np.log)

    return prices
Ejemplo n.º 30
0
 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")