How to use the beancount.core.data.Posting 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 beancount / fava / tests / test_serialisation.py View on Github external
"postings": postings,
    }

    txn = Transaction(
        {},
        datetime.date(2017, 12, 12),
        "*",
        "Test3",
        "asdfasd",
        frozenset(["tag"]),
        frozenset(["link"]),
        [],
    )
    create_simple_posting(txn, "Assets:ETrade:Cash", "100", "USD")
    txn.postings.append(
        Posting("Assets:ETrade:GLD", MISSING, None, None, None, None)
    )
    assert deserialise(json_txn) == txn

    with pytest.raises(KeyError):
        deserialise({})

    with pytest.raises(FavaAPIException):
        deserialise({"type": "NoEntry"})
github jbms / beancount-import / beancount_import / source / ofx.py View on Github external
date=raw.date,
                    flag=FLAG_OKAY,
                    payee=None,
                    narration='Transfer due to: ' + narration,
                    tags=EMPTY_SET,
                    links=EMPTY_SET,
                    postings=[
                        Posting(
                            account=get_subaccount_cash(raw.inv401ksource),
                            units=-cash_transfer_transaction_amount,
                            cost=None,
                            price=None,
                            flag=None,
                            meta=transfer_meta,
                        ),
                        Posting(
                            account=FIXME_ACCOUNT,
                            units=cash_transfer_transaction_amount,
                            cost=None,
                            price=None,
                            flag=None,
                            meta=None,
                        ),
                    ])
                results.add_pending_entry(
                    ImportResult(
                        date=transfer_entry.date,
                        entries=[transfer_entry],
                        info=get_info(raw)))

        for raw in self.raw_cash_balance_entries:
            entry = Balance(
github beancount / beancount / src / python / beancount / sources / rbcinvesting.py View on Github external
# Find the first posting with the same currency, and use the same lot
        # for it.
        frac_posting = frac_entry.postings[0]
        frac_currency = frac_posting.position.lot.currency
        for posting in entry.postings:
            if posting.position.lot.currency == frac_currency:
                break
        else:
            # Posting was not found; just put it back in the list.
            new_entries.append(frac_entry)
            continue

        index = entry.postings.index(posting)
        entry.postings.insert(index+1,
                              Posting(entry,
                                      frac_posting.account,
                                      Position(posting.position.lot,
                                               frac_posting.position.number),
                                      frac_posting.price,
                                      frac_posting.flag))

    return new_entries
github beancount / beancount / experiments / upload / list_holdings.py View on Github external
entries: A list of directives, as per the loader.
      options_map: An options map, as per the parser.
    Yields:
      Instances of Posting.
    """
    balances, _ = summarize.balance_by_account(entries)
    date = entries[-1].date
    acctypes = options.get_account_types(options_map)
    for account, balance in sorted(balances.items()):
        # Keep only the balance sheet accounts.
        acctype = account_types.get_account_type(account)
        if not acctype in (acctypes.assets, acctypes.liabilities):
            continue
        # Create a posting for each of the positions.
        for position in balance:
            yield data.Posting(account, position.units, position.cost, None, None, None)
github jbms / beancount-import / beancount_import / source / healthequity.py View on Github external
flag=None,
                ))
    else:
        raise ValueError('unexpected entry type %r' % (csv_entry, ))
    entry = Transaction(
        date=csv_entry.date,
        meta=None,
        narration=csv_entry.description,
        flag=FLAG_OKAY,
        payee=None,
        tags=EMPTY_SET,
        links=EMPTY_SET,
        postings=[])

    entry.postings.append(
        Posting(
            account=csv_entry.account,
            units=csv_entry.units,
            price=price,
            cost=cost,
            flag=None,
            meta=posting_meta))
    entry.postings.extend(extra_postings)
    entry.postings.append(
        Posting(
            meta=None,
            account=other_account,
            units=-total_amount,
            price=None,
            cost=None,
            flag=None))
    return ImportResult(
github beancount / beancount / beancount / reports / holdings_reports.py View on Github external
# Create synthetic entries for them.
    holdings_entries = []

    for index, holding in enumerate(holdings_list):
        meta = data.new_metadata('report_holdings_print', index)
        entry = data.Transaction(meta, latest_date, flags.FLAG_SUMMARIZE,
                                 None, "", None, None, [])

        # Convert the holding to a position.
        pos = holdings.holding_to_position(holding)
        entry.postings.append(
            data.Posting(holding.account, pos.units, pos.cost, None, None, None))

        cost = -convert.get_cost(pos)
        entry.postings.append(
            data.Posting(equity_account, cost, None, None, None, None))

        holdings_entries.append(entry)

    # Get opening directives for all the accounts.
    used_accounts = {holding.account for holding in holdings_list}
    open_entries = summarize.get_open_entries(entries, latest_date)
    used_open_entries = [open_entry
                         for open_entry in open_entries
                         if open_entry.account in used_accounts]

    # Add an entry for the equity account we're using.
    meta = data.new_metadata('report_holdings_print', -1)
    used_open_entries.insert(0, data.Open(meta, latest_date, equity_account,
                                          None, None))

    # Get the latest price entries.
github beancount / beancount / examples / ingest / office / importers / utrade / __init__.py View on Github external
elif rtype == 'SELL':
                    # Extract the lot. In practice this information not be there
                    # and you will have to identify the lots manually by editing
                    # the resulting output. You can leave the cost.number slot
                    # set to None if you like.
                    match = re.search(r'\(LOT ([0-9.]+)\)', row['DESCRIPTION'])
                    if not match:
                        logging.error("Missing cost basis in '%s'", row['DESCRIPTION'])
                        continue
                    cost_number = D(match.group(1))
                    cost = position.Cost(cost_number, self.currency, None, None)
                    price = amount.Amount(rate, self.currency)
                    account_gains = self.account_gains.format(instrument)
                    txn = data.Transaction(
                        meta, date, self.FLAG, None, desc, None, {link}, [
                        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,
github beancount / beancount / experiments / returns / returns.py View on Github external
# We will attach a link to each of the split entries.
            link = LINK_FORMAT.format(index)
            index += 1

            # Calculate the weight of the balance to transfer.
            balance_transfer = inventory.Inventory()
            for posting in postings_external:
                balance_transfer.add_amount(convert.get_weight(posting))

            prototype_entry = entry._replace(flag=flags.FLAG_RETURNS,
                                             links=(entry.links or set()) | set([link]))

            # Create internal flows posting.
            postings_transfer_int = [
                data.Posting(transfer_account, pos.units, pos.cost, None, None, None)
                for pos in balance_transfer.get_positions()]
            new_entries.append(prototype_entry._replace(
                postings=(postings_assets + postings_internal + postings_transfer_int)))

            # Create external flows posting.
            postings_transfer_ext = [
                data.Posting(transfer_account, -pos.units, pos.cost, None, None, None)
                for pos in balance_transfer.get_positions()]
            new_entries.append(prototype_entry._replace(
                postings=(postings_transfer_ext + postings_external)))
        else:
            new_entries.append(entry)

    # The transfer account does not have an Open entry, insert one. (This is
    # just us being pedantic about Beancount requirements, this will not change
    # the returns, but if someone looks at internalized entries it produces a
github beancount / beancount / experiments / sharing / extract_sheets.py View on Github external
payee = row[coltypes.get(csv.Col.PAYEE)]
    narration = None
    if coltypes.get(csv.Col.NARRATION):
        narration = row[coltypes.get(csv.Col.NARRATION)]

    postings = []
    txn = data.Transaction(data.new_metadata(docid, index),
                           date,
                           flags.FLAG_OKAY,
                           payee,
                           narration,
                           data.EMPTY_SET,
                           data.EMPTY_SET,
                           postings)
    units = amount.Amount(number, 'USD')
    postings.append(data.Posting(account, units, None, None, None, None))
    postings.append(data.Posting(inflows_account, -units, None, None, None, None))
    return txn