How to use the beancount.core.data.new_metadata 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 / beancount / beancount / plugins / unrealized.py View on Github external
inserted. It replaces the account type with an entry in an income account.
    Optionally, it can book the gain in a subaccount of the original and income
    accounts.

    Args:
      entries: A list of data directives.
      options_map: A dict of options, that confirms to beancount.parser.options.
      subaccount: A string, and optional the name of a subaccount to create
        under an account to book the unrealized gain. If this is left to its
        default value, the gain is booked directly in the same account.
    Returns:
      A list of entries, which includes the new unrealized capital gains entries
      at the end, and a list of errors. The new list of entries is still sorted.
    """
    errors = []
    meta = data.new_metadata('', 0)

    account_types = options.get_account_types(options_map)

    # Assert the subaccount name is in valid format.
    if subaccount:
        validation_account = account.join(account_types.assets, subaccount)
        if not account.is_valid(validation_account):
            errors.append(
                UnrealizedError(meta,
                                "Invalid subaccount name: '{}'".format(subaccount),
                                None))
            return entries, errors

    if not entries:
        return (entries, errors)
github beancount / beancount / beancount / ingest / importers / csv / basecsv.py View on Github external
row=last_row.row,
        )
        is_ascending = first_date < last_date

        # Reverse the list if the file is in descending order
        if not is_ascending:
            first_row, last_row = last_row, first_row
            first_date, last_date = last_date, first_date
            entries = list(reversed(entries))

        # Add a balance entry if possible
        if entries:
            idx = len(entries) if is_ascending else 0
            for balance in self.csvconfig.get_balances(
                    field_map=field_map,
                    meta=data.new_metadata(file.name, last_row.index),
                    row=last_row.row,
            ):
                entries.insert(idx, balance)

        return entries
github beancount / beancount / beancount / plugins / fill_account.py View on Github external
def fill_account(entries, unused_options_map, insert_account):
    """Insert an posting with a default account when there is only a single posting.

    Args:
      entries: A list of directives.
      unused_options_map: A parser options dict.
      insert_account: A string, the name of the account.
    Returns:
      A list of entries, possibly with more Price entries than before, and a
      list of errors.
    """
    if not account.is_valid(insert_account):
        return entries, [
            FillAccountError(data.new_metadata('', 0),
                             "Invalid account name: '{}'".format(insert_account),
                             None)]

    new_entries = []
    for entry in entries:
        if isinstance(entry, data.Transaction) and len(entry.postings) == 1:
            inv = inventory.Inventory()
            for posting in entry.postings:
                if posting.cost is None:
                    inv.add_amount(posting.units)
                else:
                    inv.add_amount(convert.get_cost(posting))
            inv.reduce(convert.get_units)
            new_postings = list(entry.postings)
            for pos in inv:
                new_postings.append(data.Posting(insert_account, -pos.units,
github siddhantgoel / beancount-dkb / beancount_dkb / ec.py View on Github external
data.Transaction(
                            meta,
                            date,
                            self.FLAG,
                            line['Auftraggeber / Begünstigter'],
                            description,
                            data.EMPTY_SET,
                            data.EMPTY_SET,
                            postings,
                        )
                    )

                line_index += 1

            # 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 / beancount / beancount / core / getters.py View on Github external
# Currency in price.
                price = posting.price
                if price:
                    commodities_map.setdefault(price.currency, None)

        elif isinstance(entry, Balance):
            commodities_map.setdefault(entry.amount.currency, None)

        elif isinstance(entry, Price):
            commodities_map.setdefault(entry.currency, None)

    if create_missing:
        # Create missing Commodity directives when they haven't been specified explicitly.
        # (I think it might be better to always do this from the loader.)
        date = entries[0].date
        meta = data.new_metadata('', 0)
        commodities_map = {
            commodity: (entry
                        if entry is not None
                        else Commodity(meta, date, commodity))
            for commodity, entry in commodities_map.items()}

    return commodities_map
github beancount / beancount / beancount / parser / grammar.py View on Github external
This is the main routine that takes up most of the parsing time; be very
        careful with modifications here, they have an impact on performance.

        Args:
          filename: the current filename.
          lineno: the current line number.
          date: a datetime object.
          flag: a str, one-character, the flag associated with this transaction.
          txn_strings: A list of strings, possibly empty, possibly longer.
          tags_links: A TagsLinks namedtuple of tags, and/or links.
          posting_or_kv_list: a list of Posting or KeyValue instances, to be inserted in
            this transaction, or None, if no postings have been declared.
        Returns:
          A new Transaction object.
        """
        meta = new_metadata(filename, lineno)

        # Separate postings and key-values.
        explicit_meta = {}
        postings = []
        tags, links = tags_links.tags, tags_links.links
        if posting_or_kv_list:
            last_posting = None
            for posting_or_kv in posting_or_kv_list:
                if isinstance(posting_or_kv, Posting):
                    postings.append(posting_or_kv)
                    last_posting = posting_or_kv
                elif isinstance(posting_or_kv, TagsLinks):
                    if postings:
                        self.errors.append(ParserError(
                            meta,
                            "Tags or links not allowed after first " +
github beancount / beancount / experiments / prices / fetch-lifetime-prices.py View on Github external
entries[-1].date):
        # If the price entry is already in the ledger, ignore it.
        if key in price_map:
            continue
        date, currency, cost_currency = key

        # Ignore entries too early.
        if args.min_date is not None and date < args.min_date:
            continue

        # Ignore entries with an empty cost currency.
        if cost_currency is None:
            continue

        # Create a price directive.
        price = data.Price(data.new_metadata(__file__ ,0),
                           date, currency, Amount(ZERO, cost_currency))
        prices.append(price)

    # For now, just print those out.
    printer.print_entries(prices)
github beancount / beancount / beancount / ops / summarize.py View on Github external
# Filter out to keep only the accounts we want.
    transfer_balances = {account: balance
                         for account, balance in balances.items()
                         if account_pred(account)}

    # We need to insert the entries at the end of the previous day.
    if date:
        transfer_date = date - datetime.timedelta(days=1)
    else:
        transfer_date = entries[-1].date

    # Create transfer entries.
    transfer_entries = create_entries_from_balances(
        transfer_balances, transfer_date, transfer_account, False,
        data.new_metadata('', 0), flags.FLAG_TRANSFER,
        "Transfer balance for '{account}' (Transfer balance)")

    # Remove balance assertions that occur after a transfer on an account that
    # has been transferred away; they would break.
    after_entries = [entry
                     for entry in entries[index:]
                     if not (isinstance(entry, balance.Balance) and
                             entry.account in transfer_balances)]

    # Split the new entries in a new list.
    return (entries[:index] + transfer_entries + after_entries)
github zsxsoft / my-beancount-scripts / modules / imports / alipay.py View on Github external
meta['alipay_trade_no'] = row['交易号']
            meta['trade_time'] = str(time)
            meta['timestamp'] = str(time.timestamp()).replace('.0', '')
            account = get_account_by_guess(row['交易对方'], row['商品名称'], time)
            flag = "*"
            amount = float(row['金额(元)'])
            if account == "Expenses:Unknown":
                flag = "!"

            if row['备注'] != '':
                meta['note'] = row['备注']

            if row['商家订单号'] != '':
                meta['shop_trade_no'] = row['商家订单号']

            meta = data.new_metadata(
                'beancount/core/testing.beancount',
                12345,
                meta
            )
            entry = Transaction(
                meta,
                date(time.year, time.month, time.day),
                flag,
                row['交易对方'],
                row['商品名称'],
                data.EMPTY_SET,
                data.EMPTY_SET, []
            )
            price = row['金额(元)']
            money_status = row['资金状态']
            if money_status == '已支出':