DecCF./ˈdɛk.ɛf/

Valuation and uncertainty

Built-in metrics

  • total: the sum of net cash positions in flows and options over published result periods.
  • npv: present value at the run's annual discount rate.
  • irr: annualized internal rate of return when it can be solved.
  • wal: weighted average time to cashflow in years, when the data supports a value.

The discount rate is zero unless supplied; it must be finite and greater than −1. The model calendar sets periods per year: 365, 52, 12, 4, or 1. Schedule placement controls the time point within each period.

Declare custom metrics with functions in defineModel({ metrics: { name: (ctx) => ... } }), or use a metric() declaration to select a period length and evaluation frequency. After the simulation loop, each callback is evaluated for every eligible period with that period's context and history. Plain functions default to every period. The result series retains those values; the summary retains the last defined value. Callbacks can read inputs, fields, states, accounts and completed cashflows through that period. Returning undefined omits that period's value. The names total, npv, irr, and wal are reserved.

Select metric dates

metric({schedule}) restricts evaluation to an existing calendar schedule. Omit it to keep every period allowed by frequency and periodLength, which both default to 1 model period. A selected date still needs to satisfy the frequency and have a complete trailing window. The schedule does not change the calculation window or annual aggregation rule.

This metric has values [null, null, 3]: it runs only in the selected final year. Its summary is 3. Changing the declared date input selects a different matching period on the same timeline. A schedule may also use a derived date, such as an editable plan's final year, or a recurring calendar schedule. Schedule dates must use declared inputs or derived values with declared dependencies. The ordinary calendar-grain rules apply; a one-time date must be compatible with the model's calendar grain. Trigger-relative schedules are not supported for metrics.

Skipped periods never evaluate the callback or create its calculation context, and appear as null in the metric series. A schedule outside the timeline emits no values and omits the metric from the summary. When several dates emit values, the summary retains the last defined one. Use a schedule for a final-period report to avoid repeatedly evaluating a report that is available only at that date.

ctx.sumAccountPostings(accounts, from?, to?, { excludePeriodClosing? }) aggregates signed debit/credit movements on selected accounts. This lets a metric select accounting activity through the account plan rather than flow names.

Distributions and draws

Distributions accept clip: [min, max], and can also be checked against input domains. Central values in a deterministic run are:

  • normal: mean
  • log-normal: expected value from mu and sigma
  • uniform: midpoint of the range
  • triangular: mode

To vary values, callbacks must use ctx.draw() or ctx.sample(). draw() reuses a value across periods; sample() draws once per period and owner. Correlations are not modeled automatically.

Monte Carlo

runMonteCarlo(model, { trials, seed, ...runOptions }) requires a positive integer trial count and an integer seed. It runs stochastic trials using pseudorandom samples initialized by the seed. The output summarizes sampled numeric metrics with valid sample count, mean, standard deviation, min, max, and percentiles p5, p25, p50, p75, and p95; it is not a deterministic forecast. It also returns runtime timings for each trial, the aggregate metric calculations, and the full simulation call. Timing values depend on runtime conditions and are not reproducible simulation outputs.

The engine prepares the model and calendar once per Monte Carlo call. It tracks context reads in calculations, derived inputs and flow amount callbacks, then reuses values that depend only on fixed run inputs, dates, or other reusable calculations. Reuse is per calculation or flow and period. ctx.get() on a distribution reads its center; ctx.draw() and ctx.sample() prevent exact reuse unless that input has a fixed run override. Reads of mutable accounts, fields, cashflows, states, trigger sources, or posting history conservatively prevent reuse. Each trial still has its own balances, postings, events, and random draws.

The Calculator can execute independent exact trials in parallel, with a maximum of 32 workers bounded by available processing capacity and batch size. Small batches stay sequential to avoid worker startup costs; larger batches can use more available processors. It prepares eligible immutable invariant values once and copies them into each worker's own cache for this run. Money values and records containing Money stay local to each worker so their object identity is preserved. There is no shared mutable cache. Trial numbers remain global, so pseudo-random and Sobol samples and their summary order remain reproducible within the same calculation runtime. Different scenarios and changed inputs use separate caches. Active approximate runs keep their sequential cache-learning order. This orchestration does not add a worker-count option to the synchronous deccf.runMonteCarlo() model-authoring call.

Every Monte Carlo result also includes the complete ordinary base calculation: deterministic, effective inputs, account postings, annual rollups and graph metadata. It uses the same input overrides and the distributions’ central values, independently of trial count, seed, sampling and approximation settings. Existing summaries remain the sampled statistics; monte_carlo identifies the simulation and carries those summaries as well. Reports can therefore use the same base data in both calculation modes. This base calculation is neither a selected trial nor the mean of sampled results.

By default, individual trials retain only final metric values and timings in the returned result. Explicitly selected temporal series add pointwise summaries without retaining individual trial histories. In general execution they still keep the history needed during calculation and evaluate every scheduled metric, including earlier periods and validation. Full trial-by-trial report data is not added. Runtime timings include the additional base calculation under timings.baselineRun.

Summarize a standard series

Declare monteCarlo: {series: ["account.savings.balance", "flow.contribution", "metric.income"]} to select existing standard series for uncertainty charts. execution: "indexed" can be added when the model supports indexed execution. With no series selection, the result keeps its previous shape and work on temporal summaries is omitted.

simulation.seriesSummaries[id] contains exact model dates and matching points. Each defined numeric point is a SampledSeriesPointSummary with trials, mean, standardDeviation, min, max and empirical percentiles (p5, p25, p50, p75, p95). A point with no numeric observations is null; missing values are never counted as zero. Text observations do not produce numeric statistics. The point's trials counts only its defined observations. Scalar metric summaries retain empirical histogram distributions; temporal points contain moments and percentiles without repeating a histogram at every date.

The record also contains baseline values matching its exact dates, before annual amount storage, and annual: {dates, points, baseline}, with dates at calendar or declared fiscal-year starts. Each trial is aggregated before its statistics are calculated: flows sum, accounts retain the last balance, and metrics follow their annualAggregation and fiscalYearStartMonth. This preserves dependence between monthly values; adding monthly percentiles does not produce a percentile of an annual sum. Years without any observations stay null.

Optional currency and unit describe the observations. valuation: {moneyValue, inflation, moneyValueBaseDate} records the run's purchasing-power selection. Money is valued at its explicit date or the observation date before either monthly or annual statistics. A numeric unit:"money" remains display metadata and does not convert a number into Money. amountStorage can compact the ordinary baseline while temporal uncertainty retains every original date. Serial and worker results use the same trials. Final summaries and the complete ordinary baseline remain available.

See Sample a distribution through time for a complete callable model and simulation example. Baseline metric names can be combined with series; their baseline observations are broadcast unchanged across trials.

Indexed Monte Carlo

deccf.defineModel({monteCarlo: {execution: "indexed", baselineMetrics: [...]}, ...}) opts into strict indexed execution of sampled outcomes. Omit monteCarlo to keep general execution. This is a model declaration, shared by runMonteCarlo() and Monte Carlo runScenarios() calls; it is not a run input or a worker-count setting.

Indexed execution follows the original calculation calendar and financial operations while retaining the values needed by the selected outcomes. It does not replace monthly cashflows with annual formulas or change the trial seed and Sobol coordinates. It reduces work on full report calculations and implicit metrics during sampled trials. The complete ordinary unseeded baseline still supplies reports, series, postings, graph metadata and its usual built-in metrics.

The option accepts:

FieldMeaning
executionOptional; "indexed" selects strict indexed execution. Omission keeps general execution. Other values are rejected.
seriesOptional unique standard series names: account.<name>.balance, flow.<name> and metric.<name>. Selects monthly or other original-period uncertainty plus annual summaries. Unknown names are rejected.
baselineMetricsOptional array of unique declared metric names, default []. Unknown or duplicate names are rejected. These metrics are calculated in the ordinary baseline and their final numeric values are repeated across all trials.

Every remaining sampled metric must use deccf.metric({value, ...}). Every declared scheduled context is evaluated; the final summary retains its last defined emitted value. periodLength: 1 and frequency: 1 remain the defaults. Use schedule.once(finalDate) when only a final outcome is needed. The timeline must be nonempty and cannot have additional projection periods.

Supported value sources are number, text or Money literals and input, calculation, calculation-projection or account references. Direct flow, field and expression references are unsupported; expose the intended value through a static calculation when needed. Plain numbers retain their values; unit: "money" supplies display and aggregation metadata without turning a number into Money. Return typed Money to apply moneyValue: "today" conversion before sampled statistics are computed. Money retains its currency and explicit valuation date.

The sampled dependency graph includes all model accounts, flows, entities and inputs, plus the calculations needed by ledger operations and selected metric values. It must support static indexed execution. Only calculations outside these dependencies are omitted from sampled trials. A calculation can remain dynamic for a baseline report when sampled outcomes and ledger operations do not depend on it.

Unsupported features produce DECCF_INVALID_MONTE_CARLO; there is no automatic fallback. They include sampled metric calculate callbacks; dynamic calculations or flows in the sampled graph; expression bindings or flow amounts; events, options and agreements; entity fields and lifecycles; triggered or trigger-relative flows; derived inputs; and account initial values supplied by a callback, expression, calculation or calculation projection. Static literals, input values, parameters and once bindings can initialize accounts. Existing model validation, finite-number checks and balanced-posting checks still apply.

Indexed mode summarizes declared numeric metrics only. It omits implicit sampled summaries for total, npv, irr and wal, while those metrics remain available in the full baseline. A numeric baselineMetrics value produces a fixed distribution: its mean, minimum, maximum and every percentile equal its baseline value, its standard deviation is zero, and its valid sample count is the requested trial count. This is an explicit fixed baseline outcome, not evidence that the metric is unaffected by uncertainty. Text and undefined values do not produce numeric summaries.

Active approximation (approximate: true with more than 1,000 trials) is rejected in indexed mode. At up to 1,000 trials the same request remains exact and reports inactive approximation. Pseudorandom and Sobol sampling are otherwise supported, including the usual power-of-two trial requirement for Sobol.

See Use indexed execution for declared outcomes for a complete deccf.defineModel() and deccf.runMonteCarlo() example.

Select sampling: "sobol" to use a randomized Sobol sequence instead of the default "pseudo-random" sampler:

Sobol requires a power-of-two trial count. It uses the Joe–Kuo direction numbers with a seeded lower-triangular matrix scramble and digital shift (LMS+shift). Every distribution, owner, period and uniform coordinate receives a stable slot before execution; normal and log-normal draws retain their two-coordinate Box–Muller transform. Conditional calls do not shift other inputs' streams. Slots are reserved even for overridden inputs. Model-wide ctx.draw() coordinates come first; potential per-owner, per-period ctx.sample() coordinates follow. Sobol supports the first 21,201 reserved coordinate positions (indexes 0 through 21,200). Unused slots beyond that range do not invalidate a run: a model using only its supported model-wide draw positions can run even when its potential owner/period namespace is larger. Attempting to sample a reserved position beyond the supported range still fails, regardless of how few other positions are used. samplingDimensions reports the full potential reserved namespace size, including unused slots, so it may exceed 21,201; it is not a count of the coordinates actually drawn. The supported slot assignments and same-seed streams remain unchanged. Structural scenario changes can change the slot layout; the same seed does not guarantee paired streams across different structures. Individual simulations still preserve all their history. Sobol can improve estimation accuracy with fewer simulations, but does not guarantee a faster run or improvement for every model. The reported standard deviation describes the distribution of outcomes, not uncertainty in the mean estimate. Use independently seeded replicate batches to assess numerical estimation error.

Static-first Sobol layout

Set monteCarlo: {samplingLayout: "static-first"} in deccf.defineModel() to reserve declared bind.sample() coordinates before the other potential owner/period samples. This is optional, independent of execution: "indexed", and shared by Monte Carlo runs and scenarios. Omitting it keeps the existing coordinate layout and same-seed streams. Other supplied values are rejected with DECCF_INVALID_MONTE_CARLO.

Model-wide ctx.draw() positions remain first and unchanged. Next come the declared static samples, ordered by input name and period: annual bindings use the first represented period in each calendar year, including partial years, while period bindings use every model period. Multiple consumers of the same input and period share their existing sample. Remaining ctx.sample() positions follow, ordered by input, owner and period, with promoted positions removed. A dynamic model-wide sample of an already promoted input/period shares that logical sample; different owners, periods, inputs and Box–Muller coordinates never share a position. The layout reserves slots even for unused bindings, branches and overridden inputs and does not depend on call order or worker count.

This moves a long forecast's declared annual samples ahead of its potentially large entity/period grid. It changes Sobol sample streams only when explicitly selected; global draws and pseudorandom streams retain their values. The same structural model, inputs and seed remain reproducible across general, indexed and parallel execution. Structural scenario changes can change positions. The 21,201 coordinate limit still applies to actual draws, including dynamic callbacks; an unsupported position fails explicitly. samplingDimensions still reports the full potential namespace, including unused positions, so it can exceed 21,201 in a successful static-first run.

Approximate Monte Carlo

Set approximate: true to permit approximation. It activates only above 1,000 trials; smaller runs still use exact draws and report approximation.active: false. Defaults remain exact. The Calculator and Web API support up to 4,096 trials per scenario, including balanced Sobol sizes 1,024, 2,048 and 4,096.

Approximation divides each uniform random coordinate into midpoint bins before transforming it to the chosen distribution. approximationBins accepts 16–4,096, with default 64. This changes the sampled distribution, including its tails; more bins give finer resolution. Flow amount callbacks with one or two directly sampled numeric dependencies can reuse observed grid values in a bounded table of up to 256 points per flow and period. Conditional branches keep their original read order. Callbacks that read history, mutable state, trigger sources or dependent calculations remain fully evaluated. There is no interpolation across unobserved cells.

When at least 20 distinct, actually evaluated grid points return the same amount, a histogram shortcut may reuse that amount for new points. Every eighth shortcut attempt reevaluates the callback. Observed variation or newly discovered unsafe dependencies permanently disables this shortcut for the affected flow and period. Earlier skipped rare outcomes cannot be recovered automatically; the result always includes a caution when histogram shortcuts were used.

Observed one- and two-input response curves are checked for sharp jumps or changes of slope. Warnings name the affected flow and period; sparse or capped observations are marked insufficient. This is a diagnostic, not an accuracy guarantee: an unseen threshold can still be missed. Run the exact mode to check important estimates, quantiles and rare events. Approximation counters, warnings and assessment status are returned under result.approximation and shown beside the Calculator's summaries.

Numeric metric columns and sorting scratch are private to each executor and reused across metric summaries. Full simulation histories remain separate per trial, including histories reachable through retained callback contexts. Repeated growing cashflow and posting sums extend an ordered fold instead of restarting at the beginning; they retain the original floating-point addition order and read-permission checks.

Scenarios

runScenarios(model, [{ name, overrides }], options) evaluates every named scenario and returns an array of { name, result }, plus batch timings on the array. Each overrides value is a Map keyed by declared input references; scalar inputs use their usual values, while curve inputs use { series: { points, interpolation } }. Put scenario-specific model inputs in each scenario's map. Shared run options such as currency and discount rate apply to every scenario. Pass trials and seed to run Monte Carlo trials for every scenario and receive a summary result per scenario. Object-based deterministic.inputs is available to ordinary run() calls, but is not the scenario override format.

The Calculator's Scenarios tab calls this batch API when you select Run model. It submits all cards together, merging each card's selected values over the current Model inputs, then displays the returned scenario results through report tabs. See Create scenarios in the Calculator.

Models can also declare editable scenario proposals with defineModel({scenarios: [{name, input}]}). Each input is a partial plain-value tree keyed by preconditions. These proposals initialize a fresh Calculator session; they do not alter ordinary run() behavior. Saved or edited cards take precedence. See Suggest scenarios in the model.

Scenario and goal metrics

deccf.analysis.scenario(), deccf.analysis.first() and deccf.analysis.threshold() declare ordinary scalar metrics. Each candidate evaluates the same accounts, flows and calculations in fresh state, using the baseline inputs with the requested scalar leaf changes. The original inputs remain unchanged, including object structure, arrays and Money values. Analysis metrics emit once at the final model period. Candidate runs exclude all analysis metrics, so analyses cannot select one another.

scenario({metric, changes?, compare?, onInvalid?, label?, unit?}) selects the candidate's final numeric or Money metric. changes contains {input, value} entries targeting declared scalar input leaves, including leaves inside object inputs. Its onInvalid option defaults to "error". Choose "omit" to leave this metric absent when changed inputs fail ordinary input validation, for example when a delayed date exceeds a declared upper bound. Calculation and financial callback failures still propagate. Its optional compare(candidate, baselineContext) callback performs a pure financial comparison using the candidate's nominal scalar value and baseline financial references. Money retains its currency and explicit valuation date; the selected output valuation applies once. Selecting built-in total preserves its per-cashflow-date valuation; selecting npv preserves its base-date amount. These aggregates are not deflated again at the final period. A compare callback receives nominal candidate values, including nominal aggregate totals.

first({input, from, to, metric, atLeast?, atMost?, changes?, compare?, label?, unit?}) finds the earliest feasible integer, testing every candidate from ceil(from) through floor(to) in ascending order. It requires an integer input and does not assume monotonic feasibility. For example:

Declare age and an ordinary numeric feasible metric in the same model and include earliest in its metrics. The result is the first feasible integer, including zero, or no emitted value when no candidate is feasible. Bounds must be ordered safe integers spanning at most 10,000 candidates.

threshold({input, from, to, metric, atLeast?, atMost?, select?, tolerance?, maxIterations?, changes?, compare?, label?, unit?}) bisects a bounded decimal, rate or fraction input. Feasibility must be monotonic across the interval: select:"minimum" assumes infeasible values followed by feasible values, while "maximum" assumes the reverse. The default selection is "minimum". An already feasible selected endpoint returns immediately; an infeasible opposite endpoint produces no emitted value. The returned side always remains feasible, including when the iteration limit is reached. Absolute tolerance defaults to 1e-6 in the searched input's units; maxIterations defaults to 80 and must resolve to an integer from 1 to 256.

For both goals, atLeast defaults to 1; use atMost for an upper limit. Supplying both is invalid. Bounds, targets, tolerance and iteration limits accept finite numbers, declared input references or input-only arithmetic expressions. Changes additionally accept Money, text and booleans. Unknown references or metrics, duplicate changes, nonnumeric goal results and invalid input values fail validation. No feasible result is represented by an absent scalar metric and null series observations.

All three declarations accept compare(value, baselineContext) for a pure financial comparison. For a goal, value is the found input scalar; for a scenario it is the selected nominal metric. Returning undefined omits the output. The callback does not run when a goal has no feasible result.

Put analysis metric names in monteCarlo.baselineMetrics to evaluate comparisons and searches once during the complete baseline calculation. Their baseline values are then shared by trials; they describe deterministic planning decisions rather than sampled uncertainty.