beancount.core

Core basic objects and data structures to represent a list of entries.

beancount.core.account

Functions that operate on account strings.

These account objects are rather simple and dumb; they do not contain the list of their associated postings. This is achieved by building a realization; see realization.py for details.

class beancount.core.account.AccountTransformer(rsep=None)

Account name transformer.

This is used to support Win… huh, filesystems and platforms which do not support colon characters.

rsep

A character string, the new separator to use in link names.

parse(transformed_name)

Convert the transform account name to an account name.

render(account_name)

Convert the account name to a transformed account name.

beancount.core.account.commonprefix(accounts)

Return the common prefix of a list of account names.

Parameters

accounts – A sequence of account name strings.

Returns

A string, the common parent account. If none, returns an empty string.

beancount.core.account.has_component(account_name, component)

Return true if one of the account contains a given component.

Parameters
  • account_name – A string, an account name.

  • component – A string, a component of an account name. For instance, ‘Food’ in ‘Expenses:Food:Restaurant’. All components are considered.

Returns

A boolean, true if the component is in the account. Note that a component name must be whole, that is ‘NY’ is not in Expenses:Taxes:StateNY’.

beancount.core.account.is_valid(string)

Return true if the given string is a valid account name. This does not check for the root account types, just the general syntax.

Parameters

string – A string, to be checked for account name pattern.

Returns

A boolean, true if the string has the form of an account’s name.

beancount.core.account.join(*components)

Join the names with the account separator.

Parameters

*components – Strings, the components of an account name.

Returns

A string, joined in a single account name.

beancount.core.account.leaf(account_name)

Get the name of the leaf of this account.

Parameters

account_name – A string, the name of the account whose leaf name to return.

Returns

A string, the name of the leaf of the account.

beancount.core.account.parent(account_name)

Return the name of the parent account of the given account.

Parameters

account_name – A string, the name of the account whose parent to return.

Returns

A string, the name of the parent account of this account.

beancount.core.account.parent_matcher(account_name)

Build a predicate that returns whether an account is under the given one.

Parameters

account_name – The name of the parent account we want to check for.

Returns

A callable, which, when called, will return true if the given account is a child of ‘account_name’.

beancount.core.account.parents(account_name)

A generator of the names of the parents of this account, including this account.

Parameters

account_name – The name of the account we want to start iterating from.

Returns

A generator of account name strings.

beancount.core.account.root(num_components, account_name)

Return the first few components of an account’s name.

Parameters
  • num_components – An integer, the number of components to return.

  • account_name – A string, an account name.

Returns

A string, the account root up to ‘num_components’ components.

beancount.core.account.sans_root(account_name)

Get the name of the account without the root.

For example, an in put of ‘Assets:BofA:Checking’ will produce ‘BofA:Checking’.

Parameters

account_name – A string, the name of the account whose leaf name to return.

Returns

A string, the name of the non-root portion of this account name.

beancount.core.account.split(account_name)

Split an account’s name into its components.

Parameters

account_name – A string, an account name.

Returns

A list of strings, the components of the account name (without the separators).

beancount.core.account.walk(root_directory)

A version of os.walk() which yields directories that are valid account names.

This only yields directories that are accounts… it skips the other ones. For convenience, it also yields you the account’s name.

Parameters

root_directory – A string, the name of the root of the hierarchy to be walked.

Yields

Tuples of (root, account-name, dirs, files), similar to os.walk().

beancount.core.account_types

Definition for global account types.

This is where we keep the global account types value and definition.

Note that it’s unfortunate that we’re using globals and side-effect here, but this is the best solution in the short-term, the account types are used in too many places to pass around that state everywhere. Maybe we change this later on.

class beancount.core.account_types.AccountTypes(assets, liabilities, equity, income, expenses)
beancount.core.account_types.get_account_sign(account_name, account_types=None)

Return the sign of the normal balance of a particular account.

Parameters
  • account_name – A string, the name of the account whose sign is to return.

  • account_types – An optional instance of the current account_types.

Returns

+1 or -1, depending on the account’s type.

beancount.core.account_types.get_account_sort_key(account_types, account_name)

Return a tuple that can be used to order/sort account names.

Parameters

account_types – An instance of AccountTypes, a tuple of account type names.

Returns

A function object to use as the optional ‘key’ argument to the sort function. It accepts a single argument, the account name to sort and produces a sortable key.

beancount.core.account_types.get_account_type(account_name)

Return the type of this account’s name.

Warning: No check is made on the validity of the account type. This merely returns the root account of the corresponding account name.

Parameters

account_name – A string, the name of the account whose type is to return.

Returns

A string, the type of the account in ‘account_name’.

beancount.core.account_types.is_account_type(account_type, account_name)

Return the type of this account’s name.

Warning: No check is made on the validity of the account type. This merely returns the root account of the corresponding account name.

Parameters
  • account_type – A string, the prefix type of the account.

  • account_name – A string, the name of the account whose type is to return.

Returns

A boolean, true if the account is of the given type.

beancount.core.account_types.is_balance_sheet_account(account_name, account_types)

Return true if the given account is a balance sheet account. Assets, liabilities and equity accounts are balance sheet accounts.

Parameters
  • account_name – A string, an account name.

  • account_types – An instance of AccountTypes.

Returns

A boolean, true if the account is a balance sheet account.

beancount.core.account_types.is_equity_account(account_name, account_types)

Return true if the given account is an equity account.

Parameters
  • account_name – A string, an account name.

  • account_types – An instance of AccountTypes.

Returns

A boolean, true if the account is an equityaccount.

beancount.core.account_types.is_income_statement_account(account_name, account_types)

Return true if the given account is an income statement account. Income and expense accounts are income statement accounts.

Parameters
  • account_name – A string, an account name.

  • account_types – An instance of AccountTypes.

Returns

A boolean, true if the account is an income statement account.

beancount.core.account_types.is_root_account(account_name, account_types=None)

Return true if the account name is a root account. This function does not verify whether the account root is a valid one, just that it is a root account or not.

Parameters
  • account_name – A string, the name of the account to check for.

  • account_types – An optional instance of the current account_types; if provided, we check against these values. If not provided, we merely check that name pattern is that of an account component with no separator.

Returns

A boolean, true if the account is root account.

beancount.core.amount

Amount class.

This simple class is used to associate a number of units of a currency with its currency:

(number, currency).

beancount.core.amount.A(string)

Create an amount from a string.

This is a miniature parser used for building tests.

Parameters

string – A string of <number> <currency>.

Returns

A new instance of Amount.

class beancount.core.amount.Amount

An ‘Amount’ represents a number of a particular unit of something.

It’s essentially a typed number, with corresponding manipulation operations defined on it.

static from_string(string)

Create an amount from a string.

This is a miniature parser used for building tests.

Parameters

string – A string of <number> <currency>.

Returns

A new instance of Amount.

to_string(dformat=<beancount.core.display_context.DisplayFormatter object>)

Convert an Amount instance to a printable string.

Parameters

dformat – An instance of DisplayFormatter.

Returns

A formatted string of the quantized amount and symbol.

valid_types_currency = (<class 'str'>, <class 'type'>, <class 'NoneType'>)
valid_types_number = (<class 'decimal.Decimal'>, <class 'type'>, <class 'NoneType'>)
beancount.core.amount.abs(amount)

Return the absolute value of the given amount.

Parameters

amount – An instance of Amount.

Returns

An instance of Amount.

beancount.core.amount.add(amount1, amount2)

Add the given amounts with the same currency.

Parameters
  • amount1 – An instance of Amount.

  • amount2 – An instance of Amount.

Returns

An instance of Amount, with the sum the two amount’s numbers, in the same currency.

beancount.core.amount.div(amount, number)

Divide the given amount by a number.

Parameters
  • amount – An instance of Amount.

  • number – A decimal number.

Returns

An Amount, with the same currency, but with amount units divided by ‘number’.

beancount.core.amount.from_string(string)

Create an amount from a string.

This is a miniature parser used for building tests.

Parameters

string – A string of <number> <currency>.

Returns

A new instance of Amount.

beancount.core.amount.mul(amount, number)

Multiply the given amount by a number.

Parameters
  • amount – An instance of Amount.

  • number – A decimal number.

Returns

An Amount, with the same currency, but with ‘number’ times units.

beancount.core.amount.sortkey(amount)

A comparison function that sorts by currency first.

Parameters

amount – An instance of Amount.

Returns

A sort key, composed of the currency first and then the number.

beancount.core.amount.sub(amount1, amount2)

Subtract the given amounts with the same currency.

Parameters
  • amount1 – An instance of Amount.

  • amount2 – An instance of Amount.

Returns

An instance of Amount, with the difference between the two amount’s numbers, in the same currency.

beancount.core.compare

Comparison helpers for data objects.

class beancount.core.compare.CompareError(source, message, entry)
beancount.core.compare.compare_entries(entries1, entries2)

Compare two lists of entries. This is used for testing.

The entries are compared with disregard for their file location.

Parameters
  • entries1 – A list of directives of any type.

  • entries2 – Another list of directives of any type.

Returns

success: A booelan, true if all the values are equal. missing1: A list of directives from ‘entries1’ not found in

’entries2’.

missing2: A list of directives from ‘entries2’ not found in

’entries1’.

Return type

A tuple of (success, not_found1, not_found2), where the fields are

Raises

ValueError – If a duplicate entry is found.

beancount.core.compare.excludes_entries(subset_entries, entries)

Check that a list of entries does not appear in another list.

Parameters
  • subset_entries – The set of entries to look for in ‘entries’.

  • entries – The larger list of entries that should not include ‘subset_entries’.

Returns

A boolean and a list of entries that are not supposed to appear.

Raises

ValueError – If a duplicate entry is found.

beancount.core.compare.hash_entries(entries)

Compute unique hashes of each of the entries and return a map of them.

This is used for comparisons between sets of entries.

Parameters

entries – A list of directives.

Returns

A dict of hash-value to entry (for all entries) and a list of errors. Errors are created when duplicate entries are found.

beancount.core.compare.hash_entry(entry)

Compute the stable hash of a single entry.

Parameters

entry – A directive instance.

Returns

A stable hexadecimal hash of this entry.

beancount.core.compare.includes_entries(subset_entries, entries)

Check if a list of entries is included in another list.

Parameters
  • subset_entries – The set of entries to look for in ‘entries’.

  • entries – The larger list of entries that could include ‘subset_entries’.

Returns

A boolean and a list of missing entries.

Raises

ValueError – If a duplicate entry is found.

beancount.core.compare.stable_hash_namedtuple(objtuple, ignore=frozenset({}))

Hash the given namedtuple and its child fields.

The hash_obj is updated. This iterates over all the members of objtuple, skipping the attributes from ‘ignore’, and if the elements are lists or sets, sorts them for stability.

Parameters
  • objtuple – A tuple object or other.

  • ignore – A set of strings, attribute names to be skipped in computing a stable hash. For instance, circular references to objects or irrelevant data.

beancount.core.convert

Conversions from Position (or Posting) to units, cost, weight, market value.

Units: Just the primary amount of the position. Cost: The cost basis of the position, if available. Weight: The cost basis or price of the position. Market Value: The units converted to a value via a price map.

To convert an inventory’s contents, simply use these functions in conjunction with Inventory.reduce(), like

cost_inv = inv.reduce(convert.get_cost)

This module equivalently converts Position and Posting instances. Note that we’re specifically avoiding to create an import dependency on beancount.core.data in order to keep this module isolatable, but it works on postings due to duck-typing.

Function named get_*() are used to compute values from postings to their price currency. Functions named convert_*() are used to convert postings and amounts to any currency.

beancount.core.convert.convert_amount(amt, target_currency, price_map, date=None, via=None)

Return the market value of an Amount in a particular currency.

In addition, if a conversion rate isn’t available, you can provide a list of currencies to attempt to synthesize a rate for via implieds rates.

Parameters
  • amt – An instance of Amount.

  • target_currency – The target currency to convert to.

  • price_map – A dict of prices, as built by prices.build_price_map().

  • date – A datetime.date instance to evaluate the value at, or None.

  • via – A list of currencies to attempt to synthesize an implied rate if the direct conversion fails.

Returns

An Amount, either with a succesful value currency conversion, or if we could not convert the value, the amount itself, unmodified.

beancount.core.convert.convert_position(pos, target_currency, price_map, date=None)

Return the market value of a Position or Posting in a particular currency.

In addition, if the rate from the position’s currency to target_currency isn’t available, an attempt is made to convert from its cost currency, if one is available.

Parameters
  • pos – An instance of Position or Posting, equivalently.

  • target_currency – The target currency to convert to.

  • price_map – A dict of prices, as built by prices.build_price_map().

  • date – A datetime.date instance to evaluate the value at, or None.

Returns

An Amount, either with a succesful value currency conversion, or if we could not convert the value, just the units, unmodified. (See get_value() above for details.)

beancount.core.convert.get_cost(pos)

Return the total cost of a Position or Posting.

Parameters

pos – An instance of Position or Posting, equivalently.

Returns

An Amount.

beancount.core.convert.get_units(pos)

Return the units of a Position or Posting.

Parameters

pos – An instance of Position or Posting, equivalently.

Returns

An Amount.

beancount.core.convert.get_value(pos, price_map, date=None)

Return the market value of a Position or Posting.

Note that if the position is not held at cost, this does not convert anything, even if a price is available in the ‘price_map’. We don’t specify a target currency here. If you’re attempting to make such a conversion, see convert_*() functions below.

Parameters
  • pos – An instance of Position or Posting, equivalently.

  • price_map – A dict of prices, as built by prices.build_price_map().

  • date – A datetime.date instance to evaluate the value at, or None.

Returns

An Amount, either with a succesful value currency conversion, or if we could not convert the value, just the units, unmodified. This is designed so that you could reduce an inventory with this and not lose any information silently in case of failure to convert (possibly due to an empty price map). Compare the returned currency to that of the input position if you need to check for success.

beancount.core.convert.get_weight(pos)

Return the weight of a Position or Posting.

This is the amount that will need to be balanced from a posting of a transaction.

This is a key element of the semantics of transactions in this software. A balance amount is the amount used to check the balance of a transaction. Here are all relevant examples, with the amounts used to balance the postings:

Assets:Account 5234.50 USD -> 5234.50 USD Assets:Account 3877.41 EUR @ 1.35 USD -> 5234.50 USD Assets:Account 10 HOOL {523.45 USD} -> 5234.50 USD Assets:Account 10 HOOL {523.45 USD} @ 545.60 CAD -> 5234.50 USD

Parameters

pos – An instance of Position or Posting, equivalently.

Returns

An Amount.

beancount.core.data

Basic data structures used to represent the Ledger entries.

class beancount.core.data.Balance(meta, date, account, amount, tolerance, diff_amount)
class beancount.core.data.Booking

An enumeration.

AVERAGE = 'AVERAGE'
FIFO = 'FIFO'
LIFO = 'LIFO'
NONE = 'NONE'
STRICT = 'STRICT'
class beancount.core.data.Close(meta, date, account)
class beancount.core.data.Commodity(meta, date, currency)
class beancount.core.data.Custom(meta, date, type, values)
class beancount.core.data.Document(meta, date, account, filename, tags, links)
class beancount.core.data.Event(meta, date, type, description)
class beancount.core.data.Note(meta, date, account, comment)
class beancount.core.data.Open(meta, date, account, currencies, booking)
class beancount.core.data.Pad(meta, date, account, source_account)
class beancount.core.data.Posting(account, units, cost, price, flag, meta)
class beancount.core.data.Price(meta, date, currency, amount)
class beancount.core.data.Query(meta, date, name, query_string)
class beancount.core.data.Transaction(meta, date, flag, payee, narration, tags, links, postings)
class beancount.core.data.TxnPosting(txn, posting)
beancount.core.data.create_simple_posting(entry, account, number, currency)

Create a simple posting on the entry, with just a number and currency (no cost).

Parameters
  • entry – The entry instance to add the posting to.

  • account – A string, the account to use on the posting.

  • number – A Decimal number or string to use in the posting’s Amount.

  • currency – A string, the currency for the Amount.

Returns

An instance of Posting, and as a side-effect the entry has had its list of postings modified with the new Posting instance.

beancount.core.data.create_simple_posting_with_cost(entry, account, number, currency, cost_number, cost_currency)

Create a simple posting on the entry, with just a number and currency (no cost).

Parameters
  • entry – The entry instance to add the posting to.

  • account – A string, the account to use on the posting.

  • number – A Decimal number or string to use in the posting’s Amount.

  • currency – A string, the currency for the Amount.

  • cost_number – A Decimal number or string to use for the posting’s cost Amount.

  • cost_currency – a string, the currency for the cost Amount.

Returns

An instance of Posting, and as a side-effect the entry has had its list of postings modified with the new Posting instance.

beancount.core.data.entry_sortkey(entry)

Sort-key for entries. We sort by date, except that checks should be placed in front of every list of entries of that same day, in order to balance linearly.

Parameters

entry – An entry instance.

Returns

A tuple of (date, integer, integer), that forms the sort key for the entry.

beancount.core.data.filter_txns(entries)

A generator that yields only the Transaction instances.

This is such an incredibly common operation that it deserves a terse filtering mechanism.

Parameters

entries – A list of directives.

Yields

A sorted list of only the Transaction directives.

beancount.core.data.find_closest(entries, filename, lineno)

Find the closest entry from entries to (filename, lineno).

Parameters
  • entries – A list of directives.

  • filename – A string, the name of the ledger file to look for. Be careful to provide the very same filename, and note that the parser stores the absolute path of the filename here.

  • lineno – An integer, the line number closest after the directive we’re looking for. This may be the exact/first line of the directive.

Returns

The closest entry found in the given file for the given filename, or None, if none could be found.

beancount.core.data.get_entry(posting_or_entry)

Return the entry associated with the posting or entry.

Parameters

entry – A TxnPosting or entry instance

Returns

A datetime instance.

beancount.core.data.has_entry_account_component(entry, component)

Return true if one of the entry’s postings has an account component.

Parameters
  • entry – A Transaction entry.

  • component – A string, a component of an account name. For instance, ‘Food’ in ‘Expenses:Food:Restaurant’. All components are considered.

Returns

A boolean, true if the component is in the account. Note that a component name must be whole, that is ‘NY’ is not in Expenses:Taxes:StateNY’.

beancount.core.data.iter_entry_dates(entries, date_begin, date_end)

Iterate over the entries in a date window.

Parameters
  • entries – A date-sorted list of dated directives.

  • date_begin – A datetime.date instance, the first date to include.

  • date_end – A datetime.date instance, one day beyond the last date.

Yields

Instances of the dated directives, between the dates, and in the order in which they appear.

beancount.core.data.new_directive(clsname, fields)

Create a directive class. Do not include default fields. This should probably be carried out through inheritance.

Parameters
  • name – A string, the capitalized name of the directive.

  • fields (List[Tuple]) – A string or the list of strings, names for the fields to add to the base tuple.

Return type

Namedtuple

Returns

A type object for the new directive type.

beancount.core.data.new_metadata(filename, lineno, kvlist=None)

Create a new metadata container from the filename and line number.

Parameters
  • filename – A string, the filename for the creator of this directive.

  • lineno – An integer, the line number where the directive has been created.

  • kvlist – An optional container of key-values.

Returns

A metadata dict.

beancount.core.data.posting_has_conversion(posting)

Return true if this position involves a conversion.

A conversion is when there is a price attached to the amount but no cost. This is used on transactions to convert between units.

Parameters

posting – an instance of Posting

Returns

A boolean, true if this posting has a price conversion.

beancount.core.data.posting_sortkey(entry)

Sort-key for entries or postings. We sort by date, except that checks should be placed in front of every list of entries of that same day, in order to balance linearly.

Parameters

entry – A Posting or entry instance

Returns

A tuple of (date, integer, integer), that forms the sort key for the posting or entry.

beancount.core.data.remove_account_postings(account, entries)

Remove all postings with the given account.

Parameters

account – A string, the account name whose postings we want to remove.

Returns

A list of entries without the rounding postings.

beancount.core.data.sanity_check_types(entry, allow_none_for_tags_and_links=False)

Check that the entry and its postings has all correct data types.

Parameters
  • entry – An instance of one of the entries to be checked.

  • allow_none_for_tags_and_links – A boolean, whether to allow plugins to generate Transaction objects with None as value for the ‘tags’ or ‘links’ attributes.

Raises

AssertionError – If there is anything that is unexpected, raises an exception.

beancount.core.data.sorted(entries)

A convenience to sort a list of entries, using entry_sortkey().

Parameters

entries – A list of directives.

Returns

A sorted list of directives.

beancount.core.data.transaction_has_conversion(transaction)

Given a Transaction entry, return true if at least one of the postings has a price conversion (without an associated cost). These are the source of non-zero conversion balances.

Parameters

transaction – an instance of a Transaction entry.

Returns

A boolean, true if this transacation contains at least one posting with a price conversion.

beancount.core.display_context

A settings class to offer control over the number of digits rendered.

This module contains routines that can accumulate information on the width and precision of numbers to be rendered and derive the precision required to render all of them consistently and under certain common alignment requirements. This is required in order to output neatly lined up columns of numbers in various styles.

A common case is that the precision can be observed for numbers present in the input file. This display precision can be used as the “precision by default” if we write a routine for which it is inconvenient to feed all the numbers to build such an accumulator.

Here are all the aspects supported by this module:

PRECISION: Numbers for a particular currency are always rendered to the same precision, and they can be rendered to one of two precisions; either

  1. the most common number of fractional digits, or

  2. the maximum number of digits seen (this is useful for rendering prices).

ALIGNMENT: Several alignment methods are supported.

“natural”: Render the strings as small as possible with no padding, but to their currency’s precision. Like this:

‘1.2345’ ‘764’ ‘-7,409.01’ ‘0.00000125’

“dot-aligned”: The periods will align vertically, the left and right sides

are padded so that the column of numbers has the same width:

‘ 1.2345 ‘ ‘ 764 ‘ ‘-7,409.01 ‘ ‘ 0.00000125’

“right”: The strings are all flushed right, the left side is padded so that

the column of numbers has the same width:

‘ 1.2345’ ‘ 764’ ‘ -7,409.01’ ‘ 0.00000125’

SIGN: If a negative sign is present in the input numbers, the rendered numbers reserve a space for it. If not, then we save the space.

COMMAS: If the user requests to render commas, commas are rendered in the output.

RESERVED: A number of extra integral digits reserved on the left in order to allow rendering novel numbers that haven’t yet been seen. For example, balances may contains much larger numbers than the numbers seen in input files, and these need to be accommodated when aligning to the right.

class beancount.core.display_context.Align

Alignment style for numbers.

DOT = 2
NATURAL = 1
RIGHT = 3
class beancount.core.display_context.DisplayContext

A builder object used to construct a DisplayContext from a series of numbers.

ccontexts

A dict of currency string to CurrencyContext instance.

commas

A bool, true if we should render commas. This just gets propagated onwards as the default value of to build with.

DEFAULT_UNINITIALIZED_PRECISION = 8
build(alignment=<Align.NATURAL: 1>, precision=<Precision.MOST_COMMON: 1>, commas=None, reserved=0)

Build a formatter for the given display context.

Parameters
  • alignment – The desired alignment.

  • precision – The desired precision.

  • commas – Whether to render commas or not. If ‘None’, the default value carried by the context will be used.

  • reserved – An integer, the number of extra digits to be allocated in the maximum width calculations.

quantize(number, currency, precision=<Precision.MOST_COMMON: 1>)

Quantize the given number to the given precision.

Parameters
  • number – A Decimal instance, the number to be quantized.

  • currency – A currency string.

  • precision – Which precision to use.

Returns

A Decimal instance, the quantized number.

set_commas(commas)

Set the default value for rendering commas.

update(number, currency='__default__')

Update the builder with the given number for the given currency.

Parameters
  • number – An instance of Decimal to consider for this currency.

  • currency – An optional string, the currency this numbers applies to.

class beancount.core.display_context.DisplayFormatter(dcontext, precision, fmtstrings)

A class used to contain various settings that control how we output numbers. In particular, the precision used for each currency, and whether or not commas should be printed. This object is intended to be passed around to all functions that format numbers to strings.

dcontext

A DisplayContext instance.

precision

An enum of Precision from which it was built.

fmtstrings

A dict of currency to pre-baked format strings for it.

fmtfuncs

A dict of currency to pre-baked formatting functionsfor it.

format(number, currency='__default__')
quantize(number, currency='__default__')
class beancount.core.display_context.Precision

The type of precision required.

MAXIMUM = 2
MOST_COMMON = 1

beancount.core.distribution

A simple accumulator for data about a mathematical distribution.

class beancount.core.distribution.Distribution

A class that computes a histogram of integer values. This is used to compute a length that will cover at least some decent fraction of the samples.

empty()

Return true if the distribution is empty.

Returns

A boolean.

max()

Return the minimum value seen in the distribution.

Returns

An element of the value type, or None, if the distribution was empty.

min()

Return the minimum value seen in the distribution.

Returns

An element of the value type, or None, if the distribution was empty.

mode()

Return the mode of the distribution.

Returns

An element of the value type, or None, if the distribution was empty.

update(value)

Add a sample to the distribution.

Parameters

value – A value of the function.

beancount.core.flags

Flag constants.

beancount.core.getters

Getter functions that operate on lists of entries to return various lists of things that they reference, accounts, tags, links, currencies, etc.

class beancount.core.getters.GetAccounts

Accounts gatherer.

Balance(entry)

Process directives with a single account attribute.

Parameters

entry – An instance of a directive.

Returns

The single account of this directive.

Close(entry)

Process directives with a single account attribute.

Parameters

entry – An instance of a directive.

Returns

The single account of this directive.

Commodity(entry)

Process directives with no accounts.

Parameters

entry – An instance of a directive.

Returns

An empty list

Custom(entry)

Process directives with no accounts.

Parameters

entry – An instance of a directive.

Returns

An empty list

Document(entry)

Process directives with a single account attribute.

Parameters

entry – An instance of a directive.

Returns

The single account of this directive.

Event(entry)

Process directives with no accounts.

Parameters

entry – An instance of a directive.

Returns

An empty list

Note(entry)

Process directives with a single account attribute.

Parameters

entry – An instance of a directive.

Returns

The single account of this directive.

Open(entry)

Process directives with a single account attribute.

Parameters

entry – An instance of a directive.

Returns

The single account of this directive.

Pad(entry)

Process a Pad directive.

Parameters

entry – An instance of Pad.

Returns

The two accounts of the Pad directive.

Price(entry)

Process directives with no accounts.

Parameters

entry – An instance of a directive.

Returns

An empty list

Query(entry)

Process directives with no accounts.

Parameters

entry – An instance of a directive.

Returns

An empty list

Transaction(entry)

Process a Transaction directive.

Parameters

entry – An instance of Transaction.

Yields

The accounts of the legs of the transaction.

get_accounts_use_map(entries)

Gather the list of accounts from the list of entries.

Parameters

entries – A list of directive instances.

Returns

A pair of dictionaries of account name to date, one for first date used and one for last date used. The keys should be identical.

get_entry_accounts(entry)

Gather all the accounts references by a single directive.

Note: This should get replaced by a method on each directive eventually, that would be the clean way to do this.

Parameters

entry – A directive instance.

Returns

A set of account name strings.

beancount.core.getters.get_account_components(entries)

Gather all the account components available in the given directives.

Parameters

entries – A list of directive instances.

Returns

A list of strings, the unique account components, including the root account names.

beancount.core.getters.get_account_open_close(entries)

Fetch the open/close entries for each of the accounts.

If an open or close entry happens to be duplicated, accept the earliest entry (chronologically).

Parameters

entries – A list of directive instances.

Returns

A map of account name strings to pairs of (open-directive, close-directive) tuples.

beancount.core.getters.get_accounts(entries)

Gather all the accounts references by a list of directives.

Parameters

entries – A list of directive instances.

Returns

A set of account strings.

beancount.core.getters.get_accounts_use_map(entries)

Gather all the accounts references by a list of directives.

Parameters

entries – A list of directive instances.

Returns

A pair of dictionaries of account name to date, one for first date used and one for last date used. The keys should be identical.

beancount.core.getters.get_active_years(entries)

Yield all the years that have at least one entry in them.

Parameters

entries – A list of directive instances.

Yields

Unique dates see in the list of directives.

Return a list of all the links seen in the given entries.

Parameters

entries – A list of directive instances.

Returns

A set of links strings.

beancount.core.getters.get_all_payees(entries)

Return a list of all the unique payees seen in the given entries.

Parameters

entries – A list of directive instances.

Returns

A set of payee strings.

beancount.core.getters.get_all_tags(entries)

Return a list of all the tags seen in the given entries.

Parameters

entries – A list of directive instances.

Returns

A set of tag strings.

beancount.core.getters.get_commodity_map(entries, create_missing=True)

Create map of commodity names to Commodity entries.

Parameters
  • entries – A list of directive instances.

  • create_missing – A boolean, true if you want to automatically generate missing commodity directives if not present in the output map.

Returns

A map of commodity name strings to Commodity directives.

beancount.core.getters.get_dict_accounts(account_names)

Return a nested dict of all the unique leaf names. account names are labelled with LABEL=True

Parameters

account_names – An iterable of account names (strings)

Returns

A nested OrderedDict of account leafs

beancount.core.getters.get_entry_accounts(entry)

Gather all the accounts references by a single directive.

Note: This should get replaced by a method on each directive eventually, that would be the clean way to do this.

Parameters

entries – A directive instance.

Returns

A set of account strings.

beancount.core.getters.get_leveln_parent_accounts(account_names, level, nrepeats=0)

Return a list of all the unique leaf names are level N in an account hierarchy.

Parameters
  • account_names – A list of account names (strings)

  • level – The level to cross-cut. 0 is for root accounts.

  • nrepeats – A minimum number of times a leaf is required to be present in the the list of unique account names in order to be returned by this function.

Returns

A list of leaf node names.

beancount.core.getters.get_min_max_dates(entries, types=None)

Return the minimum and amximum dates in the list of entries.

Parameters
  • entries – A list of directive instances.

  • types – An optional tuple of types to restrict the entries to.

Returns

A pair of datetime.date dates, the minimum and maximum dates seen in the directives.

beancount.core.getters.get_values_meta(name_to_entries_map, *meta_keys, default=None)

Get a map of the metadata from a map of entries values.

Given a dict of some key to a directive instance (or None), return a mapping of the key to the metadata extracted from each directive, or a default value. This can be used to gather a particular piece of metadata from an accounts map or a commodities map.

Parameters
  • name_to_entries_map – A dict of something to an entry or None.

  • meta_keys – A list of strings, the keys to fetch from the metadata.

  • default – The default value to use if the metadata is not available or if the value/entry is None.

Returns

A mapping of the keys of name_to_entries_map to the values of the ‘meta_keys’ metadata. If there are multiple ‘meta_keys’, each value is a tuple of them. On the other hand, if there is only a single one, the value itself is returned.

beancount.core.interpolate

Code used to automatically complete postings without positions.

class beancount.core.interpolate.BalanceError(source, message, entry)
beancount.core.interpolate.compute_entries_balance(entries, prefix=None, date=None)

Compute the balance of all postings of a list of entries.

Sum up all the positions in all the postings of all the transactions in the list of entries and return an inventory of it.

Parameters
  • entries – A list of directives.

  • prefix – If specified, a prefix string to restrict by account name. Only postings with an account that starts with this prefix will be summed up.

  • date – A datetime.date instance at which to stop adding up the balance. The date is exclusive.

Returns

An instance of Inventory.

beancount.core.interpolate.compute_entry_context(entries, context_entry)

Compute the balances of all accounts referenced by entry up to entry.

This provides the inventory of the accounts to which the entry is to be applied, before and after.

Parameters
  • entries – A list of directives.

  • context_entry – The entry for which we want to obtain the before and after context.

Returns

Two dicts of account-name to Inventory instance, one which represents the context before the entry is applied, and one that represents the context after it has been applied.

beancount.core.interpolate.compute_residual(postings)

Compute the residual of a set of complete postings, and the per-currency precision.

This is used to cross-check a balanced transaction.

The precision is the maximum fraction that is being used for each currency (a dict). We use the currency of the weight amount in order to infer the quantization precision for each currency. Integer amounts aren’t contributing to the determination of precision.

Parameters

postings – A list of Posting instances.

Returns

An instance of Inventory, with the residual of the given list of postings.

beancount.core.interpolate.fill_residual_posting(entry, account_rounding)

If necessary, insert a posting to absorb the residual. This makes the transaction balance exactly.

Note: This was developed in order to tweak transactions before exporting them to Ledger. A better method would be to enable the feature that autoamtically inserts these rounding postings on all transactions, and so maybe this method can be deprecated if we do so.

Parameters
  • entry – An instance of a Transaction.

  • account_rounding – A string, the name of the rounding account that absorbs residuals / rounding errors.

Returns

A possibly new, modified entry with a new posting. If a residual was not needed - the transaction already balanced perfectly - no new leg is inserted.

beancount.core.interpolate.get_residual_postings(residual, account_rounding)

Create postings to book the given residuals.

Parameters
  • residual – An Inventory, the residual positions.

  • account_rounding – A string, the name of the rounding account that absorbs residuals / rounding errors.

Returns

A list of new postings to be inserted to reduce the given residual.

beancount.core.interpolate.has_nontrivial_balance(posting)

Return True if a Posting has a balance amount that would have to be calculated.

Parameters

posting – A Posting instance.

Returns

A boolean.

beancount.core.interpolate.infer_tolerances(postings, options_map, use_cost=None)

Infer tolerances from a list of postings.

The tolerance is the maximum fraction that is being used for each currency (a dict). We use the currency of the weight amount in order to infer the quantization precision for each currency. Integer amounts aren’t contributing to the determination of precision.

The ‘use_cost’ option allows one to experiment with letting postings at cost and at price influence the maximum value of the tolerance. It’s tricky to use and alters the definition of the tolerance in a non-trivial way, if you use it. The tolerance is expanded by the sum of the cost times a fraction ‘M’ of the smallest digits in the number of units for all postings held at cost.

For example, in this transaction:

2006-01-17 * “Plan Contribution”

Assets:Investments:VWELX 18.572 VWELX {30.96 USD} Assets:Investments:VWELX 18.572 VWELX {30.96 USD} Assets:Investments:Cash -1150.00 USD

The tolerance for units of USD will calculated as the MAXIMUM of:

0.01 * M = 0.005 (from the 1150.00 USD leg)

The sum of

0.001 * M x 30.96 = 0.01548 + 0.001 * M x 30.96 = 0.01548

= 0.03096

So the tolerance for USD in this case is max(0.005, 0.03096) = 0.03096. Prices contribute similarly to the maximum tolerance allowed.

Note that ‘M’ above is the inferred_tolerance_multiplier and its default value is 0.5.

Parameters
  • postings – A list of Posting instances.

  • options_map – A dict of options.

  • use_cost – A boolean, true if we should be using a combination of the smallest digit of the number times the cost or price in order to infer the tolerance. If the value is left unspecified (as ‘None’), the default value can be overridden by setting an option.

Returns

A dict of currency to the tolerated difference amount to be used for it, e.g. 0.005.

beancount.core.interpolate.is_tolerance_user_specified(tolerance)

Return true if the given tolerance number was user-specified.

This would allow the user to provide a tolerance like # 0.1234 but not 0.123456. This is used to detect whether a tolerance value # is input by the user and not inferred automatically.

Parameters

tolerance – An instance of Decimal.

Returns

A boolean.

beancount.core.interpolate.quantize_with_tolerance(tolerances, currency, number)

Quantize the units using the tolerance dict.

Parameters
  • tolerances – A dict of currency to tolerance Decimalvalues.

  • number – A number to quantize.

  • currency – A string currecy.

Returns

A Decimal, the number possibly quantized.

beancount.core.inventory

A container for an inventory of positions.

This module provides a container class that can hold positions. An inventory is a mapping ofpositions, where each position is keyed by

(currency: str, cost: Cost) -> position: Position

where

‘currency’: The commodity under consideration, USD, CAD, or stock units such

as HOOL, MSFT, AAPL, etc.;

‘cost’: None or a Cost instance existing of cost currency, number, date, and

label;

‘position’: A Position object, whose ‘units’ attribute is guaranteed to have

the same currency as ‘currency’ and whose ‘cost’ attribute is equal to the ‘cost’ key. It basically stores the number of units.

This is meant to accommodate both booked and non-booked amounts. The clever trick that we pull to do this is that for positions which aren’t booked, we simply leave the ‘cost’ as None. This is the case for most of the transactions.

class beancount.core.inventory.Booking

Result of booking a new lot to an existing inventory.

AUGMENTED = 3
CREATED = 1
IGNORED = 4
REDUCED = 2
class beancount.core.inventory.Inventory(positions=None)

An Inventory is a set of positions.

positions

A list of Position instances, held in this Inventory object.

add_amount(units, cost=None)

Add to this inventory using amount and cost. This adds with strict lot matching, that is, no partial matches are done on the arguments to the keys of the inventory.

Parameters
  • units – An Amount instance to add.

  • cost – An instance of Cost or None, as a key to the inventory.

Returns

A pair of (position, booking) where ‘position’ is the position that that was modified BEFORE it was modified, and where ‘booking’ is a Booking enum that hints at how the lot was booked to this inventory. Position may be None if there is no corresponding Position object, e.g. the position was deleted.

add_inventory(other)

Add all the positions of another Inventory instance to this one.

Parameters

other – An instance of Inventory to add to this one.

Returns

This inventory, modified.

add_position(position)

Add using a position (with strict lot matching). Return True if this position was booked against and reduced another.

Parameters

position – The Posting or Position to add to this inventory.

Returns

A pair of (position, booking) where ‘position’ is the position that that was modified, and where ‘booking’ is a Booking enum that hints at how the lot was booked to this inventory.

average()

Average all lots of the same currency together.

Use the minimum date from each aggregated set of lots.

Returns

An instance of Inventory.

cost_currencies()

Return the list of unit currencies held in this inventory.

Returns

A set of currency strings.

currencies()

Return the list of unit currencies held in this inventory.

Returns

A list of currency strings.

currency_pairs()

Return the commodities held in this inventory.

Returns

A set of currency strings.

static from_string(string)

Create an Inventory from a string. This is useful for writing tests.

Parameters

string – A comma-separated string of <number> <currency> with an optional {<number> <currency>} for the cost.

Returns

A new instance of Inventory with the given balances.

get_currency_units(currency)

Fetch the total amount across all the position in the given currency. This may sum multiple lots in the same currency denomination.

Parameters

currency – A string, the currency to filter the positions with.

Returns

An instance of Amount, with the given currency.

get_only_position()

Return the first position and assert there are no more. If the inventory is empty, return None.

get_positions()

Return the positions in this inventory.

Returns

A shallow copy of the list of positions.

is_empty()

Return true if the inventory is empty, that is, has no positions.

Returns

A boolean.

is_mixed()

Return true if the inventory contains a mix of positive and negative lots for at least one instrument.

Returns

A boolean.

is_reduced_by(ramount)

Return true if the amount could reduce this inventory.

Parameters

ramount – An instance of Amount.

Returns

A boolean.

is_small(tolerances)

Return true if all the positions in the inventory are small.

Parameters

tolerances – A Decimal, the small number of units under which a position is considered small, or a dict of currency to such epsilon precision.

Returns

A boolean.

reduce(reducer, *args)

Reduce an inventory using one of the conversion functions.

See functions in beancount.core.conversions.

Returns

An instance of Inventory.

segregate_units(currencies)

Split up the list of positions to the given currencies.

Parameters

currencies – A list of currency strings, the currencies to isolate.

Returns

A dict of currency to Inventory instances.

to_string(dformat=<beancount.core.display_context.DisplayFormatter object>, parens=True)

Convert an Inventory instance to a printable string.

Parameters
  • dformat – An instance of DisplayFormatter.

  • parents – A boolean, true if we should surround the results by parentheses.

Returns

A formatted string of the quantized amount and symbol.

beancount.core.inventory.check_invariants(inv)

Check the invariants of the Inventory.

Parameters

inventory – An instance of Inventory.

Returns

True if the invariants are respected.

beancount.core.inventory.from_string(string)

Create an Inventory from a string. This is useful for writing tests.

Parameters

string – A comma-separated string of <number> <currency> with an optional {<number> <currency>} for the cost.

Returns

A new instance of Inventory with the given balances.

beancount.core.number

The module contains the basic Decimal type import.

About Decimal usage:

  • Do not import Decimal from the ‘decimal’ or ‘cdecimal’ modules; always import your Decimal class from beancount.core.amount.

  • Prefer to use D() to create new instances of Decimal objects, which handles more syntax, e.g., handles None, and numbers with commas.

beancount.core.number.D(strord=None)

Convert a string, possibly with commas, into a Decimal object.

This function just returns the argument if it is already a Decimal object, for convenience. This is used in parsing amounts from files in the importers. This is the main function you should use to build all numbers the system manipulates (never use floating-point in an accounting system)..

Parameters

stdord – A string or Decimal instance.

Returns

A Decimal instance.

class beancount.core.number.MISSING
beancount.core.number.is_fast_decimal(decimal_module)

Return true if a fast C decimal implementattion is installed.

beancount.core.number.round_to(number, increment)

Round a number down to a particular increment.

Parameters
  • number – A Decimal, the number to be rounded.

  • increment – A Decimal, the size of the increment.

Returns

A Decimal, the rounded number.

beancount.core.number.same_sign(number1, number2)

Return true if both numbers have the same sign.

Parameters
  • number1 – An instance of Decimal.

  • number2 – An instance of Decimal.

Returns

A boolean.

beancount.core.position

A position object, which consists of units Amount and cost Cost.

See types below for details.

class beancount.core.position.Cost(number, currency, date, label)
class beancount.core.position.CostSpec(number_per, number_total, currency, date, label, merge)
class beancount.core.position.Position

A ‘Position’ is a pair of units and optional cost. This is used to track inventories.

units

An Amount, the number of units and its currency.

cost

A Cost that represents the lot, or None.

cost_types = (<class 'beancount.core.position.Cost'>, <class 'beancount.core.position.CostSpec'>)
currency_pair()

Return the currency pair associated with this position.

Returns

A pair of a currency string and a cost currency string or None.

static from_amounts(units, cost_amount=None)

Create a position from an amount and a cost.

Parameters
  • amount – An amount, that represents the number of units and the lot currency.

  • cost_amount – If not None, represents the cost amount.

Returns

A Position instance.

static from_string(string)

Create a position from a string specification.

This is a miniature parser used for building tests.

Parameters

string – A string of <number> <currency> with an optional {<number> <currency>} for the cost, similar to the parser syntax.

Returns

A new instance of Position.

get_negative()

Get a copy of this position but with a negative number.

Returns

An instance of Position which represents the inserse of this Position.

is_negative_at_cost()

Return true if the position is held at cost and negative.

Returns

A boolean.

sortkey()

Return a key to sort positions by. This key depends on the order of the currency of the lot (we want to order common currencies first) and the number of units.

Returns

A tuple, used to sort lists of positions.

to_string(dformat=<beancount.core.display_context.DisplayFormatter object>, detail=True)

Render the position to a string.See to_string() for details.

beancount.core.position.cost_to_str(cost, dformat, detail=True)

Format an instance of Cost or a CostSpec to a string.

Parameters
  • cost – An instance of Cost or CostSpec.

  • dformat – A DisplayFormatter object.

  • detail – A boolean, true if we should render the non-amount components.

Returns

A string, suitable for formatting.

beancount.core.position.from_amounts(units, cost_amount=None)

Create a position from an amount and a cost.

Parameters
  • amount – An amount, that represents the number of units and the lot currency.

  • cost_amount – If not None, represents the cost amount.

Returns

A Position instance.

beancount.core.position.from_string(string)

Create a position from a string specification.

This is a miniature parser used for building tests.

Parameters

string – A string of <number> <currency> with an optional {<number> <currency>} for the cost, similar to the parser syntax.

Returns

A new instance of Position.

beancount.core.position.get_position(posting)

Build a Position instance from a Posting instance.

Parameters

posting – An instance of Posting.

Returns

An instance of Position.

beancount.core.position.to_string(pos, dformat=<beancount.core.display_context.DisplayFormatter object>, detail=True)

Render the Position or Posting instance to a string.

Parameters
  • pos – An instance of Position or Posting.

  • dformat – An instance of DisplayFormatter.

  • detail – A boolean, true if we should only render the lot details beyond the cost (lot-date, label, etc.). If false, we only render the cost, if present.

Returns

A string, the rendered position.

beancount.core.prices

This module has code that can build a database of historical prices at various times, from which unrealized capital gains and market value can be deduced.

Prices are deduced from Price entries found in the file, or perhaps created by scripts (for example you could build a script that will fetch live prices online and create entries on-the-fly).

class beancount.core.prices.PriceMap

A price map dictionary.

The keys include both the set of forward (base, quote) pairs and their inverse. In order to determine which are the forward pairs, access the ‘forward_pairs’ attribute

Atttributes:

forward_pairs: A list of (base, quote) keys for the forward pairs.

forward_pairs
beancount.core.prices.build_price_map(entries)

Build a price map from a list of arbitrary entries.

If multiple prices are found for the same (currency, cost-currency) pair at the same date, the latest date is kept and the earlier ones (for that day) are discarded.

If inverse price pairs are found, e.g. USD in AUD and AUD in USD, the inverse that has the smallest number of price points is converted into the one that has the most price points. In that way they are reconciled into a single one.

Parameters
  • entries – A list of directives, hopefully including some Price and/or

  • entries. (Transaction) –

Returns

A dict of (currency, cost-currency) keys to sorted lists of (date, number) pairs, where ‘date’ is the date the price occurs at and ‘number’ a Decimal that represents the price, or rate, between these two currencies/commodities. Each date occurs only once in the sorted list of prices of a particular key. All of the inverses are automatically generated in the price map.

beancount.core.prices.get_all_prices(price_map, base_quote)

Return a sorted list of all (date, number) price pairs.

Parameters
  • price_map – A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map.

  • base_quote – A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a ‘/’ separator.

Returns

A list of (date, Decimal) pairs, sorted by date.

Raises

KeyError – If the base/quote could not be found.

beancount.core.prices.get_last_price_entries(entries, date)

Run through the entries until the given date and return the last Price entry encountered for each (currency, cost-currency) pair.

Parameters
  • entries – A list of directives.

  • date – An instance of datetime.date. If None, the very latest price is returned.

Returns

A list of price entries.

beancount.core.prices.get_latest_price(price_map, base_quote)

Return the latest price/rate from a prica map for the given base/quote pair. This is often used to just get the ‘current’ price if you’re looking at the entire set of entries.

Parameters

price_map – A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map.

Returns

A pair of (date, number), where ‘date’ is a datetime.date instancea dn ‘number’ is a Decimal of the price, or rate, at that date. The date is the latest date which we have an available price for in the price map.

beancount.core.prices.get_price(price_map, base_quote, date=None)

Return the price as of the given date.

If the date is unspecified, return the latest price.

Parameters
  • price_map – A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map.

  • base_quote – A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a ‘/’ separator.

  • date – A datetime.date instance, the date at which we want the conversion rate.

Returns

A pair of (datetime.date, Decimal) instance. If no price information could be found, return (None, None).

beancount.core.prices.normalize_base_quote(base_quote)

Convert a slash-separated string to a pair of strings.

Parameters

base_quote – A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a ‘/’ separator.

Returns

A pair of strings.

beancount.core.realization

Realization of specific lists of account postings into reports.

This code converts a list of entries into a tree of RealAccount nodes (which stands for “realized accounts”). The RealAccount objects contain lists of Posting instances instead of Transactions, or other entry types that are attached to an account, such as a Balance or Note entry.

The interface of RealAccount corresponds to that of a regular Python dict, where the keys are the names of the individual components of an account’s name, and the values are always other RealAccount instances. If you want to get an account by long account name, there are helper functions in this module for this purpose (see realization.get(), for instance). RealAccount instances also contain the final balance of that account, resulting from its list of postings.

You should not build RealAccount trees yourself; instead, you should filter the list of desired directives to display and call the realize() function with them.

class beancount.core.realization.RealAccount(account_name, *args, **kwargs)

A realized account, inserted in a tree, that contains the list of realized entries.

account

A string, the full name of the corresponding account.

postings

A list of postings associated with this accounting (does not include the postings of children accounts).

balance

The final balance of the list of postings associated with this account.

account
balance
copy()

Override dict.copy() to clone a RealAccount.

This is only necessary to correctly implement the copy method. Otherwise, calling .copy() on a RealAccount instance invokes the base class’ method, which return just a dict.

Returns

A cloned instance of RealAccount, with all members shallow-copied.

txn_postings
beancount.core.realization.compute_balance(real_account)

Compute the total balance of this account and all its subaccounts.

Parameters

real_account – A RealAccount instance.

Returns

An Inventory.

beancount.core.realization.compute_postings_balance(txn_postings)

Compute the balance of a list of Postings’s or TxnPosting’s positions.

Parameters

postings – A list of Posting instances and other directives (which are skipped).

Returns

An Inventory.

beancount.core.realization.contains(real_account, account_name)

True if the given account node contains the subaccount name.

Parameters

account_name – A string, the name of a direct or indirect subaccount of this node.

Returns

A boolean, true the name is a child of this node.

beancount.core.realization.dump(root_account)

Convert a RealAccount node to a line of lines.

Note: this is not meant to be used to produce text reports; the reporting code should produce an intermediate object that contains the structure of it, which can then be rendered to ASCII, HTML or CSV formats. This is intended as a convenient little function for dumping trees of data for debugging purposes.

Parameters

root_account – A RealAccount instance.

Returns

A list of tuples of (first_line, continuation_line, real_account) where
first_line: A string, the first line to render, which includes the

account name.

continuation_line: A string, further line to render if necessary. real_account: The RealAccount instance which corresponds to this

line.

beancount.core.realization.dump_balances(real_root, dformat, at_cost=False, fullnames=False, file=None)

Dump a realization tree with balances.

Parameters
  • real_root – An instance of RealAccount.

  • dformat – An instance of DisplayFormatter to format the numbers with.

  • at_cost – A boolean, if true, render the values at cost.

  • fullnames – A boolean, if true, don’t render a tree of accounts and render the full account names.

  • file – A file object to dump the output to. If not specified, we return the output as a string.

Returns

A string, the rendered tree, or nothing, if ‘file’ was provided.

beancount.core.realization.filter(real_account, predicate)

Filter a RealAccount tree of nodes by the predicate.

This function visits the tree and applies the predicate on each node. It returns a partial clone of RealAccount whereby on each node - either the predicate is true, or - for at least one child of the node the predicate is true. All the leaves have the predicate be true.

Parameters
  • real_account – An instance of RealAccount.

  • predicate – A callable/function which accepts a real_account and returns a boolean. If the function returns True, the node is kept.

Returns

A shallow clone of RealAccount is always returned.

beancount.core.realization.find_last_active_posting(txn_postings)

Look at the end of the list of postings, and find the last posting or entry that is not an automatically added directive. Note that if the account is closed, the last posting is assumed to be a Close directive (this is the case if the input is valid and checks without errors.

Parameters

txn_postings – a list of postings or entries.

Returns

An entry, or None, if the input list was empty.

beancount.core.realization.get(real_account, account_name, default=None)

Fetch the subaccount name from the real_account node.

Parameters
  • real_account – An instance of RealAccount, the parent node to look for children of.

  • account_name – A string, the name of a possibly indirect child leaf found down the tree of ‘real_account’ nodes.

  • default – The default value that should be returned if the child subaccount is not found.

Returns

A RealAccount instance for the child, or the default value, if the child is not found.

beancount.core.realization.get_or_create(real_account, account_name)

Fetch the subaccount name from the real_account node.

Parameters
  • real_account – An instance of RealAccount, the parent node to look for children of, or create under.

  • account_name – A string, the name of the direct or indirect child leaf to get or create.

Returns

A RealAccount instance for the child, or the default value, if the child is not found.

beancount.core.realization.get_postings(real_account)

Return a sorted list a RealAccount’s postings and children.

Parameters

real_account – An instance of RealAccount.

Returns

A list of Posting or directories.

beancount.core.realization.index_key(sequence, value, key, cmp)

Find the index of the first element in ‘sequence’ which is equal to ‘value’. If ‘key’ is specified, the value compared to the value returned by this function. If the value is not found, return None.

Parameters
  • sequence – The sequence to search.

  • value – The value to search for.

  • key – A predicate to call to obtain the value to compare against.

  • cmp – A comparison predicate.

Returns

The index of the first element found, or None, if the element was not found.

beancount.core.realization.iter_children(real_account, leaf_only=False)

Iterate this account node and all its children, depth-first.

Parameters
  • real_account – An instance of RealAccount.

  • leaf_only – A boolean flag, true if we should yield only leaves.

Yields

Instances of RealAccount, beginning with this account. The order is undetermined.

beancount.core.realization.iterate_with_balance(txn_postings)

Iterate over the entries, accumulating the running balance.

For each entry, this yields tuples of the form:

(entry, postings, change, balance)

entry: This is the directive for this line. If the list contained Posting

instance, this yields the corresponding Transaction object.

postings: A list of postings on this entry that affect the balance. Only the

postings encountered in the input list are included; only those affect the balance. If ‘entry’ is not a Transaction directive, this should always be an empty list. We preserve the original ordering of the postings as they appear in the input list.

change: An Inventory object that reflects the total change due to the

postings from this entry that appear in the list. For example, if a Transaction has three postings and two are in the input list, the sum of the two postings will be in the ‘change’ Inventory object. However, the position for the transactions’ third posting–the one not included in the input list–will not be in this inventory.

balance: An Inventory object that reflects the balance after adding the

‘change’ inventory due to this entry’s transaction. The ‘balance’ yielded is never None, even for entries that do not affect the balance, that is, with an empty ‘change’ inventory. It’s up to the caller, the one rendering the entry, to decide whether to render this entry’s change for a particular entry type.

Note that if the input list of postings-or-entries is not in sorted date order, two postings for the same entry appearing twice with a different date in between will cause the entry appear twice. This is correct behavior, and it is expected that in practice this should never happen anyway, because the list of postings or entries should always be sorted. This method attempts to detect this and raises an assertion if this is seen.

Parameters

txn_postings – A list of postings or directive instances. Postings affect the balance; other entries do not.

Yields

Tuples of (entry, postings, change, balance) as described above.

beancount.core.realization.postings_by_account(entries)

Create lists of postings and balances by account.

This routine aggregates postings and entries grouping them by account name. The resulting lists contain postings in-lieu of Transaction directives, but the other directives are stored as entries. This yields a list of postings or other entries by account. All references to accounts are taken into account.

Parameters

entries – A list of directives.

Returns

A mapping of account name to list of TxnPosting instances or non-Transaction directives, sorted in the same order as the entries.

beancount.core.realization.realize(entries, min_accounts=None, compute_balance=True)

Group entries by account, into a “tree” of realized accounts. RealAccount’s are essentially containers for lists of postings and the final balance of each account, and may be non-leaf accounts (used strictly for organizing accounts into a hierarchy). This is then used to issue reports.

The lists of postings in each account my be any of the entry types, except for Transaction, whereby Transaction entries are replaced by the specific Posting legs that belong to the account. Here’s a simple diagram that summarizes this seemingly complex, but rather simple data structure:

+————-+ postings +——+ | RealAccount |---------->| Open | +————-+ +——+


v

+————+ +————-+ | TxnPosting |---->| Transaction | +————+ +————-+

\

v `.__ +———+

+—–+ `——–>| Posting | | Pad | +———+ +—–+


v

Balance


v

Close


.

Parameters
  • entries – A list of directives.

  • min_accounts – A list of strings, account names to ensure we create, regardless of whether there are postings on those accounts or not. This can be used to ensure the root accounts all exist.

  • compute_balance – A boolean, true if we should compute the final balance on the realization.

Returns

The root RealAccount instance.