Development

If you want to try out the current master-version of Fava and see what we are working on, check out the online dev-demo (updated every midnight UTC).

Setting up a development environment

If you want to hack on Fava or run the latest development version, make sure you have Python 3 (with pip) and Node.js (with npm) installed. Then this will get you up and running:

git clone https://github.com/beancount/fava.git
cd fava
# using a virtual environment is optional, but recommended
virtualenv -p python3 venv
. venv/bin/activate
make
pip install --editable .

You can start Fava in the virtual environment as usual by running fava.

You can run the tests with make test (requires tox). After any changes to the Javascript code, you will need to re-run make.

If you need a newer version of Beancount than the latest released one, you can install from source like so (more details here):

pip install hg+https://bitbucket.org/blais/beancount#egg=beancount

Contributions are very welcome, just open a PR on GitHub.

Fava is released under the MIT License.

API Documentation

Note

There’s no stability guarantee as this is just for internal purposes currently.

fava.application

Fava’s main WSGI application.

when using Fava’s WSGI app, make sure to set app.config['BEANCOUNT_FILES']. To start a simple server:

from fava.application import app
app.config['BEANCOUNT_FILES'] = ['/path/to/file.beancount']
app.run('localhost', 5000)
fava.application.app

An instance of flask.Flask, this is Fava’s WSGI application.

fava.application.account(name, subreport='journal')

The account report.

fava.application.document()

Download a document.

fava.application.download_journal()

Download a Journal file.

fava.application.download_query(result_format)

Download a query result.

fava.application.fava_api_exception(error)

Handle API errors.

fava.application.get_locale()

Get locale.

Returns:The locale that should be used for Babel. If not given as an option to Fava, guess from browser.
fava.application.help_page(page_slug='_index')

Fava’s included documentation.

fava.application.holdings_by(aggregation_key)

The holdings report.

fava.application.index()

Redirect to the Income Statement (of the given or first file).

fava.application.jump()

Redirect back to the referer, replacing some parameters.

This is useful for sidebar links, e.g. a link /jump?time=year would set the time filter to year on the current page.

When accessing /jump?param1=abc from /example/page?param1=123&param2=456, this view should redirect to /example/page?param1=abc&param2=456.

fava.application.report(report_name)

Endpoint for most reports.

fava.application.statement()

Download a statement file.

fava.application.static_url(**values)

Return a static url with an mtime query string for cache busting.

fava.application.template_context()

Inject variables into the template context.

fava.application.url_for(endpoint, **values)

A wrapper around flask.url_for that uses a cache.

fava.application.url_for_current(**kwargs)

URL for current page with updated request args.

fava.application.url_for_source(**kwargs)

URL to source file (possibly link to external editor).

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.ExtensionModule(ledger)

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

load_file()

Get’s called when the file has been (re)loaded.

run_hook(event, *args)
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()

Get’s 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)
account

Alias for field number 0

currency

Alias for field number 4

date_start

Alias for field number 1

number

Alias for field number 3

period

Alias for field number 2

class fava.core.budgets.BudgetError(source, message, entry)
entry

Alias for field number 2

message

Alias for field number 1

source

Alias for field number 0

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()

Get’s 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.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)
date

Alias for field number 0

filename

Alias for field number 2

lineno

Alias for field number 3

re

Alias for field number 1

class fava.core.fava_options.OptionError(source, message, entry)
entry

Alias for field number 2

message

Alias for field number 1

source

Alias for field number 0

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 Balances and Transactions.

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

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

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

Filters a list of entries.

apply(entries, options)

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+|"[^"]*"|\\\'[^\\\']*\\\''))
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+|"[^"]*"|\\\'[^\\\']*\\\')')
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

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()

Get’s 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.IngestError(source, message, entry)
entry

Alias for field number 2

message

Alias for field number 1

source

Alias for field number 0

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.

static file_account(filename, importer)

Account for the given file.

Parameters:
  • filename – The full path to a file.
  • importer – An importer that matched the file.
Returns:

The account name or the exception message if one occurs.

static file_date(filename, importer)

Date for the given file.

Parameters:
  • filename – The full path to a file.
  • importer – An importer that matched the file.
Returns:

The date or the exception message if one occurs.

identify_directory(directory)

Identify files and importers for a given directory.

Parameters:directory – The directory to search (relative to Beancount file).
Returns:Tuples of filenames and lists of matching importers.
load_file()

Get’s called when the file has been (re)loaded.

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)
entry

Alias for field number 2

message

Alias for field number 1

source

Alias for field number 0

class fava.core.misc.FavaMisc(ledger)

Provides access to some miscellaneous reports.

load_file()

Get’s 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.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()

Get’s 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.
class fava.core.tree.TreeNode(name)

A node in the account tree.

balance

CounterInventory – The account balance.

balance_children

CounterInventory – The cumulative account balance.

children

A list of TreeNode, its children.

has_txns

bool – True if the account has any transactions.

name

str – Account name.

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.

fava.template_filters

Template filters for Fava.

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

fava.template_filters.balance_children(account)

Compute the total balance of an account.

fava.template_filters.basename(file_path)

Return the basename of a filepath.

fava.template_filters.cost(inventory)

Get the cost of an inventory.

fava.template_filters.cost_or_value(inventory, date=None)

Get the cost or value of an inventory.

fava.template_filters.flag_to_type(flag)

Names for entry flags.

fava.template_filters.format_amount(amount)

Format an amount to string using the DisplayContext.

fava.template_filters.format_currency(value, currency=None, show_if_zero=False)

Format a value using the derived precision for a specified currency.

fava.template_filters.format_date(date)

Format a date according to the current interval.

fava.template_filters.format_errormsg(message)

Match account names in error messages and insert HTML links for them.

fava.template_filters.get_market_value(pos, price_map, 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 – A Position.
  • price_map – A dict of prices, as built by prices.build_price_map().
  • date – A datetime.date instance to evaluate the value at, or None.
Returns:

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

fava.template_filters.get_or_create(account, account_name)

Get or create a child account.

fava.template_filters.hash_entry(entry)

Hash an entry.

fava.template_filters.remove_keys(_dict, keys)

Remove keys from a dictionary.

fava.template_filters.should_show(account)

Determine whether the account should be shown.

fava.template_filters.units(inventory)

Get the units of an inventory.

fava.util

Some small utility functions.

fava.util.filter_api_changed(record)

Filter out LogRecords for requests that poll for changes.

fava.util.listify(func)

Decorator to make generator function return a list.

fava.util.pairwise(iterable)

s -> (s0,s1), (s1,s2), (s2, s3), …

fava.util.resource_path(relative_path)

Get absolute path to resource.

fava.util.send_file_inline(filename)

Send a file inline, including the original filename.

Ref: http://test.greenbytes.de/tech/tc2231/.

fava.util.setup_logging()

Setup logging for Fava.

fava.util.simple_wsgi(_, start_response)

A simple wsgi app that always returns an empty response.

fava.util.slugify(string)

Slugify a string.

Parameters:string – A string.
Returns:A ‘slug’ of the string suitable for URLs. Retains non-ascii characters.
fava.util.timefunc(func)

Decorator to time function for debugging.

fava.util.date

Date-related functionality.

Note

Date ranges are always tuples (start, end) from the (inclusive) start date to the (exclusive) end date.

class fava.util.date.Interval

The possible intervals.

DAY = 'day'
MONTH = 'month'
QUARTER = 'quarter'
WEEK = 'week'
YEAR = 'year'
fava.util.date.days_in_daterange(start_date, end_date)

Yield a datetime for every day in the specified interval.

Parameters:
  • start_date – A start date.
  • end_date – An end date (exclusive).
Returns:

An iterator yielding all days between start_date to end_date.

fava.util.date.get_next_interval(date: datetime.date, interval: fava.util.date.Interval)

Get the start date of the next interval.

Parameters:
  • date – A date.
  • interval – An interval.
Returns:

The start date of the next interval after date.

fava.util.date.interval_ends(first, last, interval: fava.util.date.Interval)

List intervals.

Parameters:
  • first – A datetime.date.
  • last – A datetime.date.
  • interval – An interval.
Yields:

Dates corresponding to the starts/ends of intervals between first and last.

fava.util.date.number_of_days_in_period(interval, date)

Number of days in the surrounding interval.

Parameters:
  • interval – An interval.
  • date – A date.
Returns:

A number, the number of days surrounding the given date in the interval.

fava.util.date.parse_date(string)

Parse a date.

Example of supported formats:

  • 2010-03-15, 2010-03, 2010
  • 2010-W01, 2010-Q3

Ranges of dates can be expressed in the following forms:

  • start - end
  • start to end

where start and end look like one of the above examples

Parameters:string – A date(range) in our custom format.
Returns:A tuple (start, end) of dates.
fava.util.date.substitute(string)

Replace variables referring to the current day.

Parameters:string – A string, possibly containing variables for today.
Returns:A string, where variables referring to the current day, like ‘year’ or ‘week’ have been replaced by the corresponding string understood by parse_date(). Can compute addition and subtraction.

fava.util.excel

Writing query results to CSV and spreadsheet documents.

fava.util.excel.to_csv(types, rows)

Save result to CSV.

Parameters:
  • types – query result_types.
  • rows – query result_rows.
Returns:

The (binary) file contents.

fava.util.excel.to_excel(types, rows, result_format, query_string)

Save result to spreadsheet document.

Parameters:
  • types – query result_types.
  • rows – query result_rows.
  • result_format – One of ‘xls’, ‘xlsx’, or ‘ods’.
  • query_string – The query string (is written to the document).
Returns:

The (binary) file contents.