Model#
A Model holds the timeline, inputs, named series, entities and checks; render()
evaluates it and returns a Result. Series are described on the Series page, and entities and groups on
their own pages.
- class boki.Model(name, start=None, end=None, periods=None, step=<Unit month>, timeline=None, *, actual_until=None)#
Business-plan model: a timeline, assumptions, named series, entities with books, and checks.
A model is built by declaring things on it and nothing is computed until Model.render. Declaring (Model.input, Model.series, Model.entity, Model.check, …) builds expressions and checks units; Model.render evaluates them and returns a Result to read values, statements and the Excel workbook from. A model can be rendered again with other inputs or scenarios.
- Parameters:
- namestr
Name of the model. It appears in error messages.
- startdate | str | int | None
First period. A date or date text (
"2027-04") makes dated periods; an integer such as2027makes undated periods labelled"2027","2028", …, which needsperiods. Required unlesstimelineis given.- enddate | str | None
Date text such as
"2029-03". Withoutperiods, the model has every period that starts in or before the month ofend. Ignored whenperiodsortimelineis given.- periodsint | None
Number of periods. Required unless
endortimelineis given.- stepUnit | Quantity
Length of each period:
b.month(the default),b.year, or a multiple such as3 * b.month. It must be a time. Ignored whentimelineis given.- timelineTimeline | None
A ready-made timeline, for periods of different lengths (boki.timeline). It replaces
start,end,periodsandstep.- actual_untildate | str | int | None
Last historical (actual) period, as a period index, label (
"2024"), or date. Periods up to and includingactual_untilare historical actuals; periods after it are forecast periods whose opening balances carry forward from the last actual period.None(the default) treats every period as a forecast period.
- Attributes:
- namestr
Name of the model.
- timelineTimeline
The model’s periods.
- actual_untilint or None
Zero-based period index of the last historical period, or
Nonewhen the model has no historical periods.- is_actualSeries
Boolean series that is
Truein periods up to and includingactual_until, andFalseotherwise.- is_forecastSeries
Boolean series that is
Truein forecast periods (afteractual_until, or every period whenactual_untilisNone).- tSeries
Zero-based index of each period (0, 1, 2, …), dimensionless.
- dateSeries
First day of each period, a date series. It is missing for undated periods.
- period_endSeries
First day after each period, which is the start of the next one.
m.period_end - 1 * b.dayis the last day.- period_lengthSeries
Length of each period in months, so a quarterly period is 3. Multiply a rate per month by it to get the amount in the period.
- entitieslist
The entities of the model, in the order Model.entity created them.
- groupslist
The groups of the model, in the order Model.group created them.
See also
boki.timelinePeriods of varying length.
boki.ResultWhat Model.render returns.
Notes
Construction raises ValueError if
startis an integer andperiodsis missing, ifstartis a date and neitherperiodsnorendis given, if a date cannot be parsed, or if the model would have no period. It raises UnitError ifstepis not a time.A plain number used as a rate is per period:
0.03is 3% per period, whether the period is a month or a year. A rate per time (0.12 / b.year) is converted by the length of each period; seeperiod_length.Models hold closures, so they cannot be pickled. See the model and periods guide.
Examples
A three-month model with an assumption and two series, read from a render:
>>> import boki as b >>> m = b.Model("Coffee", start="2027-01", periods=3, step=b.month) >>> cups = m.input("Cups", 100) >>> price = m.series("Price", data={0: 3, 1: 3, 2: 4}) >>> revenue = m.series("Revenue", cups * price) >>> r = m.render() >>> r[revenue] [300, 300, 400] >>> r.value(revenue, "2027-03") 400
Annual periods starting in January are labelled by year, and
endincludes the last period that starts in its month:>>> m = b.Model("Annual", start="2027-01", end="2029-06", step=b.year) >>> [p.label for p in m.timeline.periods] ['2027', '2028', '2029'] >>> m.n 3
- check(cond, message, level='error')#
Declare a condition that must hold in every period, such as
cash >= 0.A check is a statement the modeler makes about the plan. A failure at the default level stops Model.render with CheckFailed, which still carries the complete result. The result of every check is listed in
r.checks, and the Excel output has a Checks sheet.- Parameters:
- condSeries
The condition, usually a comparison (
cash >= 5 * USD) or a combination with&,|and~. It fails in a period where it is false. A period where it is missing is not evaluated.- messagestr
Name of the check, shown in the failure report and in
r.checks.- levelstr, default=”error”
"error": a failure raises CheckFailed."warn": a failure only warns, for a benchmark the plan may miss."off": not evaluated and not reported.
- Raises:
- ValueError
At construction, if
levelis not"error","warn"or"off".- TypeError
At construction, if
condhas a type a series expression cannot use.
See also
boki.Model.renderEvaluates the checks;
checks="warn"downgrades the errors while exploring.boki.CheckFailedRaised for a failed
"error"check.
Notes
The failure message names the failing periods and, for a comparison of two series, both sides in the period of the largest violation. See checks stop the render.
Examples
A failing check stops the render and reports the worst period:
>>> 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) checks failed: Cash is not negative (fails in 2027-02; worst 2027-02: Cash -20 vs 0)
- entity(name, standard=None, fiscal=None, layout=None, currency=None, tax_rate=None)#
Create an entity: a company with its own double-entry books.
The entity holds the
pl,bsandcfmakers of its layout, from which the line items of the statements are created (co.pl.revenue("Sales", 100)).- Parameters:
- namestr
Name of the entity, unique among the model’s entities and groups. It titles the entity’s statements.
- standardStandard, optional
Accounting standard:
b.JGAAP(the default),b.IFRSorb.USGAAP. It sets the account names, their order and the standard-specific treatments.- fiscalFiscal, optional
Fiscal calendar from
b.fiscal(year_end), such asb.fiscal("03-31"). Statements and tables read withby="fiscal_year"need it. The default has no fiscal calendar.- layoutLayout, optional
Industry layout such as
b.layouts.bank. The default is the standard’s general layout.- currencyUnit, optional
Functional currency, such as
JPY. The default lets the first amount booked decide it.- tax_ratescalar or Series, optional
Default tax rate for deferred taxes, a dimensionless ratio such as
0.3for 30%.
- Returns:
- Entity
The new entity. It is also appended to
m.entities.
- Raises:
- ValueError
At construction, if an entity or a group with this name already exists in the model.
See also
boki.Model.groupCombine entities into consolidated books.
Notes
The entity’s postings balance by construction.
Model.renderverifies that the balance sheet balances and that the direct and indirect cash flows agree with each other and with the change in cash, and raises LedgerError otherwise. See double-entry bookkeeping.Examples
A company with an opening balance, a revenue line and a cost, in a monthly model:
>>> 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) >>> sales = co.pl.revenue("Sales", 100) >>> rent = co.pl.sga("Rent", 40) >>> r = m.render() >>> r[co.pl.net_income] [60, 60, 60] >>> r.value(co.bs.cash, "2027-03") 1180.0
- fx(base, quote, *, closing, average, opening)#
Register the exchange rates of one currency pair and return them.
Rates are quoted as units of
quoteper one unit ofbase. Entities with different functional currencies use the rates to translate amounts between them (consolidation, intercompany trades).- Parameters:
- baseUnit
The currency of one unit, such as
b.units.USD.- quoteUnit
The currency the rates are measured in, such as
b.units.JPY. It must differ frombase.- closingscalar, Quantity, Series, dict, list, or tuple
Rate at the end of each period, in
quoteperbase. A plain number is the same rate every period. A dict maps periods to rates; a list or tuple has one rate for each period of the model.- averagescalar, Quantity, Series, dict, list, or tuple
Average rate over each period, in
quoteperbase, in the same forms asclosing.- openingscalar, Quantity, or Series
One rate at the model start, in
quoteperbase. It must be a single value.
- Returns:
- FxPair
The registered rates, as series named
<base>/<quote> closingand so on.
- Raises:
- TypeError
At construction, if
baseorquoteis not a Unit, oropeningis not a single value.- ValueError
At construction, if
baseandquoteare the same currency, the pair is already registered, or a list has the wrong number of rates.- UnitError
At construction, if a rate has units other than
quoteperbase.- CheckFailed
At evaluation, if a rate is not positive in some period.
See also
boki.model.FxPairThe registered rates.
Examples
>>> import boki as b >>> from boki.units import JPY, USD >>> m = b.Model("FX", start="2027-01", periods=2, step=b.month) >>> pair = m.fx(USD, JPY, closing=[150, 152], average=151, opening=149) >>> r = m.render() >>> r[pair.closing] [150.0, 152.0]
- group(name, parent)#
Create a group of entities under a parent, whose consolidated books the statements read.
Add subsidiaries to the group with
g.own(sub, method="consolidate").r.pl(g),r.bs(g)andr.cf(g)then show the consolidated statements.- Parameters:
- namestr
Name of the group, unique among the model’s entities and groups.
- parentEntity
The entity that owns the group, normally the parent company of the subsidiaries. It must be an entity of this model.
- Returns:
- Group
The new group. It is also appended to
m.groups.
- Raises:
- ValueError
At construction, if an entity or a group with this name already exists in the model, or
parentis not an entity of this model.
See also
boki.Model.entityCreate an entity with its own books.
Notes
See consolidation for how groups combine subsidiaries.
Examples
>>> import boki as b >>> m = b.Model("Group", start="2027-01", periods=2, step=b.year) >>> parent = m.entity("Parent", standard=b.IFRS) >>> sub = m.entity("Sub", standard=b.IFRS) >>> g = m.group("Holdings", parent=parent) >>> g.own(sub, method="consolidate") >>> g.name, [group.name for group in m.groups] ('Holdings', ['Holdings'])
- input(name, default, scenarios=None, choices=None, *, display=None, source=None, note=None)#
Declare a named assumption with a default value.
An input is a series you can change without editing the model: per render with
render(inputs=...)orrender(scenario=...), and in the Inputs sheet of the Excel output. It shows in the unit its default was written in (400 * MWhshows in MWh), or indisplay.- Parameters:
- namestr
Name of the input, unique among the model’s inputs and series.
- defaultscalar, Quantity, Series, or str
Value used unless a scenario or
render(inputs=...)replaces it. A plain number is dimensionless; as a rate it is per period (0.03is 3% per period, whether the period is a month or a year). A Quantity carries a unit (3000 * JPY). A rate per time (0.12 / b.year) is stored per month and becomes per period when multiplied bym.period_length. A series such asb.by_year({...})gives a value in each period. A string is one ofchoices.- scenariosdict, optional
Maps a scenario name to its value, in any form
defaulttakes.render(scenario=name)uses it.- choiceslist, tuple, or dict, optional
The allowed values. A list or tuple restricts the value to its members. A dict maps a choice name to its value: the input’s value is a name, and the input reads as the mapped value.
- displayUnit or Quantity, optional
Unit to show the input in, of the same dimension as its value. A different time base is allowed, such as
1 / b.yearfor a monthly rate.- sourcestr, optional
Citation or provenance for the assumption, such as
"FY2024 10-K p.42". Written to the Excel Inputs sheet when any input carries a source or note.- notestr, optional
Free-text rationale or note for the assumption.
- Returns:
- Input
The new input, a series that is scalar when
defaultis a single value.
- Raises:
- ValueError
At construction, if an input or a series with this name already exists. At evaluation, if the chosen value is not among
choices.- TypeError
At construction, if
defaulthas a type a series expression cannot use, such as a list, ordisplayis not a unit.- UnitError
At construction, if
displayhas other dimensions than the value. At evaluation, if a Quantity override has other dimensions than the input.
See also
boki.Model.seriesA named series computed from an expression.
boki.Model.renderChoose a scenario or override inputs for one render.
Examples
An assumption with a scenario, and an override for one render:
>>> import boki as b >>> m = b.Model("Plan", start="2027-01", periods=3, step=b.month) >>> churn = m.input("Churn rate", 0.03, scenarios={"Bear": 0.05}) >>> m.render()[churn] 0.03 >>> m.render(scenario="Bear")[churn] 0.05 >>> m.render(inputs={"Churn rate": 0.01})[churn] 0.01
A rate per year is per month internally; multiplying by the period length gives the rate for each period:
>>> m = b.Model("Rates", start="2027-01", periods=2, step=3 * b.month) >>> rate = m.input("Interest rate", 0.12 / b.year) >>> [round(v, 6) for v in m.render()[rate * m.period_length]] [0.03, 0.03]
- property n#
Number of periods in the model.
- Returns:
- int
The length of the timeline.
Examples
>>> import boki as b >>> b.Model("Plan", start="2027-01", periods=36, step=b.month).n 36
- render(scenario=None, inputs=None, fix=None, checks=None)#
Evaluate the model and return its result.
Everything is computed first: the solves, the ledger tie-outs, and the checks. Then failed
"warn"checks issue warnings and failed"error"checks raise CheckFailed, whoseresultis the complete Result. A model can be rendered any number of times with different arguments.- Parameters:
- scenariostr, optional
Name of a scenario. Inputs declared with
scenarios=take the value of this scenario; the others keep their default.- inputsdict, optional
Overrides as
{input or name: value}, which take precedence over scenarios and defaults. A value is a number, a Quantity in the input’s unit, a series, or a choice name.- fixdict, optional
{unknown: value}: use this value for the unknown and skip solving for it, for example a pasted result of the source spreadsheet.- checksstr, optional
"warn"downgrades every"error"check, yours and the built-in ones, to a warning for this render, while exploring a plan that does not hold together yet. Checks at level"off"stay off. The defaultNonekeeps the levels.
- Returns:
- Result
The values, statements and Excel output of this render.
- Raises:
- ValueError
At call, if
checksis neitherNonenor"warn".- KeyError
At call, if
inputsnames an input that does not exist.- CheckFailed
At evaluation, if a check at level
"error"fails, including the built-in check that cash is not negative.- LedgerError
At evaluation, if an entity’s books do not tie out: the opening or a closing balance sheet does not balance, or the direct and indirect cash flows disagree with each other or with the change in cash.
- UnitError
At evaluation, if a Quantity in
fixhas other dimensions than its unknown.
See also
boki.Model.checkDeclare a check.
boki.Model.solveDeclare the equations solved during a render.
boki.ResultThe object returned.
Notes
Evaluation errors of the series the render reads, such as a division by zero, a value outside a
choiceslist, or CycleError, are raised here or when the result is read.Examples
Render a scenario, and downgrade a failing check to a warning:
>>> import boki as b >>> m = b.Model("Plan", start="2027-01", periods=3, step=b.month) >>> growth = m.input("Growth", 0.0, scenarios={"Bull": 0.1}) >>> sales = m.series("Sales", 100 * (1 + growth) ** m.t) >>> m.render()[sales] [100.0, 100.0, 100.0] >>> [round(v, 2) for v in m.render(scenario="Bull")[sales]] [100.0, 110.0, 121.0] >>> cash = m.series("Cash", data={1: -5}) >>> m.check(cash >= 0, "Cash is not negative") >>> import warnings >>> with warnings.catch_warnings(record=True) as caught: ... warnings.simplefilter("always") ... r = m.render(checks="warn") >>> r.checks[0].level, r.checks[0].passed, len(caught) ('warn', False, 1)
- series(name=None, expr=None, *, data=None, unit=None, display=None)#
Create a named series from an expression, from period data, or from a function of the period.
There are four forms.
m.series("x", expr)names an expression.m.series("x")declares a series to define later with Named.define.m.series("x", data={...})holds values at chosen periods and 0 elsewhere.@m.series(or@m.series(unit=...)) turns a Python function of the period index into a series; inside it,x[t]reads other series as numbers and ordinaryifworks.- Parameters:
- namestr or callable, optional
Name of the series, unique in the model. A function, when
@m.seriesis applied to it, becomes the series and is named after itself. May be omitted withdata=(an unnamed series) or when returning a decorator.- exprSeries, Quantity, or number, optional
The expression. Leave it out to declare the series and define it later.
- datadict, optional
Values at selected periods, as
{period: value}: the period is an index, a label ("2028") or a date, and the value a number or Quantity. Other periods are 0. A series made withdata=is fixed and cannot be defined later.- unitUnit, optional
The unit the series must have, such as
JPY. It is checked against the expression or the function’s return values; without it the series takes the expression’s unit. Ignored withdata=.- displayUnit or Quantity, optional
Unit to show the series in, of the same dimension as its values (
MWh, or1 / b.yearfor a monthly rate). Without it a series defined as a quantity shows in the unit it was written in, and a computed physical quantity (W, Wh, g, m) gets an SI prefix chosen from its values.
- Returns:
- Series or callable
The Named series for the first two forms. For
data=a series of the fixed values, and for@m.seriesthe series that the function computes; both read like any other series. Called with onlyunit=ordisplay=, it returns the decorator to apply to a function.
- Raises:
- ValueError
At construction, if a series with this name already exists in the model.
- UnitError
At construction, if
exprhas other units thanunit, ifdisplayhas other dimensions than the series, or if the values ofdatamix units.- TypeError
At construction, if
expror a data value has a type a series expression cannot use, such as a list, orunitordisplayis not a unit.
See also
boki.Model.inputA named assumption that scenarios and renders can change.
boki.series.Named.defineDefine a declared series later.
Examples
The four forms in a monthly model:
>>> import boki as b >>> m = b.Model("Forms", start="2027-01", periods=3, step=b.month) >>> units = m.series("Units", data={0: 10, 1: 12}) >>> revenue = m.series("Revenue", units * 30) >>> margin = m.series("Margin") >>> _ = margin.define(revenue * 0.2) >>> @m.series ... def doubled(t): ... return units[t] * 2 >>> r = m.render() >>> r[revenue], r[margin], r[doubled] ([300, 360, 0], [60.0, 72.0, 0.0], [20, 24, 0])
- solve(unknowns, equations, *, integer=False, min=None, tol=1e-09, max_iter=500)#
Declare the equation that determines one or more unknowns; render solves it.
The equation’s form selects the method.
u == expression, with the unknown alone on the left, iterates a fixed point (use it for circular references such as interest on an average balance). Any other==for a scalar unknown, such asnpv == 0orvalue == price, is a goal seek by the secant method, as in Excel. A per-period unknown solves each period:==by secant, and>=/<=withinteger=Truefor the smallest integer that satisfies the condition.- Parameters:
- unknownsUnknown, or list or tuple of Unknown
The unknowns to solve for, from Model.unknown.
- equationsSeries, or list or tuple of Series
One equation for each unknown, in the same order, built by comparing series with
==,>=or<=.- integerbool, default=False
Search whole numbers for per-period
>=/<=conditions.- minfloat, optional
Lowest value tried in the integer search of each period. The default is 0.
- tolfloat, default=1e-9
Convergence tolerance. Fixed-point iteration stops when no unknown moves by more than
tol(relative to its size, for values above 1). A goal seek stops when the equation’s two sides differ by at mosttoltimes the larger of 1 and the right side. A per-period secant needs the sides to differ by less thantol.- max_iterint, default=500
Maximum iterations for each solve.
- Raises:
- ValueError
At construction, if the number of equations differs from the number of unknowns.
- TypeError
At construction, if an unknown is not made by Model.unknown, if an equation is not a comparison, or if a scalar unknown’s equation is not written with
==. At evaluation, if several scalar unknowns are solved and an equation is not writtenu == expression.- ArithmeticError
At evaluation, if the solve does not converge within
max_iteriterations, the secant stalls, or no integer satisfies a per-period condition.- NotImplementedError
At evaluation, if a per-period unknown has an equation other than
==or an integer>=/<=.
See also
boki.Model.unknownDeclare an unknown.
boki.Model.renderSolve and evaluate;
fix=skips the solve for chosen unknowns.
Notes
Cycles are detected before evaluation. Only values passed to solve are solved; a cycle that is not wrapped in solve raises CycleError. When a cycle has several solutions, the
initof the unknown picks one. See Solving.Examples
A fixed point and a goal seek on scalar unknowns:
>>> import boki as b >>> m = b.Model("Solve", start="2027-01", periods=2, step=b.year) >>> debt = m.unknown("Debt", init=100) >>> m.solve(debt, debt == 0.5 * debt + 10) >>> rate = m.unknown("Rate", init=1) >>> m.solve(rate, 3 * rate == 12) >>> r = m.render() >>> round(r[debt], 6), round(r[rate], 6) (20.0, 4.0)
The smallest whole headcount that covers demand in each period:
>>> m = b.Model("Hiring", start="2027-01", periods=2, step=b.month) >>> hires = m.unknown("Hires", per_period=True) >>> demand = m.series("Demand", data={0: 25, 1: 40}) >>> m.solve(hires, hires * 10 >= demand, integer=True, min=0) >>> m.render()[hires] [3, 4]
- unknown(name, init=0.0, per_period=None, unit=None)#
Declare a value that Model.solve will find.
Use an unknown for a number the model must determine, such as the debt amount that meets a covenant, or the headcount that covers demand. Declaring it does not solve it: pass it to Model.solve with an equation.
- Parameters:
- namestr
Name of the unknown, unique among the model’s series.
- initscalar or Quantity, default=0.0
Starting value of the search, in the unit of the unknown. A Quantity such as
100 * USDalso fixes the unit. When there is no solve (orfix=replaces it), the unknown keeps this value. It selects among solutions when an equation has several.- per_periodbool, optional
Truegives one value for each period;FalseorNone(the default) gives one value for the whole model.- unitUnit, optional
Unit of the value, such as
USD. The default is the unit ofinit.
- Returns:
- Unknown
The new unknown, a series that is scalar unless
per_periodis true.
- Raises:
- ValueError
At construction, if a series with this name already exists in the model.
- TypeError
At construction, if
unitis not a unit, orinithas a type a series expression cannot use.
See also
boki.Model.solveFind the value of an unknown.
boki.Model.inputA value you choose instead.
Examples
A scalar unknown with a starting value, and a per-period unknown in a unit:
>>> import boki as b >>> from boki.units import USD >>> m = b.Model("Unknowns", start="2027-01", periods=2, step=b.month) >>> debt = m.unknown("Debt", init=100 * USD) >>> hires = m.unknown("Hires", per_period=True) >>> m.render()[debt], m.render()[hires] (100.0, [0.0, 0.0])
- boki.Model.date#
First day of each period, a date series; missing for an undated model. See the Attributes of
boki.Model.
- boki.Model.period_end#
First day after each period, which is the start of the next one. See the Attributes of
boki.Model.
Inputs and unknowns#
- class boki.model.Input(name, default, scenarios, choices, display=None, source=None, note=None)#
Named assumption of the model, with a default, optional scenarios and optional allowed values.
Model.input creates inputs. An input is a Series that is scalar when its default is a single value and has a value per period when the default is a series (such as
b.by_year({...})). Its value is chosen at render time, in this order:render(inputs={...}), then the scenario named byrender(scenario=...), then the default. The input shows in the unit its default was written in (400 * MWhshows in MWh), or indisplay.- Parameters:
- namestr
Name of the input, unique among the model’s inputs and series.
- defaultSeries | Quantity | float | str
The value used when no override applies. A string is a choice; see
choices.- scenariosdict | None
Values by scenario name, in any form
defaulttakes.Nonemeans no scenarios.- choiceslist | tuple | dict | None
The allowed values: a list or tuple of them, or a dict that maps a choice name to its value.
Noneallows any value.- displayUnit | None
Unit to show the input in. It must have the dimensions of the value.
- sourcestr | None
Citation or provenance for the assumption, such as
"FY2024 10-K p.42". Shown in the Excel Inputs sheet.- notestr | None
Free-text rationale or comment for the assumption.
- Attributes:
- namestr
Name of the input.
- defaultSeries | Quantity | float | str
The default value, as given.
- scenariosdict
Values by scenario name; empty when there are none.
- choiceslist, tuple, dict, or None
The allowed values, as given;
Nonewhen any value is allowed.- sourcestr or None
Citation or provenance string, or
None.- notestr or None
Free-text note, or
None.
See also
boki.Model.inputCreate an input.
boki.Model.renderChoose the scenario and override inputs for one render.
boki.model.UnknownA value found by solving instead of chosen.
Notes
Result.to_excelwrites the inputs on an Inputs sheet, and the formulas refer to their cells, so changing an assumption in Excel changes the result. See the inputs guide.Examples
>>> import boki as b >>> m = b.Model("Plan", start="2027-01", periods=2, step=b.month) >>> churn = m.input("Churn rate", 0.03, scenarios={"Bear": 0.05}) >>> m.render()[churn], m.render(scenario="Bear")[churn], m.render(inputs={churn: 0.01})[churn] (0.03, 0.05, 0.01)
- class boki.model.Unknown(name, init, per_period, unit)#
Value that Model.solve finds, instead of one you choose.
Model.unknown creates unknowns. An unknown is scalar (one value for the whole model) unless it was declared with
per_period=True, which gives one value per period. Before solving, and in a render without a solve, it has its initial value. Use it in expressions like any other series; the equation passed to Model.solve fixes it.- Parameters:
- namestr
Name of the unknown, unique among the model’s series.
- initSeries | Quantity | float
Starting value of the search, a number or a Quantity (a constant, not a series).
- per_periodbool
Whether the unknown has a value in each period (
True) or one value (False).- unitUnit | Dims | None
Unit of the value.
Nonetakes the unit ofinit.
- Attributes:
- namestr
Name of the unknown.
- initfloat
Starting value in base units, as a plain number.
See also
boki.Model.unknownCreate an unknown.
boki.Model.solveSolve for unknowns.
boki.model.InputA value you choose.
Examples
>>> import boki as b >>> m = b.Model("Solve", start="2027-01", periods=2, step=b.year) >>> debt = m.unknown("Debt", init=100) >>> m.solve(debt, debt == 0.5 * debt + 10) >>> round(m.render()[debt], 6) 20.0
Timeline and periods#
- class boki.model.Timeline(periods)#
Ordered periods of a model, each with its own length in months.
A model’s timeline is
m.timeline. Build one by giving Model astart, a step and a count, or pass your own withModel(timeline=...): Timeline.regular for equal periods and boki.timeline for periods of varying length.- Parameters:
- periodslist[Period]
The periods in time order. At least one is needed.
- Attributes:
- periodslist[Period]
The periods in time order.
- nint
Number of periods.
- Raises:
- ValueError
At construction, if
periodsis empty.
See also
boki.timelinePeriods of varying length.
boki.ModelA model, which holds its timeline.
Examples
>>> import boki as b >>> m = b.Model("Plan", start="2027-04", periods=3, step=b.year) >>> m.timeline.n 3 >>> [period.label for period in m.timeline.periods] ['2027-04', '2028-04', '2029-04']
- classmethod regular(start, step, n=None, end=None)#
Return a timeline of equal periods.
- Parameters:
- startdate, str, or int
First period. A date or date text (
"2027-04") makes dated periods. An integer such as2027makes undated periods labelled"2027","2028", … and needsn.- stepUnit or Quantity
Length of each period:
b.month,b.year, or a multiple such as3 * b.month. It must be a time.- nint, optional
Number of periods. When given,
endis ignored.- enddate or str, optional
Date text such as
"2029-03". Withoutn, the timeline has every period that starts in or before the month ofend.
- Returns:
- Timeline
The periods. Annual periods that start in January are labelled by calendar year (
"2027"); other dated periods by their first month ("2027-04").
- Raises:
- ValueError
At construction, if
startis an integer andnis missing; ifstartis a date and neithernnorendis given or a date cannot be parsed; or if the timeline would have no period.- UnitError
At construction, if
stepis not a time.
See also
boki.timelinePeriods of varying length.
Examples
Four quarters, from a start and from an end:
>>> import boki as b >>> from boki.model import Timeline >>> [p.label for p in Timeline.regular("2027-01", 3 * b.month, 4).periods] ['2027-01', '2027-04', '2027-07', '2027-10'] >>> Timeline.regular("2027-01", 3 * b.month, end="2027-12").n 4
- class boki.model.Period(start, months, label, end_date=None)#
One period of a model’s timeline: when it starts, how long it is, and what it is called.
Periods come from Timeline; read them from
m.timeline.periods. Periods of one model need not have the same length (see boki.timeline).- Parameters:
- startdate | None
First day of the period, or
Nonefor an undated model (one built with an integerstart).- monthsint
Length of the period in months.
- labelstr
Name of the period, used to select it (
r.value(x, "2028")) and as the column heading.- end_datedate | None
First day after the period.
None, the default, computes it fromstartandmonths.
- Attributes:
- startdate | None
First day of the period, or
Nonefor an undated model.- monthsint
Length of the period in months.
- labelstr
Name of the period:
"2027"for a 12-month period starting in January,"2027-04"for other dated periods, and the integer text for an undated model.- end_datedate | None
First day after the period, as given at construction;
Nonewhen it is computed. Use Period.end.
See also
boki.model.TimelineThe periods of a model, in order.
boki.Model.period_endThe end of each period as a series.
Examples
The second quarter of a quarterly model:
>>> import boki as b >>> m = b.Model("Quarters", start="2027-01", periods=4, step=3 * b.month) >>> p = m.timeline.periods[1] >>> p.label, p.start, p.end, p.months ('2027-04', datetime.date(2027, 4, 1), datetime.date(2027, 7, 1), 3)
- property end#
First day after the period, which is the start of the next period.
- Returns:
- date or None
The explicit
end_dateif one was given, elsestartplusmonths(a day past the month’s end is clamped).Nonefor an undated period. The last day of the period is one day earlier.
Examples
>>> import boki as b >>> m = b.Model("Months", start="2027-01", periods=2, step=b.month) >>> [p.end for p in m.timeline.periods] [datetime.date(2027, 2, 1), datetime.date(2027, 3, 1)]
- boki.timeline(start, segments)#
Return a timeline whose periods change length, such as monthly during construction and quarterly after.
Pass the result to
Model(timeline=...). Each segment adds a run of equal periods that follows the previous one. Periods are labelled by their first month ("2027-04").- Parameters:
- startdate or str
First day of the first period, for example
"2015-09".- segmentslist of tuple
(count, step)pairs in time order:countperiods of lengthstep, a time such asb.month,b.yearor3 * b.month.
- Returns:
- Timeline
The periods of all segments in order.
- Raises:
- UnitError
At construction, if a step is not a time.
- ValueError
At construction, if the date cannot be parsed or no segment has a period.
See also
boki.model.Timeline.regularEqual periods.
boki.ModelTakes the timeline with
timeline=.
Examples
Three monthly periods and then two quarterly ones;
m.period_lengthgives each period’s months:>>> import boki as b >>> t = b.timeline("2027-01", [(3, b.month), (2, 3 * b.month)]) >>> m = b.Model("Mixed", timeline=t) >>> [p.label for p in m.timeline.periods] ['2027-01', '2027-02', '2027-03', '2027-04', '2027-07'] >>> m.render()[m.period_length] [1, 1, 1, 3, 3]
- boki.date(x)#
Return a date from a date, a string such as
"2027-04", or a year.This is the parser behind every date argument of boki (
start=,end=, period keys,by_yearkeys), sob.date("2027-04")shows what a date string means. A missing month or day is January or the 1st.- Parameters:
- xdate, str, or int
A datetime.date (returned as is), or text of year, month and day separated by
-or/:"2028","2027-04","2027/04/15". An integer year such as2028is read as"2028".
- Returns:
- date
The datetime.date: January 1 of the year, or the 1st of the month, when the text has fewer parts.
- Raises:
- ValueError
At construction, if the text is not made of integer year, month and day, or the date does not exist (for example month 13).
See also
boki.timelineBuild periods of varying length from a start date.
Examples
>>> import boki as b >>> b.date("2027-04") datetime.date(2027, 4, 1) >>> b.date("2027/04/15") datetime.date(2027, 4, 15) >>> b.date(2028) datetime.date(2028, 1, 1)
Errors#
- class boki.CycleError(chain, periods=None)#
Error raised when a series depends on itself in the same period.
The message names the series in the cycle and the period, and says how to break it: read an earlier period with
x.lag(1), or wrap the loop in Model.solve. A circular reference is found when the values are read, by Model.render or byr[x]andr.value(x, period). It subclasses RecursionError.- Parameters:
- chainlist[tuple[Series, int | None]]
The series and period index of each step of the cycle, from the first repeated step to the request that closed the loop. The period is
Nonefor a scalar series. Unnamed intermediate expressions are included.- periodslist[Period] | None
The model’s periods, used to write period labels in the message. The default shows period indices.
- Attributes:
- chainlist[tuple[Series, int | None]]
The steps of the cycle, as given at construction.
See also
boki.Model.solveSolve a deliberate circular reference.
boki.Series.lagRead an earlier period to break a cycle.
Examples
Two series defined in terms of each other:
>>> import boki as b >>> m = b.Model("Cycle", start="2027-01", periods=2, step=b.month) >>> a = m.series("A") >>> c = m.series("C", a + 1) >>> _ = a.define(c + 1) >>> r = m.render() >>> try: ... r[a] ... except b.CycleError as error: ... print(str(error).splitlines()[0]) circular reference: A -> C -> A (in 2027-01)