Beispiel #1
0
 def test_face_value(self):
     self.assertEquals(self.security.face_value, Money(20, 'USD'))
     self.security.face_value = Money(30, 'RUB')
     self.assertEquals(self.security.face_value_unit, 'RUB')
     self.assertEquals(self.security.face_value_amount, 30)
     self.security.face_value = None
     self.assertIsNone(self.security.face_value)
Beispiel #2
0
 def setUpClass(cls):
     cls.m1 = Money(10, 55)
     cls.m2 = Money(5, 35)
     cls.m3 = Money(73, 44, 73.44)
     print(
         f'Starting test class Money with attributes:\n{cls.m1};\n{cls.m2};\n{cls.m3}'
     )
def money_calc():
    '''
    Money addition calculator.
    Prompt for a series of Money objects until empty
    string is entered; then print results of the
    running total.
    '''
    n = 0
    while True:
        s = input('Enter money value: ')
        s = s.strip()
        if not s:
            break
        a_list = s.split()  # Split into amt, units.
        d = a_list[0]
        if len(a_list) > 1:
            m = Money(d, a_list[1])
        else:
            m = Money(d)
        if n == 0:
            amt = m
            Money.default_curr = m.units
        else:
            amt += m
        n += 1
    print('Total is', amt)
Beispiel #4
0
 def __init__(self, inital_salary, annual_raise_percent, last_raise_date,
              initial_max_payment):
     self.inital_salary = Money(inital_salary)
     self.annual_raise_percent = annual_raise_percent
     self.last_raise_date = last_raise_date
     self.initial_max_payment = Money(initial_max_payment)
     self.tax_rate = 0.25
Beispiel #5
0
def cprint(text, color='gray', format=None, pre=''):
    """
    simple color printing to console
    :param text: any
    :param color: string
    :param format: string
    :param pre: string to be added before the formatting
    :return: bool
    """
    if format == 'currency':
        print(colored(pre + str(Money(amount=text, currency='GBP')), color))
    elif format == 'percentage':
        print(colored(pre + "{0:.0f}%".format(text * 100), color))
    elif format == 'decimal':
        print(colored(pre + "{0:.2f}".format(text), color))
    elif format == 'bigdecimal':
        print(colored(pre + "{0:.5f}".format(text), color))
    elif format == 'trade':
        print(colored('Trades\n', 'green'))
        for index, row in text.iterrows():
            print(
                colored(
                    '  stock:{} | action:{} | qtd:{} | price:{} | date: {}'.
                    format(row['stock'], row['action'], row['quantity'],
                           str(Money(amount=row['price'], currency='GBP')),
                           str(index).split('.')[0]), color))
        print(colored('\nTotal trades: {}'.format(len(text)), 'green'))
    else:
        print(colored(text, color))
Beispiel #6
0
    def test_price_attribute(self):
        e = SimpleMoneyModel()
        e.price = Money(3, "BGN")
        self.assertEqual(e.price, Money(3, "BGN"))

        e.price = Money.from_string("BGN 5.0")
        self.assertEqual(e.price, Money(5, "BGN"))
 def test_create(self):
     self.assertEqual(BisnodeFinancialStatementCommon.objects.count(), 0)
     financial_statement = self.standard_report.financialStatementCommon[0]
     financial_report = BisnodeFinancialStatementCommonFactory()
     financial_report.create(self.company_report.id, financial_statement)
     BisnodeFinancialStatementCommon.objects.get(
         id=financial_report.id, company_report=self.company_report)
     self.assertEqual(financial_report.statement_date, date(2013, 12, 01))
     self.assertEqual(financial_report.number_of_months_covered, 12)
     self.assertEqual(financial_report.total_income,
                      Money(231750000, 'SEK'))
     self.assertEqual(financial_report.income_after_financial_items,
                      Money(11861000, 'SEK'))
     self.assertEqual(financial_report.net_worth, Money(87057000, 'SEK'))
     self.assertEqual(financial_report.total_assets,
                      Money(256405000, 'SEK'))
     self.assertEqual(financial_report.average_number_of_employees, 140)
     self.assertEqual(financial_report.equity_ratio, 34.0)
     self.assertEqual(financial_report.quick_ratio, 105.9)
     self.assertEqual(financial_report.current_ratio, 175.5)
     self.assertEqual(financial_report.profit_margin, 10.2)
     self.assertEqual(financial_report.return_of_total_assets, 9.2)
     self.assertEqual(financial_report.return_on_equity, 13.6)
     self.assertEqual(financial_report.interest_on_liabilities, 3.6)
     self.assertEqual(financial_report.risk_margin, 5.6)
     self.assertEqual(financial_report.liability_ratio, 1.9)
     self.assertEqual(financial_report.interest_cover, 3.8)
     self.assertEqual(financial_report.turnover_assets, 0.9)
Beispiel #8
0
def index(request):
    """Primary homepage view"""

    num_investments = Investment.objects.filter(user=request.user).count()
    gbp_total = InvestmentValuation.objects.filter(
        investment__currency__short_code__startswith='GBP',
        latest__exact='y',
        investment__user=request.user).aggregate(Sum('amount'))
    usd_total = InvestmentValuation.objects.filter(
        investment__currency__short_code__startswith='USD',
        latest__exact='y',
        investment__user=request.user).aggregate(Sum('amount'))
    ###total_gbp = my_investment_valuations_in_gbp.aggregate(Sum('amount'))
    ###total_usd = my_investment_valuations_in_usd.aggregate(Sum('amount'))
    ###total_gbp = total_gbp or 0
    ###total_usd = total_usd or 0
    try:
        gbp_total = Money(gbp_total.get('amount__sum', 0), 'GBP')
    except TypeError:
        gbp_total = Money(0, 'GBP')
    try:
        usd_total = Money(usd_total.get('amount__sum', 0), 'USD')
    except TypeError:
        usd_total = Money(0, 'USD')
    context = {
        'num_investments': num_investments,
        'total_gbp': gbp_total,
        'total_usd': usd_total,
    }

    return render(request, 'index.html', context=context)
Beispiel #9
0
    def __init__(self,
                 raw: List[Union[float, Decimal]],
                 market: 'Market',
                 ask_bid: str,
                 limit_order_price: Union[Money, float, int, str,
                                          Decimal] = None):
        self.market = market
        self.ask_bid = ask_bid
        self.base_currency = market['base']
        self.quote_currency = market['quote']
        self.exchange_name = market['exchange']

        self.raw = raw
        self.quote_unit_price = Money(
            Decimal(raw[0]).quantize(satoshi), self.quote_currency)
        self.base_volume = Money(
            Decimal(raw[1]).quantize(satoshi), self.base_currency)
        if not limit_order_price:
            self.limit_order_price = self.quote_unit_price  # used for combined orders
            self.is_combined = False
        else:
            if not isinstance(limit_order_price, Money):
                limit_order_price = self.quantize(
                    Money(limit_order_price, self.quote_currency))
            assert limit_order_price.currency == self.quote_currency
            self.limit_order_price = limit_order_price
            self.is_combined = True
 def test_parse(self):
     p = MoneyUtility.parse
     eq_(Money("0", "USD"), p(None))
     eq_(Money("4.00", "USD"), p("4"))
     eq_(Money("-4.00", "USD"), p("-4"))
     eq_(Money("4.40", "USD"), p("4.40"))
     eq_(Money("4.40", "USD"), p("$4.40"))
Beispiel #11
0
 def test_instance_descriptor_set(self):
     obj = self.manager_create_instance()
     self.assertEqual(obj.price, Money('1234.00', 'EUR'))
     obj.price = Money('0.99', 'EUR')
     self.assertEqual(obj.price, Money('0.99', 'EUR'))
     obj.save()
     self.assertEqual(obj.price, Money('0.99', 'EUR'))
Beispiel #12
0
    def combined(cls, orders: 'List[Order]') -> 'Union[Order, None]':
        if len(orders) == 0: return None

        assert _(orders).map('base_currency').uniq().size().value() == 1
        assert _(orders).map('quote_currency').uniq().size().value() == 1
        assert _(orders).map('ask_bid').uniq().size().value() == 1
        assert _(orders).map('market.symbol').uniq().size().value() == 1
        assert _(orders).map('market.exchange').uniq().size().value() == 1

        limit_order_price = Money(0, orders[0].quote_currency)
        quote_total_price = Money(0, orders[0].quote_currency)
        base_volume = Money(0, orders[0].base_currency)

        for order in orders:
            quote_total_price += order.quote_total_price
            base_volume += order.base_volume
        quote_price_unit = quote_total_price / base_volume.amount

        if orders[0].ask_bid == 'ask':
            limit_order_price = _(orders).map('quote_unit_price').max().value()
        if orders[0].ask_bid == 'bid':
            limit_order_price = _(orders).map('quote_unit_price').min().value()

        combined_order = Order(
            raw=[quote_price_unit.amount, base_volume.amount],
            market=orders[0].market,
            ask_bid=orders[0].ask_bid,
            limit_order_price=limit_order_price,
        )
        return combined_order
Beispiel #13
0
    def get_transfer_details(self, sender_account, recipient_account):
        settings = sender_account.broker.get_value(self.setting)
        data = {}

        data['transfer_type'] = self.type
        data['min_amount_for_approve'] = settings['min_amount_for_approve']
        data['min_commission'] = Money(
            settings['commissions']['min_commission'],
            USD).to(sender_account.currency)
        data['max_commission'] = Money(
            settings['commissions']['max_commission'],
            USD).to(sender_account.currency)

        if sender_account.currency == recipient_account.currency:
            data['commission'] = settings['commissions']['same_currencies']
        else:
            data['commission'] = settings['commissions'][
                'different_currencies']

            exchange_string, exchange_coefficient = InternalTransfer.get_exchange_rate(
                sender_account.currency,
                recipient_account.currency,
            )
            data['exchange_rate'] = exchange_string
            data['exchange_coefficient'] = exchange_coefficient

        data['exchange_coefficient_for_fix'] = Money(1, USD).to(
            sender_account.currency).amount
        return data
Beispiel #14
0
 def printout(self):
     # This will print out the receipt for the transaction using the class variables.
     print("=" * 44)
     print("|{:^42}|".format("Receipt"))
     print("|{:^42}|".format(datetime.datetime.now().strftime("%m/%d/%Y")))
     print("|{:^42}|".format(
         datetime.datetime.now().strftime("%I:%M:%S %p")))
     print("=" * 44)
     print("| {0:<40} |  \n| {2:<10} | {1:>11} | {3:>12}  |".format(
         "Item", "Quantity", "Price/Item", "Price"))
     print("=" * 44)
     for i in range(0, len(self.thing)):
         print("| {0:<40} |  \n| {2:<10} | {1:>11} | {3:>13} |".format(
             self.thing[i], self.number[i],
             Money(self.price[i], "USD").format("en_US"),
             Money(self.total_price[i], "USD").format("en_US")))
     print("=" * 44)
     print("| {1:<20}{5:>20} |\n"
           "| {2:<20}{6:>20} |\n"
           "| {3:<20}{7:>20} |\n"
           "| {4:<20}{8:>20} |".format(
               sum(self.number), "Number of Items: ", "Subtotal: ",
               "Sales Tax: ", "Total Price: ",
               int(round(sum(self.number), 0)),
               Money(sum(self.total_price), "USD").format('en_US'),
               Money((sum(self.total_price) * self.sales_tax),
                     "USD").format('en_US'),
               Money(sum(self.total_price) * (1 + self.sales_tax),
                     "USD").format('en_US')))
async def main_async():
    exchange_names = ccxt.exchanges
    # exchange_names   = [ "bleutrade", "kraken", "bittrex", "nova", "poloniex", "yobit" ]
    arbitrage_coins  = [
        Money(0.01,      "BTC"),
        Money(0.1,       "ETH"),
        Money(100000,    "MOON"),
        Money(10000,     "DOGE"),
    ]

    exchanges = {}
    for exchange_name in exchange_names:
        attempts_remaining = 6
        print("loading: %s " % exchange_name, end='')
        while not exchange_name in exchanges and attempts_remaining >= 0:
            attempts_remaining -= 1
            try:
                # exchanges[exchange_name] = Exchange.init_sync(exchange_name, limit=None)
                exchanges[exchange_name] = await Exchange.init_async(exchange_name, limit=None)
            except:
                print(".", end='')
        print("")

    arbitrage_markets = {}
    for exchange_name in exchanges.keys():
        for input_coin in arbitrage_coins:
            print("find_arbitrage_loops: %s -> %s" % (exchange_name, input_coin))
            arbitrage_markets[exchange_name+':'+str(input_coin)] = exchanges[exchange_name].find_arbitrage_loops(input_coin, depth=6, profit=1)

    for key, arbitrage_loops in arbitrage_markets.items():
        if len(arbitrage_loops):
            print("\n----------------------------------------\n".join([ str(trade) for trade in arbitrage_loops ]))
    print("DONE")
Beispiel #16
0
    def send_campaign_matched(self, donor_name, donation, campaign_total, campaign_target):
        """Method to send a confirmation to a campaigner when their campaign has been matched

        Args:
            donor_name(str): Name of the donor
            donation(int): Donation amount in cents
            campaign_total(int): Campaign total to date in cents
            campaign_target(int): Campaign match target in cents

        Returns:
            None
        """
        donation = Money(amount=(donation / 100), currency="USD")
        donation = donation.format('en_US').split(".")[0]

        campaign_total = Money(amount=(campaign_total / 100), currency="USD")
        campaign_total = campaign_total.format('en_US').split(".")[0]

        campaign_target = Money(amount=(campaign_target / 100), currency="USD")
        campaign_target = campaign_target.format('en_US').split(".")[0]

        email_msg = u"Congrats! {} just donated {} to your campaign! ".format(donor_name, donation)
        email_msg += u"\r\nYou have now raised {}, achieving your {} match target!".format(campaign_total,
                                                                                           campaign_target)

        subject = u"Donatemates: Campaign Matched!"

        self.send_email(self.campaigner_address, subject, email_msg, self.lame_html(email_msg))
Beispiel #17
0
    def send_campaign_update(self, donor_name, donation, campaign_total, campaign_target):
        """Method to send a confirmation to a donor

        Args:
            donor_name(str): Name of the donor
            donation(int): Donation amount in cents
            campaign_total(int): Campaign total to date in cents
            campaign_target(int): Campaign match target in cents

        Returns:
            None
        """
        donation = Money(amount=(donation / 100), currency="USD")
        donation = donation.format('en_US').split(".")[0]

        campaign_total = Money(amount=(campaign_total / 100), currency="USD")
        campaign_total = campaign_total.format('en_US').split(".")[0]

        campaign_target = Money(amount=(campaign_target / 100), currency="USD")
        campaign_target = campaign_target.format('en_US').split(".")[0]

        email_msg = u"Good news! {} just donated {} to your campaign! ".format(donor_name, donation)
        email_msg += u"\r\nYou're at {} out of the total {} you've offered to match.".format(campaign_total,
                                                                                             campaign_target)

        subject = u"Donatemates: Campaign Update"

        self.send_email(self.campaigner_address, subject, email_msg, self.lame_html(email_msg))
    def __init__(self,  id=None,   nickname=None, email=None,   password=None,
                    wallet=None,   session=None,  created=None, updated=None):
        self.id = id
        self.type = 1
        self.nickname = nickname
        self.email = email
        self.password = password
        self.wallet = wallet
        self.session = session
        self.created = created
        self.updated = updated

        # For checking take_money and give_money methods
        gold = Money(code=1, amount=10)
        silver = Money(code=2, amount=100)
        copper = Money(code=3, amount=1000)

        self.gold = gold
        self.silver = silver
        self.copper = copper
        self.money = {
            GOLD: gold,
            SILVER: silver,
            COPPER: copper
        }
Beispiel #19
0
def get_amount(row, field_names):
    if 'amount' in field_names:
        return Money(row[field_names['amount']], 'USD')
    amount = row[field_names['debit']]
    if amount != '':
        return -1 * Money(amount, 'USD')
    else:
        return Money(row[field_names['credit']], 'USD')
Beispiel #20
0
def test_convert_currencies_backref():
    currency_exchange = CurrencyExchange()
    currency_exchange.add_rate('USD', 'BRL', 4)

    one_dolar = Money(1, 'USD', currency_exchange)
    converted = currency_exchange.convert(one_dolar, 'BRL')

    assert converted == Money(4, 'BRL')
Beispiel #21
0
    def testSplit(self):
        money = Money(1000)
        split = money.split(3)

        self.assertEqual(3, len(split))
        self.assertEqual(split[0], Money(333))
        self.assertEqual(split[1], Money(333))
        self.assertEqual(split[2], Money(334))
Beispiel #22
0
 def testDefaults(self):
     ent = Entity_0_USD.objects.create(name='0 USD')
     ent = Entity_0_USD.objects.get(pk=ent.id)
     self.assertEquals(ent.price, Money(0, 'USD'))
     
     ent = Entity_USD.objects.create(name='100 USD', price=100)
     ent = Entity_USD.objects.get(pk=ent.id)
     self.assertEquals(ent.price, Money(100, 'USD'))
Beispiel #23
0
def test_convert_currencies():
    currency_exchange = CurrencyExchange()
    currency_exchange.add_rate('USD', 'BRL', 4)

    four_reais = Money(4, 'BRL', currency_exchange)
    converted = currency_exchange.convert(four_reais, 'USD')

    assert converted == Money(1, 'USD')
Beispiel #24
0
def test_sign():
    pos = Money(1000)
    neg = Money(-1000)

    assert -pos == neg
    assert neg == +neg
    assert abs(pos) == pos
    assert abs(neg) == pos
Beispiel #25
0
    def testEdgeCases(self):
        created = TestMoneyModel.objects.create(name="zero dollars",
                                                price=Money(0, "USD"))
        created.save()
        self.assertEquals(created.price, Money(0, "USD"))

        ent = TestMoneyModel.objects.filter(price__exact=Money(0, "USD")).get()
        self.assertEquals(ent.price, Money(0, "USD"))
Beispiel #26
0
 def test_balance_and_availablechanged_after_withdraw(self):
     """ test if the balance and available is correct after withdraw. """
     bank_account = set_up()
     bank_account.deposit(Money(9000))
     wd = bank_account.withdraw(2500)
     self.assertEqual(wd, Money(2500))
     self.assertEqual(bank_account.balance, 6500)
     self.assertEqual(bank_account.available, 5500)
Beispiel #27
0
def document():
    content = request.json
    data_entries = []
    support_category_map = {}
    for i,j,l,n in zip(content['data'],content['hours'],content['goals'],content['hoursFrequncy']):
        x={}
        SupportCategoryName = i['SupportCategoryName']
        x['SupportCategory'] = SupportCategoryName
        x['ItemName'] = i['SupportItemName']
        x['ItemId'] = i['SupportItemNumber']
        
        multiplication = ""
        if (n[-1]=="W"):
            x['H'] = "Hours per Week: "+ n.split(',')[0] + "\n" + "Duration: " + n.split(',')[1] + " weeks"
            multiplication = n.split(',')[0] + "x" + n.split(',')[1] + "x"
        elif (n[-1]=="M"):
            x['H'] = "Hours per Month: "+ n.split(',')[0] + "\n" + "Duration: " + n.split(',')[1] + " months"
            multiplication = n.split(',')[0] + "x" + n.split(',')[1] + "x"
        else:
            x['H'] = "Hours per plan period: "+ n + " hours"
            multiplication = n + "x"
        
        cost = Money(str(i['Price']*int(j)), 'USD')
        x['Cost'] = multiplication  + Money(str(i['Price']),'USD').format('en_US') + "\n= " + cost.format('en_US')

        if SupportCategoryName in support_category_map:
            support_category_map[SupportCategoryName] += i['Price']*int(j)
        else:
            support_category_map[SupportCategoryName] = i['Price']*int(j)
        
        goals = ""
        for goal in l:
            goals = goals + goal + "\n" + "\n"
        x['Goals'] = goals
        data_entries.append(x)
	
    totalcost = ""
    for key,value in support_category_map.items():
        totalcost = totalcost + key + " = " + Money(str(value),'USD').format('en_US') + "\n"

    document = MailMerge('WordTemplate.docx')
    total_cost = totalcost
    document.merge(totalcost= total_cost.format('en_US'))

    datetimeobject = datetime.strptime(content['start'],'%Y-%m-%d')
    startDate = datetimeobject.strftime('%d/%m/%Y')

    datetimeobject = datetime.strptime(content['end'],'%Y-%m-%d')
    endDate = datetimeobject.strftime('%d/%m/%Y')


    datetimeobject = datetime.strptime(content['today'],'%Y-%m-%d')
    today = datetimeobject.strftime('%d/%m/%Y')

    document.merge(name=str(content['name']),ndis=str(content['ndis']),sos=str(content['sos']),duration=str(int(content['duration']/7))+" weeks",start=startDate,end=endDate,today=today,policy=content['policy'])
    document.merge_rows('SupportCategory',data_entries)
    document.write('test-output.docx')
    return send_file('test-output.docx', as_attachment=True)
async def ein_search(ctx, ein: int):
    ein_r = asyncio.get_event_loop()
    future = ein_r.run_in_executor(
        None, requests.get,
        'https://projects.propublica.org/nonprofits/api/v2/organizations/{}.json'
        .format(str(ein)))
    results = await future
    results = results.json()
    if "status" in results:
        await ctx.send('EIN not found')
        return
    data = {}
    for item in results['filings_with_data']:
        new_key = item['tax_prd']
        data[new_key] = {}
        if item['formtype'] == 0: data[new_key]['Form'] = '990'
        elif item['formtype'] == 1: data[new_key]['Form'] = '990_EZ'
        elif item['formtype'] == 2: data[new_key]['Form'] = '990-PF'
        else: data[new_key]['Form'] = 'Unknown'
        data[new_key]['Revenue'] = Money(item['totrevenue'],
                                         'USD').format('en_US')
        data[new_key]['Expenses'] = Money(item['totfuncexpns'],
                                          'USD').format('en_US')
        data[new_key]['Liabilities'] = Money(item['totliabend'],
                                             'USD').format('en_US')
        data[new_key][
            'PDF'] = item['pdf_url'] if item['pdf_url'] else "Unavailable"
    for item in results['filings_without_data']:
        new_key = item['tax_prd']
        data[new_key] = {}
        if item['formtype'] == 0: data[new_key]['Form'] = '990'
        elif item['formtype'] == 1: data[new_key]['Form'] = '990_EZ'
        elif item['formtype'] == 2: data[new_key]['Form'] = '990-PF'
        else: data[new_key]['Form'] = 'Unknown'
        data[new_key]['Revenue'] = 'Unavailable - Check PDF'
        data[new_key]['Expenses'] = 'Unavailable - Check PDF'
        data[new_key]['Liabilities'] = 'Unavailable - Check PDF'
        data[new_key][
            'PDF'] = item['pdf_url'] if item['pdf_url'] else "Unavailable"
    return_string = ''
    for tax_prd in sorted(data, reverse=True):
        return_string += 'Tax Period: ' + datetime.strptime(
            str(tax_prd), '%Y%m').strftime('%m-%Y') + '\n'
        return_string += 'Form Type: ' + data[tax_prd]['Form'] + '\n'
        return_string += 'Revenue: ' + data[tax_prd]['Revenue'] + '\n'
        return_string += 'Expenses: ' + data[tax_prd]['Expenses'] + '\n'
        return_string += 'Liabilities: ' + data[tax_prd]['Liabilities'] + '\n'
        return_string += 'PDF link: ' + data[tax_prd]['PDF'] + '\n'
    records_omitted = 0
    while len(return_string) > 2000:
        return_string = return_string.split('\n')
        return_string = "\n".join(return_string[:-6])
        records_omitted += 1
    await ctx.send(return_string)
    if records_omitted > 0:
        await ctx.send(
            'There were {} ommitted records from this query.'.format(
                records_omitted))
Beispiel #29
0
    def testSubtraction(self):
        brl20 = Money(2000)
        brl05 = Money(500)

        brl15 = brl20 - brl05

        self.assertEqual(1500, brl15.amount)
        self.assertEqual(2, brl15.precision)
        self.assertEqual('BRL', brl15.currency)
Beispiel #30
0
    def testAddition(self):
        brl10 = Money(1000)
        brl20 = Money(2000)

        brl30 = brl10 + brl20

        self.assertEqual(3000, brl30.amount)
        self.assertEqual(2, brl30.precision)
        self.assertEqual('BRL', brl30.currency)