Standard library#

boki.lib holds financial formulas that follow published definitions, such as discounting, returns, cost of capital, tax depreciation, and option value. They build ordinary series, so they take scalars, quantities, and series, and their results work in expressions and in Excel output. Rates are dimensionless and per period unless a function says otherwise: 0.01 is 1% per period whether the period is a month or a year. See the conventions for the timing of flows, year zero, and signs.

Growth and lookup#

boki.lib.compound(x0, rate)#

Return a series that starts at x0 and grows by rate in each period after the first.

Parameters:
x0scalar, Quantity, or Series

Value in the first period, in any unit. The result has the unit of x0. A Series is read in the first period only.

ratescalar or Series

Growth rate, dimensionless and per period: 0.05 is 5% per period, whether the period is a month or a year. A Series gives a rate for each period. The rate of the first period is not used.

Returns:
Series

x0 in the first period, then the previous value times 1 + rate in each later period.

Raises:
UnitError

At construction, if rate has units, such as a rate per time like 0.05 / b.year. Convert it with rate * m.period_length.

See also

boki.lib.index

An index that starts at 1 and can grow only in some periods.

boki.lib.discount

The cumulative discount factor.

Notes

The first period does not grow. For a series that already grows in the first period, write compound(1 + rate[0], rate). rate * m.period_length converts a rate per time into a rate per period by simple (non-compounding) scaling: 0.12 / b.year is 1% in a monthly period.

Examples

A price of 100 that grows 10% in the second year and 20% in the third:

>>> import boki as b
>>> m = b.Model("Price", start="2027-01", periods=3, step=b.year)
>>> growth = m.series("Growth", data={1: 0.1, 2: 0.2})
>>> price = b.lib.compound(100, growth)
>>> r = m.render()
>>> [round(v, 2) for v in r[price]]
[100, 110.0, 132.0]

A rate per year converted for monthly periods grows 1% per month:

>>> m = b.Model("Monthly price", start="2027-01", periods=3, step=b.month)
>>> price = b.lib.compound(100, 0.12 / b.year * m.period_length)
>>> r = m.render()
>>> [round(v, 2) for v in r[price]]
[100, 101.0, 102.01]
boki.lib.index(rate, when=None, start=None)#

Return an index that is 1 in the first period and compounds by rate in the periods where it applies.

Use it for a price or cost index that starts at 1 and grows only from a date or only while a condition holds.

Parameters:
ratescalar, Quantity, or Series

Growth rate. A plain number or a dimensionless series is per period: 0.01 is 1% in each period, whether a month or a year. A quantity or series per time, such as 0.12 / b.year, is an annual rate compounded over the length of each period, so it gives the same annual growth in a monthly and an annual model.

whenSeries, optional

A condition. The index grows only in periods where it holds. If it is None, the index grows in every period. The default is None.

startdate or str, optional

The index grows only in periods that start on or after this date, such as "2028", "2028-04", or a datetime.date. It needs dated periods. If it is None, there is no start date. The default is None.

Returns:
Series

A dimensionless series: 1 in the first period, then the previous value times 1 + growth in each period where the index grows, and unchanged in other periods.

See also

boki.lib.compound

A series that starts at a value you choose and grows every period.

Notes

The first period is always 1, whatever when and start say. If both when and start are given, the index grows only where both hold. A rate per time is compounded as (1 + rate) ** (months / 12) - 1 for a period of that many months.

Examples

A cost index with 12% a year, read after one year in a monthly model, and with 1% per period for comparison:

>>> import boki as b
>>> m = b.Model("Index", start="2027-01", periods=13, step=b.month)
>>> r = m.render()
>>> round(r.value(b.lib.index(0.12 / b.year), "2028-01"), 4)
1.12
>>> round(r.value(b.lib.index(0.01), "2028-01"), 4)
1.1268

Growth that starts in 2029 in an annual model:

>>> m = b.Model("Escalation", start="2027-01", periods=5, step=b.year)
>>> index = b.lib.index(0.1, start="2029")
>>> r = m.render()
>>> [round(v, 4) for v in r[index]]
[1.0, 1.0, 1.1, 1.21, 1.331]
boki.lib.fade(a, b, over)#

Return a series that is a until a period, b from a later period, and a straight line in between.

Parameters:
ascalar, Quantity, or Series

Value up to and including the first period of over. A Series is read in each period.

bscalar, Quantity, or Series

Value from the second period of over on, in the unit of a.

overtuple

Two periods (first, last), each a zero-based period index, a date, or a period label such as "2028". Between them, the value moves linearly with the period count.

Returns:
Series

a in periods up to first, b from last, and a + (b - a) * (t - first) / (last - first) in between, where t is the period index. The series has the common unit of a and b.

Raises:
UnitError

At construction, if a and b have incompatible units.

IndexError

At evaluation, if a period of over is outside the model’s timeline.

See also

boki.step

Hold a value until the next key.

Examples

A margin that falls from 1 to 0 over the first three periods:

>>> import boki as b
>>> m = b.Model("Fade", start="2027-01", periods=5, step=b.year)
>>> margin = b.lib.fade(1.0, 0.0, over=(0, 3))
>>> r = m.render()
>>> [round(v, 3) for v in r[margin]]
[1.0, 0.667, 0.333, 0.0, 0.0]

Period labels give the ends of the transition:

>>> growth = b.lib.fade(10, 20, over=("2028", "2030"))
>>> r[growth]
[10, 10, 15.0, 20, 20]
boki.lib.lookup(x, table)#

Return the value for the largest key that is not above x, from a banded table.

Use it for tax brackets, synthetic ratings, or a rate by calendar year with date keys. It is like Excel’s approximate LOOKUP.

Parameters:
xSeries, number, or date

The value to look up, in each period: a number, or a date for date keys. A scalar is looked up once.

tabledict

Map the lower bound of each band to its value, a number or Quantity. Keys are sorted, so the order does not matter. Use a very low key such as -1e9 for a band with no lower bound. A key and x must be comparable: both numbers or both dates.

Returns:
Series

The value of the band that x falls in, in each period. It has the unit of the table values when they all share one unit, and an unknown unit otherwise.

Raises:
ValueError

At evaluation, if x is below the first key of the table.

See also

boki.step

Hold a value until the next period key.

boki.by_year

Select values by model year.

Notes

Excel writes the table as two rows on the Inputs sheet (keys and values) and the cell as LOOKUP. A key is the lower bound of its band, so a value equal to a key falls in that key’s band.

Examples

A tax rate of 10% below 1000, 20% from 1000, and 30% from 5000:

>>> import boki as b
>>> m = b.Model("Brackets", start="2027-01", periods=3, step=b.year)
>>> income = m.series("Income", data={0: 500, 1: 1500, 2: 6000})
>>> rate = b.lib.lookup(income, {0: 0.1, 1000: 0.2, 5000: 0.3})
>>> r = m.render()
>>> r[rate]
[0.1, 0.2, 0.3]

A rate by calendar year, with date keys and the model’s dates:

>>> import datetime
>>> rate = b.lib.lookup(m.date, {datetime.date(2027, 1, 1): 0.1, datetime.date(2029, 1, 1): 0.2})
>>> r[rate]
[0.1, 0.1, 0.2]

Discounting and returns#

boki.lib.discount(rate)#

Return the cumulative discount factor at the end of each period.

Parameters:
ratescalar or Series

Discount rate, dimensionless and per period: 0.1 is 10% per period, whether the period is a month or a year. A Series gives a rate for each period.

Returns:
Series

A dimensionless series: the product of 1 / (1 + rate) over the periods up to and including each period. The first period is 1 / (1 + rate), because flows occur at the end of each period.

Raises:
UnitError

At construction, if rate has units, such as a rate per time like 0.1 / b.year. Convert it with rate * m.period_length.

See also

boki.lib.npv

The present value of cash flows.

Notes

Calling discount again with the same rate series returns the same node, so npv at that rate and the plan’s own discount row share one row in Excel. See the time points and discounting conventions.

Examples

Factors for a 10% annual rate:

>>> import boki as b
>>> m = b.Model("Discount", start="2027-01", periods=3, step=b.year)
>>> factor = b.lib.discount(0.1)
>>> r = m.render()
>>> [round(v, 4) for v in r[factor]]
[0.9091, 0.8264, 0.7513]
boki.lib.npv(cash_flows, rate, at=-1, initial=None)#

Return the present value of cash flows at a per-period discount rate.

Each period’s flow arrives at the end of the period, as in discount and Excel’s NPV. The value is as of the end of period at; the default, -1, is the start of the model.

Parameters:
cash_flowsSeries, Quantity, or scalar

Cash flow in each period, in any unit. The result has its unit. A scalar counts as the same flow in every period.

ratescalar or Series

Discount rate, dimensionless and per period: 0.01 is 1% per period, whether the period is a month or a year. A Series is a rate that changes by period (for example a WACC set year by year): each flow is discounted by the product of 1 + rate over the periods up to and including its own, as discount does.

atint, optional

Period whose end the value is taken at. -1 is the start of the model, 0 the end of the first period. With a constant rate it can be any period, including one after the end of the model; with a Series rate that varies by period it must be -1 or a period of the model. The default is -1.

initialscalar, Quantity, or Series, optional

A flow at the start of the model, such as an investment at closing, valued as of that date. If it is None, there is none. The default is None.

Returns:
Series

The value, a scalar series (the same in every period) with the unit of cash_flows.

Raises:
UnitError

At construction, if rate has units, such as a rate per time like 0.1 / b.year. Convert it with rate * m.period_length.

ValueError

At construction, if rate is a Series that varies by period and at is below -1.

IndexError

At evaluation, if rate is a Series that varies by period and at is after the last period.

See also

boki.lib.discount

The cumulative discount factor.

boki.lib.irr

The rate at which the present value is zero.

boki.lib.xnpv

The present value of flows on given dates.

Notes

Excel gets NPV() for a constant rate, and SUMPRODUCT of the flows and the discount(rate) row for a series. See the time points and discounting conventions.

Examples

Flows of 10, 10, and 110 at 10% per year, valued at the start of the model, at the end of the first year, and with an investment of 90 at the start:

>>> import boki as b
>>> m = b.Model("Valuation", start="2027-01", periods=3, step=b.year)
>>> flows = m.series("Flows", data={0: 10, 1: 10, 2: 110})
>>> r = m.render()
>>> round(r[b.lib.npv(flows, 0.1)], 2)
100.0
>>> round(r[b.lib.npv(flows, 0.1, at=0)], 2)
110.0
>>> round(r[b.lib.npv(flows, 0.1, initial=-90)], 2)
10.0

In a monthly model the rate is per month, so a 12% annual rate is written as 1% per period:

>>> m = b.Model("Rent", start="2027-01", periods=3, step=b.month)
>>> rent = m.series("Rent", data={0: 100, 1: 100, 2: 100})
>>> r = m.render()
>>> round(r[b.lib.npv(rent, 0.12 / 12)], 2)
294.1
boki.lib.xnpv(cash_flows, rate, dates)#

Return the value at the first date of cash flows on given dates at an annual rate, on an actual/365 basis.

Parameters:
cash_flowsSeries

Cash flow in each period, in any unit. The result has its unit.

ratescalar or Series

Annual discount rate, dimensionless: 0.1 is 10% a year. The dates set the timing, so it is a rate for a year whatever the period length, and a rate per time such as 0.1 / b.year is rejected.

datesSeries

The date of each period’s flow, such as m.date. The first date is the date the value is taken at.

Returns:
Series

The value, a scalar series (the same in every period) with the unit of cash_flows.

Raises:
UnitError

At construction, if rate has units.

See also

boki.lib.npv

The present value of flows by period.

boki.lib.xirr

The annual rate at which the value is zero.

Notes

Each flow is discounted by (1 + rate) ** (days / 365) from the first date, like Excel’s XNPV. Unlike npv, the first flow is not discounted, because it is on the first date.

Examples

Annual flows on the first day of each year, discounted at 10% a year to the first date:

>>> import boki as b
>>> m = b.Model("Project", start="2027-01", periods=4, step=b.year)
>>> flows = m.series("Flows", data={0: -100, 1: 40, 2: 50, 3: 60})
>>> r = m.render()
>>> round(r[b.lib.xnpv(flows, 0.1, m.date)], 2)
22.74
boki.lib.irr(cash_flows, initial=None, *, running=False, default=None)#

Return the internal rate of return per period of a series of cash flows.

Parameters:
cash_flowsSeries

Cash flow in each period, arriving at the end of the period, in any unit. The flows must change sign.

initialscalar, Quantity, or Series, optional

A flow one period before the first, such as the investment at closing when the model starts with the first operating year. If it is None, there is none. It cannot be combined with running=True. The default is None.

runningbool, optional

If True, return a series of the rate of return of the flows up to and including each period, as Excel’s IRR($C5:C5) filled right. It reads only the periods so far, so a later flow can depend on it (a partnership flip once the investor’s rate to date reaches its target). The default is False.

defaultint or float, optional

The value where the flows have no rate of return, as IFERROR(IRR(...), 0) does. If it is None, that is an error. The default is None.

Returns:
Series

A dimensionless rate per period. A scalar series (the same in every period) when running is False, and one value for each period when it is True.

Raises:
TypeError

At construction, if default is not a number (a bool is not accepted), if running is True and initial is given, or if running is True and cash_flows is a scalar.

NoRateOfReturn

At evaluation, if the flows have no sign change within -99% to 1000% per period and default is None.

See also

boki.lib.xirr

The annual rate for flows on given dates.

boki.lib.npv

The present value at a given rate.

boki.lib.NoRateOfReturn

The error for flows without a rate of return.

Notes

The rate is per period, so monthly flows give a monthly rate: annualize it as (1 + irr) ** 12 - 1. If the flows change sign more than once, such as a decommissioning cost at the end, the rate chosen is a root where the value falls as the rate rises (invest first, then earn, the usual IRR) and, among those, the one nearest 10%, as Excel’s IRR does from its default guess. Only irr and xirr take default=; guard other divisions with x.where(denominator != 0, 0). See the time points and discounting conventions.

Examples

An investment of 100 followed by flows of 40, 50, and 60:

>>> import boki as b
>>> m = b.Model("Project", start="2027-01", periods=4, step=b.year)
>>> flows = m.series("Flows", data={0: -100, 1: 40, 2: 50, 3: 60})
>>> r = m.render()
>>> round(r[b.lib.irr(flows)], 4)
0.2165

The same project with the investment passed as initial, one period before the first flow:

>>> m = b.Model("Operating years", start="2027-01", periods=3, step=b.year)
>>> flows = m.series("Flows", data={0: 10, 1: 10, 2: 110})
>>> r = m.render()
>>> round(r[b.lib.irr(flows, initial=-100)], 4)
0.1

The rate is per period: 100 invested grows to 112.68 in twelve months, a 1% monthly rate and 12.68% a year:

>>> m = b.Model("Monthly", start="2027-01", periods=13, step=b.month)
>>> flows = m.series("Flows", data={0: -100, 12: 112.6825})
>>> r = m.render()
>>> monthly = r[b.lib.irr(flows)]
>>> round(monthly, 4)
0.01
>>> round((1 + monthly) ** 12 - 1, 4)
0.1268

The rate to date, with default=0 before the flows change sign:

>>> m = b.Model("To date", start="2027-01", periods=4, step=b.year)
>>> flows = m.series("Flows", data={0: -100, 1: 40, 2: 50, 3: 60})
>>> r = m.render()
>>> [round(v, 4) for v in r[b.lib.irr(flows, running=True, default=0.0)]]
[0.0, -0.6, -0.0652, 0.2165]
boki.lib.xirr(cash_flows, dates, *, default=None)#

Return the annual internal rate of return of cash flows on given dates, on an actual/365 basis.

Parameters:
cash_flowsSeries

Cash flow in each period, in any unit. The flows must change sign.

datesSeries

The date of each period’s flow, such as m.date or m.period_end. It must have a date in every period; the first date is the date the rate is measured from.

defaultint or float, optional

The value where the flows have no rate of return, as for irr. If it is None, that is an error. The default is None.

Returns:
Series

A dimensionless annual rate, a scalar series (the same in every period).

Raises:
TypeError

At construction, if default is not a number (a bool is not accepted).

NoRateOfReturn

At evaluation, if the flows have no sign change within -99% to 1000% and default is None.

See also

boki.lib.irr

The rate per period, without dates.

boki.lib.xnpv

The present value of flows on given dates.

boki.lib.NoRateOfReturn

The error for flows without a rate of return.

Notes

Time between flows is the number of days divided by 365, like Excel’s XIRR, so the rate is annual whatever the period length. The search range is -99% to 1000% a year.

Examples

Annual flows on the first day of each year:

>>> import boki as b
>>> m = b.Model("Project", start="2027-01", periods=4, step=b.year)
>>> flows = m.series("Flows", data={0: -100, 1: 40, 2: 50, 3: 60})
>>> r = m.render()
>>> round(r[b.lib.xirr(flows, m.date)], 4)
0.2163
exception boki.lib.NoRateOfReturn#

Error raised when cash flows have no internal rate of return.

irr and xirr raise it at evaluation when the flows have no sign change within the search range, from -99% to 1000% per period, and no default= was given. It is an ArithmeticError.

See also

boki.lib.irr

The internal rate of return per period.

boki.lib.xirr

The annual internal rate of return for flows on given dates.

Notes

Flows that are all positive or all negative have no rate of return. irr(..., default=0) returns the default instead of raising, which is how a running IRR starts before the first sign change.

Examples

Flows without an outflow have no rate of return:

>>> import boki as b
>>> m = b.Model("Receipts", start="2027-01", periods=2, step=b.year)
>>> flows = m.series("Flows", data={0: 10, 1: 10})
>>> r = m.render()
>>> try:
...     r[b.lib.irr(flows)]
... except b.lib.NoRateOfReturn as error:
...     print(error)
no sign change: the cash flows have no internal rate of return in range
>>> r[b.lib.irr(flows, default=0)]
0
boki.lib.gordon(cash_flow, rate, growth)#

Return the value of a perpetuity whose cash flow grows at a constant rate: cash_flow / (rate - growth).

Parameters:
cash_flowscalar, Quantity, or Series

The first cash flow of the perpetuity, such as the terminal year’s flow, in any unit. The result has its unit.

ratescalar or Series

Discount rate, dimensionless and per period. A rate per time such as 0.1 / b.year is not rejected here, so convert it with rate * m.period_length first.

growthscalar or Series

Growth rate of the cash flow, dimensionless and on the same per-period basis as rate.

Returns:
Series

The perpetuity value, a series that has the unit of cash_flow and is scalar when all arguments are.

See also

boki.lib.npv

The present value of finite cash flows.

Notes

The formula needs rate above growth. If they are equal the division fails at evaluation, and a growth above rate gives a negative value.

Examples

A terminal flow of 100 growing 2% a year at a 10% discount rate:

>>> import boki as b
>>> m = b.Model("Terminal value", start="2027-01", periods=3, step=b.year)
>>> value = b.lib.gordon(100, 0.10, 0.02)
>>> r = m.render()
>>> round(r[value], 2)
1250.0
boki.lib.levelized(cost, quantity, rate)#

Return the levelized cost: the present value of costs divided by the present value of quantities.

Use it for the levelized cost of energy (LCOE) and similar unit costs.

Parameters:
costSeries

Cost in each period, in a currency unit.

quantitySeries

Quantity delivered in each period, such as energy produced.

ratescalar or Series

Discount rate, dimensionless and per period, as for npv.

Returns:
Series

A scalar series (the same in every period): npv(cost, rate) / npv(quantity, rate), in the unit of cost per unit of quantity.

Raises:
UnitError

At construction, if rate has units, such as a rate per time like 0.1 / b.year.

See also

boki.lib.npv

The present value used for both sides.

Notes

Quantities are held in base units, so a quantity in MWh is stored in Wh and the result is in currency per Wh; multiply by 1,000,000 for currency per MWh.

Examples

A cost of 100 a year for 50 units a year, at 8%:

>>> import boki as b
>>> m = b.Model("Unit cost", start="2027-01", periods=3, step=b.year)
>>> cost = m.series("Cost", data={0: 100, 1: 100, 2: 100})
>>> units = m.series("Units", data={0: 50, 1: 50, 2: 50})
>>> r = m.render()
>>> round(r[b.lib.levelized(cost, units, 0.08)], 4)
2.0
boki.lib.pmt(rate, n, pv)#

Return the level payment per period that repays pv over n periods at a per-period rate.

The payment is made at the end of each period (an ordinary annuity). It is positive for a positive pv; Excel’s PMT has the opposite sign.

Parameters:
ratescalar or Series

Interest rate, dimensionless and per period: 0.01 is 1% per period, whether the period is a month or a year. Divide an annual rate by 12 for monthly periods. A rate per time such as 0.1 / b.year raises UnitError when it is a scalar quantity; a series with units is not checked.

nint or Series

Number of periods over which the amount is repaid. It must not be zero.

pvscalar, Quantity, or Series

Amount to repay, in any unit. The result has its unit.

Returns:
Series | Quantity | float

The payment per period: a Series if any argument is a series (with the unit of pv), a Quantity if pv is a quantity, and otherwise a number.

Raises:
UnitError

At construction, if rate is a scalar quantity with units.

See also

boki.lib.npv

The present value of a series of payments.

Notes

With a rate of 0 the payment is pv / n. Otherwise it is pv * rate / (1 - (1 + rate) ** -n).

Examples

Repay 1000 over twelve months at 12% a year, which is 1% a month:

>>> import boki as b
>>> payment = b.lib.pmt(0.12 / 12, 12, 1000)
>>> round(payment, 2)
88.85

With a series for the amount the payment is a series:

>>> m = b.Model("Loan", start="2027-01", periods=12, step=b.month)
>>> loan = m.series("Loan", 1000)
>>> r = m.render()
>>> round(r[b.lib.pmt(0.01, 12, loan)], 2)
88.85

Cost of capital and options#

boki.lib.capm(beta, rf, erp)#

Return the cost of equity from the capital asset pricing model: rf + beta * erp.

Parameters:
betascalar or Series

Equity beta, dimensionless.

rfscalar or Series

Risk-free rate, dimensionless and per period (0.03 is 3% a period).

erpscalar or Series

Equity risk premium, dimensionless and on the same per-period basis as rf.

Returns:
Series | float

The cost of equity on the per-period basis of rf and erp: a Series if any argument is a series, otherwise a number.

Raises:
UnitError

At construction, if an argument has units, such as a rate per time like 0.03 / b.year: the sum with a plain number then has incompatible units.

See also

boki.lib.wacc

The weighted average cost of capital.

boki.lib.hamada

The levered beta used in the cost of equity.

Examples

A beta of 1.2, a 3% risk-free rate, and a 5% equity risk premium:

>>> import boki as b
>>> round(b.lib.capm(1.2, 0.03, 0.05), 4)
0.09
boki.lib.hamada(unlevered, de, tax)#

Return the levered equity beta from an unlevered beta and a debt-to-equity ratio, by the Hamada equation.

The levered beta is unlevered * (1 + (1 - tax) * de).

Parameters:
unleveredscalar or Series

Unlevered (asset) beta, dimensionless.

descalar or Series

Debt-to-equity ratio at market values, dimensionless (0.5 is 50 of debt per 100 of equity).

taxscalar or Series

Tax rate on the interest shield, a dimensionless fraction (0.25 is 25%).

Returns:
Series | float

The levered beta: a Series if any argument is a series, otherwise a number.

Raises:
UnitError

At construction, if tax or de has units, because the sum with a plain number then has incompatible units.

See also

boki.lib.capm

The cost of equity from a beta.

boki.lib.wacc

The weighted average cost of capital.

Examples

An unlevered beta of 1.0 with 50% debt to equity and a 25% tax rate:

>>> import boki as b
>>> round(b.lib.hamada(1.0, 0.5, 0.25), 4)
1.375
boki.lib.wacc(cost_of_equity, cost_of_debt, debt_ratio, tax)#

Return the weighted average cost of capital with an after-tax cost of debt.

The result is cost_of_equity * (1 - debt_ratio) + cost_of_debt * (1 - tax) * debt_ratio.

Parameters:
cost_of_equityscalar or Series

Cost of equity, dimensionless and per period (0.1 is 10% a period), such as the result of capm.

cost_of_debtscalar or Series

Pre-tax cost of debt, dimensionless and on the same per-period basis as cost_of_equity.

debt_ratioscalar or Series

Debt as a dimensionless share of total capital, debt over debt plus equity (0.4 is 40%).

taxscalar or Series

Tax rate on the interest shield, a dimensionless fraction (0.25 is 25%).

Returns:
Series | float

The cost of capital on the per-period basis of the two costs: a Series if any argument is a series, otherwise a number.

Raises:
UnitError

At construction, if an argument has units, such as a rate per time like 0.04 / b.year: the sum with a plain number then has incompatible units.

See also

boki.lib.capm

The cost of equity.

boki.lib.npv

Discount cash flows at the result.

Examples

10% cost of equity, 4% cost of debt, 40% debt, and a 25% tax rate:

>>> import boki as b
>>> round(b.lib.wacc(0.1, 0.04, 0.4, 0.25), 4)
0.072
boki.lib.black_scholes(underlying, strike, years, volatility, rate, yield_=0.0, call=True)#

Return the Black-Scholes value of a European option.

Use it for real options such as expanding, delaying, or abandoning a project, or a natural-resource option. The value is as of today for an option that expires in years years.

Parameters:
underlyingscalar, Quantity, or Series

Current value of the underlying asset, such as the present value of a project’s cash flows, in any unit. The result has its unit.

strikescalar, Quantity, or Series

Exercise price, in the same unit as underlying.

yearsscalar or Series

Time to expiry in years, a plain number: 0.5 is six months. It must be positive.

volatilityscalar or Series

Annualized volatility of the underlying, dimensionless: 0.2 is 20% a year. It must be positive.

ratescalar or Series

Continuously compounded risk-free rate per year, dimensionless: 0.05 is 5% a year.

yield_scalar or Series, optional

Continuous payout rate of the underlying per year, dimensionless, such as dividends or the annual cost of delay. The default is 0.0.

callbool, optional

True for a call (the right to buy at strike), False for a put. The default is True.

Returns:
Series | Quantity | float

The option value: a Series if any argument is a series, a Quantity if the underlying and strike are quantities, and otherwise a number. It has the unit of underlying.

See also

boki.lib.npv

The present value that often serves as the underlying.

Notes

years, volatility, rate, and yield_ are per year, not per period, so they do not depend on the model’s period length. A zero years or volatility divides by zero, and a non-positive underlying or strike has no logarithm; both fail at evaluation.

Examples

An at-the-money call and put on an underlying worth 100, one year to expiry, 20% volatility, and a 5% rate:

>>> import boki as b
>>> round(b.lib.black_scholes(100, 100, 1, 0.2, 0.05), 4)
10.4506
>>> round(b.lib.black_scholes(100, 100, 1, 0.2, 0.05, call=False), 4)
5.5735

A continuous payout of 2% lowers the call value:

>>> round(b.lib.black_scholes(100, 100, 1, 0.2, 0.05, yield_=0.02), 4)
9.227

With a series for the underlying, the value is a series:

>>> m = b.Model("Option", start="2027-01", periods=2, step=b.year)
>>> worth = m.series("Worth", data={0: 100, 1: 120})
>>> r = m.render()
>>> [round(v, 2) for v in r[b.lib.black_scholes(worth, 100, 1, 0.2, 0.05)]]
[10.45, 26.17]

Tax and regulatory capital#

boki.lib.macrs(years)#

Return the US MACRS tax depreciation schedule as a kernel over annual periods.

The schedule is the General Depreciation System with the half-year convention, in IRS Publication 946, Table A-1: 200% declining balance for 3 to 10 years and 150% for 15 and 20 years, switching to straight line.

Parameters:
yearsint

MACRS recovery period in years. It must be one of 3, 5, 7, 10, 15, or 20.

Returns:
Kernel

A kernel named "macrs(<years>)" whose weight k is the share of the cost deducted k years after the year placed in service. The table has years + 1 weights, rounded as published, so they sum to 1 within rounding.

Raises:
ValueError

At construction, if years is not 3, 5, 7, 10, 15, or 20.

See also

boki.lib.straight_line

Straight-line tax depreciation.

boki.shapes.spread

Apply a kernel to a series.

Notes

The kernel counts periods, so use it with annual periods: capex.spread(macrs(5)) is the deduction each year. In a model with shorter periods each weight would apply to one period, not to one year.

Examples

A five-year asset bought for 100 in the first year:

>>> import boki as b
>>> m = b.Model("Tax depreciation", start="2027-01", periods=6, step=b.year)
>>> capex = m.series("Capex", data={0: 100})
>>> deduction = capex.spread(b.lib.macrs(5))
>>> r = m.render()
>>> [round(v, 2) for v in r[deduction]]
[20.0, 32.0, 19.2, 11.52, 11.52, 5.76]
boki.lib.straight_line(years, half_year=True)#

Return a straight-line depreciation schedule as a kernel over annual periods.

Parameters:
yearsint

Recovery period in years. It must be at least 1.

half_yearbool, optional

If True, deduct half a year’s share in the first year and the other half in the year after the last, so the schedule covers years + 1 years, as tax schedules such as the 20-year straight line do. If False, deduct 1 / years in each of years years. The default is True.

Returns:
Kernel

A kernel named "straight_line(<years>)" whose weight k is the share of the cost deducted k years after the year placed in service. The weights sum to 1.

Raises:
ValueError

At construction, if years is less than 1.

See also

boki.lib.macrs

US MACRS tax depreciation.

boki.shapes.spread

Apply a kernel to a series.

Notes

The kernel counts periods, so use it with annual periods. b.even(years) gives the same weights as half_year=False for any period length.

Examples

A four-year asset bought for 100 in the first year, with the half-year convention:

>>> import boki as b
>>> m = b.Model("Tax depreciation", start="2027-01", periods=6, step=b.year)
>>> capex = m.series("Capex", data={0: 100})
>>> deduction = capex.spread(b.lib.straight_line(4))
>>> r = m.render()
>>> [round(v, 2) for v in r[deduction]]
[12.5, 25.0, 25.0, 25.0, 12.5, 0.0]
>>> b.lib.straight_line(2, half_year=False).weights
(0.5, 0.5)
boki.lib.nol(base, opening=0, cap=None)#

Return a tax loss carryforward on a tax base: the balance, the losses used, and the taxable income left.

Losses add to the balance, and later profits use it up, at most cap times the profit of a period when a law limits it. The carryforward is computed outside the ledger; pl.income_tax(nol=True) keeps the same carryforward inside the tax line, as its .nol. boki.nol is the same function.

Parameters:
baseSeries

Pretax income or another tax base in each period. A negative value is a loss that adds to the balance; a positive value is profit that the balance can offset.

openingscalar or Quantity, optional

Losses carried in from before the model starts, in the unit of base. The default is 0.

capscalar or Series, optional

The most of a period’s profit that the carryforward can offset, a dimensionless fraction of the profit (0.8 is 80%). If it is None, there is no limit. The default is None.

Returns:
NOL

A named tuple (balance, used, taxable) of series in the unit of base. balance is the losses still to use at the end of each period. used is the losses used against the period’s profit: the smaller of cap times the profit and the balance carried from the previous period. taxable is the profit left after them, max(base, 0) - used.

Notes

Multiply taxable by the tax rate for the tax of each period. A loss in a period adds to the balance at the end of that period; it is first available in the next one.

Examples

A loss of 50, then profits of 30, 100, and 10, taxed at 25%:

>>> import boki as b
>>> m = b.Model("Tax losses", start="2027-01", periods=4, step=b.year)
>>> income = m.series("Pretax income", data={0: -50, 1: 30, 2: 100, 3: 10})
>>> carry = b.lib.nol(income)
>>> r = m.render()
>>> r[carry.balance]
[50, 20, 0, 0]
>>> r[carry.used]
[0, 30, 20, 0]
>>> r[carry.taxable]
[0, 0, 80, 10]
>>> r[carry.taxable * 0.25]
[0.0, 0.0, 20.0, 2.5]

Losses of 20 carried in from before the model, with the carryforward limited to 80% of each profit:

>>> carry = b.lib.nol(income, opening=20, cap=0.8)
>>> [round(v, 2) for v in r[carry.used]]
[0.0, 24.0, 46.0, 0.0]
boki.lib.ssfa(kg, w, attachment, detachment, p=0.5, floor=0.2)#

Return the risk weight of a securitization tranche under the Simplified Supervisory Formula Approach.

The formula is the US capital rule’s SSFA (12 CFR 217.144). The part of the tranche below KA takes a 1,250% risk weight, and above it the weight follows K_SSFA.

Parameters:
kgfloat

KG of the rule: the weighted-average capital requirement of the underlying exposures, as a dimensionless fraction of exposure (0.08 is 8%).

wfloat

W of the rule: the share of the underlying exposures that are delinquent or in default, as a dimensionless fraction of exposure.

attachmentfloat

Attachment point A of the tranche: the share of the pool that absorbs losses first, as a fraction of the pool.

detachmentfloat

Detachment point D of the tranche, as a fraction of the pool. It must be above attachment.

pfloat, optional

Supervisory parameter: 0.5 for a securitization, 1.5 for a resecuritization. The default is 0.5.

floorfloat, optional

Lowest risk weight as a ratio (0.20 is 20%). The default is 0.20.

Returns:
float

The risk weight as a ratio of exposure: 12.5 is 1,250% and floor is the lowest value.

Notes

KA = (1 - w) * kg + 0.5 * w. If detachment is at or below KA the whole tranche takes 1,250%. Otherwise the capital per unit above KA is K_SSFA = (e^(a*u) - e^(a*l)) / (a * (u - l)) with a = -1 / (p * KA), u = D - KA and l = max(A - KA, 0). The share of the tranche below KA takes 1,250% and the rest takes 12.5 * K_SSFA. The result is never below floor. A zero KA (kg and w both 0) or a tranche with no thickness divides by zero.

Examples

A thin first-loss tranche takes a weight near 1,250%, and a senior tranche takes the 20% floor:

>>> import boki as b
>>> round(b.lib.ssfa(0.05, 0.1, 0.0, 0.1), 4)
12.4682
>>> round(b.lib.ssfa(0.05, 0.1, 0.3, 1.0), 4)
0.2