def convert(self, currency, code): # code_dict = {"USD": "$", "EUR": "€", "JAP": "¥"} if isinstance(currency, Currency): if code in self.rates: # if code in list(code_dict.keys()): # code = code_dict[code] abrev = "" if currency.code == "$": abrev = "USD" elif currency.code == "€": abrev = "EUR" elif currency.code == "¥": abrev = "JAP" if abrev == code: return Currency(currency.amount, code) else: return Currency( currency.amount * (self.rates[code] / self.rates[abrev]), code) else: raise UnknownCurrencyCodeError( "Do not have the rate for that currency") else: raise DifferentClassError( "Cannot convert something other than a Currency")
def GetSupportedCurrencies(self): ''' Get the supported API currencies. @returns: Collection of Currency objects containing currency code and description ''' jsonData = self._getApiJsonResponse(self._apiCurrencyList) indexSymbol = 'currency' indexDescription = 'country' currencyCollection = [] for data in jsonData: currencyData = '' try: currencyData = Currency(data[indexSymbol], data[indexDescription]) except Exception: currencyData = Currency(data[indexSymbol], '') currencyCollection.append(currencyData) return currencyCollection
def test_mixed_addition(): five_dollars = Currency(5, "USD") ten_euro = Currency(10, "EUR") bank = Bank() bank.addRate("EUR", "USD", 2) result = bank.reduce(five_dollars.plus(ten_euro), "USD") assert result == Currency(10, "USD")
def test_converter_handles_bigger_dictionary(self): converter_init = Converter({ 'usd': 1.0, 'eur': 0.94, 'aud': 1.34, 'jpy': 112.48 }) one_dollar_to_yen = converter_init.convert(Currency('usd', 1), 'jpy') self.assertEqual(one_dollar_to_yen, Currency('jpy', 112.48))
def getCurrencyData(): for url in uList: page = requests.get(url) soup = bs4.BeautifulSoup(page.content) currenciesForSite = [] for tr in soup.findAll('tr'): rows = tr.findAll('td') if "raffles1" in url and len(rows) == 5: iso = check(rows[0].find(text=True)) name = check(rows[1].find(text=True)) units = check(rows[2].find(text=True)) selling = check(rows[3].find(text=True)) #raffles site puts selling first buying = check(rows[4].find(text=True)) if iso and name and units and selling and buying is not None: c = Currency(iso,name,units,buying,selling,"raffles1") currenciesForSite.append(c) # print iso,name,units,selling,buying # print vars(c) else: pass mapping["raffles1"] = currenciesForSite elif "mustafa" in url and len(rows) == 7: iso = check(rows[2].find(text=True)) name = check(rows[3].find(text=True)) units = check(rows[4].find(text=True)) buying = check(rows[5].find(text=True)) #mustafa site puts buying first selling = check(rows[6].find(text=True)) if iso and name and units and selling and buying is not None: c = Currency(iso,name,units,buying,selling,"mustafa") currenciesForSite.append(c) # print iso,name,units,selling,buying #use these to check for unwanted values that went through # print vars(c) else: pass mapping["mustafa"] = currenciesForSite currenciesForSite = [] # print len(mapping["raffles1"]) # print len(mapping["mustafa"]) #remove duplicates # for site in mapping: # newList = [] # print site.upper() + "\n" # newList = removeDuplicates(mapping[site]) # print len(mapping[site]) # mapping[site] = newList # print len(newList) # for cObj in newList: # print vars(cObj) return mapping
def test_converter_handles_changing_currency_code(self): converter_init = Converter({ 'usd': 1.0, 'eur': 0.94, 'aud': 1.34, 'jpy': 112.48 }) euro_to_yen = converter_init.convert(Currency('eur', 1), 'jpy') self.assertEqual(euro_to_yen, Currency('jpy', 119.66))
def callback( instance ): # I don't know what instance is but the API says to use it. amount = float(value.text) original = button_1.text convert_to = button_two.text money = Currency(original, convert_to, amount) number = money.convert() # number = float(value.text) * 2.5 results_label.text = "{:,.2f} {}s".format(number, convert_to)
def main(): # file_input("Pepe.txt") gui = input("Do you want to use the G)UI or C)onsole?: ") if gui == 'C': mode = input("Do you wish to import custom currencies via a file? (y or n): ") valid = False while not valid: if mode == "y": valid = True dic, new_name = file_input() o = input("What is your starting currency?: ") name = input("What do you want to convert to?: ") amount = float(input("How much do you want to convert?: ")) money = Currency(o, name, amount) money.add_entry(new_name, dic) converted = money.convert() # money.show_rates() print("Converted {:,.2f} {} to {:,.2f} {}".format(amount, o, converted, name)) elif mode == "n": valid = True original = input("What is your starting currency?: ") amount = float(input("How much do you want to convert?: ")) name = input("What do you want to convert to?: ") money = Currency(original, name, amount) converted = money.convert() # money.show_rates() print("Converted {:,.2f} {} to {:,.2f} {}".format(amount, original, converted, name)) else: print("Invalid choice, try again...") valid = False else: GUI().run()
def buildCurrencyDict(self, filename): # Build Method with open(os.path.join(filename), "rt", encoding="utf8") as f: # Opens file to read text data reader = csv.reader(f) for row in reader: self.currencyDict[row[1]] = Currency( row[1], row[2], row[3]) # Value is Currency object return self.currencyDict
def convert(self, currency, currency_code): self.currency = currency self.currency_code = currency_code if currency.nation in self.dictionary and currency_code in self.dictionary: new_value = round( (currency.value * self.dictionary[currency_code]) / self.dictionary[currency.nation], 2) return Currency(currency_code, new_value) else: UnknownCurrencyCodeError()
def loadData(self, csvFile): try: with open(csvFile, encoding = 'utf-8') as csvFile: reader = csv.DictReader(csvFile) try: for row in reader: self._countryDict[row['name']] = Currency(row['currency_name'], row['currency_alphabetic_code']) except Exception: pass except FileNotFoundError: print('CSV file not found!') sys.exit(1)
def loadData(self, filename): with open(filename, encoding="utf8") as filename: reader = csv.reader(filename) try: for row in reader: self.currencydict[row[0]] = Currency( row[0], row[14], row[17]) except FileNotFoundError: print("File not found")
def fetchData(): for item in data: indiv = data[item] code = indiv['code'] alphaCode = indiv['alphaCode'] numericCode = indiv['numericCode'] name = indiv['name'] rate = indiv['rate'] date = indiv['date'] inverseRate = indiv['inverseRate'] currency = Currency(code, alphaCode, numericCode, name, rate, date, inverseRate) currencyArray.append(currency) codeList.append(currency.code)
class MtGoxAPI: _instance = None _config = None _mtgox = None _currency_pair = None _currency = None @classmethod def get_instance(cls, **kwargs): # try: if not 'config' in kwargs\ or not 'mtgox' in kwargs\ or not 'currency_pair' in kwargs: raise Exception('Dependencies missing') if cls._instance is None: cls._instance = MtGoxAPI() cls._instance._config = kwargs['config'] cls._instance._mtgox = kwargs['mtgox'] cls._instance._currency_pair = kwargs['currency_pair'] cls._instance._init_currency() # except Exception, e: # MtGoxAPI couldn't be initialised return cls._instance def _init_currency(self): self._currency = Currency(self._config) def _get_url(self, path, **kwargs): exchange = "" if 'exchange' in kwargs: exchange = kwargs['exchange'] + "/" #return api_base_url + exchange + path return exchange + path def get_balance(self): def _parse(resp): balance = resp["Wallets"]["AUD"]["Balance"]["display"] btc_balance = resp["Wallets"]["BTC"]["Balance"]["display"] return { "balance": balance, "btc_balance": btc_balance, } res = self._mtgox.request(self._get_url(self._config.get('service_mtgox', 'money_info_path'))) #print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) print(json.dumps(_parse(res))) return def get_money_info(self): res = self._mtgox.request(self._get_url(self._config.get('service_mtgox', 'money_info_path'))) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) def get_exchange(self): exchange_string = self._currency_pair.to_string() res = self._mtgox.request( self._get_url(self._config.get('service_mtgox', 'ticker_path'), exchange=exchange_string) ) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) return def get_quote(self): fixed_cur = self._currency_pair.get_fixed() aux_cur = self._currency_pair.get_variable() exchange_string = self._currency_pair.to_string() def convert_to_int_amount(amount_float): amount_int = self._currency.float_to_int(amount_float, fixed_cur) return int(amount_int) def convert_to_float_amount(amount_int): amount_float = self._currency.int_to_float(amount_int, aux_cur) return float(amount_float) def get_params(): print("Quote type? (bid, ask)") quote_type = input() print("Amount? (1.0 = 1.0BTC, 1.0 = 1.0AUD)") amount = float(input()) params = { 'type': quote_type, 'amount': convert_to_int_amount(amount) } return params path = self._config.get('service_mtgox', 'money_quote_path') res = self._mtgox.request( self._get_url(path,exchange=exchange_string), params=get_params() ) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) if 'amount' in res: quote = res["amount"] amount_float = convert_to_float_amount(quote) print("Quoted: {0} {1}".format(amount_float, self._currency_pair.get_variable())) return def add_buy_order(self): self.add_order('bid') def add_sell_order(self): self.add_order('ask') # merge with add_sell_order def add_order(self, order_type): fixed_cur = self._currency_pair.get_fixed() aux_cur = self._currency_pair.get_variable() exchange_string = self._currency_pair.to_string() def convert_to_int_amount(amount_float): amount_int = self._currency.float_to_int(amount_float, fixed_cur) return int(amount_int) def convert_to_float_amount(amount_int): amount_float = self._currency.int_to_float(amount_int, aux_cur) return float(amount_float) def get_params(): print("Amount? (1.0 = 1.0BTC, 1.0 = 1.0AUD)") amount = float(input()) print("Price (per bitcoin)? (optional for non market rate)") price = input() params = { 'type': order_type, 'amount_int': convert_to_int_amount(amount), } # if a limit rate is given, add the parameter if price: params['price_int'] = convert_to_int_amount(float(price)) return params path = self._config.get('service_mtgox', 'money_order_add_path') res = self._mtgox.request( self._get_url(path,exchange=exchange_string), params=get_params() ) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) return def view_open_orders(self): exchange_string = self._currency_pair.to_string() def get_params(): params = {} return params def get_orders(res): if 'success' in res: return res['data'] path = self._config.get('service_mtgox', 'money_order_info_path') res = self._mtgox.request( self._get_url(path,exchange=exchange_string), params=get_params() ) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) def view_closed_order(self): exchange_string = self._currency_pair.to_string() def get_params(): print("Quote type? (bid, ask)") order_type = input() print("Order id (oid)?") oid = str(input()) params = { 'type': order_type, 'order': oid } return params path = self._config.get('service_mtgox', 'money_order_result_path') res = self._mtgox.request( self._get_url(path,exchange=exchange_string), params=get_params() ) print(res) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) def cancel_order(self): exchange_string = self._currency_pair.to_string() def get_params(): print("Order id (oid)?") oid = input() params = { 'oid': str(oid) } return params path = self._config.get('service_mtgox', 'money_order_cancel_path') res = self._mtgox.request( self._get_url(path,exchange=exchange_string), params=get_params() ) print(json.dumps(res, sort_keys=True, indent=4, separators=(',', ': '))) def _set_currency(self): currencies = self._currency_pair.get_currencies() print("Choose a currency: ") for i in range(len(currencies) - 1): print(str(i + 1) + ") " + currencies[i]) cur = int(input()) return currencies[cur - 1] def set_fixed_cur(self): #cur = _set_currency() #currency_pair.set_fixed(cur) print("Fixed at BTC currently") return def set_variable_cur(self): cur = self._set_currency() self._currency_pair.set_variable(cur) self._currency = Currency(self._config)
def _init_currency(self): self._currency = Currency(self._config)
def set_variable_cur(self): cur = self._set_currency() self._currency_pair.set_variable(cur) self._currency = Currency(self._config)
def test_reduce_different_currencies(): bank = Bank() bank.addRate("EUR", "USD", 2) result = bank.reduce(Currency(2, "EUR"), "USD") assert result == Currency(1, "USD")
def setUpCurrency(): if not DataProvider.ChosenCurrency: pln = Currency("PLN", [1, 2, 5]) return pln
def test_get_error_if_unknown_currency_code(self): converter_init = Converter({'usd': 1.0, 'eur': 0.94, 'aud': 1.34}) euro_to_yen = converter_init.convert(Currency('eur', 1), 'jpy') self.assertRaises(UnknownCurrencyCodeError)
def test_simple_addition(): summed = Currency(5, "USD").plus(Currency(1, "USD")) bank = Bank() reduced = bank.reduce(summed, "USD") assert reduced == Currency(6, "USD")
def testPlusReturnsSum(): five = Currency(5, "USD") one = Currency(1, "USD") result = five.plus(one) assert result.augend == five assert result.addend == one
def test_converter_handles_changing_currency_code(self): converter_init = Converter({'usd': 1, 'eur': 0.94}) one_dollar_to_euro = converter_init.convert(Currency('usd', 1), 'eur') self.assertEqual(one_dollar_to_euro, Currency('eur', 0.94))
def test_converter_makes_same_currency_the_same(self): converter_init = Converter({'usd': 1, 'eur': 0.94}) one_dollar = Currency('usd', 1) other_dollar = converter_init.convert(Currency('usd', 1), 'usd') self.assertEqual(one_dollar, other_dollar)
from Currency import Currency c = Currency("$", 5) d = c e = Currency("#", 5) f = Currency("$", 10) g = Currency("#", 10) h = 2 # (c == d), (c != e), (c != f), (c != g) def test_is_equal(c, d): assert (c == d) == True def test_code_is_not_equal(c, e): assert (c == e) == False def test_amount_is_not_equal(c, f): assert (c == f) == False def test_neither_is_equal(c, g): assert (c == g) == False def test_multiply_currencies(c, h): assert (c.multiply(h)) == 10 def test_multiply_currencies(c, h): assert (c.multiply(h)) == DifferentCurrencyCodeError
def test_reduce_sum(): summed = Currency(5, "USD").plus(Currency(1, "USD")) bank = Bank() reduced = bank.reduce(summed, "USD") assert reduced == Currency(6, "USD")
def parse_file_name(self, file_name): """ Maps Dukascopy file name elements to individual information components: * currency: Instrument in slashed format * curr_clean: in clean format * time_frame: bar size * price_type: bid or ask :param file_name: :return: _name_info, information elements found on name """ # PARSE CURRENCY _name_info = dict() _fn_comps = file_name.split("_") _curr_clean = _fn_comps[0] _tf_raw = _fn_comps[1] _price_type = _fn_comps[2] _cr = Cr.Currency() _name_info["represent"] = "CANDLE" try: _name_info["instrument"] = _fn_comps[0] #_name_info["curr_clean"] = _curr_clean except KeyError as e: raise Exception(f"Currency code {e} was not found") _tf_comps = _tf_raw.split(" ") _time_frame = None if len(_tf_comps) == 1: if _tf_comps[0].lower() == "monthly": _time_frame = "M" elif _tf_comps[0].lower() == "weekly": _time_frame = "W" elif _tf_comps[0].lower() == "daily": _time_frame = "D" elif _tf_comps[0].lower() == "hourly": _time_frame = "H1" else: raise Exception(f"Time Frame {_tf_comps[0]} is not valid") elif len(_tf_comps) == 2: if _tf_comps[1].lower() == "hours": _time_frame = f"H{_tf_comps[0]}" elif _tf_comps[1].lower() == "mins": _time_frame = f"m{_tf_comps[0]}" elif _tf_comps[1].lower() == "min": _time_frame = "m1" else: raise Exception(f"Time frame {_tf_raw} not valid") if _time_frame is None: raise Exception(f"Time frame not mapped for file {file_name}") _name_info["bar_size"] = _time_frame _name_info["price_type"] = _price_type self.file_name_info = _name_info return _name_info
from Currency import Currency currency = Currency() print(currency.convert(10)) # this converts this Dollar amount to Euro. Need to figure out how to input different currency values...
def test_multiplication(): five = Currency(5) assert five.times(2) == Currency(10) assert five.times(3) == Currency(15)
def convert(self, currency, to_code): try: return Currency(to_code, round(currency.amount * (self.rates[to_code]/self.rates[currency.currency_code]), 2)) except: raise UnknownCurrencyCodeError()
from Currency import Currency five_dollars = Currency("$5") my_money = Currency("5", "USD") def test_print(): assert str(five_dollars) == "$5.0" def test_is_equal(): assert my_money == five_dollars test_print() test_is_equal()
def __init__(self, value = 0): Currency.__init__(self, "HUF", "Hungarian National Bank", 0) self.value = value
def test_equality(): five_dollars = Currency(5, "USD") assert five_dollars == Currency(5, "USD") assert five_dollars != Currency(6, "USD") five_euro = Currency(5, "EUR") assert five_dollars != five_euro
def test_reduce(): bank = Bank() result = bank.reduce(Currency(1, "USD"), "USD") assert result == Currency(1, "USD")