Savings domain pack
savingsPlan() builds a recurring balance, contribution, return, fee and withdrawal from existing DECCF calculations, fields and cashflows. The cashflow perspective is the saver: contributions are outflows and actual withdrawals are inflows. Fees reduce the balance and are not recorded as a second cash payment.
const { savingsPlan, withdrawals } = modules.savings;
const fund = savingsPlan({
owner: subject,
calendar: "monthly",
openingBalance: currentSavings,
annualRate: investmentReturn,
contribution: annualDeposit,
contributionPlacement: "end",
withdrawal: withdrawals.byDivisor({ divisor: distributionDivisor }),
});
return defineModel({
name: "savings projection",
currency: currencies.USD,
timeline: periods.monthly({ from: "2026-01", count: 120 }),
preconditions: { currentSavings, investmentReturn, annualDeposit, distributionDivisor },
entities: { subject },
components: { fund: fund.component },
metrics: { ending_balance: (ctx) => ctx.get(fund.balance) },
});Rates are nominal by default, and the configured calendar must match the model calendar. Contributions can be placed at the start or end of each period. feeRate is a period rate charged on opening balance. Withdrawals happen at period end; the actual withdrawal is capped to available funds by default and any shortfall is reported separately. Use insufficientFunds: "error" to reject any such shortfall.
The component returns ordinary field, calculation and flow references for composition. Callback sources may read only declared inputs, calculations and opening accounts. Withdrawal callbacks also receive the already calculated opening balance, return base, growth, fee and available amount. Use an explicit dependsOn for same-period calculation reads.
A contribution may be a signed budget surplus. A positive value is deposited; a negative value requests a withdrawal to cover the deficit, in addition to any configured withdrawal. With the default capped withdrawals, the savings balance stays at or above zero and the uncovered amount appears in withdrawalShortfall and its accumulated total. With insufficientFunds: "error", an uncovered deficit stops the calculation.
Retirement planning
Choose Retirement planning for the original annual projection or Retirement planning · accounts for an explicit monthly account model. The accounts example creates a person and an owned retirement portfolio. Income, spending, saving, withdrawals and investment gains or losses settle as ordinary monthly account postings; annual reports aggregate those monthly observations.
In Retirement planning · accounts, Financial assumptions → Rate range and search precision → Threshold search precision · iterations defaults to 24. Each iteration halves the search interval for the inflation buffer and minimum-return comparisons. With the default interval from almost −100% to 1,000%, 24 iterations resolve rates within 11 / 2^24, about 0.0000656 percentage points. The setting remains editable from 1 to 100; a saved or explicitly entered value of 55 still uses 55 iterations. It changes these two comparison thresholds only. The monthly savings, income, expenses, returns and funded-year calculations retain their precision. The original projection helper's default remains 55 iterations.
In the Retirement planning example, change comparison amounts, percentages and the retirement delay on What if, the input page after Retirement. The Financial assumptions tab groups inflation, investment returns, pension growth and Annual income increase (%). Other tabs contain horizon, compounding, cash-flow timing, income surplus, milestone multiples, budget ages, threshold search, uncertainty and the withdrawal safety reference. Expenses are entered in today's money and increase with inflation from the current age, including working years. Annual income growth applies to working income and other retirement income from the current age; pension uses its own growth rate. Annual saving stays the same nominal amount each year. Changing a comparison updates both its calculation and its card text.
Current income/expense has Income and Expense tabs for annual working-year figures. These amounts provide lifetime chart context; Annual Savings (Until Retirement) remains a separate assumption. Newly created examples start with annual income of 80,000 and expenses of 55,000 in the model's currency, matching the separate 25,000 savings assumption. Older input records that omit the page keep working income and expenses unknown. New runs start with Monte Carlo, 128 simulations and Sobol sampling.
The example uses its existing inflation assumption for the result choice between nominal amounts and today's money. Changing that output choice keeps the same savings, returns, withdrawals and funding outcomes. Each age is dated relative to the model's starting date and current age: opening portfolios, annual budgets and retirement targets use that age's anniversary; closing portfolios and final legacy use the next anniversary, after the year's withdrawal and return. This also applies to the lifetime chart and Monte Carlo percentiles. Legacy and milestone targets display as monetary amounts, with coverage percentages shown separately. Funding-gap cards summarize the amount needed from capital; the charts and annual tables show the full income and expense budget. What-if labels describe the entered assumptions.
Income standard deviation controls a shared annual growth shock for working income, other income and pension. Its default is 0.5 percentage points, clipped between −1.5 and +1.5 percentage points, compared with the inflation shock's 1 percentage point standard deviation. Each income keeps its own growth assumption: the same annual shock is added to income growth and pension growth when each applies. Past accrued increases stay fixed; uncertainty applies to future years. Set the income standard deviation to zero to keep both growth paths fixed. The new controls are optional in saved input records and use their declared defaults when missing.
retirementProjection: monthly savings and retirement income
Use modules.savings.retirementProjection() in a calculation to compare a retirement plan, inspect its annual budget and test different choices. Supply all age, amount and rate assumptions as ordinary numbers. Amounts use one consistent currency and annual rates use decimal fractions, such as 0.06 for 6%.
const plan = modules.savings.retirementProjection({
currentAge: 49, retirementAge: 65, lifeExpectancy: 95, pensionStartAge: 67,
currentSavings: 450000, annualSavings: 25000,
preRetirementReturn: 0.06, postRetirementReturn: 0.04,
inflation: 0.03, pensionAnnualIncrease: 0.025,
monthlyPension: 3500, monthlyOtherIncome: 300, annualExpenses: 55000,
// Optional: omit any setting to keep the original default.
includeLifetimeRows: true,
annualWorkingIncome: 80000, annualWorkingExpenses: 55000,
horizonAge: 150, accumulationPeriodsPerYear: 12,
contributionPlacement: 'end', withdrawalPlacement: 'start',
reinvestIncomeSurplus: false, otherIncomeAnnualIncrease: 0,
expenseInflationStartYear: 2, budgetAges: [65, 66, 67, 76, 86, 95],
milestoneMultiples: {ten: 10, twentyFive: 25, thirty: 30, thirtyThree: 33},
whatIf: {
delayYears: 1, annualSavingsAfterStopping: 0,
extraMonthlySavings: 500, extraMonthlyIncome: 500,
lowerExpenseReduction: 0.1, higherExpenseIncrease: 0.1,
pensionRemoval: 1, pensionReduction: 0.5, marketCrashLoss: 0.2,
},
rateBounds: {minimum: -1 + Number.EPSILON, maximum: 10},
thresholdSearch: {minimumRate: -1 + Number.EPSILON, maximumRate: 10, iterations: 55},
});
const retirementSavings = plan.summary.startingPortfolio;
const currentYear = plan.lifetimeRows.age49;
const pensionYear = plan.rows.age67;
const extraIncomeDepletionAge = plan.whatIf.extraIncomeDepletionAge;Optional retirementProjection settings
The defaults below reproduce the workbook. Every supplied group can contain just the members you want to change. For example, whatIf: {extraMonthlySavings: 1000} changes extra savings to 1,000 per month while keeping every other comparison unchanged. Comparison results keep their existing names; noPensionDepletionAge uses pensionRemoval, and halfPensionDepletionAge uses pensionReduction, even if those fractions differ from 1 and 0.5.
| Optional setting | Default and behavior |
|---|---|
execution | "legacy" when omitted; "timeline" runs the projection, earliest-retirement candidates, comparisons and threshold trials through annual DECCF periods and the personal account ledger. The report fields and financial timing are the same. Other values are rejected. |
dynamic | false; custom sampleReturn, sampleInflation, sampleIncomeIncrease and samplePensionIncrease callbacks require true for either execution mode. Use annualRates for data-only sampled paths. The component retirementPlan uses its own top-level dynamic setting. |
annualRates | Omitted; optional accumulationReturn, retirementReturn, inflation, incomeIncrease and pensionIncrease maps contain absolute annual decimal rates keyed by age, such as age65. Missing ages use the corresponding mean. See annual rate data below. |
includeLifetimeRows | false; true adds the lifetimeRows record. Omission keeps the exact existing result shape. Non-boolean values are rejected. |
sampledEarliestRetirement | false; the earliest-retirement search uses the mean rates. Set true to check every candidate age against the same sampled annual return, inflation and income path, through life expectancy. Reuse stored annual shocks by age across callbacks; the search can call them repeatedly. What-if comparisons keep the means. Non-boolean values are rejected. |
annualWorkingIncome | Omitted; working-year income is null. A supplied finite nonnegative annual amount is constant chart context through the year before retirement. |
annualWorkingExpenses | Omitted; working-year expenses is null. A supplied finite nonnegative annual amount is constant chart context through the year before retirement. |
includeSavingsInWorkingExpenses | false by default. Set true when annualWorkingExpenses excludes saving: each working-year expense becomes the inflation-adjusted living amount plus the fixed nominal annualSavings. Working gap reports max(0, expenses - income) when both amounts are known. Deposits are not counted twice; portfolio accumulation and retirement expenses keep their existing calculations. |
horizonAge | 150; last year checked for longevity and sampling, at least life expectancy. |
accumulationPeriodsPerYear | 12; divides the nominal annual return and annual contributions into equal periods. |
contributionPlacement | "end"; choose "start" for contributions before each working-period return. |
withdrawalPlacement | "start"; choose "end" to apply the annual return before withdrawal. |
reinvestIncomeSurplus | false; true deposits positive income minus expenses at the withdrawal placement. |
otherIncomeAnnualIncrease | 0; annual decimal increase from the second retirement year. |
expenseInflationStartYear | 2; first one-based retirement year receiving expense inflation. |
expenseInflationBaseAge | Omitted; keeps the existing retirement-year expense timing. An integer from 0 through currentAge instead treats both expense amounts as money at that age, inflates them once per elapsed year, and uses inflated first-retirement-year costs for milestone targets. Overrides expenseInflationStartYear. |
incomeIncreaseBaseAge | Omitted; working income stays constant and other income grows from retirement. An integer from 0 through currentAge instead anchors working income and monthly other income to that age, growing both by otherIncomeAnnualIncrease per elapsed year. Pension growth remains separate. |
budgetAges | First two retirement ages, pension start, retirement years 12/22 and life expectancy; an explicit list keeps its order, removes duplicates and omits out-of-plan ages. [] selects none. |
milestoneMultiples | {ten:10, twentyFive:25, thirty:30, thirtyThree:33}; partial nonnegative overrides keep the same result keys. |
rateBounds | {minimum:-1+Number.EPSILON, maximum:10}; validation bounds for all annual rates, including callbacks and other income increases. |
thresholdSearch | Bounds inherit rateBounds; 55 bisection iterations. Partial overrides can narrow the searched interval or change precision. |
The complete whatIf group and its defaults are shown in the callable example above. Amounts and expense increases must be finite and nonnegative; reduction and loss fractions must lie between 0 and 1. Ages and iteration counts must be integers. Rate bounds must be finite, increasing and strictly above −100%; threshold bounds must be increasing and inside them. Invalid settings are rejected even when includeWhatIf is false. Omitted and undefined members keep defaults; null groups and unknown group members are rejected.
To enter expenses and income in today's money, set both base ages to the current age:
const plan = modules.savings.retirementProjection({
currentAge: 40, retirementAge: 65, lifeExpectancy: 95, pensionStartAge: 67,
dynamic: true,
currentSavings: 450000, annualSavings: 25000,
preRetirementReturn: .06, postRetirementReturn: .04,
inflation: .02, pensionAnnualIncrease: .025,
monthlyPension: 3500, monthlyOtherIncome: 300, annualExpenses: 55000,
expenseInflationBaseAge: 40, incomeIncreaseBaseAge: 40,
otherIncomeAnnualIncrease: .03,
annualWorkingIncome: 80000, annualWorkingExpenses: 55000,
includeLifetimeRows: true, includeSavingsInWorkingExpenses: true, includeWhatIf: false,
sampleIncomeIncrease: ({mean}) => mean,
samplePensionIncrease: ({mean}) => mean,
});
const retirementExpenses = plan.rows.age65.expenses;Age 40 keeps the entered amounts; age 41 expenses rise by 2% and working income by 3%. Age 65 expenses include 25 annual increases, and age 66 includes 26. Other retirement income includes the same elapsed income increases. Annual saving remains 25,000, independently of the working budget. With either base age supplied, a retirement target below the current age starts retirement now, using current savings without recreating historical withdrawals. Life expectancy must still include the current age. Invalid, null, fractional or future base ages are rejected. Omitting both base ages preserves existing projections.
For bounded execution, the function accepts horizon ages through 150, up to 366 accumulation periods per year, up to 1001 explicit budget ages, an inflation starting year from 1 through 1001, and 1–100 threshold iterations. Twelve calendar months convert monthly pension, income and extra savings to annual amounts regardless of compounding frequency. Bisection leaves a rate interval no wider than its initial width divided by 2 ** iterations. A feasible lower return boundary or upper inflation boundary returns that boundary; an infeasible search returns null. The following paragraphs describe the defaults; the optional settings above override these conventions.
This example reaches about 1,841,396 at retirement and leaves about 4,561,910 after the age-95 year. Contributions of annualSavings / 12 occur at each month end while working, with monthly growth of preRetirementReturn / 12. Retirement years start with the stated expenses, reduce the funding gap by pension and other income, withdraw that gap, then grow the remaining portfolio by the annual retirement return. Inflation first increases expenses in the second retirement year. Pension starts at monthlyPension * 12 at pensionStartAge and increases each later year by pensionAnnualIncrease. Other income stays constant. Income above expenses does not add to the portfolio.
rows contains annual records named by age, from retirement through life expectancy, both inclusive. Each row includes the opening portfolio, annual income and expenses, the gap, withdrawalRate, actual withdrawal, shortfall, closing portfolio, and whether that year is funded or is a pension bridge year. The budget record selects the first two years, pension start, years 12 and 22, and the final year, omitting duplicates and dates outside the plan. Its keys are also age names.
Lifetime retirementProjection records
Set includeLifetimeRows: true to add annual chart records in lifetimeRows from currentAge through lifeExpectancy, inclusive, in age order. By default the property is omitted, preserving the exact result shape expected by existing models. Each age key, such as age49, contains age, phase, portfolio, closingPortfolio, income, expenses and gap. The phase is "accumulation" before retirement and "retirement" afterwards. portfolio is the opening balance at that age; closingPortfolio includes that year's contributions, withdrawals and return. Every closing balance is the next year's opening balance, including the transition into retirement. Working balances use the existing compounding pass and the same annual return draws, with no extra sampling calls. Retired records copy the matching values from rows; the existing rows, budget and summary keep their meaning.
Working income and expenses are optional context. annualWorkingIncome and annualWorkingExpenses each default to undefined, producing null for the corresponding working-year field. A supplied value is a finite, nonnegative annual amount in the plan's currency and stays constant through the year before retirement unless its corresponding base age is supplied. With base ages, income grows by the annual income increase and expenses share the same inflation factors as retirement costs. With the default includeSavingsInWorkingExpenses: false, working gap is 0 when both amounts are known because the working projection makes no portfolio withdrawals. With includeSavingsInWorkingExpenses: true, the entered living expenses exclude saving: inflation applies only to those living expenses, then the same nominal annualSavings is added each working year. Its working gap is max(0, expenses - income). If either amount is unknown, gap remains null. A reported working shortfall is budget context; it does not withdraw money from the portfolio or change the independently entered savings deposit. These amounts do not derive or replace annualSavings: enter saving separately, even when expenses exceed income. Supplying them never changes portfolio balances, retirement budgets, longevity, comparisons or milestones. Explicit null, negative amounts and nonfinite values are rejected, including when includeWhatIf is false.
The summary reports the retirement starting portfolio, years to retirement, planned retirement and bridge years, final legacy, maximum withdrawal rate and average bridge withdrawal rate. portfolioLasts requires every planned year to be funded: a later pension cannot erase an earlier shortfall. The calculation checks through horizonAge, 150 by default. depletionAge is the first uncovered year, fundedUntilAge is the preceding age, and yearsFunded counts consecutive completed years. Both ages are null when all years through the horizon are funded; display that case as the horizon followed by “+”. longevityBuffer subtracts planned retirement years from yearsFunded. These are bounded estimates. earliestRetirementAge tests whole retirement ages from the current age through life expectancy, and is null when no age funds the plan. It uses the stated mean rates by default; sampledEarliestRetirement: true instead uses the supplied annual sampling callbacks.
whatIf tests delaying retirement one year, retiring now, stopping contributions, saving 6,000 more per year, receiving 500 more monthly other income, lowering or raising expenses by 10%, removing or halving pension, and a 20% loss at retirement. Depletion ages are null for 150+. delayYearsGain and extraSavingsYearsGain express the extra retirement starting capital in years of the baseline first-year funding gap: extra capital divided by first-year expenses less first-year income. They measure spending-equivalent years, rather than extra funded years, and are null when that gap is zero. The example gains about 2.7 such years by delaying one year, or 3.1 by saving an extra 500 per month. Delaying is unavailable (null) at the plan's final age. minimumReturn is the lowest annual retirement return funding every planned year. inflationBuffer is the highest sustainable inflation minus the selected inflation, expressed as a decimal rate difference; it can be negative. A threshold is null if the supported rate range cannot fund the plan. Set includeWhatIf: false to skip comparisons and threshold searches and receive whatIf: null.
milestones reports targets of 10, 25, 30 and 33 times first-year expenses. Each includes its multiplier, target amount, and coverage as retirement savings divided by the target. Coverage is null when expenses are zero. Withdrawal rates are null for a positive funding gap with no opening portfolio, and zero when both are zero.
Annual rate data and dynamic sampling
For static sampled calculations, pass annualRates with any of these channels: accumulationReturn, retirementReturn, inflation, incomeIncrease and pensionIncrease. Each channel is a plain age-keyed record, for example retirementReturn:{age65:0.03,age66:-0.1}. Values are absolute annual decimal rates, not shocks added to the mean. Missing channels or ages use their corresponding mean assumptions. Keys must be canonical age0 through age150; values must be finite and inside rateBounds. Unknown channels, malformed keys and null maps are rejected. Data is copied so later source mutations cannot change the resolved configuration.
The main projection uses these paths, and sampledEarliestRetirement:true reuses them for candidate retirement ages. Deterministic what-if comparisons and threshold searches keep the means. A channel cannot be combined with its corresponding sample callback: sampleReturn conflicts with either return channel; the other callbacks conflict with their matching channel.
const sampledPlan = modules.savings.retirementProjection({
execution:'timeline', currentAge:60, retirementAge:62, lifeExpectancy:64, pensionStartAge:67,
currentSavings:1000, annualSavings:0, annualExpenses:200,
preRetirementReturn:0, postRetirementReturn:0, inflation:0.02,
pensionAnnualIncrease:0, monthlyPension:0, monthlyOtherIncome:0,
horizonAge:67, includeWhatIf:false, sampledEarliestRetirement:true,
annualRates:{inflation:{age61:0.03,age62:0.01,age63:0.04,age64:0.02}},
});
const earliestAgeOnThisPath = sampledPlan.summary.earliestRetirementAge;Custom synchronous sampleReturn({ age, phase, mean }) and sampleInflation({ age, mean }) callbacks require dynamic:true in a standalone retirementProjection, for both legacy and timeline execution. They return annual rate draws. Return phases are "accumulation" and "retirement"; one accumulation draw applies to every working period in that year (twelve by default). Inflation sampling begins at expenseInflationStartYear, the second retirement year by default. With expenseInflationBaseAge, inflation draws instead cover each age from the base age plus one through the horizon, including working years, exactly once per age in the main projection. Working expense rows and retirement costs share those factors. Callbacks continue through the horizonAge funding check and affect the main projection. All comparisons and, by default, the earliest-retirement search use the mean assumptions.
Optional sampleIncomeIncrease({age, mean}) returns the annual growth rate for the shared working and other-income path. It starts after incomeIncreaseBaseAge, or after retirement when that option is omitted. Working income stays constant when its base age is omitted. Optional samplePensionIncrease({age, mean}) returns pension growth from the year after pensionStartAge. Neither callback resamples past increases through currentAge, and the starting income and pension amounts are unchanged. Each callback runs once per applicable future age through the horizon in the main projection, regardless of whether lifetime rows are requested. It must return a synchronous finite annual rate inside rateBounds; invalid callback types and values fail. Omitted or undefined callbacks preserve fixed growth. Returning mean, as above, also keeps fixed growth. To correlate pension and other-income changes, share a sampled shock for each age and add it to each callback's own mean. What-if comparisons always keep the declared means.
Set sampledEarliestRetirement: true to evaluate candidate retirement ages from the current age through life expectancy using that same sampled annual path. The first age funding every remaining planned year becomes summary.earliestRetirementAge; it stays null if none does. This search runs even with includeWhatIf: false. Sampling callbacks can run repeatedly for a given age, including in different return phases: reuse a stored annual shock for that age and add the callback's own mean, instead of drawing a fresh shock per call. The Retirement planning example uses stable annual coordinates for this purpose. With no callbacks, turning the option on leaves the result unchanged.
const annualInflationShocks = new Map([[61, 0.01], [62, -0.01], [63, 0.02], [64, 0]]);
const sampledPlan = modules.savings.retirementProjection({
currentAge: 60, retirementAge: 62, lifeExpectancy: 64, pensionStartAge: 67,
dynamic: true,
currentSavings: 1000, annualSavings: 0, annualExpenses: 200,
preRetirementReturn: 0, postRetirementReturn: 0, inflation: 0.02,
pensionAnnualIncrease: 0, monthlyPension: 0, monthlyOtherIncome: 0,
sampledEarliestRetirement: true, includeWhatIf: false,
sampleInflation: ({age, mean}) => mean + (annualInflationShocks.get(age) ?? 0),
});
const earliestAgeOnThisPath = sampledPlan.summary.earliestRetirementAge;Ages must be integers from 0 through horizonAge (at most 150), with current age no greater than retirement age and life expectancy no smaller than retirement age. Pension start may be later than a shortened horizon, through age 150. Money must be finite and nonnegative. All annual rates, including callback results, must lie inside rateBounds (default strictly above -1 and at most 10). Invalid values or calculations too large to represent stop the calculation with a model error. The function requires scalar assumptions, so read the values of model inputs in the calling calculation before passing them.
A report using annual ledger execution
Select execution:'timeline' to compare the same report through native annual account projections. This changes the execution method for the base plan and its searches; the result still has summary, rows, budget, whatIf and milestones.
const report = modules.savings.retirementProjection({
execution:'timeline',
currentAge:62, retirementAge:65, lifeExpectancy:72, pensionStartAge:67,
currentSavings:450000, annualSavings:25000,
preRetirementReturn:.06, postRetirementReturn:.04,
inflation:.03, pensionAnnualIncrease:.025,
monthlyPension:3500, monthlyOtherIncome:300, annualExpenses:55000,
horizonAge:75, includeWhatIf:false,
});
const legacy = report.summary.legacy;Reuse a retirement calculator
modules.savings.prepareRetirementProjection({execution}) creates a synchronous calculator for repeated reports. The configuration is optional; execution accepts "legacy" or "timeline" and defaults to "legacy", matching retirementProjection. Unknown configuration names and unsupported modes are errors. The returned calculator takes the usual complete retirement assumptions, with execution omitted. Supplying a defined execution to a calculation call is rejected; create another calculator to change modes.
const calculateRetirement = modules.savings.prepareRetirementProjection({execution:'timeline'});
const assumptions = {
currentAge:62, retirementAge:65, lifeExpectancy:72, pensionStartAge:67,
currentSavings:450000, annualSavings:25000,
preRetirementReturn:0.06, postRetirementReturn:0.04,
inflation:0.03, pensionAnnualIncrease:0.025,
monthlyPension:3500, monthlyOtherIncome:300, annualExpenses:55000,
horizonAge:75, includeWhatIf:false,
};
const first = calculateRetirement(assumptions);
const increased = calculateRetirement({...assumptions,annualSavings:30000});
const extraStartingCapital = increased.summary.startingPortfolio-first.summary.startingPortfolio;Create the calculator once where the model declares its reusable values, then call it with the assumptions for each report. Both calls return the same complete report shape as retirementProjection. Each call freshly validates and copies its amounts, ages, annual rate data and nested settings. Mutating one call's source or result does not change another call's report. Timeline preparation is reused as needed within that calculator; reports, balances, history and sampled values are calculated afresh. Custom sampling callbacks still require dynamic:true and run independently for each call. Separate calculators do not share results or simulation state.
retirementPlan: compose the annual account ledger
Use modules.savings.retirementPlan({options, owner?, preconditions?, dependsOn?, reportSchedule?, dynamic?}) when other calculations need the person's account balances, assets or flows. retirementProjection({execution:'timeline', ...}) instead returns a completed report; its internally simulated accounts are not references in the surrounding model.
const person = deccf.entity.party({label:'Planner'});
const savings = deccf.input.money(450000, deccf.currencies.USD);
const plan = modules.savings.retirementPlan({
owner: person,
preconditions: {savings},
options: ctx => ({
currentAge:62, retirementAge:65, lifeExpectancy:72, pensionStartAge:67,
currentSavings:ctx.get(savings).amount, annualSavings:25000,
preRetirementReturn:.06, postRetirementReturn:.04, inflation:.03,
pensionAnnualIncrease:.025, monthlyPension:3500,
monthlyOtherIncome:300, annualExpenses:55000,
horizonAge:75, includeWhatIf:false, includeLifetimeRows:true,
}),
});
return deccf.defineModel({
currency:deccf.currencies.USD,
timeline:deccf.periods.annual({from:'2026-01', count:14}),
entities:{person},
components:{retirement:plan.component},
metrics:{portfolio:ctx=>ctx.get(plan.accounts.portfolio)},
});The first period represents currentAge, and every following annual period adds one age. Include all ages through horizonAge: count = horizonAge - currentAge + 1. The component does not select or replace the surrounding timeline. A different calendar or a period beyond the horizon is rejected. Changing age inputs also requires a matching timeline; derive its count from those inputs when they are editable. A shorter run has yearly balances but has not reached the final projection.
options is required. Pass a RetirementProjectionOptions object of scalar values, or a synchronous callback resolving that object once per execution or Monte Carlo trial. Its default configuration context reads declared inputs and bindings through get and supplies draw/sample; it has no time or ledger reads. Static configuration contains data only; use annualRates for sampled paths. Both forms accept the same amounts, rates, age constraints and optional defaults described above. All financial amounts are in the surrounding model's currency; the numeric records carry no separate currency conversion. The component always uses native periods, regardless of the execution setting inside options. A fixed options object is copied with resolved defaults when the component is created; later edits to that caller object do not change it.
Set top-level dynamic:true when the options callback needs the full calculation context and must be resolved per period, or when the options contain custom sampling callbacks. This top-level setting authorizes sampling callbacks; options.dynamic:true alone does not. Declare same-period dependencies with dependsOn. Keep age and horizon settings consistent throughout one run. The default dynamic:false resolves data-only configuration once and uses static bindings for the annual ledger calculations and flows.
owner defaults to a new party registered by the component. With a supplied person, declare it once in the surrounding model's entities; the component registers its owned asset and uses that person's standard accounts so other domain functions can target them. preconditions defaults to {} and declares input references used by an options callback. dependsOn defaults to [] and declares its same-period calculation dependencies. reportSchedule is an optional schedule limiting when the completed report is calculated; omit it to check each period. A schedule that skips the horizon will not produce a completed report.
The returned object contains these ordinary references:
| Member | Meaning |
|---|---|
component | Include this in defineModel({components}) to register the ledger, entities, flows and calculations. |
person | The supplied owner or the generated party. |
asset | The retirement portfolio asset, owned by person. The investment balance is held in the person's standard account. |
accounts | Named standard account references, described below. |
flows | Named posting cashflows: workingIncome, pension, otherIncome, expenses, contribution, withdrawal, growth and loss. |
calculations.year | Current year's opening portfolio, contributions, investment growth, income, expenses, requested and actual withdrawals, shortfall and financial factors. It is calculated during the ordinary period phase. |
calculations.history | Flat periodEnd state: openingPortfolio, closingPortfolio, legacy, depletionAge, yearsFunded and portfolioLasts. Closing portfolio includes all settled postings; the other fields retain their cumulative funding meaning. There are no rows or lifetimeRows maps here. Use deccf.bind.history(plan.calculations.history) for prior state snapshots; the final projection assembles complete rows once. |
calculations.projection | At periodEnd, null before the horizon, then the complete RetirementProjectionResult, including the selected budget, milestones, earliest retirement and optional comparisons. |
The account references use the following personal account-plan codes. The general living expense leaf expense.other can coexist with separately classified housing, food and tax accounts.
| Account reference | Personal code |
|---|---|
accounts.cash | assets.cash.bank |
accounts.portfolio | assets.investments.brokerage |
accounts.netWorth | equity.retained_earnings |
accounts.workingIncome | income.employment.net_salary |
accounts.otherIncome | income.other.net |
accounts.pensionIncome | income.pension.net |
accounts.investmentIncome | income.capital.other |
accounts.expenses | expense.other |
For reports, read calculations.projection in a metric after the last period or from another phase:'periodEnd' calculation with a declared dependency. A period-phase calculation cannot depend on period-end results. If includeWhatIf is omitted, comparisons and threshold searches are included; set it to false for whatIf:null when only the ledger and base projection are needed. Counterfactuals use isolated native projections with the same assumptions. Additional flows attached by the surrounding model affect its main ledger; they are not copied into those counterfactual projections.
Portfolio contributions transfer funds from accounts.cash to accounts.portfolio; withdrawals transfer them back. Contributions, withdrawals, growth and losses belong to the owned asset; income and spending flows belong to person. Person-level results include the owned asset, while asset-level results can show its investment flows separately. Growth and losses change the investment value against investment income and have zero cash movement. Retirement income above spending stays in the bank unless reinvestIncomeSurplus:true transfers it into the portfolio. The next year reads the actual settled portfolio account, including postings from other components. The final history observes all current-period postings as well, so an extra transfer in the final year appears in legacy. The yearly funding test still describes this component's requested retirement withdrawal; separately added obligations need their own funding checks.
Working income and expenses retain their informational budget meaning from the original projection. Saving remains the separately entered nominal amount even when the working budget does not cover it. The ledger records these amounts without inventing extra income or an automatic portfolio withdrawal to finance a working deficit; the bank account can therefore be negative. Retirement expenses are also posted in full when a capped withdrawal leaves a shortfall. Use the reported shortfall and bank balance when composing additional funding logic.
Entered income and returns are after-tax planning assumptions. Working income uses income.employment.net_salary, pension uses income.pension.net, and other income uses income.other.net. These accounts describe net cash receipts and are separate from gross salary and gross pension categories used by income-tax calculations. Investment growth uses income.capital.other. Selecting a tax domain does not make these assumptions a complete gross-income or taxable-capital model: supply the appropriate tax bases and avoid charging tax twice when extending the plan.