def test_description(self): c = currency('eur') self.assertEqual(c.description(), 'EUR / USD Spot Exchange Rate') c = currency('chf') self.assertEqual(c.description(), 'USD / CHF Spot Exchange Rate') c = currency('usd') self.assertEqual(c.description(), 'Dollar')
def test_description(): c = currency('eur') assert c.description() == 'EUR / USD Spot Exchange Rate' c = currency('chf') assert c.description() == 'USD / CHF Spot Exchange Rate' c = currency('usd') assert c.description() == 'Dollar'
def currency_list(queryset): currencies = queryset.values('currency').distinct().order_by('currency') currency_dict = [ {'name': CURRENCIES[ccy.currency(c['currency']).code], 'code': ccy.currency(c['currency']).code} for c in currencies ] return currency_dict
def test_as_cross(): c1 = currency('eur') c2 = currency('chf') assert c1.as_cross() == 'EURUSD' assert c2.as_cross() == 'USDCHF' assert c1.as_cross('/') == 'EUR/USD' assert c2.as_cross('/') == 'USD/CHF'
def currency_list(queryset): currencies = queryset.values("currency").distinct().order_by("currency") currency_dict = [ {"name": CURRENCIES[ccy.currency(c["currency"]).code], "code": ccy.currency(c["currency"]).code} for c in currencies ] return currency_dict
def test_as_cross(self): c1 = currency('eur') c2 = currency('chf') self.assertEqual(c1.as_cross(), 'EURUSD') self.assertEqual(c2.as_cross(), 'USDCHF') self.assertEqual(c1.as_cross('/'), 'EUR/USD') self.assertEqual(c2.as_cross('/'), 'USD/CHF')
def test_swap(): c1 = currency('eur') c2 = currency('chf') inv, a1, a2 = c1.swap(c2) assert not inv assert c1 == a1 assert c2 == a2 inv, a1, a2 = c2.swap(c1) assert inv assert c1 == a1 assert c2 == a2
def test_swap(self): c1 = currency('eur') c2 = currency('chf') inv, a1, a2 = c1.swap(c2) self.assertFalse(inv) self.assertEqual(c1, a1) self.assertEqual(c2, a2) inv, a1, a2 = c2.swap(c1) self.assertTrue(inv) self.assertEqual(c1, a1) self.assertEqual(c2, a2)
class ChangeCurrencyForm(FlaskForm): currencies = [] list = ccy.all() for item in sorted(list): currency = ccy.currency(item) currencies.append((item, item + " - " + currency.name)) currency = SelectField(u'Currency', choices=currencies) submit = SubmitField('Set currency')
def get_currency_from_paybox(currency): """ Convert Paybox currency format to Saleor currency format. Paybox currency is using numeric code (ISO 4217) while Saleor is using lowercase string. :param currency: str :return: str """ currency = ccy.currency(currency) return currency.code.lower()
def get_currency_for_paybox(currency): """ Convert Saleor's currency format to Paybox currency format. Paybox currency is using numeric code (ISO 4217) while Saleor is using lowercase string. :param currency: str :return: str """ currency = ccy.currency(currency) return currency.isonumber
def __init__(self, country_code='fr', cross='usd', conv=None): self.cross = cross self.ccy_code = ccy.countryccy(country_code) self.money = ccy.currency(self.ccy_code) self.engine = converter.Converter(1, self.money.code, cross) if conv is None: locale.setlocale(locale.LC_ALL, '') conv = locale.localeconv() self.conv = conv self.symbol = locale.nl_langinfo(locale.CRNCYSTR)[1:]
def usdbase(self): reader = self.reader handler = self.handler or self.handle usdobj = currency('USD') for d in reader: dt = ecbdate(d['Date']) if self.start > dt: continue if self.end < dt: break usd = float(d[usdobj.code]) handler('EUR', dt, usd) for ccy, v in d.items(): if ccy == usdobj.code or len(ccy) != 3: continue try: cobj = currency(ccy) cu = float(v)/usd if cobj.order < usdobj.order: cu = 1./cu except: continue handler(ccy, dt, cu)
def test_pickle(self): c = currency('eur') cd = pickle.dumps(c) c2 = pickle.loads(cd) self.assertEqual(c, c2) self.assertNotEqual(c, 'EUR')
def test_spot_price(self): c1 = currency('eur') c2 = currency('gbp') self.assertAlmostEqual(c1.spot(c2, 1.3, 1.6), 1.3/1.6) self.assertAlmostEqual(c2.spot(c1, 1.6, 1.3), 1.3/1.6)
def test_spot_price(): c1 = currency('eur') c2 = currency('gbp') assert c1.spot(c2, 1.3, 1.6) == 1.3 / 1.6 assert c2.spot(c1, 1.6, 1.3) == 1.3 / 1.6
def test_pickle(): c = currency('eur') cd = pickle.dumps(c) c2 = pickle.loads(cd) assert c == c2 assert c != 'EUR'
def test_spot_price(self): c1 = currency('eur') c2 = currency('gbp') self.assertAlmostEqual(c1.spot(c2, 1.3, 1.6), 1.3 / 1.6) self.assertAlmostEqual(c2.spot(c1, 1.6, 1.3), 1.3 / 1.6)
def test_json(): c = currency('eur') info = c.info() json.dumps(info)
def adddataid(code, curncy, country = None, **kwargs): '''Add new data id to database''' if country is None: country = ccy.currency(curncy).default_country return _api.adddataid(code, curncy = curncy, country = country, **kwargs)
import os from urllib import urlopen import StringIO import csv import zipfile from datetime import date from ccy import currency __all__ = ['ecbccy', 'ecbzipccy'] usdobj = currency('USD') def ecbdate(dstr): ''' convert ecb string date into python date ''' bits = dstr.split('-') year = int(bits[0]) month = int(bits[1]) day = int(bits[2]) return date(year, month, day) class ecbccy(object): url = 'http://www.ecb.int/stats/eurofxref' filename = 'eurofxref'
class PrizepoolModForm(forms.Form): sorted_curs = sorted(ccy.currencydb(), key=operator.itemgetter(0)) currencies = [(ccy.currency(c).code, ccy.currency(c).name) for c in sorted_curs] currency = forms.ChoiceField(choices=currencies, required=True, label=_('Currency')) ranked = forms.CharField(required=False, max_length=10000, label=_('Ranked')) unranked = forms.CharField(required=False, max_length=10000, label=_('Unranked')) # {{{ Constructor def __init__(self, request=None, event=None): if request is not None: super(PrizepoolModForm, self).__init__(request.POST) else: initial = { 'ranked': earnings_code( event.earnings_set.filter( placement__gt=0).order_by('-earnings')), 'unranked': earnings_code( event.earnings_set.filter( placement=0).order_by('-earnings')), } try: initial['currency'] = event.earnings_set.all().first().currency except: initial['currency'] = 'USD' super(PrizepoolModForm, self).__init__(initial=initial) self.label_suffix = '' # }}} # {{{ Function for parsing a single line def line_to_data(self, line): ind = line.find(' ') prize = Decimal(line[:ind]) queryset = find_player(query=line[ind + 1:]) if not queryset.exists(): raise Exception(_("No such player: '%s'.") % line[ind + 1:]) elif queryset.count() > 1: raise Exception(_("Ambiguous player: '%s'.") % line[ind + 1:]) else: return prize, queryset.first() # }}} # {{{ update_event: Pushes changes to event object def update_event(self, event): ret = [] if not self.is_valid(): ret.append( Message(_('Entered data was invalid, no changes made.'), type=Message.ERROR)) for field, errors in self.errors.items(): for error in errors: ret.append( Message(error=error, field=self.fields[field].label)) return ret # {{{ Gather data ranked, unranked, ok = [], [], True for line in self.cleaned_data['ranked'].split('\n'): if line.strip() == '': continue try: prize, player = self.line_to_data(line) ranked.append({ 'prize': prize, 'player': player, 'placement': 0 }) except Exception as e: ret.append(Message(str(e), type=Message.ERROR)) ok = False for line in self.cleaned_data['unranked'].split('\n'): if line.strip() == '': continue try: prize, player = self.line_to_data(line) unranked.append({ 'prize': prize, 'player': player, 'placement': -1 }) except Exception as e: ret.append(Message(str(e), type=Message.ERROR)) ok = False if not ok: ret.append( Message(_('Errors occured, no changes made.'), type=Message.ERROR)) return ret # }}} # {{{ Fix placements of ranked prizes ranked.sort(key=lambda a: a['placement']) for i, e in enumerate(ranked): ranked[i]['placement'] = i # }}} # {{{ Commit try: Earnings.set_earnings(event, ranked, self.cleaned_data['currency'], True) Earnings.set_earnings(event, unranked, self.cleaned_data['currency'], False) except RateNotFoundError as e: ret.append(Message(str(e), type=Message.ERROR)) return ret # }}} # Translators: New prizepools added to the database. ret.append(Message(_('New prizes committed.'), type=Message.SUCCESS)) return ret
def test_print(): stream = StreamIO() c2 = currency('chf') c2.printinfo(stream) value = stream.getvalue() assert value
def test_print(self): stream = StreamIO() c2 = currency('chf') c2.printinfo(stream) value = stream.getvalue() self.assertTrue(value)
def test_json(self): c = currency('eur') info = c.info() s = json.dumps(info)
def events(request, event_id=None): # Redirect to proper URL if there's a ?goto=... present if 'goto' in request.GET: return redirect('/results/events/' + request.GET['goto']) base = base_ctx('Results', 'By Event', request) base.update(csrf(request)) try: event = Event.objects.get(id=int(event_id)) except: # This is executed for invalid event IDs or the root table ind_bigs = collect(Event.objects.filter(parent__isnull=True, big=True, category='individual').\ select_related('event').order_by('lft'), 2) ind_smalls = Event.objects.filter(parent__isnull=True, big=False, category='individual').\ select_related('event').order_by('name') team_bigs = collect(Event.objects.filter(parent__isnull=True, big=True, category='team').\ select_related('event').order_by('lft'), 2) team_smalls = Event.objects.filter(parent__isnull=True, big=False, category='team').\ select_related('event').order_by('name') freq_bigs = collect(Event.objects.filter(parent__isnull=True, big=True, category='frequent').\ select_related('event').order_by('lft'), 2) freq_smalls = Event.objects.filter(parent__isnull=True, big=False, category='frequent').\ select_related('event').order_by('name') base.update({'ind_bigs': ind_bigs, 'ind_smalls': ind_smalls,\ 'team_bigs': team_bigs, 'team_smalls': team_smalls,\ 'freq_bigs': freq_bigs, 'freq_smalls': freq_smalls}) return render_to_response('events.html', base) # Number of matches (set event to big if too large) matches = Match.objects.filter(eventobj__lft__gte=event.lft, eventobj__rgt__lte=event.rgt) if matches.count() > 200 and not event.big: event.big = True event.save() # Get parent, ancestors and siblings if event.parent != None: siblings = event.parent.event_set.exclude(id=event.id).order_by('lft') else: siblings = None # Make modifications if neccessary if base['adm'] == True: if 'op' in request.POST and request.POST['op'] == 'Modify': if request.POST['type'] != 'nochange': event.change_type(request.POST['type']) if 'siblings' in request.POST.keys() and siblings is not None: for sibling in siblings: sibling.change_type(request.POST['type']) if request.POST['name'] != '' and request.POST['name'] != event.name: event.name = request.POST['name'] event.update_name() event.save() for e in event.get_children(): e.update_name() if request.POST['date'].strip() != 'No change': matches.update(date=request.POST['date']) base['message'] = 'Modified all matches.' if request.POST['offline'] != 'nochange': matches.update(offline=(request.POST['offline'] == 'offline')) base['message'] = 'Modified all matches.' if request.POST['game'] != 'nochange': matches.update(game=request.POST['game']) base['message'] = 'Modified all matches.' if request.POST['homepage'] != event.get_homepage(): event.set_homepage(request.POST['homepage']) if request.POST['tlpd_in_id'] != event.get_tlpd_in_id(): event.set_tlpd_in_id(request.POST['tlpd_in_id']) if request.POST['tlpd_kr_id'] != event.get_tlpd_kr_id(): event.set_tlpd_kr_id(request.POST['tlpd_kr_id']) if request.POST['tl_thread'] != event.get_tl_thread(): event.set_tl_thread(request.POST['tl_thread']) if request.POST['lp_name'] != event.get_lp_name(): event.set_lp_name(request.POST['lp_name']) elif 'add' in request.POST and request.POST['add'] == 'Add': parent = event for q in request.POST['subevent'].strip().split(','): type = request.POST['type'] parent.add_child(q.strip(), type, 'noprint' in request.POST, 'closed' in request.POST) elif 'move' in request.POST and request.POST['move'] == 'Move': eventid = request.POST['moveevent'] newparent = Event.objects.get(id=eventid) if event.lft > newparent.rgt: diff = newparent.rgt - event.lft else: diff = newparent.rgt - event.rgt - 1 event_shift(event, diff) event.set_parent(newparent) event.update_name() for e in event.get_children(): e.update_name() elif 'earnings' in request.POST and request.POST['earnings'] == 'Add': amount = int(request.POST['amount']) currency = request.POST['currency'] players = [] amounts = [] placements = [] for i in range(0, amount): player = request.POST['player-' + str(i)] player = Player.objects.get(id=player) amount = request.POST['amount-' + str(i)] amount = amount.replace(',', '').replace('.', '').replace(' ', '') players.append(player) amounts.append(amount) placements.append(i) success = Earnings.set_earnings(event, players, amounts, currency, placements) if success: base['message'] = 'Updated tournament prizepool.' else: base['message'] = 'There was an error updating the tournament prizepool.' base['event'] = event base['path'] = Event.objects.filter(lft__lte=event.lft, rgt__gte=event.rgt).order_by('lft') base['children'] = Event.objects.filter(parent=event).order_by('lft') if event.parent != None: base['siblings'] = event.parent.event_set.exclude(id=event.id).order_by('lft') # Used for moving events base['surroundingevents'] = event.get_parent(1).get_children().exclude(lft__gte=event.lft, rgt__lte=event.rgt) # Determine WoL/HotS and Online/Offline and event type if matches.values("game").distinct().count() == 1: base['game'] = matches[0].game if base['game'] == 'WoL': base['game'] = 'Wings of Liberty' elif base['game'] == 'HotS': base['game'] = 'Heart of the Swarm' #elif base['game'] = 'LotV': #base['game'] = 'Legacy of the Void' # Get list of players and earnings for prizepools base['players'] = Player.objects.filter(Q(id__in=matches.values('pla')) | Q(id__in=matches.values('plb'))) earnings = Earnings.objects.filter(event=event).order_by('placement') base['earnings'] = earnings base['prizepool'] = earnings.aggregate(Sum('earnings'))['earnings__sum'] base['prizepoolorig'] = earnings.aggregate(Sum('origearnings'))['origearnings__sum'] try: base['prizepoolcur'] = earnings.values('currency')[0]['currency'] except: base['prizepoolcur'] = "USD" # Get list of currencies currencies = [] sortedcurrencies = sorted(ccy.currencydb(), key=operator.itemgetter(0)) for currency in sortedcurrencies: dict = {} dict["name"] = ccy.currency(currency).name dict["code"] = ccy.currency(currency).code currencies.append(dict) base['currencies'] = currencies base['offline'] = None if matches.values("offline").distinct().count() == 1: base['offline'] = matches[0].offline # Statistics base['nmatches'] = matches.count() if base['nmatches'] > 0: qset = matches.aggregate(Sum('sca'), Sum('scb')) base['ngames'] = qset['sca__sum'] + qset['scb__sum'] else: base['ngames'] = 0 # Matchup wins and losses nti = lambda x: 0 if x is None else x qseta = matches.filter(rca='P', rcb='T').aggregate(Sum('sca'), Sum('scb')) qsetb = matches.filter(rcb='P', rca='T').aggregate(Sum('sca'), Sum('scb')) base['pvt_wins'] = nti(qseta['sca__sum']) + nti(qsetb['scb__sum']) base['pvt_loss'] = nti(qsetb['sca__sum']) + nti(qseta['scb__sum']) qseta = matches.filter(rca='P', rcb='Z').aggregate(Sum('sca'), Sum('scb')) qsetb = matches.filter(rcb='P', rca='Z').aggregate(Sum('sca'), Sum('scb')) base['pvz_wins'] = nti(qseta['sca__sum']) + nti(qsetb['scb__sum']) base['pvz_loss'] = nti(qsetb['sca__sum']) + nti(qseta['scb__sum']) qseta = matches.filter(rca='T', rcb='Z').aggregate(Sum('sca'), Sum('scb')) qsetb = matches.filter(rcb='T', rca='Z').aggregate(Sum('sca'), Sum('scb')) base['tvz_wins'] = nti(qseta['sca__sum']) + nti(qsetb['scb__sum']) base['tvz_loss'] = nti(qsetb['sca__sum']) + nti(qseta['scb__sum']) # Dates base['earliest'] = event.get_earliest() base['latest'] = event.get_latest() matches = matches.order_by('-date', '-eventobj__lft', '-id')[0:200] base['matches'] = display_matches(matches) return render_to_response('eventres.html', base)
current_rates = CurrencyConverter( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip') #check the current rates current_rates._get_rate('USD', date=date(2017, 5, 4)) # We can also Load the history rates as well from the website history_rates = CurrencyConverter( 'http://www.ecb.int/stats/eurofxref/eurofxref-hist.zip') # check the information in detail about the currencies for e.g INR (INDIA) ccy = ccy.currency('INR') ccy.printinfo() #check the currency of the country ccy.countryccy('us') # Lets check the rates from current_currency current_rates.convert(100, 'EUR', 'INR') #convert the current rate from Euro to INR for today's date current_rates.convert(100, 'EUR', 'INR', date=date(2017, 5, 4)) # We can also make the default currency, lets make it Euro
def adddataid(code, curncy, country=None, **kwargs): '''Add new data id to database''' if country is None: country = ccy.currency(curncy).default_country return _api.adddataid(code, curncy=curncy, country=country, **kwargs)