Excel and Beancount output#

r.to_excel(path, ...) writes a workbook with live formulas. The boki.Style decides how it looks, b.sheet, b.section, b.row, b.block, b.panel and b.link decide where rows go, and the returned boki.excel.Report says what was written. boki.export.to_beancount writes an entity’s ledger as Beancount text. The narrative guides are the Excel notes and the Excel presentation notes.

Style#

class boki.Style(name, money=None, units=<factory>, hide=(), helpers='group', language='en', negatives='parens', zero='–', expenses='negative', colors=True, ratios=True, gridlines=False, periods='fy', statements=True, columns='fiscal', font=None, decimals=None, band=None, shade=None, dollars=False, titles=<factory>, header=None)#

How the Excel output looks: number scale and formats, colors, signs, headings, and which sheets to build.

A style changes only how numbers are shown. The Model sheet keeps base units and the formulas the export is checked against, and the statement sheets refer to it. The presets in b.styles are styles. Pass one as style= to Result.to_excel, or pass the settings you want to change as keyword arguments, which override the style: r.to_excel("plan.xlsx", money="$mm"). A Style is immutable; replace (or calling the style) makes a changed copy.

Parameters:
namestr

Name of the style, such as "banker". Required. It is a label and does not change the output.

moneystr, float, or int, optional

The money scale of the whole workbook: "$mm", "$000", "millions JPY", "thousands JPY", "hundred millions JPY" or a number such as 1000. Currency marks are ignored, because the books have one currency. Statement sheets divide by the scale and caption it, such as (in millions). The default is None, which means no scaling.

unitsdict, optional

Display unit for series on the Model sheet, as {series: Unit}, such as {generation: MWh}. The unit must have the dimension of the series. The default is an empty dict.

hideiterable, optional

Named series (or their names) to fold away like helper rows on the Model sheet. The default is an empty tuple.

helpersstr, default=”group”

"group" folds the helper rows (rows for unnamed intermediate expressions) and "show" leaves them open.

languagestr, default=”en”

Language of the names of kinds, automatic accounts and statement lines. "en" is the default. "ja" takes the same English labels and changes the sheet names and the sheet title format.

negativesstr, default=”parens”

How a negative number is shown: "parens" as (1,234), "triangle" with a triangle mark in front, or "minus" as -1,234.

zerostr, default=”–”

The text shown for a zero.

expensesstr, default=”negative”

"negative" shows expenses as negative numbers and subtotals add them. "positive" shows expenses as positive numbers and subtotals subtract them.

colorsbool, default=True

Color the text: inputs blue, formulas black, links to other sheets green.

ratiosbool, default=True

Add growth under revenue, margin under each profit subtotal, and the effective tax rate under income taxes.

gridlinesbool, default=False

Show the gridlines of the sheets.

periodsstr, default=”fy”

How period columns are headed: "fy" as FY2027E, "year" as plain years such as 2027, or "raw" with the model’s own period labels.

statementsbool, default=True

Build the statement sheets (income statement, balance sheet, cash flow) in this style. False writes only the plain link sheets.

columnsstr, default=”fiscal”

Statement columns for a model with periods shorter than a year: "fiscal" sums them into fiscal years, "periods" keeps one column for each model period.

fontstr, optional

Font name for the statement sheets, such as "Arial". The default is None, the spreadsheet default.

decimalsint, optional

Digits after the decimal point. The default is None, which uses 1 when the money scale is a million or more and 0 otherwise.

bandstr, optional

Fill color of the title band and the column headers, as a hex RGB string such as "1F3864"; the text on it is white. The default is None, no band.

shadestr, optional

Fill color of the final totals, as a hex RGB string. The default is None, no fill.

dollarsbool, default=False

Put a dollar sign on the first line and the totals, and caption the statements on three lines, as a 10-K does.

titlesdict, optional

Statement and line names that differ in this style, as {key: name}, such as {"IS": "Consolidated Statements of Operations"}. The default is an empty dict.

headerstr, optional

A line above the period headings, where {end} is the fiscal year end such as December 31: "Year Ended {end},". The default is None, no line.

Attributes:
namestr

The style’s name.

moneystr | float | None

The money scale as given.

unitsdict

The display units of series.

hidetuple

The series folded away.

helpersstr

"group" or "show".

languagestr

The label language.

negativesstr

The negative-number format.

zerostr

The text for zero.

expensesstr

"negative" or "positive".

colorsbool

Whether text is colored.

ratiosbool

Whether ratio rows are added.

gridlinesbool

Whether gridlines show.

periodsstr

The period heading format.

statementsbool

Whether statement sheets are built.

columnsstr

The statement column grouping.

fontstr | None

The font name.

decimalsint | None

Digits after the point.

bandstr | None

The band fill color.

shadestr | None

The totals fill color.

dollarsbool

Whether dollar signs are shown as in a filing.

titlesdict

The names that differ.

headerstr | None

The line above the period headings.

Raises:
TypeError

At construction through replace, if a setting is not a field of the style.

ValueError

At construction through replace, if columns is not "fiscal" or "periods", helpers is not "group" or "show", or money is not a scale boki knows. A Style made directly is not checked until it is used.

See also

boki.styles.styles

The presets.

boki.Style.replace

Make a changed copy.

Notes

Settings apply in this order: the preset, then the keyword overrides, which are applied to it with replace. The scale changes only the statement sheets and number formats; formulas and values on the Model sheet stay in base units, and every formula recalculates to boki’s value. See Excel presentation.

Examples

Change a preset’s settings, and an invalid setting is an error:

>>> import boki as b
>>> style = b.styles.banker(money="$mm", negatives="minus")
>>> style.name, style.money, style.negatives, style.band
('banker', '$mm', 'minus', '1F3864')
>>> b.styles.banker(columns="weekly")
Traceback (most recent call last):
...
ValueError: columns= must be 'fiscal' or 'periods'
__call__(**kw)#

Return a copy of the style with some settings changed; the same as replace.

Parameters:
**kwobject

Settings to change, by the names of the fields of Style, such as money="$mm".

Returns:
Style

A new style with the given settings. The original is unchanged.

Raises:
TypeError

At construction, if a keyword is not a field of the style.

ValueError

At construction, if columns, helpers or money has an invalid value.

See also

boki.Style.replace

The same operation under its method name.

Examples

>>> import boki as b
>>> b.styles.plain(gridlines=False).gridlines
False
replace(**kw)#

Return a copy of the style with some settings changed.

The checks that settings are valid run here, so a mistake fails when the style is made and not when the workbook is written.

Parameters:
**kwobject

Settings to change, by the names of the fields of Style. units, hide and titles are copied to a dict, a tuple and a dict.

Returns:
Style

A new style with the given settings. The original is unchanged.

Raises:
TypeError

At construction, if a keyword is not a field of the style.

ValueError

At construction, if columns is not "fiscal" or "periods", helpers is not "group" or "show", or money is not a scale boki knows, such as "$mm".

See also

boki.Style

The settings.

Examples

A preset in millions, with the scale checked:

>>> import boki as b
>>> style = b.styles.japanese.replace(money="millions JPY")
>>> style.money, style.negatives
('millions JPY', 'triangle')
>>> b.styles.banker.replace(money="lots")
Traceback (most recent call last):
...
ValueError: money='lots': use a scale such as '$mm', '$000', 'millions JPY', 'thousands JPY' or a number
>>> b.styles.banker.replace(colour=False)
Traceback (most recent call last):
...
TypeError: unknown style setting(s): colour
class boki.styles.styles#

The Excel style presets: b.styles.banker (the default for every standard), sec, japanese and plain.

Each preset is a Style. Use one as r.to_excel("plan.xlsx", style=b.styles.sec) or change it with keyword arguments: b.styles.banker(money="$mm"). The class only holds the presets.

Attributes:
bankerStyle

Investment-banking look, the default: expenses negative in parentheses, blue inputs and green links, growth and margin rows, a dark title band, shaded totals, Arial.

secStyle

A filing look: Times New Roman, no colors, no ratio rows, dollar signs on the first line and the totals, plain year headings with a “Year Ended” line, and “Consolidated” statement titles.

japaneseStyle

Japanese accounting presentation: triangle marks for negatives, expenses shown positive with subtotals that subtract, no ratio rows, fiscal-year headings.

plainStyle

The plain output: minus signs, expenses positive, no colors or ratio rows, gridlines on, the model’s own period labels, no statement sheets, and helper rows shown.

See also

boki.Style

The settings of a style.

Examples

The presets differ in how they show negatives and expenses:

>>> import boki as b
>>> b.styles.banker.negatives, b.styles.japanese.negatives, b.styles.plain.negatives
('parens', 'triangle', 'minus')
>>> b.styles.banker.expenses, b.styles.plain.expenses
('negative', 'positive')

Placement#

boki.sheet(name, entries, *, money=None)#

Make a workbook sheet of placed rows, in reading order.

Pass the sheets to Result.to_excel(sheets=[...]). A placed series is written on its sheet with its formula, and the rest of the model stays where boki puts it.

Parameters:
namestr

The sheet’s name. Required. Inputs, Model and Checks are the workbook’s own sheets, in any capitalization.

entriesiterable

The sections, blocks, panels, rows, links, and series, in order. Required.

moneystr, float, or int, optional

Optional sheet-level money scale such as "$mm" or "$000".

Returns:
Sheet

The sheet, to pass in sheets= of Result.to_excel.

Raises:
ValueError

At construction, if name is Inputs, Model or Checks, in any capitalization.

See also

boki.section

Group rows under a heading.

boki.row

Place a series.

boki.block

Expand a series into verified component rows.

boki.panel

Add a 2D non-time-series table.

boki.link

Show a row again.

Examples

Place revenue on a Sales sheet and link it from a Summary sheet, in a workbook written to a temporary folder:

>>> import pathlib, tempfile
>>> import boki as b
>>> m = b.Model("Sheets", start="2027-01", periods=3, step=b.month)
>>> customers = m.input("Customers", 100)
>>> revenue = m.series("Revenue", customers * 20)
>>> revenue_row = b.row(revenue)
>>> sales = b.sheet("Sales", [b.section("Revenue", [customers, revenue_row])])
>>> summary = b.sheet("Summary", [b.link(revenue_row)])
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder:
...     report = r.to_excel(pathlib.Path(folder) / "plan.xlsx", sheets=[sales, summary])
>>> report.formulas > 0
True
>>> b.sheet("Model", [])
Traceback (most recent call last):
...
ValueError: b.sheet('Model'): that name is the workbook's own sheet
boki.section(title, entries)#

Group rows under a heading on a sheet.

Parameters:
titlestr

The heading written above the rows. Required.

entriesiterable

The rows in order: series, placed rows made by b.row, links made by b.link, blocks made by b.block, and panels made by b.panel. Required.

Returns:
Section

The section, to use in the entries of a Sheet.

See also

boki.sheet

Make the sheet that holds sections.

boki.row

Place a series.

Examples

>>> import boki as b
>>> m = b.Model("Section", start="2027-01", periods=2, step=b.month)
>>> customers = m.input("Customers", 100)
>>> revenue = m.series("Revenue", customers * 5)
>>> block = b.section("Revenue", [customers, b.row(revenue)])
>>> block.title, len(block.entries)
('Revenue', 2)
boki.row(series, label=None, *, sign=1, scale=1, total=False, formula=None, verify='perturb', fmt=None)#

Place a series on a sheet: its formula is written in this row.

Put the result in the entries of b.sheet, b.section, or b.block. The display settings change only how the row shows the value; formulas and statements that refer to the row turn it back into the value, so they never change a result. Pass formula= to write an alternative equivalent expression in Excel, verified against series across scenarios and perturbed inputs.

Parameters:
seriesSeries

The series to write. Required.

labelstr, optional

Row label, which replaces the series’ name. The default is None, which keeps the name. An unnamed series needs a label.

signint, default=1

1 or -1. -1 shows the value negated, such as a cost shown as a negative number.

scalefloat, default=1

A positive number the row’s value is divided by for display, such as 1000 for thousands. A bool is not accepted.

totalbool or str, default=False

Row emphasis: False, True (bold subtotal with top rule), or "grand" (double bottom rule and shading).

formulaSeries, optional

Equivalent expression to emit in Excel instead of series’s lowered expression. Verified against series when to_excel runs.

verifystr, default=”perturb”

Equivalence check mode for formula: "perturb", "base", or "off".

fmtstr, optional

Display format hint: "percent", "multiple", "days", "integer", or "number".

Returns:
Line

The placed row, to use in a Sheet, Section, or Block, and as the target of Link.

Raises:
ValueError

At construction, if sign is not 1 or -1, scale is not a positive number, or total, verify, or fmt is invalid. At evaluation (when Result.to_excel writes the sheets), if the same series is placed by two rows, or an unnamed series is placed without a label.

See also

boki.block

Expand a series into itemized rows with a verified SUM total.

boki.link

Show a placed row again on another sheet.

boki.sheet

Make the sheet that holds placed rows.

Notes

A row shows value * sign / scale. Use link to show a placed row again; placing the same series twice with row is an error. An input placed on a sheet is written as a link to its row on the Inputs sheet. See Excel row placement.

Examples

A cost shown as a negative number, in thousands:

>>> import boki as b
>>> m = b.Model("Row", start="2027-01", periods=2, step=b.month)
>>> cost = m.series("Cost", 5000)
>>> line = b.row(cost, "Operating cost", sign=-1, scale=1000)
>>> line.label, line.sign, line.scale
('Operating cost', -1, 1000)
>>> b.row(cost, sign=2)
Traceback (most recent call last):
...
ValueError: b.row: sign= is 1 or -1, got 2

Show a placed row again: each cell refers to the row that b.row placed elsewhere.

The value keeps one formula, in the placed row, and the link shows it as that row shows it (or negated when sign=-1).

Parameters:
targetLine or Series

The placed row to show again, as returned by b.row, or a series that is placed elsewhere. Required.

labelstr, optional

Row label of the link. The default is None, which uses the label of the target.

signint, default=1

1 keeps the target’s sign and -1 negates it.

totalbool or str, default=False

Row emphasis: False, True, or "grand".

fmtstr, optional

Optional display format hint: "percent", "multiple", "days", "integer", or "number".

Returns:
Link

The link, to use in the entries of a Sheet, Section, or Block.

Raises:
ValueError

At construction, if sign is not 1 or -1, or total or fmt is invalid.

See also

boki.row

Place a series.

boki.sheet

Make the sheet that holds links.

Examples

Place revenue on one sheet and show it again on a summary sheet:

>>> import boki as b
>>> m = b.Model("Link", start="2027-01", periods=2, step=b.month)
>>> revenue = m.series("Revenue", 5)
>>> row = b.row(revenue)
>>> summary = b.sheet("Summary", [b.link(row, "Revenue")])
>>> summary.entries[0].target is row
True
boki.block(target, rows, *, label=None, sign=1, total=True, verify='perturb', fmt=None)#

Expand a series into itemized rows followed by a verified SUM total row.

Use b.block to present a canonical boki series (such as co.cf.operating) as human-authored component rows summed by =SUM(...) in Excel (such as an indirect cash-flow block). Before writing the workbook, boki verifies that the sum of rows matches target across the base render, every scenario, and perturbed inputs; any discrepancy raises EquivalenceError.

Parameters:
targetSeries

The canonical series whose home becomes the block’s SUM row. Required.

rowsiterable

The component rows whose values sum to target: series, Line, or Link. Must be non-empty.

labelstr, optional

Label for the total row. Defaults to target.name.

signint, default=1

1 or -1 applied when comparing the sum against target.

totalbool or str, default=True

Emphasis of the total row: True (subtotal) or "grand".

verifystr, default=”perturb”

Equivalence check mode: "perturb", "base", or "off".

fmtstr, optional

Optional display format hint for the total row.

Returns:
Block

The verified block, to place inside a Sheet or Section.

Raises:
ValueError

At construction, if rows is empty, sign is not 1 or -1, or total, verify, or fmt is invalid.

See also

boki.row

Place a single row with an optional verified formula override.

boki.excel.EquivalenceError

Raised when the block sum disagrees with target.

Examples

Expand a total into two component rows and verify equivalence on export:

>>> import boki as b
>>> m = b.Model("Block", start="2027-01", periods=2, step=b.year)
>>> a = m.series("A", 10)
>>> c = m.series("C", 20)
>>> combined = m.series("Combined", a + c)
>>> blk = b.block(combined, [a, c], label="Total")
>>> blk.label, len(blk.rows)
('Total', 2)
boki.panel(title, columns, rows)#

Create a 2D non-time-series table panel (such as Sources & Uses or a Valuation Bridge).

Parameters:
titlestr

Heading written above the panel. Required.

columnsiterable of str

Column labels for the table. Must be non-empty.

rowsiterable

Rows as (label, values) or (label, values, options) tuples, where values has one cell per column (a scalar Series, Quantity, number, or string) and options is an optional dict with total / fmt.

Returns:
Panel

The panel, to include in a Sheet or Section.

Raises:
ValueError

At construction, if columns is empty or a row’s value count does not match columns.

See also

boki.sheet

Place panels on a workbook sheet.

Examples

>>> import boki as b
>>> p = b.panel("Valuation", ["$mm", "x EBITDA"], [("Enterprise value", [500, 10.0])])
>>> p.title, p.columns
('Valuation', ('$mm', 'x EBITDA'))
boki.sensitivity(title, row_values, col_values, formula, *, fmt=None, row_fmt=None, col_fmt=None, highlight=None, corner='')#

Create a 2D sensitivity matrix whose cells reference live numeric row and column headers in Excel.

Parameters:
titlestr

Heading written above the sensitivity table. Required.

row_valuesiterable

Values for the row axis (numbers or scalar Series). Must be non-empty.

col_valuesiterable

Values for the column axis (numbers or scalar Series). Must be non-empty.

formulacallable

Function (row_var, col_var) -> Series returning the expression for each cell. Required.

fmtstr, optional

Display format hint for matrix cells ("percent", "multiple", "price", "money", etc.).

row_fmtstr, optional

Format hint or Excel format string for row headers in Column A.

col_fmtstr, optional

Format hint or Excel format string for column headers.

highlighttuple of int, optional

Optional 0-based (row_index, col_index) of the Base-case cell to shade.

cornerstr, default=””

Optional label for the top-left corner cell of the header band.

Returns:
Sensitivity

The sensitivity matrix, to place in a Sheet or Section.

Raises:
ValueError

At construction, if row_values or col_values is empty, formula is not callable, or highlight is out of range.

See also

boki.panel

Construct a general 2D summary table.

boki.sheet

Place tables on a workbook sheet.

Examples

>>> import boki as b
>>> s = b.sensitivity("Products", [2.0, 3.0], [10.0, 20.0], lambda r, c: r * c, highlight=(0, 1))
>>> s.title, s.highlight
('Products', (0, 1))
class boki.placement.Sheet(name, entries, money=None)#

A workbook sheet of placed rows, in reading order.

b.sheet(name, entries, ...) makes one, and Result.to_excel(sheets=[...]) writes each as a workbook sheet, in the order given. A Sheet is immutable and compares by identity.

Parameters:
namestr

The sheet’s name. Required. Inputs, Model and Checks belong to the workbook, in any capitalization.

entriestuple

The sections, blocks, panels, rows, links, and series, in order. Required.

moneystr, float, or int, optional

Optional sheet-level money display scale such as "$mm" or "$000". Overrides the workbook style’s money for this sheet when set.

Attributes:
namestr

The sheet name.

entriestuple

The entries of the sheet.

moneystr | float | int | None

Optional money scale for this sheet.

See also

boki.sheet

Make a sheet.

boki.section

Group rows under a heading.

Examples

>>> import boki as b
>>> m = b.Model("Sheet", start="2027-01", periods=2, step=b.month)
>>> revenue = m.series("Revenue", 5)
>>> summary = b.sheet("Summary", [b.row(revenue)])
>>> summary.name, len(summary.entries)
('Summary', 1)
class boki.placement.Section(title, entries)#

A titled group of rows on a sheet.

b.section(title, entries) makes one. A section heading is written above its rows. A Section is immutable and compares by identity.

Parameters:
titlestr

The heading. Required.

entriestuple

The rows, in order: series, placed rows (Line), links (Link), verified blocks (Block), and panels (Panel). Required.

Attributes:
titlestr

The section heading.

entriestuple

The entries of the section.

See also

boki.section

Make a section.

boki.sheet

A sheet holds sections and rows.

Examples

>>> import boki as b
>>> m = b.Model("Section", start="2027-01", periods=2, step=b.month)
>>> revenue = m.series("Revenue", 5)
>>> block = b.section("Revenue", [b.row(revenue)])
>>> block.title, len(block.entries)
('Revenue', 1)
class boki.placement.Line(series, label=None, sign=1, scale=1, total=False, formula=None, verify='perturb', fmt=None)#

A series placed on a sheet: the row where its formula is written, and how the row shows it.

b.row(series, ...) makes one. Put it in the entries of a Sheet, Section, or Block. The row’s display settings change only how the value is shown; formulas that refer to the row convert it back, so a result never changes. An optional formula overrides the Excel formula written for this row after boki verifies equivalence against series. A Line is immutable and compares by identity.

Parameters:
seriesSeries

The series to write. Required.

labelstr, optional

Row label, which replaces the series’ name. The default is None, which keeps the name; an unnamed series needs a label.

signint, default=1

1 shows the value as it is and -1 shows it negated, such as a cost shown as a negative number.

scalefloat, default=1

A positive divisor for display: 1000 shows the value in thousands. The cell shows value * sign / scale.

totalbool or str, default=False

Row emphasis: False for a regular line, True for a bold subtotal with a top rule, or "grand" for a bold total with a top rule, double bottom rule, and shading.

formulaSeries, optional

Alternative expression written to Excel in place of series’s own formula (for forecast periods when the row has historical actuals). Verified against series according to verify.

verifystr, default=”perturb”

Equivalence check for formula: "perturb" checks base, all scenarios, and perturbed inputs; "base" checks the rendered result only; "off" skips verification.

fmtstr, optional

Display format hint: "percent", "multiple", "days", "integer", or "number".

Attributes:
seriesobject

The placed series.

labelstr | None

The row label, or None.

signint

1 or -1.

scalefloat

The display divisor.

totalbool | str

False, True, or "grand".

formulaobject

Optional override expression, or None.

verifystr

Equivalence verification mode.

fmtstr | None

Optional format hint.

See also

boki.row

Make a placed row, with its checks.

boki.block

Expand a series into itemized rows and a verified SUM total.

boki.link

Show a placed row again on another sheet.

Examples

A cost shown as a negative number, in thousands:

>>> import boki as b
>>> m = b.Model("Line", start="2027-01", periods=2, step=b.month)
>>> cost = m.series("Cost", 5)
>>> line = b.row(cost, "Operating cost", sign=-1, scale=1000)
>>> line.label, line.sign, line.scale, line.series is cost
('Operating cost', -1, 1000, True)

A placed row shown again elsewhere: each cell refers to the row it links to.

b.link(row) makes one. A value then has one formula, in the row that was placed, and the link shows it as that row shows it (optionally negated with sign=-1). A Link is immutable and compares by identity.

Parameters:
targetLine or Series

The placed row to show again: the Line made by b.row, or a series that is placed elsewhere. Required.

labelstr, optional

Row label for the link. The default is None, which uses the label of the target.

signint, default=1

1 keeps the target’s sign and -1 negates it.

totalbool or str, default=False

Row emphasis: False, True, or "grand".

fmtstr, optional

Optional format hint: "percent", "multiple", "days", "integer", or "number".

Attributes:
targetobject

The row or series the link shows.

labelstr | None

The row label, or None.

signint

1 or -1.

totalbool | str

False, True, or "grand".

fmtstr | None

Optional format hint.

See also

boki.link

Make a link.

boki.row

Place a series.

Examples

>>> import boki as b
>>> m = b.Model("Link", start="2027-01", periods=2, step=b.month)
>>> revenue = m.series("Revenue", 5)
>>> row = b.row(revenue)
>>> shown_again = b.link(row, "Revenue (summary)")
>>> shown_again.label, shown_again.target is row
('Revenue (summary)', True)
class boki.placement.Block(target, rows, label=None, sign=1, total=True, verify='perturb', fmt=None)#

An itemized group of rows whose Excel SUM is verified equal to a target series.

b.block(target, rows, ...) makes one. In Excel, the itemized rows appear first, followed by a total row that sums them with =SUM(...) and acts as the home row of target. Before writing the workbook, boki verifies that the sum of rows equals target across the base render, every scenario, and perturbed inputs. A Block is immutable and compares by identity.

Parameters:
targetSeries

The canonical series whose home becomes the block’s SUM row (for example co.cf.operating). Required.

rowstuple

Itemized rows whose displayed values sum to target: series, Line, or Link. Required.

labelstr, optional

Label for the SUM total row. Defaults to target.name.

signint, default=1

1 or -1 applied to the target comparison.

totalbool or str, default=True

Emphasis of the total row: True (subtotal) or "grand".

verifystr, default=”perturb”

Equivalence verification mode: "perturb", "base", or "off".

fmtstr, optional

Optional display format hint for the total row.

Attributes:
targetobject

The canonical target series.

rowstuple

The itemized component entries.

labelstr | None

Total row label, or None.

signint

1 or -1.

totalbool | str

Total row emphasis.

verifystr

Verification mode.

fmtstr | None

Optional format hint.

See also

boki.block

Construct a verified block.

boki.row

Place a single row with an optional verified formula override.

Examples

>>> import boki as b
>>> m = b.Model("Block", start="2027-01", periods=2, step=b.year)
>>> a = m.series("A", 10)
>>> c = m.series("C", 20)
>>> total = m.series("Total", a + c)
>>> blk = b.block(total, [a, c], label="Combined")
>>> blk.label, len(blk.rows)
('Combined', 2)
class boki.placement.Panel(title, columns, rows)#

A 2D summary table (such as Sources & Uses or a DCF Valuation Bridge) placed on a sheet.

b.panel(title, columns, rows) makes one. Each cell value may be a scalar Series (written as a live Excel formula referring to placed rows or inputs), a Quantity, a number, or a string. A Panel is immutable and compares by identity.

Parameters:
titlestr

Heading written above the panel. Required.

columnstuple

Column headers, such as ("$mm", "%", "x EBITDA"). Required.

rowstuple

Rows of the panel as (label, values) or (label, values, options_dict) pairs, where values has one entry per column and options_dict may specify total and fmt. Required.

Attributes:
titlestr

The panel heading.

columnstuple

The column headers.

rowstuple

The panel rows.

See also

boki.panel

Construct a 2D panel.

boki.sheet

Place panels alongside time-series sections on a sheet.

Examples

>>> import boki as b
>>> pnl = b.panel("Sources", ["$mm", "%"], [("Debt", [60, 0.6]), ("Equity", [40, 0.4])])
>>> pnl.title, pnl.columns, len(pnl.rows)
('Sources', ('$mm', '%'), 2)
class boki.placement.Sensitivity(title, row_values, col_values, formula, fmt=None, row_fmt=None, col_fmt=None, highlight=None, corner='')#

A 2D sensitivity matrix whose Excel formulas reference live numeric row and column headers.

b.sensitivity(title, row_values, col_values, formula, ...) makes one. Row headers live in Column A and column headers live in the panel header row as real numbers or live formulas (formatted with row_fmt / col_fmt), and every matrix cell emits a live Excel formula referencing $A<row> and <col>$<hdr>. Editing any axis header directly in Excel recalculates that row or column live. A Sensitivity is immutable and compares by identity.

Parameters:
titlestr

Heading written above the sensitivity table. Required.

row_valuestuple

Row-axis values written into Column A (numbers or scalar Series). Required.

col_valuestuple

Column-axis values written into the table header row (numbers or scalar Series). Required.

formulacallable

Callable (row_var, col_var) -> Series defining each cell in terms of the row and column axis variables. Required.

fmtstr, optional

Display format hint for matrix cells ("percent", "multiple", "price", "money", etc.).

row_fmtstr, optional

Display format hint or Excel number format for Column A row headers (for example '"Entry "0.0"x"' or "percent").

col_fmtstr, optional

Display format hint or Excel number format for top-row column headers (for example '"Exit "0.0"x"' or '"g = "0.0%').

highlighttuple of int, optional

Optional (row_index, col_index) (0-based) to highlight as the Base-case cell.

cornerstr, default=””

Optional label for the top-left corner cell of the header band (for example "Entry / Exit").

Attributes:
titlestr

Table heading.

row_valuestuple

Row-axis header values.

col_valuestuple

Column-axis header values.

formulaobject

Callable building the matrix cell expression.

fmtstr | None

Cell format hint.

row_fmtstr | None

Row-header format hint or Excel format string.

col_fmtstr | None

Column-header format hint or Excel format string.

highlighttuple | None

Highlighted (row_idx, col_idx) or None.

cornerstr

Top-left corner header text.

See also

boki.sensitivity

Construct a 2D sensitivity table.

boki.panel

Construct a general 2D summary table.

Examples

>>> import boki as b
>>> s = b.sensitivity("Grid", [1.0, 2.0], [10.0, 20.0], lambda r, c: r * c, fmt="number")
>>> s.title, len(s.row_values), len(s.col_values)
('Grid', 2, 2)

The report and its warnings#

class boki.excel.Report(formulas=0, values=0, data=0, guarded=0, reasons=<factory>, unnamed=<factory>, unplaced=<factory>)#

What an Excel export wrote: how many cells are formulas, data, or values boki computed, and why.

Result.to_excel returns one. str(report) gives a one-line summary.

Parameters:
formulasint, default=0

Number of cells of the model’s series that were written as live formulas. The formulas of the statement sheets are not counted.

valuesint, default=0

Number of cells that could not be written as formulas and hold the value boki computed, shaded and with a note.

dataint, default=0

Number of cells that hold input data, such as the points of a time table.

guardedint, default=0

Number of formula cells written with a part boki does not read as NA(), to avoid a circular reference in Excel.

reasonsdict, optional

Why cells hold values, as {reason: count}; the reasons are the messages of Untranslatable. The default is an empty dict.

unnamedlist, optional

Descriptions of the time tables without a name. to_excel raises UnnamedAssumption when any exist, so a report that was returned has an empty list. The default is an empty list.

unplacedlist, optional

Labels of any rows that remained on the Model sheet when omit_unused_model=True. Empty when every needed calculation lives on placed sheets. The default is an empty list.

Attributes:
formulasint

Number of formula cells.

valuesint

Number of value cells.

dataint

Number of data cells.

guardedint

Number of guarded formula cells.

reasonsdict[str, int]

The count of value cells for each reason.

unnamedlist[str]

The unnamed tables found.

unplacedlist[str]

Labels of rows left on the Model sheet when omit_unused_model=True.

See also

boki.excel.Untranslatable

The reason a cell is a value.

boki.excel.CircularReferenceWarning

The warning that goes with guarded.

Notes

Values are in base units (currency, Wh, months), the same as the model. A value cell is a value, not a formula, so it does not follow a changed input in the workbook; export again from boki.

Examples

Export to a temporary folder and read the report:

>>> import pathlib, tempfile
>>> import boki as b
>>> m = b.Model("Report", start="2027-01", periods=3, step=b.month)
>>> customers = m.input("Customers", 100)
>>> revenue = m.series("Revenue", customers * 20)
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder:
...     report = r.to_excel(pathlib.Path(folder) / "plan.xlsx")
>>> report.formulas > 0, report.values, report.guarded, report.unnamed
(True, 0, 0, [])
exception boki.excel.Untranslatable#

A series that cannot be written as an Excel formula.

The Excel writer raises it while translating a series, and to_excel catches it: the cell is written as the value boki computed, shaded and with a note, and counted in Report.values. The message of the exception is the reason, counted in Report.reasons. You do not normally see the exception itself; you see its reasons in the report.

See also

boki.excel.Report

The report that counts the value cells and their reasons.

Notes

Typical reasons are an unknown that was solved (Unknown), a Python function used as a series, a period chosen by a series, and a reduction that has no row to refer to. See the Excel notes for what is written as a formula.

Examples

A solved unknown has no formula, so its cell is a value, and the reason is reported:

>>> import pathlib, tempfile
>>> import boki as b
>>> m = b.Model("Solve", start="2027-01", periods=2, step=b.year)
>>> size = m.unknown("Size", init=1)
>>> demand = m.input("Demand", 10)
>>> m.solve(size, size == b.min(demand * 2, 15))
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder:
...     report = r.to_excel(pathlib.Path(folder) / "solve.xlsx")
>>> report.reasons
{'Unknown': 1}
exception boki.excel.UnnamedAssumption#

Error that a time table used inside a formula has no name.

A time table (b.by_year, b.step, or data) used inside a formula without a name needs a row in the workbook, and a row needs a name. to_excel raises this error and lists each table with the file and line where it was made and the row that uses it. Name the table with m.input("...", ...), or with m.series when its values are other series. A single number such as 0.45 * sales stays inline and needs no name.

See also

boki.excel.Report

The report, whose unnamed attribute lists the tables.

Notes

The error is a ValueError. It is raised when the workbook is written, before any file is saved.

Examples

A cost ratio that changes by year, used without a name:

>>> import pathlib, tempfile
>>> import boki as b
>>> from boki.units import USD
>>> from boki.excel import UnnamedAssumption
>>> m = b.Model("Unnamed", start="2027-01", periods=3, step=b.year)
>>> co = m.entity("Co", standard=b.IFRS, currency=USD)
>>> sales = co.pl.revenue("Sales", m.input("Sales plan", b.by_year({0: 100, 1: 120, 2: 150}) * USD))
>>> ratio = b.by_year({0: 0.4, 1: 0.38, 2: 0.36})
>>> cost = co.pl.cogs("Cost", ratio * sales)
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder:
...     try:
...         r.to_excel(pathlib.Path(folder) / "unnamed.xlsx")
...     except UnnamedAssumption as error:
...         print(str(error).splitlines()[0])
1 assumption tables have no name; a table needs a row, and a row a name. Name each with m.input("…", …):
exception boki.excel.EquivalenceError#

Error that a b.row(..., formula=...) or b.block(...) rewrite disagrees with boki’s model.

Before writing the workbook, to_excel checks every verified rewrite against its target series across the base render, all declared scenarios, and randomly perturbed numeric inputs. Any mismatch raises this error with the row or block label, case, period, expected value, and rewrite value.

See also

boki.row

Place a row with an optional verified formula= override.

boki.block

Expand a series into itemized rows with a verified SUM total.

Examples

An incorrect override formula fails verification before the file is written:

>>> import pathlib, tempfile
>>> import boki as b
>>> m = b.Model("Equiv", start="2027-01", periods=2, step=b.year)
>>> x = m.input("X", 10)
>>> y = m.series("Y", x * 2)
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder:
...     try:
...         r.to_excel(pathlib.Path(folder) / "bad.xlsx",
...                    sheets=[b.sheet("S", [b.row(y, formula=x * 3)])])
...     except b.EquivalenceError as error:
...         print("mismatch" in str(error).lower())
True
exception boki.excel.CircularReferenceWarning#

Warning that the export guarded cells whose full formula would make a circular reference in Excel.

boki reads only the cells a value needs, and Excel’s dependency graph counts every reference in a formula. When the extra references would close a circular reference that boki does not have, to_excel writes the fewest of them as NA() and warns with the guarded cells. The guarded cells are shaded and have a note, and Report.guarded counts them.

See also

boki.excel.Report

The report, whose guarded attribute counts the cells.

Notes

A guarded cell keeps its live condition and the formula for the branch boki reads. If a changed input in the workbook makes the cell read the guarded part, it shows #N/A and so do the cells that use it, instead of a wrong number; export again from boki for those inputs. See circular references boki does not have.

Examples

A debt sized from its own cash flow, with the construction years masked by an IF, warns when it is exported:

>>> import pathlib, tempfile, warnings
>>> import boki as b
>>> from boki.units import USD, year
>>> m = b.Model("Toll road", start="2020", periods=8, step=year)
>>> calendar = m.date.year
>>> start = m.input("construction start", 2020)
>>> opening = m.input("opening year", 2022)
>>> building = (calendar >= start) & (calendar < opening)
>>> operating = calendar >= opening
>>> debt_period = operating & (calendar < opening + 4)
>>> rate = m.input("debt rate", 0.05)
>>> capex = m.series("capex", (60 * USD).where(building, 0 * USD))
>>> revenue = m.series("net revenue", (40 * USD).where(operating, 0 * USD))
>>> commitment = m.series("debt commitment")
>>> fee = m.series("arrangement fee", (0.02 * commitment).where(calendar == start, 0 * USD))
>>> drawdown = m.series("drawdown", (0.7 * (capex + fee)).where(building, 0 * USD))
>>> equity = m.series("equity", (0.3 * (capex + fee)).where(building, 0 * USD))
>>> cfads = m.series("CFADS", revenue - capex + equity + drawdown - fee)
>>> factor = m.series("debt discount factor", (1 + rate) ** -(calendar - opening + 1))
>>> npv = m.series("NPV of CFADS", (cfads * factor).where(debt_period, 0 * USD).sum())
>>> sized = commitment.define(npv / 1.3)
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder, warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always")
...     report = r.to_excel(pathlib.Path(folder) / "toll.xlsx")
>>> [warning.category.__name__ for warning in caught]
['CircularReferenceWarning']
>>> report.guarded
8

Beancount#

boki.export.to_beancount(result, entity, currency=None)#

Write an entity’s ledger as Beancount text.

Each posting of the entity with a non-zero amount in a period becomes one transaction dated the last day of that period, with the debit and the credit as its two legs. The text is meant for plain-text-accounting tools, which read the account tree, the opening balances and the transactions.

Parameters:
resultResult

The result of m.render() that holds the amounts. Required.

entityEntity

The entity whose books to write, such as co, or group.books for the consolidated books. Required.

currencystr, optional

The Beancount commodity of every amount, such as "JPY". The default is None, which uses the entity’s currency when its books are in a single currency.

Returns:
str

The Beancount text: two option lines, an open directive for every account, one dated transaction for the opening balances (the day before the first period), and the transactions of the periods. Amounts have two decimals.

Raises:
ValueError

At evaluation, if the model’s periods are not dated, or if currency is omitted and the entity’s books are not in one currency (for example when nothing has been booked).

See also

boki.Style

How the Excel output looks.

Notes

Account names are Root:Kind:Name, where the root is Assets, Liabilities, Equity, Income or Expenses, and the kind and the name are written in CamelCase with ASCII characters only. A name with no ASCII characters becomes A1, A2 and so on, and a duplicate gets a numeric suffix. The original name is kept as the boki-name metadata of the open directive. Beancount derives retained earnings from the Income and Expenses accounts itself, so profit is not closed into the retained earnings account.

Examples

A café with opening cash of 1,000 for two months, written as Beancount text, which Beancount loads without errors:

>>> import boki as b
>>> from boki.units import JPY
>>> from boki.export import to_beancount
>>> m = b.Model("Cafe", start="2027-01", periods=2, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS, currency=JPY)
>>> co.bs.opening(cash=1000)
>>> sales = co.pl.revenue("Sales", 100)
>>> rent = co.pl.sga("Rent", 30)
>>> r = m.render()
>>> text = to_beancount(r, co)
>>> print("\n".join(text.splitlines()[:5]))
option "title" "Cafe"
option "operating_currency" "JPY"

2026-12-31 open Assets:Cash:Cash JPY
  boki-name: "Cash"
>>> from beancount import loader
>>> entries, errors, options = loader.load_string(text)
>>> errors
[]