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 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 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 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 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_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 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 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 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 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 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 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 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)
def test_multiplication(): five = Currency(5) assert five.times(2) == Currency(10) assert five.times(3) == Currency(15)
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 setUpCurrency(): if not DataProvider.ChosenCurrency: pln = Currency("PLN", [1, 2, 5]) return pln
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_simple_addition(): 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
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()
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)
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)
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_reduce_sum(): summed = Currency(5, "USD").plus(Currency(1, "USD")) bank = Bank() reduced = bank.reduce(summed, "USD") assert reduced == Currency(6, "USD")
def test_reduce(): bank = Bank() result = bank.reduce(Currency(1, "USD"), "USD") assert result == Currency(1, "USD")
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 test_currency_instance(self): one_dollar = Currency('usd', 1) self.assertIsInstance(one_dollar, Currency)
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))
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