fava.core

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

class fava.core.FavaLedger(path)

Create an interface for a Beancount ledger.

Parameters:

path (str) – Path to the main Beancount file.

account_journal(filtered, account_name, conversion, *, with_children)

Journal for an account.

Parameters:
  • filtered (FilteredLedger) – The currently filtered ledger.

  • account_name (str) – An account name.

  • conversion (str | Conversion) – The conversion to use.

  • with_children (bool) – Whether to include postings of subaccounts of the account.

Returns:

Iterable[tuple[Directive, SimpleCounterInventory, SimpleCounterInventory]] – A generator of (entry, change, balance) tuples.

accounts

A AccountDict module - details about the accounts.

all_entries: list[Directive]

List of all (unfiltered) entries.

all_entries_by_type: EntriesByType

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

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:

bool – 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.

commodities

A CommoditiesModule instance.

commodity_pairs()

List pairs of commodities.

Returns:

list[tuple[str, str]] – 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 (str) – Hash of entry.

Returns:

tuple[Directive, dict[str, list[str]] | None, dict[str, list[str]] | None, str, str] – A tuple (entry, before, after, source_slice, sha256sum) of the (unique) entry with the given entry_hash. If the entry is a Balance or Transaction then before and after contain the balances before and after the entry of the affected accounts.

errors: list[BeancountError]

A list of all errors reported by Beancount.

extensions

A ExtensionModule instance.

fava_options: FavaOptions

A dict with all of Fava’s option values.

file

A FileModule instance.

format_decimal

A DecimalFormatModule instance.

get_entry(entry_hash)

Find an entry.

Parameters:

entry_hash (str) – Hash of the entry.

Returns:

Directive – The entry with the given hash.

Raises:

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

get_filtered(account=None, filter=None, time=None)

Filter the ledger.

Return type:

FilteredLedger

static group_entries_by_type()

Group entries by type.

Parameters:

entries (list[Directive]) – A list of entries to group.

Returns:

EntriesByType – A namedtuple containing the grouped lists of entries.

ingest

A IngestModule instance.

interval_balances(filtered, interval, account_name, *, accumulate=False)

Balances by interval.

Parameters:
  • filtered (FilteredLedger) – The currently filtered ledger.

  • interval (Interval) – An interval.

  • account_name (str) – An account name.

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

Returns:

tuple[list[Tree], list[DateRange]] – A pair of a list of Tree instances and the intervals.

join_path(*args)

Path relative to the directory of the ledger.

Return type:

Path

load_file()

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

Return type:

None

misc

A FavaMisc instance.

property mtime: int

The timestamp to the latest change of the underlying files.

options: BeancountOptions

The Beancount options map.

paths_to_watch()

Get paths to included files and document directories.

Returns:

tuple[list[Path], list[Path]] – A tuple (files, directories).

prices: FavaPriceMap

The price map.

query_shell

A QueryShell instance.

property root_accounts: tuple[str, str, str, str, str]

The five root accounts.

statement_path(entry_hash, metadata_key)

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

Return type:

str

watcher
class fava.core.FilteredLedger(ledger, account=None, filter=None, time=None)

Filtered Beancount ledger.

account_is_closed(account_name)

Check if the account is closed.

Parameters:

account_name (str) – An account name.

Returns:

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

date_range: DateRange | None
property end_date: date | None

The date to use for prices.

entries
interval_ranges(interval)

Yield date ranges corresponding to interval boundaries.

Return type:

Iterable[DateRange]

ledger
prices(base, quote)

List all prices.

Return type:

list[tuple[date, Decimal]]

property root_tree: Tree

A root tree.

property root_tree_closed: Tree

A root tree for the balance sheet.

fava.core.accounts

Account close date and metadata.

class fava.core.accounts.AccountData(close_date=None, meta=<factory>, uptodate_status=None, balance_string=None, last_entry=None)

Holds information about an account.

balance_string: str | None = None

Balance directive if this account has an uptodate status.

close_date: date | None = None

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

last_entry: LastEntry | None = None

The last entry of the account (unless it is a close Entry)

meta: Mapping[str, str | int | bool | Decimal | date | Amount]

The metadata of the Open entry of this account.

uptodate_status: str | None = None

Uptodate status. Is only computed if the account has a “fava-uptodate-indication” meta attribute.

class fava.core.accounts.AccountDict(ledger)

Account info dictionary.

EMPTY = AccountData(close_date=None, meta={}, uptodate_status=None, balance_string=None, last_entry=None)
all_balance_directives()

Balance directives for all accounts.

Return type:

str

load_file()

Run when the file has been (re)loaded.

Return type:

None

setdefault(key, _=None)

Get the account of the given name, insert one if it is missing.

Return type:

AccountData

class fava.core.accounts.LastEntry(date, entry_hash)

Date and hash of the last entry for an account.

date: date

The entry date.

entry_hash: str

The entry hash.

fava.core.accounts.balance_string(tree_node)

Balance directive for the given account for today.

Return type:

str

fava.core.accounts.get_last_entry(txn_postings)

Last entry.

Return type:

Directive | None

fava.core.accounts.uptodate_status(txn_postings)

Status of the last balance or transaction.

Parameters:

txn_postings (list[Directive | TransactionPosting]) – The TransactionPosting for the account.

Returns:

str | None – 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.

fava.core.attributes

Attributes for auto-completion.

class fava.core.attributes.AttributesModule(ledger)

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

load_file()

Run when the file has been (re)loaded.

Return type:

None

payee_accounts(payee)

Rank accounts for the given payee.

Return type:

list[str]

payee_transaction(payee)

Get the last transaction for a payee.

Return type:

Transaction | None

fava.core.attributes.get_active_years(entries, fye)

Return active years, with support for fiscal years.

Parameters:
Returns:

list[str] – A reverse sorted list of years or fiscal years that occur in the entries.

fava.core.budgets

Parsing and computing budgets.

class fava.core.budgets.Budget(account: str, date_start: datetime.date, period: Interval, number: Decimal, currency: str)

A budget entry.

fava.core.budgets.BudgetDict

A map of account names to lists of budget entries.

alias of Dict[str, List[Budget]]

class fava.core.budgets.BudgetError(source: Meta | None, message: str, entry: Directive | None)

Error with a budget.

class fava.core.budgets.BudgetModule(ledger)

Parses budget entries.

calculate(account, begin_date, end_date)

Calculate the budget for an account in an interval.

Return type:

dict[str, Decimal]

calculate_children(account, begin_date, end_date)

Calculate the budget for an account including its children.

Return type:

dict[str, Decimal]

load_file()

Run when the file has been (re)loaded.

Return type:

None

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

Calculate budget for an account.

Parameters:
  • budgets (Dict[str, List[Budget]]) – A list of Budget entries.

  • account (str) – An account name.

  • date_from (date) – Starting date.

  • date_to (date) – End date (exclusive).

Returns:

dict[str, Decimal] – A dictionary of currency to Decimal with the budget for the specified account and period.

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

Calculate budget for an account including budgets of its children.

Parameters:
  • budgets (Dict[str, List[Budget]]) – A list of Budget entries.

  • account (str) – An account name.

  • date_from (date) – Starting date.

  • date_to (date) – End date (exclusive).

Returns:

dict[str, Decimal] – 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 (list[Custom]) – the Custom entries to parse budgets from.

Returns:

tuple[Dict[str, List[Budget]], list[BudgetError]] – 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.

static can_plot_query(types)

Whether we can plot the given query.

Parameters:

types (list[tuple[str, type[Any]]]) – The list of types returned by the BQL query.

Return type:

bool

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

Render an account tree.

Return type:

SerialisedTreeNode

interval_totals(filtered, interval, accounts, conversion, *, invert=False)

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

Parameters:
  • filtered (FilteredLedger) – The filtered ledger.

  • interval (Interval) – An interval.

  • accounts (str | tuple[str, ...]) – A single account (str) or a tuple of accounts.

  • conversion (str | Conversion) – The conversion to use.

  • invert (bool) – invert all numbers.

Return type:

Iterable[DateAndBalanceWithBudget]

linechart(filtered, account_name, conversion)

Get the balance of an account as a line chart.

Parameters:
Returns:

Iterable[DateAndBalance] – 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(filtered, interval, conversion)

Compute net worth.

Parameters:
Returns:

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

query(types, rows)

Chart for a query.

Parameters:
Return type:

list[dict[str, date | str | SimpleCounterInventory]]

class fava.core.charts.DateAndBalance(date, balance)

Balance at a date.

balance: SimpleCounterInventory
date: date
class fava.core.charts.DateAndBalanceWithBudget(date, balance, account_balances, budgets)

Balance at a date with a budget.

account_balances: dict[str, SimpleCounterInventory]
balance: SimpleCounterInventory
budgets: dict[str, Decimal]
date: date
class fava.core.charts.FavaJSONProvider(app)

Use custom JSON encoder and decoder.

dumps(obj, **_kwargs)

Serialize data as JSON.

Parameters:
  • obj (Any) – The data to serialize.

  • kwargs – May be passed to the underlying JSON library.

Return type:

str

loads(s, **_kwargs)

Deserialize data as JSON.

Parameters:
  • s (str | bytes) – Text or UTF-8 bytes.

  • kwargs – May be passed to the underlying JSON library.

Return type:

Any

fava.core.charts.dumps(obj, **_kwargs)

Dump as a JSON string.

Return type:

str

fava.core.charts.loads(s)

Load a JSON string.

Return type:

Any

fava.core.commodities

Attributes for auto-completion.

class fava.core.commodities.CommoditiesModule(ledger)

Details about the currencies and commodities.

load_file()

Run when the file has been (re)loaded.

Return type:

None

name(commodity)

Get the name of a commodity (or the commodity itself if not set).

Return type:

str

fava.core.conversion

Commodity conversion helpers for Fava.

All functions in this module will be automatically added as template filters.

fava.core.conversion.AT_COST = <fava.core.conversion._AtCostConversion object>

Convert position to its total cost.

fava.core.conversion.AT_VALUE = <fava.core.conversion._AtValueConversion object>

Convert position to its market value.

class fava.core.conversion.Conversion

A conversion.

abstract apply(inventory, prices, date=None)

Apply the conversion to an inventory.

Return type:

SimpleCounterInventory

fava.core.conversion.UNITS = <fava.core.conversion._UnitsConversion object>

Convert position to its units.

fava.core.conversion.conversion_from_str(value)

Parse a conversion string.

Return type:

Conversion

fava.core.conversion.convert_position(pos, target_currency, prices, date=None)

Get the value of a Position in a particular currency.

Parameters:
  • pos (Position) – A Position.

  • target_currency (str) – The target currency to convert to.

  • prices (FavaPriceMap) – A FavaPriceMap

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

Returns:

Amount – An Amount, with value converted or if the conversion failed just the cost value (or the units if the position has no cost).

fava.core.conversion.cost_or_value(inventory, conversion, prices, date=None)

Get the cost or value of an inventory.

Return type:

SimpleCounterInventory

fava.core.conversion.get_cost(pos)

Return the total cost of a Position.

Return type:

Amount

fava.core.conversion.get_market_value(pos, prices, date=None)

Get the market value of a Position.

This differs from the convert.get_value function in Beancount by returning the cost value if no price can be found.

Parameters:
  • pos (Position) – A Position.

  • prices (FavaPriceMap) – A FavaPriceMap

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

Returns:

Amount – An Amount, with value converted or if the conversion failed just the cost value (or the units if the position has no cost).

fava.core.conversion.get_units(pos)

Return the units of a Position.

Return type:

Amount

fava.core.conversion.simple_units(inventory)

Get the units of an inventory.

Return type:

SimpleCounterInventory

fava.core.conversion.units(inventory)

Get the units of an inventory.

Return type:

SimpleCounterInventory

fava.core.documents

Document path related helpers.

fava.core.documents.filepath_in_document_folder(documents_folder, account, filename, ledger)

File path for a document in the folder for an account.

Parameters:
  • documents_folder (str) – The documents folder.

  • account (str) – The account to choose the subfolder for.

  • filename (str) – The filename of the document.

  • ledger (FavaLedger) – The FavaLedger.

Returns:

Path – The path that the document should be saved at.

fava.core.documents.is_document_or_import_file(filename, ledger)

Check whether the filename is a document or in an import directory.

Parameters:
  • filename (str) – The filename to check.

  • ledger (FavaLedger) – The FavaLedger.

Returns:

bool – Whether this is one of the documents or a path in an import dir.

fava.core.extensions

Fava extensions.

class fava.core.extensions.ExtensionDetails(name, report_title, has_js_module)

The information about an extension that is needed for the frontend.

has_js_module: bool
name: str
report_title: str | None
class fava.core.extensions.ExtensionModule(ledger)

Fava extensions.

after_delete_entry(entry)

Run all after_delete_entry hooks.

Return type:

None

after_entry_modified(entry, new_lines)

Run all after_entry_modified hooks.

Return type:

None

after_insert_entry(entry)

Run all after_insert_entry hooks.

Return type:

None

after_insert_metadata(entry, key, value)

Run all after_insert_metadata hooks.

Return type:

None

after_load_file()

Run all after_load_file hooks.

Return type:

None

after_write_source(path, source)

Run all after_write_source hooks.

Return type:

None

before_request()

Run all before_request hooks.

Return type:

None

property extension_details: list[ExtensionDetails]

Extension information to provide to the Frontend.

get_extension(name)

Get the extension with the given name.

Return type:

FavaExtensionBase | None

load_file()

Run when the file has been (re)loaded.

Return type:

None

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': {}}"
Return type:

dict[str, str | None]

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.FavaOptions(account_journal_include_children=True, auto_reload=False, collapse_pattern=<factory>, currency_column=61, conversion_currencies=(), default_file=None, default_page='income_statement/', fiscal_year_end=FiscalYearEnd(month=12, day=31), import_config=None, import_dirs=(), indent=2, insert_entry=<factory>, invert_income_liabilities_equity=False, language=None, locale=None, show_accounts_with_zero_balance=True, show_accounts_with_zero_transactions=True, show_closed_accounts=False, sidebar_show_queries=5, unrealized='Unrealized', upcoming_events=7, uptodate_indicator_grey_lookback_days=60, use_external_editor=False)

Options for Fava that can be set in the Beancount file.

account_journal_include_children: bool = True
auto_reload: bool = False
collapse_pattern: list[Pattern[str]]
conversion_currencies: tuple[str, ...] = ()
currency_column: int = 61
default_file: str | None = None
default_page: str = 'income_statement/'
fiscal_year_end: FiscalYearEnd = FiscalYearEnd(month=12, day=31)
import_config: str | None = None
import_dirs: tuple[str, ...] = ()
indent: int = 2
insert_entry: list[InsertEntryOption]
invert_income_liabilities_equity: bool = False
language: str | None = None
locale: str | None = None
show_accounts_with_zero_balance: bool = True
show_accounts_with_zero_transactions: bool = True
show_closed_accounts: bool = False
sidebar_show_queries: int = 5
unrealized: str = 'Unrealized'
upcoming_events: int = 7
uptodate_indicator_grey_lookback_days: int = 60
use_external_editor: bool = False
class fava.core.fava_options.InsertEntryOption(date, re, filename, lineno)

Insert option.

An option that determines where entries for matching accounts should be inserted.

date: date
filename: str
lineno: int
re: Pattern[str]
class fava.core.fava_options.OptionError(source: Meta | None, message: str, entry: Directive | None)

An error for one the Fava options.

fava.core.fava_options.parse_option_custom_entry(entry, options)

Parse a single custom fava-option entry and set option accordingly.

Return type:

None

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 (list[Custom]) – A list of Custom entries.

Returns:

tuple[FavaOptions, list[OptionError]] – 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.

exception fava.core.file.ExternallyChangedError(path)

The file changed externally.

class fava.core.file.FileModule(ledger)

Functions related to reading/writing to Beancount files.

delete_entry_slice(entry_hash, sha256sum)

Delete slice of the source file for an entry.

Parameters:
  • entry_hash (str) – Hash of an entry.

  • sha256sum (str) – The sha256sum of the current lines of the entry.

Raises:

FavaAPIError – If the entry is not found or the file changed.

Return type:

None

get_source(path)

Get source files.

Parameters:

path (Path) – The path of the file.

Returns:

tuple[str, str] – A string with the file contents and the sha256sum of the file.

Raises:

FavaAPIError – If the file at path is not one of the source files or it contains invalid unicode.

insert_entries(entries)

Insert entries.

Parameters:

entries (list[Directive]) – A list of entries.

Return type:

None

insert_metadata(entry_hash, basekey, value)

Insert metadata into a file at lineno.

Also, prevent duplicate keys.

Parameters:
  • entry_hash (str) – Hash of an entry.

  • basekey (str) – Key to insert metadata for.

  • value (str) – Metadate value to insert.

Return type:

None

render_entries(entries)

Return entries in Beancount format.

Only renders Balance and Transaction.

Parameters:

entries (list[Directive]) – A list of entries.

Yields:

The entries rendered in Beancount format.

Return type:

Iterable[Markup]

save_entry_slice(entry_hash, source_slice, sha256sum)

Save slice of the source file for an entry.

Parameters:
  • entry_hash (str) – Hash of an entry.

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

  • sha256sum (str) – The sha256sum of the current lines of the entry.

Returns:

str – The sha256sum of the new lines of the entry.

Raises:

FavaAPIError – If the entry is not found or the file changed.

set_source(path, source, sha256sum)

Write to source file.

Parameters:
  • path (Path) – The path of the file.

  • source (str) – A string with the file contents.

  • sha256sum (str) – Hash of the file.

Returns:

str – The sha256sum of the updated file.

Raises:

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

exception fava.core.file.InvalidUnicodeError(reason)

The source file contains invalid unicode.

exception fava.core.file.NonSourceFileError(path)

Trying to read a non-source file.

fava.core.file.delete_entry_slice(entry, sha256sum)

Delete slice of the source file for an entry.

Parameters:
  • entry (Directive) – An entry.

  • sha256sum (str) – The sha256sum of the current lines of the entry.

Raises:

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

Return type:

None

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

Lines of entry starting at lineno.

Parameters:
  • lines (list[str]) – A list of lines.

  • lineno (int) – The 0-based line-index to start at.

Return type:

list[str]

fava.core.file.find_insert_position(entry, insert_options, default_filename)

Find insert position for an entry.

Parameters:
  • entry (Directive) – An entry.

  • insert_options (list[InsertEntryOption]) – A list of InsertOption.

  • default_filename (str) – The default file to insert into if no option matches.

Returns:

tuple[str, int | None] – 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 (Directive) – An entry.

Returns:

tuple[str, str] – A string containing the lines of the entry and the sha256sum of these lines.

fava.core.file.insert_entry(entry, default_filename, insert_options, currency_column, indent)

Insert an entry.

Parameters:
  • entry (Directive) – An entry.

  • default_filename (str) – The default file to insert into if no option matches.

  • insert_options (list[InsertEntryOption]) – Insert options.

  • currency_column (int) – The column to align currencies at.

  • indent (int) – Number of indent spaces.

Returns:

tuple[Path, list[InsertEntryOption]] – A changed path and list of updated insert options.

fava.core.file.insert_metadata_in_file(path, lineno, indent, key, value)

Insert the specified metadata in the file below lineno.

Takes the whitespace in front of the line that lineno into account.

Return type:

None

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

Save slice of the source file for an entry.

Parameters:
  • entry (Directive) – An entry.

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

  • sha256sum (str) – The sha256sum of the current lines of the entry.

Returns:

str – The sha256sum of the new lines of the entry.

Raises:

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

fava.core.filters

Entry filters.

class fava.core.filters.AccountFilter(value)

Filter by account.

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

apply(entries)

Filter a list of directives.

Return type:

list[Directive]

class fava.core.filters.AdvancedFilter(value)

Filter by tags and links and keys.

apply(entries)

Filter a list of directives.

Return type:

list[Directive]

class fava.core.filters.EntryFilter

Filters a list of entries.

abstract apply(entries)

Filter a list of directives.

Return type:

list[Directive]

exception fava.core.filters.FilterError(filter_type, message)

Filter exception.

class fava.core.filters.FilterSyntaxLexer

Lexer for Fava’s filter syntax.

ALL(token, _)
Return type:

tuple[str, str]

ANY(token, _)
Return type:

tuple[str, str]

KEY(token, value)
Return type:

tuple[str, str]

Return type:

tuple[str, str]

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)
Return type:

tuple[str, str]

TAG(token, value)
Return type:

tuple[str, str]

lex(data)

A generator yielding all tokens in a given line.

Parameters:

data (str) – A string, the line to lex.

Yields:

All Tokens in the line.

Return type:

Iterable[Token]

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(_)
Return type:

None

p_expr(p)

expr : simple_expr

Return type:

None

p_expr_all(p)

expr : ALL expr ‘)’

Return type:

None

p_expr_and(p)

expr : expr expr %prec AND

Return type:

None

p_expr_any(p)

expr : ANY expr ‘)’

Return type:

None

p_expr_negated(p)

expr : ‘-’ expr %prec UMINUS

Return type:

None

p_expr_or(p)

expr : expr ‘,’ expr

Return type:

None

p_expr_parentheses(p)

expr : ‘(’ expr ‘)’

Return type:

None

p_filter(p)

filter : expr

Return type:

None

simple_expr : LINK

Return type:

None

p_simple_expr_STRING(p)

simple_expr : STRING

Return type:

None

p_simple_expr_TAG(p)

simple_expr : TAG

Return type:

None

p_simple_expr_key(p)

simple_expr : KEY STRING

Return type:

None

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

Match a string.

match: Callable[[str], bool]
class fava.core.filters.TimeFilter(options, fava_options, value)

Filter by dates.

apply(entries)

Filter a list of directives.

Return type:

list[Directive]

date_range
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.group_entries

Entries grouped by type.

class fava.core.group_entries.EntriesByType(Balance: list[abc.Balance], Close: list[abc.Close], Commodity: list[abc.Commodity], Custom: list[abc.Custom], Document: list[abc.Document], Event: list[abc.Event], Note: list[abc.Note], Open: list[abc.Open], Pad: list[abc.Pad], Price: list[abc.Price], Query: list[abc.Query], Transaction: list[abc.Transaction])

Entries grouped by type.

class fava.core.group_entries.TransactionPosting(transaction: abc.Transaction, posting: abc.Posting)

Pair of a transaction and a posting.

fava.core.group_entries.group_entries_by_account(entries)

Group entries by account.

Parameters:

entries (list[Directive]) – A list of entries.

Returns:

dict[str, list[Directive | TransactionPosting]] – A dict mapping account names to their entries.

fava.core.group_entries.group_entries_by_type(entries)

Group entries by type.

Parameters:

entries (list[Directive]) – A list of entries to group.

Returns:

EntriesByType – A namedtuple containing the grouped lists of entries.

fava.core.ingest

Ingest helper functions.

class fava.core.ingest.FileImportInfo(importer_name, account, date, name)

Info about one file/importer combination.

account: str
date: date
importer_name: str
name: str
class fava.core.ingest.FileImporters(name, basename, importers)

Importers for a file.

basename: str
importers: list[FileImportInfo]
name: str
class fava.core.ingest.IngestError(source: Meta | None, message: str, entry: Directive | None)

An error with one of the importers.

class fava.core.ingest.IngestModule(ledger)

Exposes ingest functionality.

extract(filename, importer_name)

Extract entries from filename with the specified importer.

Parameters:
  • filename (str) – The full path to a file.

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

Returns:

list[Directive] – A list of new imported entries.

import_data()

Identify files and importers that can be imported.

Returns:

list[FileImporters] – A list of FileImportInfo.

load_file()

Run when the file has been (re)loaded.

Return type:

None

property module_path: Path | None

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.ingest.filepath_in_primary_imports_folder(filename, ledger)

File path for a document to upload to the primary import folder.

Parameters:
  • filename (str) – The filename of the document.

  • ledger (FavaLedger) – The FavaLedger.

Returns:

Path – The path that the document should be saved at.

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.

Return type:

None

add_amount(amount, cost=None)

Add an Amount to the inventory.

Return type:

None

add_inventory(counter)

Add another CounterInventory.

Return type:

None

add_position(pos)

Add a Position or Posting to the inventory.

Return type:

None

is_empty()

Check if the inventory is empty.

Return type:

bool

reduce(reducer, *args, **_kwargs)

Reduce inventory.

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

Return type:

SimpleCounterInventory

to_strings()

Print as a list of strings (e.g. for snapshot tests).

Return type:

list[str]

class fava.core.inventory.SimpleCounterInventory

A simple inventory mapping just strings to numbers.

add(key, number)

Add a number to key.

Return type:

None

is_empty()

Check if the inventory is empty.

Return type:

bool

reduce(reducer, *args, **_kwargs)

Reduce inventory.

Return type:

SimpleCounterInventory

fava.core.misc

Some miscellaneous reports.

class fava.core.misc.FavaError(source: Meta | None, message: str, entry: Directive | None)

Generic Fava-specific error.

class fava.core.misc.FavaMisc(ledger)

Provides access to some miscellaneous reports.

load_file()

Run when the file has been (re)loaded.

Return type:

None

User-chosen links to show in the sidebar.

upcoming_events: list[Event]

Upcoming events in the next few days.

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

Align currencies in one column.

Return type:

str

Parse custom entries for links.

They have the following format:

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

Return type:

list[tuple[str, str]]

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

Parse entries for upcoming events.

Parameters:
  • events (list[Event]) – A list of events.

  • max_delta (int) – Number of days that should be considered.

Returns:

list[Event] – A list of the Events in entries that are less than max_delta days away.

fava.core.module_base

Base class for the “modules” of FavaLedger.

class fava.core.module_base.FavaModule(ledger)

Base class for the “modules” of FavaLedger.

load_file()

Run when the file has been (re)loaded.

Return type:

None

fava.core.number

Formatting numbers.

class fava.core.number.DecimalFormatModule(ledger)

Formatting numbers.

load_file()

Run when the file has been (re)loaded.

Return type:

None

fava.core.number.get_locale_format(locale, precision)

Obtain formatting pattern for the given locale and precision.

Parameters:
  • locale (Locale | None) – An optional locale.

  • precision (int) – The precision.

Returns:

Callable[[Decimal], str] – A function that renders Decimals to strings as desired.

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.

Return type:

None

do_EOF(_)

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

Return type:

None

do_exit(_)

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

Return type:

None

do_quit(_)

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

Return type:

None

execute_query(entries, query)

Run a query.

Parameters:
  • entries (list[Directive]) – The entries to run the query on.

  • query (str) – A query string.

Returns:

Any – 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).

get_pager()

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

Return type:

Any

load_file()

Run when the file has been (re)loaded.

Return type:

None

noop(_)

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

Return type:

None

on_Reload(_)

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

Return type:

None

on_RunCustom(run_stmt)

Run a custom query.

Return type:

Any

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: :rtype: None

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(entries, query_string, result_format)

Get query result as file.

Parameters:
  • entries (list[Directive]) – The entries to run the query on.

  • query_string (str) – A string, the query to run.

  • result_format (str) – The file format to save to.

Returns:

Any – 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:
  • FavaAPIError – If the result format is not supported or the

  • query failed.

fava.core.tree

Account balance trees.

class fava.core.tree.SerialisedTreeNode(account, balance, balance_children, children, has_txns)

A serialised TreeNode.

account: str
balance: SimpleCounterInventory
balance_children: SimpleCounterInventory
children: list[SerialisedTreeNode]
has_txns: bool
class fava.core.tree.SerialisedTreeNodeWithCost(account, balance, balance_children, children, has_txns, cost, cost_children)

A serialised TreeNode with cost.

cost: SimpleCounterInventory
cost_children: SimpleCounterInventory
class fava.core.tree.Tree(entries=None, create_accounts=None)

Account tree.

Parameters:
property accounts: list[str]

The accounts in this tree.

ancestors(name)

Ancestors of an account.

Parameters:

name (str) – An account name.

Yields:

The ancestors of the given account from the bottom up.

Return type:

Iterable[TreeNode]

cap(options, unrealized_account)

Transfer Income and Expenses, add conversions and unrealized gains.

Parameters:
  • options (BeancountOptions) – The Beancount options.

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

Return type:

None

get(name, *, insert=False)

Get an account.

Parameters:
  • name (str) – An account name.

  • insert (bool) – 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:
Return type:

None

net_profit(options, account_name)

Calculate the net profit.

Parameters:
  • options (BeancountOptions) – The Beancount options.

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

Return type:

TreeNode

class fava.core.tree.TreeNode(name)

A node in the account tree.

balance

The account balance.

balance_children

The cumulative account balance.

children: list[TreeNode]

A list of TreeNode, its children.

has_txns

Whether the account has any transactions.

name: str

Account name.

serialise(conversion, prices, end, *, with_cost=False)

Serialise the account.

Parameters:
  • conversion (str | Conversion) – The conversion to use.

  • prices (FavaPriceMap) – The price map to use.

  • end (date | None) – A date to use for cost conversions.

  • with_cost (bool) – Additionally convert to cost.

Return type:

SerialisedTreeNode | SerialisedTreeNodeWithCost

serialise_with_context()

Serialise, getting all parameters from Flask context.

Return type:

SerialisedTreeNode | SerialisedTreeNodeWithCost

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.

update(files, folders)

Update the folders/files to watch.

Return type:

None

class fava.core.watcher.WatcherBase

ABC for Fava ledger file watchers.

check()

Check for changes.

Returns:

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

last_checked: int

Timestamp of the latest change noticed by the file watcher.

last_notified: int

Timestamp of the latest change that the watcher was notified of.

notify(path)

Notify the watcher of a change to a path.

Return type:

None

abstract update(files, folders)

Update the folders/files to watch.

Parameters:
Return type:

None

class fava.core.watcher.WatchfilesWatcher

A file and folder watcher using the watchfiles library.

update(files, folders)

Update the folders/files to watch.

Return type:

None