Financial formulas
This pack provides reusable financial calculations for model inputs, cashflows, calculations and metrics. It uses ordinary DECCF callbacks and metric declarations; it adds no engine concepts. The Calculator lists it as Financial formulas.
const { formulas } = modules["financial-formulas"];
const { savingsPlan } = modules.savings;
const periodRate = formulas.rates.period({ annualRate, convention: "effective" });
const goalContribution = formulas.savings.requiredContribution({
openingBalance,
target,
periodRate,
periods: (ctx) => ctx.time.index + 1,
});
const fund = savingsPlan({
openingBalance,
annualRate,
contribution: monthlyContribution,
contributionPlacement: "end",
});Formula factories accept numbers, declared inputs, calculation references and record projections, inspectable expressions, or compatible callbacks. Amount sources also accept Money. Configured formulas can be passed directly to a calculation or plan without writing a callback. Formula dependencies are carried with the formula; arbitrary callbacks must still declare their dependencies. The two composite packs also use these formulas internally: selecting loans or savings selects this pack automatically.
amount.during and snapshots.atPeriod take an integer literal or a fixed input.integer for their period bounds. For phase limits that change with other inputs, use an ordinary model callback with explicit preconditions or a savings/loan plan callback.
Formula groups
amount:shareOf, sparseatPeriods, and half-openduringprofiles.rates: nominal, effective or explicitly compounded annual-to-period rates.growth: compound growth, annual step growth and degradation for fixed assumptions. A dynamic period index is allowed; a changing rate should be modeled period by period with a savings or loan plan.savings: future value and the contribution needed to reach a target, for end- or start-of-period deposits.valuation: real value and present value.financing: interest on opening balance, annuity payment and capped principal from a remaining balance.usage: convert mileage/intensity to consumption and consumption to cost without implicit unit conversion.business: operating result, break-even units, static cash runway and ratios. Undefined metrics stay undefined when the margin or denominator does not support a result.workingCapital: cash-conversion days, signed net working capital, funding cost, unpaid share and signed VAT net.accounting: opening debit and credit balances from an account's prior balance.dates.monthDistanceanddates.shiftMonth: count signed calendar months or shift a month across year boundaries. Both accept validYYYY-MMorYYYY-MM-DDdates.metrics: cumulative selected flows and discounted NPV/payback for selected flows with explicit placements.snapshots.atPeriod: preserve a calculation at a selected model period with existing field and metric declarations.series.running: reusable running sums, minima, maxima and products, with an optional initial value.series.rateScenario: a base rate, period changes, an optional floor and a shared uncertain shock per simulation trial.solve.variableandsolve.bisect: find a scoped unknown in a continuous formula within explicit bounds; return convergence, residual and reason as well as the value.
Money inputs are read as numeric amounts and compatible money currencies are checked when the formula or composition runs. No exchange rate is inferred and no cents rounding is hidden. Annual rates use the model's periods per year; nominal rates divide by that count unless a capitalization frequency is supplied. metrics.discountedCashflows requires the declared cashflow placement to match the selected placement.
See Reusable financial formulas for migration examples and period conventions.
See Declarative financial models for callback-free expressions, direct result metrics, series and goal seeking. The solver evaluates a formula in the current period; it does not change saved input values or rerun an entire model. tolerance is measured in the formula result, and callers should always inspect the returned reason.
Running values and changing factors
series.running({ source, operation, initial, name, phase }) declares one numeric calculation over every model period. The required source and optional initial accept numbers, Money, declared inputs, calculations and their projections, expressions, or compatible callbacks. operation is "sum" (the default), "min", "max" or "product"; name defaults to "running".
The source is read in each period. An explicit initial is read once, in period zero, and combined with the first source. If initial is omitted, the first result is the first source itself. Each later result combines the previous result and the current source. Thus product factors 2, 3, 0.5 produce 2, 6, 3 without an initial, or 20, 60, 30 with initial: 10. An explicit zero is preserved. Every run and every repeated item starts with its own accumulator.
For changing inflation or rent escalation, supply a factor such as 1.002 for a 0.2% increase during that model period. Use initial: 1 for a dimensionless index, or the starting amount for an indexed amount. The helper does not convert annual rates into period rates. This monthly model increases rent in the first month and applies the new monthly inflation assumption from period 12 onward:
const inflation = modules['financial-formulas'].series.rateScenario({
name: 'monthlyInflation',
base: 0.002,
changes: [{ fromPeriod: 12, change: 0.001 }],
});
const indexedRent = modules['financial-formulas'].series.running({
name: 'indexedRent',
source: deccf.expr.add(1, inflation),
operation: 'product',
initial: 10000,
});
return deccf.defineModel({
currency: deccf.currencies.SEK,
timeline: deccf.periods.monthly({ from: '2027-01', count: 24 }),
calculations: { inflation, indexedRent },
metrics: { rent: deccf.metric({ value: indexedRent }) },
});The calculation returns numbers: Money sources contribute their numeric amounts in the model currency, without rounding or preserving a valuation date. Product does not infer units; use dimensionless source factors when the accumulator represents money. Zero and negative finite values are supported. A missing source or unknown operation rejects with DECCF_FORMULA_CONFIG; nonnumeric or nonfinite source/initial values and product overflow reject with DECCF_FORMULA_VALUE. A zero accumulator does not make an invalid source valid.
Dependencies are carried from the source and initial. The phase defaults to "periodEnd" when they require settled flows or end-of-period calculations, and to "period" otherwise. An explicit phase must allow all dependency reads. Arbitrary callbacks must declare their own dependencies. The helper adds no accounts or payments; use its calculation reference wherever a numeric source is accepted.
formulas.series.pulse({ atPeriod, amount }) returns the amount in one selected zero-based period and zero in every other period. It can schedule a one-off loan drawdown or another payment. The selected period may come from an integer input, row field, or declared calculation. Its amount and period dependencies travel with the formula.
Standard amount, financing, rate, growth and repayment formulas can be nested inside repeated loans. Each row uses its own values, including formulas passed through series.rateScenario. Custom callbacks still need explicit declarations and are rejected when their captured row values cannot be bound safely.
Named calculation records
Use formulas.snapshots.record to publish a structured row made from existing inputs, expressions and calculations. Declare each field's type explicitly; Money remains Money and scheduled missing observations remain missing. The record adds no accounts or payments. For example, a repeated asset can expose its name, value and actual payments together in a RecordTable:
const detail = formulas.snapshots.record({
name: 'detail',
fields: { name: assetName, value: assetValue, payment: actualPayment },
resultType: { name: 'text', value: 'money', payment: 'money' },
});Nested records, keyed maps and calculation projections can also be fields. Dependencies and end-of-period timing follow the sources. Optional schedule, owner, phase and publish use the ordinary calculation meanings.
formulas.snapshots.select selects a value from a calculated record using literal text or declared text inputs as path segments. This is useful when an editable row ID selects its corresponding calculated result:
const charge = formulas.snapshots.select({
name: 'charge', source: annualCharges,
path: ['perProperty', homeId, 'total'], resultType: 'money',
fallback: money(0, currencies.SEK),
});A missing path rejects by default. Set a typed fallback only when absence has an explicit meaning, such as no January 1 property charge for a newly acquired home. Unsafe keys and accessors always reject, including when a fallback exists.
Calendar months
formulas.dates.monthDistance(from, to) returns the signed integer calendar-month count between two dates. Both arguments accept YYYY-MM or YYYY-MM-DD in years 0001–9999. Days do not affect the count: January 31 to February 1 is one month, the reverse is minus one, and dates in the same month give zero. This counts calendar positions, not elapsed days or calculation periods.
formulas.dates.shiftMonth(period, offset) accepts the same dates and an integer month offset, positive or negative, and always returns YYYY-MM. Zero retains the input month. A full date's day is checked and then discarded, so shifting January 31 by one month returns February without choosing a replacement day.
const months = modules["financial-formulas"].formulas.dates.monthDistance("2026-12-31", "2027-02-01");
const invoiceMonth = modules["financial-formulas"].formulas.dates.shiftMonth("2026-12-31", 2);
// months is 2; invoiceMonth is "2027-02".Both helpers reject malformed formats, non-string dates and invalid calendar dates, including impossible leap days, with DECCF_FORMULA_VALUE. Month shifting also rejects noninteger offsets and results outside years 0001–9999. For compatibility, a YYYY-MM input with year 0000 remains accepted by shiftMonth only when its shifted result is in 0001–9999; full dates with year 0000 are invalid. Neither helper has an omitted-argument default. The same calls are also available as modules["financial-formulas"].monthDistance and .shiftMonth.