def RealTimeCurrencyExchangeRate1(inrvalue1): c1 = CurrencyRates() print(inrvalue1) print(c1.get_rate('INR', 'USD')) usdValue1 = inrvalue1 * c1.get_rate('INR', 'USD') print(usdValue1) return usdValue1
def normalize_currency(job_entry): c = CurrencyRates() if job_entry.currency == 'USD': job_entry.salary *= round(float(c.get_rate('USD', 'RUB'))) if job_entry.currency == 'EUR': job_entry.salary *= round(float(c.get_rate('EUR', 'RUB'))) return job_entry
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 __init__(self): c = CurrencyRates() self.languages = [ "Swift", "Assembler", "Pascal", "Elixir", "CSS3", "Scala", "HTML", "NoSQL", "Python", "Ruby", "C#", "Fortran", "Lisp", "Matlab", "Objective-C", "HTML5", "Go", "SCSS", "Erlang", "PHP", "Kotlin", "SQL", "Rust", "Flutter", "Julia", "CSS", "C++", "Golang", "TypeScript", "JavaScript", "C", "Java", "VBA", "R", "Lua", "Dart" ] self.languages_lower = [ 'swift', 'assembler', 'pascal', 'elixir', 'css3', 'scala', 'html', 'nosql', 'python', 'ruby', 'c#', 'fortran', 'lisp', 'matlab', 'objective-c', 'html5', 'go', 'scss', 'erlang', 'php', 'kotlin', 'sql', 'rust', 'flutter', 'julia', 'css', 'c++', 'golang', 'typescript', 'javascript', 'c', 'java', 'vba', 'r', 'lua', 'dart' ] self.EUR = c.get_rate('EUR', 'PLN') self.USD = c.get_rate('USD', 'PLN') self.GBP = c.get_rate('GBP', 'PLN') print(" EUR:", self.EUR, " USD:", self.USD, " GBP:", self.GBP) self.links = [] self.today = date.today() self.driver = webdriver.Firefox() self.driver.get("https://justjoin.it/") sleep(2)
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()
class TestForceDecimalAmountConvert(TestCase): """ Test the force_decimal=True type enforcing """ def setUp(self): self.c = CurrencyRates(force_decimal=True) def test_amount_decimal_convert(self): amount = self.c.convert('USD', 'INR', Decimal('10.45')) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_convert_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() amount = self.c.convert('USD', 'INR', Decimal('10.45'), date_obj) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_invalid_type(self): self.assertRaises(DecimalFloatMismatchError, self.c.convert, 'USD', 'INR', 10.45) def test_decimal_get_rates_valid_code(self): all_rates = self.c.get_rates('USD') # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() all_rates = self.c.get_rates('USD', date_obj) # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_invalid_code(self): self.assertRaises(RatesNotAvailableError, self.c.get_rates, 'XYZ') def test_decimal_get_rate_with_valid_codes(self): rate = self.c.get_rate('USD', 'INR') # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() rate = self.c.get_rate('USD', 'INR', date_obj) # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_invalid_codes(self): # raise exception for invalid currency codes self.assertRaises(RatesNotAvailableError, self.c.get_rate, 'ABCD', 'XYZ')
def convert_currency(a, tocurrency): c = CurrencyRates() if tocurrency == 'usd': return (a * (c.get_rate('INR', 'USD'))) if tocurrency == 'usd': return (a * (c.get_rate('INR', 'GBP'))) if tocurrency == 'EUR': return (a * (c.get_rate('INR', 'EUR')))
class TestForceDecimalAmountConvert(TestCase): """ Test the force_decimal=True type enforcing """ def setUp(self): self.c = CurrencyRates(force_decimal=True) def test_amount_decimal_convert(self): amount = self.c.convert('USD', 'INR', Decimal('10.45')) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_convert_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() amount = self.c.convert('USD', 'INR', Decimal('10.45'), date_obj) self.assertTrue(isinstance(amount, Decimal)) def test_amount_decimal_invalid_type(self): self.assertRaises(DecimalFloatMismatchError, self.c.convert, 'USD', 'INR', 10.45) def test_decimal_get_rates_valid_code(self): all_rates = self.c.get_rates('USD') # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() all_rates = self.c.get_rates('USD', date_obj) # Check if return value of get_rates dictionary self.assertTrue(isinstance(all_rates, dict)) # Test at least one rate value returned self.assertTrue(len(all_rates.keys())) # Test one rate in returned dict is now a Decimal self.assertTrue(isinstance(all_rates.get('INR'), Decimal)) def test_decimal_get_rates_invalid_code(self): self.assertRaises(RatesNotAvailableError, self.c.get_rates, 'XYZ') def test_decimal_get_rate_with_valid_codes(self): rate = self.c.get_rate('USD', 'INR') # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() rate = self.c.get_rate('USD', 'INR', date_obj) # check if return value is Decimal self.assertTrue(isinstance(rate, Decimal)) def test_decimal_get_rate_with_invalid_codes(self): # raise exception for invalid currency codes self.assertRaises(RatesNotAvailableError, self.c.get_rate, 'ABCD', 'XYZ')
def get_exchange(): c = CurrencyRates() try: res = dict(eur=c.get_rate('EUR', 'RUB'), usd=c.get_rate('USD', 'RUB')) except Exception as e: res = dict(eur=-0.1, usd=-0.1) res['usd'] = SHORT_FLOAT_STR.format(res['usd']) res['eur'] = SHORT_FLOAT_STR.format(res['eur']) return res
def exchangerates(country_currency): c = CurrencyRates() try: exchange_rate = c.get_rate('USD', country_currency) except: exchange_rate = "Not Available :(" return exchange_rate
def currency_convertor(request): c = CurrencyRates() s = CurrencyCodes() currency_list = { 'USD', 'EUR', 'JPY', 'GBP', 'AUD', 'CAD', 'CHF', 'CNY', 'SEK', 'NZD', 'MXN', 'SGD', 'HKD', 'INR' } if request.method == "POST": trade_size1_3 = request.POST['trade_size1_3'] if trade_size1_3 is '': trade_size1_3 = 1 else: trade_size1_3 = float(trade_size1_3) cur_1 = request.POST['sel1_1'] cur_2 = request.POST['sel1_2'] if cur_2 == cur_1: cur_2 = 'INR' cur_1 = 'USD' symbol = s.get_symbol(cur_2) rate = c.get_rate(cur_1, cur_2) value = rate * trade_size1_3 one = 1 return render( request, 'currency_convertor.html', { 'currencyList': currency_list, 'value': value, 'symbol': symbol, 'from_currency': cur_1, 'to_currency': cur_2, 'rate': rate, 'one': one }) return render(request, 'currency_convertor.html', {'currencyList': currency_list})
def get_exchange_rate(currency1: str, currency2: str) -> float: if currency1 == currency2: return 1 c = CurrencyRates() rate = c.get_rate(currency1, currency2) del c return rate
def change_money(val1, val2, money, tup, history): c = CurrencyRates() if tup == (): a = c.convert(val1, val2, money) s = 'Конвертировал ' + str(money) + ' ' + val1 + ' в ' + val2 s += ' по курсу ' + str(c.get_rate(val1, val2)) + ' и получил ' s += str(a) + ' ' + val2 history.append(s) return a else: a = c.convert(val1, val2, money, tup) s = 'Конвертировал ' + str(money) + ' ' + val1 + ' в ' + val2 s += ' по курсу ' + str(c.get_rate(val1, val2, tup)) + ' и получил ' s += str(a) + ' ' + val2 history.append(s) return a
def exchangerates(country_currency): c = CurrencyRates() try: exchange_rate = c.get_rate('USD', country_currency) except: exchange_rate = "Sorry, the Exchange Rate is Currently Not Available :(" return exchange_rate
def main(): """Main program loop.""" banner = 'convert_currency version {0}'.format(VERSION) options = parse_arguments(banner) options['fee'] = 100 + options['fee'] try: options['date'] = datetime.strptime(options['date'], '%Y-%m-%d') except ValueError as exception: print('Dates must be in the form YYYY-mm-dd: {0}'.format( exception, file=sys.stderr)) sys.exit(-1) rates = CurrencyRates() print('Converting from {0} to {1}'.format(options['from'], options['to'])) try: rate = rates.get_rate(options['from'], options['to'], options['date']) add_fee, subtract_fee = calculate_fees(rate, options['fee'], 5) print('{0} {1:>10} {2:>10} {3:>10}'.format( options['date'].strftime('%Y-%m-%d'), subtract_fee, rate, add_fee)) if options['amount']: total = round(rate * options['amount'], 2) add_fee, subtract_fee = calculate_fees(total, options['fee'], 2) print(' {0:>6} {1} = {2:>10} {3:>10} {4:>10} {5}'.format( options['amount'], options['from'], subtract_fee, total, add_fee, options['to'])) except RatesNotAvailableError as exception: print('Could not convert rates: {0}'.format(exception), file=sys.stderr)
def get_rate(conn): """ 美元汇率查看 :param conn: :return: """ now = datetime.datetime.now() current_time = now.strftime("%Y-%m-%d %H:%M:%S") stamp_current_time = datetime.datetime.strptime(current_time, '%Y-%m-%d %H:%M:%S') c = CurrencyRates() c.get_rates('USD') # 查看美元最新汇率 stock_price = c.get_rate('USD', 'CNY') # 人民币汇率 stock_time = str(current_time) stock_name = '人民币汇率' stock_applies = None spider_data = stamp_current_time # 更新美元汇率 sql_update = """ UPDATE public.stock_code SET stock_time = %s, spider_data = %s, stock_name= %s, stock_price= %s, stock_applies= %s WHERE stock_name = '人民币汇率' """ sql_params = [ stock_time, spider_data, stock_name, stock_price, stock_applies ] logger.debug(sql_update) logger.debug(sql_params) execute_sql(conn, sql_update, sql_params)
def test_asset_allocation(self): """ Test asset allocation method. """ p = Portfolio() tickers = ["VCN.TO", "ZAG.TO", "XAW.TO", "TSLA"] quantities = [2, 20, 10, 4] p.easy_add_assets(tickers=tickers, quantities=quantities) asset_alloc = p.asset_allocation() self.assertAlmostEqual(sum(asset_alloc.values()), 100., 7) rates = CurrencyRates() prices = [ yf.Ticker(ticker).info["ask"] * rates.get_rate(yf.Ticker(ticker).info["currency"], "CAD") for ticker in tickers ] total = np.sum(np.asarray(quantities) * np.asarray(prices)) n = len(tickers) for i in range(n): self.assertAlmostEqual(asset_alloc[tickers[i]], quantities[i] * prices[i] / total * 100., 1)
def get_currency_rate(x, y): if x == '': x = y c = CurrencyRates() r = c.get_rate(x, y) print(r) return r
def _fetch_single_rate(self, provider: converter.CurrencyRates, base_currency: str, currency: str, date_obj: date) -> []: """ Fetch one conversion rate between a currency and a base currency at a given date :param provider: provider of the values :param base_currency: base currency :param currency: currency to convert from :param date_obj: date of value :return: List of rates """ try: value = provider.get_rate(dest_cur=currency, base_cur=base_currency, date_obj=date_obj) return [ self.serializer(base_currency=base_currency, currency=currency, date=date_obj, value=value) ] except converter.RatesNotAvailableError as e: logging.error(e) raise RatesNotAvailableError
def __init__(self, account, instrument, mode, quantity, margin): self.account = account self.instrument = instrument self.mode = mode self.quantity = quantity self.open_price = account.price_tables[instrument][INVERTED_MODE[ mode.value]] self.target_price = account.price_tables[instrument][mode.value] self.spread = abs(self.open_price - self.target_price) self.margin = margin c = CurrencyRates() eur_mult = c.get_rate('EUR', instrument.value[:3]) self.conv_rate = eur_mult * \ c.get_rate(instrument.value[:3], instrument.value[3:]) self.used_funds = margin * quantity / \ self.conv_rate * self.target_price
def main(): config = load_config() if config["currency"] == "USD": rate = 1 else: c = CurrencyRates() rate = c.get_rate('USD', config["currency"]) wb = load_workbook(resource_path("./stockx_book.xlsx")) ws = wb['Sheet1'] for row in ws.iter_rows(min_row=config["start-row"]): if row[0].value == None: break print(f'Doing {row[0].value}') urlkey = search_product(row[0].value) row[6].value = "Stockx" row[6].hyperlink = f'https://stockx.com/{urlkey}' result = product_info(urlkey, str(row[2].value)) row[1].value = result["title"] if result["uuid"] == None: print("Size not found, check if W or Y is needed.") sales = get_sales(result["uuid"]) row[4].value = round((sales["last"] * rate), 2) row[5].value = round((sales["average"] * rate), 2) now = datetime.now() dt_string = now.strftime("%d/%m/%Y %I:%M:%S %p") row[7].value = dt_string wb.save(resource_path("./stockx_book.xlsx"))
def final_rate(self): c = CurrencyRates() if self.is_eur: return 1 else: self.rate = c.get_rate(self.currency.upper(), settings.PAYMENTS_CH_EUR.upper()) return self.rate * 0.99
def get_currency(from_currency, to_currency): from forex_python.converter import CurrencyRates c = CurrencyRates() result = c.get_rate(from_currency, to_currency) #get currency rate between CAD and CNY print("Result: \n", "from currency", from_currency, "to currency", to_currency, " is ", result) return result
def convert(arg1, arg2, amount): try: c = CurrencyRates() value = round(amount * c.get_rate(arg1, arg2), 2) return value except: value = 0 return value
def get_last_month_data(self): cur = CurrencyRates() x = [] y_usd = [] y_aud = [] y_jpy = [] last_month_date = datetime.datetime.now().replace( hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(-29) count_date = 0 while count_date < 30: x.append(last_month_date.strftime('%Y-%m-%d')) y_usd.append(cur.get_rate('USD', 'CNY', last_month_date)) y_aud.append(cur.get_rate('AUD', 'CNY', last_month_date)) y_jpy.append(cur.get_rate('JPY', 'CNY', last_month_date)) last_month_date += datetime.timedelta(1) count_date += 1 return (x, y_usd, y_aud, y_jpy)
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: buy_currency = tracker.get_slot("buy_currency") sell_currency = tracker.get_slot("sell_currency") c = CurrencyRates() ex_rate = c.get_rate(buy_currency.upper(), sell_currency.upper()) d = datetime.today().strftime("%m/%d/%Y") return [SlotSet("exchange_rate", ex_rate), SlotSet("date", d)]
def get_dollar_won_rate(self): ''' url = 'https://v6.exchangerate-api.com/v6/ ''' print('환율정보 받아오는중') today = datetime.date.today() c = CurrencyRates() rate = c.get_rate('USD', 'KRW', today) return today.strftime("%Y-%m-%d"), rate / 10000.
def convert(input_val, ouput_val, amount, date=datetime.now()): c = CurrencyRates() itog = c.convert(input_val, ouput_val, amount, date) with open('history.txt', 'a') as f: history = 'конвертировал {} {} в {} по курсу {} и получил {} {}\n'.format( amount, input_val, ouput_val, c.get_rate(input_val, ouput_val), itog, ouput_val) f.write(history) return itog
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') # Inconsistent results for Euro after broken API was updated if isinstance(eur_to_sek, str): eur_to_sek = float(eur_to_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, Loader=yaml.SafeLoader) url_string = 'http://{}:{}@{}:{}'.format( server_settings['statusdb'].get('username'), server_settings['statusdb'].get('password'), server_settings['statusdb'].get('url'), server_settings['statusdb'].get('port') ) couch = Server(url_string) 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_in_SEK') current_eur = get_current(db, 'EUR_in_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)
def create_europe_esl_sunday(self, contents): contents = self.create_tournament(contents) currency_converter = CurrencyRates() eur_exchange_rate = currency_converter.get_rate('EUR', 'USD') contents = contents.replace("VOGANBOT_TOTAL_PRIZE", str(150 * eur_exchange_rate)) return contents
def GetCurrency(): global userData, data c = CurrencyRates() try: data['currency']['EUR2RUB'] = round(c.get_rate('EUR', 'RUB'), 2) data['currency']['USD2RUB'] = round(c.get_rate('USD', 'RUB'), 2) except requests.exceptions.RequestException as e: data['currency']['error'] = "No internet connection" else: data['currency']['error'] = None
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)
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)
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')
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)
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)