Simulate uncertainty
Choose a distribution and explicitly sample it in a declared binding or supported model callback. Declaring a distribution alone does not make results uncertain: ctx.get(distribution) and ordinary bindings use its central value.
For a financial forecast, keep editable rate means in the input domain and illustrative standard deviations in code, using hidden distribution declarations. The complete annual returns example combines editable dollar capital and an annual effective return, a hidden normal shock, native monthly periods and previous-balance compounding. It includes a separate standard metric-card presentation and ready Monte Carlo controls with 64 trials and Sobol. These defaults suit an app with useful uncertainty; an ordinary arithmetic calculator can keep deterministic defaults. Code comments explain the units, timing and illustrative volatility assumption.
Use bind.sample(shock,{calendar:"annual"}) for annually resetting interest, investment returns, inflation or appreciation. A fixed contractual assumption or horizon-wide WACC uses bind.once(ctx => ctx.draw(shock)) instead. Reuse a shared rate in related financial objects and comparisons. Accumulate the changing returns from previous balances or a native running product; applying the latest sampled rate to the whole elapsed horizon would rewrite the earlier returns.
For Sobol forecasts with many entities and periods, add monteCarlo: {samplingLayout: "static-first"} to reserve the declared annual samples before the potential owner/period grid. This explicit opt-in changes Sobol sample streams, while global draws and pseudorandom streams retain their values. The limit remains 21,201 actual coordinates; samplingDimensions counts the full potential namespace. See the complete contract and callable example.
Choose matching model and financial-object calendars. Preserve opening values, end-of-period timing and nominal/effective rate conversion. Keep ordinary debt rates nonnegative, compounded rates above -1, and DCF discount rates strictly above terminal growth. Tax, fee, VAT, allocation and degradation shares do not become random interest assumptions merely because they are rates.
Available distributions are normal, logNormal, uniform, and triangular. Put clip on the distribution parameters; it limits the central value and samples. Input types and domain can add further validation. The engine does not provide a correlation matrix.
runMonteCarlo() requires a positive integer trials count and an integer seed. Summaries include mean, standard deviation, minimum, maximum, and percentiles p5, p25, p50, p75, and p95.
In the Calculator, open Run input, choose Monte Carlo, then set the trial count and seed before selecting Run model. The result includes both the ordinary base calculation and the simulation summaries. Period-by-period reports, balances and KPI cards use the base calculation with central input values; histograms and Monte Carlo summaries show the sampled outcomes. The base calculation uses the same input overrides and does not depend on the seed or number of trials. It is a separate calculation, not a randomly chosen trial or the mean of the simulation.
If execution lasts longer than 300 ms, a progress ring appears in the input toolbar. It measures completed baseline, trial and summary work. The ring softens from 90%, reaches 100% only after a successful result is accepted, then fades away. Canceling or failing clears it without 100%. The previous report remains visible while the new run finishes. This feedback is automatic: keep progress UI and custom simulation loops out of the financial model. See Calculation progress for the optional observation and Web API contracts.
Calculator runs can distribute independent simulations across up to 32 workers, limited by available processing capacity and batch size. Small batches stay sequential to avoid worker startup costs; larger batches can use more available processors. This applies to browser execution and hosted execution where parallel processing is available. The same model, inputs, seed and sampling method produce the same statistics regardless of the worker count. Canceling the run stops the worker group.
Workers reuse eligible immutable values that are constant across trials. Money values and records containing Money remain local to each worker; their object identity is preserved. Sampled values, balances and postings stay separate for each trial, and caches are discarded between different runs or scenarios. Active approximate mode keeps its sequential learning order. Parallel processing can reduce elapsed time when enough processing capacity is available; it does not change the model's monthly calculation steps.
Use indexed execution for declared outcomes
Set monteCarlo: {execution: "indexed"} in deccf.defineModel() when the simulation can calculate its outcomes through static bindings. Indexed execution skips report calculations that the sampled outcomes and ledger do not need. The model still follows every monthly period, and the returned result includes the complete ordinary base calculation.
Declare each sampled outcome with deccf.metric({value, schedule}), selecting the final model period. Use a calculation, its projection, or an account as the value source. All the calculations and ledger operations needed by these outcomes must support static execution. See Static bindings for declaring dependencies and sampled configuration.
const initialCapital = deccf.input.money(10000, deccf.currencies.SEK);
const annualReturn = deccf.input.uniform({min: 0.02, max: 0.08});
const sampledReturn = deccf.bind.once(ctx => ctx.draw(annualReturn));
const wealth = deccf.calculation({
name: "wealth",
resultType: "number",
bindings: {initialCapital, sampledReturn},
calculate: ({initialCapital, sampledReturn}, {time}) =>
initialCapital.amount * (1 + sampledReturn) ** ((time.index + 1) / 12),
});
const finalDate = deccf.schedule.once("2026-12-01");
const model = deccf.defineModel({
currency: deccf.currencies.SEK,
timeline: deccf.periods.monthly({from: "2026-01", count: 12}),
preconditions: {initialCapital, annualReturn},
calculations: {wealth},
monteCarlo: {execution: "indexed", baselineMetrics: ["startingCapital"]},
metrics: {
finalWealth: deccf.metric({value: wealth, schedule: finalDate, unit: "money"}),
startingCapital: deccf.metric({schedule: finalDate, calculate: ctx => ctx.get(initialCapital)}),
},
});
const simulation = deccf.runMonteCarlo(model, {trials: 128, seed: 7, sampling: "sobol"});
// finalWealth contains sampled year-end amounts in SEK.
// startingCapital has mean 10000 and standardDeviation 0.
return model;baselineMetrics is optional and defaults to an empty list. A listed metric is evaluated during the ordinary base calculation, then its final numeric value is repeated in the simulation statistics. Its standard deviation is zero and every percentile equals its baseline value. Use this only for outcomes that should deliberately remain fixed at the base case. These statistics do not estimate that metric's uncertainty.
Indexed mode summarizes only declared numeric metrics. It omits automatic sampled total, npv, irr and wal summaries; the full baseline retains those ordinary metrics. Update any histogram or uncertainty chart that selected an implicit metric before opting in. Omitting monteCarlo preserves the existing general calculation mode and its summaries.
The sampled metrics must retain periodLength: 1 and frequency: 1, their defaults, and run exactly once in the last model period. Unsupported metric callbacks, dynamic sampled dependencies and unsupported ledger features produce an error. There is no automatic fallback. Dynamic reports outside the sampled dependencies can still run in the complete baseline. approximate: true remains exact at up to 1,000 trials; active approximation above 1,000 trials is incompatible with indexed mode and is rejected. See Valuation and uncertainty for the complete contract.
Store results and choose draws
To reduce saved output, choose Store amounts → Calendar year or Fiscal year in Run input. See Store monetary results by year for aggregation rules and report choices.
ctx.get(growth) always returns the distribution's central value. ctx.draw(growth) reuses a draw across periods within one trial. ctx.sample(growth) draws separately by period and owner. A plain run(model) uses the central value when a callback calls draw() or sample() without a seed and trial.