Exemplo n.º 1
0
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')
Exemplo n.º 2
0
def get_currency_daily_price(end_date,currency_type):
    if not type(currency_type) is list:
        print("currency_type data error!!exit!!")
        exit()

    USD_csv_file="./currency_daily_data/USD_price.csv"
    EUR_csv_file="./currency_daily_data/EUR_price.csv"
    GBP_csv_file="./currency_daily_data/GBP_price.csv"
    CNY_csv_file="./currency_daily_data/CNY_price.csv"
    AUD_csv_file="./currency_daily_data/AUD_price.csv"

    start_date=datetime(2000,1,1)
    #start_date=datetime(2017,1,1) # for test
    end_date=datetime.today()
    date_range=daterange(start_date,end_date)
    #print(date_range)
    c=CurrencyRates()
    #currency_data=pd.DataFrame()
    print(currency_type)
    #if type(currency_type) is list:
        #currency_data.columns=currency_type
    for data_type in currency_type:
        array_data={"date":[],"rate":[]}
        if data_type =="USD":
            csv_file=USD_csv_file
        elif data_type == "EUR":
            csv_file=EUR_csv_file
        elif data_type== "GBP":
            csv_file=GBP_csv_file
        elif data_type== "CNY":
            csv_file=CNY_csv_file
        elif data_type=="AUD":
            csv_file=AUD_csv_file
        else:
            print("currency_type not specified!!please check again!!")
            exit()


        for date in date_range:
            #print(date)
            data=c.get_rate(currency_type,"JPY",date)
            #print(data)
            #if not currency_type in currency_data.columns.values():
            #currency_data.columns.append(currency_type)
            array_data["date"].append(date)
            array_data["rate"].append(data)
        #print(array_data.values())
        #currency_data=pd.DataFrame(list(array_data.items()),columns=["date","rate"])
        currency_data=pd.DataFrame({"date":array_data["date"],"rate":array_data["rate"]})
        print(currency_data)
        gen_currency_csv_file(currency_data,csv_file)

    print(currency_data)
Exemplo n.º 3
0
def jpdTohkd():
    # get currency rate for JPY
    # currentJPY = 0.07122
    c = CurrencyRates()
    currentJPY = c.get_rate('JPY','HKD')
    datetimeStr = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')


    g1 = jpy2hkd.Group("100", 100, 1000, 50, 100, currentJPY)
    g2 = jpy2hkd.Group("1000", 1000, 5000, 100, 1000, currentJPY)
    # g2 = jpy2hkd.Group("2000", 2000, 3000, 100, 1000, currentJPY)
    # g2 = jpy2hkd.Group("3000", 3000, 4000, 100, 1000, currentJPY)
    # g2 = jpy2hkd.Group("4000", 4000, 5000, 100, 1000, currentJPY)
    g3 = jpy2hkd.Group("5000", 5000, 10000, 100, 1000, currentJPY)

    main = jpy2hkd.jpy2hkd()
    main.AddGroup("100",g1)
    main.AddGroup("1000",g2)
    main.AddGroup("5000",g3)

    jpy = 100
    hkd = round(currentJPY * jpy,1)
    errors = []

    if request.method == "POST":
        try:
            jpy_in = request.form.get('jpy_in')
            hkd_in = request.form.get('hkd_in')

            if jpy_in is not None:
                jpy = float(jpy_in)
                if jpy != 0:
                    hkd = jpy*currentJPY
                    hkd = round(hkd,1)

            if hkd_in is not None:
                hkd = float(hkd_in)
                if hkd != 0:
                    jpy = hkd/currentJPY
                    jpy = round(jpy,1)
        except:
            errors.append("Unable to get URL.")

    disCurrnetJPY = round((currentJPY*100),2)
    return render_template(
        "jpy2hkd.html", 
        main = main, 
        jpy = jpy, hkd = hkd, 
        currentJPY = disCurrnetJPY, 
        datetimeStr = datetimeStr)
def getHistoricalXRatesForDate(dateObj):
	dateStart = dateObj
	dateEnd = dateStart
	dataBtc = quandl.get(["BCHARTS/KRAKENUSD.4"], start_date=dateStart, end_date=dateEnd, returns="numpy")
	if dataBtc.size > 0:
		btcUsdClosePrice = dataBtc[0][1]
	else:
		statusMsg = "ERROR - BTC/USD close price not found for date {0} !".format(dateStart)
		writeOutputParms(statusMsg, '0', '0')
		sys.exit(1)

	cr = CurrencyRates()
	usdChfRate = cr.get_rate('USD', 'CHF', dateObj)

	return float(btcUsdClosePrice), float(usdChfRate)
Exemplo n.º 5
0
    def currencyconv(self, jarvis, amount, fr, to):
        """
        currencyconv converts the given amount to another currency
        using fore-python
        """

        b = BtcConverter(force_decimal=True)
        c = CurrencyRates(force_decimal=True)

        if (to == "BTC"):
            result = b.convert_to_btc(Decimal(amount), fr)
        elif (fr == "BTC"):
            result = b.convert_btc_to_cur(Decimal(amount), to)
        else:
            result = c.convert(fr, to, Decimal(amount))
        outputText = str(amount) + " " + fr + \
            " are equal to " + str(result) + " " + to
        jarvis.say(outputText)
def main(config, push_to_server=False):

    c = CurrencyRates()
    # Will raise RatesNotAvailableError if not able to fetch from the api
    usd_to_sek = c.get_rate('USD', 'SEK')
    eur_to_sek = c.get_rate('EUR', 'SEK')

    # Create the doc that will be uploaded
    doc = {}
    doc['Issued at'] = datetime.datetime.now().isoformat()
    # I know it's bad practice to call the _source_url method,
    # but if it breaks it breaks.
    doc['Data source'] = "forex_python ({})".format(c._source_url())
    doc['USD_in_SEK'] = usd_to_sek
    doc['EUR_in_SEK'] = eur_to_sek

    # Load the statusdb database
    with open(config) as settings_file:
        server_settings = yaml.load(settings_file)
    couch = Server(server_settings.get("couch_server", None))
    db = couch['pricing_exchange_rates']

    # Check that new is not too strange compared to current.
    # This is a safety measure so that we have lower risk of having erroneus
    # exchange rates in the db.
    current_usd = get_current(db, 'usd_to_sek')
    current_eur = get_current(db, 'eur_to_sek')

    check_financial_crisis(current_usd, usd_to_sek, 'USD')
    check_financial_crisis(current_eur, eur_to_sek, 'EUR')

    # Completely conserved currencies are also strange.
    if (current_eur is not None) and (current_usd is not None):
        # This assumes the script is not ran too often
        # (api udpates once per day)
        small_number = 0.0000000001
        if (abs(current_usd - usd_to_sek) < small_number) and \
                (abs(current_eur - eur_to_sek) < small_number):
            raise Exception("Super stable currencies? Stale api would be my guess.")

    if push_to_server:
        db.save(doc)
    else:
        print(doc)
Exemplo n.º 7
0
def _load_forex(start=date(2015, 1, 1),
                end=date.today(),
                currency_1='USD',
                currency_2='EUR'):
    """Load forex dataset."""
    cr = CurrencyRates()

    def get_rate(day):
        time.sleep(0.1)
        return cr.get_rate(currency_1, currency_2, day)

    return _fetch(get_rate, start=start, end=end)
Exemplo n.º 8
0
def get_output_rates(amount, input_currency, output_currency):
    currency_rates = CurrencyRates()

    if output_currency:
        if input_currency == output_currency:
            converted_amount = amount
        else:
            converted_amount = currency_rates.convert(input_currency.code,
                                                      output_currency.code,
                                                      amount)
        output = {output_currency.code: converted_amount}
    else:
        latest_rates_for_input_currency = currency_rates.get_rates(
            input_currency.code)

        for code, value in latest_rates_for_input_currency.items():
            latest_rates_for_input_currency[code] = value * amount

        output = latest_rates_for_input_currency

    return output
Exemplo n.º 9
0
def RealTimeCurrencyConversion():

    c = CurrencyRates()

    from_currency = ip1.get()
    to_currency = ip2.get()

    if (value.get() == ""):
        tkinter.messagebox.showerror(
            "Error", "Amount Not Entered.\n Please a valid amount.")

    elif (from_currency == "Select" or to_currency == "Select"):
        tkinter.messagebox.showerror(
            "Error",
            "Currency Not Selected.\n Please select the currencies to be converted"
        )

    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))
Exemplo n.º 10
0
def pip(request):
    c = CurrencyRates()
    s = CurrencyCodes()
    decimal = 0.0001
    currency_list = {
        'GBP', 'AUD', 'CAD', 'CHF', 'CNY', 'SEK', 'NZD', 'MXN', 'SGD', 'HKD',
        'INR', 'USD', 'EUR', 'JPY'
    }
    if request.method == "POST":
        pip = 0
        base_currency = request.POST['sel2_1']
        counter_currency = request.POST['sel2_2']
        account_currency = request.POST['sel2_3']
        trade_size2_4 = request.POST['trade_size2_4']
        if trade_size2_4 is '':
            trade_size2_4 = 10000
        else:
            trade_size2_4 = float(trade_size2_4)

        if counter_currency == account_currency:
            mp = 1.0
        else:
            mp = c.get_rate(account_currency, counter_currency)

        if (base_currency == 'JPY') or (counter_currency == 'JPY'):
            decimal = 0.01
        symbol = s.get_symbol(counter_currency)
        pip = (decimal * trade_size2_4) / mp

        return render(
            request, 'pip.html', {
                'symbol': symbol,
                'currencyList': currency_list,
                'pip': pip,
                'base_currency': base_currency,
                'counter_currency': counter_currency,
                'account_currency': account_currency,
                'mp': mp
            })
    return render(request, 'pip.html', {'currencyList': currency_list})
Exemplo n.º 11
0
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
    })
    def post(self):

        postedData = request.get_json()

        # Verify validity of posted data
        status_code = DataCheck(postedData, "usdtogbp")
        if (status_code != 200):
            retJson = {
                "Message": "An error happened",
                "Status Code": status_code
            }
            return jsonify(retJson)

        # If i am here, then status_code == 200
        username = postedData["username"]
        password = postedData["password"]
        x = postedData["x"]
        x = int(x)

        # verifyCredentials
        retJson, error = verifyCredentials(username, password)
        if error:
            return jsonify(retJson)

        # Finding tokens
        tokens = users.find({"username": username})[0]["tokens"]

        # Verify token existance
        if tokens <= 0:
            return jsonify(generateReturnDictionary(303, "Not Enough Tokens"))

        # Convert the posted data since tokens exist using CurrencyRates module
        c = CurrencyRates()
        rb = c.convert('USD', 'GBP', x)
        # Conversion is ready, next step   ---->   Tokens = Tokens-1
        users.update_one({"username": username},
                         {"$set": {
                             "tokens": tokens - 1
                         }})
        return jsonify(generateReturnDictionary(200, rb))
Exemplo n.º 13
0
    def __init__(self, bot):
        self.bot = bot

        self.exchangeNames = {
            "EUR": ["eur", "euro member countries"],
            "IDR": ["idr", "indonesia rupiah"],
            "BGN": ["bgn", "bulgaria lev"],
            "ILS": ["ils", "israel shekel"],
            "GBP": ["gbp", "united kingdom pound"],
            "DKK": ["dkk", "denmark krone"],
            "CAD": ["cad", "canada dollar"],
            "JPY": ["jpy", "japan yen"],
            "HUF": ["huf", "hungary forint"],
            "RON": ["ron", "Romania New Leu"],
            "MYR": ["myr", "malaysia ringgit"],
            "SEK": ["sek", "sweden krona"],
            "SGD": ["sgd", "singapore dollar"],
            "HKD": ["hkd", "hong kong dollar"],
            "AUD": ["aud", "australia dollar"],
            "CHF": ["chf", "switzerland franc"],
            "KRW": ["krw", "korea won", "korea south won"],
            "CNY": ["cny", "china yun renminbi"],
            "TRY": ["try", "turkey lira"],
            "HRK": ["hrk", "croatia kuna"],
            "NZD": ["nzd", "new zealand dollar"],
            "THB": ["thb", "thailand baht"],
            "USD": ["usd", "united states dollar"],
            "NOK": ["nok", "norway krone"],
            "RUB": ["rub", "russia ruble"],
            "INR": ["inr", "india ruppe"],
            "MXN": ["mxn", "mexico peso"],
            "CZK": ["czh", "czech republic koruna"],
            "BRL": ["brl", "brazil real"],
            "PLN": ["pln", "poland zloty"],
            "PHP": ["php", "philippines peso"],
            "ZAR": ["zar", "south africa rand"]
        }
        self.CurrencyRates = CurrencyRates()
        self.CurrencyCodes = CurrencyCodes()
Exemplo n.º 14
0
    def save(self, *args, **kwargs):
        c = CurrencyRates()
        if not self.id:
            entry_risk = ((self.entry_price - self.stop_price)*self.position/self.instrument.tickunit)\
                             *self.instrument.tickprice*self.num_cons
            self.entry_risk = self.current_risk = c.convert(
                self.instrument.currency, 'USD', entry_risk)

        if self.exits.count() > 0:
            self.num_close_cons = self.exits.aggregate(
                Sum('num_cons'))['num_cons__sum']
            self.num_open_cons = self.num_cons - self.num_close_cons
        current_risk = ((self.current_price - self.stop_price)*self.position/self.instrument.tickunit)\
                         *self.instrument.tickprice*self.num_open_cons
        self.current_risk = c.convert(self.instrument.currency, 'USD',
                                      current_risk)
        current_profit = ((self.current_price - self.entry_price)*self.position/self.instrument.tickunit)\
                         *self.instrument.tickprice*self.num_open_cons
        self.current_profit = c.convert(self.instrument.currency, 'USD',
                                        current_profit)
        self.is_open = True if self.num_open_cons > 0 else False
        super(FuturesEntry, self).save(*args, **kwargs)
Exemplo n.º 15
0
def RealTimeCurrencyConversion():
    from forex_python.converter import CurrencyRates
    c = CurrencyRates()

    from_currency = variable1.get()
    to_currency = variable2.get()

    if (Amount1_field.get() == ""):
        tkinter.messagebox.showinfo(
            "Error !!", "Amount Not Entered.\n Please a valid amount.")

    elif (from_currency == "currency" or to_currency == "currency"):
        tkinter.messagebox.showinfo(
            "Error !!",
            "Currency Not Selected.\n Please select FROM and TO Currency form menu."
        )

    else:
        new_amt = c.convert(from_currency, to_currency,
                            float(Amount1_field.get()))
        new_amount = float("{:.4f}".format(new_amt))
        Amount2_field.insert(0, str(new_amount))
Exemplo n.º 16
0
def show_amount():
    """Show conversion result."""

    from_conv = request.args["convert_from"]
    to = request.args["convert_to"]
    try:
        amount = Decimal(request.args["amount"])
    except DecimalException:
        session['error'] = "Amount Is Not Valid"
        return redirect("/error")
    """ Request arguments """

    c = CurrencyRates()
    try:
        text = c.convert(from_conv, to, amount)
    except RatesNotAvailableError:
        session['error'] = "Invalid Currency Code"
        return redirect("/error")
    """ Convert currency """

    return render_template("conversion.html", text=text)
    """ Append conversion.html to browser. """
Exemplo n.º 17
0
def convert(e):
    c = CurrencyRates()

    from_currency = variable1.get()
    to_currency = variable2.get()

    try:
        if from_amount_entry.get() == '':
            tk.messagebox.showerror('Error', 'Please enter a valid amount.')

        elif from_currency == '' or to_currency == '':
            tk.messagebox.showerror('Error', 'Please select a currency pair.')

        else:
            new_amt = c.convert(from_currency, to_currency,
                                float(from_amount_entry.get()))
            new_amount = float(f'{new_amt:.2e}')

            to_amount_label.config(text=f'{new_amount:,}')

    except ValueError:
        tk.messagebox.showerror('Error', 'Please enter a valid amount.')
Exemplo n.º 18
0
def convert():
    try:
        amount = request.form["amount"]
        to = request.form["to"]
        from_code = request.form["from-code"]
        c = CurrencyRates()
        converted = c.convert(from_code, to, float(amount))

        def get_name_symbol(code):
            return next((item for item in currency_data if item["cc"] == code),
                        None)

        from_name = get_name_symbol(from_code)['name']
        to_symb = get_name_symbol(to)['symbol']
        to_name = get_name_symbol(to)['name']
        flash(
            f"{amount} {from_name} equals {to_symb}{round(converted, 2)} {to_name}",
            'success')
    except forex_python.converter.RatesNotAvailableError:
        flash(f"{from_code} to {to} conversion is currently not available.",
              'error')
    return redirect('/convert')
Exemplo n.º 19
0
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')
Exemplo n.º 20
0
def get_money_interval():

    user_difficulty = input("please put difficulty number:")
    user_difficulty_int = int(user_difficulty)
    c = CurrencyRates()
    currenecy = c.get_rate('USD', 'ILS')
    print(currenecy)
    print(
        "The machine will genrreate randon nmber, you will have to guess the value to ILS "
    )
    Random_number = int(random.randint(1, 101))

    print(Random_number)

    total_amount = Random_number * currenecy

    user_guess1 = int(
        input("user please a number what will be the Cuerrency "))
    user_guess2 = int(user_guess1 * currenecy)
    var1 = -1
    interval = int(user_difficulty_int - user_guess2)
    interval2 = int(user_difficulty_int + user_guess2)
    machine_sum = currenecy * Random_number
    user_guess = int(user_guess2 + interval + interval2)

    user_sum = int(currenecy * user_guess)

    try:
        if user_sum == machine_sum:
            print("yes you are correct")
        elif user_sum != machine_sum:
            print("NOPE - wrong guess Please play again")
    except:
        print("Worng calc")

#   exit()
    for x in range(2):
        return get_money_interval()
        break
Exemplo n.º 21
0
def quote(query, convert):  # Contata API e ajusta os valores de moeda
    try:
        c = CurrencyRates()  # Valores de moeda (Forex-Python)

        stock = str(query[0])
        amnt = int(query[1])

        tickr = Ticker(stock)  # Informaçoes da ação (yahooquery)
        data = tickr.summary_detail

        prc = data[stock]['regularMarketPreviousClose']
        currency = data[stock]['currency']

        if convert:  # Conversão de moeda
            prc = round(c.convert(currency, 'BRL', prc), 2)
            val = prc * amnt
            return [stock, prc, amnt, val, 'BRL']

        val = prc * amnt  # Sem conversão
        return [stock, prc, amnt, val, currency]
    except:
        return ['SÍMBOLO INVÁLIDO', 0, 0, 0]  # Em caso de erro interno
Exemplo n.º 22
0
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')
Exemplo n.º 23
0
class TestGetRate(TestCase):
    """
    Test get_rate function using valid and invalid currency codes
    """
    def setUp(self):
        self.c = CurrencyRates()

    def test_get_rate_with_valid_codes(self):
        rate = self.c.get_rate('USD', 'INR')

        # check if return value is float
        self.assertTrue(isinstance(rate, float))

    def test_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 float
        self.assertTrue(isinstance(rate, float))

    def test_get_rate_with_invalid_codes(self):
        # raise exception for invalid currency codes
        self.assertRaises(RatesNotAvailableError, self.c.get_rate, 'ABCD', 'XYZ')
Exemplo n.º 24
0
def convert():
    """Show index.html."""
    c = CurrencyRates()
    amount = request.form.get('amount')
    rate_from = request.form.get('rate-from')
    rate_too = request.form.get('rate-too')

    cc = CurrencyCodes()
    name_from = cc.get_currency_name(rate_from)
    name_to = cc.get_currency_name(rate_too)
    symbol = cc.get_symbol(rate_too)

    if not amount:
        con_rate = "{0:.2f}".format(round(c.get_rate(rate_from, rate_too), 2))
        return render_template("convert.html", con_rate=con_rate, name_from=name_from, name_to=name_to, symbol=symbol, rates=session.get("rates"), bit=session.get("bit"))

    else:
        con_rate = "{0:.2f}".format(
            round(c.convert(rate_from, rate_too, amount), 2))
        return render_template("convert.html",
                               con_rate=con_rate, name_from=name_from,
                               name_to=name_to, symbol=symbol,
                               rates=session.get("rates"), bit=session.get("bit"))
Exemplo n.º 25
0
 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
Exemplo n.º 26
0
def convert_to_all(input_currency, amount, currencies):
    """
    convert amount of input_currency to all supported currencies
    :param input_currency: input currency code
    :param amount: amount of input currency
    :param currencies: list of supported currencies codes
    :return: dictionary, key - currency code, value - converted amount of input_currency
    {
        <3 letter output currency code>: <float>
        ...
    }
    """
    output_dict = {}
    c = CurrencyRates()
    for curr in currencies:
        if curr == input_currency:
            continue
        try:
            rate = c.get_rate(input_currency, curr)
        except RatesNotAvailableError:
            continue
        output_dict[curr] = round(amount * rate, 2)
    return output_dict
Exemplo n.º 27
0
	def currencies():
		coins = ["bitcoin", "ethereum", "bitcoin-cash"]
		n = 0
		coin_usd = []
		coin_try = []
		for coin in coins[:]:
			url = "https://api.coinmarketcap.com/v1/ticker/"+coin+"/"
			#print("Fetching prices for " + coin + "...")
			resp = requests.get(url, verify=True) #verify is checking SSL certificate
			#if(resp.status_code != 200):
				#print("Status: ", resp.status_code,)
			data = json.loads(resp.text)[0]
			cr = CurrencyRates()
			usd = float(data['price_usd'])
			tl = cr.convert("USD","TRY",usd)
			coin_usd.append(usd)
			coin_try.append(tl)
			n += 1
		usdtry = cr.get_rate('USD','TRY')
		chftry = cr.get_rate('CHF','TRY')
		eurtry = cr.get_rate('EUR','TRY')
		result = "BTC: " + str(coin_usd[0]) + " USD" + "\n" + "ETH: " + str(coin_usd[1]) + " USD" + "\n" + "BCH: " + str(coin_usd[2]) + " USD" + "\n" + "USD/TRY: " + str(usdtry) + "\n" + "CHF/TRY: " + str(chftry) + "\n" + "EUR/TRY: " + str(eurtry) + "\n"
		return result
Exemplo n.º 28
0
class TestAmountConvert(TestCase):
    """
    test amount conversion from one currency to other
    """
    def setUp(self):
        self.c = CurrencyRates()

    def test_amount_convert_valid_currency(self):
        amount = self.c.convert('USD', 'INR', 10)

        # test if amount returned in float
        self.assertTrue(isinstance(amount, float))

    def test_amount_convert_date(self):
        date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date()
        amount = self.c.convert('USD', 'INR', 10, date_obj)

        # test if amount returned in float
        self.assertTrue(isinstance(amount, float))

    def test_amount_convert_invalid_currency(self):
        # test if amount returned in float
        self.assertRaises(RatesNotAvailableError, self.c.convert, 'ABC', 'XYZ', 10)
Exemplo n.º 29
0
    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]
Exemplo n.º 30
0
 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
Exemplo n.º 31
0
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 convert_curr():
    """Function that converts amount from one currency to another

    Args:
        None
    
    Return:
        None: only prints out the results
    """

    # create the currency instance
    curr_instance = CurrencyRates()

    # take user inputs
    amount = int(input("Enter the amount: "))
    from_currency = input("From Currency: ").upper()
    to_currency = input("To Currency: ").upper()

    print(from_currency, " To ", to_currency, amount)

    # perform the conversion
    result = curr_instance.convert(from_currency, to_currency, amount)
    print(result)
Exemplo n.º 33
0
def convert_currency():
    """
    The flask API for changing the currency rate from source currency to target
    currency.
    :return:
    """
    source = request.args.get('source')
    target = request.args.get('target')
    amount = request.args.get('amount')
    finding_date = request.args.get('date')

    cur_rates_obj = CurrencyRates(force_decimal=True)

    if not source or not target or not amount:
        return jsonify({
            'error': {
                'message': 'data not passed: source or target or amount.'
            },
            'status_code': 400
        })

    elif finding_date:
        date_obj = datetime.datetime.strptime(finding_date,
                                              '%d-%m-%Y,%H:%M:%S')
        value = cur_rates_obj.convert(source, target, Decimal(amount),
                                      date_obj)

    else:
        value = cur_rates_obj.convert(source, target, Decimal(amount))

    return jsonify({
        'source_currency': source,
        'target_currency': target,
        'amount': amount,
        'converted_value': value,
        'status_code': 200
    })
Exemplo n.º 34
0
class Currency():
    def __init__(self):
        self.cr = CurrencyRates()
        self.codes = CurrencyCodes()
        self.curr_codes = [
            'EUR', 'IDR', 'BGN', 'ILS', 'GBP', 'DKK', 'CAD', 'JPY', 'HUF',
            'RON', 'MYR', 'SEK', 'SGD', 'HKD', 'AUD', 'CHF', 'KRW', 'CNY',
            'TRY', 'HRK', 'NZD', 'THB', 'USD', 'NOK', 'RUB', 'INR', 'MXN',
            'CZK', 'BRL', 'PLN', 'PHP', 'ZAR'
        ]
        self.results = {'frm': '', 'to': '', 'amount': ''}

    def check_valid_code(self, frm, to, amount):
        results = self.results
        if frm in self.curr_codes:
            results['frm'] = 'ok'
        else:
            results['frm'] = 'no'
        if to in self.curr_codes:
            results['to'] = 'ok'
        else:
            results['to'] = 'no'
        if amount == '':
            results['amount'] = 'no'
        else:
            results['amount'] = 'ok'
        return self.handle_results(results, frm, to, amount)

    def handle_results(self, results, frm, to, amount):
        if 'no' in results.values():
            return self.give_error(results, frm, to)
        else:
            return self.conversion(frm, to, amount)

    def give_error(self, results, frm, to):
        if results['frm'] == 'no':
            flash(f'Not a valid code: {frm}')
        if results['to'] == 'no':
            flash(f'Not a valid code: {to}')
        if results['amount'] == 'no':
            flash('Not a valid amount.')
        return 'error'

    def conversion(self, frm, to, amount):
        x = self.codes.get_symbol(to)
        conv = self.cr.convert(frm, to, float(amount))
        conv = round(conv, 2)
        conv = (f'{x}{conv}')
        return conv
Exemplo n.º 35
0
class currencyfilter(absfilter):
    def __init__(self):
        self.__currency = CurrencyRates()

    def msgprocess(self, msg):
        text = ''
        allmatched = re.findall(u'(\d+日元)', msg)
        if len(allmatched) > 0:
            for matched in allmatched:
                jpy = matched[:-2]
                cny = self.__currency.convert('JPY', 'CNY', int(jpy))
                text += matched + ' => ' + str(cny) + u'人民币' + '\n'
            return text
        else:
            return None
Exemplo n.º 36
0
def convert():
    """ Display converted amount"""
    if request.method == 'POST':
        # storing three form inputs into variables
        first_currency = request.form.get("convert-from")
        second_currency = request.form.get("convert-to")
        amt = request.form.get("amount")
        # write 3 validation in the form of if statements
        if (first_currency in legit_currencies
                and second_currency in legit_currencies
                and amt.isalpha() is False):
            # if first_currency in legit_currencies
            # if they all pass, this is the HAPPY path
            currency_rate = CurrencyRates(force_decimal=True)
            converted_amount = round(
                currency_rate.convert(first_currency, second_currency,
                                      Decimal(amt)), 2)
            return render_template('converter.html',
                                   converted_amt=converted_amount)
        else:
            return render_template('base.html',
                                   first_currency=first_currency,
                                   second_currency=second_currency,
                                   error=True)
Exemplo n.º 37
0
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
Exemplo n.º 38
0
class TestAmountConvert(TestCase):
    """
    test amount conversion from one currency to other
    """
    def setUp(self):
        self.c = CurrencyRates()

    def test_amount_convert_valid_currency(self):
        amount = self.c.convert('USD', 'INR', 10)

        # test if amount returned in float
        self.assertTrue(isinstance(amount, float))

    def test_amount_convert_date(self):
        date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date()
        amount = self.c.convert('USD', 'INR', 10, date_obj)

        # test if amount returned in float
        self.assertTrue(isinstance(amount, float))

    def test_amount_convert_invalid_currency(self):
        # test if amount returned in float
        self.assertRaises(RatesNotAvailableError, self.c.convert, 'ABC', 'XYZ',
                          10)
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
Exemplo n.º 40
0
 def setUp(self):
     self.c = CurrencyRates()
Exemplo n.º 41
0
import xml.etree.ElementTree as ET
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)
Exemplo n.º 42
0
 def setUp(self):
     self.c = CurrencyRates(force_decimal=True)
Exemplo n.º 43
0
def forex(from_currency, to_currency, amount):
    try:
        currency_rates = CurrencyRates()
        return currency_rates.convert(from_currency, to_currency, amount)
    except:
        return amount