fava.core

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

exception fava.core.EntryNotFoundForHashError(entry_hash)

Entry not found for hash.

class fava.core.FavaLedger(path, *, poll_watcher=False)

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.

Yields:

Tuples of (entry, change, balance).

Return type:

Iterable[tuple[Directive, SimpleCounterInventory, SimpleCounterInventory]]

accounts

A AccountDict module - details about the accounts.

all_entries: Sequence[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:

Sequence[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, Mapping[str, Sequence[str]] | None, Mapping[str, Sequence[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.

property errors: Sequence[BeancountError]

The errors that the Beancount loading plus Fava module errors.

extensions

A ExtensionModule instance.

fava_options: FavaOptions

A dict with all of Fava’s option values.

fava_options_errors: Sequence[BeancountError]

A list of all errors from parsing the custom options.

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:

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

get_filtered
static group_entries_by_type()

Group entries by type.

Parameters:

entries (Sequence[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[Sequence[Tree], Sequence[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_errors: Sequence[BeancountError]

A list of all errors reported by Beancount.

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[Sequence[Path], Sequence[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.

The entry that we look up should contain a path to a document (absolute or relative to the filename of the entry) or just its basename. We go through all documents and match on the full path or if one of the documents with a matching account has a matching file basename.

Parameters:
  • entry_hash (str) – Hash of the entry containing the path in its metadata.

  • metadata_key (str) – The key that the path should be in.

Returns:

str – The filename of the matching document entry.

Raises:
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:

Sequence[tuple[date, Decimal]]

property root_tree: Tree

A root tree.

property root_tree_closed: Tree

A root tree for the balance sheet.

exception fava.core.StatementMetadataInvalidError(key)

Statement metadata not found or invalid.

exception fava.core.StatementNotFoundError

Statement not found.

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 (Sequence[Directive | TransactionPosting]) – The TransactionPosting for the account.

Returns:

Optional[Literal['green', 'yellow', 'red']] – 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:

Sequence[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:

Mapping[str, Decimal]

calculate_children(account, begin_date, end_date)

Calculate the budget for an account including its children.

Return type:

Mapping[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:

Mapping[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:

Mapping[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 (Sequence[Custom]) – the Custom entries to parse budgets from.

Returns:

tuple[dict[str, list[Budget]], Sequence[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.

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.

Yields:

The balances and budgets for the intervals.

Return type:

Iterable[DateAndBalanceWithBudget]

linechart(filtered, account_name, conversion)

Get the balance of an account as a line chart.

Parameters:
Yields:

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.

Return type:

Iterable[DateAndBalance]

net_worth(filtered, interval, conversion)

Compute net worth.

Parameters:
Yields:

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

Return type:

Iterable[DateAndBalance]

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: Mapping[str, SimpleCounterInventory]
balance: SimpleCounterInventory
budgets: Mapping[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.

exception fava.core.documents.NotADocumentsFolderError(folder)

Not a documents folder.

exception fava.core.documents.NotAValidAccountError(account)

Not a valid account.

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: Sequence[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.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>, conversion_currencies=(), currency_column=61, 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: Sequence[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: Sequence[InsertEntryOption]
invert_income_liabilities_equity: bool = False
language: str | None = None
locale: str | None = None
set_collapse_pattern(value)

Set the collapse_pattern option.

Return type:

None

set_default_file(value, filename)

Set the default_file option.

Return type:

None

set_fiscal_year_end(value)

Set the fiscal_year_end option.

Return type:

None

set_insert_entry(value, date, filename, lineno)

Set the insert_entry option.

Return type:

None

set_language(value)

Set the locale option.

Return type:

None

set_locale(value)

Set the locale option.

Return type:

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]
exception fava.core.fava_options.InvalidFiscalYearEndOptionError(value)
exception fava.core.fava_options.MissingOptionError
exception fava.core.fava_options.NotARegularExpressionError(value)
exception fava.core.fava_options.NotAStringOptionError(key)
class fava.core.fava_options.OptionError(source: Meta | None, message: str, entry: Directive | None)

An error for one the Fava options.

exception fava.core.fava_options.UnknownLocaleOptionError(value)
exception fava.core.fava_options.UnknownOptionError(key)
exception fava.core.fava_options.UnsupportedLanguageOptionError(value)
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 (Sequence[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:
insert_entries(entries)

Insert entries.

Parameters:

entries (Sequence[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 (Sequence[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:
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:

ExternallyChangedError – If the file was changed externally.

Return type:

None

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

Lines of entry starting at lineno.

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

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

Return type:

Sequence[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 (Sequence[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 (Sequence[InsertEntryOption]) – Insert options.

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

  • indent (int) – Number of indent spaces.

Returns:

tuple[Path, Sequence[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:

ExternallyChangedError – If the file was changed externally.

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:

Sequence[Directive]

class fava.core.filters.AdvancedFilter(value)

Filter by tags and links and keys.

apply(entries)

Filter a list of directives.

Return type:

Sequence[Directive]

class fava.core.filters.EntryFilter

Filters a list of entries.

abstract apply(entries)

Filter a list of directives.

Return type:

Sequence[Directive]

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

Filter exception.

exception fava.core.filters.FilterIllegalCharError(char)

Filter illegal char error.

exception fava.core.filters.FilterParseError

Filter parse error.

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]

CMP_OP(token, value)
Return type:

tuple[str, str]

EQ_OP(token, value)
Return type:

tuple[str, str]

KEY(token, value)
Return type:

tuple[str, str]

Return type:

tuple[str, str]

NUMBER(token, value)
Return type:

tuple[str, Decimal]

RULES = (('LINK', '\\^[A-Za-z0-9\\-_/.]+'), ('TAG', '\\#[A-Za-z0-9\\-_/.]+'), ('ALL', 'all\\('), ('ANY', 'any\\('), ('KEY', '[a-z][a-zA-Z0-9\\-_]+(?=\\s*(:|=|>=|<=|<|>))'), ('EQ_OP', ':'), ('CMP_OP', '(=|>=|<=|<|>)'), ('NUMBER', '\\d*\\.?\\d+'), ('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<ALL>all\\()|(?P<ANY>any\\()|(?P<KEY>[a-z][a-zA-Z0-9\\-_]+(?=\\s*(:|=|>=|<=|<|>)))|(?P<EQ_OP>:)|(?P<CMP_OP>(=|>=|<=|<|>))|(?P<NUMBER>)
tokens = ('ANY', 'ALL', 'CMP_OP', 'EQ_OP', 'KEY', 'LINK', 'NUMBER', '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)
Return type:

None

simple_exprKEY EQ_OP STRING
KEY CMP_OP NUMBER
p_simple_expr_units(p)

simple_expr : CMP_OP NUMBER

Return type:

None

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

Match a string.

match: Callable[[str], bool]
class fava.core.filters.MatchAmount(op, value)

Matches an amount.

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

Filter by dates.

apply(entries)

Filter a list of directives.

Return type:

Sequence[Directive]

date_range
exception fava.core.filters.TimeFilterParseError(value)

Time filter parse error.

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: Sequence[abc.Balance], Close: Sequence[abc.Close], Commodity: Sequence[abc.Commodity], Custom: Sequence[abc.Custom], Document: Sequence[abc.Document], Event: Sequence[abc.Event], Note: Sequence[abc.Note], Open: Sequence[abc.Open], Pad: Sequence[abc.Pad], Price: Sequence[abc.Price], Query: Sequence[abc.Query], Transaction: Sequence[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 (Sequence[Directive]) – A list of entries.

Returns:

Mapping[str, Sequence[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 (Sequence[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
exception fava.core.ingest.ImportConfigLoadError(message)

Error on loading the import config.

exception fava.core.ingest.ImporterExtractError

Error calling extract for importer.

exception fava.core.ingest.ImporterMethodCallError

Error calling one of the importer methods.

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.

exception fava.core.ingest.MissingImporterConfigError

Missing import-config option.

exception fava.core.ingest.MissingImporterDirsError

You need to set at least one imports-dir.

fava.core.ingest.extract_from_file(importer, path, existing_entries)

Import entries from a document.

Parameters:
Returns:

list[Directive] – The list of imported entries.

fava.core.ingest.file_import_info(path, 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.ingest.find_imports(config, directory)

Pair files and matching importers.

Yields:

For each file in directory, a pair of its filename and the matching importers.

Return type:

Iterable[FileImporters]

fava.core.ingest.get_cached_file(path)

Get a cached FileMemo.

This checks the file’s mtime before getting it from the Cache. In addition to using the beangulp cache.

Return type:

FileMemo

fava.core.ingest.get_name(importer)

Get the name of an importer.

Return type:

str

fava.core.ingest.importer_identify(importer, path)

Get the name of an importer.

Return type:

bool

fava.core.ingest.load_import_config(module_path)

Load the given import config and extract importers and hooks.

Parameters:

module_path (Path) – Path to the import config.

Returns:

tuple[Mapping[str, BeanImporterProtocol | Importer], Sequence[Callable[[list[tuple[str, list[Directive]]], Sequence[Directive]], list[tuple[str, list[Directive]]]]]] – A pair of the importers (by name) and the list of hooks.

fava.core.ingest.walk_dir(directory)

Walk through all files in dir.

Ignores common dot-directories like .git, .cache. .venv, see IGNORE_DIRS.

Parameters:

directory (Path) – The directory to start in.

Yields:

All full paths under directory, ignoring some directories.

Return type:

Iterable[Path]

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.

property errors: Sequence[FavaError]

An error if no operating currency is set.

load_file()

Run when the file has been (re)loaded.

Return type:

None

User-chosen links to show in the sidebar.

upcoming_events: Sequence[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:

Sequence[tuple[str, str]]

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

Parse entries for upcoming events.

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

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

Returns:

Sequence[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

Query result types.

class fava.core.query.AmountColumn(name, dtype='Amount')

An amount query column.

dtype: str = 'Amount'
class fava.core.query.BaseColumn(name, dtype)

A query column.

dtype: str
name: str
static serialise(val)

Serialiseable version of the column value.

Return type:

bool | int | str | date | Decimal | Position | SimpleCounterInventory

class fava.core.query.BoolColumn(name, dtype='bool')

A boolean query column.

dtype: str = 'bool'
class fava.core.query.DateColumn(name, dtype='date')

A date query column.

dtype: str = 'date'
class fava.core.query.DecimalColumn(name, dtype='Decimal')

A Decimal query column.

dtype: str = 'Decimal'
class fava.core.query.IntColumn(name, dtype='int')

A int query column.

dtype: str = 'int'
class fava.core.query.InventoryColumn(name, dtype='Inventory')

A str query column.

dtype: str = 'Inventory'
static serialise(val)

Serialise an inventory.

Return type:

SimpleCounterInventory | None

class fava.core.query.ObjectColumn(name, dtype='object')

An object query column.

dtype: str = 'object'
static serialise(val)

Serialise an object of unknown type to a string.

Return type:

str

class fava.core.query.PositionColumn(name, dtype='Position')

A Position query column.

dtype: str = 'Position'
class fava.core.query.QueryResultTable(types, rows, t='table')

Table query result.

rows: list[tuple[bool | int | str | date | Decimal | Position | SimpleCounterInventory, ...]]
t: Literal['table'] = 'table'
types: list[BaseColumn]
class fava.core.query.QueryResultText(contents, t='string')

Text query result.

contents: str
t: Literal['string'] = 'string'
class fava.core.query.SetColumn(name, dtype='set')

A set query column.

dtype: str = 'set'
class fava.core.query.StrColumn(name, dtype='str')

A str query column.

dtype: str = 'str'

fava.core.query_shell

For using the Beancount shell from Fava.

class fava.core.query_shell.FavaBQLShell(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

do_run(arg)

Run a custom query.

Return type:

Cursor | 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_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: Cursor

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.

outfile: StringIO
run(entries, query)

Run a query, capturing output as string or returning the result.

Return type:

Cursor | str

exception fava.core.query_shell.FavaShellError(message)

An error in the Fava BQL shell, will be turned into a string.

exception fava.core.query_shell.NonExportableQueryError

Only queries that return a table can be printed to a file.

exception fava.core.query_shell.QueryCompilationError(err)

Query compilation error.

exception fava.core.query_shell.QueryNotFoundError(name)

Query ‘{name}’ not found.

exception fava.core.query_shell.QueryParseError(err)

Query parse error.

class fava.core.query_shell.QueryShell(ledger)

A Fava module to run BQL queries.

execute_query_serialised(entries, query)

Run a query and returns its serialised result.

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

  • query (str) – A query string.

Returns:

QueryResultTable | QueryResultText – Either a table or a text result (depending on the query).

Raises:

FavaAPIError – If the query response is an error.

query_to_file(entries, query_string, result_format)

Get query result as file.

Parameters:
  • entries (Sequence[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:

tuple[str, BytesIO] – 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.

exception fava.core.query_shell.TooManyRunArgsError(args)

Too many args to run: ‘{args}’.

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: Sequence[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:
  • entries (Iterable[Directive] | None) – A list of entries to compute balances from.

  • create_accounts (list[str] | None) – A list of accounts that the tree should contain.

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