fava.core

This module provides the data required by Fava’s reports.

class fava.core.AccountData

Holds information about an account.

close_date

The date on which this account is closed (or datetime.date.max).

meta

The metadata of the Open entry of this account.

class fava.core.FavaLedger(path)

Create an interface for a Beancount ledger.

Parameters

path – Path to the main Beancount file.

account_is_closed(account_name)

Check if the account is closed.

Parameters

account_name – An account name.

Returns

True if the account is closed before the end date of the current time filter.

account_journal(account_name, with_journal_children=False)

Journal for an account.

Parameters
  • account_name – An account name.

  • with_journal_children – Whether to include postings of subaccounts of the given account.

Returns

A list of tuples (entry, postings, change, balance). change and balance have already been reduced to units.

account_types

A Namedtuple containing the names of the five base accounts.

account_uptodate_status(account_name)

Status of the last balance or transaction.

Parameters

account_name – An account name.

Returns

A status string for the last balance or transaction of the account.

  • ’green’: A balance check that passed.

  • ’red’: A balance check that failed.

  • ’yellow’: Not a balance check.

accounts

A dict containing information about the accounts.

all_entries

List of all (unfiltered) entries.

all_entries_by_type

Dict of list of all (unfiltered) entries by type.

all_root_account
attributes

An AttributesModule instance.

beancount_file_path

The path to the main Beancount file.

budgets

A BudgetModule instance.

changed()

Check if the file needs to be reloaded.

Returns

True if a change in one of the included files or a change in a document folder was detected and the file has been reloaded.

charts

A ChartModule instance.

commodity_pairs()

List pairs of commodities.

Returns

A list of pairs of commodities. Pairs of operating currencies will be given in both directions not just in the one found in file.

context(entry_hash)

Context for an entry.

Parameters

entry_hash – Hash of entry.

Returns

A tuple (entry, balances, source_slice, sha256sum) of the (unique) entry with the given entry_hash. If the entry is a Balance or Transaction then balances is a 2-tuple containing the balances before and after the entry of the affected accounts.

end_date

The date to use for prices.

entries
errors

A list of all errors reported by Beancount.

events(event_type=None)

List events (possibly filtered by type).

extensions

A ExtensionModule instance.

fava_options

A dict with all of Fava’s option values.

file

A FileModule instance.

filter(force=False, **kwargs)

Set and apply (if necessary) filters.

format_decimal

A DecimalFormatModule instance.

get_account_sign(account_name)

Get account sign.

Parameters

account_name – An account name.

Returns

The sign of the given account, +1 for an assets or expenses account, -1 otherwise.

get_entry(entry_hash)

Find an entry.

Parameters

entry_hash – Hash of the entry.

Returns

The entry with the given hash.

Raises

FavaAPIException – If there is no entry for the given hash.

ingest

A IngestModule instance.

interval_balances(interval, account_name, accumulate=False)

Balances by interval.

Parameters
  • interval – An interval.

  • account_name – An account name.

  • accumulate – A boolean, True if the balances for an interval should include all entries up to the end of the interval.

Returns

A list of RealAccount instances for all the intervals.

interval_ends(interval)

Generator yielding dates corresponding to interval boundaries.

last_entry(account_name)

Get last entry of an account.

Parameters

account_name – An account name.

Returns

The last entry of the account if it is not a Close entry.

load_file()

Load the main file and all included files and set attributes.

misc

A FavaMisc instance.

options

A Beancount options map.

paths_to_watch()

The paths to included files and document directories.

Returns

A tuple (files, directories).

postings

All postings contained in some transaction.

price_map
prices(base, quote)

List all prices.

query_shell

A QueryShell instance.

root_account
root_tree
root_tree_closed

A root tree for the balance sheet.

statement_path(entry_hash, metadata_key)

Returns the path for a statement found in the specified entry.

fava.core.attributes

Attributes for auto-completion.

class fava.core.attributes.AttributesModule(ledger)

Some attributes of the ledger (mostly for auto-completion).

load_file()

Gets called when the file has been (re)loaded.

payee_accounts(payee)

Rank accounts for the given payee.

payee_transaction(payee)

The last transaction for the given payee.

fava.core.budgets

Parsing and computing budgets.

class fava.core.budgets.Budget(account, date_start, period, number, currency)
class fava.core.budgets.BudgetError(source, message, entry)
class fava.core.budgets.BudgetModule(ledger)

Parses budget entries.

calculate(account_name, begin_date, end_date)

Calculate the budget for an account in an interval.

calculate_children(account_name, begin_date, end_date)

Calculate the budget for an account including its children.

load_file()

Gets called when the file has been (re)loaded.

fava.core.budgets.calculate_budget(budgets, account_name, date_from, date_to)

Calculate budget for an account.

Parameters
  • budgets – A list of Budget entries.

  • account_name – An account name.

  • date_from – Starting date.

  • date_to – End date (exclusive).

Returns

A dictionary of currency to Decimal with the budget for the specified account and period.

fava.core.budgets.calculate_budget_children(budgets, account_name, date_from, date_to)

Calculate budget for an account including budgets of its children.

Parameters
  • budgets – A list of Budget entries.

  • account_name – An account name.

  • date_from – Starting date.

  • date_to – End date (exclusive).

Returns

A dictionary of currency to Decimal with the budget for the specified account and period.

fava.core.budgets.parse_budgets(custom_entries)

Parse budget directives from custom entries.

Parameters

custom_entries – the Custom entries to parse budgets from.

Returns

A dict of accounts to lists of budgets.

Example

2015-04-09 custom “budget” Expenses:Books “monthly” 20.00 EUR

fava.core.charts

Provide data suitable for Fava’s charts.

class fava.core.charts.ChartModule(ledger)

Return data for the various charts in Fava.

events(event_type=None)

All events for a given event type.

hierarchy(account_name, begin=None, end=None)

An account tree.

interval_totals(interval, accounts)

Renders totals for account (or accounts) in the intervals.

Parameters
  • interval – An interval.

  • accounts – A single account (str) or a tuple of accounts.

ledger
linechart(account_name)

The balance of an account.

Parameters

account_name – A string.

Returns

A list of dicts for all dates on which the balance of the given account has changed containing the balance (in units) of the account at that date.

net_worth(interval)

Compute net worth.

Parameters

interval – A string for the interval.

Returns

A list of dicts for all ends of the given interval containing the net worth (Assets + Liabilities) separately converted to all operating currencies.

class fava.core.charts.FavaJSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)

Allow encoding some Beancount date structures.

default(o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    return JSONEncoder.default(self, o)

fava.core.extensions

Fava extensions

class fava.core.extensions.ExtensionModule(ledger)

Fava extensions.

load_file()

Gets called when the file has been (re)loaded.

run_hook(event, *args)

Run a hook for all extensions.

template_and_extension(name)

Provide data to render an extension report.

Parameters

name – The extension class qualname.

Returns

Tuple of associated template source, extension instance

fava.core.extensions.extension_entries(custom_entries)

Parse custom entries for extensions.

They have the following format: 2016-04-01 custom “fava-extension” “my_extension” “{‘my_option’: {}}”

fava.core.fava_options

Fava’s options.

Options for Fava can be specified through Custom entries in the Beancount file. This module contains a list of possible options, the defaults and the code for parsing the options.

class fava.core.fava_options.InsertEntryOption(date, re, filename, lineno)
class fava.core.fava_options.OptionError(source, message, entry)
fava.core.fava_options.parse_options(custom_entries)

Parse custom entries for Fava options.

The format for option entries is the following:

2016-04-01 custom “fava-option” “[name]” “[value]”

Parameters

custom_entries – A list of Custom entries.

Returns

A tuple (options, errors) where options is a dictionary of all options to values, and errors contains possible parsing errors.

fava.core.file

Reading/writing Beancount files.

class fava.core.file.FileModule(ledger)

Functions related to reading/writing to Beancount files.

get_source(path)

Get source files.

Parameters

path – The path of the file.

Returns

A string with the file contents and the sha256sum of the file.

Raises

FavaAPIException – If the file at path is not one of the source files.

insert_entries(entries)

Insert entries.

Parameters

entries – A list of entries.

insert_metadata(entry_hash, basekey, value)

Insert metadata into a file at lineno.

Also, prevent duplicate keys.

list_sources()

List source files.

Returns

A list of all sources files, with the main file listed first.

render_entries(entries)

Return entries in Beancount format.

Only renders Balance and Transaction.

Parameters

entries – A list of entries.

Yields

The entries rendered in Beancount format.

set_source(path, source, sha256sum)

Write to source file.

Parameters
  • path – The path of the file.

  • source – A string with the file contents.

  • sha256sum – Hash of the file.

Returns

The sha256sum of the updated file.

Raises

FavaAPIException – If the file at path is not one of the source files or if the file was changed externally.

fava.core.file.find_entry_lines(lines, lineno)

Lines of entry starting at lineno.

fava.core.file.find_insert_position(accounts, date, insert_options, filenames)

Find insert position for an account.

Parameters
  • accounts – A list of accounts.

  • date – A date. Only InsertOptions before this date will be considered.

  • insert_options – A list of InsertOption.

  • filenames – List of Beancount files.

Returns

A tuple of the filename and the line number.

fava.core.file.get_entry_slice(entry)

Get slice of the source file for an entry.

Parameters

entry – An entry.

Returns

A string containing the lines of the entry and the sha256sum of these lines.

Raises

FavaAPIException – If the file at path is not one of the source files.

fava.core.file.incomplete_sortkey(entry)

Sortkey for entries that might have incomplete metadata.

fava.core.file.insert_entry(entry, filenames, fava_options)

Insert an entry.

Parameters
  • entry – An entry.

  • filenames – List of filenames.

  • fava_options – The ledgers fava_options. Note that the line numbers of the insert options might be updated.

fava.core.file.insert_metadata_in_file(filename, lineno, key, value)

Inserts the specified metadata in the file below lineno, taking into account the whitespace in front of the line that lineno.

fava.core.file.leading_space(line)

Returns a string representing the leading whitespace for the specified string.

fava.core.file.next_key(basekey, keys)

Returns the next unused key for basekey in the supplied array.

The first try is basekey, followed by basekey-2, basekey-3, etc until a free one is found.

fava.core.file.save_entry_slice(entry, source_slice, sha256sum)

Save slice of the source file for an entry.

Parameters
  • entry – An entry.

  • source_slice – The lines that the entry should be replaced with.

  • sha256sum – The sha256sum of the current lines of the entry.

Returns

The sha256sum of the new lines of the entry.

Raises

FavaAPIException – If the file at path is not one of the source files.

fava.core.filters

Entry filters.

class fava.core.filters.AccountFilter(*args)

Filter by account.

The filter string can either a regular expression or a parent account.

set(value)

Set the filter.

Subclasses should check for validity of the value in this method.

class fava.core.filters.AdvancedFilter(*args)

Filter by tags and links and keys.

set(value)

Set the filter.

Subclasses should check for validity of the value in this method.

class fava.core.filters.EntryFilter(options, fava_options)

Filters a list of entries.

apply(entries)

Apply filter.

Parameters
  • entries – a list of entries.

  • options – an options_map.

Returns

A list of filtered entries.

set(value)

Set the filter.

Subclasses should check for validity of the value in this method.

class fava.core.filters.FilterSyntaxLexer

Lexer for Fava’s filter syntax.

ALL(token, _)
ANY(token, _)
KEY(token, value)
RULES = (('LINK', '\\^[A-Za-z0-9\\-_/.]+'), ('TAG', '\\#[A-Za-z0-9\\-_/.]+'), ('KEY', '[a-z][a-zA-Z0-9\\-_]+:'), ('ALL', 'all\\('), ('ANY', 'any\\('), ('STRING', '\\w[-\\w]*|"[^"]*"|\\\'[^\\\']*\\\''))
STRING(token, value)
TAG(token, value)
lex(data)

A generator yielding all tokens in a given line.

Parameters

data – A string, the line to lex.

Yields

All Tokens in the line.

regex = re.compile('(?P<LINK>\\^[A-Za-z0-9\\-_/.]+)|(?P<TAG>\\#[A-Za-z0-9\\-_/.]+)|(?P<KEY>[a-z][a-zA-Z0-9\\-_]+:)|(?P<ALL>all\\()|(?P<ANY>any\\()|(?P<STRING>\\w[-\\w]*|"[^"]*"|\\\'[^\\\']*\\\')')
tokens = ('ANY', 'ALL', 'KEY', 'LINK', 'STRING', 'TAG')
class fava.core.filters.FilterSyntaxParser
p_error(_)
p_expr(p)

expr : simple_expr

p_expr_all(p)

expr : ALL expr ‘)’

p_expr_and(p)

expr : expr expr %prec AND

p_expr_any(p)

expr : ANY expr ‘)’

p_expr_negated(p)

expr : ‘-‘ expr %prec UMINUS

p_expr_or(p)

expr : expr ‘,’ expr

p_expr_parentheses(p)

expr : ‘(‘ expr ‘)’

p_filter(p)

filter : expr

simple_expr : LINK

p_simple_expr_STRING(p)

simple_expr : STRING

p_simple_expr_TAG(p)

simple_expr : TAG

p_simple_expr_key(p)

simple_expr : KEY STRING

precedence = (('left', 'AND'), ('right', 'UMINUS'))
tokens = ('ANY', 'ALL', 'KEY', 'LINK', 'STRING', 'TAG')
class fava.core.filters.Match(search)

Match a string.

match
class fava.core.filters.TimeFilter(*args)

Filter by dates.

set(value)

Set the filter.

Subclasses should check for validity of the value in this method.

class fava.core.filters.Token(type_, value)

A token having a certain type and value.

The lexer attribute only exists since PLY writes to it in case of a parser error.

lexer
type
value
fava.core.filters.entry_account_predicate(entry, predicate)

Predicate for filtering by account.

Parameters
  • entry – An entry.

  • predicate – A predicate for account names.

Returns

True if predicate is True for any account of the entry.

fava.core.helpers

Exceptions and module base class.

exception fava.core.helpers.FavaAPIException(message)

Fava’s base exception class.

class fava.core.helpers.FavaModule(ledger)

Base class for the “modules” of FavaLedger.

load_file()

Gets called when the file has been (re)loaded.

exception fava.core.helpers.FilterException(filter_type, message)

Filter exception.

fava.core.ingest

Ingest helper functions.

class fava.core.ingest.FileImportInfo(importer_name, account, date, name)
class fava.core.ingest.FileImporters(name, basename, importers)
class fava.core.ingest.IngestError(source, message, entry)
class fava.core.ingest.IngestModule(ledger)

Exposes ingest functionality.

extract(filename, importer_name)

Extract entries from filename with the specified importer.

Parameters
  • filename – The full path to a file.

  • importer_name – The name of an importer that matched the file.

Returns

A list of new imported entries.

import_data()

Identify files and importers that can be imported.

Returns

A dict mapping directories to lists of FileImportInfo.

load_file()

Gets called when the file has been (re)loaded.

module_path

The path to the importer configuration.

fava.core.ingest.file_import_info(filename, importer)

Generate info about a file with an importer.

Return type

FileImportInfo

fava.core.inventory

Alternative implementation of Beancount’s Inventory.

class fava.core.inventory.CounterInventory

A lightweight inventory.

This is intended as a faster alternative to Beancount’s Inventory class. Due to not using a list, for inventories with a lot of different positions, inserting is much faster.

The keys should be tuples (currency, cost).

add(key, number)

Add a number to key.

add_amount(amount, cost=None)

Add an Amount to the inventory.

add_inventory(counter)

Add another CounterInventory.

add_position(pos)

Add a Position or Posting to the inventory.

is_empty()

Check if the inventory is empty.

reduce(reducer, *args)

Reduce inventory.

Note that this returns a simple CounterInventory with just currencies as keys.

fava.core.misc

Some miscellaneous reports.

class fava.core.misc.FavaError(source, message, entry)
class fava.core.misc.FavaMisc(ledger)

Provides access to some miscellaneous reports.

load_file()

Gets called when the file has been (re)loaded.

fava.core.misc.align(string, fava_options)

Align currencies in one column.

Parse custom entries for links.

They have the following format:

2016-04-01 custom “fava-sidebar-link” “2014” “/income_statement/?time=2014”

fava.core.misc.upcoming_events(events, max_delta)

Parse entries for upcoming events.

Parameters
  • events – A list of events.

  • max_delta – Number of days that should be considered.

Returns

A list of the Events in entries that are less than max_delta days away.

fava.core.number

Formatting numbers.

class fava.core.number.DecimalFormatModule(ledger)

Formatting numbers.

load_file()

Gets called when the file has been (re)loaded.

fava.core.query_shell

For using the Beancount shell from Fava.

class fava.core.query_shell.QueryShell(ledger)

A light wrapper around Beancount’s shell.

add_help()

Attach help functions for each of the parsed token handlers.

do_EOF(_)

Doesn’t do anything in Fava’s query shell.

do_exit(_)

Doesn’t do anything in Fava’s query shell.

do_quit(_)

Doesn’t do anything in Fava’s query shell.

execute_query(query, add_to_history=False)

Run a query.

Parameters

query – A query string.

Returns

A tuple (contents, types, rows) where either the first or the last two entries are None. If the query result is a table, it will be contained in types and rows, otherwise the result will be contained in contents (as a string).

static get_history(max_entries)

Get the most recently used shell commands (removing duplicates).

get_pager()

No real pager, just a wrapper that doesn’t close self.buffer.

load_file()

Gets called when the file has been (re)loaded.

noop(_)

Doesn’t do anything in Fava’s query shell.

on_Reload(_)

Doesn’t do anything in Fava’s query shell.

on_RunCustom(run_stmt)

Run a custom query.

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.

query_to_file(query_string, result_format)

Get query result as file.

Parameters
  • query_string – A string, the query to run.

  • result_format – The file format to save to.

Returns

A tuple (name, data), where name is either ‘query_result’ or the name of a custom query if the query string is ‘run name_of_query’. data contains the file contents.

Raises
  • FavaAPIException – If the result format is not supported or the

  • query failed.

fava.core.tree

Account balance trees.

class fava.core.tree.Tree(entries=None)

Account tree.

Parameters

entries – A list of entries to compute balances from.

ancestors(name)

Ancestors of an account.

Parameters

name – An account name.

Yields

The ancestors of the given account from the bottom up.

cap(options, unrealized_account)

Transfer Income and Expenses, add conversions and unrealized gains.

Parameters
  • options – The Beancount options.

  • unrealized_account – The name of the account to post unrealized gains to (as a subaccount of Equity).

get(name, insert=False)

Get an account.

Parameters
  • name – An account name.

  • insert – If True, insert the name into the tree if it does not exist.

Returns

The account of that name or an empty account if the account is not in the tree.

Return type

TreeNode

insert(name, balance)

Insert account with a balance.

Insert account and update its balance and the balances of its ancestors.

Parameters
  • name – An account name.

  • balance – The balance of the account.

net_profit(options, account_name)

Calculate the net profit.

Parameters
  • options – The Beancount options.

  • account_name – The name to use for the account containing the net profit.

class fava.core.tree.TreeNode(name)

A node in the account tree.

balance

The account balance.

Type

CounterInventory

balance_children

The cumulative account balance.

Type

CounterInventory

children

A list of TreeNode, its children.

has_txns

True if the account has any transactions.

Type

bool

name

Account name.

Type

str

serialise(end)

Serialise the account.

Parameters

end – A date to use for cost conversions.

fava.core.watcher

A simple file and folder watcher.

class fava.core.watcher.Watcher

A simple file and folder watcher.

For folders, only checks mtime of the folder and all subdirectories. So a file change won’t be noticed, but only new/deleted files.

check()

Check for changes.

Returns

True if there was a file change in one of the files or folders, False otherwise.

update(files, folders)

Update the folders/files to watch.

Parameters
  • files – A list of file paths.

  • folders – A list of paths to folders.