beancount.reports

Routines to produce various reports, either to HTML or to text.

beancount.reports.balance_reports

Report classes for all reports that display ending balances of accounts.

class beancount.reports.balance_reports.BalanceSheetReport(*args, formatter=None, css_id=None, css_class=None)

Print out a balance sheet.

default_format = 'html'
names = ['balsheet']
render_htmldiv(entries, errors, options_map, file, fwdfunc=<function BalanceSheetReport.render_real_htmldiv>)
render_real_html(real_root, price_map, price_date, options_map, file)

Wrap an htmldiv into our standard HTML template.

Parameters
  • real_root – An instance of RealAccount.

  • price_map – A price database.

  • price_date – A date for evaluating prices.

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

  • file – A file object to write the output to.

render_real_htmldiv(real_root, price_map, price_date, options_map, file)
class beancount.reports.balance_reports.BalancesReport(*args, formatter=None, css_id=None, css_class=None)

Print out the trial balance of accounts matching an expression.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = 'text'
names = ['balances', 'bal', 'trial']
render_htmldiv(entries, errors, options_map, file, fwdfunc=<function BalancesReport.render_real_htmldiv>)
render_real_html(real_root, price_map, price_date, options_map, file)

Wrap an htmldiv into our standard HTML template.

Parameters
  • real_root – An instance of RealAccount.

  • price_map – A price database.

  • price_date – A date for evaluating prices.

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

  • file – A file object to write the output to.

render_real_htmldiv(real_root, price_map, price_date, options_map, file)
render_real_text(real_root, price_map, price_date, options_map, file)
render_text(entries, errors, options_map, file, fwdfunc=<function BalancesReport.render_real_text>)
class beancount.reports.balance_reports.IncomeStatementReport(*args, formatter=None, css_id=None, css_class=None)

Print out an income statement.

default_format = 'html'
names = ['income']
render_htmldiv(entries, errors, options_map, file, fwdfunc=<function IncomeStatementReport.render_real_htmldiv>)
render_real_html(real_root, price_map, price_date, options_map, file)

Wrap an htmldiv into our standard HTML template.

Parameters
  • real_root – An instance of RealAccount.

  • price_map – A price database.

  • price_date – A date for evaluating prices.

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

  • file – A file object to write the output to.

render_real_htmldiv(real_root, price_map, price_date, options_map, file)

beancount.reports.base

Base class for all reports classes.

Each report class should be able to render a filtered list of entries to a variety of formats. Each report has a name, some command-line options, and supports some subset of formats.

class beancount.reports.base.HTMLReport(*args, formatter=None, css_id=None, css_class=None)

A mixin for reports that support forwarding html to htmldiv implementation.

default_format = 'html'
render_html(entries, errors, options_map, file)
class beancount.reports.base.RealizationMeta

A metaclass for reports that render a realization.

The main use of this metaclass is to allow us to create report classes with render_real_*() methods that accept a RealAccount instance as the basis for producing a report.

RealAccount can be expensive to build, and may be pre-computed and kept around to generate the various reports related to a particular filter of a subset of transactions, and it would be inconvenient to have to recalculate it every time we need to produce a report. In particular, this is the case for the web interface: the user selects a particular subset of transactions to view, and can then click to the various reports related to this subset of transactions. This is why this is useful.

The classes generated with this metaclass respond to the same interface as the regular report classes, so that if invoked from the command-line, it will automatically build the realization from the given set of entries. This metaclass looks at the class’ existing render_real_*() methods and generate the corresponding render_*() methods automatically.

render_real_html(real_root, price_map, price_date, options_map, file)

Wrap an htmldiv into our standard HTML template.

Parameters
  • real_root – An instance of RealAccount.

  • price_map – A price database.

  • price_date – A date for evaluating prices.

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

  • file – A file object to write the output to.

class beancount.reports.base.Report(args, parser)

Base class for all reports.

names

A list of strings, the various names of this report. The first name is taken to be the authoritative name of the report; the rest are considered aliases.

parser

The parser for the command’s arguments. This is used to raise errors.

args

An object that contains the values of this command’s parsed arguments.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = None
classmethod from_args(argv=None, **kwds)

A convenience method used to create an instance from arguments.

This creates an instance of the report with default arguments. This is a convenience that may be used for tests. Our actual script uses subparsers and invokes add_args() and creates an appropriate instance directly.

Parameters
  • argv – A list of strings, command-line arguments to use to construct tbe report.

  • kwds – A dict of other keyword arguments to pass to the report’s constructor.

Returns

A new instace of the report.

classmethod get_supported_formats()

Enumerates the list of supported formats, by inspecting methods of this object.

Returns

A list of strings, such as [‘html’, ‘text’].

names = None
render(entries, errors, options_map, output_format=None, file=None)

Render a report of filtered entries to any format.

This function dispatches to a specific method.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

  • output_format – A string, the name of the format. I fnot specified, use the default format.

  • file – The file to write the output to.

Returns

If no ‘file’ is provided, return the contents of the report as a string.

Raises

ReportError – If the requested format is not supported.

exception beancount.reports.base.ReportError

Error that occurred during report generation.

class beancount.reports.base.TableReport(*args, formatter=None, css_id=None, css_class=None)

A base class for reports that supports automatic conversions from Table.

default_format = 'text'
generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

render_csv(entries, errors, options_map, file)
render_htmldiv(entries, errors, options_map, file)
render_text(entries, errors, options_map, file)
beancount.reports.base.get_html_template()

Returns our vanilla HTML template for embedding an HTML div.

Returns

{title}: for the title of the page. {body}: for the body, where the div goes.

Return type

A string, with a formatting style placeholders

beancount.reports.context

Produce a rendering of the account balances just before and after a particular entry is applied.

beancount.reports.context.render_entry_context(entries, options_map, entry)

Render the context before and after a particular transaction is applied.

Parameters
  • entries – A list of directives.

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

  • entry – The entry instance which should be rendered. (Note that this object is expected to be in the set of entries, not just structurally equal.)

Returns

A multiline string of text, which consists of the context before the transaction is applied, the transaction itself, and the context after it is applied. You can just print that, it is in form that is intended to be consumed by the user.

beancount.reports.context.render_file_context(entries, options_map, filename, lineno)

Render the context before and after a particular transaction is applied.

Parameters
  • entries – A list of directives.

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

  • filename – A string, the name of the file from which the transaction was parsed.

  • lineno – An integer, the line number in the file the transaction was parsed from.

Returns

A multiline string of text, which consists of the context before the transaction is applied, the transaction itself, and the context after it is applied. You can just print that, it is in form that is intended to be consumed by the user.

beancount.reports.convert_reports

Format converter reports.

This module contains reports that can convert an input file into other formats, such as Ledger.

class beancount.reports.convert_reports.HLedgerPrinter(dcontext=None)

Multi-method for printing directives in HLedger format.

Open(entry, oss)
Posting(posting, entry, oss)
Transaction(entry, oss)
class beancount.reports.convert_reports.HLedgerReport(args, parser)

Print out the entries in a format that can be parsed by HLedger.

default_format = 'hledger'
names = ['hledger']
render_hledger(entries, errors, options_map, file)
class beancount.reports.convert_reports.LedgerPrinter(dcontext=None)

Multi-method for printing directives in Ledger format.

Balance(entry, oss)
Close(entry, oss)
Commodity(entry, oss)
Custom(entry, oss)
Document(entry, oss)
Event(entry, oss)
Note(entry, oss)
Open(entry, oss)
Pad(entry, oss)
Posting(posting, entry, oss)
Price(entry, oss)
Query(entry, oss)
Transaction(entry, oss)
class beancount.reports.convert_reports.LedgerReport(args, parser)

Print out the entries in a format that can be parsed by Ledger.

default_format = 'ledger'
names = ['ledger']
render_ledger(entries, errors, options_map, file)
beancount.reports.convert_reports.postings_by_type(entry)

Split up the postings by simple, at-cost, at-price.

Parameters

entry – An instance of Transaction.

Returns

A tuple of simple postings, postings with price conversions, postings held at cost.

beancount.reports.convert_reports.quote(match)

Add quotes around a re.MatchObject.

Parameters

match – A MatchObject from the re module.

Returns

A quoted string of the match contents.

beancount.reports.convert_reports.quote_currency(string)

Quote all the currencies with numbers from the given string.

Parameters

string – A string of text.

Returns

A string of text, with the commodity expressions surrounded with quotes.

beancount.reports.convert_reports.split_currency_conversions(entry)

If the transcation has a mix of conversion at cost and a currency conversion, split the transction into two transactions: one that applies the currency conversion in the same account, and one that uses the other currency without conversion.

This is required because Ledger does not appear to be able to grok a transaction like this one:

2014-11-02 * “Buy some stock with foreign currency funds”

Assets:CA:Investment:HOOL 5 HOOL {520.0 USD} Expenses:Commissions 9.95 USD Assets:CA:Investment:Cash -2939.46 CAD @ 0.8879 USD

HISTORICAL NOTE: Adding a price directive on the first posting above makes Ledger accept the transaction. So we will not split the transaction here now. However, since Ledger’s treatment of this type of conflict is subject to revision (See http://bugs.ledger-cli.org/show_bug.cgi?id=630), we will keep this code around, it might become useful eventually. See https://groups.google.com/d/msg/ledger-cli/35hA0Dvhom0/WX8gY_5kHy0J for details of the discussion.

Parameters

entry – An instance of Transaction.

Returns

A pair of

converted: boolean, true if a conversion was made. entries: A list of the original entry if converted was False,

or a list of the split converted entries if True.

beancount.reports.export_reports

Reports to Export to third-party portfolio sites.

class beancount.reports.export_reports.ExportEntry(symbol, cost_currency, number, cost_number, mutual_fund, memo, holdings)
class beancount.reports.export_reports.ExportPortfolioReport(*args, formatter=None, css_id=None, css_class=None)

Holdings lists that can be exported to external portfolio management software.

EXPORT_FORMAT = '{atype} {0.number:10.2f} {0.symbol:16} {cost_number:10.2f} {0.cost_currency:16} {0.memo}\n'
HOLDING_FORMAT = ' Holding: {h.account:48} {h.number:10.2f} {h.currency:12} {cost_number:10.2f} {cost_currency:12}\n'
PREFIX = 'OFXHEADER:100\nDATA:OFXSGML\nVERSION:102\nSECURITY:NONE\nENCODING:USASCII\nCHARSET:1252\nCOMPRESSION:NONE\nOLDFILEUID:NONE\nNEWFILEUID:NONE\n\n'
SECURITY = '\n<{infotype}>\n <SECINFO>\n <SECID>\n <UNIQUEID>{uniqueid}\n <UNIQUEIDTYPE>TICKER\n </SECID>\n <SECNAME>{secname}\n <TICKER>{ticker}\n </SECINFO>\n</{infotype}>\n'
TEMPLATE = '\n<OFX>\n <SIGNONMSGSRSV1>\n <SONRS>\n <STATUS>\n <CODE>0\n <SEVERITY>INFO\n </STATUS>\n <DTSERVER>{dtserver}\n <LANGUAGE>ENG\n </SONRS>\n </SIGNONMSGSRSV1>\n <INVSTMTMSGSRSV1>\n <INVSTMTTRNRS>\n <TRNUID>1001\n <STATUS>\n <CODE>0\n <SEVERITY>INFO\n </STATUS>\n <INVSTMTRS>\n <DTASOF>{dtasof}\n <CURDEF>USD\n <INVACCTFROM>\n <BROKERID>{broker}\n <ACCTID>{account}\n </INVACCTFROM>\n <INVTRANLIST>\n <DTSTART>{dtstart}\n <DTEND>{dtend}\n {invtranlist}\n </INVTRANLIST>\n </INVSTMTRS>\n </INVSTMTTRNRS>\n </INVSTMTMSGSRSV1>\n <SECLISTMSGSRSV1>\n <SECLIST>\n {seclist}\n </SECLIST>\n </SECLISTMSGSRSV1>\n</OFX>\n'
TRANSACTION = '\n<{txntype}>\n <INVBUY>\n <INVTRAN>\n <FITID>{fitid}\n <DTTRADE>{dttrade}\n <MEMO>{memo}\n </INVTRAN>\n <SECID>\n <UNIQUEID>{uniqueid}\n <UNIQUEIDTYPE>TICKER\n </SECID>\n <UNITS>{units}\n <UNITPRICE>{unitprice}\n <COMMISSION>{fee}\n <TOTAL>{total}\n <SUBACCTSEC>CASH\n <SUBACCTFUND>CASH\n </INVBUY>\n <BUYTYPE>{buytype}\n</{txntype}>\n'
classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = 'ofx'
names = ['export_holdings', 'export_portfolio', 'pfexport', 'exportpf']
render_csv(entries, unused_errors, options_map, file)
render_ofx(entries, unused_errors, options_map, file)
beancount.reports.export_reports.classify_holdings_for_export(holdings_list, commodities_map)

Figure out what to do for example with each holding.

Parameters
  • holdings_list – A list of Holding instances to be exported.

  • commodities_map – A dict of commodity to Commodity instances.

Returns

action_holdings: A list of (symbol, holding) for each holding. ‘Symbol’

is the ticker to use for export, and may be “CASH” or “IGNORE” for holdings to be converted or ignored.

Return type

A pair of

beancount.reports.export_reports.export_holdings(entries, options_map, promiscuous, aggregate_by_commodity=False)

Compute a list of holdings to export.

Holdings that are converted to cash equivalents will receive a currency of “CASH:<currency>” where <currency> is the converted cash currency.

Parameters
  • entries – A list of directives.

  • options_map – A dict of options as provided by the parser.

  • promiscuous – A boolean, true if we should output a promiscuious memo.

  • aggregate_by_commodity – A boolean, true if we should group the holdings by account.

Returns

A pair of

exported: A list of ExportEntry tuples, one for each exported position. converted: A list of ExportEntry tuples, one for each converted position.

These will contain multiple holdings.

holdings_ignored: A list of Holding instances that were ignored, either

because they were explicitly marked to be ignored, or because we could not convert them to a money vehicle matching the holding’s cost-currency.

beancount.reports.export_reports.get_money_instruments(commodities_map)

Get the money-market stand-ins for cash positions.

Parameters

commodities_map – A map of currency to their corresponding Commodity directives.

Returns

A dict of quote currency to the ticker symbol that stands for it, e.g. {‘USD’: ‘VMMXX’}.

beancount.reports.export_reports.get_symbol(sources, prefer='google')

Filter a source specification to some corresponding ticker.

Parameters

source – A comma-separated list of sources as a string, such as “google/NASDAQ:AAPL,yahoo/AAPL”.

Returns

The symbol string.

Raises

ValueError – If the sources does not contain a ticker for the google source.

beancount.reports.export_reports.is_mutual_fund(ticker)

Return true if the GFinanc ticker is for a mutual fund.

Parameters

ticker – A string, the symbol for GFinance.

Returns

A boolean, true for mutual funds.

beancount.reports.export_reports.render_ofx_date(dtime)

Render a datetime to the OFX format.

Parameters

dtime – A datetime.datetime instance.

Returns

A string, rendered to milliseconds.

beancount.reports.gviz

Support for creating Google gviz timeline charts.

beancount.reports.gviz.gviz_timeline(time_array, data_array_map, css_id='chart')

Create a HTML rendering of the given arrays.

Parameters
  • time_array – A sequence of datetime objects.

  • data_array_map – A dict or list of items of name to sequence of data points.

  • css_id – A string, the CSS id attribute of the target node.

Returns

Javascript code for rendering the chart. (It’s up to you to insert the a div with the correct CSS id in your accompanying HTML page.)

beancount.reports.holdings_reports

Generate reports no holdings.

class beancount.reports.holdings_reports.CashReport(*args, formatter=None, css_id=None, css_class=None)

The list of cash holdings (defined as currency = cost-currency).

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['cash']
class beancount.reports.holdings_reports.HoldingsReport(*rest, **kwds)

The full list of holdings for Asset and Liabilities accounts.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

aggregations = {'account': {'aggregation_key': <function HoldingsReport.<lambda>>}, 'commodity': {'aggregation_key': <function HoldingsReport.<lambda>>}, 'currency': {'aggregation_key': <function HoldingsReport.<lambda>>}, 'root-account': {'aggregation_key': <function HoldingsReport.<lambda>>, 'sort_key': <function HoldingsReport.<lambda>>}}
generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['holdings']
render_beancount(entries, errors, options_map, file)
class beancount.reports.holdings_reports.NetWorthReport(*args, formatter=None, css_id=None, css_class=None)

Generate a table of total net worth for each operating currency.

generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['networth', 'equity']
beancount.reports.holdings_reports.get_assets_holdings(entries, options_map, currency=None)

Return holdings for all assets and liabilities.

Parameters
  • entries – A list of directives.

  • options_map – A dict of parsed options.

  • currency – If specified, a string, the target currency to convert all holding values to.

Returns

A list of Holding instances and a price-map.

beancount.reports.holdings_reports.get_holdings_entries(entries, options_map)

Summarizes the entries to list of entries representing the final holdings..

This list includes the latest prices entries as well. This can be used to load a full snapshot of holdings without including the entire history. This is a way of summarizing a balance sheet in a way that filters away history.

Parameters
  • entries – A list of directives.

  • options_map – A dict of parsed options.

Returns

A string, the entries to print out.

beancount.reports.holdings_reports.load_from_csv(fileobj)

Load a list of holdings from a CSV file.

Parameters

fileobj – A file object.

Yields

Instances of Holding, as read from the file.

beancount.reports.holdings_reports.report_holdings(currency, relative, entries, options_map, aggregation_key=None, sort_key=None)

Generate a detailed list of all holdings.

Parameters
  • currency – A string, a currency to convert to. If left to None, no conversion is carried out.

  • relative – A boolean, true if we should reduce this to a relative value.

  • entries – A list of directives.

  • options_map – A dict of parsed options.

  • aggregation_key – A callable use to generate aggregations.

  • sort_key – A function to use to sort the holdings, if specified.

Returns

A Table instance.

beancount.reports.html_formatter

Base class for HTML formatters.

This object encapsulates the rendering of various objects to HTML. You may, and should, derive and override from this object in order to provide links within a web interface.

class beancount.reports.html_formatter.HTMLFormatter(dcontext)

A trivial formatter object that can be used to format strings as themselves. This mainly defines an interface to implement.

render_account(account_name)

Render an account name.

Parameters

account_name – A string, the name of the account to render.

Returns

A string of HTML to be spliced inside an HTML template.

render_amount(amount)

Render an amount.

Parameters

amount – An Amount instance.

Returns

A string of HTML to be spliced inside a table cell.

render_commodity(base_quote)

Render a commodity (base currency / quote currency).

This is only used when we want the commodity to link to its prices.

Parameters

commodity – A pair of strings, the base and quote currency names.

Returns

A string of HTML to be spliced inside an HTML template.

render_context(entry)

Render a reference to context around a transaction (maybe as an HTML link).

Parameters

entry – A directive.

Returns

A string of HTML to be spliced inside an HTML template.

render_doc(filename)

Render a document path.

Parameters

filename – A string, the filename for the document.

Returns

A string of HTML to be spliced inside an HTML template.

render_event_type(event)

Render an event type.

Parameters

event – A string, the name of the even type.

Returns

A string of HTML to be spliced inside an HTML template.

render_inventory(inv)

Render an inventory.

You can use this opportunity to convert the inventory to units or cost or whatever.

Parameters

inv – An Inventory instance.

Returns

A string of HTML to be spliced inside a table cell.

Render a transaction link (maybe as an HTML link).

Parameters

link – A string, the name of the link to render.

Returns

A string of HTML to be spliced inside an HTML template.

render_number(number, currency)

Render a number for a currency using the formatter’s display context.

Parameters
  • number – A Decimal instance, the number to be rendered.

  • currency – A string, the commodity the number represent.

Returns

A string, the formatted number to render.

render_source(meta)

Render a reference to the source file.

Parameters

meta – A metadata dict object.

Returns

A string of HTML to be spliced inside an HTML template.

beancount.reports.journal_html

HTML rendering routines for serving a lists of postings/entries.

class beancount.reports.journal_html.Row(entry, leg_postings, rowtype, extra_class, flag, description, links, amount_str, balance_str)
beancount.reports.journal_html.html_entries_table(oss, txn_postings, formatter, render_postings=True)

Render a list of entries into an HTML table, with no running balance.

This is appropriate for rendering tables of entries for postings with multiple accounts, whereby computing the running balances makes little sense.

(This function returns nothing, it write to oss as a side-effect.)

Parameters
  • oss – A file object to write the output to.

  • txn_postings – A list of Posting or directive instances.

  • formatter – An instance of HTMLFormatter, to be render accounts, inventories, links and docs.

  • render_postings – A boolean; if true, render the postings as rows under the main transaction row.

beancount.reports.journal_html.html_entries_table_with_balance(oss, txn_postings, formatter, render_postings=True)

Render a list of entries into an HTML table, with a running balance.

(This function returns nothing, it write to oss as a side-effect.)

Parameters
  • oss – A file object to write the output to.

  • txn_postings – A list of Posting or directive instances.

  • formatter – An instance of HTMLFormatter, to be render accounts, inventories, links and docs.

  • render_postings – A boolean; if true, render the postings as rows under the main transaction row.

beancount.reports.journal_html.iterate_html_postings(txn_postings, formatter)

Iterate through the list of transactions with rendered HTML strings for each cell.

This pre-renders all the data for each row to HTML. This is reused by the entries table rendering routines.

Parameters
  • txn_postings – A list of TxnPosting or directive instances.

  • formatter – An instance of HTMLFormatter, to be render accounts, inventories, links and docs.

Yields

Instances of Row tuples. See above.

Render Transaction links to HTML.

Parameters

links – A list of set of strings, transaction “links” to be rendered.

Returns

A string, a snippet of HTML to be rendering somewhere.

beancount.reports.journal_reports

Report classes for all reports that display ending journals of accounts.

class beancount.reports.journal_reports.ConversionsReport(*args, formatter=None, css_id=None, css_class=None)

Print out a report of all conversions.

names = ['conversions']
render_htmldiv(entries, errors, options_map, file)
class beancount.reports.journal_reports.DocumentsReport(*args, formatter=None, css_id=None, css_class=None)

Print out a report of documents.

names = ['documents']
render_htmldiv(entries, errors, options_map, file)
class beancount.reports.journal_reports.JournalReport(*args, formatter=None, css_id=None, css_class=None)

Print out an account register/journal.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = 'text'
default_width = 80
get_postings(real_root)

Return the postings corresponding to the account filter option.

Parameters

real_root – A RealAccount node for the root of all accounts.

Returns

A list of posting or directive instances.

names = ['journal', 'register', 'account']
render_csv(entries, errors, options_map, file, fwdfunc=<function JournalReport.render_real_csv>)
render_htmldiv(entries, errors, options_map, file, fwdfunc=<function JournalReport.render_real_htmldiv>)
render_real_csv(real_root, price_map, price_date, options_map, file)
render_real_html(real_root, price_map, price_date, options_map, file)

Wrap an htmldiv into our standard HTML template.

Parameters
  • real_root – An instance of RealAccount.

  • price_map – A price database.

  • price_date – A date for evaluating prices.

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

  • file – A file object to write the output to.

render_real_htmldiv(real_root, price_map, price_date, options_map, file)
render_real_text(real_root, price_map, price_date, options_map, file)
render_text(entries, errors, options_map, file, fwdfunc=<function JournalReport.render_real_text>)
test_args = ['--width=80']

beancount.reports.journal_text

Text rendering routines for serving a lists of postings/entries.

class beancount.reports.journal_text.AmountColumnSizer(prefix)

A class that computes minimal sizes for columns of numbers and their currencies.

get_format(precision)

Return a format string for the column of numbers.

Parameters

precision – An integer, the number of digits to render after the period.

Returns

A new-style Python format string, with PREFIX_number and PREFIX_currency named fields.

get_generic_format(precision)

Return a generic format string for rendering as wide as required. This can be used to render an empty string in-lieu of a number.

Parameters

precision – An integer, the number of digits to render after the period.

Returns

A new-style Python format string, with PREFIX_number and PREFIX_currency named fields.

get_number_width()

Return the width of the integer part of the max number.

Returns

An integer, the number of digits required to render the integral part.

update(number, currency)

Update the sizer with the given number and currency.

Parameters
  • number – A Decimal instance.

  • currency – A string, the currency to render for it.

beancount.reports.journal_text.get_entry_text_description(entry)

Return the text of a description.

Parameters

entry – A directive, of any type.

Returns

A string to use for the filling the description field in text reports.

beancount.reports.journal_text.render_posting(posting, number_format)

Render a posting compactly, for text report rendering.

Parameters

posting – An instance of Posting.

Returns

A string, the rendered posting.

beancount.reports.journal_text.size_and_render_amounts(postings, at_cost, render_balance)

Iterate through postings and compute sizers and render amounts.

Parameters
  • postings – A list of Posting or directive instances.

  • at_cost – A boolean, if true, render the cost value, not the actual.

  • render_balance – A boolean, if true, renders a running balance column.

beancount.reports.journal_text.text_entries_table(oss, postings, width, at_cost, render_balance, precision, verbosity, output_format)

Render a table of postings or directives with an accumulated balance.

This function has three verbosity modes for rendering: 1. COMPACT: no separating line, no postings 2. NORMAL: a separating line between entries, no postings 3. VERBOSE: renders all the postings in addition to normal.

The output is written to the ‘oss’ file object. Nothing is returned.

Parameters
  • oss – A file object to write the output to.

  • postings – A list of Posting or directive instances.

  • width – An integer, the width to render the table to.

  • at_cost – A boolean, if true, render the cost value, not the actual.

  • render_balance – A boolean, if true, renders a running balance column.

  • precision – An integer, the number of digits to render after the period.

  • verbosity – An integer, the verbosity level. See COMPACT, NORMAL, VERBOSE, etc.

  • output_format – A string, either ‘text’ or ‘csv’ for the chosen output format. This routine’s inner loop calculations are complex enough it gets reused by both formats.

Raises

ValueError – If the width is insufficient to render the description.

beancount.reports.misc_reports

Miscellaneous report classes.

class beancount.reports.misc_reports.AccountsReport(args, parser)

Print out the list of all accounts.

default_format = 'beancount'
names = ['accounts']
render_beancount(entries, errors, options_map, file)
class beancount.reports.misc_reports.ActivityReport(*args, formatter=None, css_id=None, css_class=None)

Render the last or recent update activity.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = 'text'
names = ['activity', 'updated']
render_htmldiv(entries, errors, options_map, file, fwdfunc=<function ActivityReport.render_real_htmldiv>)
render_real_html(real_root, price_map, price_date, options_map, file)

Wrap an htmldiv into our standard HTML template.

Parameters
  • real_root – An instance of RealAccount.

  • price_map – A price database.

  • price_date – A date for evaluating prices.

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

  • file – A file object to write the output to.

render_real_htmldiv(real_root, price_map, price_date, options_map, file)
render_real_text(real_root, price_map, price_date, options_map, file)
render_text(entries, errors, options_map, file, fwdfunc=<function ActivityReport.render_real_text>)
class beancount.reports.misc_reports.CurrentEventsReport(*args, formatter=None, css_id=None, css_class=None)

Produce a table of the current values of all event types.

generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['current_events', 'latest_events']
class beancount.reports.misc_reports.ErrorReport(*args, formatter=None, css_id=None, css_class=None)

Report the errors.

default_format = 'text'
names = ['errors']
render_htmldiv(entries, errors, options_map, file)
render_text(entries, errors, options_map, file)
class beancount.reports.misc_reports.EventsReport(*args, formatter=None, css_id=None, css_class=None)

Produce a table of all the values of a particular event.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['events']
class beancount.reports.misc_reports.NoopReport(args, parser)

Report nothing.

default_format = 'text'
names = ['check', 'validate']
render_text(entries, errors, options_map, file)
class beancount.reports.misc_reports.PrintReport(args, parser)

Print out the entries.

default_format = 'beancount'
names = ['print']
render_beancount(entries, errors, options_map, file)
class beancount.reports.misc_reports.StatsDirectivesReport(*args, formatter=None, css_id=None, css_class=None)

Render statistics on each directive type, the number of entries by type.

generate_table(entries, _, __)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['stats-types', 'stats-directives', 'stats-entries']
class beancount.reports.misc_reports.StatsPostingsReport(*args, formatter=None, css_id=None, css_class=None)

Render the number of postings for each account.

generate_table(entries, _, __)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['stats-postings']

beancount.reports.price_reports

Miscellaneous report classes.

class beancount.reports.price_reports.CommoditiesReport(*args, formatter=None, css_id=None, css_class=None)

Print out a list of commodities.

default_format = 'text'
generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['commodities']
class beancount.reports.price_reports.CommodityLifetimes(*args, formatter=None, css_id=None, css_class=None)

Print out a list of lifetimes of each commodity.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = 'text'
names = ['lifetimes']
render_text(entries, errors, options_map, file)
class beancount.reports.price_reports.CommodityPricesReport(*args, formatter=None, css_id=None, css_class=None)

Print all the prices for a particular commodity.

classmethod add_args(parser)

Add arguments to parse for this report.

Parameters

parser – An instance of argparse.ArgumentParser.

default_format = 'text'
generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

get_date_rates(entries)
names = ['prices']
render_htmldiv(entries, errors, options_map, file)
class beancount.reports.price_reports.PriceDBReport(args, parser)

Print out the normalized price entries from the price db. Normalized means that we print prices in the most common (base, quote) order. This can be used to rebuild a prices database without having to share the entire ledger file.

Only the forward prices are printed; which (base, quote) pair is selected is selected based on the most common occurrence between (base, quote) and (quote, base). This is done in the price map.

default_format = 'beancount'
names = ['pricedb', 'pricesdb', 'prices_db']
render_beancount(entries, errors, options_map, file)
class beancount.reports.price_reports.PricesReport(args, parser)

Print out the unnormalized price entries that we input. Unnormalized means that we may render both (base,quote) and (quote,base). This can be used to rebuild a prices database without having to share the entire ledger file.

Note: this type of report should be removed once we have filtering on directive type, this is simply the ‘print’ report with type:price. Maybe rename the ‘pricedb’ report to just ‘prices’ for simplicity’s sake.

default_format = 'beancount'
names = ['all_prices']
render_beancount(entries, errors, options_map, file)
class beancount.reports.price_reports.TickerReport(*args, formatter=None, css_id=None, css_class=None)

Print a parseable mapping of (base, quote, ticker, name) for all commodities.

generate_table(entries, errors, options_map)

Render the report to a Table instance.

Parameters
  • entries – A list of directives to render.

  • errors – A list of errors that occurred during processing.

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

Returns

An instance of Table, that will get converted to another format.

names = ['tickers', 'symbols']

beancount.reports.report

Produce various custom implemented reports.

class beancount.reports.report.ListFormatsAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

An argparse action that prints all supported formats (for each report).

format_order = {'beancount': 99, 'csv': 4, 'html': 2, 'htmldiv': 3, 'text': 1}
format_order_last = 100
class beancount.reports.report.ListReportsAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

An argparse action that just prints the list of reports and exits.

beancount.reports.report.get_all_reports()

Return all report classes.

Returns

A list of all available report classes.

beancount.reports.report.get_list_report_string(only_report=None)

Return a formatted string for the list of supported reports.

Parameters

only_report – A string, the name of a single report to produce the help for. If not specified, list all the available reports.

Returns

A help string, or None, if ‘only_report’ was provided and is not a valid report name.

beancount.reports.report.main()

beancount.reports.table

Table rendering.

class beancount.reports.table.Table(columns, header, body)
beancount.reports.table.attribute_to_title(fieldname)

Convert programming id into readable field name.

Parameters

fieldname – A string, a programming ids, such as ‘book_value’.

Returns

A readable string, such as ‘Book Value.’

beancount.reports.table.compute_table_widths(rows)

Compute the max character widths of a list of rows.

Parameters

rows – A list of rows, which are sequences of strings.

Returns

A list of integers, the maximum widths required to render the columns of this table.

Raises

IndexError – If the rows are of different lengths.

beancount.reports.table.create_table(rows, field_spec=None)

Convert a list of tuples to an table report object.

Parameters
  • rows – A list of tuples.

  • field_spec – A list of strings, or a list of (FIELDNAME-OR-INDEX, HEADER, FORMATTER-FUNCTION) triplets, that selects a subset of the fields is to be rendered as well as their ordering. If this is a dict, the values are functions to call on the fields to render them. If a function is set to None, we will just call str() on the field.

Returns

A Table instance.

beancount.reports.table.render_table(table_, output, output_format, css_id=None, css_class=None)

Render the given table to the output file object in the requested format.

The table gets written out to the ‘output’ file.

Parameters
  • table_ – An instance of Table.

  • output – A file object you can write to.

  • output_format – A string, the format to write the table to, either ‘csv’, ‘txt’ or ‘html’.

  • css_id – A string, an optional CSS id for the table object (only used for HTML).

  • css_class – A string, an optional CSS class for the table object (only used for HTML).

beancount.reports.table.table_to_csv(table, file=None, **kwargs)

Render a Table to a CSV file.

Parameters
  • table – An instance of a Table.

  • file – A file object to write to. If no object is provided, this function returns a string.

  • **kwargs – Optional arguments forwarded to csv.writer().

Returns

A string, the rendered table, or None, if a file object is provided to write to.

beancount.reports.table.table_to_html(table, classes=None, file=None)

Render a Table to HTML.

Parameters
  • table – An instance of a Table.

  • classes – A list of string, CSS classes to set on the table.

  • file – A file object to write to. If no object is provided, this function returns a string.

Returns

A string, the rendered table, or None, if a file object is provided to write to.

beancount.reports.table.table_to_text(table, column_interspace=' ', formats=None)

Render a Table to ASCII text.

Parameters
  • table – An instance of a Table.

  • column_interspace – A string to render between the columns as spacer.

  • formats – An optional dict of column name to a format character that gets inserted in a format string specified, like this (where ‘<char>’ is): {:<char><width>}. A key of ‘*’ will provide a default value, like this, for example: (… formats={‘*’: ‘>’}).

Returns

A string, the rendered text table.

beancount.reports.tree_table

Routines to render an HTML table with a tree of accounts.

beancount.reports.tree_table.is_account_active(real_account)

Return true if the account should be rendered. An active account has at least one directive that is not an Open directive.

Parameters

real_account – An instance of RealAccount.

Returns

A boolean, true if the account is active, according to the definition above.

beancount.reports.tree_table.table_of_balances(real_root, price_map, price_date, operating_currencies, formatter, classes=None)

Render a tree table with the balance of each accounts.

Parameters
  • real_root – A RealAccount node, the root node to render.

  • price_map – A prices map, a built by build_price_map.

  • price_date – A datetime.date instance, the date at which to compute market value.

  • operating_currencies – A list of strings, the operating currencies to render to their own dedicated columns.

  • formatter – A object used to render account names and other links.

  • classes – A list of strings, the CSS classes to attach to the renderd top-level table objet.

Returns

A string with HTML contents, the rendered table.

beancount.reports.tree_table.tree_table(oss, real_account, formatter, header=None, classes=None)

Generator to a tree of accounts as an HTML table.

This yields each real_account object in turn and a list object used to provide the values for the various columns to render.

Parameters
  • oss – a io.StringIO instance, into which we will render the HTML.

  • real_account – an instance of a RealAccount node.

  • formatter – A object used to render account names and other links.

  • header – a list of header columns to render. The first column is special, and is used for the account name.

  • classes – a list of CSS class strings to apply to the table element.

Returns

A generator of tuples of

real_account: An instance of RealAccount to render as a row cells: A mutable list object to accumulate values for each column you

want to render.

row_classes: A mutable list object to accumulate css classes that you

want to add for the row.

You need to append to the given ‘cells’ object; if you don’t append anything, this tells this routine to skip rendering the row. On the very last line, the ‘real_account’ object will be a special sentinel value to indicate that it is meant to render the totals line: TOTALS_LINE.