How to use the beancount.core.data.Balance function in beancount

To help you get started, we’ve selected a few beancount examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github siddhantgoel / beancount-dkb / beancount_dkb / credit.py View on Github external
data.Transaction(
                        meta,
                        date,
                        self.FLAG,
                        None,
                        description,
                        data.EMPTY_SET,
                        data.EMPTY_SET,
                        postings,
                    )
                )

            # Closing Balance
            meta = data.new_metadata(file_.name, closing_balance_index)
            entries.append(
                data.Balance(
                    meta,
                    self._balance_date,
                    self.account,
                    self._balance_amount,
                    None,
                    None,
                )
            )

        return entries
github beancount / fava / fava / api / serialization.py View on Github external
def serialize_entry_with(entry, change, balance):
    new_entry = serialize_entry(entry)
    if isinstance(entry, Balance):
        new_entry['change'] = {}
        if entry.diff_amount:
            new_entry['change'] = {entry.diff_amount.currency:
                                   entry.diff_amount.number}
        new_entry['balance'] = serialize_inventory(balance)

    if isinstance(entry, Transaction):
        new_entry['change'] = serialize_inventory(change)
        new_entry['balance'] = serialize_inventory(balance)

    return new_entry
github beancount / beancount / beancount / reports / journal_html.py View on Github external
if isinstance(entry, data.Transaction):
            rowtype = FLAG_ROWTYPES.get(entry.flag, 'Transaction')
            extra_class = 'warning' if entry.flag == flags.FLAG_WARNING else ''
            flag = entry.flag
            description = '<span class="narration">{}</span>'.format(entry.narration)
            if entry.payee:
                description = ('<span class="payee">{}</span>'
                               '<span class="pnsep">|</span>'
                               '{}').format(entry.payee, description)
            amount_str = formatter.render_inventory(change)

            if entry.links and formatter:
                links = [formatter.render_link(link) for link in entry.links]

        elif isinstance(entry, data.Balance):
            # Check the balance here and possibly change the rowtype
            if entry.diff_amount is None:
                description = 'Balance {} has {}'.format(
                    formatter.render_account(entry.account),
                    entry.amount)
            else:
                description = ('Balance in {} fails; '
                               'expected = {}, balance = {}, difference = {}').format(
                                   formatter.render_account(entry.account),
                                   entry.amount,
                                   entry_balance.get_currency_units(entry.amount.currency),
                                   entry.diff_amount)
                extra_class = 'fail'

            amount_str = formatter.render_amount(entry.amount)
github beancount / beancount / examples / ingest / office / importers / utrade / utrade_csv.py View on Github external
data.Posting(self.account_cash, units, None, None, None, None),
                            data.Posting(self.account_fees, fees, None, None, None, None),
                            data.Posting(account_inst, units_inst, cost, price, None, None),
                            data.Posting(account_gains, None, None, None, None, None),
                        ])

            else:
                logging.error("Unknown row type: %s; skipping", rtype)
                continue

            entries.append(txn)

        # Insert a final balance check.
        if index:
            entries.append(
                data.Balance(meta, date + datetime.timedelta(days=1),
                             self.account_cash,
                             amount.Amount(D(row['BALANCE']), self.currency),
                             None, None))

        return entries
github beancount / beancount / beancount / ops / pad.py View on Github external
for entry in postings:

            assert not isinstance(entry, data.Posting)
            if isinstance(entry, data.TxnPosting):
                # This is a transaction; update the running balance for this
                # account.
                pad_balance.add_position(entry.posting)

            elif isinstance(entry, data.Pad):
                if entry.account == account_:
                    # Mark this newly encountered pad as active and allow all lots
                    # to be padded heretofore.
                    active_pad = entry
                    padded_lots = set()

            elif isinstance(entry, data.Balance):
                check_amount = entry.amount

                # Compare the current balance amount to the expected one from
                # the check entry. IMPORTANT: You need to understand that this
                # does not check a single position, but rather checks that the
                # total amount for a particular currency (which itself is
                # distinct from the cost).
                balance_amount = pad_balance.get_currency_units(check_amount.currency)
                diff_amount = amount.sub(balance_amount, check_amount)

                # Use the specified tolerance or automatically infer it.
                tolerance = balance.get_balance_tolerance(entry, options_map)

                if abs(diff_amount.number) > tolerance:
                    # The check fails; we need to pad.
github beancount / fava / fava / core / __init__.py View on Github external
def context(self, entry_hash):
        """Context for an entry.

        Arguments:
            entry_hash: Hash of entry.

        Returns:
            A tuple ``(entry, balances, source_slice, sha256sum)`` of the
            (unique) entry with the given ``entry_hash``. If the entry is a
            Balance or Transaction then ``balances`` is a 2-tuple containing
            the balances before and after the entry of the affected accounts.
        """
        entry = self.get_entry(entry_hash)
        balances = None
        if isinstance(entry, (Balance, Transaction)):
            balances = interpolate.compute_entry_context(
                self.all_entries, entry
            )
        source_slice, sha256sum = get_entry_slice(entry)
        return entry, balances, source_slice, sha256sum
github beancount / beancount / beancount / plugins / check_closing.py View on Github external
Returns:
      A list of new errors, if any were found.
    """
    new_entries = []
    for entry in entries:
        if isinstance(entry, data.Transaction):
            for posting in entry.postings:
                if posting.meta and posting.meta.get('closing', False):
                    # Remove the metadata.
                    meta = posting.meta.copy()
                    del meta['closing']
                    entry = entry._replace(meta=meta)

                    # Insert a balance.
                    date = entry.date + datetime.timedelta(days=1)
                    balance = data.Balance(data.new_metadata("", 0),
                                           date, posting.account,
                                           amount.Amount(ZERO, posting.units.currency),
                                           None, None)
                    new_entries.append(balance)
        new_entries.append(entry)
    return new_entries, []
github beancount / beancount / examples / ingest / office / importers / utrade / __init__.py View on Github external
data.Posting(self.account_cash, units, None, None, None, None),
                        data.Posting(self.account_fees, fees, None, None, None, None),
                        data.Posting(account_inst, units_inst, cost, price, None, None),
                        data.Posting(account_gains, None, None, None, None, None),
                        ])

            else:
                logging.error("Unknown row type: %s; skipping", rtype)
                continue

            entries.append(txn)

        # Insert a final balance check.
        if index:
            entries.append(
                data.Balance(meta, date + datetime.timedelta(days=1),
                             self.account_cash,
                             amount.Amount(D(row['BALANCE']), self.currency),
                             None, None))

        return entries
github beancount / beancount / src / python / beancount / sources / oanda.new.py View on Github external
currency = guess_currency(filename)

    # Iterate over all the transactions in the OANDA account.
    prev_balance = Decimal('0')
    prev_date = datetime.date(1970, 1, 1)
    for lineno, obj in enumerate(csv_utils.csv_dict_reader(open(filename), delimiter='\t')):

        txntype = obj['transaction']
        date = datetime.datetime.strptime(obj['date'], '%Y-%m-%d %H:%M:%S').date()

        # Insert some Balance entries every month or so.
        if date.month != prev_date.month:
            prev_date = date
            fileloc = data.FileLocation(filename, lineno)
            amount = Amount(prev_balance, currency)
            new_entries.append(Balance(fileloc, date, config['asset'], amount, None))

        # Ignore certain ones that have no effect on the balance, they just
        # change our positions.
        if txntype in IGNORE_TRANSACTIONS:
            continue
        assert txntype in RELEVANT_TRANSACTIONS, txntype

        # Get the change amounts.
        interest = get_number(obj, 'interest')
        pnl      = get_number(obj, 'p_l')
        amount   = get_number(obj, 'amount')
        other    = None

        # If the amount of change is supposed to balance, assert the
        # interest/pnl components match the amount.
        if is_balanced_txn(obj):