Result#

boki.Model.render() returns a Result: read series values from it, draw statements and tables, and write the Excel workbook.

class boki.Result(model, render)#

Values, statements and Excel output of one render of a model.

Model.render returns a result. It holds the evaluated model: read any series from it with r[x] (all periods) or r.value(x, period) (one period), statements with Result.pl, Result.bs and Result.cf, arbitrary series as a table with Result.table, and write the workbook with Result.to_excel. Rendering again with other inputs gives a new, independent result.

Parameters:
modelModel

The model that was rendered.

renderRender

The evaluation of the model, which holds the computed values. Internal.

Attributes:
checkslist[CheckResult]

The outcome of every check of the model that was evaluated: yours and the built-in checks, such as that cash is never negative. Checks at level "off" are absent.

See also

boki.Model.render

Creates a result.

boki.CheckFailed

Carries the result of a render whose checks failed.

Notes

Only Model.render creates a result. Values are in base units (currency, Wh, months); tables and statements divide by a display unit or a money scale when they are shown.

Examples

>>> import boki as b
>>> m = b.Model("Cafe", start="2027-01", periods=3, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS)
>>> co.bs.opening(cash=1000, retained_earnings=1000)
>>> sales = co.pl.revenue("Sales", 100)
>>> rent = co.pl.sga("Rent", 40)
>>> r = m.render()
>>> r.value(co.pl.net_income, "2027-02")
60
>>> r[co.bs.cash]
[1060.0, 1120.0, 1180.0]
>>> [check.name for check in r.checks]
['Cafe: cash is not negative']
__getitem__(key)#

Return the values of a series: a list with one value per period, or one number for a scalar series.

Parameters:
keySeries or str

The series. A string is the name of a series, input or unknown of the model (r["Revenue"]). Any other value is turned into a series, so r[x * 2] evaluates an expression that has no name.

Returns:
list or float

For a series with a value in each period, the list of values in period order, in base units (None for a missing value). For a scalar series, its single value.

Raises:
KeyError

At call, if a string names no series of the model.

TypeError

At call, if key has a type a series expression cannot use.

See also

boki.Result.value

The value in one period.

boki.Result.table

Several series side by side.

Examples

>>> import boki as b
>>> m = b.Model("Plan", start="2027-01", periods=3, step=b.month)
>>> units = m.series("Units", data={0: 10, 1: 12, 2: 9})
>>> total = m.series("Total", units.sum())
>>> r = m.render()
>>> r[units]
[10, 12, 9]
>>> r["Units"] == r[units]
True
>>> r[total]
31
>>> r[units * 2]
[20, 24, 18]
bs(entity, by=None)#

Return an entity’s balance sheet as a table.

Assets, liabilities and equity follow the entity’s layout, with totals. Each row is a closing balance.

Parameters:
entityEntity or Group

The entity, or a group, whose consolidated books are shown.

bystr, optional

"fiscal_year" groups the periods into the fiscal years of the entity’s calendar, keeping each balance at the year’s last period. The default shows one column for each period.

Returns:
Table

The statement, titled BS <entity name>.

Raises:
ValueError

At call, if by is neither None nor "fiscal_year", or by="fiscal_year" has an entity without a fiscal calendar, or the periods are undated.

See also

boki.Result.pl

The profit and loss statement.

boki.Result.cf

The cash flow statement.

Notes

The balance sheet balances by construction, and Model.render verifies it. See double-entry bookkeeping.

Examples

>>> import boki as b
>>> m = b.Model("Cafe", start="2027-01", periods=2, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS)
>>> co.bs.opening(cash=1000, retained_earnings=1000)
>>> sales = co.pl.revenue("Sales", 100)
>>> table = m.render().bs(co)
>>> table.title, table.row("Total assets")
('BS Cafe', [1100.0, 1200.0])
cf(entity, by=None, method='direct')#

Return an entity’s cash flow statement as a table.

Rows are operating, investing and financing cash flows and the net change in cash. The direct method lists the cash received and paid by line; the indirect method starts from the profit for the year.

Parameters:
entityEntity or Group

The entity, or a group, whose consolidated books are shown.

bystr, optional

"fiscal_year" groups the periods into the fiscal years of the entity’s calendar, summing flows. The default shows one column for each period.

methodstr, default=”direct”

"direct" or "indirect". Both give the same totals; Model.render verifies it.

Returns:
Table

The statement, titled CF <entity name>.

Raises:
KeyError

At call, if method is not "direct" or "indirect".

ValueError

At call, if by is neither None nor "fiscal_year", or by="fiscal_year" has an entity without a fiscal calendar, or the periods are undated.

See also

boki.Result.pl

The profit and loss statement.

boki.Result.bs

The balance sheet.

Examples

The two methods reach the same net change in cash:

>>> import boki as b
>>> m = b.Model("Cafe", start="2027-01", periods=2, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS)
>>> co.bs.opening(cash=1000, retained_earnings=1000)
>>> sales = co.pl.revenue("Sales", 100)
>>> rent = co.pl.sga("Rent", 40)
>>> r = m.render()
>>> r.cf(co).row("Net change in cash")
[60.0, 60.0]
>>> r.cf(co).row("Net change in cash") == r.cf(co, method="indirect").row("Net change in cash")
True
display_unit(node)#

Return the unit that tables and Excel show a series in.

The unit is chosen in this order: the display= of the series; the unit a quantity literal was written in (m.input("x", 400 * MWh) shows in MWh); for a computed physical quantity (W, Wh, g, m and their per-month forms), the SI prefix that puts the row’s largest absolute value over all periods in the range 1 to 1000. The unit is the same for every period of a row.

Parameters:
nodeSeries or str

The series, or the name of a series, input or unknown of the model.

Returns:
Unit or None

The unit to show the values in, or None to show base units (a dimensionless series, or one whose unit is unknown).

Raises:
KeyError

At call, if a string names no series of the model.

See also

boki.Model.series

Set a series’ display= unit.

boki.Result.table

Shows each row in its display unit.

Notes

Values stay in base units everywhere (W, Wh, per month); this only chooses how they are shown, so arithmetic, unit checks and Excel formulas are unaffected. Money is never prefixed (the style’s money= scaling shows it) and dimensionless numbers have no unit to prefix.

Examples

>>> import boki as b
>>> from boki.units import MWh, W
>>> m = b.Model("Power", start="2027-01", periods=2, step=b.month)
>>> capacity = m.input("Capacity", 400 * MWh)
>>> load = m.series("Load", data={0: 3500 * W, 1: 1200 * W})
>>> r = m.render()
>>> r.display_unit(capacity).name, r.display_unit("Load").name, r.display_unit(m.t)
('MWh', 'kW', None)
pl(entity, by=None, detail=True)#

Return an entity’s profit and loss statement as a table.

Rows follow the entity’s layout: each kind with revenue or expense lines shows its total, and with detail=True the lines below it, followed by the subtotals (gross profit, operating profit, profit for the year). Labels follow the entity’s accounting standard and language.

Parameters:
entityEntity or Group

The entity, or a group, whose consolidated books are shown.

bystr, optional

"fiscal_year" groups the periods into the fiscal years of the entity’s calendar, summing flows. The default shows one column for each period.

detailbool, default=True

Show the lines of each kind below its total; False shows only totals and subtotals.

Returns:
Table

The statement, titled PL <entity name>.

Raises:
ValueError

At call, if by is neither None nor "fiscal_year", or by="fiscal_year" has an entity without a fiscal calendar, or the periods are undated.

See also

boki.Result.bs

The balance sheet.

boki.Result.cf

The cash flow statement.

Examples

>>> import boki as b
>>> m = b.Model("Cafe", start="2027-01", periods=2, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS)
>>> co.bs.opening(cash=1000, retained_earnings=1000)
>>> sales = co.pl.revenue("Sales", 100)
>>> rent = co.pl.sga("Rent", 40)
>>> table = m.render().pl(co)
>>> table.title, table.row("Profit for the year")
('PL Cafe', [60, 60])
table(nodes, *, where=None, unit=None, title='', by=None, entity=None, stock=())#

Return chosen series side by side as a table, one row for each series and one column for each period.

Each series is shown in its display unit (Result.display_unit), and its row is labelled with the unit when that is not the base unit, such as Generation (MWh). Printing the table, or showing it in a notebook, draws it as text.

Parameters:
nodesiterable of Series

The series to show, in row order. A scalar series repeats its value in every period. A row is labelled with the series’ name, or ? for an unnamed series.

whereSeries, optional

A condition: only the periods where it holds are shown.

unitUnit or Quantity, optional

Divide every row by this scale instead of using display units, and show no unit labels: unit=1000 * USD shows thousands of dollars. The default uses each series’ display unit.

titlestr, default=””

The table’s title, shown above the first column.

bystr, optional

"fiscal_year" groups the periods into the fiscal years of entity’s fiscal calendar: flows are summed over the year, and balances are kept at the year’s last period. The default shows one column for each period.

entityEntity, optional

The entity whose fiscal calendar groups the periods. Required with by="fiscal_year".

stockiterable of Series, default=()

Series that are balances, such as headcount or customers, which by="fiscal_year" keeps at the year’s last period instead of summing. Ledger balances and their totals are balances already.

Returns:
Table

The rows and column labels, in base units divided by each row’s display unit or by unit.

Raises:
ValueError

At call, if by is neither None nor "fiscal_year", or by="fiscal_year" has no entity with a fiscal calendar, or the periods are undated.

See also

boki.Result.pl

A profit-and-loss statement as a table.

boki.Result.__getitem__

The values of one series as a list.

Examples

A series in a physical unit is labelled with its display unit:

>>> import boki as b
>>> from boki.units import MWh, USD
>>> m = b.Model("Plant", start="2027-01", periods=3, step=b.month)
>>> generation = m.series("Generation", data={0: 400 * MWh, 1: 500 * MWh, 2: 300 * MWh})
>>> revenue = m.series("Revenue", generation / MWh * 30 * USD)
>>> r = m.render()
>>> table = r.table([generation, revenue], title="Plant")
>>> table.columns
['2027-01', '2027-02', '2027-03']
>>> [(row.label, row.unit, row.values) for row in table.rows]
[('Generation', 'MWh', [400.0, 500.0, 300.0]), ('Revenue', '', [12000.0, 15000.0, 9000.0])]

Group a monthly model by fiscal year; flows are summed and the headcount is kept at the year end:

>>> m = b.Model("Years", start="2027-01", periods=24, step=b.month)
>>> co = m.entity("Co", standard=b.IFRS, fiscal=b.fiscal("12-31"))
>>> sales = m.series("Sales", 10)
>>> headcount = m.series("Headcount", m.t + 1)
>>> table = m.render().table([sales, headcount], by="fiscal_year", entity=co, stock=[headcount])
>>> table.columns, table.row("Sales"), table.row("Headcount")
(['FY2027-12', 'FY2028-12'], [120.0, 120.0], [12.0, 24.0])
to_excel(path, style=None, sheets=None, *, scenarios=None, omit_unused_model=False, checks=None, **overrides)#

Write the model to an Excel workbook that keeps live formulas.

The workbook has an Inputs sheet, a Model sheet with one formula for each series and period, a sheet for each entity’s statements, and a Checks sheet. Cells hold formulas that refer to the inputs, so changing an input in Excel recalculates the model.

Parameters:
pathstr or path-like

The .xlsx file to write. An existing file is replaced.

styleStyle, optional

How numbers and headings look: a preset from b.styles (b.styles.banker, the default, japanese, plain or sec) or a modified copy. A style changes only how values are shown, never the model sheet’s formulas.

sheetslist, optional

Where rows go, in reading order: a list of b.sheet(name, [...]) whose entries are sections, series, b.row(...), b.block(...), b.panel(...), and b.link(...). The default writes every row to the Model sheet.

scenariossequence of str, optional

Scenario names to expose as a live Excel selector on the Inputs sheet (for example ["Base", "Bull", "Bear"]). Changing the active case cell recalculates the workbook in Excel.

omit_unused_modelbool, default=False

Drop unreachable Model-sheet rows and omit the Model sheet entirely when every placed sheet and check formula resolves without it. Remaining Model rows are listed in Report.unplaced.

checksbool, optional

Whether to write the Checks sheet. None (the default) follows style.statements.

**overrides

Settings of the style applied for this call, such as money="$mm" (scale and label of money amounts), units={series: MWh} (display units), hide=[series, ...], columns="fiscal" or "periods" and helpers="group" or "show". They are the fields of Style.

Returns:
Report

What was written: counts of formula cells (formulas), cells written as values (values) and data cells (data), the cells guarded against a circular reference (guarded), why cells fell back to values (reasons), and any Model rows left unplaced (unplaced).

Raises:
UnnamedAssumption

At call, if a data table (b.by_year, b.step, …) used in an expression has no name; name it with m.input.

EquivalenceError

At call, if a b.row(..., formula=...) or b.block(...) rewrite disagrees with boki across scenarios or perturbed inputs.

ValueError

At call, if sheets places a series twice with b.row, links a row that is not placed, names two sheets alike, or gives an unnamed series no label=; if units names a unit of another dimension; or if columns, helpers or money has a value outside its choices.

TypeError

At call, if a keyword argument is not a setting of the style.

See also

boki.Result.table

The same numbers as a table in Python.

Notes

A cell that Excel cannot compute from boki’s expression is written as a value (highlighted) and counted in reasons. Where Excel would see a circular reference that boki does not have, the cell is guarded with NA() and a CircularReferenceWarning is issued. See the Excel output and row placement notes.

Examples

Write a model with a money scale in millions, and read how many cells are formulas:

>>> import tempfile
>>> import boki as b
>>> m = b.Model("Cafe", start="2027-01", periods=3, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS)
>>> co.bs.opening(cash=1000000, retained_earnings=1000000)
>>> sales = co.pl.revenue("Sales", 100000)
>>> r = m.render()
>>> with tempfile.TemporaryDirectory() as folder:
...     report = r.to_excel(f"{folder}/cafe.xlsx", money="$mm")
>>> report.formulas > 0
True
value(node, t=None)#

Return the value of a series in one period.

Parameters:
nodeSeries

The series to read; any value is turned into a series. A name string is not looked up: use r["name"].

tint, str, or date, optional

The period: an index from 0 (negative counts from the end), a label ("2028", "2027-04") or a date inside the period. Required for a series with a value in each period; a scalar series ignores it.

Returns:
float

The value in base units, or None when the series has no value in that period.

Raises:
IndexError

At call, if the period is outside the model’s timeline.

ValueError

At call, if t is missing for a series with a value in each period, or cannot be read as a period.

TypeError

At call, if t is a bool.

See also

boki.Result.__getitem__

All the periods at once.

Notes

A bare r.value(x) is for scalar series (totals, inputs). Name the period for every other series, as in the examples.

Examples

Read one period by label, by index, and a scalar series:

>>> import boki as b
>>> m = b.Model("Plan", start="2027-01", periods=3, step=b.month)
>>> units = m.series("Units", data={0: 10, 1: 12, 2: 9})
>>> r = m.render()
>>> r.value(units, "2027-02"), r.value(units, 2), r.value(units, -1)
(12, 9, 9)
>>> r.value(units.sum())
31
boki.Result.checks#

The outcome of every check evaluated in the render, as boki.model.CheckResult objects. See the Attributes of boki.Result.

Tables#

class boki.statements.Table(title, columns, rows)#

Rows of values by period: what Result.table, Result.pl, Result.bs and Result.cf return.

A table has a title, a label for each column (the periods, or fiscal years), and rows. Printing it, or showing it in a notebook, draws it as aligned text, with nested lines indented and numbers in thousands separators. Statement rows follow the entity’s layout and language; the rows of Result.table follow the series you passed.

Parameters:
titlestr

Title shown above the first column.

columnslist[str]

Column labels: period labels, or fiscal-year labels such as "FY2027-12".

rowslist[Row]

The rows, in display order. Each row has one value for each column.

Attributes:
titlestr

Title of the table, such as "PL Cafe".

columnslist[str]

Column labels.

rowslist[Row]

The rows, each with a label, values, level (1 for a line below a total), stock and unit.

See also

boki.Result.table

A table of chosen series.

boki.Result.pl

A profit and loss statement as a table.

Notes

Values are in base units divided by the row’s display unit or by the unit given to Result.table. Only Result methods create a table.

Examples

>>> import boki as b
>>> m = b.Model("Cafe", start="2027-01", periods=2, step=b.month)
>>> co = m.entity("Cafe", standard=b.IFRS)
>>> co.bs.opening(cash=1000, retained_earnings=1000)
>>> sales = co.pl.revenue("Sales", 100)
>>> table = m.render().pl(co)
>>> table.title, table.columns
('PL Cafe', ['2027-01', '2027-02'])
>>> [(row.label, row.level, row.values) for row in table.rows[:2]]
[('Revenue', 0, [100, 100]), ('Sales', 1, [100, 100])]
class boki.statements.Row(label, values, stock=False, level=0, unit='')#

One row of a Table: a label and a value for each column.

Parameters:
labelstr

Name shown at the start of the row.

valueslist[Any]

One value for each column of the table, in column order. None is a missing value.

stockbool | str

How the row groups by fiscal year: False for a flow (summed), True for a balance (the value at the year’s last period), "first" for an opening balance (the value at the year’s first period).

levelint

Indentation: 0 for totals and subtotals, 1 for the lines below a total.

unitstr

The display unit named after the label, when the values are not in base units; "" otherwise.

Attributes:
labelstr

Name shown at the start of the row.

valueslist[Any]

One value for each column of the table.

stockbool | str

How the row groups by fiscal year.

levelint

Indentation of the row.

unitstr

The display unit named after the label, or "".

See also

boki.statements.Table

The rows of a statement or of Result.table.

Examples

>>> import boki as b
>>> from boki.units import MWh
>>> m = b.Model("Plant", start="2027-01", periods=2, step=b.month)
>>> generation = m.series("Generation", data={0: 400 * MWh, 1: 500 * MWh})
>>> row = m.render().table([generation]).rows[0]
>>> row.label, row.unit, row.values, row.level
('Generation', 'MWh', [400.0, 500.0], 0)

Excel output (Result.to_excel, Report and the export warnings) is on the output page.

Checks#

class boki.model.CheckResult(name, level, passed, periods, detail)#

Outcome of one check in one render: whether it held, where it failed, and how to report it.

Read the results of a render from r.checks. A check at level "off" is not evaluated and has no result.

Parameters:
namestr

The check’s message, such as "Minimum cash".

levelstr

"error" or "warn". With render(checks="warn") an "error" check reports as "warn".

passedbool

Whether the check held in every period it was evaluated.

periodslist[str]

Labels of the periods in which it failed; empty when it passed.

detailstr

The sentence that reports the outcome: the name, and for a failure the periods and, for a comparison, the worst period with both sides.

Attributes:
namestr

The check’s message.

levelstr

"error" or "warn".

passedbool

Whether the check held in every evaluated period.

periodslist[str]

Labels of the periods in which it failed.

detailstr

The sentence that reports the outcome.

See also

boki.Model.check

Declare a check.

boki.Result.checks

The results of a render.

boki.CheckFailed

Raised when an "error" check fails.

Examples

>>> import boki as b
>>> m = b.Model("Checks", start="2027-01", periods=3, step=b.month)
>>> cash = m.series("Cash", data={0: 50, 1: -20, 2: 30})
>>> m.check(cash >= 0, "Cash is not negative", level="off")
>>> m.check(cash >= -50, "Overdraft limit")
>>> check = m.render().checks[0]
>>> check.name, check.level, check.passed, check.periods
('Overdraft limit', 'error', True, [])
class boki.CheckFailed(message, result, failures)#

Error raised by Model.render when a check at level "error" fails.

Model.render computes everything first, so the exception carries the complete Result for inspection. It subclasses AssertionError, so a test runner reports it as a failed assertion.

Parameters:
messagestr

The text of the error: "checks failed:" followed by one line for each failed check.

resultResult

The complete result of the render that failed its checks.

failureslist[CheckResult]

The failed checks at level "error".

Attributes:
resultResult

The complete result: e.result[cash], e.result.pl(co).

failureslist[CheckResult]

The failed checks at level "error", each with its name, failing periods and detail.

See also

boki.Model.check

Declare a check and its level.

boki.model.CheckResult

One check’s outcome.

Examples

Read the failure and the values behind it:

>>> import boki as b
>>> m = b.Model("Cash", start="2027-01", periods=3, step=b.month)
>>> cash = m.series("Cash", data={0: 50, 1: -20, 2: 30})
>>> m.check(cash >= 0, "Cash is not negative")
>>> try:
...     m.render()
... except b.CheckFailed as error:
...     print(error.failures[0].periods)
...     print(error.result[cash])
['2027-02']
[50, -20, 30]