beancount.query

Transaction and postings filtering syntax parser.

beancount.query.numberify

Code to split table columns containing amounts and inventories into number columns.

For example, given a column with this content:

—– amount —— 101.23 USD

200 JPY

99.23 USD 38.34 USD, 100 JPY

We can convert this into two columns and remove the currencies:

-amount (USD)- -amount (JPY)-
101.23

200

99.23 38.34 100

The point is that the columns should be typed as numbers to make this importable into a spreadsheet and able to be processed.

Notes:

  • This handles the Amount, Position and Inventory datatypes. There is code to automatically recognize columns containing such types from a table of strings and convert such columns to their corresponding guessed data types.

  • The per-currency columns are ordered in decreasing order of the number of instances of numbers seen for each currency. So if the most numbers you have in a column are USD, then the USD column renders first.

  • Cost basis specifications should be unmodified and reported to a dedicated extra column, like this:

    —– amount —— 1 AAPL {21.23 USD}

    We can convert this into two columns and remove the currencies:

    -amount (AAPL)- -Cost basis-

    1 {21.23 USD}

    (Eventually we might support the conversion of cost amounts as well, but they may contain other informations, such as a label or a date, so for now we don’t convert them. I’m not sure there’s a good practical use case in doing that yet.)

  • We may provide some options to break out only some of the currencies into columns, in order to handle the case where an inventory contains a large number of currencies and we want to only operate on a restricte set of operating currencies.

  • If you provide a DisplayForamtter object to the numberification routine, they quantize each column according to their currency’s precision. It is recommended that you do that.

class beancount.query.numberify.AmountConverter(name, index, currency)

A converter that extracts the number of an amount for a specific currency.

dtype

alias of decimal.Decimal

class beancount.query.numberify.IdentityConverter(name, dtype, index)

A converter that simply copies its column.

class beancount.query.numberify.InventoryConverter(name, index, currency)

A converter that extracts the number of a inventory for a specific currency. If there are multiple lots we aggregate by currency.

dtype

alias of decimal.Decimal

class beancount.query.numberify.PositionConverter(name, index, currency)

A converter that extracts the number of a position for a specific currency.

dtype

alias of decimal.Decimal

beancount.query.numberify.convert_col_Amount(name, drows, index)

Create converters for a column of type Amount.

Parameters
  • name – A string, the column name.

  • drows – The table of objects.

  • index – The column number.

Returns

A list of Converter instances, one for each of the currency types found.

beancount.query.numberify.convert_col_Inventory(name, drows, index)

Create converters for a column of type Inventory.

Parameters
  • name – A string, the column name.

  • drows – The table of objects.

  • index – The column number.

Returns

A list of Converter instances, one for each of the currency types found.

beancount.query.numberify.convert_col_Position(name, drows, index)

Create converters for a column of type Position.

Parameters
  • name – A string, the column name.

  • drows – The table of objects.

  • index – The column number.

Returns

A list of Converter instances, one for each of the currency types found.

beancount.query.numberify.numberify_results(dtypes, drows, dformat=None)

Number rows containing Amount, Position or Inventory types.

Parameters
  • result_types – A list of items describing the names and data types of the items in each column.

  • result_rows – A list of ResultRow instances.

  • dformat – An optional DisplayFormatter. If set, quantize the numbers by their currency-specific precision when converting the Amount’s, Position’s or Inventory’es..

Returns

A pair of modified (result_types, result_rows) with converted datatypes.

beancount.query.query

A library to run queries. This glues together all the parts of the query engine.

beancount.query.query.run_query(entries, options_map, query, *format_args, numberify=False)

Compile and execute a query, return the result types and rows.

Parameters
  • entries – A list of entries, as produced by the loader.

  • options_map – A dict of options, as produced by the loader.

  • query – A string, a single BQL query, optionally containing some new-style (e.g., {}) formatting specifications.

  • format_args – A tuple of arguments to be formatted in the query. This is just provided as a convenience.

  • numberify – If true, numberify the results before returning them.

Returns

A pair of result types and result rows.

Raises

beancount.query.query_compile

Interpreter for the query language’s AST.

This code accepts the abstract syntax tree produced by the query parser, resolves the column and function names, compiles and interpreter and prepares a query to be run against a list of entries.

class beancount.query.query_compile.AttributeColumn(dtype)
class beancount.query.query_compile.CompilationEnvironment

Base class for all compilation contexts. A compilation context provides column accessors specific to the particular row objects that we will access.

columns = None
context_name = None
functions = None
get_column(name)

Return a column accessor for the given named column. :param name: A string, the name of the column to access.

get_function(name, operands)

Return a function accessor for the given named function. :param name: A string, the name of the function to access.

exception beancount.query.query_compile.CompilationError

A compiler/interpreter error.

class beancount.query.query_compile.EvalAdd(left, right)
class beancount.query.query_compile.EvalAggregator(operands, dtype)

Base class for all aggregator evaluator types.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

finalize(store)

Finalize this node’s aggregate data and return it.

For aggregate methods, this finalizes the node and returns the final value. The context node will be the alloc instead of the context object.

Parameters

store – An object indexable by handles appropriated during allocate().

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_compile.EvalAnd(left, right)
class beancount.query.query_compile.EvalBinaryOp(operator, left, right, dtype)
left
operator
right
class beancount.query.query_compile.EvalColumn(dtype)

Base class for all column accessors.

class beancount.query.query_compile.EvalConstant(value)
value
class beancount.query.query_compile.EvalContains(left, right)
class beancount.query.query_compile.EvalDiv(left, right)
class beancount.query.query_compile.EvalEqual(left, right)
class beancount.query.query_compile.EvalFrom(c_expr, open, close, clear)
class beancount.query.query_compile.EvalFunction(operands, dtype)

Base class for all function objects.

eval_args(context)
operands
class beancount.query.query_compile.EvalGreater(left, right)
class beancount.query.query_compile.EvalGreaterEq(left, right)
class beancount.query.query_compile.EvalLess(left, right)
class beancount.query.query_compile.EvalLessEq(left, right)
class beancount.query.query_compile.EvalMatch(left, right)
static match(left, right)
class beancount.query.query_compile.EvalMul(left, right)
class beancount.query.query_compile.EvalNode(dtype)
childnodes()

Returns the child nodes of this node. :Yields: A list of EvalNode instances.

dtype
class beancount.query.query_compile.EvalNot(operand)
class beancount.query.query_compile.EvalOr(left, right)
class beancount.query.query_compile.EvalPrint(c_from)
class beancount.query.query_compile.EvalQuery(c_targets, c_from, c_where, group_indexes, order_indexes, ordering, limit, distinct, flatten)
class beancount.query.query_compile.EvalSub(left, right)
class beancount.query.query_compile.EvalTarget(c_expr, name, is_aggregate)
class beancount.query.query_compile.EvalUnaryOp(operator, operand, dtype)
operand
operator
class beancount.query.query_compile.ResultSetEnvironment

An execution context that provides access to attributes from a result set.

context_name = 'sub-query'
get_column(name)

Override the column getter to provide a single attribute getter.

beancount.query.query_compile.compile(statement, targets_environ, postings_environ, entries_environ)

Prepare an AST any of the statement into an executable statement.

Parameters
  • statement – An instance of the parser’s Select, Balances, Journal or Print.

  • targets_environ – A compilation environment for evaluating targets.

  • postings_environ – : A compilation environment for evaluating postings filters.

  • entries_environ – : A compilation environment for evaluating entry filters.

Returns

An instance of EvalQuery or EvalPrint, ready to be executed.

Raises

CompilationError – If the statement cannot be compiled, or is not one of the supported statements.

beancount.query.query_compile.compile_expression(expr, environ)

Bind an expression to its execution context.

Parameters
  • expr – The root node of an expression.

  • environ – An CompilationEnvironment instance.

Returns

The root node of a bound expression.

beancount.query.query_compile.compile_from(from_clause, environ)

Compiled a From clause as provided by the parser, in the given environment.

Parameters
  • select – An instance of query_parser.Select.

  • environ – : A compilation context for evaluating entry filters.

Returns

An instance of Query, ready to be executed.

beancount.query.query_compile.compile_group_by(group_by, c_targets, environ)

Process a group-by clause.

Parameters
  • group_by – A GroupBy instance as provided by the parser.

  • c_targets – A list of compiled target expressions.

  • environ – A compilation context to be used to evaluate GROUP BY expressions.

Returns

A tuple of

new_targets: A list of new compiled target nodes. group_indexes: If the query is an aggregate query, a list of integer

indexes to be used for processing grouping. Note that this list may be empty (in the case of targets with only aggregates). On the other hand, if this is not an aggregated query, this is set to None. So do distinguish the empty list vs. None.

beancount.query.query_compile.compile_order_by(order_by, c_targets, environ)

Process an order-by clause.

Parameters
  • order_by – A OrderBy instance as provided by the parser.

  • c_targets – A list of compiled target expressions.

  • environ – A compilation context to be used to evaluate ORDER BY expressions.

Returns

A tuple of

new_targets: A list of new compiled target nodes. order_indexes: A list of integer indexes to be used for processing ordering.

beancount.query.query_compile.compile_print(print_stmt, env_entries)

Compile a Print statement.

Parameters
  • statement – An instance of query_parser.Print.

  • entries_environ – : A compilation environment for evaluating entry filters.

Returns

An instance of EvalPrint, ready to be executed.

beancount.query.query_compile.compile_select(select, targets_environ, postings_environ, entries_environ)

Prepare an AST for a Select statement into a very rudimentary execution tree. The execution tree mostly looks much like an AST, but with some nodes replaced with knowledge specific to an execution context and eventually some basic optimizations.

Parameters
  • select – An instance of query_parser.Select.

  • targets_environ – A compilation environment for evaluating targets.

  • postings_environ – : A compilation environment for evaluating postings filters.

  • entries_environ – : A compilation environment for evaluating entry filters.

Returns

An instance of EvalQuery, ready to be executed.

beancount.query.query_compile.compile_targets(targets, environ)

Compile the targets and check for their validity. Process wildcard.

Parameters
  • targets – A list of target expressions from the parser.

  • environ – A compilation context for the targets.

Returns

A list of compiled target expressions with resolved names.

beancount.query.query_compile.find_unique_name(name, allocated_set)

Come up with a unique name for ‘name’ amongst ‘allocated_set’.

Parameters
  • name – A string, the prefix of the name to find a unique for.

  • allocated_set – A set of string, the set of already allocated names.

Returns

A unique name. ‘allocated_set’ is unmodified.

beancount.query.query_compile.get_columns_and_aggregates(node)

Find the columns and aggregate nodes below this tree.

All nodes under aggregate nodes are ignored.

Parameters

node – An instance of EvalNode.

Returns

A pair of (columns, aggregates), both of which are lists of EvalNode instances.

columns: The list of all columns accessed not under an aggregate node. aggregates: The lis tof all aggregate nodes.

beancount.query.query_compile.is_aggregate(node)

Return true if the node is an aggregate.

Parameters

node – An instance of EvalNode.

Returns

A boolean.

beancount.query.query_compile.is_hashable_type(node)

Return true if the node is of a hashable type.

Parameters

node – An instance of EvalNode.

Returns

A boolean.

beancount.query.query_compile.transform_balances(balances)

Translate a Balances entry into an uncompiled Select statement.

Parameters

balances – An instance of a Balance object.

Returns

An instance of an uncompiled Select object.

beancount.query.query_compile.transform_journal(journal)

Translate a Journal entry into an uncompiled Select statement.

Parameters

journal – An instance of a Journal object.

Returns

An instance of an uncompiled Select object.

beancount.query.query_env

Environment object for compiler.

This module contains the various column accessors and function evaluators that are made available by the query compiler via their compilation context objects. Define new columns and functions here.

class beancount.query.query_env.AbsDecimal(operands)

Compute the length of the argument. This works on sequences.

class beancount.query.query_env.AbsInventory(operands)

Compute the length of the argument. This works on sequences.

class beancount.query.query_env.AbsPosition(operands)

Compute the length of the argument. This works on sequences.

class beancount.query.query_env.AccountColumn

The account of the posting.

class beancount.query.query_env.AccountSortKey(operands)

Get a string to sort accounts in order taking into account the types.

class beancount.query.query_env.AnyMeta(operands)

Get metadata from the posting or its parent transaction’s metadata if not present.

class beancount.query.query_env.BalanceColumn

The balance for the posting. These can be summed into inventories.

class beancount.query.query_env.CloseDate(operands)

Get the date of the close directive of the account.

class beancount.query.query_env.Coalesce(operands)

Return the first non-null argument

class beancount.query.query_env.ConvertAmount(operands)

Coerce an amount to a particular currency.

class beancount.query.query_env.ConvertAmountWithDate(operands)

Coerce an amount to a particular currency.

class beancount.query.query_env.ConvertInventory(operands)

Coerce an inventory to a particular currency.

class beancount.query.query_env.ConvertInventoryWithDate(operands)

Coerce an inventory to a particular currency.

class beancount.query.query_env.ConvertPosition(operands)

Coerce an amount to a particular currency.

class beancount.query.query_env.ConvertPositionWithDate(operands)

Coerce an amount to a particular currency.

class beancount.query.query_env.CostCurrencyColumn

The cost currency of the posting.

class beancount.query.query_env.CostDateColumn

The cost currency of the posting.

class beancount.query.query_env.CostInventory(operands)

Get the cost of an inventory.

class beancount.query.query_env.CostLabelColumn

The cost currency of the posting.

class beancount.query.query_env.CostNumberColumn

The number of cost units of the posting.

class beancount.query.query_env.CostPosition(operands)

Get the cost of a position.

class beancount.query.query_env.Count(operands)

Count the number of occurrences of the argument.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, unused_ontext)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.Currency(operands)

Extract the currency from an Amount.

class beancount.query.query_env.CurrencyColumn

The currency of the posting.

class beancount.query.query_env.CurrencyMeta(operands)

Get the metadata dict of the commodity directive of the currency.

class beancount.query.query_env.Date(operands)

Construct a date with year, month, day arguments

class beancount.query.query_env.DateAdd(operands)

Adds/subtracts number of days from the given date

class beancount.query.query_env.DateColumn

The date of the parent transaction for this posting.

class beancount.query.query_env.DateDiff(operands)

Calculates the difference (in days) between two dates

class beancount.query.query_env.DateEntryColumn

The date of the directive.

class beancount.query.query_env.Day(operands)

Extract the day from a date.

class beancount.query.query_env.DayColumn

The day of the date of the parent transaction for this posting.

class beancount.query.query_env.DayEntryColumn

The day of the date of the directive.

class beancount.query.query_env.DescriptionColumn

A combination of the payee + narration for the transaction of this posting.

class beancount.query.query_env.DescriptionEntryColumn

A combination of the payee + narration of the transaction, if present.

class beancount.query.query_env.EntryMeta(operands)

Get some metadata key of the parent directive (Transaction).

class beancount.query.query_env.FileLocationColumn

The filename:lineno where the posting was parsed from or created.

If you select this column as the first column, because it renders like errors, Emacs is able to pick those up and you can navigate between an arbitrary list of transactions with next-error and previous-error.

class beancount.query.query_env.FilenameColumn

The filename where the posting was parsed from or created.

class beancount.query.query_env.FilenameEntryColumn

The filename where the directive was parsed from or created.

class beancount.query.query_env.FilterCurrencyInventory(operands)

Filter an inventory to just the specified currency.

class beancount.query.query_env.FilterCurrencyPosition(operands)

Filter an inventory to just the specified currency.

class beancount.query.query_env.FilterEntriesEnvironment

An execution context that provides access to attributes on Transactions and other entry types.

columns = {'date': <class 'beancount.query.query_env.DateEntryColumn'>, 'day': <class 'beancount.query.query_env.DayEntryColumn'>, 'description': <class 'beancount.query.query_env.DescriptionEntryColumn'>, 'filename': <class 'beancount.query.query_env.FilenameEntryColumn'>, 'flag': <class 'beancount.query.query_env.FlagEntryColumn'>, 'id': <class 'beancount.query.query_env.IdEntryColumn'>, 'lineno': <class 'beancount.query.query_env.LineNoEntryColumn'>, 'links': <class 'beancount.query.query_env.LinksEntryColumn'>, 'month': <class 'beancount.query.query_env.MonthEntryColumn'>, 'narration': <class 'beancount.query.query_env.NarrationEntryColumn'>, 'payee': <class 'beancount.query.query_env.PayeeEntryColumn'>, 'tags': <class 'beancount.query.query_env.TagsEntryColumn'>, 'type': <class 'beancount.query.query_env.TypeEntryColumn'>, 'year': <class 'beancount.query.query_env.YearEntryColumn'>}
context_name = 'FROM clause'
functions = {('neg', <class 'decimal.Decimal'>): <class 'beancount.query.query_env.NegDecimal'>, ('neg', <class 'beancount.core.amount.Amount'>): <class 'beancount.query.query_env.NegAmount'>, ('neg', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.NegPosition'>, ('neg', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.NegInventory'>, ('abs', <class 'decimal.Decimal'>): <class 'beancount.query.query_env.AbsDecimal'>, ('abs', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.AbsPosition'>, ('abs', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.AbsInventory'>, ('safediv', <class 'decimal.Decimal'>, <class 'decimal.Decimal'>): <class 'beancount.query.query_env.SafeDiv'>, ('safediv', <class 'decimal.Decimal'>, <class 'int'>): <class 'beancount.query.query_env.SafeDivInt'>, 'length': <class 'beancount.query.query_env.Length'>, 'str': <class 'beancount.query.query_env.Str'>, 'maxwidth': <class 'beancount.query.query_env.MaxWidth'>, 'root': <class 'beancount.query.query_env.Root'>, 'parent': <class 'beancount.query.query_env.Parent'>, 'leaf': <class 'beancount.query.query_env.Leaf'>, 'grep': <class 'beancount.query.query_env.Grep'>, 'grepn': <class 'beancount.query.query_env.GrepN'>, 'subst': <class 'beancount.query.query_env.Subst'>, 'open_date': <class 'beancount.query.query_env.OpenDate'>, 'close_date': <class 'beancount.query.query_env.CloseDate'>, 'meta': <class 'beancount.query.query_env.Meta'>, 'entry_meta': <class 'beancount.query.query_env.EntryMeta'>, 'any_meta': <class 'beancount.query.query_env.AnyMeta'>, 'open_meta': <class 'beancount.query.query_env.OpenMeta'>, 'currency_meta': <class 'beancount.query.query_env.CurrencyMeta'>, 'commodity_meta': <class 'beancount.query.query_env.CurrencyMeta'>, 'account_sortkey': <class 'beancount.query.query_env.AccountSortKey'>, ('units', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.UnitsPosition'>, ('units', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.UnitsInventory'>, ('cost', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.CostPosition'>, ('cost', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.CostInventory'>, 'year': <class 'beancount.query.query_env.Year'>, 'month': <class 'beancount.query.query_env.Month'>, 'ymonth': <class 'beancount.query.query_env.YearMonth'>, 'quarter': <class 'beancount.query.query_env.Quarter'>, 'day': <class 'beancount.query.query_env.Day'>, 'weekday': <class 'beancount.query.query_env.Weekday'>, 'today': <class 'beancount.query.query_env.Today'>, ('date', <class 'int'>, <class 'int'>, <class 'int'>): <class 'beancount.query.query_env.Date'>, ('date', <class 'str'>): <class 'beancount.query.query_env.ParseDate'>, 'date_diff': <class 'beancount.query.query_env.DateDiff'>, 'date_add': <class 'beancount.query.query_env.DateAdd'>, ('convert', <class 'beancount.core.amount.Amount'>, <class 'str'>): <class 'beancount.query.query_env.ConvertAmount'>, ('convert', <class 'beancount.core.amount.Amount'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertAmountWithDate'>, ('convert', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.ConvertPosition'>, ('convert', <class 'beancount.core.position.Position'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertPositionWithDate'>, ('convert', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.ConvertInventory'>, ('convert', <class 'beancount.core.inventory.Inventory'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertInventoryWithDate'>, ('value', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.ValuePosition'>, ('value', <class 'beancount.core.position.Position'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ValuePositionWithDate'>, ('value', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.ValueInventory'>, ('value', <class 'beancount.core.inventory.Inventory'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ValueInventoryWithDate'>, ('getprice', <class 'str'>, <class 'str'>): <class 'beancount.query.query_env.Price'>, ('getprice', <class 'str'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.PriceWithDate'>, 'number': <class 'beancount.query.query_env.Number'>, 'currency': <class 'beancount.query.query_env.Currency'>, 'commodity': <class 'beancount.query.query_env.Currency'>, 'getitem': <class 'beancount.query.query_env.GetItemStr'>, 'findfirst': <class 'beancount.query.query_env.FindFirst'>, 'joinstr': <class 'beancount.query.query_env.JoinStr'>, ('possign', <class 'decimal.Decimal'>, <class 'str'>): <class 'beancount.query.query_env.PosSignDecimal'>, ('possign', <class 'beancount.core.amount.Amount'>, <class 'str'>): <class 'beancount.query.query_env.PosSignAmount'>, ('possign', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.PosSignPosition'>, ('possign', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.PosSignInventory'>, 'coalesce': <class 'beancount.query.query_env.Coalesce'>, 'only': <class 'beancount.query.query_env.OnlyInventory'>, ('filter_currency', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.FilterCurrencyPosition'>, ('filter_currency', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.FilterCurrencyInventory'>, 'has_account': <class 'beancount.query.query_env.MatchAccount'>}
class beancount.query.query_env.FilterPostingsEnvironment

An execution context that provides access to attributes on Postings.

columns = {'account': <class 'beancount.query.query_env.AccountColumn'>, 'balance': <class 'beancount.query.query_env.BalanceColumn'>, 'change': <class 'beancount.query.query_env.PositionColumn'>, 'cost_currency': <class 'beancount.query.query_env.CostCurrencyColumn'>, 'cost_date': <class 'beancount.query.query_env.CostDateColumn'>, 'cost_label': <class 'beancount.query.query_env.CostLabelColumn'>, 'cost_number': <class 'beancount.query.query_env.CostNumberColumn'>, 'currency': <class 'beancount.query.query_env.CurrencyColumn'>, 'date': <class 'beancount.query.query_env.DateColumn'>, 'day': <class 'beancount.query.query_env.DayColumn'>, 'description': <class 'beancount.query.query_env.DescriptionColumn'>, 'filename': <class 'beancount.query.query_env.FilenameColumn'>, 'flag': <class 'beancount.query.query_env.FlagColumn'>, 'id': <class 'beancount.query.query_env.IdColumn'>, 'lineno': <class 'beancount.query.query_env.LineNoColumn'>, 'links': <class 'beancount.query.query_env.LinksColumn'>, 'location': <class 'beancount.query.query_env.FileLocationColumn'>, 'month': <class 'beancount.query.query_env.MonthColumn'>, 'narration': <class 'beancount.query.query_env.NarrationColumn'>, 'number': <class 'beancount.query.query_env.NumberColumn'>, 'other_accounts': <class 'beancount.query.query_env.OtherAccountsColumn'>, 'payee': <class 'beancount.query.query_env.PayeeColumn'>, 'position': <class 'beancount.query.query_env.PositionColumn'>, 'posting_flag': <class 'beancount.query.query_env.PostingFlagColumn'>, 'price': <class 'beancount.query.query_env.PriceColumn'>, 'tags': <class 'beancount.query.query_env.TagsColumn'>, 'type': <class 'beancount.query.query_env.TypeColumn'>, 'weight': <class 'beancount.query.query_env.WeightColumn'>, 'year': <class 'beancount.query.query_env.YearColumn'>}
context_name = 'WHERE clause'
functions = {('neg', <class 'decimal.Decimal'>): <class 'beancount.query.query_env.NegDecimal'>, ('neg', <class 'beancount.core.amount.Amount'>): <class 'beancount.query.query_env.NegAmount'>, ('neg', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.NegPosition'>, ('neg', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.NegInventory'>, ('abs', <class 'decimal.Decimal'>): <class 'beancount.query.query_env.AbsDecimal'>, ('abs', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.AbsPosition'>, ('abs', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.AbsInventory'>, ('safediv', <class 'decimal.Decimal'>, <class 'decimal.Decimal'>): <class 'beancount.query.query_env.SafeDiv'>, ('safediv', <class 'decimal.Decimal'>, <class 'int'>): <class 'beancount.query.query_env.SafeDivInt'>, 'length': <class 'beancount.query.query_env.Length'>, 'str': <class 'beancount.query.query_env.Str'>, 'maxwidth': <class 'beancount.query.query_env.MaxWidth'>, 'root': <class 'beancount.query.query_env.Root'>, 'parent': <class 'beancount.query.query_env.Parent'>, 'leaf': <class 'beancount.query.query_env.Leaf'>, 'grep': <class 'beancount.query.query_env.Grep'>, 'grepn': <class 'beancount.query.query_env.GrepN'>, 'subst': <class 'beancount.query.query_env.Subst'>, 'open_date': <class 'beancount.query.query_env.OpenDate'>, 'close_date': <class 'beancount.query.query_env.CloseDate'>, 'meta': <class 'beancount.query.query_env.Meta'>, 'entry_meta': <class 'beancount.query.query_env.EntryMeta'>, 'any_meta': <class 'beancount.query.query_env.AnyMeta'>, 'open_meta': <class 'beancount.query.query_env.OpenMeta'>, 'currency_meta': <class 'beancount.query.query_env.CurrencyMeta'>, 'commodity_meta': <class 'beancount.query.query_env.CurrencyMeta'>, 'account_sortkey': <class 'beancount.query.query_env.AccountSortKey'>, ('units', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.UnitsPosition'>, ('units', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.UnitsInventory'>, ('cost', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.CostPosition'>, ('cost', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.CostInventory'>, 'year': <class 'beancount.query.query_env.Year'>, 'month': <class 'beancount.query.query_env.Month'>, 'ymonth': <class 'beancount.query.query_env.YearMonth'>, 'quarter': <class 'beancount.query.query_env.Quarter'>, 'day': <class 'beancount.query.query_env.Day'>, 'weekday': <class 'beancount.query.query_env.Weekday'>, 'today': <class 'beancount.query.query_env.Today'>, ('date', <class 'int'>, <class 'int'>, <class 'int'>): <class 'beancount.query.query_env.Date'>, ('date', <class 'str'>): <class 'beancount.query.query_env.ParseDate'>, 'date_diff': <class 'beancount.query.query_env.DateDiff'>, 'date_add': <class 'beancount.query.query_env.DateAdd'>, ('convert', <class 'beancount.core.amount.Amount'>, <class 'str'>): <class 'beancount.query.query_env.ConvertAmount'>, ('convert', <class 'beancount.core.amount.Amount'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertAmountWithDate'>, ('convert', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.ConvertPosition'>, ('convert', <class 'beancount.core.position.Position'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertPositionWithDate'>, ('convert', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.ConvertInventory'>, ('convert', <class 'beancount.core.inventory.Inventory'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertInventoryWithDate'>, ('value', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.ValuePosition'>, ('value', <class 'beancount.core.position.Position'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ValuePositionWithDate'>, ('value', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.ValueInventory'>, ('value', <class 'beancount.core.inventory.Inventory'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ValueInventoryWithDate'>, ('getprice', <class 'str'>, <class 'str'>): <class 'beancount.query.query_env.Price'>, ('getprice', <class 'str'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.PriceWithDate'>, 'number': <class 'beancount.query.query_env.Number'>, 'currency': <class 'beancount.query.query_env.Currency'>, 'commodity': <class 'beancount.query.query_env.Currency'>, 'getitem': <class 'beancount.query.query_env.GetItemStr'>, 'findfirst': <class 'beancount.query.query_env.FindFirst'>, 'joinstr': <class 'beancount.query.query_env.JoinStr'>, ('possign', <class 'decimal.Decimal'>, <class 'str'>): <class 'beancount.query.query_env.PosSignDecimal'>, ('possign', <class 'beancount.core.amount.Amount'>, <class 'str'>): <class 'beancount.query.query_env.PosSignAmount'>, ('possign', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.PosSignPosition'>, ('possign', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.PosSignInventory'>, 'coalesce': <class 'beancount.query.query_env.Coalesce'>, 'only': <class 'beancount.query.query_env.OnlyInventory'>, ('filter_currency', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.FilterCurrencyPosition'>, ('filter_currency', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.FilterCurrencyInventory'>}
class beancount.query.query_env.FindFirst(operands)

Filter a string sequence by regular expression and return the first match.

class beancount.query.query_env.First(operands)

Keep the first of the values seen.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.FlagColumn

The flag of the parent transaction for this posting.

class beancount.query.query_env.FlagEntryColumn

The flag the transaction.

class beancount.query.query_env.GetItemStr(operands)

Get the string value of a dict. The value is always converted to a string.

class beancount.query.query_env.Grep(operands)

Match a group against a string and return only the matched portion.

class beancount.query.query_env.GrepN(operands)

Match a pattern with subgroups against a string and return the subgroup at the index

class beancount.query.query_env.IdColumn

The unique id of the parent transaction for this posting.

class beancount.query.query_env.IdEntryColumn

Unique id of a directive.

class beancount.query.query_env.JoinStr(operands)

Join a sequence of strings to a single comma-separated string.

class beancount.query.query_env.Last(operands)

Keep the last of the values seen.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.Leaf(operands)

Get the name of the leaf subaccount.

class beancount.query.query_env.Length(operands)

Compute the length of the argument. This works on sequences.

class beancount.query.query_env.LineNoColumn

The line number from the file the posting was parsed from.

class beancount.query.query_env.LineNoEntryColumn

The line number from the file the directive was parsed from.

class beancount.query.query_env.LinksColumn

The set of links of the parent transaction for this posting.

class beancount.query.query_env.LinksEntryColumn

The set of links of the transaction.

class beancount.query.query_env.MatchAccount(operands)

A predicate, true if the transaction has at least one posting matching the regular expression argument.

class beancount.query.query_env.Max(operands)

Compute the maximum of the values.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.MaxWidth(operands)

Convert the argument to a substring. This can be used to ensure maximum width

class beancount.query.query_env.Meta(operands)

Get some metadata key of the Posting.

class beancount.query.query_env.Min(operands)

Compute the minimum of the values.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.Month(operands)

Extract the month from a date.

class beancount.query.query_env.MonthColumn

The month of the date of the parent transaction for this posting.

class beancount.query.query_env.MonthEntryColumn

The month of the date of the directive.

class beancount.query.query_env.NarrationColumn

The narration of the parent transaction for this posting.

class beancount.query.query_env.NarrationEntryColumn

The narration of the transaction.

class beancount.query.query_env.NegAmount(operands)
class beancount.query.query_env.NegDecimal(operands)
class beancount.query.query_env.NegInventory(operands)
class beancount.query.query_env.NegPosition(operands)
class beancount.query.query_env.Number(operands)

Extract the number from an Amount.

class beancount.query.query_env.NumberColumn

The number of units of the posting.

class beancount.query.query_env.OnlyInventory(operands)

Get one currency’s amount from the inventory.

class beancount.query.query_env.OpenDate(operands)

Get the date of the open directive of the account.

class beancount.query.query_env.OpenMeta(operands)

Get the metadata dict of the open directive of the account.

class beancount.query.query_env.OtherAccountsColumn

The list of other accounts in the transcation, excluding that of this posting.

class beancount.query.query_env.Parent(operands)

Get the parent name of the account.

class beancount.query.query_env.ParseDate(operands)

Construct a date with year, month, day arguments

class beancount.query.query_env.PayeeColumn

The payee of the parent transaction for this posting.

class beancount.query.query_env.PayeeEntryColumn

The payee of the transaction.

class beancount.query.query_env.PosSignAmount(operands)

Correct sign of an Amount based on the usual balance of associated account.

class beancount.query.query_env.PosSignDecimal(operands)

Correct sign of an Amount based on the usual balance of associated account.

class beancount.query.query_env.PosSignInventory(operands)

Correct sign of an Amount based on the usual balance of associated account.

class beancount.query.query_env.PosSignPosition(operands)

Correct sign of an Amount based on the usual balance of associated account.

class beancount.query.query_env.PositionColumn

The position for the posting. These can be summed into inventories.

class beancount.query.query_env.PostingFlagColumn

The flag of the posting itself.

class beancount.query.query_env.Price(operands)

Fetch a price for something at a particular date

class beancount.query.query_env.PriceColumn

The price attached to the posting.

class beancount.query.query_env.PriceWithDate(operands)

Fetch a price for something at a particular date

class beancount.query.query_env.Quarter(operands)

Extract the quarter from a date.

class beancount.query.query_env.Root(operands)

Get the root name(s) of the account.

class beancount.query.query_env.SafeDiv(operands)

A division operation that swallows dbz exceptions and outputs 0 instead.

class beancount.query.query_env.SafeDivInt(operands)
class beancount.query.query_env.Str(operands)

Convert the argument to a string.

class beancount.query.query_env.Subst(operands)

Substitute leftmost non-overlapping occurrences of pattern by replacement.

class beancount.query.query_env.Sum(operands)

Calculate the sum of the numerical argument.

allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.SumAmount(operands)

Calculate the sum of the amount. The result is an Inventory.

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.SumBase(operands)
allocate(allocator)

Allocate handles to store data for a node’s aggregate storage.

This is called once before beginning aggregations. If you need any kind of per-aggregate storage during the computation phase, get it in this method.

Parameters

allocator – An instance of Allocator, on which you can call allocate() to obtain a handle for a slot to store data on store objects later on.

initialize(store)

Initialize this node’s aggregate data. If the node is not an aggregate, simply initialize the subnodes. Override this method in the aggregator if you need data for storage.

Parameters

store – An object indexable by handles appropriated during allocate().

class beancount.query.query_env.SumInventory(operands)

Calculate the sum of the inventories. The result is an Inventory.

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.SumPosition(operands)

Calculate the sum of the position. The result is an Inventory.

update(store, context)

Evaluate this node. This is designed to recurse on its children.

Parameters
  • store – An object indexable by handles appropriated during allocate().

  • context – The object to which the evaluation need to apply (see __call__).

class beancount.query.query_env.TagsColumn

The set of tags of the parent transaction for this posting.

class beancount.query.query_env.TagsEntryColumn

The set of tags of the transaction.

class beancount.query.query_env.TargetsEnvironment

An execution context that provides access to attributes on Postings.

context_name = 'targets/column'
functions = {('neg', <class 'decimal.Decimal'>): <class 'beancount.query.query_env.NegDecimal'>, ('neg', <class 'beancount.core.amount.Amount'>): <class 'beancount.query.query_env.NegAmount'>, ('neg', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.NegPosition'>, ('neg', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.NegInventory'>, ('abs', <class 'decimal.Decimal'>): <class 'beancount.query.query_env.AbsDecimal'>, ('abs', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.AbsPosition'>, ('abs', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.AbsInventory'>, ('safediv', <class 'decimal.Decimal'>, <class 'decimal.Decimal'>): <class 'beancount.query.query_env.SafeDiv'>, ('safediv', <class 'decimal.Decimal'>, <class 'int'>): <class 'beancount.query.query_env.SafeDivInt'>, 'length': <class 'beancount.query.query_env.Length'>, 'str': <class 'beancount.query.query_env.Str'>, 'maxwidth': <class 'beancount.query.query_env.MaxWidth'>, 'root': <class 'beancount.query.query_env.Root'>, 'parent': <class 'beancount.query.query_env.Parent'>, 'leaf': <class 'beancount.query.query_env.Leaf'>, 'grep': <class 'beancount.query.query_env.Grep'>, 'grepn': <class 'beancount.query.query_env.GrepN'>, 'subst': <class 'beancount.query.query_env.Subst'>, 'open_date': <class 'beancount.query.query_env.OpenDate'>, 'close_date': <class 'beancount.query.query_env.CloseDate'>, 'meta': <class 'beancount.query.query_env.Meta'>, 'entry_meta': <class 'beancount.query.query_env.EntryMeta'>, 'any_meta': <class 'beancount.query.query_env.AnyMeta'>, 'open_meta': <class 'beancount.query.query_env.OpenMeta'>, 'currency_meta': <class 'beancount.query.query_env.CurrencyMeta'>, 'commodity_meta': <class 'beancount.query.query_env.CurrencyMeta'>, 'account_sortkey': <class 'beancount.query.query_env.AccountSortKey'>, ('units', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.UnitsPosition'>, ('units', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.UnitsInventory'>, ('cost', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.CostPosition'>, ('cost', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.CostInventory'>, 'year': <class 'beancount.query.query_env.Year'>, 'month': <class 'beancount.query.query_env.Month'>, 'ymonth': <class 'beancount.query.query_env.YearMonth'>, 'quarter': <class 'beancount.query.query_env.Quarter'>, 'day': <class 'beancount.query.query_env.Day'>, 'weekday': <class 'beancount.query.query_env.Weekday'>, 'today': <class 'beancount.query.query_env.Today'>, ('date', <class 'int'>, <class 'int'>, <class 'int'>): <class 'beancount.query.query_env.Date'>, ('date', <class 'str'>): <class 'beancount.query.query_env.ParseDate'>, 'date_diff': <class 'beancount.query.query_env.DateDiff'>, 'date_add': <class 'beancount.query.query_env.DateAdd'>, ('convert', <class 'beancount.core.amount.Amount'>, <class 'str'>): <class 'beancount.query.query_env.ConvertAmount'>, ('convert', <class 'beancount.core.amount.Amount'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertAmountWithDate'>, ('convert', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.ConvertPosition'>, ('convert', <class 'beancount.core.position.Position'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertPositionWithDate'>, ('convert', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.ConvertInventory'>, ('convert', <class 'beancount.core.inventory.Inventory'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ConvertInventoryWithDate'>, ('value', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.ValuePosition'>, ('value', <class 'beancount.core.position.Position'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ValuePositionWithDate'>, ('value', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.ValueInventory'>, ('value', <class 'beancount.core.inventory.Inventory'>, <class 'datetime.date'>): <class 'beancount.query.query_env.ValueInventoryWithDate'>, ('getprice', <class 'str'>, <class 'str'>): <class 'beancount.query.query_env.Price'>, ('getprice', <class 'str'>, <class 'str'>, <class 'datetime.date'>): <class 'beancount.query.query_env.PriceWithDate'>, 'number': <class 'beancount.query.query_env.Number'>, 'currency': <class 'beancount.query.query_env.Currency'>, 'commodity': <class 'beancount.query.query_env.Currency'>, 'getitem': <class 'beancount.query.query_env.GetItemStr'>, 'findfirst': <class 'beancount.query.query_env.FindFirst'>, 'joinstr': <class 'beancount.query.query_env.JoinStr'>, ('possign', <class 'decimal.Decimal'>, <class 'str'>): <class 'beancount.query.query_env.PosSignDecimal'>, ('possign', <class 'beancount.core.amount.Amount'>, <class 'str'>): <class 'beancount.query.query_env.PosSignAmount'>, ('possign', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.PosSignPosition'>, ('possign', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.PosSignInventory'>, 'coalesce': <class 'beancount.query.query_env.Coalesce'>, 'only': <class 'beancount.query.query_env.OnlyInventory'>, ('filter_currency', <class 'beancount.core.position.Position'>, <class 'str'>): <class 'beancount.query.query_env.FilterCurrencyPosition'>, ('filter_currency', <class 'beancount.core.inventory.Inventory'>, <class 'str'>): <class 'beancount.query.query_env.FilterCurrencyInventory'>, ('sum', <class 'beancount.core.amount.Amount'>): <class 'beancount.query.query_env.SumAmount'>, ('sum', <class 'beancount.core.position.Position'>): <class 'beancount.query.query_env.SumPosition'>, ('sum', <class 'beancount.core.inventory.Inventory'>): <class 'beancount.query.query_env.SumInventory'>, 'sum': <class 'beancount.query.query_env.Sum'>, 'count': <class 'beancount.query.query_env.Count'>, 'first': <class 'beancount.query.query_env.First'>, 'last': <class 'beancount.query.query_env.Last'>, 'min': <class 'beancount.query.query_env.Min'>, 'max': <class 'beancount.query.query_env.Max'>}
wildcard_columns = ['date', 'flag', 'payee', 'narration', 'position']
class beancount.query.query_env.Today(operands)

Today’s date

class beancount.query.query_env.TypeColumn

The data type of the parent transaction for this posting.

class beancount.query.query_env.TypeEntryColumn

The data type of the directive.

class beancount.query.query_env.UnitsInventory(operands)

Get the number of units of an inventory (stripping cost).

class beancount.query.query_env.UnitsPosition(operands)

Get the number of units of a position (stripping cost).

class beancount.query.query_env.ValueInventory(operands)

Coerce an inventory to its market value at the current date.

class beancount.query.query_env.ValueInventoryWithDate(operands)

Coerce an inventory to its market value at a particular date.

class beancount.query.query_env.ValuePosition(operands)

Convert a position to its cost currency at the market value.

class beancount.query.query_env.ValuePositionWithDate(operands)

Convert a position to its cost currency at the market value of a particular date.

class beancount.query.query_env.Weekday(operands)

Extract a 3-letter weekday from a date.

class beancount.query.query_env.WeightColumn

The computed weight used for this posting.

class beancount.query.query_env.Year(operands)

Extract the year from a date.

class beancount.query.query_env.YearColumn

The year of the date of the parent transaction for this posting.

class beancount.query.query_env.YearEntryColumn

The year of the date of the directive.

class beancount.query.query_env.YearMonth(operands)

Extract the year and month from a date.

beancount.query.query_execute

Execution of interpreter on data rows.

class beancount.query.query_execute.Allocator

A helper class to count slot allocations and return unique handles to them.

allocate()

Allocate a new slot to store row aggregation information.

Returns

A unique handle used to index into an row-aggregation store (an integer).

create_store()

Create a new row-aggregation store suitable to contain all the node allocations.

Returns

A store that can accomodate and be indexed by all the allocated slot handles.

class beancount.query.query_execute.RowContext

A dumb container for information used by a row expression.

account_types = None
balance = None
commodity_map = None
entry = None
open_close_map = None
options_map = None
posting = None
price_map = None
beancount.query.query_execute.create_row_context(entries, options_map)

Create the context container which we will use to evaluate rows.

beancount.query.query_execute.execute_print(c_print, entries, options_map, file)

Print entries from a print statement specification.

Parameters
  • c_print – An instance of a compiled EvalPrint statemnet.

  • entries – A list of directives.

  • options_map – A parser’s option_map.

  • file – The output file to print to.

beancount.query.query_execute.execute_query(query, entries, options_map)

Given a compiled select statement, execute the query.

Parameters
  • query – An instance of a query_compile.Query

  • entries – A list of directives.

  • options_map – A parser’s option_map.

Returns

result_types: A list of (name, data-type) item pairs. result_rows: A list of ResultRow tuples of length and types described by

’result_types’.

Return type

A pair of

beancount.query.query_execute.filter_entries(c_from, entries, options_map, context)

Filter the entries by the given compiled FROM clause.

Parameters
  • c_from – A compiled From clause instance.

  • entries – A list of directives.

  • options_map – A parser’s option_map.

  • context – A prototype of RowContext to use for evaluation.

Returns

A list of filtered entries.

beancount.query.query_execute.flatten_results(result_types, result_rows)

Convert inventories in result types to have a row for each.

This routine will expand all result lines with an inventory into a new line for each position.

Parameters
  • result_types – A list of (name, data-type) item pairs.

  • result_rows – A list of ResultRow tuples of length and types described by ‘result_types’.

Returns

A list of (name, data-type) item pairs. There should be no

Inventory types anymore.

result_rows: A list of ResultRow tuples of length and types described by

’result_types’. All inventories from the input should have been converted to Position types.

Return type

result_types

beancount.query.query_execute.row_sortkey(order_indexes, values, c_exprs)

Generate a sortkey for the given values.

Parameters
  • order_indexes – The indexes by which the rows should be sorted.

  • values – The computed values in the row.

  • c_exprs – The matching c_expr’s.

Returns

A tuple, the sortkey.

beancount.query.query_execute.uses_balance_column(c_expr)

Return true if the expression accesses the special ‘balance’ column.

Parameters

c_expr – A compiled expression tree (an EvalNode node).

Returns

A boolean, true if the expression contains a BalanceColumn node.

beancount.query.query_parser

Parser for Beancount Query Language.

class beancount.query.query_parser.Add
class beancount.query.query_parser.And
class beancount.query.query_parser.Balances(summary_func, from_clause, where_clause)
class beancount.query.query_parser.Contains
class beancount.query.query_parser.Div
class beancount.query.query_parser.Equal
class beancount.query.query_parser.Errors
class beancount.query.query_parser.Explain(statement)
class beancount.query.query_parser.Greater
class beancount.query.query_parser.GreaterEq
class beancount.query.query_parser.Journal(account, summary_func, from_clause)
class beancount.query.query_parser.Less
class beancount.query.query_parser.LessEq
class beancount.query.query_parser.Lexer

PLY lexer for the Beancount Query Language.

keywords = {'AND', 'AS', 'ASC', 'AT', 'BALANCES', 'BY', 'CLEAR', 'CLOSE', 'DESC', 'DISTINCT', 'ERRORS', 'EXPLAIN', 'FALSE', 'FLATTEN', 'FROM', 'GROUP', 'HAVING', 'IN', 'JOURNAL', 'LIMIT', 'NOT', 'NULL', 'ON', 'OPEN', 'OR', 'ORDER', 'PIVOT', 'PRINT', 'RELOAD', 'RUN', 'SELECT', 'TRUE', 'WHERE'}
t_ASTERISK = '\\*'
t_COMMA = ','
t_DATE(token)

(#(“[^”]*”|\'[^\']*\')|dddd-dd-dd)

t_DECIMAL(token)

[-+]?([0-9]+.[0-9]*|[0-9]*.[0-9]+)

t_EQ = '='
t_GT = '>'
t_GTE = '>='
t_ID(token)

[a-zA-Z][a-zA-Z_]*

t_INTEGER(token)

[-+]?[0-9]+

t_LPAREN = '\\('
t_LT = '<'
t_LTE = '<='
t_MINUS = '-'
t_NE = '!='
t_PLUS = '\\+'
t_RPAREN = '\\)'
t_SEMI = ';'
t_SLASH = '/'
t_STRING(token)

(“[^”]*”|’[^’]*’)

t_TILDE = '~'
t_error(token)
t_ignore = ' \t\n'
tokens = ['ID', 'INTEGER', 'DECIMAL', 'STRING', 'DATE', 'COMMA', 'SEMI', 'LPAREN', 'RPAREN', 'TILDE', 'EQ', 'NE', 'GT', 'GTE', 'LT', 'LTE', 'ASTERISK', 'SLASH', 'PLUS', 'MINUS', 'FROM', 'FALSE', 'OPEN', 'NOT', 'NULL', 'PRINT', 'HAVING', 'ON', 'ASC', 'AT', 'JOURNAL', 'RELOAD', 'SELECT', 'BALANCES', 'LIMIT', 'OR', 'AND', 'ORDER', 'DESC', 'FLATTEN', 'DISTINCT', 'GROUP', 'CLOSE', 'TRUE', 'AS', 'PIVOT', 'WHERE', 'CLEAR', 'BY', 'RUN', 'IN', 'ERRORS', 'EXPLAIN']
class beancount.query.query_parser.Match
class beancount.query.query_parser.Mul
class beancount.query.query_parser.Not
class beancount.query.query_parser.Or
exception beancount.query.query_parser.ParseError

A parser error.

class beancount.query.query_parser.Parser(**options)

PLY parser for the Beancount Query Language’s full command syntax.

p_balances_statement(p)

balances_statement : BALANCES summary_func from where

p_delimiter(p)
delimiterSEMI
empty
p_errors_statement(p)

errors_statement : ERRORS

p_explain_statement(p)

top_statement : EXPLAIN statement delimiter

p_journal_statement(p)
journal_statementJOURNAL summary_func from
JOURNAL account summary_func from
p_print_statement(p)

print_statement : PRINT from

p_regular_statement(p)

top_statement : statement delimiter

p_reload_statement(p)

reload_statement : RELOAD

p_run_statement(p)
run_statementRUN ID
RUN STRING
RUN ASTERISK
RUN empty
p_statement(p)
statementselect_statement
balances_statement
journal_statement
print_statement
run_statement
errors_statement
reload_statement
p_summary_func(p)
summary_funcempty
AT ID
start = 'top_statement'
class beancount.query.query_parser.Print(from_clause)
class beancount.query.query_parser.Reload
class beancount.query.query_parser.RunCustom(query_name)
class beancount.query.query_parser.Select(targets, from_clause, where_clause, group_by, order_by, pivot_by, limit, distinct, flatten)
class beancount.query.query_parser.SelectParser(**options)

PLY parser for the Beancount Query Language’s SELECT statement.

handle_comma_separated_list(p)

Handle a list of 0, 1 or more comma-separated values. :param p: A gramar object.

p_account(p)

account : STRING

p_boolean(p)
booleanTRUE
FALSE
p_column(p)

column : ID

p_column_list(p)
column_listcolumn
column_list COMMA column
p_constant(p)
constantNULL
boolean
INTEGER
DECIMAL
STRING
DATE
p_distinct(p)
distinctempty
DISTINCT
p_empty(_)

empty :

p_error(token)
p_expr_index(p)
expr_indexexpression
INTEGER
p_expr_index_list(p)
expr_index_listexpr_index
expr_index_list COMMA expr_index
p_expression_add(p)

expression : expression PLUS expression

p_expression_and(p)

expression : expression AND expression

p_expression_column(p)

expression : column

p_expression_constant(p)

expression : constant

p_expression_contains(p)

expression : expression IN expression

p_expression_div(p)

expression : expression SLASH expression

p_expression_eq(p)

expression : expression EQ expression

p_expression_function(p)

expression : ID LPAREN expression_list_opt RPAREN

p_expression_gt(p)

expression : expression GT expression

p_expression_gte(p)

expression : expression GTE expression

p_expression_list(p)
expression_listexpression
expression_list COMMA expression
p_expression_list_opt(p)
expression_list_optempty
expression
expression_list COMMA expression
p_expression_lt(p)

expression : expression LT expression

p_expression_lte(p)

expression : expression LTE expression

p_expression_match(p)

expression : expression TILDE expression

p_expression_mul(p)

expression : expression ASTERISK expression

p_expression_ne(p)

expression : expression NE expression

p_expression_not(p)

expression : NOT expression

p_expression_or(p)

expression : expression OR expression

p_expression_paren(p)

expression : LPAREN expression RPAREN

p_expression_sub(p)

expression : expression MINUS expression

p_flatten(p)
flattenempty
FLATTEN
p_from(p)
fromempty
FROM opt_expression opt_open opt_close opt_clear
p_from_subselect(p)
from_subselectfrom
FROM LPAREN select_statement RPAREN
p_group_by(p)
group_byempty
GROUP BY expr_index_list having
p_having(p)
havingempty
HAVING expression
p_limit(p)
limitempty
LIMIT INTEGER
p_opt_clear(p)
opt_clearempty
CLEAR
p_opt_close(p)
opt_closeempty
CLOSE
CLOSE ON DATE
p_opt_expression(p)
opt_expressionempty
expression
p_opt_open(p)
opt_openempty
OPEN ON DATE
p_order_by(p)
order_byempty
ORDER BY expr_index_list ordering
p_ordering(p)
orderingempty
ASC
DESC
p_pivot_by(p)
pivot_byempty
PIVOT BY column_list
p_select_statement(p)

select_statement : SELECT distinct target_spec from_subselect where group_by order_by pivot_by limit flatten

p_target(p)
targetexpression AS ID
expression
p_target_list(p)
target_listtarget
target_list COMMA target
p_target_spec(p)
target_specASTERISK
target_list
p_where(p)
whereempty
WHERE expression
parse(line, debug=False, default_close_date=None)
precedence = [('left', 'OR'), ('left', 'AND'), ('left', 'NOT'), ('left', 'PLUS', 'MINUS'), ('left', 'ASTERISK', 'SLASH'), ('left', 'EQ', 'NE', 'GT', 'GTE', 'LT', 'LTE', 'TILDE', 'IN')]
start = 'select_statement'
tokenize(line)
class beancount.query.query_parser.Sub
beancount.query.query_parser.get_expression_name(expr)

Come up with a reasonable identifier for an expression.

Parameters

expr – An expression node.

beancount.query.query_render

Rendering of rows.

class beancount.query.query_render.AmountRenderer(dcontext)

A renderer for amounts. The currencies align with each other.

dtype

alias of beancount.core.amount.Amount

format(amount_)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(amount_)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.BoolRenderer(dcontext)

A renderer for left-aligned strings.

dtype

alias of builtins.bool

format(value)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(value)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.ColumnRenderer(unused_dcontext)

Base class for classes that render and compute formatting and width for all values that appear within a column. All the values rendered are assumed to be of the same type, or None (empty). The class receives all the values that will be rendered to accumulate the dimensions it will need to format them later on. It is then responsible to render those values in a way that will align nicely in a column, in the rendered output, whereby all the values render to the same width.

dtype = None
format(value)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(value)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.DateTimeRenderer(dcontext)

A renderer for decimal numbers.

dtype

alias of datetime.date

format(dtime)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

update(_)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.DecimalRenderer(dcontext)

A renderer for decimal numbers.

dtype

alias of decimal.Decimal

format(number, key=None)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(number, key=None)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.IntegerRenderer(dcontext)

A renderer for integers.

dtype

alias of builtins.int

format(number)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(number)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.InventoryRenderer(dcontext)

A renderer for Inventoru instances. Inventories renders as a list of position strings. Both the unit numbers and the cost numbers are aligned, if any.

dtype

alias of beancount.core.inventory.Inventory

format(inv)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

update(inv)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

class beancount.query.query_render.ObjectRenderer(dcontext)

A renderer for a generic object type.

dtype

alias of builtins.object

format(string)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(string)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.PositionRenderer(dcontext)

A renderer for positions. Inventories renders as a list of position strings. Both the unit numbers and the cost numbers are aligned, if any.

dtype

alias of beancount.core.position.Position

format(pos)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(pos)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.StringRenderer(dcontext)

A renderer for left-aligned strings.

dtype

alias of builtins.str

format(string)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(string)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

class beancount.query.query_render.StringSetRenderer(dcontext)

A renderer for sets of strings.

dtype

alias of builtins.set

format(string_set)

Format the value.

Parameters

value – Any object of the type ‘dtype’.

Returns

A string, or a list of strings, the rendered and aligned string(s) representations of for the value. A value may render on multiple lines, which is why a list may be returned here.

prepare()

Prepare to render all values of a column. This is called after having seen all the values in calls to update().

update(string_set)

Update the rendered with the given value. :param value: Any object of the type ‘dtype’.

Returns

An integer, the number of lines this will get rendered to.

width()

Return the computed width of this column. :returns: An integer, the number of characters wide required for this field.

beancount.query.query_render.get_renderers(result_types, result_rows, dcontext)

Create renderers for each column and prepare them with the given data.

Parameters
  • result_types – A list of items describing the names and data types of the items in each column.

  • result_rows – A list of ResultRow instances.

  • dcontext – A DisplayContext object prepared for rendering numbers.

Returns

A list of subclass instances of ColumnRenderer.

beancount.query.query_render.render_csv(result_types, result_rows, dcontext, file, expand=False)

Render the result of executing a query in text format.

Parameters
  • result_types – A list of items describing the names and data types of the items in each column.

  • result_rows – A list of ResultRow instances.

  • dcontext – A DisplayContext object prepared for rendering numbers.

  • file – A file object to render the results to.

  • expand – A boolean, if true, expand columns that render to lists on multiple rows.

beancount.query.query_render.render_rows(result_types, result_rows, dcontext, expand=False, spaced=False)

Render the result of executing a query in text format.

Parameters
  • result_types – A list of items describing the names and data types of the items in each column.

  • result_rows – A list of ResultRow instances.

  • dcontext – A DisplayContext object prepared for rendering numbers.

  • expand – A boolean, if true, expand columns that render to lists on multiple rows.

  • spaced – If true, leave an empty line between each of the rows. This is useful if the results have a lot of rows that render over multiple lines.

beancount.query.query_render.render_text(result_types, result_rows, dcontext, file, expand=False, boxed=False, spaced=False)

Render the result of executing a query in text format.

Parameters
  • result_types – A list of items describing the names and data types of the items in each column.

  • result_rows – A list of ResultRow instances.

  • dcontext – A DisplayContext object prepared for rendering numbers.

  • file – A file object to render the results to.

  • expand – A boolean, if true, expand columns that render to lists on multiple rows.

  • boxed – A boolean, true if we should render the results in a fancy-looking ASCII box.

  • spaced – If true, leave an empty line between each of the rows. This is useful if the results have a lot of rows that render over multiple lines.

beancount.query.shell

An interactive command-line shell interpreter for the Beancount Query Language.

class beancount.query.shell.BQLShell(is_interactive, loadfun, outfile, default_format='text', do_numberify=False)

An interactive shell interpreter for the Beancount query language.

help_attributes()
help_from()
help_targets()
help_where()
on_Balances(balance)

Select balances of some subset of postings. This command is a convenience and converts into an equivalent Select statement, designed to extract the most sensible list of columns for the register of a list of entries as a table.

The general form of a JOURNAL statement loosely follows SQL syntax:

BALANCE [FROM_CLAUSE]

See the SELECT query help for more details on the FROM clause.

on_Errors(errors_statement)

Print the errors that occurred during parsing.

on_Explain(explain)

Compile and print a compiled statement for debugging.

on_Journal(journal)

Select a journal of some subset of postings. This command is a convenience and converts into an equivalent Select statement, designed to extract the most sensible list of columns for the register of a list of entries as a table.

The general form of a JOURNAL statement loosely follows SQL syntax:

JOURNAL <account-regexp> [FROM_CLAUSE]

See the SELECT query help for more details on the FROM clause.

on_Print(print_stmt)

Print entries in Beancount format.

The general form of a PRINT statement includes an SQL-like FROM selector:

PRINT [FROM <from_expr> …]

Where:

from_expr: A logical expression that matches on the attributes of

the directives. See SELECT command for details (this FROM expression supports all the same expressions including its OPEN, CLOSE and CLEAR operations).

on_Reload(unused_statement=None)

Reload the input file without restarting the shell.

on_RunCustom(run_stmt)

Run a custom query instead of a SQL command.

RUN <custom-query-name>

Where:

custom-query-name: Should be the name of a custom query to be defined

in the Beancount input file.

on_Select(statement)

Extract data from a query on the postings.

The general form of a SELECT statement loosely follows SQL syntax, with some mild and idiomatic extensions:

SELECT [DISTINCT] [<targets>|*] [FROM <from_expr> [OPEN ON <date>] [CLOSE [ON <date>]] [CLEAR]] [WHERE <where_expr>] [GROUP BY <groups>] [ORDER BY <groups> [ASC|DESC]] [LIMIT num]

Where:

targets: A list of desired output attributes from the postings, and

expressions on them. Some of the attributes of the parent transaction directive are made available in this context as well. Simple functions (that return a single value per row) and aggregation functions (that return a single value per group) are available. For the complete list of supported columns and functions, see help on “targets”. You can also provide a wildcard here, which will select a reasonable default set of columns for rendering a journal.

from_expr: A logical expression that matches on the attributes of

the directives (not postings). This allows you to select a subset of transactions, so the accounting equation is respected for balance reports. For the complete list of supported columns and functions, see help on “from”.

where_expr: A logical expression that matches on the attributes of

postings. The available columns are similar to those in the targets clause, without the aggregation functions.

OPEN clause: replace all the transactions before the given date by

summarizing entries and transfer Income and Expenses balances to Equity.

CLOSE clause: Remove all the transactions after the given date and

CLEAR: Transfer final Income and Expenses balances to Equity.

prompt = 'beancount> '
class beancount.query.shell.DispatchingShell(is_interactive, parser, outfile, default_format, do_numberify)

A usable convenient shell for interpreting commands, with history.

add_help()

Attach help functions for each of the parsed token handlers.

cmdloop()

Override cmdloop to handle keyboard interrupts.

default(line)

Default handling of lines which aren’t recognized as native shell commands.

Parameters

line – The string to be parsed.

dispatch(statement)

Dispatch the given statement to a suitable method.

Parameters

statement – An instance provided by the parser.

Returns

Whatever the invoked method happens to return.

do_EOF(_)

Exit the parser.

do_clear(_)

Clear the history.

do_exit(_)

Exit the parser.

do_help(command)

Strip superfluous semicolon.

do_history(_)

Print the command-line history statement.

do_lex(line)

Just run the lexer on the following command and print the output.

do_parse(line)

Just run the parser on the following command and print the output.

do_quit(_)

Exit the parser.

do_set(line)

Get/set shell settings variables.

do_tokenize(line)

Just run the lexer on the following command and print the output.

doc_header = 'Shell utility commands (type help <topic>):'
emptyline()

Do nothing on an empty line.

exit(_)

Exit the parser.

get_pager()

Create and return a context manager to write to, a pager subprocess if required.

Returns

A pair of a file object to write to, and a pipe object to wait on (or

None if not necessary to wait).

initialize_vars(default_format, do_numberify)

Initialize the setting variables of the interactive shell.

max_entries = 64
misc_header = 'Beancount query commands:'
run_parser(line, default_close_date=None)

Handle statements via our parser instance and dispatch to appropriate methods.

Parameters
  • line – The string to be parsed.

  • default_close_date – A datetimed.date instance, the default close date.

beancount.query.shell.convert_bool(string)

Convert a string to a boolean.

Parameters

string – A string representing a boolean.

Returns

The corresponding boolean.

beancount.query.shell.create_custom_query_map(entries)

Extract a mapping of the custom queries from the list of entries.

Parameters

entries – A list of entries.

Returns

A map of query-name strings to Query directives.

beancount.query.shell.generate_env_attribute_list(env)

Generate a dictionary of rendered attribute lists for help.

Parameters

env – An instance of an environment.

Returns

A dict with keys ‘columns’, ‘functions’ and ‘aggregates’ to rendered and formatted strings.

beancount.query.shell.generate_env_attributes(wrapper, field_dict, filter_pred=None)

Generate a string of all the help functions of the attributes.

Parameters
  • wrapper – A TextWrapper instance to format the paragraphs.

  • field_dict – A dict of the field-names to the node instances, fetch from an environment.

  • filter_pred – A predicate to filter the desired columns. This is applied to the evaluator node instances.

Returns

A formatted multiline string, ready for insertion in a help text.

beancount.query.shell.get_history(max_entries)

Return the history in the readline buffer.

Parameters

max_entries – An integer, the maximum number of entries to return.

Returns

A list of string, the previous history of commands.

beancount.query.shell.load_history(filename)

Load the shell’s past history.

Parameters

filename – A string, the name of the file containing the shell history.

beancount.query.shell.main()
beancount.query.shell.print_statistics(entries, options_map, outfile)

Print summary statistics to stdout.

Parameters
  • entries – A list of directives.

  • options_map – An options map. as produced by the parser.

  • outfile – A file object to write to.

beancount.query.shell.save_history(filename)

Save the shell history. This should be invoked on exit.

Parameters

filename – A string, the name of the file to save the history to.

beancount.query.shell.summary_statistics(entries)

Calculate basic summary statistics to output a brief welcome message.

Parameters

entries – A list of directives.

Returns

A tuple of three integers, the total number of directives parsed, the total number of transactions and the total number of postings there in.