def convertCurrency(): """ Convert from one currency to other. """ try: click.echo(chalk.blue("Enter currency codes seperated by space:")) currency_name_from, currency_name_to = input().split() currency_rate_per_unit = currency_rates.get_rates( currency_name_from)[currency_name_to] click.echo( currency_codes.get_symbol(currency_name_from) + " 1" + " = " + currency_codes.get_symbol(currency_name_to) + " " + str(currency_rate_per_unit)) click.echo("Enter the amount in " + currency_name_from + " to be converted to " + currency_name_to) currency_amount_to_be_converted = int(input()) converted_amount = convert(currency_name_from, currency_name_to, currency_amount_to_be_converted) click.echo( str(currency_amount_to_be_converted) + " " + currency_name_from + " = " + str(converted_amount) + " " + currency_name_to) except RatesNotAvailableError: click.echo( chalk.red( "Currency code does not exist. Try with some other currency code" )) except: click.echo(chalk.red("Something went wrong. Try again!"))
def convert_money(val_from, val_to, amount): ans = input('Желаете ввести дату?\n1 - Да\n2 - Нет\n') while ans != '1' or ans != '2': if ans == '1': date = input('Введите дату в формате DD.MM.YYYY: ').split('.') write_to_file(val_from, val_to, amount, int(date[2]), int(date[1]), int(date[0])) return round( convert(val_from, val_to, amount, date_obj=datetime.date(int(date[2]), int(date[1]), int(date[0]))), 3) elif ans == '2': write_to_file(val_from, val_to, amount) return round(convert(val_from, val_to, amount), 3) else: ans = input('Ошибка ввода, попробуйте еще: ')
def perevod(convert_from, convert_to, kol): print('Вводить дату? (Y/N): ') vvod = input() while vvod != 'Y' or vvod != 'N' or vvod != 'y' or vvod != 'n': if vvod == 'y' or vvod == 'Y': date = get_date() into_file(convert_from, convert_to, kol, date[2], date[1], date[0]) return round( convert(convert_from, convert_to, kol, date_obj=datetime.date(date[2], date[1], date[0])), 2) elif vvod == 'n' or vvod == 'N': print('Дата установлена текущая') into_file(convert_from, convert_to, kol, datetime.datetime.today().year, datetime.datetime.today().month, datetime.datetime.today().day) return round(convert(convert_from, convert_to, kol), 2) else: print('Ошибка ввода, попробуйте еще: ') vvod = input()
def main(argv): period = 10 while True: print('#####') ##this code is executed every period ##update quariga trading summary and the quadriga order book quadriga_summary.update() order_book.update() ##update price from bitfinex, convert to CAD and append to the price history list priceticker = fiat.convert( 'USD', 'CAD', bf_client.ticker(settings.CURRENCY + 'usd')['mid']) price_history.appendPrice(priceticker) ma5 = price_history.getMovingAverageForMinutes(1) ema20 = price_history.getExpMovingAverageForMinutes(1) print("MA5: ", ma5) print("EMA: ", ema20) ##BUY if (priceticker > price_history.getMovingAverage()): print('avove total MA, price increasing..') if (ma5 is None): print('no ma5 YET..') else: #print('ma5: ', ma5) if (analysis.checkIfGoodDeal(float(order_book.asks[0][0]), priceticker, True)): print("buy this: ", order_book.asks[0]) print('its a good deal as the bitfinex price is: ', priceticker) ##SELL if (priceticker < price_history.getMovingAverage()): print('under total MA, price decreasing..') if (ma5 is None): print('no MA5 yet..') else: #print('ma5: ', ma5) if (analysis.checkIfGoodDeal(float(order_book.bids[0][0]), priceticker, False)): print("sell this: ", order_book.bids[0]) print('its a good deal as the bitfinex price is: ', priceticker) time.sleep(period) ##rest 10 seconds (end of loop)
def write_to_file(val_from, val_to, amount, year=datetime.datetime.today().year, month=datetime.datetime.today().month, day=datetime.datetime.today().day): file = open('history.txt', 'a') file.write( 'Конвертировал ' + str(amount) + ' ' + str(val_from) + ' в ' + str(val_to) + ' по курсу ' + str( round( get_rate(val_from, val_to, date_obj=datetime.date(year, month, day)), 3)) + ' и получил ' + str( round( convert(val_from, val_to, amount, date_obj=datetime.date(year, month, day)), 3)) + '\n') file.close()
def test_amount_convert_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() amount = convert('USD', 'INR', 10, date_obj) # test if amount returned in float self.assertTrue(isinstance(amount, float))
def test_amount_convert_valid_currency(self): amount = convert('USD', 'INR', 10) # test if amount returned in float self.assertTrue(isinstance(amount, float))
def test_amount_convert_valid_currency_same_currency(self): amount = convert('USD', 'USD', 10) self.assertEqual(amount, float(10))
# https://pypi.org/project/CurrencyConverter/ # https://stackoverflow.com/questions/44604440/forex-historical-data-in-python import pandas as pd from datetime import date, datetime from forex_python.converter import get_rate, convert my_cols = ['TransID', 'Date', 'Currency', 'Net'] df = pd.read_csv('example_data.txt', names=my_cols, sep=',') df = df.drop(df.index[0]) df.head() df.columns df['TransID'] df['Date'] df['Currency'] df['Net'] for index, row in df.iterrows(): # print(row['Date'], row['Net']) curr = 'USD' am = float(row['Net']) t1 = row['Date'] t2 = str.split(t1, '-') y, m, d = int(t2[0]), int(t2[1]), int(t2[2]) # c = CurrencyConverter() # c.convert(am, 'USD', 'EUR',date=date(y, m, d)) # converts from USD to EUR t = datetime(y, m, d) converted = (convert('USD', 'EUR', am, t)) # with forex_python print(row['Date'], y, m, d, am, converted)
from forex_python.converter import convert print('Conversion from USD to PHP: ₱{:,.2f}'.format( convert("USD", "PHP", 56000)))
def main(args): # argument parser setup parser = argparse.ArgumentParser(description='currency converter') parser.add_argument('-a', '--amount', type=float, help='Amount to convert', required=True) parser.add_argument('-i', '--input_currency', type=str, help='Currency to convert', required=True) parser.add_argument('-o', '--output_currency', type=str, help='Currency to be converted to', required=False) if args: arguments = parser.parse_args(args) else: arguments = parser.parse_args() # get currency exchange rates converter = forex_python.converter.CurrencyRates() output = {} # check input arguments, convert symbols to 3 letter code if len(arguments.input_currency) > 3: fatalError("Invalid input currency!") else: input_currency = symbol_converter(arguments.input_currency) if arguments.output_currency: if len(arguments.output_currency) > 3: fatal_error("Invalid output currency!") else: output_currency = symbol_converter(arguments.output_currency) # convert input currency to desired output currency try: output[arguments.output_currency] = converter.convert( input_currency, output_currency, arguments.amount) except (forex_python.converter.RatesNotAvailableError, forex_python.converter.DecimalFloatMismatchError): fatal_error("Unable to convert, " "chceck currency format or " "if currency you've entered is supported.") output = { symbol_converter(key): round(value, 3) for key, value in output.items() } else: # convert input currency to all availible currencies try: currency_dict = converter.get_rates(input_currency) except (forex_python.converter.RatesNotAvailableError, forex_python.converter.DecimalFloatMismatchError): fatal_error("Unable to convert, " "chceck input currency format or " "if currency you've entered is supported.") output = { key: round(value * arguments.amount, 3) for key, value in currency_dict.items() } del output[input_currency] # print or return results in specified format result = json.dumps( { "input": { "amount": arguments.amount, "currency": input_currency }, "output": output }, indent=4) if args: return result else: print(result)