A local-first personal finance app
:chart_with_upwards_trend: Monte Carlo income streams (#8955)
Michael Clarkdc006aa19275
diff --git a/packages/component-library/src/Menu.tsx b/packages/component-library/src/Menu.tsxindex 8da0f8dc28..56f27c1387 100644--- a/packages/component-library/src/Menu.tsx+++ b/packages/component-library/src/Menu.tsx@@ -84,16 +84,26 @@ export function Menu<const NameType = string>({const currentIndex = filteredItems.indexOf(items[hoveredIndex || 0]);const transformIndex = (idx: number) => items.indexOf(filteredItems[idx]);+ // Keyboard navigation starts on the first selectable item, so a leading+ // heading or line is never hoveredfunction hoverPrevious() {+ if (filteredItems.length === 0) {+ return;+ }setHoveredIndex(- hoveredIndex === null ? 0 : transformIndex(Math.max(currentIndex - 1, 0)),+ hoveredIndex === null+ ? transformIndex(0)+ : transformIndex(Math.max(currentIndex - 1, 0)),);}function hoverNext() {+ if (filteredItems.length === 0) {+ return;+ }setHoveredIndex(hoveredIndex === null- ? 0+ ? transformIndex(0): transformIndex(Math.min(currentIndex + 1, filteredItems.length - 1)),);}diff --git a/packages/component-library/src/Select.stories.tsx b/packages/component-library/src/Select.stories.tsxindex 8c5da2894c..cb97907d9f 100644--- a/packages/component-library/src/Select.stories.tsx+++ b/packages/component-library/src/Select.stories.tsx@@ -81,6 +81,26 @@ export const WithSeparator: Story = {},};+export const WithHeadings: Story = {+ args: {+ options: [+ ['none', 'Outside the plan'],+ [Menu.label, 'Income streams'],+ ['pension', 'State pension'],+ ['rental', 'Rental income'],+ ],+ value: 'none',+ },+ parameters: {+ docs: {+ description: {+ story:+ 'A [Menu.label, text] entry renders a non-selectable heading over the options that follow it.',+ },+ },+ },+};+export const WithDisabledKeys: Story = {args: {options: [diff --git a/packages/component-library/src/Select.tsx b/packages/component-library/src/Select.tsxindex 4389f7a66b..338fdb65ba 100644--- a/packages/component-library/src/Select.tsx+++ b/packages/component-library/src/Select.tsx@@ -4,21 +4,34 @@ import type { CSSProperties } from 'react';import { Button } from './Button';import { SvgExpandArrow } from './icons/v0';import { Menu } from './Menu';+import type { MenuItem } from './Menu';import { Popover } from './Popover';import { View } from './View';+/** A non-selectable heading above the options that follow it */+export type SelectHeading = readonly [typeof Menu.label, string];++export type SelectOption<Value = string> =+ | [Value, string]+ | SelectHeading+ | typeof Menu.line;++function isHeading<Value>(+ option: readonly [Value, string] | SelectHeading,+): option is SelectHeading {+ return option[0] === Menu.label;+}+function isValueOption<Value>(- option: readonly [Value, string] | typeof Menu.line,+ option: readonly [Value, string] | SelectHeading | typeof Menu.line,): option is [Value, string] {- return option !== Menu.line;+ return option !== Menu.line && !isHeading(option);}-export type SelectOption<Value = string> = [Value, string] | typeof Menu.line;-type SelectProps<Value> = {id?: string;bare?: boolean;- options: Array<readonly [Value, string] | typeof Menu.line>;+ options: Array<readonly [Value, string] | SelectHeading | typeof Menu.line>;value: Value;defaultLabel?: string;onChange?: (newValue: Value) => void;@@ -31,6 +44,8 @@ type SelectProps<Value> = {/*** @param {Array<[string, string]>} options - An array of options value-label pairs.+ * `Menu.line` renders a divider and `[Menu.label, 'Heading']` a heading+ * over the options that follow it.* @param {string} value - The currently selected option value.* @param {string} [defaultLabel] - The label to display when the selected value is not in the options.* @param {function} [onChange] - A callback function invoked when the selected value changes.@@ -112,20 +127,25 @@ export function Select<const Value = string>({onOpenChange={() => setIsOpen(false)}style={popoverStyle}>- <Menu+ <Menu<Value>onMenuSelect={item => {onChange?.(item);setIsOpen(false);}}- items={options.map(item =>- item === Menu.line- ? Menu.line- : {- name: item[0],- text: item[1],- disabled: disabledKeys.includes(item[0]),- },- )}+ items={options.map((item): MenuItem<Value> => {+ if (item === Menu.line) {+ return Menu.line;+ }+ if (isHeading(item)) {+ // Menu shows a label item's name as the heading text+ return { type: Menu.label, name: item[1], text: item[1] };+ }+ return {+ name: item[0],+ text: item[1],+ disabled: disabledKeys.includes(item[0]),+ };+ })}getItemStyle={option => {if (targetOption && targetOption[0] === option.name) {return { fontWeight: 'bold' };diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 657c7f5725..d7fc9267dc 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -72,6 +72,7 @@"#components/reports/reports/monte-carlo/monteCarloHistoricalReturns": "./src/components/reports/reports/monte-carlo/monteCarloHistoricalReturns.ts","#components/reports/reports/monte-carlo/monteCarloSimulation": "./src/components/reports/reports/monte-carlo/monteCarloSimulation.ts","#components/reports/reports/monte-carlo/monteCarloStyles": "./src/components/reports/reports/monte-carlo/monteCarloStyles.ts",+ "#components/reports/reports/monte-carlo/monteCarloYearStory": "./src/components/reports/reports/monte-carlo/monteCarloYearStory.ts","#components/reports/reports/monte-carlo/useResolvedMonteCarloConfig": "./src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts","#components/reports/setSessionReport": "./src/components/reports/setSessionReport.ts","#components/reports/spendingAverageRange": "./src/components/reports/spendingAverageRange.ts",diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsxindex 193da4c5ef..9b8e9ea434 100644--- a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsx+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsx@@ -23,6 +23,7 @@ import { buildMonteCarloCashflowChart } from '#components/reports/graphs/util/moimport { useMonteCarloTickFormatter } from '#components/reports/graphs/util/useMonteCarloTickFormatter';import type {MonteCarloContribution,+ MonteCarloIncomeStream,MonteCarloPot,MonteCarloRunDetailRow,MonteCarloSpendingPhase,@@ -41,6 +42,7 @@ type MonteCarloCashflowGraphProps = {rows: MonteCarloRunDetailRow[];pots: MonteCarloPot[];contributions: MonteCarloContribution[];+ incomeStreams: MonteCarloIncomeStream[];spendingPhases: MonteCarloSpendingPhase[];/** The user's current age; the x-axis shows startAge + year - 1 */startAge: number;@@ -56,6 +58,7 @@ export function MonteCarloCashflowGraph({rows,pots,contributions,+ incomeStreams,spendingPhases,startAge,}: MonteCarloCashflowGraphProps) {@@ -69,6 +72,7 @@ export function MonteCarloCashflowGraph({rows,pots,contributions,+ incomeStreams,spendingPhases,startAge,translate: t,diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsxindex e786c2d53b..4a0a2cdfde 100644--- a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsx+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsx@@ -85,6 +85,15 @@ export function MonteCarloCashflowGraphTooltip({{t('The pots had already run out - this spending went unfunded.')}</div>)}+ {point.unspentIncome > 0 && (+ <div style={{ marginBottom: 10, maxWidth: 220 }}>+ <FinancialText as="span">+ {t('Unspent income: {{amount}} - it leaves the plan.', {+ amount: format(point.unspentIncome, 'financial'),+ })}+ </FinancialText>+ </div>+ )}<div style={{ lineHeight: 1.5 }}>{sections.map(group => (<View key={group.key}>diff --git a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.tsindex a1666bfc85..5e26b92bda 100644--- a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts+++ b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import type {MonteCarloContribution,+ MonteCarloIncomeStream,MonteCarloPot,MonteCarloRunDetailRow,MonteCarloSpendingPhase,@@ -35,6 +36,7 @@ function makePot(id: string, name = ''): MonteCarloPot {annualFeeFixed: 0,feeAdjustsWithInflation: false,annualFeeRate: 0,+ isSurplus: false,};}@@ -47,6 +49,21 @@ function makeContribution(id: string, name = ''): MonteCarloContribution {toAge: null,annualAmount: 0,adjustsWithInflation: false,+ sourceIncomeStreamId: null,+ beforeTax: false,+ };+}++function makeIncomeStream(id: string, name = ''): MonteCarloIncomeStream {+ return {+ id,+ name,+ fromAge: null,+ toAge: null,+ annualAmount: 0,+ adjustsWithInflation: false,+ taxRate: 0,+ taxableFraction: 1,};}@@ -65,11 +82,17 @@ function makeRow(startBalance: 0,withdrawal: 0,plannedSpending: 0,+ spent: 0,growth: 0,endBalance: 0,potBalances: [],potStartBalances: [],inflation: null,+ income: 0,+ incomeAmounts: [],+ incomeTax: 0,+ unspentIncome: 0,+ surplusSaved: 0,contributions: 0,potContributions: [],contributionAmounts: [],@@ -89,14 +112,20 @@ const contributions = [makeContribution('contribution-1', 'Salary sacrifice'),makeContribution('contribution-2'),];+const incomeStreams = [+ makeIncomeStream('income-1', 'State pension'),+ makeIncomeStream('income-2'),+];const phases = [makePhase('phase-1', null, 'Early'), makePhase('phase-2', 62)];describe('buildMonteCarloCashflowChart', () => {- it('builds one series per pot, active contribution and phase', () => {+ it('builds one series per pot, active income, phase and active contribution', () => {const rows = [makeRow({year: 1,potWithdrawals: [30_000, 10_000],+ incomeAmounts: [12_000, 0],+ incomeTax: 500,contributionAmounts: [5_000, 0],plannedSpending: 38_000,taxPaid: 2_000,@@ -106,6 +135,7 @@ describe('buildMonteCarloCashflowChart', () => {rows,pots,contributions,+ incomeStreams,spendingPhases: phases,startAge: 60,translate,@@ -116,8 +146,8 @@ describe('buildMonteCarloCashflowChart', () => {).toEqual([['pot', 'Pension'],['pot', 'Pot 2'],- // The second contribution never deposits anything, so no series- ['contribution', 'Salary sacrifice'],+ // The second stream never pays anything, so no series+ ['income', 'State pension'],]);expect(chart.outflowSeries.map(series => [series.kind, series.label]),@@ -125,12 +155,15 @@ describe('buildMonteCarloCashflowChart', () => {['phase', 'Early'],['phase', 'Phase 2'],['tax', 'Tax'],+ // The second contribution never deposits anything, so no series+ ['contribution', 'Salary sacrifice'],]);expect(chart.tooltipGroups.map(group => group.key)).toEqual(['withdrawals',- 'contributions',+ 'income','tax','spending',+ 'contributions',]);const [point] = chart.data;@@ -139,14 +172,17 @@ describe('buildMonteCarloCashflowChart', () => {expect(point.amounts).toEqual({pot0: 30_000,pot1: 10_000,- contribution0: 5_000,- contribution1: 0,+ income0: 12_000,+ income1: 0,// Age 60 is before phase 2 starts, so the plan belongs to phase 1phase0: -38_000,phase1: 0,- tax0: -2_000,+ // Tax on withdrawals and on income together+ tax0: -2_500,+ contribution0: -5_000,+ contribution1: 0,});- expect(chart.stackExtents).toEqual([45_000, -40_000]);+ expect(chart.stackExtents).toEqual([52_000, -45_500]);});it('attributes each year to the phase active at that age', () => {@@ -159,6 +195,7 @@ describe('buildMonteCarloCashflowChart', () => {rows,pots,contributions: [],+ incomeStreams: [],spendingPhases: phases,startAge: 60,translate,@@ -174,16 +211,21 @@ describe('buildMonteCarloCashflowChart', () => {]);});- it('omits tax and contribution groups when nothing was paid', () => {+ it('omits tax, income and contribution groups when nothing moved', () => {const chart = buildMonteCarloCashflowChart({rows: [makeRow({ year: 1, potWithdrawals: [100, 0] })],pots,contributions,+ incomeStreams,spendingPhases: phases,startAge: 60,translate,});+ expect(chart.inflowSeries.map(series => series.kind)).toEqual([+ 'pot',+ 'pot',+ ]);expect(chart.outflowSeries.map(series => series.kind)).toEqual(['phase','phase',@@ -194,11 +236,32 @@ describe('buildMonteCarloCashflowChart', () => {]);});+ it('shows the tax group for income tax alone', () => {+ const chart = buildMonteCarloCashflowChart({+ rows: [makeRow({ year: 1, incomeAmounts: [1_000, 0], incomeTax: 200 })],+ pots,+ contributions: [],+ incomeStreams,+ spendingPhases: phases,+ startAge: 60,+ translate,+ });++ expect(chart.tooltipGroups.map(group => group.key)).toEqual([+ 'withdrawals',+ 'income',+ 'tax',+ 'spending',+ ]);+ expect(chart.data[0].amounts.tax0).toBe(-200);+ });+it('falls back to a single phase when none are configured', () => {const chart = buildMonteCarloCashflowChart({rows: [makeRow({ year: 1, plannedSpending: 500 })],pots,contributions: [],+ incomeStreams: [],spendingPhases: [],startAge: 60,translate,@@ -216,6 +279,7 @@ describe('buildMonteCarloCashflowChart', () => {rows: [],pots,contributions: [],+ incomeStreams: [],spendingPhases: [makePhase('late', 70), makePhase('early', null)],startAge: 60,translate,@@ -228,14 +292,49 @@ describe('buildMonteCarloCashflowChart', () => {]);});- it('flags the synthetic years after a failure', () => {+ it('shows money saved into the surplus pot as an outflow', () => {+ const surplusPot = { ...makePot('surplus', 'Rainy day'), isSurplus: true };+ const chart = buildMonteCarloCashflowChart({+ rows: [+ makeRow({+ year: 1,+ incomeAmounts: [1_000, 0],+ unspentIncome: 600,+ surplusSaved: 600,+ }),+ ],+ pots: [surplusPot, ...pots],+ contributions: [],+ incomeStreams,+ spendingPhases: phases,+ startAge: 60,+ translate,+ });++ const surplusSeries = chart.outflowSeries.find(+ series => series.kind === 'surplus',+ );+ expect(surplusSeries?.label).toBe('Saved into Rainy day');+ expect(chart.tooltipGroups.map(group => group.key)).toEqual([+ 'withdrawals',+ 'income',+ 'spending',+ 'surplus',+ ]);+ expect(chart.data[0].amounts.surplus0).toBe(-600);+ // Saved money isn't unspent+ expect(chart.data[0].unspentIncome).toBe(0);+ });++ it('carries the unfunded and unspent flags for the tooltip', () => {const chart = buildMonteCarloCashflowChart({rows: [- makeRow({ year: 1, plannedSpending: 100 }),+ makeRow({ year: 1, plannedSpending: 100, unspentIncome: 250 }),makeRow({ year: 2, plannedSpending: 100, afterDepletion: true }),],pots,contributions: [],+ incomeStreams: [],spendingPhases: phases,startAge: 60,translate,@@ -245,5 +344,6 @@ describe('buildMonteCarloCashflowChart', () => {false,true,]);+ expect(chart.data.map(point => point.unspentIncome)).toEqual([250, 0]);});});diff --git a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.ts b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.tsindex 906af8562a..ca17727cc3 100644--- a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.ts+++ b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.ts@@ -4,10 +4,13 @@ import type { TFunction } from 'i18next';import { getColorScale } from '#components/reports/chart-theme';import {getActiveSpendingPhase,+ getMonteCarloPotLabel,+ getMonteCarloSurplusPotLabel,resolveSpendingPhases,} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import type {MonteCarloContribution,+ MonteCarloIncomeStream,MonteCarloPot,MonteCarloRunDetailRow,MonteCarloSpendingPhase,@@ -15,9 +18,11 @@ import type {export type MonteCarloCashflowSeriesKind =| 'pot'- | 'contribution'+ | 'income'| 'phase'- | 'tax';+ | 'tax'+ | 'contribution'+ | 'surplus';/** One stacked bar series of the cashflow chart */export type MonteCarloCashflowSeries = {@@ -46,15 +51,20 @@ export type MonteCarloCashflowDataPoint = {age: number;/** A synthetic year after the plan ran out: spending with no funding */afterDepletion: boolean;+ /** Income the year didn't need - it left the plan */+ unspentIncome: number;/** Per series key: positive for money in, negative for money out */amounts: Record<string, number>;};export type MonteCarloCashflowChart = {data: MonteCarloCashflowDataPoint[];- /** Series stacked above zero: pot withdrawals, then contributions */+ /** Series stacked above zero: pot withdrawals, then income streams */inflowSeries: MonteCarloCashflowSeries[];- /** Series stacked below zero: planned spending by phase, then tax */+ /**+ * Series stacked below zero: planned spending by phase, tax, then+ * contributions+ */outflowSeries: MonteCarloCashflowSeries[];tooltipGroups: MonteCarloCashflowTooltipGroup[];/** Each year's total money in and total money out, for axis padding */@@ -66,6 +76,7 @@ type BuildMonteCarloCashflowChartInput = {rows: MonteCarloRunDetailRow[];pots: MonteCarloPot[];contributions: MonteCarloContribution[];+ incomeStreams: MonteCarloIncomeStream[];spendingPhases: MonteCarloSpendingPhase[];/** The user's current age; a row's age is startAge + year - 1 */startAge: number;@@ -77,53 +88,55 @@ function seriesKey(kind: MonteCarloCashflowSeriesKind, index: number) {}/**- * Turns a captured run into the cashflow chart's series and data: money- * in above zero (each pot's gross withdrawal, plus each contribution),- * money out below zero (the planned spending, coloured by its spending- * phase, plus tax). Spending shows the plan rather than the delivered- * amount, so in a shortfall year the withdrawal bars visibly fall short- * of the spending bar. Fees stay out - they never pass through the- * user's hands.+ * Turns a captured run into the cashflow chart's series and data - the+ * household's yearly cashflow. Money in above zero: each pot's gross+ * withdrawal and each income stream's gross. Money out below zero: the+ * planned spending (coloured by its spending phase), tax on withdrawals+ * and income, each contribution paid into a pot, and money saved into+ * the surplus pot. Spending shows the+ * plan rather than the delivered amount, so in a shortfall year the+ * inflows visibly fall short of the spending bar. Fees stay out - they+ * never pass through the user's hands.*/export function buildMonteCarloCashflowChart({rows,pots,contributions,+ incomeStreams,spendingPhases,startAge,translate,}: BuildMonteCarloCashflowChartInput): MonteCarloCashflowChart {const colorScale = getColorScale('qualitative');const phases = resolveSpendingPhases(spendingPhases);- const hasTax = rows.some(row => row.taxPaid !== 0);+ const hasTax = rows.some(row => row.taxPaid !== 0 || row.incomeTax !== 0);++ // Inflows take colours from the start of the scale and outflows from+ // the end, so the two sides of the zero line only share a colour once+ // the scale is exhausted+ const inflowColor = (index: number) => colorScale[index % colorScale.length];+ const outflowColor = (index: number) =>+ colorScale[colorScale.length - 1 - (index % colorScale.length)];- // Inflows take colours from the start of the scale and spending phases- // from the end, so the two sides of the zero line only share a colour- // once the scale is exhaustedconst potSeries: MonteCarloCashflowSeries[] = pots.map((pot, potIndex) => ({key: seriesKey('pot', potIndex),kind: 'pot',- label: pot.name || translate('Pot {{number}}', { number: potIndex + 1 }),- color: colorScale[potIndex % colorScale.length],+ label: getMonteCarloPotLabel(pots, potIndex, translate),+ color: inflowColor(potIndex),}));- // Only contributions that deposit something in this run get a series- const contributionSeries: MonteCarloCashflowSeries[] = contributions.flatMap(- (contribution, contributionIndex) =>- rows.some(row => (row.contributionAmounts[contributionIndex] ?? 0) !== 0)+ // Only streams that pay something in this run get a series+ const incomeSeries: MonteCarloCashflowSeries[] = incomeStreams.flatMap(+ (incomeStream, incomeIndex) =>+ rows.some(row => (row.incomeAmounts[incomeIndex] ?? 0) !== 0)? [{- key: seriesKey('contribution', contributionIndex),- kind: 'contribution' as const,+ key: seriesKey('income', incomeIndex),+ kind: 'income',label:- contribution.name ||- translate('Contribution {{number}}', {- number: contributionIndex + 1,- }),- color:- colorScale[- (pots.length + contributionIndex) % colorScale.length- ],- },+ incomeStream.name ||+ translate('Income {{number}}', { number: incomeIndex + 1 }),+ color: inflowColor(pots.length + incomeIndex),+ } satisfies MonteCarloCashflowSeries,]: [],);@@ -140,8 +153,7 @@ export function buildMonteCarloCashflowChart({translate('Phase {{number}}', {number: configuredIndex === -1 ? 1 : configuredIndex + 1,}),- color:- colorScale[colorScale.length - 1 - (phaseIndex % colorScale.length)],+ color: outflowColor(phaseIndex),};},);@@ -151,12 +163,46 @@ export function buildMonteCarloCashflowChart({label: translate('Tax'),color: theme.reportsNumberNegative,};+ // Only contributions that deposit something in this run get a series+ const contributionSeries: MonteCarloCashflowSeries[] = contributions.flatMap(+ (contribution, contributionIndex) =>+ rows.some(row => (row.contributionAmounts[contributionIndex] ?? 0) !== 0)+ ? [+ {+ key: seriesKey('contribution', contributionIndex),+ kind: 'contribution',+ label:+ contribution.name ||+ translate('Contribution {{number}}', {+ number: contributionIndex + 1,+ }),+ color: outflowColor(phases.length + contributionIndex),+ } satisfies MonteCarloCashflowSeries,+ ]+ : [],+ );++ // Money the plan saved into its surplus pot instead of spending+ const hasSurplus = rows.some(row => row.surplusSaved > 0);+ const surplusSeries: MonteCarloCashflowSeries = {+ key: seriesKey('surplus', 0),+ kind: 'surplus',+ label: translate('Saved into {{pot}}', {+ pot: getMonteCarloSurplusPotLabel(pots, translate),+ }),+ color: outflowColor(phases.length + contributions.length),+ };- const inflowSeries = [...potSeries, ...contributionSeries];- const outflowSeries = [...phaseSeries, ...(hasTax ? [taxSeries] : [])];+ const inflowSeries = [...potSeries, ...incomeSeries];+ const outflowSeries = [+ ...phaseSeries,+ ...(hasTax ? [taxSeries] : []),+ ...contributionSeries,+ ...(hasSurplus ? [surplusSeries] : []),+ ];- // Tax sits between Withdrawals and Spending so the deduction chain- // reads in order: gross withdrawal, minus tax, leaves spending+ // Tax sits between the inflows and Spending so the deduction chain+ // reads in order: gross in, minus tax, leaves spendingconst tooltipGroups: MonteCarloCashflowTooltipGroup[] = [{key: 'withdrawals',@@ -164,12 +210,12 @@ export function buildMonteCarloCashflowChart({series: potSeries,listMembers: true,},- ...(contributionSeries.length > 0+ ...(incomeSeries.length > 0? [{- key: 'contributions',- heading: translate('Contributions'),- series: contributionSeries,+ key: 'income',+ heading: translate('Income'),+ series: incomeSeries,listMembers: true,},]@@ -190,6 +236,26 @@ export function buildMonteCarloCashflowChart({series: phaseSeries,listMembers: true,},+ ...(contributionSeries.length > 0+ ? [+ {+ key: 'contributions',+ heading: translate('Contributions'),+ series: contributionSeries,+ listMembers: true,+ },+ ]+ : []),+ ...(hasSurplus+ ? [+ {+ key: 'surplus',+ heading: translate('Saved'),+ series: [surplusSeries],+ listMembers: false,+ },+ ]+ : []),];const data = rows.map((row): MonteCarloCashflowDataPoint => {@@ -198,9 +264,9 @@ export function buildMonteCarloCashflowChart({potSeries.forEach((series, potIndex) => {amounts[series.key] = row.potWithdrawals[potIndex] ?? 0;});- contributions.forEach((_, contributionIndex) => {- amounts[seriesKey('contribution', contributionIndex)] =- row.contributionAmounts[contributionIndex] ?? 0;+ incomeStreams.forEach((_, incomeIndex) => {+ amounts[seriesKey('income', incomeIndex)] =+ row.incomeAmounts[incomeIndex] ?? 0;});// The year's planned spend belongs to whichever phase is activeconst activePhase = getActiveSpendingPhase(phases, age);@@ -209,12 +275,23 @@ export function buildMonteCarloCashflowChart({phases[phaseIndex] === activePhase ? -row.plannedSpending : 0;});if (hasTax) {- amounts[taxSeries.key] = -row.taxPaid;+ amounts[taxSeries.key] = -(row.taxPaid + row.incomeTax);+ }+ contributions.forEach((_, contributionIndex) => {+ const deposited = row.contributionAmounts[contributionIndex] ?? 0;+ // Stacked below zero; a plain 0 (not -0) when nothing was paid in+ amounts[seriesKey('contribution', contributionIndex)] =+ deposited > 0 ? -deposited : 0;+ });+ if (hasSurplus) {+ amounts[surplusSeries.key] = row.surplusSaved > 0 ? -row.surplusSaved : 0;}return {year: row.year,age,afterDepletion: row.afterDepletion === true,+ // Only income that actually left the plan counts as unspent+ unspentIncome: row.surplusSaved > 0 ? 0 : row.unspentIncome,amounts,};});diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsxindex a940b83e8f..7657b1ee42 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx@@ -206,6 +206,7 @@ export function MonteCarlo() {const cashflowGraphProps = {pots: resolvedConfig.pots,contributions: resolvedConfig.contributions,+ incomeStreams: resolvedConfig.incomeStreams,spendingPhases: resolvedConfig.spendingPhases,startAge: config.currentAge,};@@ -544,8 +545,8 @@ export function MonteCarlo() {><Trans>Money flowing in and out each year of this simulated run:- withdrawals and contributions above zero, planned spending- and tax below.+ withdrawals and income above zero; planned spending, tax,+ contributions and money saved into the surplus pot below.</Trans></Text><MonteCarloCashflowGraph@@ -563,7 +564,11 @@ export function MonteCarlo() {simulationIndex={selectedRunIndex}simulationCount={result.simulationCount}startAge={config.currentAge}- hasContributions={config.contributions.length > 0}+ hasContributions={+ config.contributions.length > 0 ||+ config.pots.some(pot => pot.isSurplus)+ }+ incomeStreams={resolvedConfig.incomeStreams}withdrawalRule={resolvedConfig.withdrawalRule}cashflowGraph={<MonteCarloCashflowGraph@@ -678,13 +683,17 @@ export function MonteCarlo() {<Paragraph><Trans>Each scenario replays your retirement with a different sequence of- yearly investment returns. Every year, any contributions are added- at the start, then the withdrawal is taken, and then each pot- grows or shrinks with that year's return. Pots with an access- age stay invested but can't fund withdrawals until you reach- it - if the accessible pots can't cover a year's- withdrawal, the plan counts as having run out, even if locked pots- still hold money. The shaded bands show the range of outcomes+ yearly investment returns. Every year, any income arrives and any+ contributions are paid in at the start - some of them out of that+ income; the income then pays for the year's spending first+ and the withdrawal covers the rest; anything left unspent is saved+ into the Surplus cash pot for later years when the plan keeps one,+ and otherwise leaves the plan; and then each pot grows or shrinks+ with that year's return. Pots with an access age stay+ invested but can't fund withdrawals until you reach it - if+ the accessible pots can't cover what a year's spending+ still needs, the plan counts as having run out, even if locked+ pots still hold money. The shaded bands show the range of outcomesacross all scenarios: the darker band covers the middle half, andthe lighter band covers 80% of them.</Trans>diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsxindex c7f9ba9a39..fadfc28424 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx@@ -21,11 +21,14 @@ import { v4 as uuidv4 } from 'uuid';import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';import { MonteCarloContributions } from '#components/reports/reports/monte-carlo/MonteCarloContributions';import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import { MonteCarloIncomeStreams } from '#components/reports/reports/monte-carlo/MonteCarloIncomeStreams';import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';import { MonteCarloPotConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloPotConfiguration';import { MonteCarloPotsTableHeader } from '#components/reports/reports/monte-carlo/MonteCarloPotsTableHeader';import {createMonteCarloPot,+ createMonteCarloSurplusPot,+ getMonteCarloPotLabel,MAX_SIMULATION_COUNT,MIN_SIMULATION_COUNT,MONTE_CARLO_DEFAULTS,@@ -48,6 +51,7 @@ type ConfigurationTab =| 'plan'| 'pots'| 'contributions'+ | 'income'| 'withdrawals'| 'tax';@@ -69,6 +73,34 @@ export function MonteCarloConfiguration({const { t } = useTranslation();const [activeTab, setActiveTab] = useState<ConfigurationTab>('plan');+ // Whether unspent money is kept is simply whether a surplus pot exists+ const keepsSurplus = config.pots.some(pot => pot.isSurplus);+ const ordinaryPotCount = config.pots.filter(pot => !pot.isSurplus).length;++ function onKeepSurplusChange(keep: boolean) {+ if (keep) {+ // First in the list, matching the order it's drawn on+ onConfigChange({+ pots: [createMonteCarloSurplusPot(uuidv4()), ...config.pots],+ });+ } else {+ // The surplus pot only exists while unspent money is kept; it+ // takes its contributions with it, and the plan always keeps a pot+ const surplusPotIds = config.pots+ .filter(pot => pot.isSurplus)+ .map(pot => pot.id);+ const remainingPots = config.pots.filter(pot => !pot.isSurplus);+ onConfigChange({+ pots: remainingPots.length+ ? remainingPots+ : [createMonteCarloPot(uuidv4())],+ contributions: config.contributions.filter(+ contribution => !surplusPotIds.includes(contribution.potId),+ ),+ });+ }+ }+function onPotChange(potId: string, changes: Partial<MonteCarloPot>) {onConfigChange({pots: config.pots.map(pot =>@@ -138,6 +170,12 @@ export function MonteCarloConfiguration({><Trans>Investment pots</Trans></ModeButton>+ <ModeButton+ selected={activeTab === 'income'}+ onSelect={() => setActiveTab('income')}+ >+ <Trans>Income</Trans>+ </ModeButton><ModeButtonselected={activeTab === 'contributions'}onSelect={() => setActiveTab('contributions')}@@ -170,15 +208,19 @@ export function MonteCarloConfiguration({): activeTab === 'contributions'? t(- "Money you add to your pots each year, in today's money - for example pension or savings deposits while you're still earning.",+ "Money you add to your pots each year, in today's money - paid from one of your income streams, or from outside the plan.",)- : activeTab === 'withdrawals'+ : activeTab === 'income'? t(- 'How much you take out each year, and optional rules that adjust it as markets move.',+ "Money you receive each year without drawing on your pots, in today's money - a state pension, an annuity, rental or part-time work. It pays for spending first; the pots fund the rest.",)- : t(- 'How withdrawals are taxed - your spending is what you keep after tax.',- )}+ : activeTab === 'withdrawals'+ ? t(+ 'How much you take out each year, and optional rules that adjust it as markets move.',+ )+ : t(+ 'How withdrawals are taxed - your spending is what you keep after tax.',+ )}</Text>{activeTab === 'contributions' && (<MonteCarloHelpTooltip>@@ -190,6 +232,29 @@ export function MonteCarloConfiguration({amount's buying power constant; untick it for a fixed amountthat shrinks in real terms. A pot can receive any number ofcontributions - even one that is still locked for withdrawals.+ <br />+ <br />+ A contribution paid from an income stream is capped at what that+ stream brings in that year. Tick Before tax for a workplace+ pension or salary sacrifice, which is deducted before the+ income's tax is worked out.+ </Trans>+ </MonteCarloHelpTooltip>+ )}+ {activeTab === 'income' && (+ <MonteCarloHelpTooltip>+ <Trans>+ Each income stream arrives every year in its age window (both ages+ inclusive), taxed the same way as pot withdrawals: at its own rate+ under the flat model, or by its taxable portion under the bands+ model, where it uses up the lower bands before any pot withdrawal+ is taxed. What is left after tax and any contributions paid from+ it goes towards the year's spending; the pots only fund the+ remainder. Income beyond that is unspent: it is saved into the+ Surplus cash pot, or leaves the plan if you tick Assume any+ unspent money is spent under Manage surplus on the Plan details+ tab. You can also route specific amounts into a pot with a+ contribution.</Trans></MonteCarloHelpTooltip>)}@@ -444,6 +509,50 @@ export function MonteCarloConfiguration({</View>)}</View>++ <View style={{ gap: 10, flexBasis: '100%' }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Manage surplus</Trans>+ </Text>+ <Text style={{ color: theme.pageText }}>+ <Trans>+ Money the plan doesn't spend - such as income beyond your+ spending - is saved into a Surplus cash pot. Tick the box to+ treat it as spent and gone instead.+ </Trans>+ </Text>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 4,+ // Sized to its content so the help icon sits by the label+ // rather than at the far end of the full-width group+ alignSelf: 'flex-start',+ }}+ >+ <LabeledCheckbox+ id="mc-assume-surplus-spent"+ checked={!keepsSurplus}+ onChange={event => onKeepSurplusChange(!event.target.checked)}+ >+ <Trans>Assume any unspent money is spent</Trans>+ </LabeledCheckbox>+ <MonteCarloHelpTooltip>+ <Trans>+ The Surplus cash pot is created automatically. Income beyond+ your spending goes into it, and it is drawn on before any+ other pot when spending needs funding.+ <br />+ <br />+ It starts empty and holds cash - no access age, no tax, no+ fees. It can't be edited or deleted from the pots list;+ tick the box to remove it, along with any contributions paid+ into it, and untick it to bring it back empty.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </View></View>)}@@ -479,8 +588,13 @@ export function MonteCarloConfiguration({<MonteCarloPotConfigurationkey={pot.id}pot={pot}- potNumber={config.pots.indexOf(pot) + 1}- canRemove={config.pots.length > 1}+ potLabel={getMonteCarloPotLabel(+ config.pots,+ config.pots.indexOf(pot),+ t,+ )}+ // The surplus pot is managed by the Manage surplus toggle+ canRemove={ordinaryPotCount > 1 && !pot.isSurplus}usesHistoricalReturns={config.returnModel !== 'normal'}usesTaxBands={config.taxModel === 'bands'}onPotChange={changes => onPotChange(pot.id, changes)}@@ -518,6 +632,19 @@ export function MonteCarloConfiguration({<MonteCarloContributionscontributions={config.contributions}pots={config.pots}+ incomeStreams={config.incomeStreams}+ currentAge={config.currentAge}+ targetAge={config.targetAge}+ onConfigChange={onConfigChange}+ />+ )}++ {/* Income */}+ {activeTab === 'income' && (+ <MonteCarloIncomeStreams+ incomeStreams={config.incomeStreams}+ contributions={config.contributions}+ usesTaxBands={config.taxModel === 'bands'}currentAge={config.currentAge}targetAge={config.targetAge}onConfigChange={onConfigChange}@@ -590,14 +717,14 @@ export function MonteCarloConfiguration({</View><MonteCarloWithdrawalRuleConfigurationrule={config.withdrawalRule}- minimumWithdrawal={config.minimumWithdrawal}+ minimumSpending={config.minimumSpending}onRuleChange={changes =>onConfigChange({withdrawalRule: { ...config.withdrawalRule, ...changes },})}- onMinimumWithdrawalChange={value =>- onConfigChange({ minimumWithdrawal: value })+ onMinimumSpendingChange={value =>+ onConfigChange({ minimumSpending: value })}/></View>diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsxindex a82966dc79..97d45a5f92 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsx@@ -4,7 +4,12 @@ import { Button } from '@actual-app/components/button';import { SvgDelete } from '@actual-app/components/icons/v0';import { SvgAdd } from '@actual-app/components/icons/v1';import { Input } from '@actual-app/components/input';+import { Menu } from '@actual-app/components/menu';import { Select } from '@actual-app/components/select';+import type {+ SelectHeading,+ SelectOption,+} from '@actual-app/components/select';import { styles } from '@actual-app/components/styles';import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';@@ -12,14 +17,17 @@ import { View } from '@actual-app/components/view';import { v4 as uuidv4 } from 'uuid';import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';+import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';import {createMonteCarloContribution,+ getMonteCarloPotLabel,MAX_AMOUNT,} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import type {MonteCarloConfig,MonteCarloContribution,+ MonteCarloIncomeStream,MonteCarloPot,} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import { Field, Row, TableHeader } from '#components/table';@@ -27,9 +35,14 @@ import { FinancialInput } from '#components/util/FinancialInput';const CONTRIBUTION_ROW_HEIGHT = 43;+/** The Select value for a contribution paid from outside the plan */+const OUTSIDE_SOURCE = '';+type MonteCarloContributionsProps = {contributions: MonteCarloContribution[];pots: MonteCarloPot[];+ /** Income streams a contribution can be paid out of */+ incomeStreams: MonteCarloIncomeStream[];currentAge: number;targetAge: number;onConfigChange: (changes: Partial<MonteCarloConfig>) => void;@@ -38,6 +51,7 @@ type MonteCarloContributionsProps = {export function MonteCarloContributions({contributions,pots,+ incomeStreams,currentAge,targetAge,onConfigChange,@@ -69,7 +83,11 @@ export function MonteCarloContributions({onConfigChange({contributions: [...contributions,- createMonteCarloContribution(uuidv4(), pots[0].id),+ createMonteCarloContribution(+ uuidv4(),+ // The surplus pot is managed by the plan, so start on an ordinary one+ (pots.find(pot => !pot.isSurplus) ?? pots[0]).id,+ ),],});}@@ -86,11 +104,25 @@ export function MonteCarloContributions({const potOptions = pots.map((pot, potIndex) =>- [pot.id, pot.name || t('Pot {{number}}', { number: potIndex + 1 })] as [+ [pot.id, getMonteCarloPotLabel(pots, potIndex, t)] satisfies [string,string,],);+ const sourceOptions: SelectOption[] = [+ [OUTSIDE_SOURCE, t('Outside the plan')],+ ...(incomeStreams.length > 0+ ? [[Menu.label, t('Income streams')] satisfies SelectHeading]+ : []),+ ...incomeStreams.map(+ (incomeStream, incomeIndex) =>+ [+ incomeStream.id,+ incomeStream.name ||+ t('Income {{number}}', { number: incomeIndex + 1 }),+ ] satisfies [string, string],+ ),+ ];return (<View style={{ gap: 10 }}>@@ -112,6 +144,9 @@ export function MonteCarloContributions({<Field width="flex" style={{ minWidth: 160 }}><Trans>Into pot</Trans></Field>+ <Field width="flex" style={{ minWidth: 160 }}>+ <Trans>Paid from</Trans>+ </Field><Field width="flex" style={{ minWidth: 100 }}><Trans>From age</Trans></Field>@@ -121,7 +156,39 @@ export function MonteCarloContributions({<Field width="flex" style={{ minWidth: 140 }}><Trans>Amount (per year)</Trans></Field>- <Field width="flex" style={{ minWidth: 170 }} />+ <Field width="flex" style={{ minWidth: 170 }}>+ <Trans>Inflation</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: 120 }} truncate={false}>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 5,+ whiteSpace: 'nowrap',+ }}+ >+ <Text>+ <Trans>Before tax</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ For a contribution paid from an income stream: tick it to+ take the money out of the income before its tax is worked+ out, like a workplace pension or salary sacrifice - the+ stream then pays less tax. Leave it unticked to save from+ income that has already been taxed.+ <br />+ <br />+ For example, a 10,000 contribution from a 12,000 income+ taxed at 20%: before tax, only the remaining 2,000 is taxed+ (400); after tax, the full 12,000 is taxed (2,400) and the+ contribution comes out of what is left. A state pension is+ usually taxed as you receive it, so it stays unticked.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </Field><Field width={36} /></TableHeader>@@ -160,6 +227,21 @@ export function MonteCarloContributions({/></Field>+ <Field width="flex" style={{ minWidth: 160 }} truncate={false}>+ <Select+ value={contribution.sourceIncomeStreamId ?? OUTSIDE_SOURCE}+ onChange={value =>+ updateContribution(contribution.id, {+ sourceIncomeStreamId:+ value === OUTSIDE_SOURCE ? null : value,+ // Before tax only means something for income+ ...(value === OUTSIDE_SOURCE && { beforeTax: false }),+ })+ }+ options={sourceOptions}+ />+ </Field>+<Field width="flex" style={{ minWidth: 100 }} truncate={false}><MonteCarloNumberInputvalue={contribution.fromAge}@@ -221,6 +303,22 @@ export function MonteCarloContributions({</LabeledCheckbox></Field>+ <Field width="flex" style={{ minWidth: 120 }} truncate={false}>+ {contribution.sourceIncomeStreamId != null && (+ <LabeledCheckbox+ id={`contribution-before-tax-${contribution.id}`}+ checked={contribution.beforeTax}+ onChange={event =>+ updateContribution(contribution.id, {+ beforeTax: event.target.checked,+ })+ }+ >+ <Trans>Before tax</Trans>+ </LabeledCheckbox>+ )}+ </Field>+<Fieldwidth={36}truncate={false}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloIncomeStreams.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloIncomeStreams.tsxnew file mode 100644index 0000000000..36ef838bce--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloIncomeStreams.tsx@@ -0,0 +1,262 @@+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+import { SvgAdd } from '@actual-app/components/icons/v1';+import { Input } from '@actual-app/components/input';+import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import { v4 as uuidv4 } from 'uuid';++import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';+import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';+import {+ createMonteCarloIncomeStream,+ MAX_AMOUNT,+ MAX_WITHDRAWAL_TAX_RATE,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type {+ MonteCarloConfig,+ MonteCarloContribution,+ MonteCarloIncomeStream,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { Field, Row, TableHeader } from '#components/table';+import { FinancialInput } from '#components/util/FinancialInput';++const INCOME_ROW_HEIGHT = 43;++type MonteCarloIncomeStreamsProps = {+ incomeStreams: MonteCarloIncomeStream[];+ /** Contributions paid out of a removed stream fall back to outside money */+ contributions: MonteCarloContribution[];+ /** True when the bands tax model is active */+ usesTaxBands: boolean;+ currentAge: number;+ targetAge: number;+ onConfigChange: (changes: Partial<MonteCarloConfig>) => void;+};++export function MonteCarloIncomeStreams({+ incomeStreams,+ contributions,+ usesTaxBands,+ currentAge,+ targetAge,+ onConfigChange,+}: MonteCarloIncomeStreamsProps) {+ const { t } = useTranslation();++ function updateIncomeStream(+ incomeStreamId: string,+ changes: Partial<MonteCarloIncomeStream>,+ ) {+ onConfigChange({+ incomeStreams: incomeStreams.map(incomeStream =>+ incomeStream.id === incomeStreamId+ ? { ...incomeStream, ...changes }+ : incomeStream,+ ),+ });+ }++ function removeIncomeStream(incomeStreamId: string) {+ onConfigChange({+ incomeStreams: incomeStreams.filter(+ incomeStream => incomeStream.id !== incomeStreamId,+ ),+ contributions: contributions.map(contribution =>+ contribution.sourceIncomeStreamId === incomeStreamId+ ? { ...contribution, sourceIncomeStreamId: null, beforeTax: false }+ : contribution,+ ),+ });+ }++ function addIncomeStream() {+ onConfigChange({+ incomeStreams: [...incomeStreams, createMonteCarloIncomeStream(uuidv4())],+ });+ }++ return (+ <View style={{ gap: 10 }}>+ <View+ style={{+ ...styles.tableContainer,+ ...styles.horizontalScrollbar,+ flex: 'unset',+ // Scroll sideways when the columns' minimum widths don't fit,+ // instead of clipping the end of the rows+ overflowX: 'auto',+ }}+ >+ <View style={{ minWidth: 'fit-content' }}>+ <TableHeader>+ <Field width="flex" style={{ minWidth: 150 }}>+ <Trans>Income name</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: 100 }}>+ <Trans>From age</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: 100 }}>+ <Trans>To age</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: 140 }}>+ <Trans>Amount (per year)</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: 130 }}>+ {usesTaxBands ? (+ <Trans>Taxable portion (%)</Trans>+ ) : (+ <Trans>Tax (%)</Trans>+ )}+ </Field>+ <Field width="flex" style={{ minWidth: 170 }}>+ <Trans>Inflation</Trans>+ </Field>+ <Field width={36} />+ </TableHeader>++ {incomeStreams.map((incomeStream, index) => (+ <Row+ key={incomeStream.id}+ collapsed+ height={INCOME_ROW_HEIGHT}+ style={{+ backgroundColor: theme.tableBackground,+ ':hover': { backgroundColor: theme.tableRowBackgroundHover },+ }}+ >+ <Field width="flex" style={{ minWidth: 150 }} truncate={false}>+ <Input+ defaultValue={incomeStream.name}+ placeholder={t('Income {{number}}', { number: index + 1 })}+ aria-label={t('Income name')}+ onUpdate={newName => {+ if (newName !== incomeStream.name) {+ updateIncomeStream(incomeStream.id, { name: newName });+ }+ }}+ />+ </Field>++ <Field width="flex" style={{ minWidth: 100 }} truncate={false}>+ <MonteCarloNumberInput+ value={incomeStream.fromAge}+ aria-label={t('From age')}+ allowEmpty+ roundToInteger+ min={currentAge}+ max={incomeStream.toAge ?? targetAge}+ step={1}+ placeholder={t('Now')}+ onCommit={newValue =>+ updateIncomeStream(incomeStream.id, { fromAge: newValue })+ }+ />+ </Field>++ <Field width="flex" style={{ minWidth: 100 }} truncate={false}>+ <MonteCarloNumberInput+ value={incomeStream.toAge}+ aria-label={t('To age')}+ allowEmpty+ roundToInteger+ min={incomeStream.fromAge ?? currentAge}+ max={targetAge}+ step={1}+ placeholder={t('End of plan')}+ onCommit={newValue =>+ updateIncomeStream(incomeStream.id, { toAge: newValue })+ }+ />+ </Field>++ <Field width="flex" style={{ minWidth: 140 }} truncate={false}>+ <FinancialInput+ value={incomeStream.annualAmount}+ aria-label={t('Amount (per year)')}+ onUpdate={value => {+ const newAmount = Math.min(MAX_AMOUNT, Math.max(0, value));+ if (newAmount !== incomeStream.annualAmount) {+ updateIncomeStream(incomeStream.id, {+ annualAmount: newAmount,+ });+ }+ }}+ />+ </Field>++ <Field width="flex" style={{ minWidth: 130 }} truncate={false}>+ {usesTaxBands ? (+ <MonteCarloNumberInput+ value={incomeStream.taxableFraction}+ aria-label={t('Taxable portion (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ updateIncomeStream(incomeStream.id, {+ taxableFraction: newValue ?? 1,+ })+ }+ />+ ) : (+ <MonteCarloNumberInput+ value={incomeStream.taxRate}+ aria-label={t('Tax (%)')}+ scale={100}+ min={0}+ max={MAX_WITHDRAWAL_TAX_RATE * 100}+ onCommit={newValue =>+ updateIncomeStream(incomeStream.id, {+ taxRate: newValue ?? 0,+ })+ }+ />+ )}+ </Field>++ <Field width="flex" style={{ minWidth: 170 }} truncate={false}>+ <LabeledCheckbox+ id={`income-inflation-${incomeStream.id}`}+ checked={incomeStream.adjustsWithInflation}+ onChange={event =>+ updateIncomeStream(incomeStream.id, {+ adjustsWithInflation: event.target.checked,+ })+ }+ >+ <Trans>Adjust by inflation</Trans>+ </LabeledCheckbox>+ </Field>++ <Field+ width={36}+ truncate={false}+ style={{ alignItems: 'center' }}+ >+ <Button+ variant="bare"+ aria-label={t('Remove income')}+ onPress={() => removeIncomeStream(incomeStream.id)}+ style={{ padding: 6 }}+ >+ <SvgDelete width={12} height={12} />+ </Button>+ </Field>+ </Row>+ ))}+ </View>+ </View>++ <View style={{ flexDirection: 'row' }}>+ <Button onPress={addIncomeStream}>+ <SvgAdd width={10} height={10} style={{ marginRight: 5 }} />+ <Trans>Add income</Trans>+ </Button>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsxindex 63f5b3eb87..cee922d2f7 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx@@ -47,7 +47,7 @@ type MonteCarloPotConfigurationProps = ComponentPropsWithoutRef<typeof GridListItem<MonteCarloPot>> & {pot: MonteCarloPot;- potNumber: number;+ potLabel: string;canRemove: boolean;/** True when a historical return model is active */usesHistoricalReturns: boolean;@@ -59,7 +59,7 @@ type MonteCarloPotConfigurationProps = ComponentPropsWithoutRef<export function MonteCarloPotConfiguration({pot,- potNumber,+ potLabel,canRemove,usesHistoricalReturns,usesTaxBands,@@ -115,9 +115,117 @@ export function MonteCarloPotConfiguration({]: [];+ // The surplus pot is managed by the Manage surplus setting: it holds+ // whatever the plan didn't spend, as cash, immediately accessible,+ // untaxed and fee-free - so its row is read-only+ if (pot.isSurplus) {+ const readOnlyCellStyle = { color: theme.tableText };+ return (+ <GridListItem+ textValue={potLabel}+ className={css({+ '&[data-dragging]': {+ opacity: 0.5,+ },+ })}+ {...props}+ >+ <Row+ collapsed+ height={POT_ROW_HEIGHT}+ style={{+ backgroundColor: theme.tableBackground,+ ':hover': { backgroundColor: theme.tableRowBackgroundHover },+ }}+ >+ <Field width={POT_COLUMNS.expand} />+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.name }}+ truncate={false}+ >+ <View+ style={{ flexDirection: 'row', alignItems: 'center', gap: 5 }}+ >+ <Text style={readOnlyCellStyle}>{potLabel}</Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Your plan's surplus pot. Income beyond your spending is+ saved here each year, and it is drawn on before any other pot+ when spending needs funding. It starts empty and holds cash:+ no access age, no tax, no fees. To remove it, tick Assume any+ unspent money is spent under Manage surplus on the Plan+ details tab.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.startingBalance }}+ truncate={false}+ >+ <Text style={readOnlyCellStyle}>+ <Trans>Starts empty</Trans>+ </Text>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.linkedAccount }}+ truncate={false}+ >+ <Text style={readOnlyCellStyle}>+ <Trans>None</Trans>+ </Text>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.allocation }}+ truncate={false}+ >+ <Text style={readOnlyCellStyle}>+ <Trans>Cash / money market</Trans>+ </Text>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.expectedReturn }}+ truncate={false}+ >+ <Text style={readOnlyCellStyle}>+ <FinancialText as="span">+ {historicalMixStats != null+ ? t('{{value}} (historical)', {+ value: `${(historicalMixStats.mean * 100).toFixed(1)}%`,+ })+ : `${(pot.expectedReturnMean * 100).toFixed(1)}%`}+ </FinancialText>+ </Text>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.volatility }}+ truncate={false}+ >+ <Text style={readOnlyCellStyle}>+ <FinancialText as="span">+ {historicalMixStats != null+ ? t('{{value}} (historical)', {+ value: `${(historicalMixStats.stdDev * 100).toFixed(1)}%`,+ })+ : `${(pot.returnStdDev * 100).toFixed(1)}%`}+ </FinancialText>+ </Text>+ </Field>+ <Field width={POT_COLUMNS.remove} />+ </Row>+ </GridListItem>+ );+ }+return (<GridListItem- textValue={pot.name || t('Pot {{number}}', { number: potNumber })}+ textValue={potLabel}className={css({'&[data-dragging]': {opacity: 0.5,@@ -166,7 +274,7 @@ export function MonteCarloPotConfiguration({// auto-filled name actually shows upkey={pot.accountId ?? 'manual'}defaultValue={pot.name}- placeholder={t('Pot {{number}}', { number: potNumber })}+ placeholder={potLabel}onUpdate={newName => {if (newName !== pot.name) {onPotChange({ name: newName });diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsxindex ad066c0da6..c5ce2c4851 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx@@ -15,13 +15,22 @@ import { View } from '@actual-app/components/view';import { FinancialText } from '#components/FinancialText';import { PrivacyFilter } from '#components/PrivacyFilter';import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import {+ getMonteCarloPotLabel,+ getMonteCarloSurplusPotLabel,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import type {+ MonteCarloIncomeStream,MonteCarloPot,MonteCarloRuleExplanation,MonteCarloRunDetailRow,MonteCarloWithdrawalRuleConfig,} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';+import {+ buildMonteCarloYearStory,+ formatRuleRate,+} from '#components/reports/reports/monte-carlo/monteCarloYearStory';import { useFormat } from '#hooks/useFormat';// The minWidth keeps amounts readable on narrow screens - the table@@ -39,13 +48,6 @@ const POT_CELL_STYLE = {textAlign: 'right',} as const;-// Enough precision that multiplying the displayed rate by the balance-// reproduces the displayed amounts; trailing zeros trimmed so simple-// rates still read cleanly (4% rather than 4.0000%)-function formatRuleRate(rate: number) {- return `${Number((rate * 100).toFixed(4))}%`;-}-type MonteCarloRunDetailTableProps = {rows: MonteCarloRunDetailRow[];pots: MonteCarloPot[];@@ -54,6 +56,8 @@ type MonteCarloRunDetailTableProps = {startAge: number;/** Show the Contributions columns (the plan has contributions set up) */hasContributions: boolean;+ /** The plan's income streams; the Income column shows when there are any */+ incomeStreams: MonteCarloIncomeStream[];/** The configured rule, quoted in the per-year explanations */withdrawalRule: MonteCarloWithdrawalRuleConfig;/** Rendered between the header row and the table - the cashflow chart */@@ -68,6 +72,7 @@ export function MonteCarloRunDetailTable({simulationCount,startAge,hasContributions,+ incomeStreams,withdrawalRule,cashflowGraph,onBack,@@ -75,23 +80,43 @@ export function MonteCarloRunDetailTable({const { t } = useTranslation();const format = useFormat();const [expandedYears, setExpandedYears] = useState<Set<number>>(new Set());+ // Years whose detailed working is shown under the summary+ const [workingYears, setWorkingYears] = useState<Set<number>>(new Set());+ const hasIncome = incomeStreams.length > 0;+ const surplusPotName = getMonteCarloSurplusPotLabel(pots, t);+ const hasSurplusPot = pots.some(pot => pot.isSurplus);const lastRow = rows[rows.length - 1];const hasSurvived = lastRow != null && lastRow.endBalance > 0;// Present whenever the plan has inflation enabledconst showInflation = rows.some(row => row.inflation != null);const allExpanded = rows.length > 0 && expandedYears.size === rows.length;+ function toggleInSet(previous: Set<number>, year: number) {+ const next = new Set(previous);+ if (next.has(year)) {+ next.delete(year);+ } else {+ next.add(year);+ }+ return next;+ }+function toggleYear(year: number) {- setExpandedYears(previous => {- const next = new Set(previous);- if (next.has(year)) {+ if (expandedYears.has(year)) {+ // Collapsing a year hides its working too, so reopening it starts+ // from the summary again+ setWorkingYears(previous => {+ const next = new Set(previous);next.delete(year);- } else {- next.add(year);- }- return next;- });+ return next;+ });+ }+ setExpandedYears(previous => toggleInSet(previous, year));+ }++ function toggleWorking(year: number) {+ setWorkingYears(previous => toggleInSet(previous, year));}// Run-level cost of the plan: what left the pots, and how much of it@@ -99,10 +124,76 @@ export function MonteCarloRunDetailTable({let totalWithdrawn = 0;let totalTax = 0;let totalFees = 0;+ let totalIncome = 0;+ let totalIncomeTax = 0;for (const row of rows) {totalWithdrawn += row.withdrawal;totalTax += row.taxPaid;totalFees += row.feesPaid;+ totalIncome += row.income;+ totalIncomeTax += row.incomeTax;+ }++ function getIncomeTotalsSentence() {+ const total = format(totalIncome, 'financial');+ const tax = format(totalIncomeTax, 'financial');+ if (totalIncomeTax > 0) {+ return t(+ 'Income received over this run: {{total}}, of which {{tax}} tax.',+ {+ total,+ tax,+ },+ );+ }+ return t('Income received over this run: {{total}}.', { total });+ }++ // How the year's actual spending compares with the plan: on target or a+ // shortfall (the pots couldn't cover it)+ function getSpentSentence(row: MonteCarloRunDetailRow) {+ const spent = format(row.spent, 'financial');+ const planned = format(row.plannedSpending, 'financial');+ if (row.spent < row.plannedSpending) {+ return t(+ 'Spent: {{spent}} of the {{planned}} planned - {{shortfall}} short.',+ {+ spent,+ planned,+ shortfall: format(row.plannedSpending - row.spent, 'financial'),+ },+ );+ }+ if (row.spent > row.plannedSpending) {+ return t(+ 'Spent: {{spent}} - {{extra}} more than the {{planned}} planned.',+ {+ spent,+ planned,+ extra: format(row.spent - row.plannedSpending, 'financial'),+ },+ );+ }+ return t('Spent: {{spent}}, as planned.', { spent });+ }++ function getSavedSentence(row: MonteCarloRunDetailRow) {+ return t(+ 'Saved into {{pot}}: {{amount}} - income beyond what the plan spends.',+ { pot: surplusPotName, amount: format(row.surplusSaved, 'financial') },+ );+ }++ // "State pension: 12,000.00" - the per-stream lines under a year's+ // income sentence when more than one stream is configured+ function getIncomeStreamLine(incomeIndex: number, amount: number) {+ const incomeStream = incomeStreams[incomeIndex];+ return t('{{name}}: {{amount}}', {+ name:+ incomeStream.name ||+ t('Income {{number}}', { number: incomeIndex + 1 }),+ amount: format(amount, 'financial'),+ });}// Four sentence variants so each language can phrase the combinations@@ -310,11 +401,14 @@ export function MonteCarloRunDetailTable({</Text><Buttonvariant="bare"- onPress={() =>+ onPress={() => {setExpandedYears(allExpanded ? new Set() : new Set(rows.map(row => row.year)),- )- }+ );+ if (allExpanded) {+ setWorkingYears(new Set());+ }+ }}style={{ marginLeft: 'auto', color: theme.pageText }}>{allExpanded ? (@@ -331,6 +425,16 @@ export function MonteCarloRunDetailTable({<PrivacyFilter><FinancialText as="span">{getTotalsSentence()}</FinancialText></PrivacyFilter>+ {totalIncome > 0 && (+ <>+ {' '}+ <PrivacyFilter>+ <FinancialText as="span">+ {getIncomeTotalsSentence()}+ </FinancialText>+ </PrivacyFilter>+ </>+ )}</Text><View style={{ ...styles.horizontalScrollbar, overflowX: 'auto' }}>@@ -356,9 +460,17 @@ export function MonteCarloRunDetailTable({<Trans>Contributions</Trans></Text>)}+ {hasIncome && (+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>+ <Trans>Income (net)</Trans>+ </Text>+ )}<Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}><Trans>Withdrawal</Trans></Text>+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>+ <Trans>Spent</Trans>+ </Text><Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}><Trans>Investment growth</Trans></Text>@@ -386,11 +498,15 @@ export function MonteCarloRunDetailTable({{rows.map(row => {const isFailureRow = row === lastRow && !hasSurvived;const isExpanded = expandedYears.has(row.year);+ const showsWorking = workingYears.has(row.year);// Growth applies to what stayed invested after contributions// came in and the withdrawal went out; no growth on a failure// year (the plan stops there)const growthBase =- row.startBalance + row.contributions - row.withdrawal;+ row.startBalance ++ row.contributions ++ row.surplusSaved -+ row.withdrawal;const growthPct =!isFailureRow && growthBase > 0? (row.growth / growthBase) * 100@@ -441,7 +557,19 @@ export function MonteCarloRunDetailTable({<Text style={AMOUNT_CELL_STYLE}><PrivacyFilter><FinancialText as="span">- {format(row.contributions, 'financial')}+ {format(+ row.contributions + row.surplusSaved,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {hasIncome && (+ <Text style={AMOUNT_CELL_STYLE}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(row.income - row.incomeTax, 'financial')}</FinancialText></PrivacyFilter></Text>@@ -453,6 +581,21 @@ export function MonteCarloRunDetailTable({</FinancialText></PrivacyFilter></Text>+ <Text+ style={{+ ...AMOUNT_CELL_STYLE,+ // A year that couldn't be fully paid for stands out+ ...(row.spent < row.plannedSpending && {+ color: theme.reportsNumberNegative,+ }),+ }}+ >+ <PrivacyFilter>+ <FinancialText as="span">+ {format(row.spent, 'financial')}+ </FinancialText>+ </PrivacyFilter>+ </Text><Textstyle={{...AMOUNT_CELL_STYLE,@@ -520,88 +663,201 @@ export function MonteCarloRunDetailTable({<Text style={{ fontSize: 13, color: theme.pageText }}><PrivacyFilter><FinancialText as="span">- {row.taxPaid > 0- ? t(- 'Withdrawal: {{gross}} gross − {{tax}} tax = {{net}} to spend.',- {- gross: format(row.withdrawal, 'financial'),- tax: format(row.taxPaid, 'financial'),- net: format(netSpending, 'financial'),- },- )- : t('Withdrawal: {{gross}}, untaxed.', {- gross: format(row.withdrawal, 'financial'),- })}+ {buildMonteCarloYearStory({+ row,+ withdrawalRule,+ surplusPotName,+ hasSurplusPot,+ format,+ translate: t,+ }).join(' ')}</FinancialText></PrivacyFilter></Text>- {row.ruleExplanation != null && (- <Text style={{ fontSize: 13, color: theme.pageText }}>- <PrivacyFilter>- <FinancialText as="span">- {getRuleExplanationSentence(row.ruleExplanation)}- </FinancialText>- </PrivacyFilter>- </Text>- )}- {row.minimumApplied && (- <Text style={{ fontSize: 13, color: theme.pageText }}>- <PrivacyFilter>- <FinancialText as="span">- {t(- 'Raised to the minimum withdrawal: {{amount}}.',- {- amount: format(row.withdrawal, 'financial'),- },- )}- </FinancialText>- </PrivacyFilter>- </Text>- )}- {row.contributions > 0 && (- <Text style={{ fontSize: 13, color: theme.pageText }}>- <PrivacyFilter>- <FinancialText as="span">- {t(- 'Contributions: {{amount}}, added at the start of the year.',- {- amount: format(row.contributions, 'financial'),- },- )}- </FinancialText>- </PrivacyFilter>- </Text>- )}- {row.feesPaid > 0 && (- <Text style={{ fontSize: 13, color: theme.pageText }}>- <PrivacyFilter>- <FinancialText as="span">- {t(- 'Fees paid: {{amount}}, charged at the end of the year.',- {- amount: format(row.feesPaid, 'financial'),- },- )}- </FinancialText>- </PrivacyFilter>- </Text>- )}- {row.inaccessibleBalance != null && (- <Text style={{ fontSize: 13, color: theme.pageText }}>- <PrivacyFilter>- <FinancialText as="span">- {t(- '{{amount}} remained locked in pots that had not reached their access age.',- {- amount: format(- row.inaccessibleBalance,- 'financial',- ),- },- )}- </FinancialText>- </PrivacyFilter>- </Text>+ <Button+ variant="bare"+ onPress={() => toggleWorking(row.year)}+ style={{+ alignSelf: 'flex-start',+ padding: 0,+ color: theme.pageTextLight,+ textDecoration: 'underline',+ }}+ >+ {showsWorking ? (+ <Trans>Hide the working</Trans>+ ) : (+ <Trans>Show the working</Trans>+ )}+ </Button>+ {showsWorking && (+ <View style={{ gap: 4, marginTop: 6 }}>+ {row.ruleExplanation != null && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {getRuleExplanationSentence(+ row.ruleExplanation,+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {row.minimumApplied && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {t(+ 'Raised to the minimum spending: {{amount}}.',+ {+ amount: format(+ row.plannedSpending,+ 'financial',+ ),+ },+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {row.income > 0 && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {row.incomeTax > 0+ ? t(+ 'Income: {{gross}} gross − {{tax}} tax = {{net}} received.',+ {+ gross: format(row.income, 'financial'),+ tax: format(row.incomeTax, 'financial'),+ net: format(+ row.income - row.incomeTax,+ 'financial',+ ),+ },+ )+ : t('Income: {{gross}}, untaxed.', {+ gross: format(row.income, 'financial'),+ })}+ {incomeStreams.length > 1 &&+ ` (${row.incomeAmounts+ .map((amount, incomeIndex) =>+ amount > 0+ ? getIncomeStreamLine(+ incomeIndex,+ amount,+ )+ : null,+ )+ .filter(line => line != null)+ .join('; ')})`}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {row.taxPaid > 0+ ? t(+ 'Withdrawal: {{gross}} gross − {{tax}} tax = {{net}} to spend.',+ {+ gross: format(+ row.withdrawal,+ 'financial',+ ),+ tax: format(row.taxPaid, 'financial'),+ net: format(netSpending, 'financial'),+ },+ )+ : t('Withdrawal: {{gross}}, untaxed.', {+ gross: format(row.withdrawal, 'financial'),+ })}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {getSpentSentence(row)}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ {row.surplusSaved > 0 && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {getSavedSentence(row)}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {row.unspentIncome > 0 && row.surplusSaved === 0 && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {t(+ 'Unspent income: {{amount}} - more came in than the plan spends, and it leaves the plan.',+ {+ amount: format(+ row.unspentIncome,+ 'financial',+ ),+ },+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {row.contributions > 0 && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {t(+ 'Contributions: {{amount}}, added at the start of the year.',+ {+ amount: format(+ row.contributions,+ 'financial',+ ),+ },+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {row.feesPaid > 0 && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {t(+ 'Fees paid: {{amount}}, charged at the end of the year.',+ {+ amount: format(row.feesPaid, 'financial'),+ },+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ {row.inaccessibleBalance != null && (+ <Text style={{ fontSize: 13, color: theme.pageText }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {t(+ '{{amount}} remained locked in pots that had not reached their access age.',+ {+ amount: format(+ row.inaccessibleBalance,+ 'financial',+ ),+ },+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ )}+ </View>)}{pots.length > 0 && (@@ -638,15 +894,29 @@ export function MonteCarloRunDetailTable({<Trans>Start balance</Trans></Text>{hasContributions && (- <Text+ <Viewstyle={{- ...GROUP_HEADING_STYLE,- ...POT_CELL_STYLE,width: 130,+ flexShrink: 0,+ flexDirection: 'row',+ justifyContent: 'flex-end',+ alignItems: 'center',+ gap: 4,}}>- <Trans>Contributed</Trans>- </Text>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Contributed</Trans>+ </Text>+ {hasSurplusPot && (+ <MonteCarloHelpTooltip placement="bottom end">+ <Trans>+ For the {{ surplusPotName }} pot this is the+ money the plan didn't spend that year,+ saved into it before growth.+ </Trans>+ </MonteCarloHelpTooltip>+ )}+ </View>)}<Textstyle={{@@ -745,10 +1015,7 @@ export function MonteCarloRunDetailTable({}}><Text style={{ flex: 1, minWidth: 120 }}>- {pot.name ||- t('Pot {{number}}', {- number: potIndex + 1,- })}+ {getMonteCarloPotLabel(pots, potIndex, t)}</Text><Text style={{ ...POT_CELL_STYLE, width: 130 }}><PrivacyFilter>@@ -765,7 +1032,10 @@ export function MonteCarloRunDetailTable({<PrivacyFilter><FinancialText as="span">{format(- row.potContributions[potIndex] ?? 0,+ (row.potContributions[potIndex] ?? 0) ++ (pot.isSurplus+ ? row.surplusSaved+ : 0),'financial',)}</FinancialText>diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration.tsxindex 30e2035403..9cec5c92f3 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration.tsx@@ -32,16 +32,16 @@ const INLINE_INPUT_STYLE = {type MonteCarloWithdrawalRuleConfigurationProps = {rule: MonteCarloWithdrawalRuleConfig;- minimumWithdrawal: number;+ minimumSpending: number;onRuleChange: (changes: Partial<MonteCarloWithdrawalRuleConfig>) => void;- onMinimumWithdrawalChange: (value: number) => void;+ onMinimumSpendingChange: (value: number) => void;};export function MonteCarloWithdrawalRuleConfiguration({rule,- minimumWithdrawal,+ minimumSpending,onRuleChange,- onMinimumWithdrawalChange,+ onMinimumSpendingChange,}: MonteCarloWithdrawalRuleConfigurationProps) {const { t } = useTranslation();@@ -80,22 +80,25 @@ export function MonteCarloWithdrawalRuleConfiguration({<View style={FIELD_STYLE}><View style={FIELD_LABEL_ROW_STYLE}><Text style={FIELD_LABEL_STYLE}>- <Trans>Minimum withdrawal</Trans>+ <Trans>Minimum spending</Trans></Text><MonteCarloHelpTooltip><Trans>- The annual withdrawal never drops below this amount, no matter- what the rule says. It only applies in years with planned- spending - a spending phase set to 0 takes nothing. Like your- planned spending, it's in today's money and rises- with inflation. Set to 0 for no floor.+ The lowest amount you need to live on in any year, no matter+ what the rule says: when the rule cuts below it, the plan is+ lifted back up to it and that is what gets spent. Income+ counts towards it, so the pots only withdraw enough to top it+ up. It only applies in years with planned spending - a+ spending phase set to 0 takes nothing. Like your planned+ spending, it's in today's money and rises with+ inflation. Set to 0 for no floor.</Trans></MonteCarloHelpTooltip></View><FinancialInput- value={minimumWithdrawal}+ value={minimumSpending}onUpdate={value =>- onMinimumWithdrawalChange(+ onMinimumSpendingChange(Math.min(MAX_AMOUNT, Math.max(0, value)),)}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.tsindex 60bce62d04..4abe55c2fa 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts@@ -4,16 +4,20 @@ import {getHistoricalMixStats,getHistoricalPresetStats,getMonteCarloHorizonYears,+ getMonteCarloPotLabel,getPotAssetWeights,MAX_AMOUNT,MAX_HORIZON_YEARS,MIN_HORIZON_YEARS,MIN_SIMULATION_COUNT,+ MONTE_CARLO_DEFAULTS,+ monteCarloConfigFromMeta,runMonteCarloSimulation,WITHDRAWAL_RULE_DEFAULTS,} from './monteCarloSimulation';import type {MonteCarloContribution,+ MonteCarloIncomeStream,MonteCarloParams,MonteCarloPot,} from './monteCarloSimulation';@@ -29,6 +33,24 @@ function makeContribution(toAge: null,annualAmount: 1_000_000,adjustsWithInflation: false,+ sourceIncomeStreamId: null,+ beforeTax: false,+ ...overrides,+ };+}++function makeIncomeStream(+ overrides: Partial<MonteCarloIncomeStream> = {},+): MonteCarloIncomeStream {+ return {+ id: 'income-1',+ name: 'Test income',+ fromAge: null,+ toAge: null,+ annualAmount: 1_000_000,+ adjustsWithInflation: false,+ taxRate: 0,+ taxableFraction: 1,...overrides,};}@@ -51,6 +73,7 @@ function makePot(overrides: Partial<MonteCarloPot> = {}): MonteCarloPot {annualFeeFixed: 0,feeAdjustsWithInflation: false,annualFeeRate: 0,+ isSurplus: false,...overrides,};}@@ -66,12 +89,13 @@ function makeParams(withdrawalStrategy: 'proportional',returnModel: 'normal',withdrawalRule: WITHDRAWAL_RULE_DEFAULTS,- minimumWithdrawal: 0,+ minimumSpending: 0,currentAge: 60,spendingPhases: [{ id: 'phase-1', name: '', fromAge: null, annualWithdrawal },],contributions: [],+ incomeStreams: [],inflationMean: null,inflationStdDev: 0,taxModel: 'flat',@@ -107,6 +131,45 @@ function deterministicDepletionYear(return null;}+describe('surplus pot defaults', () => {+ it('starts new plans with a surplus cash pot ahead of an ordinary pot', () => {+ expect(MONTE_CARLO_DEFAULTS.pots.map(pot => pot.isSurplus)).toEqual([+ true,+ false,+ ]);+ expect(MONTE_CARLO_DEFAULTS.pots[0]).toMatchObject({+ startingBalance: 0,+ accessAge: null,+ withdrawalTaxRate: 0,+ taxableFraction: 0,+ annualFeeRate: 0,+ annualFeeFixed: 0,+ });+ });++ it('keeps saved plans without a surplus pot unchanged', () => {+ const config = monteCarloConfigFromMeta({+ pots: [{ id: 'saved-pot', startingBalance: 500_000 }],+ });+ expect(config.pots.map(pot => pot.isSurplus)).toEqual([false]);+ });++ it('numbers ordinary pots without counting the surplus pot', () => {+ const translate = (key: string, options?: Record<string, unknown>) =>+ key.replace('{{number}}', String(options?.number));+ const pots = MONTE_CARLO_DEFAULTS.pots;+ expect(getMonteCarloPotLabel(pots, 0, translate)).toBe('Surplus cash');+ expect(getMonteCarloPotLabel(pots, 1, translate)).toBe('Pot 1');+ expect(+ getMonteCarloPotLabel(+ [...pots, { ...pots[1], name: 'ISA' }],+ 2,+ translate,+ ),+ ).toBe('ISA');+ });+});+describe('getMonteCarloHorizonYears', () => {it('derives the horizon from the configured ages', () => {expect(getMonteCarloHorizonYears({ currentAge: 60, targetAge: 90 })).toBe(@@ -219,7 +282,8 @@ describe('runMonteCarloSimulation', () => {);expect(inflated.medianDepletionYear).toBe(3);- // Flat withdrawals last one year longer: y4 hits exactly 0+ // Flat withdrawals last longer: y4 empties the pot to the penny,+ // which still funds that year, so the shortfall comes in y5const flat = runMonteCarloSimulation(makeParams({ annualWithdrawal: 50, inflationMean: null, horizonYears: 10 },@@ -230,7 +294,7 @@ describe('runMonteCarloSimulation', () => {},),);- expect(flat.medianDepletionYear).toBe(4);+ expect(flat.medianDepletionYear).toBe(5);});it('is deterministic for a given seed', () => {@@ -629,17 +693,19 @@ describe('runMonteCarloSimulation', () => {]);});- it('planned spending stays below the withdrawal when the minimum overrides a rule cut', () => {+ it('planned spending rises to the floor when the minimum overrides a rule cut', () => {// A crash pushes the withdrawal rate above the guardrails trigger, so- // the rule cuts spending - but the minimum pulls it back up. The- // captured plan is the rule's cut amount, the withdrawal the minimum+ // the rule cuts spending - but the minimum spending floor pulls the+ // plan back up: the floor is what the household lives on, so both the+ // plan and the withdrawal sit at it, and the rule's cut amount is only+ // kept in the explanationconst result = runMonteCarloSimulation(makeParams({annualWithdrawal: 4_000,horizonYears: 2,withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },- minimumWithdrawal: 4_000,+ minimumSpending: 4_000,captureRunDetail: 0,},{ startingBalance: 100_000, expectedReturnMean: -0.5, returnStdDev: 0 },@@ -651,9 +717,10 @@ describe('runMonteCarloSimulation', () => {if (cutYear.ruleExplanation?.kind !== 'factor') {throw new Error('expected a factor rule explanation');}- expect(cutYear.plannedSpending).toBe(cutYear.ruleExplanation.adjusted);+ expect(cutYear.ruleExplanation.adjusted).toBeLessThan(4_000);expect(cutYear.withdrawal).toBe(4_000);- expect(cutYear.plannedSpending).toBeLessThan(cutYear.withdrawal);+ expect(cutYear.plannedSpending).toBe(4_000);+ expect(cutYear.spent).toBe(4_000);});it('planned spending stays above the withdrawal on a shortfall year', () => {@@ -936,19 +1003,20 @@ describe('runMonteCarloSimulation', () => {});it('boundaries cut withdrawals and extend survival', () => {- // 10% withdrawal rate on a flat pot depletes in exactly year 10+ // 10% withdrawal rate on a flat pot empties it in year 10, so year+ // 11 is the first that can't be fundedconst base = makeParams({ annualWithdrawal: 10_000, horizonYears: 30 },{ startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },);const withoutRule = runMonteCarloSimulation(base);- expect(withoutRule.medianDepletionYear).toBe(10);+ expect(withoutRule.medianDepletionYear).toBe(11);const withRule = runMonteCarloSimulation({...base,withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'boundaries' },});- expect(withRule.medianDepletionYear ?? Infinity).toBeGreaterThan(10);+ expect(withRule.medianDepletionYear ?? Infinity).toBeGreaterThan(11);// The extra years come at the cost of incomeexpect(withRule.medianTotalWithdrawn).toBeLessThanOrEqual(100_000);});@@ -1166,7 +1234,7 @@ describe('runMonteCarloSimulation', () => {);});- it('minimum withdrawal floor neutralizes rule cuts', () => {+ it('minimum spending floor neutralizes rule cuts', () => {const base = makeParams({ annualWithdrawal: 10_000, horizonYears: 30 },{ startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },@@ -1175,7 +1243,7 @@ describe('runMonteCarloSimulation', () => {const cutsFloored = runMonteCarloSimulation({...base,withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'boundaries' },- minimumWithdrawal: 10_000,+ minimumSpending: 10_000,});expect(cutsFloored.percentileBands).toEqual(withoutRule.percentileBands);@@ -1184,7 +1252,7 @@ describe('runMonteCarloSimulation', () => {);});- it('takes nothing in zero-spend phases even with a minimum withdrawal', () => {+ it('takes nothing in zero-spend phases even with a minimum spending floor', () => {// Working years first (costs covered by salary), retirement at 65;// the floor guards against rule-driven cuts and must not invent// withdrawals during a deliberate zero-spend phase@@ -1196,7 +1264,7 @@ describe('runMonteCarloSimulation', () => {{horizonYears: 8,captureRunDetail: 0,- minimumWithdrawal: 15_000,+ minimumSpending: 15_000,withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },spendingPhases: [{ id: 'working', name: '', fromAge: null, annualWithdrawal: 0 },@@ -1218,7 +1286,7 @@ describe('runMonteCarloSimulation', () => {}});- it("keeps the minimum withdrawal floor in today's money under inflation", () => {+ it("keeps the minimum spending floor in today's money under inflation", () => {// Guardrails cut hard while prices rise; the floor must rise with// inflation too, so in today's money withdrawals never dip below itconst result = runMonteCarloSimulation(@@ -1230,7 +1298,7 @@ describe('runMonteCarloSimulation', () => {inflationStdDev: 0,deflateToTodaysMoney: true,captureRunDetail: 0,- minimumWithdrawal: 8_000,+ minimumSpending: 8_000,withdrawalRule: {...WITHDRAWAL_RULE_DEFAULTS,type: 'guardrails',@@ -1336,7 +1404,8 @@ describe('runMonteCarloSimulation', () => {it('sequential order skips locked pots until they unlock', () => {// The first-listed pot is locked past the horizon, so sequential- // withdrawals drain the second pot: 100 at 10/year fails in year 10+ // withdrawals drain the second pot: 100 at 10/year empties it in+ // year 10 and fails in year 11const result = runMonteCarloSimulation(makeParams({withdrawalStrategy: 'sequential',@@ -1360,7 +1429,7 @@ describe('runMonteCarloSimulation', () => {}),);- expect(result.medianDepletionYear).toBe(10);+ expect(result.medianDepletionYear).toBe(11);});it('best-performer order drains the pot with the highest return last year', () => {@@ -1821,14 +1890,14 @@ describe('runMonteCarloSimulation', () => {]);});- it('ignores the minimum withdrawal floor when no rule is active', () => {+ it('ignores the minimum spending floor when no rule is active', () => {// A leftover floor higher than the planned spending must not raise// withdrawals once the rule is switched back to Noneconst result = runMonteCarloSimulation(makeParams({annualWithdrawal: 10_000,- minimumWithdrawal: 20_000,+ minimumSpending: 20_000,horizonYears: 10,},{ startingBalance: 500_000, expectedReturnMean: 0, returnStdDev: 0 },@@ -2634,21 +2703,567 @@ describe('runMonteCarloSimulation', () => {}});- it('fees alone can deplete a plan', () => {+ it('fees can empty a pot, and the plan fails once spending goes unfunded', () => {+ // A 400 fee drains 1,000 by year 3; nothing is spent until age 64+ // (year 5), so the plan only fails there, when the first bill can't+ // be paid+ const feeDrainedPot = {+ startingBalance: 1_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeFixed: 400,+ };const result = runMonteCarloSimulation(makeParams(- { annualWithdrawal: 0, horizonYears: 5 },{- startingBalance: 1_000,- expectedReturnMean: 0,- returnStdDev: 0,- annualFeeFixed: 400,+ spendingPhases: [+ { id: 'phase-1', name: '', fromAge: null, annualWithdrawal: 0 },+ { id: 'phase-2', name: '', fromAge: 64, annualWithdrawal: 100 },+ ],+ horizonYears: 6,},+ feeDrainedPot,),);-expect(result.successRate).toBe(0);- expect(result.medianDepletionYear).toBe(3);+ expect(result.medianDepletionYear).toBe(5);++ // With nothing to fund, empty pots are not a failure+ const nothingToFund = runMonteCarloSimulation(+ makeParams({ annualWithdrawal: 0, horizonYears: 5 }, feeDrainedPot),+ );+ expect(nothingToFund.successRate).toBe(1);+ expect(nothingToFund.medianEndingBalance).toBe(0);+ });++ describe('income streams', () => {+ it('income pays for spending first and the pots fund the rest', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 4_000,+ horizonYears: 3,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_200 })],+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([2_800, 2_800, 2_800]);+ expect(rows.map(row => row.income)).toEqual([1_200, 1_200, 1_200]);+ expect(rows[0].incomeAmounts).toEqual([1_200]);+ expect(rows[0].incomeTax).toBe(0);+ expect(rows[0].unspentIncome).toBe(0);+ // The plan is still the household's 4,000+ expect(rows[0].plannedSpending).toBe(4_000);+ expect(result.medianEndingBalance).toBe(100_000 - 3 * 2_800);+ });++ it('respects the income age window and the flat tax rate', () => {+ // 1,000 gross at 20% tax from age 61 to 62 (years 2 and 3)+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 4_000,+ horizonYears: 4,+ incomeStreams: [+ makeIncomeStream({+ annualAmount: 1_000,+ fromAge: 61,+ toAge: 62,+ taxRate: 0.2,+ }),+ ],+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.income)).toEqual([0, 1_000, 1_000, 0]);+ expect(rows.map(row => row.incomeTax)).toEqual([0, 200, 200, 0]);+ // 800 net offsets the 4,000 plan+ expect(rows.map(row => row.withdrawal)).toEqual([+ 4_000, 3_200, 3_200, 4_000,+ ]);+ });++ it('under tax bands, income fills the lower bands and pot withdrawals stack on top', () => {+ // 20% above 1,000: a 1,500 pension is taxed 100 and leaves 1,400+ // net. The pots must deliver 600 net - entirely inside the 20% band+ // now that the pension has used the tax-free allowance, so the+ // gross-up is 750 (tax 150), where alone it would have been untaxed+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 2_000,+ horizonYears: 1,+ taxModel: 'bands',+ taxBands: [+ { id: 'band-1', from: 0, rate: 0 },+ { id: 'band-2', from: 1_000, rate: 0.2 },+ ],+ incomeStreams: [makeIncomeStream({ annualAmount: 1_500 })],+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const [row] = result.runDetail!;+ expect(row.incomeTax).toBe(100);+ expect(row.withdrawal).toBe(750);+ expect(row.taxPaid).toBe(150);+ expect(row.plannedSpending).toBe(2_000);+ });++ it('caps an income-sourced contribution at what the stream pays', () => {+ // 1,500 wanted from a 1,000 stream that stops at age 61+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 0,+ horizonYears: 3,+ incomeStreams: [+ makeIncomeStream({ annualAmount: 1_000, toAge: 61 }),+ ],+ contributions: [+ makeContribution({+ annualAmount: 1_500,+ sourceIncomeStreamId: 'income-1',+ }),+ ],+ captureRunDetail: 0,+ },+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.contributions)).toEqual([1_000, 1_000, 0]);+ expect(rows.map(row => row.contributionAmounts[0])).toEqual([+ 1_000, 1_000, 0,+ ]);+ expect(rows.map(row => row.unspentIncome)).toEqual([0, 0, 0]);+ expect(result.medianEndingBalance).toBe(2_000);+ });++ it('a before-tax contribution reduces the income tax; an after-tax one does not', () => {+ const income = makeIncomeStream({ annualAmount: 1_000, taxRate: 0.2 });+ const sourced = (beforeTax: boolean) =>+ runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 0,+ horizonYears: 1,+ incomeStreams: [income],+ contributions: [+ makeContribution({+ annualAmount: 400,+ sourceIncomeStreamId: 'income-1',+ beforeTax,+ }),+ ],+ captureRunDetail: 0,+ },+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ ).runDetail![0];++ // Salary sacrifice: tax on the remaining 600, leaving 480 to spend+ const beforeTax = sourced(true);+ expect(beforeTax.contributions).toBe(400);+ expect(beforeTax.incomeTax).toBe(120);+ expect(beforeTax.unspentIncome).toBe(480);+ // After tax: 200 tax on the full 1,000, then 400 out of the 800 net+ const afterTax = sourced(false);+ expect(afterTax.contributions).toBe(400);+ expect(afterTax.incomeTax).toBe(200);+ expect(afterTax.unspentIncome).toBe(400);+ });++ it('a before-tax contribution reduces taxable income under the bands model', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 0,+ horizonYears: 1,+ taxModel: 'bands',+ taxBands: [+ { id: 'band-1', from: 0, rate: 0 },+ { id: 'band-2', from: 1_000, rate: 0.2 },+ ],+ incomeStreams: [makeIncomeStream({ annualAmount: 1_500 })],+ contributions: [+ makeContribution({+ annualAmount: 600,+ sourceIncomeStreamId: 'income-1',+ beforeTax: true,+ }),+ ],+ captureRunDetail: 0,+ },+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const [row] = result.runDetail!;+ // 1,500 - 600 = 900 taxable, below the 1,000 threshold+ expect(row.incomeTax).toBe(0);+ expect(row.contributions).toBe(600);+ expect(row.unspentIncome).toBe(900);+ });++ it('income beyond the plan is unspent and leaves the pots untouched', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 400,+ horizonYears: 2,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_000 })],+ captureRunDetail: 0,+ },+ { startingBalance: 5_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([0, 0]);+ expect(rows.map(row => row.unspentIncome)).toEqual([600, 600]);+ expect(result.medianEndingBalance).toBe(5_000);+ });++ it('a plan whose income covers its spending survives with empty pots', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 800,+ horizonYears: 10,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_000 })],+ },+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.successRate).toBe(1);+ expect(result.medianEndingBalance).toBe(0);+ });++ it('withdrawal rules work on the pot-funded part of the plan', () => {+ // 4,000 planned, 2,000 covered by income: the rule sees a 2,000+ // withdrawal, not the household's 4,000+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 4_000,+ horizonYears: 3,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ incomeStreams: [makeIncomeStream({ annualAmount: 2_000 })],+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const explanation = result.runDetail![1].ruleExplanation;+ if (explanation?.kind !== 'factor') {+ throw new Error('expected a factor rule explanation');+ }+ expect(explanation.planned).toBe(2_000);+ expect(explanation.action).toBe('none');+ expect(result.runDetail![1].withdrawal).toBe(2_000);+ });++ it('the minimum spending floor counts income towards it', () => {+ // 2,000 planned, 1,000 covered by income, 1,800 floor: a crash makes+ // guardrails cut the pot-funded 1,000 by 10% a year (900, 810, 729)+ // until the floor bites - and the pots only top spending up to it,+ // so the floor withdrawal is 800, not 1,800+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 2_000,+ horizonYears: 4,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ minimumSpending: 1_800,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_000 })],+ captureRunDetail: 0,+ },+ {+ startingBalance: 100_000,+ expectedReturnMean: -0.5,+ returnStdDev: 0,+ },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([1_000, 900, 810, 800]);+ expect(rows.map(row => row.minimumApplied ?? false)).toEqual([+ false,+ false,+ false,+ true,+ ]);+ expect(rows[3].plannedSpending).toBe(1_800);+ expect(rows[3].spent).toBe(1_800);+ });++ it('the minimum spending floor does not apply when income covers the plan', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 2_000,+ horizonYears: 2,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ minimumSpending: 3_000,+ incomeStreams: [makeIncomeStream({ annualAmount: 2_000 })],+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([0, 0]);+ expect(rows.every(row => row.minimumApplied === undefined)).toBe(true);+ });++ it('the unfunded tail after a failure keeps receiving income', () => {+ // 1,000 planned, 400 income: the 500 pot can't fund the 600 gap in+ // year 1. The tail still shows the income and the full plan+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 1_000,+ horizonYears: 3,+ incomeStreams: [makeIncomeStream({ annualAmount: 400 })],+ captureRunDetail: 0,+ },+ { startingBalance: 500, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.afterDepletion ?? false)).toEqual([+ false,+ true,+ true,+ ]);+ expect(rows.map(row => row.income)).toEqual([400, 400, 400]);+ expect(rows.map(row => row.plannedSpending)).toEqual([+ 1_000, 1_000, 1_000,+ ]);+ expect(rows[2].unspentIncome).toBe(0);+ });++ it('captures what actually reached spending each year', () => {+ // 1,200 income + 2,800 net withdrawal fund the 4,000 plan until the+ // 5,000 pot runs dry in year 2; the tail only has the income+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 4_000,+ horizonYears: 3,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_200 })],+ captureRunDetail: 0,+ },+ { startingBalance: 5_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.plannedSpending)).toEqual([+ 4_000, 4_000, 4_000,+ ]);+ // Year 2 fails: the remaining 2,200 plus the income is all that's+ // spent; year 3 is the unfunded tail with only the income+ expect(rows.map(row => row.spent)).toEqual([4_000, 3_400, 1_200]);+ expect(rows.map(row => row.afterDepletion ?? false)).toEqual([+ false,+ false,+ true,+ ]);+ });++ it('saves unspent income into the surplus pot and draws on it first', () => {+ // 1,000 income against a 400 plan for two years, then no income:+ // the 600 left each year is saved, and once the income stops the+ // plan is paid from the surplus pot before the main pot is touched+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 400,+ // The surplus pot is pinned to the cash preset, so give it a+ // zero-return history to keep the arithmetic exact; the custom+ // main pot keeps its own draws under historical models+ returnModel: 'historical-bootstrap',+ historicalReturns: [+ { year: 2000, stocks: 0, bonds: 0, cash: 0, inflation: 0 },+ ],+ horizonYears: 4,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_000, toAge: 61 })],+ pots: [+ makePot({+ id: 'surplus',+ isSurplus: true,+ startingBalance: 0,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'main',+ startingBalance: 5_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ ],+ captureRunDetail: 0,+ }),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.surplusSaved)).toEqual([600, 600, 0, 0]);+ expect(rows.map(row => row.potWithdrawals)).toEqual([+ [0, 0],+ [0, 0],+ [400, 0],+ [400, 0],+ ]);+ expect(rows.map(row => row.potBalances)).toEqual([+ [600, 5_000],+ [1_200, 5_000],+ [800, 5_000],+ [400, 5_000],+ ]);+ for (const row of rows) {+ expect(+ row.startBalance ++ row.contributions ++ row.surplusSaved -+ row.withdrawal ++ row.growth -+ row.feesPaid,+ ).toBe(row.endBalance);+ }+ });++ it('lifts the plan to the spending floor instead of saving the difference', () => {+ // The spending-floor scenario again, now with a surplus pot: the+ // 800 floor withdrawal is 71 above the rule's 729, but the floor is+ // money to live on, so the plan rises to it and nothing is saved+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 2_000,+ // The surplus pot is pinned to the cash preset, so give it a+ // zero-return history to keep the arithmetic exact; the custom+ // main pot keeps its own draws under historical models+ returnModel: 'historical-bootstrap',+ historicalReturns: [+ { year: 2000, stocks: 0, bonds: 0, cash: 0, inflation: 0 },+ ],+ horizonYears: 4,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ minimumSpending: 1_800,+ incomeStreams: [makeIncomeStream({ annualAmount: 1_000 })],+ pots: [+ makePot({+ id: 'surplus',+ isSurplus: true,+ startingBalance: 0,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'main',+ startingBalance: 100_000,+ expectedReturnMean: -0.5,+ returnStdDev: 0,+ }),+ ],+ captureRunDetail: 0,+ }),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([1_000, 900, 810, 800]);+ expect(rows.map(row => row.surplusSaved)).toEqual([0, 0, 0, 0]);+ expect(rows[3].potBalances[0]).toBe(0);+ expect(rows[3].plannedSpending).toBe(1_800);+ expect(rows[3].spent).toBe(1_800);+ });++ it('survives on income that passes through a pot each year', () => {+ // Empty pots, 40k untaxed income paid into the cash pot by a+ // sourced contribution, and 40k spending: every year empties the+ // pot to the penny and is still fully funded+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 40_000,+ horizonYears: 5,+ incomeStreams: [+ makeIncomeStream({ id: 'salary', annualAmount: 40_000 }),+ ],+ contributions: [+ makeContribution({+ potId: 'cash',+ sourceIncomeStreamId: 'salary',+ annualAmount: 40_000,+ }),+ ],+ pots: [+ makePot({+ id: 'cash',+ startingBalance: 0,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ ],+ captureRunDetail: 0,+ }),+ );++ expect(result.successRate).toBe(1);+ const rows = result.runDetail!;+ expect(rows).toHaveLength(5);+ expect(rows.map(row => row.withdrawal)).toEqual(+ new Array(5).fill(40_000),+ );+ expect(rows.map(row => row.spent)).toEqual(new Array(5).fill(40_000));+ expect(rows.map(row => row.endBalance)).toEqual(new Array(5).fill(0));+ });++ it('reconciles each stream to the row total in the run detail', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 0,+ horizonYears: 2,+ inflationMean: 0.1,+ inflationStdDev: 0,+ deflateToTodaysMoney: true,+ incomeStreams: [+ makeIncomeStream({ id: 'income-1', annualAmount: 1_001 }),+ makeIncomeStream({+ id: 'income-2',+ annualAmount: 333,+ adjustsWithInflation: true,+ }),+ ],+ captureRunDetail: 0,+ },+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ for (const row of result.runDetail!) {+ expect(row.incomeAmounts.reduce((sum, amount) => sum + amount, 0)).toBe(+ row.income,+ );+ }+ });});it('keeps every output formatter-safe under absurdly large configs', () => {diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.tsindex 3bbd8d45a6..1a155d18c5 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts@@ -2,6 +2,7 @@ import { MAX_SAFE_NUMBER } from '@actual-app/core/shared/util';import type {MonteCarloAllocationPreset,MonteCarloContributionMeta,+ MonteCarloIncomeStreamMeta,MonteCarloPotMeta,MonteCarloReturnModel,MonteCarloSpendingPhaseMeta,@@ -251,6 +252,16 @@ export type MonteCarloContribution = {annualAmount: number;/** Whether the amount rises with inflation */adjustsWithInflation: boolean;+ /**+ * Income stream the contribution is paid out of - capped at what that+ * stream pays in the year; null = money from outside the plan+ */+ sourceIncomeStreamId: string | null;+ /**+ * Whether an income-sourced contribution comes out of the stream's+ * gross before its tax is worked out (salary sacrifice)+ */+ beforeTax: boolean;};export function createMonteCarloContribution(@@ -265,6 +276,46 @@ export function createMonteCarloContribution(toAge: null,annualAmount: 1_000_000, // 10,000.00 in minor unitsadjustsWithInflation: true,+ sourceIncomeStreamId: null,+ beforeTax: false,+ };+}++/**+ * One recurring yearly income received without drawing on the pots+ * (state pension, annuity, rental, part-time work) over an age window.+ * Net of its tax it pays for the year's spending first; the pots fund+ * the rest.+ */+export type MonteCarloIncomeStream = {+ id: string;+ name: string;+ /** Age the income starts (inclusive); null = starts now */+ fromAge: number | null;+ /** Age the income stops (inclusive); null = end of plan */+ toAge: number | null;+ /** Yearly gross amount in minor units, in today's money */+ annualAmount: number;+ /** Whether the amount rises with inflation */+ adjustsWithInflation: boolean;+ /** Flat tax model: effective tax rate on the income (decimal fraction) */+ taxRate: number;+ /** Bands tax model: share of the income that counts as taxable */+ taxableFraction: number;+};++export function createMonteCarloIncomeStream(+ id: string,+): MonteCarloIncomeStream {+ return {+ id,+ name: '',+ fromAge: null,+ toAge: null,+ annualAmount: 1_000_000, // 10,000.00 in minor units+ adjustsWithInflation: true,+ taxRate: 0,+ taxableFraction: 1,};}@@ -300,6 +351,12 @@ export type MonteCarloPot = {feeAdjustsWithInflation: boolean;/** Yearly fee as a fraction of the end-of-year balance */annualFeeRate: number;+ /**+ * The plan's surplus pot: income beyond the plan's spending is saved+ * into it each year, and it is drawn on before any other pot. At most one pot+ * is flagged; none = unspent money leaves the plan.+ */+ isSurplus: boolean;};export function createMonteCarloPot(id: string): MonteCarloPot {@@ -320,9 +377,65 @@ export function createMonteCarloPot(id: string): MonteCarloPot {annualFeeFixed: 0,feeAdjustsWithInflation: false,annualFeeRate: 0,+ isSurplus: false,};}+/**+ * The pot that keeps a plan's unspent money: a cash pot starting empty,+ * immediately accessible, untaxed and fee-free+ */+export function createMonteCarloSurplusPot(id: string): MonteCarloPot {+ return {+ ...createMonteCarloPot(id),+ startingBalance: 0,+ allocationPreset: 'cash',+ allocationStocks: PRESET_ASSET_WEIGHTS.cash.stocks,+ allocationBonds: PRESET_ASSET_WEIGHTS.cash.bonds,+ allocationCash: PRESET_ASSET_WEIGHTS.cash.cash,+ expectedReturnMean: ALLOCATION_PRESETS.cash.mean,+ returnStdDev: ALLOCATION_PRESETS.cash.stdDev,+ // Already-taxed money: nothing to tax on the way out under either model+ withdrawalTaxRate: 0,+ taxableFraction: 0,+ isSurplus: true,+ };+}++/**+ * How a pot is referred to in the UI: its name, or a fallback - "Surplus+ * cash" for the surplus pot, otherwise "Pot N" numbered among the+ * ordinary pots so the surplus pot doesn't shift the numbering+ */+export function getMonteCarloPotLabel(+ pots: MonteCarloPot[],+ potIndex: number,+ translate: (key: string, options?: Record<string, unknown>) => string,+): string {+ const pot = pots[potIndex];+ if (pot.name) {+ return pot.name;+ }+ if (pot.isSurplus) {+ return translate('Surplus cash');+ }+ const ordinal = pots+ .slice(0, potIndex + 1)+ .filter(other => !other.isSurplus).length;+ return translate('Pot {{number}}', { number: ordinal });+}++/** Label for the surplus pot, whether or not the plan currently has one */+export function getMonteCarloSurplusPotLabel(+ pots: MonteCarloPot[],+ translate: (key: string, options?: Record<string, unknown>) => string,+): string {+ const surplusPotIndex = pots.findIndex(pot => pot.isSurplus);+ return surplusPotIndex >= 0+ ? getMonteCarloPotLabel(pots, surplusPotIndex, translate)+ : translate('Surplus cash');+}+/** One tax band: annual taxable income from `from` upward taxed at `rate` */export type MonteCarloTaxBand = {id: string;@@ -380,12 +493,14 @@ export type MonteCarloConfig = {returnModel: MonteCarloReturnModel;/** Dynamic withdrawal adjustment rule applied at the start of each year */withdrawalRule: MonteCarloWithdrawalRuleConfig;- /** Minimum annual withdrawal in minor units; 0 = no floor */- minimumWithdrawal: number;+ /** Minimum yearly spending in minor units (today's money); 0 = no floor */+ minimumSpending: number;/** The planned spending path; each phase runs until the next one starts */spendingPhases: MonteCarloSpendingPhase[];/** Recurring yearly contributions paid into pots */contributions: MonteCarloContribution[];+ /** Recurring yearly income that pays for spending before the pots */+ incomeStreams: MonteCarloIncomeStream[];/** Mean yearly inflation as a decimal fraction; null = flat withdrawals */inflationMean: number | null;/** Yearly inflation volatility as a decimal fraction; 0 = fixed rate */@@ -401,13 +516,17 @@ export type MonteCarloConfig = {};export const MONTE_CARLO_DEFAULTS: MonteCarloConfig = {- pots: [createMonteCarloPot('pot-1')],+ pots: [+ createMonteCarloSurplusPot('surplus-pot'),+ createMonteCarloPot('pot-1'),+ ],withdrawalStrategy: 'proportional',returnModel: 'normal',withdrawalRule: WITHDRAWAL_RULE_DEFAULTS,- minimumWithdrawal: 0,+ minimumSpending: 0,spendingPhases: [createMonteCarloSpendingPhase('phase-1')],contributions: [],+ incomeStreams: [],inflationMean: 0.025,inflationStdDev: 0.02,taxModel: 'flat',@@ -449,6 +568,7 @@ function potFromMeta(potMeta: MonteCarloPotMeta, index: number): MonteCarloPot {feeAdjustsWithInflation:potMeta.feeAdjustsWithInflation ?? defaults.feeAdjustsWithInflation,annualFeeRate: potMeta.annualFeeRate ?? defaults.annualFeeRate,+ isSurplus: potMeta.isSurplus ?? defaults.isSurplus,};}@@ -495,6 +615,29 @@ function contributionFromMeta(annualAmount: contributionMeta.annualAmount ?? defaults.annualAmount,adjustsWithInflation:contributionMeta.adjustsWithInflation ?? defaults.adjustsWithInflation,+ sourceIncomeStreamId: contributionMeta.sourceIncomeStreamId ?? null,+ beforeTax: contributionMeta.beforeTax ?? defaults.beforeTax,+ };+}++function incomeStreamFromMeta(+ incomeStreamMeta: MonteCarloIncomeStreamMeta,+ index: number,+): MonteCarloIncomeStream {+ const defaults = createMonteCarloIncomeStream(+ incomeStreamMeta.id || `income-${index + 1}`,+ );+ return {+ ...defaults,+ name: incomeStreamMeta.name ?? defaults.name,+ fromAge: incomeStreamMeta.fromAge ?? null,+ toAge: incomeStreamMeta.toAge ?? null,+ annualAmount: incomeStreamMeta.annualAmount ?? defaults.annualAmount,+ adjustsWithInflation:+ incomeStreamMeta.adjustsWithInflation ?? defaults.adjustsWithInflation,+ taxRate: incomeStreamMeta.taxRate ?? defaults.taxRate,+ taxableFraction:+ incomeStreamMeta.taxableFraction ?? defaults.taxableFraction,};}@@ -504,19 +647,22 @@ export function monteCarloConfigFromMeta(return {pots: meta?.pots?.length? meta.pots.map(potFromMeta)- : [createMonteCarloPot('pot-1')],+ : MONTE_CARLO_DEFAULTS.pots,withdrawalStrategy:meta?.withdrawalStrategy ?? MONTE_CARLO_DEFAULTS.withdrawalStrategy,returnModel: meta?.returnModel ?? MONTE_CARLO_DEFAULTS.returnModel,withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, ...meta?.withdrawalRule },- minimumWithdrawal:- meta?.minimumWithdrawal ?? MONTE_CARLO_DEFAULTS.minimumWithdrawal,+ minimumSpending:+ meta?.minimumSpending ?? MONTE_CARLO_DEFAULTS.minimumSpending,spendingPhases: meta?.spendingPhases?.length? meta.spendingPhases.map(spendingPhaseFromMeta): [createMonteCarloSpendingPhase('phase-1')],contributions: meta?.contributions?.length? meta.contributions.map(contributionFromMeta): [],+ incomeStreams: meta?.incomeStreams?.length+ ? meta.incomeStreams.map(incomeStreamFromMeta)+ : [],inflationMean:meta?.inflationMean !== undefined? meta.inflationMean@@ -605,10 +751,16 @@ export type MonteCarloRunDetailRow = {withdrawal: number;/*** The year's planned net spending: the phase schedule, inflated, after- * the withdrawal rule's adjustment but before the minimum floor and- * affordability capping+ * the withdrawal rule's adjustment and the minimum spending floor, but+ * before affordability capping*/plannedSpending: number;+ /**+ * The money that actually reached spending: net income put towards it+ * plus the withdrawal net of tax. Below plannedSpending on a shortfall+ * year, equal to it otherwise+ */+ spent: number;/** Investment gain/loss applied after the withdrawal */growth: number;endBalance: number;@@ -620,6 +772,27 @@ export type MonteCarloRunDetailRow = {/** The year's realized inflation rate as a decimal fraction; null when* inflation is disabled */inflation: number | null;+ /** Gross income received this year, across every stream */+ income: number;+ /**+ * Gross income from each configured stream, in the order the streams+ * are configured (zero outside its age window)+ */+ incomeAmounts: number[];+ /** Tax paid on this year's income (0 with no tax model) */+ incomeTax: number;+ /**+ * Net income left after sourced contributions and the year's planned+ * spending (0 when the income was fully used). Saved into the surplus+ * pot when the plan has one, otherwise it leaves the plan+ */+ unspentIncome: number;+ /**+ * Unspent income saved into the surplus pot this year. Part of the+ * balance chain: start + contributions + surplusSaved - withdrawal ++ * growth - fees = end. 0 without a surplus pot+ */+ surplusSaved: number;/** Contributions paid in at the start of this year */contributions: number;/** Contribution each pot received at the start of the year, same order */@@ -659,7 +832,7 @@ export type MonteCarloRunDetailRow = {* first spending year). Amounts are deflated like the row's totals.*/ruleExplanation?: MonteCarloRuleExplanation;- /** True when the minimum withdrawal raised the final amount */+ /** True when the minimum spending floor lifted this year's plan */minimumApplied?: boolean;/*** Set on a failure year when money remained in pots that hadn't reached@@ -820,7 +993,16 @@ export function rankSimulationsWorstFirst(export function runMonteCarloSimulation(params: MonteCarloParams,): MonteCarloResult {- const pots = params.pots.length > 0 ? params.pots : MONTE_CARLO_DEFAULTS.pots;+ // The surplus pot's semantics are fixed - empty to start, cash,+ // immediately accessible, untaxed, fee-free - whatever the stored meta+ // says, so it can only ever hold what the plan didn't spend+ const pots = (+ params.pots.length > 0 ? params.pots : MONTE_CARLO_DEFAULTS.pots+ ).map(pot =>+ pot.isSurplus+ ? { ...createMonteCarloSurplusPot(pot.id), name: pot.name }+ : pot,+ );const potCount = pots.length;const potStartBalances = pots.map(pot =>clamp(pot.startingBalance, 0, MAX_AMOUNT),@@ -876,6 +1058,23 @@ export function runMonteCarloSimulation(potTaxableFractions.some(fraction => fraction > 0): potTaxRates.some(rate => rate > 0);+ // Income streams are taxed the same two ways as pots. Under the bands+ // model their taxable income fills the lower bands first, so the year's+ // pot withdrawals are taxed at the marginal rate above it.+ const incomeStreams = params.incomeStreams;+ const incomeCount = incomeStreams.length;+ const incomeTaxRates = incomeStreams.map(incomeStream =>+ clamp(incomeStream.taxRate, 0, MAX_WITHDRAWAL_TAX_RATE),+ );+ const incomeTaxableFractions = incomeStreams.map(incomeStream =>+ clamp(incomeStream.taxableFraction, 0, 1),+ );+ const hasIncomeTax =+ taxModel === 'bands'+ ? taxBands.some(band => band.rate > 0) &&+ incomeTaxableFractions.some(fraction => fraction > 0)+ : incomeTaxRates.some(rate => rate > 0);+// --- Fees --------------------------------------------------------------const potFeeFixed = pots.map(pot =>clamp(pot.annualFeeFixed ?? 0, 0, MAX_AMOUNT),@@ -915,8 +1114,13 @@ export function runMonteCarloSimulation(// Tax due on the takes currently in potTakes. Band thresholds are in// today's money, so taxable income is deflated by the replay's inflation- // path before banding (thresholds effectively rise with inflation)- function taxForTakes(cumulativeInflationNow: number) {+ // path before banding (thresholds effectively rise with inflation).+ // Under the bands model the year's income has already used up the+ // lower bands, so the takes are taxed as the slice above it.+ function taxForTakes(+ cumulativeInflationNow: number,+ taxableIncomeBase: number,+ ) {if (!hasTax) {return 0;}@@ -931,7 +1135,12 @@ export function runMonteCarloSimulation(for (let potIndex = 0; potIndex < potCount; potIndex++) {taxable += potTakes[potIndex] * potTaxableFractions[potIndex];}- return bandTax(taxable / cumulativeInflationNow) * cumulativeInflationNow;+ const baseToday = taxableIncomeBase / cumulativeInflationNow;+ return (+ (bandTax(baseToday + taxable / cumulativeInflationNow) -+ bandTax(baseToday)) *+ cumulativeInflationNow+ );}// The slice of each pot's take (currently in potTakes) that was assessed@@ -975,19 +1184,50 @@ export function runMonteCarloSimulation(}}- // Split a gross withdrawal across pots per the configured order, without- // mutating balances; writes each pot's take into potTakes. Mirrors the- // strategies' semantics exactly (same arithmetic as the pre-tax split).+ // The plan's surplus pot, if it has one: unspent money is saved into it+ // and it is drawn on before any other pot+ const surplusPotIndex = pots.findIndex(pot => pot.isSurplus);++ // Whether the withdrawal strategy may draw on a pot this year: it has+ // unlocked, and it isn't the surplus pot (which is always drawn first,+ // ahead of every strategy)+ function canDrain(potIndex: number, year: number) {+ return year >= potAccessFromYear[potIndex] && potIndex !== surplusPotIndex;+ }++ // Split a gross withdrawal across pots, without mutating balances;+ // writes each pot's take into potTakes. The surplus pot goes first,+ // then the configured strategy splits the rest across the other pots.function computeTakes(grossTotal: number,year: number,accessibleTotal: number,- lastAccessibleIndex: number,) {potTakes.fill(0);if (grossTotal <= 0 || accessibleTotal <= 0) {return;}+ let remainingGross = grossTotal;+ let remainingAccessible = accessibleTotal;+ if (surplusPotIndex !== -1 && year >= potAccessFromYear[surplusPotIndex]) {+ const take = Math.min(potBalances[surplusPotIndex], remainingGross);+ potTakes[surplusPotIndex] = take;+ remainingGross -= take;+ remainingAccessible -= potBalances[surplusPotIndex];+ }+ if (remainingGross > 0 && remainingAccessible > 0) {+ splitAcrossPots(remainingGross, year, remainingAccessible);+ }+ }++ // The configured strategy's split of a gross amount across the pots it+ // may draw on. Mirrors the strategies' semantics exactly (same+ // arithmetic as the pre-tax split).+ function splitAcrossPots(+ grossTotal: number,+ year: number,+ accessibleTotal: number,+ ) {if (isSequential || isBestPerformer) {if (isBestPerformer) {// Drain the pot with the highest return last year first; ties@@ -1007,7 +1247,7 @@ export function runMonteCarloSimulation(orderIndex++) {const potIndex = isBestPerformer ? drainOrder[orderIndex] : orderIndex;- if (year < potAccessFromYear[potIndex]) {+ if (!canDrain(potIndex, year)) {continue;}const take = Math.min(potBalances[potIndex], remaining);@@ -1022,7 +1262,7 @@ export function runMonteCarloSimulation(// comes from overweight pots, most overweight firstlet targetAccessible = 0;for (let potIndex = 0; potIndex < potCount; potIndex++) {- if (year >= potAccessFromYear[potIndex]) {+ if (canDrain(potIndex, year)) {targetAccessible += potStartBalances[potIndex];}}@@ -1030,7 +1270,7 @@ export function runMonteCarloSimulation(for (let potIndex = 0; potIndex < potCount; potIndex++) {drainOrder[potIndex] = potIndex;potIdealBalances[potIndex] =- year >= potAccessFromYear[potIndex] && targetAccessible > 0+ canDrain(potIndex, year) && targetAccessible > 0? (potStartBalances[potIndex] / targetAccessible) * remainingTotal: 0;}@@ -1047,7 +1287,7 @@ export function runMonteCarloSimulation(orderIndex++) {const potIndex = drainOrder[orderIndex];- if (year < potAccessFromYear[potIndex]) {+ if (!canDrain(potIndex, year)) {continue;}const excess = potBalances[potIndex] - potIdealBalances[potIndex];@@ -1061,7 +1301,7 @@ export function runMonteCarloSimulation(// Float-drift safety net: drain any accessible pot for whatever// tiny residue the excess passes left behindfor (let potIndex = 0; potIndex < potCount && remaining > 0; potIndex++) {- if (year < potAccessFromYear[potIndex]) {+ if (!canDrain(potIndex, year)) {continue;}const take = Math.min(@@ -1072,20 +1312,26 @@ export function runMonteCarloSimulation(remaining -= take;}} else {- // Proportional split across accessible pots; the last accessible- // pot takes the remainder so the total drops by exactly the- // withdrawal (no float drift)+ // Proportional split across the pots in play; the last of them+ // takes the remainder so the total drops by exactly the withdrawal+ // (no float drift)+ let lastDrainableIndex = -1;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ if (canDrain(potIndex, year)) {+ lastDrainableIndex = potIndex;+ }+ }let remaining = grossTotal;- for (let potIndex = 0; potIndex < lastAccessibleIndex; potIndex++) {- if (year < potAccessFromYear[potIndex]) {+ for (let potIndex = 0; potIndex < lastDrainableIndex; potIndex++) {+ if (!canDrain(potIndex, year)) {continue;}const take = grossTotal * (potBalances[potIndex] / accessibleTotal);potTakes[potIndex] = take;remaining -= take;}- if (lastAccessibleIndex >= 0) {- potTakes[lastAccessibleIndex] = remaining;+ if (lastDrainableIndex >= 0) {+ potTakes[lastDrainableIndex] = remaining;}}}@@ -1147,71 +1393,216 @@ export function runMonteCarloSimulation();}- // The first year with planned spending - withdrawal rules anchor here- // and only adjust from here on, so zero-spend years (accumulation- // before retirement) neither trigger nor drift them- let firstSpendingYear = Infinity;- for (let year = 1; year <= horizonYears; year++) {- if (plannedTodayByYear[year] > 0) {- firstSpendingYear = year;- break;+ // Scheduled amounts per year in today's money - split into an+ // inflation-adjusted and a flat portion so a year's amount is+ // flat + adjusted × cumulativeInflation. Deterministic and shared by+ // every replay. One array per year for contributions (indexed by+ // configured contribution) and for income streams (indexed by stream).+ function scheduleByYear(+ items: Array<{+ fromAge: number | null;+ toAge: number | null;+ annualAmount: number;+ adjustsWithInflation: boolean;+ }>,+ ) {+ const flatByYear: Float64Array[] = [];+ const adjustedByYear: Float64Array[] = [];+ for (let year = 0; year <= horizonYears; year++) {+ flatByYear.push(new Float64Array(items.length));+ adjustedByYear.push(new Float64Array(items.length));}+ items.forEach((item, itemIndex) => {+ const amount = clamp(item.annualAmount, 0, MAX_AMOUNT);+ for (let year = 1; year <= horizonYears; year++) {+ const age = params.currentAge + year - 1;+ if (item.fromAge != null && age < item.fromAge) {+ continue;+ }+ if (item.toAge != null && age > item.toAge) {+ continue;+ }+ const target = item.adjustsWithInflation ? adjustedByYear : flatByYear;+ target[year][itemIndex] = amount;+ }+ });+ return { flatByYear, adjustedByYear };}- // Planned contributions per year, in today's money - split into an- // inflation-adjusted and a flat portion so a year's deposit is- // flat + adjusted × cumulativeInflation. Deterministic and shared by- // every replay. Kept per pot (what the simulation deposits) and per- // contribution (what the captured run reports, so the cashflow chart- // can split deposits by source). Contributions into unknown pots (e.g.- // a pot that was deleted) are ignored.+ // Contributions into unknown pots (e.g. a pot that was deleted) or out+ // of unknown income streams are ignoredconst contributionCount = params.contributions.length;- const flatContributionsByYear: Float64Array[] = [];- const adjustedContributionsByYear: Float64Array[] = [];- const flatContributionAmountsByYear: Float64Array[] = [];- const adjustedContributionAmountsByYear: Float64Array[] = [];- for (let year = 0; year <= horizonYears; year++) {- flatContributionsByYear.push(new Float64Array(potCount));- adjustedContributionsByYear.push(new Float64Array(potCount));- flatContributionAmountsByYear.push(new Float64Array(contributionCount));- adjustedContributionAmountsByYear.push(new Float64Array(contributionCount));- }- // While deposits are still to come, an empty pot isn't a dead plan -- // depletion is only declared after the final contribution year- let lastContributionYear = 0;- let hasContributions = false;- for (- let contributionIndex = 0;- contributionIndex < contributionCount;- contributionIndex+++ const contributionPotIndex = params.contributions.map(contribution =>+ pots.findIndex(pot => pot.id === contribution.potId),+ );+ const contributionSourceIndex = params.contributions.map(contribution =>+ contribution.sourceIncomeStreamId == null+ ? -1+ : incomeStreams.findIndex(+ incomeStream => incomeStream.id === contribution.sourceIncomeStreamId,+ ),+ );+ const contributionBeforeTax = params.contributions.map(+ contribution => contribution.beforeTax,+ );+ const contributionSchedule = scheduleByYear(+ params.contributions.map((contribution, contributionIndex) =>+ contributionPotIndex[contributionIndex] === -1 ||+ (contribution.sourceIncomeStreamId != null &&+ contributionSourceIndex[contributionIndex] === -1)+ ? { ...contribution, annualAmount: 0 }+ : contribution,+ ),+ );+ const hasContributions = contributionSchedule.flatByYear.some(+ (flat, year) =>+ flat.some(amount => amount > 0) ||+ contributionSchedule.adjustedByYear[year].some(amount => amount > 0),+ );+ const incomeSchedule = scheduleByYear(incomeStreams);++ // Scratch space for settleYearFlows: the year's realized amount per+ // contribution and gross income per stream (reused across every+ // simulated year to avoid allocating in the hot loop)+ const yearContributionAmounts = new Float64Array(contributionCount);+ const yearIncomeGross = new Float64Array(incomeCount);+ const yearIncomeRemaining = new Float64Array(incomeCount);++ /**+ * Settles a year's income and contributions at the given price level,+ * filling yearContributionAmounts and yearIncomeGross:+ * 1. each stream's gross for the year;+ * 2. before-tax contributions come out of their stream's gross+ * (capped at it) - salary sacrifice;+ * 3. each stream is taxed on what's left;+ * 4. after-tax contributions come out of their stream's net (capped);+ * 5. what remains of the income is spendable.+ * Contributions from outside the plan are paid in full. Sourced+ * contributions are settled in configured order when several draw on+ * one stream.+ */+ function settleYearFlows(+ year: number,+ cumulativeInflationNow: number,+ withContributions: boolean,) {- const contribution = params.contributions[contributionIndex];- const potIndex = pots.findIndex(pot => pot.id === contribution.potId);- const amount = clamp(contribution.annualAmount, 0, MAX_AMOUNT);- if (potIndex === -1 || amount <= 0) {- continue;+ const flatIncome = incomeSchedule.flatByYear[year];+ const adjustedIncome = incomeSchedule.adjustedByYear[year];+ let grossIncome = 0;+ for (let incomeIndex = 0; incomeIndex < incomeCount; incomeIndex++) {+ const gross =+ flatIncome[incomeIndex] ++ adjustedIncome[incomeIndex] * cumulativeInflationNow;+ yearIncomeGross[incomeIndex] = gross;+ yearIncomeRemaining[incomeIndex] = gross;+ grossIncome += gross;}- for (let year = 1; year <= horizonYears; year++) {- const age = params.currentAge + year - 1;- if (contribution.fromAge != null && age < contribution.fromAge) {- continue;++ const flatContributions = contributionSchedule.flatByYear[year];+ const adjustedContributions = contributionSchedule.adjustedByYear[year];+ yearContributionAmounts.fill(0);+ if (withContributions) {+ for (+ let contributionIndex = 0;+ contributionIndex < contributionCount;+ contributionIndex+++ ) {+ const scheduled =+ flatContributions[contributionIndex] ++ adjustedContributions[contributionIndex] * cumulativeInflationNow;+ const sourceIndex = contributionSourceIndex[contributionIndex];+ if (sourceIndex === -1) {+ yearContributionAmounts[contributionIndex] = scheduled;+ } else if (contributionBeforeTax[contributionIndex]) {+ const amount = Math.min(scheduled, yearIncomeRemaining[sourceIndex]);+ yearIncomeRemaining[sourceIndex] -= amount;+ yearContributionAmounts[contributionIndex] = amount;+ }}- if (contribution.toAge != null && age > contribution.toAge) {- continue;+ }++ // Tax each stream on its gross after before-tax deductions; under+ // the bands model the pooled taxable income is banded once and the+ // tax shared out in proportion to each stream's taxable share+ let incomeTax = 0;+ let taxableIncomeBase = 0;+ if (hasIncomeTax && taxModel === 'flat') {+ for (let incomeIndex = 0; incomeIndex < incomeCount; incomeIndex++) {+ const tax =+ yearIncomeRemaining[incomeIndex] * incomeTaxRates[incomeIndex];+ yearIncomeRemaining[incomeIndex] -= tax;+ incomeTax += tax;}- const byPot = contribution.adjustsWithInflation- ? adjustedContributionsByYear- : flatContributionsByYear;- const byContribution = contribution.adjustsWithInflation- ? adjustedContributionAmountsByYear- : flatContributionAmountsByYear;- byPot[year][potIndex] += amount;- byContribution[year][contributionIndex] = amount;- hasContributions = true;- if (year > lastContributionYear) {- lastContributionYear = year;+ } else if (taxModel === 'bands') {+ for (let incomeIndex = 0; incomeIndex < incomeCount; incomeIndex++) {+ taxableIncomeBase +=+ yearIncomeRemaining[incomeIndex] *+ incomeTaxableFractions[incomeIndex];+ }+ if (hasIncomeTax && taxableIncomeBase > 0) {+ incomeTax =+ bandTax(taxableIncomeBase / cumulativeInflationNow) *+ cumulativeInflationNow;+ for (let incomeIndex = 0; incomeIndex < incomeCount; incomeIndex++) {+ yearIncomeRemaining[incomeIndex] -=+ incomeTax *+ ((yearIncomeRemaining[incomeIndex] *+ incomeTaxableFractions[incomeIndex]) /+ taxableIncomeBase);+ }+ }+ }++ if (withContributions) {+ for (+ let contributionIndex = 0;+ contributionIndex < contributionCount;+ contributionIndex+++ ) {+ const sourceIndex = contributionSourceIndex[contributionIndex];+ if (sourceIndex === -1 || contributionBeforeTax[contributionIndex]) {+ continue;+ }+ const scheduled =+ flatContributions[contributionIndex] ++ adjustedContributions[contributionIndex] * cumulativeInflationNow;+ const amount = Math.min(scheduled, yearIncomeRemaining[sourceIndex]);+ yearIncomeRemaining[sourceIndex] -= amount;+ yearContributionAmounts[contributionIndex] = amount;}}++ let spendableIncome = 0;+ for (let incomeIndex = 0; incomeIndex < incomeCount; incomeIndex++) {+ spendableIncome += yearIncomeRemaining[incomeIndex];+ }+ return { grossIncome, incomeTax, taxableIncomeBase, spendableIncome };+ }++ // The part of each year's planned spending the pots have to fund, in+ // today's money, after the income the year brings in. Withdrawal rules+ // anchor and measure against this path - they manage what the portfolio+ // pays out, not spending the income already covers. (An anchor at+ // today's prices; the in-year requirement uses the realized amounts.)+ const potFundedPlannedTodayByYear = new Float64Array(horizonYears + 1);+ for (let year = 1; year <= horizonYears; year++) {+ const { spendableIncome } = settleYearFlows(year, 1, true);+ potFundedPlannedTodayByYear[year] = Math.max(+ 0,+ plannedTodayByYear[year] - spendableIncome,+ );+ }++ // The first year the pots fund spending - withdrawal rules anchor here+ // and only adjust from here on, so years with nothing to withdraw+ // (accumulation before retirement, or income covering everything)+ // neither trigger nor drift them+ let firstSpendingYear = Infinity;+ for (let year = 1; year <= horizonYears; year++) {+ if (potFundedPlannedTodayByYear[year] > 0) {+ firstSpendingYear = year;+ break;+ }}// When showing values in today's money, outputs are discounted by each@@ -1253,7 +1644,7 @@ export function runMonteCarloSimulation(const potBalances = new Float64Array(potCount);const rule = params.withdrawalRule;- const minimumWithdrawal = clamp(params.minimumWithdrawal, 0, MAX_AMOUNT);+ const minimumSpending = clamp(params.minimumSpending, 0, MAX_AMOUNT);// Keep every emitted amount within the range the formatter accepts -// absurd configs flat-line at the cap instead of crashing the report.@@ -1313,12 +1704,18 @@ export function runMonteCarloSimulation(for (let year = 1; year <= horizonYears; year++) {if (!depleted) {const startDeflator = deflate ? 1 / cumulativeInflation : 1;- const planned = plannedTodayByYear[year] * cumulativeInflation;- // Contributions land at the start of the year, before the- // withdrawal: new money can fund this year's spending and earns- // this year's return. Locked pots receive deposits too - the- // access age only gates withdrawals.+ // The year's income arrives and its contributions are settled+ // (see settleYearFlows), then the deposits land in the pots at the+ // start of the year, before the withdrawal: new money can fund+ // this year's spending and earns this year's return. Locked pots+ // receive deposits too - the access age only gates withdrawals.+ const {+ grossIncome: grossIncomeThisYear,+ incomeTax: incomeTaxThisYear,+ taxableIncomeBase,+ spendableIncome,+ } = settleYearFlows(year, cumulativeInflation, true);let contributionsThisYear = 0;let preContributionPotBalances: number[] | null = null;// Always sized to the pots when capturing, like the other per-pot@@ -1328,48 +1725,44 @@ export function runMonteCarloSimulation(runDetail && simulationIndex === captureIndex? new Array<number>(potCount).fill(0): null;- // One entry per configured contribution, so the cashflow chart can- // split the year's deposits by their source- const capturedContributionAmounts = capturedPotContributions- ? new Array<number>(contributionCount).fill(0)- : null;if (hasContributions) {if (capturedPotContributions) {// The drill-in shows contributions as their own step, so its// Start balance column needs the pre-contribution snapshotpreContributionPotBalances = Array.from(potBalances);}- if (capturedContributionAmounts) {- // The same deposits as the per-pot loop below, grouped by- // source instead of by pot- const flatAmounts = flatContributionAmountsByYear[year];- const adjustedAmounts = adjustedContributionAmountsByYear[year];- for (- let contributionIndex = 0;- contributionIndex < contributionCount;- contributionIndex++- ) {- capturedContributionAmounts[contributionIndex] =- flatAmounts[contributionIndex] +- adjustedAmounts[contributionIndex] * cumulativeInflation;- }- }- const flatContributions = flatContributionsByYear[year];- const adjustedContributions = adjustedContributionsByYear[year];- for (let potIndex = 0; potIndex < potCount; potIndex++) {- const deposit =- flatContributions[potIndex] +- adjustedContributions[potIndex] * cumulativeInflation;+ for (+ let contributionIndex = 0;+ contributionIndex < contributionCount;+ contributionIndex+++ ) {+ const deposit = yearContributionAmounts[contributionIndex];if (deposit > 0) {+ const potIndex = contributionPotIndex[contributionIndex];potBalances[potIndex] += deposit;total += deposit;contributionsThisYear += deposit;if (capturedPotContributions) {- capturedPotContributions[potIndex] = deposit;+ capturedPotContributions[potIndex] += deposit;}}}}+ // One entry per configured contribution, so the cashflow chart can+ // split the year's deposits by their source+ const capturedContributionAmounts = capturedPotContributions+ ? Array.from(yearContributionAmounts)+ : null;++ // Income pays for the year's spending first; the pots fund only+ // the rest. Everything below - the withdrawal rule, the minimum+ // floor, the requirement the pots must meet - works on that+ // pot-funded plan. Income beyond the plan is unspent: it leaves+ // the model (route it into a pot with a contribution if wanted)+ const totalPlanned = plannedTodayByYear[year] * cumulativeInflation;+ const incomeTowardsSpending = Math.min(spendableIncome, totalPlanned);+ const planned = totalPlanned - incomeTowardsSpending;+ const unspentIncome = spendableIncome - incomeTowardsSpending;// Every pot experiences the same market year: historical models// pick one history year for all pots (normally-drawn pots share// one market shock scaled by their own volatility), and the same@@ -1387,11 +1780,9 @@ export function runMonteCarloSimulation(// Only pots that have reached their access age can fund this year's// withdrawal; locked pots stay invested but untouchablelet accessibleTotal = 0;- let lastAccessibleIndex = -1;for (let potIndex = 0; potIndex < potCount; potIndex++) {if (year >= potAccessFromYear[potIndex]) {accessibleTotal += potBalances[potIndex];- lastAccessibleIndex = potIndex;}}@@ -1463,7 +1854,7 @@ export function runMonteCarloSimulation(// read as a trigger - only market-driven drift does.// Identical to the year-1 anchor for single-phase plans.const referenceRate =- plannedTodayByYear[year] / accessibleStartByYear[year];+ potFundedPlannedTodayByYear[year] / accessibleStartByYear[year];if (currentRate >referenceRate * (1 + rule.preservationTriggerPct)@@ -1519,7 +1910,8 @@ export function runMonteCarloSimulation(rule.type === 'boundaries') && { currentRate }),...(rule.type === 'guardrails' && {referenceRate:- plannedTodayByYear[year] / accessibleStartByYear[year],+ potFundedPlannedTodayByYear[year] /+ accessibleStartByYear[year],}),...(rule.type === 'ratcheting' &&ruleAction === 'none' && { ratchetStreak }),@@ -1528,32 +1920,37 @@ export function runMonteCarloSimulation(}withdrawal = planned * adjustmentFactor;}- // The year's planned net spending: the phase schedule, inflated,- // after the withdrawal rule's adjustment but before the minimum- // floor and before affordability capping. The cashflow chart plots- // it against the actual withdrawal so surpluses and shortfalls- // stand out- const plannedSpendingThisYear = withdrawal;-- // The minimum floor belongs to the withdrawal rule system (the UI+ // The minimum spending floor belongs to the withdrawal rule system (the UI// only offers it alongside a rule); with no rule active the planned// spending is taken as-is. It guards against rule-driven cuts, so// it only applies in years with planned spending - a deliberate// zero-spend phase takes nothing. Like the phase amounts it's in- // today's money, so it rises with this replay's inflation path- const minimumThisYear = minimumWithdrawal * cumulativeInflation;+ // today's money, so it rises with this replay's inflation path.+ // It is a floor on spending, so income counts towards it and the+ // pots only top the year up to it+ const minimumThisYear = minimumSpending * cumulativeInflation;+ const minimumFromPots = Math.max(+ 0,+ minimumThisYear - incomeTowardsSpending,+ );if (rule.type !== 'none' &&- minimumWithdrawal > 0 &&+ minimumSpending > 0 &&planned > 0 &&- withdrawal < minimumThisYear+ withdrawal < minimumFromPots) {- withdrawal = minimumThisYear;+ withdrawal = minimumFromPots;if (isCapturedRun) {capturedMinimumApplied = true;}}+ // The year's planned net spending: the part income covers plus the+ // pot-funded part after the withdrawal rule's adjustment and the+ // spending floor, before affordability capping. The cashflow chart+ // plots it against the actual flows so shortfalls stand out+ const plannedSpendingThisYear = incomeTowardsSpending + withdrawal;+const yearStartTotal = total;// The spending requirement is net of tax; withdrawalTaken is the// gross that leaves the pots to deliver it@@ -1561,6 +1958,8 @@ export function runMonteCarloSimulation(let withdrawalTaken: number;let netDelivered: number;let fundingShortfall = false;+ // Unspent money saved into the surplus pot this year (0 without one)+ let surplusSavedThisYear = 0;// Per-pot balances at the point of failure: accessible pots are// consumed, locked pots keep their money@@ -1595,20 +1994,18 @@ export function runMonteCarloSimulation(// the plan funds this yearlet accessibleNetCapacity = accessibleTotal;if (hasTax && accessibleTotal * minNetFactor <= netRequired) {- computeTakes(- accessibleTotal,- year,- accessibleTotal,- lastAccessibleIndex,- );+ computeTakes(accessibleTotal, year, accessibleTotal);accessibleNetCapacity =- accessibleTotal - taxForTakes(cumulativeInflation);+ accessibleTotal -+ taxForTakes(cumulativeInflation, taxableIncomeBase);}// A shortfall needs an actual requirement: a zero-spend year with// nothing accessible (e.g. before delayed contributions start, or- // while every pot is still locked) is not a failure- if (netRequired > 0 && accessibleNetCapacity <= netRequired) {+ // while every pot is still locked) is not a failure. Exactly enough+ // is enough - a pot emptied to the penny funded the year, and next+ // year's income or contributions may refill it+ if (netRequired > 0 && accessibleNetCapacity < netRequired) {fundingShortfall = true;// The accessible pots can't cover this year's spending (locked// pots may still hold money, but the plan failed to fund it);@@ -1654,13 +2051,10 @@ export function runMonteCarloSimulation(let grossTotal = netRequired;if (hasTax) {for (let iteration = 0; iteration < 40; iteration++) {- computeTakes(- grossTotal,- year,- accessibleTotal,- lastAccessibleIndex,- );- const next = netRequired + taxForTakes(cumulativeInflation);+ computeTakes(grossTotal, year, accessibleTotal);+ const next =+ netRequired ++ taxForTakes(cumulativeInflation, taxableIncomeBase);if (Math.abs(next - grossTotal) <= 1e-7 * Math.max(1, next)) {grossTotal = next;break;@@ -1670,7 +2064,7 @@ export function runMonteCarloSimulation(grossTotal = Math.min(grossTotal, accessibleTotal);}- computeTakes(grossTotal, year, accessibleTotal, lastAccessibleIndex);+ computeTakes(grossTotal, year, accessibleTotal);for (let potIndex = 0; potIndex < potCount; potIndex++) {potBalances[potIndex] -= potTakes[potIndex];}@@ -1692,6 +2086,14 @@ export function runMonteCarloSimulation(captureTaxables(capturedPotTaxables);}+ // Income the plan didn't need is saved into the surplus pot+ // before growth, like a contribution. Without a surplus pot it+ // leaves the plan.+ if (surplusPotIndex !== -1) {+ surplusSavedThisYear = unspentIncome;+ potBalances[surplusPotIndex] += surplusSavedThisYear;+ }+const marketShock = hasNormalDrawPot ? nextNormal() : 0;total = 0;@@ -1714,17 +2116,9 @@ export function runMonteCarloSimulation(}total += potBalances[potIndex];}- if (total <= 0) {- total = 0;- // An empty balance with deposits still to come isn't a dead- // plan - future contributions re-seed the pots. This year's- // deposits have already landed, so >= is the right bound.- if (year >= lastContributionYear) {- depleted = true;- simulationDepletionYear = year;- depletionCounts[year]++;- }- }+ // Empty pots are not a failure in themselves: the plan only+ // fails in a year whose spending can't be funded (the shortfall+ // above). Future contributions or income may still carry it.}// Realize this year's inflation. Historical models take the@@ -1768,15 +2162,6 @@ export function runMonteCarloSimulation(for (let potIndex = 0; potIndex < potCount; potIndex++) {total += potBalances[potIndex];}- if (total <= 0) {- total = 0;- // Same future-deposits guard as the post-growth check- if (year >= lastContributionYear) {- depleted = true;- simulationDepletionYear = year;- depletionCounts[year]++;- }- }}const endDeflator = deflate ? 1 / cumulativeInflation : 1;@@ -1833,16 +2218,23 @@ export function runMonteCarloSimulation(const contributions = emit(contributionsThisYear, startDeflator);const withdrawal = emit(withdrawalTaken, startDeflator);const taxPaid = emit(withdrawalTaken - netDelivered, startDeflator);+ const income = emit(grossIncomeThisYear, startDeflator);const base = {year,startBalance,plannedSpending: emit(plannedSpendingThisYear, startDeflator),+ spent: emit(incomeTowardsSpending + netDelivered, startDeflator),...(capturedRuleExplanation != null && {ruleExplanation: capturedRuleExplanation,}),...(capturedMinimumApplied && { minimumApplied: true }),// A rate, not an amount - passed through undeflatedinflation: yearInflationRate,+ income,+ incomeAmounts: emitParts(yearIncomeGross, startDeflator, income),+ incomeTax: emit(incomeTaxThisYear, startDeflator),+ unspentIncome: emit(unspentIncome, startDeflator),+ surplusSaved: emit(surplusSavedThisYear, startDeflator),contributions,potContributions: emitParts(capturedPotContributions,@@ -1904,7 +2296,8 @@ export function runMonteCarloSimulation(growth: toSafeAmount(Math.round((total + feesThisYear) * endDeflator -- (yearStartTotal - withdrawalTaken) * startDeflator,+ (yearStartTotal - withdrawalTaken + surplusSavedThisYear) *+ startDeflator,),),feesPaid,@@ -1928,29 +2321,51 @@ export function runMonteCarloSimulation(// Capture-only: chart the plan's unfunded tail. Nothing moves// and no RNG is drawn (adding draws here would shift the stream// and change results), so cumulativeInflation stays frozen at- // the failure year's level and plannedSpending is priced there.- // The withdrawal rule's running adjustment persists too, so the- // tail continues the funded years' plan rather than jumping- // back to the unadjusted schedule (a no-op for rules without one)+ // the failure year's level and amounts are priced there. Income+ // keeps arriving and still covers what it can; the withdrawal+ // rule's running adjustment persists on the pot-funded part, so+ // the tail continues the funded years' plan rather than jumping+ // back to the unadjusted schedule (a no-op for rules without one).+ // Contributions stop - there is no live plan to pay into.const frozenDeflator = deflate ? 1 / cumulativeInflation : 1;+ const emitFrozen = (value: number) =>+ toSafeAmount(Math.round(value * frozenDeflator));+ const {+ grossIncome: tailGrossIncome,+ incomeTax: tailIncomeTax,+ spendableIncome: tailSpendableIncome,+ } = settleYearFlows(year, cumulativeInflation, false);+ const tailTotalPlanned = plannedTodayByYear[year] * cumulativeInflation;+ const tailIncomeTowardsSpending = Math.min(+ tailSpendableIncome,+ tailTotalPlanned,+ );+ const tailIncome = emitFrozen(tailGrossIncome);runDetail.push({year,afterDepletion: true,startBalance: 0,- plannedSpending: toSafeAmount(- Math.round(- plannedTodayByYear[year] *- adjustmentFactor *- cumulativeInflation *- frozenDeflator,- ),+ plannedSpending: emitFrozen(+ tailIncomeTowardsSpending ++ (tailTotalPlanned - tailIncomeTowardsSpending) * adjustmentFactor,),+ // Only the income still reaches spending once the pots are gone+ spent: emitFrozen(tailIncomeTowardsSpending),withdrawal: 0,growth: 0,endBalance: 0,potBalances: new Array<number>(potCount).fill(0),potStartBalances: new Array<number>(potCount).fill(0),inflation: null,+ income: tailIncome,+ incomeAmounts: Array.from(yearIncomeGross, gross =>+ emitFrozen(gross),+ ),+ incomeTax: emitFrozen(tailIncomeTax),+ unspentIncome: emitFrozen(+ tailSpendableIncome - tailIncomeTowardsSpending,+ ),+ surplusSaved: 0,contributions: 0,potContributions: new Array<number>(potCount).fill(0),contributionAmounts: new Array<number>(contributionCount).fill(0),diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloYearStory.test.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloYearStory.test.tsnew file mode 100644index 0000000000..043170d87b--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloYearStory.test.ts@@ -0,0 +1,292 @@+import type { TFunction } from 'i18next';+import { describe, expect, it } from 'vitest';++import { WITHDRAWAL_RULE_DEFAULTS } from './monteCarloSimulation';+import type { MonteCarloRunDetailRow } from './monteCarloSimulation';+import { buildMonteCarloYearStory } from './monteCarloYearStory';++// Identity translation that fills in the placeholders, so the tests read+// the English sentences the UI shows+const translate = ((key: string, options?: Record<string, unknown>) =>+ key.replace(/\{\{(\w+)\}\}/g, (_match, name: string) =>+ String(options?.[name]),+ )) as unknown as TFunction;++const format = (amount: number) => amount.toFixed(2);++function makeRow(+ overrides: Partial<MonteCarloRunDetailRow> = {},+): MonteCarloRunDetailRow {+ return {+ year: 1,+ startBalance: 100_000,+ withdrawal: 4_000,+ plannedSpending: 4_000,+ spent: 4_000,+ growth: 0,+ endBalance: 96_000,+ potBalances: [96_000],+ potStartBalances: [100_000],+ inflation: null,+ income: 0,+ incomeAmounts: [],+ incomeTax: 0,+ unspentIncome: 0,+ surplusSaved: 0,+ contributions: 0,+ potContributions: [0],+ contributionAmounts: [],+ potWithdrawals: [4_000],+ potTaxes: [0],+ potTaxables: [0],+ taxPaid: 0,+ feesPaid: 0,+ potFees: [0],+ potReturns: [0],+ ...overrides,+ };+}++function story(+ row: MonteCarloRunDetailRow,+ options: {+ hasSurplusPot?: boolean;+ withdrawalRule?: typeof WITHDRAWAL_RULE_DEFAULTS;+ } = {},+) {+ return buildMonteCarloYearStory({+ row,+ withdrawalRule: options.withdrawalRule ?? WITHDRAWAL_RULE_DEFAULTS,+ surplusPotName: 'Surplus cash',+ hasSurplusPot: options.hasSurplusPot ?? false,+ format,+ translate,+ });+}++describe('buildMonteCarloYearStory', () => {+ it('chains a guardrails cut and the spending floor that overrode it', () => {+ // The screenshot year: 40,000 planned, cut by 25% to 16,875, then+ // lifted to the 20,000 minimum spending+ const row = makeRow({+ withdrawal: 20_000,+ plannedSpending: 20_000,+ spent: 20_000,+ minimumApplied: true,+ ruleExplanation: {+ kind: 'factor',+ rule: 'guardrails',+ factor: 0.75,+ planned: 40_000,+ adjusted: 16_875,+ action: 'cut',+ currentRate: 0.082,+ referenceRate: 0.0714,+ },+ });+ expect(story(row, { hasSurplusPot: true })).toEqual([+ "Guardrails cut this year's spending from 40000.00 to 16875.00 because the withdrawal rate had climbed too far above the plan.",+ 'The minimum spending floor then lifted it to 20000.00.',+ 'Spent 20000.00 as planned, funded from the pots.',+ ]);+ });++ it('keeps a plain year to one sentence', () => {+ expect(story(makeRow())).toEqual([+ 'Spent 4000.00 as planned, funded from the pots.',+ ]);+ });++ it('says nothing about a rule that made no change', () => {+ const row = makeRow({+ ruleExplanation: {+ kind: 'factor',+ rule: 'guardrails',+ factor: 1,+ planned: 4_000,+ adjusted: 4_000,+ action: 'none',+ },+ });+ expect(story(row)).toEqual([+ 'Spent 4000.00 as planned, funded from the pots.',+ ]);+ });++ it('explains earlier adjustments that still apply', () => {+ const row = makeRow({+ withdrawal: 3_600,+ plannedSpending: 3_600,+ spent: 3_600,+ ruleExplanation: {+ kind: 'factor',+ rule: 'boundaries',+ factor: 0.9,+ planned: 4_000,+ adjusted: 3_600,+ action: 'none',+ },+ });+ expect(story(row)[0]).toBe(+ "Earlier Boundaries changes still applied, so this year's spending was 3600.00 instead of the 4000.00 planned.",+ );+ });++ it('quotes the boundary and ratchet settings the rule tripped', () => {+ const boundariesCut = makeRow({+ ruleExplanation: {+ kind: 'factor',+ rule: 'boundaries',+ factor: 0.9,+ planned: 4_000,+ adjusted: 3_600,+ action: 'cut',+ currentRate: 0.07,+ },+ });+ expect(story(boundariesCut)[0]).toBe(+ "Boundaries cut this year's spending from 4000.00 to 3600.00 because the withdrawal rate rose above 6%.",+ );++ const ratchetRaise = makeRow({+ ruleExplanation: {+ kind: 'factor',+ rule: 'ratcheting',+ factor: 1.05,+ planned: 4_000,+ adjusted: 4_200,+ action: 'raise',+ ratchetStreak: 3,+ },+ });+ expect(story(ratchetRaise)[0]).toBe(+ "Ratcheting raised this year's spending from 4000.00 to 4200.00 because the balance had stayed above 1.5× its starting level for 3 years.",+ );+ });++ it('describes floor & ceiling only when a bound applied', () => {+ const floorApplied = makeRow({+ ruleExplanation: {+ kind: 'floor-ceiling',+ rate: 0.04,+ unclamped: 3_000,+ floor: 3_400,+ ceiling: 4_800,+ applied: 'floor',+ },+ });+ expect(story(floorApplied)[0]).toBe(+ 'Floor & ceiling held spending at 3400.00 - the rate-based amount (3000.00) fell below the floor.',+ );++ const withinBounds = makeRow({+ ruleExplanation: {+ kind: 'floor-ceiling',+ rate: 0.04,+ unclamped: 4_000,+ floor: 3_400,+ ceiling: 4_800,+ applied: 'rate',+ },+ });+ expect(story(withinBounds)).toHaveLength(1);++ const anchor = makeRow({ ruleExplanation: { kind: 'anchor', rate: 0.04 } });+ expect(story(anchor)[0]).toBe(+ "This is the first spending year, so the plan's withdrawal rate was set here.",+ );+ });++ it('phrases the floor on its own when no rule sentence precedes it', () => {+ const row = makeRow({+ withdrawal: 5_000,+ plannedSpending: 5_000,+ spent: 5_000,+ minimumApplied: true,+ });+ expect(story(row)).toEqual([+ "The minimum spending floor set this year's spending at 5000.00.",+ 'Spent 5000.00 as planned, funded from the pots.',+ ]);+ });++ it('credits income for the part of spending it covered', () => {+ const partly = makeRow({+ income: 1_000,+ incomeAmounts: [1_000],+ withdrawal: 3_000,+ potWithdrawals: [3_000],+ });+ expect(story(partly)).toEqual([+ 'Income covered 1000.00 of the 4000.00 spent; withdrawals covered the rest.',+ ]);++ const fully = makeRow({+ income: 5_000,+ incomeAmounts: [5_000],+ withdrawal: 0,+ potWithdrawals: [0],+ unspentIncome: 1_000,+ });+ expect(story(fully)).toEqual([+ 'Income covered all of the 4000.00 spent, so nothing had to come from the pots.',+ '1000.00 of income beyond the plan went unspent and left the plan.',+ ]);+ // With a surplus pot the engine saves that 1,000 instead+ expect(+ story({ ...fully, surplusSaved: 1_000 }, { hasSurplusPot: true })[1],+ ).toBe('1000.00 of income beyond the plan was saved into Surplus cash.');+ });++ it('says where income went when contributions took it', () => {+ // The user's year 66: 12,547.60 income, all paid into the cash pot+ const allContributed = makeRow({+ income: 12_547.6,+ incomeAmounts: [12_547.6],+ contributions: 12_547.6,+ withdrawal: 24_282.41,+ taxPaid: 4_282.41,+ plannedSpending: 20_000,+ spent: 20_000,+ });+ expect(story(allContributed, { hasSurplusPot: true })).toEqual([+ 'The 12547.60 income all went into contributions, so the 20000.00 spent came from the pots.',+ ]);++ const partlyContributed = makeRow({+ income: 3_000,+ incomeAmounts: [3_000],+ contributions: 2_000,+ withdrawal: 3_000,+ potWithdrawals: [3_000],+ });+ expect(story(partlyContributed)).toEqual([+ 'Income covered 1000.00 of the 4000.00 spent, with another 2000.00 of it going into contributions; withdrawals covered the rest.',+ ]);+ });++ it('nets tax out of the withdrawal when crediting income', () => {+ const row = makeRow({+ income: 1_000,+ incomeAmounts: [1_000],+ withdrawal: 3_750,+ taxPaid: 750,+ potWithdrawals: [3_750],+ });+ expect(story(row)[0]).toBe(+ 'Income covered 1000.00 of the 4000.00 spent; withdrawals covered the rest.',+ );+ });++ it('reports a shortfall and any locked money', () => {+ const row = makeRow({+ withdrawal: 1_500,+ spent: 1_500,+ inaccessibleBalance: 80_000,+ });+ expect(story(row)).toEqual([+ 'Only 1500.00 of the 4000.00 planned could be funded - the plan ran out of accessible money here.',+ '80000.00 was still locked in pots that had not reached their access age.',+ ]);+ });+});diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloYearStory.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloYearStory.tsnew file mode 100644index 0000000000..3974eef115--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloYearStory.ts@@ -0,0 +1,291 @@+import type { TFunction } from 'i18next';++import type {+ MonteCarloRuleExplanation,+ MonteCarloRunDetailRow,+ MonteCarloWithdrawalRuleConfig,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';++/**+ * Enough precision that multiplying the displayed rate by the balance+ * reproduces the displayed amounts; trailing zeros trimmed so simple+ * rates still read cleanly (4% rather than 4.0000%)+ */+export function formatRuleRate(rate: number) {+ return `${Number((rate * 100).toFixed(4))}%`;+}++type MonteCarloYearStoryInput = {+ row: MonteCarloRunDetailRow;+ withdrawalRule: MonteCarloWithdrawalRuleConfig;+ /** How the surplus pot is labelled in the UI */+ surplusPotName: string;+ hasSurplusPot: boolean;+ format: (amount: number, type: 'financial') => string;+ translate: TFunction;+};++/**+ * The plain-English summary of one simulated year, as a few sentences+ * that follow cause to effect: what the withdrawal rule decided and why,+ * whether the minimum spending floor stepped in, how the year's spending was+ * funded, and where any money the plan didn't spend ended up. The+ * numbers behind each decision live in the detailed lines, not here+ */+export function buildMonteCarloYearStory({+ row,+ withdrawalRule,+ surplusPotName,+ hasSurplusPot,+ format,+ translate,+}: MonteCarloYearStoryInput): string[] {+ const sentences: string[] = [];++ const ruleSentence =+ row.ruleExplanation != null+ ? getRuleDecisionSentence(+ row.ruleExplanation,+ withdrawalRule,+ format,+ translate,+ )+ : null;+ if (ruleSentence != null) {+ sentences.push(ruleSentence);+ }++ if (row.minimumApplied) {+ const planned = format(row.plannedSpending, 'financial');+ sentences.push(+ ruleSentence != null+ ? translate(+ 'The minimum spending floor then lifted it to {{planned}}.',+ { planned },+ )+ : translate(+ "The minimum spending floor set this year's spending at {{planned}}.",+ { planned },+ ),+ );+ }++ sentences.push(...getFundingSentences(row, format, translate));++ const surplusSentence = getSurplusSentence(+ row,+ surplusPotName,+ hasSurplusPot,+ format,+ translate,+ );+ if (surplusSentence != null) {+ sentences.push(surplusSentence);+ }++ return sentences;+}++function getRuleName(+ rule: 'guardrails' | 'ratcheting' | 'boundaries',+ translate: TFunction,+) {+ if (rule === 'guardrails') {+ return translate('Guardrails');+ }+ if (rule === 'ratcheting') {+ return translate('Ratcheting');+ }+ return translate('Boundaries');+}++// What the rule decided, with the reason in words; null when the rule+// did nothing worth telling+function getRuleDecisionSentence(+ explanation: MonteCarloRuleExplanation,+ withdrawalRule: MonteCarloWithdrawalRuleConfig,+ format: MonteCarloYearStoryInput['format'],+ translate: TFunction,+): string | null {+ if (explanation.kind === 'anchor') {+ return translate(+ "This is the first spending year, so the plan's withdrawal rate was set here.",+ );+ }+ if (explanation.kind === 'floor-ceiling') {+ const values = {+ amount: format(+ explanation.applied === 'floor'+ ? explanation.floor+ : explanation.ceiling,+ 'financial',+ ),+ unclamped: format(explanation.unclamped, 'financial'),+ };+ if (explanation.applied === 'floor') {+ return translate(+ 'Floor & ceiling held spending at {{amount}} - the rate-based amount ({{unclamped}}) fell below the floor.',+ values,+ );+ }+ if (explanation.applied === 'ceiling') {+ return translate(+ 'Floor & ceiling held spending at {{amount}} - the rate-based amount ({{unclamped}}) rose above the ceiling.',+ values,+ );+ }+ return null;+ }++ const rule = getRuleName(explanation.rule, translate);+ const planned = format(explanation.planned, 'financial');+ const adjusted = format(explanation.adjusted, 'financial');+ if (explanation.action === 'cut') {+ if (explanation.rule === 'boundaries') {+ return translate(+ "{{rule}} cut this year's spending from {{planned}} to {{adjusted}} because the withdrawal rate rose above {{upper}}.",+ {+ rule,+ planned,+ adjusted,+ upper: formatRuleRate(withdrawalRule.upperRateThreshold),+ },+ );+ }+ return translate(+ "{{rule}} cut this year's spending from {{planned}} to {{adjusted}} because the withdrawal rate had climbed too far above the plan.",+ { rule, planned, adjusted },+ );+ }+ if (explanation.action === 'raise') {+ if (explanation.rule === 'boundaries') {+ return translate(+ "{{rule}} raised this year's spending from {{planned}} to {{adjusted}} because the withdrawal rate fell below {{lower}}.",+ {+ rule,+ planned,+ adjusted,+ lower: formatRuleRate(withdrawalRule.lowerRateThreshold),+ },+ );+ }+ if (explanation.rule === 'ratcheting') {+ return translate(+ "{{rule}} raised this year's spending from {{planned}} to {{adjusted}} because the balance had stayed above {{multiple}} its starting level for {{years}} years.",+ {+ rule,+ planned,+ adjusted,+ multiple: `${Number(withdrawalRule.balanceThresholdMultiple.toFixed(2))}×`,+ years: withdrawalRule.consecutiveYears,+ },+ );+ }+ return translate(+ "{{rule}} raised this year's spending from {{planned}} to {{adjusted}} because the withdrawal rate had fallen well below the plan.",+ { rule, planned, adjusted },+ );+ }+ if (explanation.factor !== 1) {+ return translate(+ "Earlier {{rule}} changes still applied, so this year's spending was {{adjusted}} instead of the {{planned}} planned.",+ { rule, planned, adjusted },+ );+ }+ return null;+}++// How the year's spending was paid for, or that it couldn't be+function getFundingSentences(+ row: MonteCarloRunDetailRow,+ format: MonteCarloYearStoryInput['format'],+ translate: TFunction,+): string[] {+ const spent = format(row.spent, 'financial');+ if (row.spent < row.plannedSpending) {+ const sentences = [+ translate(+ 'Only {{spent}} of the {{planned}} planned could be funded - the plan ran out of accessible money here.',+ { spent, planned: format(row.plannedSpending, 'financial') },+ ),+ ];+ if (row.inaccessibleBalance != null) {+ sentences.push(+ translate(+ '{{amount}} was still locked in pots that had not reached their access age.',+ { amount: format(row.inaccessibleBalance, 'financial') },+ ),+ );+ }+ return sentences;+ }+ if (row.income > 0) {+ // What the pots put towards spending: the withdrawal net of tax+ const netFromPots = row.withdrawal - row.taxPaid;+ if (netFromPots <= 0) {+ return [+ translate(+ 'Income covered all of the {{spent}} spent, so nothing had to come from the pots.',+ { spent },+ ),+ ];+ }+ const fromIncome = row.spent - netFromPots;+ // Net income that neither went to spending nor was left over was+ // paid into pots by contributions sourced from the income+ const netIncome = row.income - row.incomeTax;+ const toContributions = netIncome - row.unspentIncome - fromIncome;+ if (fromIncome <= 0) {+ return [+ translate(+ 'The {{netIncome}} income all went into contributions, so the {{spent}} spent came from the pots.',+ { netIncome: format(netIncome, 'financial'), spent },+ ),+ ];+ }+ if (toContributions > 0) {+ return [+ translate(+ 'Income covered {{fromIncome}} of the {{spent}} spent, with another {{toContributions}} of it going into contributions; withdrawals covered the rest.',+ {+ fromIncome: format(fromIncome, 'financial'),+ toContributions: format(toContributions, 'financial'),+ spent,+ },+ ),+ ];+ }+ return [+ translate(+ 'Income covered {{fromIncome}} of the {{spent}} spent; withdrawals covered the rest.',+ { fromIncome: format(fromIncome, 'financial'), spent },+ ),+ ];+ }+ return [+ translate('Spent {{spent}} as planned, funded from the pots.', { spent }),+ ];+}++// Where money the plan didn't spend ended up; null when there was none+function getSurplusSentence(+ row: MonteCarloRunDetailRow,+ surplusPotName: string,+ hasSurplusPot: boolean,+ format: MonteCarloYearStoryInput['format'],+ translate: TFunction,+): string | null {+ if (hasSurplusPot && row.surplusSaved > 0) {+ return translate(+ '{{unspent}} of income beyond the plan was saved into {{pot}}.',+ { pot: surplusPotName, unspent: format(row.surplusSaved, 'financial') },+ );+ }+ if (row.unspentIncome > 0) {+ return translate(+ '{{unspent}} of income beyond the plan went unspent and left the plan.',+ { unspent: format(row.unspentIncome, 'financial') },+ );+ }+ return null;+}diff --git a/packages/docs/docs/experimental/monte-carlo-analysis.md b/packages/docs/docs/experimental/monte-carlo-analysis.mdindex 41b72f6b5b..ae2291e8ca 100644--- a/packages/docs/docs/experimental/monte-carlo-analysis.md+++ b/packages/docs/docs/experimental/monte-carlo-analysis.md@@ -36,13 +36,13 @@ The report works immediately with sensible example numbers filled in, so you can## Setting Up Your Plan-The configuration area at the top of the report is organized into five tabs.+The configuration area at the top of the report is organized into six tabs.### Plan Details-The tab is organized into three small groups - **Your plan**, **Simulation** and **Inflation**:+The tab is organized into four small groups - **Your plan**, **Simulation**, **Inflation** and **Manage surplus**:- **Your current age** and **Pot must last until age** - these two numbers define the period being tested. If you're 40 and want the money to last until you're 95, the report simulates 55 years.- **Return model** - how the simulation invents each year's investment returns:@@ -55,6 +55,7 @@ The tab is organized into three small groups - **Your plan**, **Simulation** and- **Simulations** - how many replays to run (1,000 to 10,000). More replays give steadier numbers but take slightly longer. When using historical sequences, this field is disabled because there is exactly one replay per historical starting year.- **Inflation - Mean (%)** - the average yearly rise in prices. When set, your planned spending grows with it so your spending power keeps up. Leave it blank to take exactly the same amount every year. With a historical return model, the two inflation inputs are replaced by an **Adjust spending with inflation** checkbox: each simulated year then uses that year's actual US inflation, keeping inflation and market returns paired the way they really were.- **Inflation - Std dev (%)** - real-world inflation bounces around from year to year rather than staying fixed. When set, each simulated year draws its own inflation rate around the mean, separately in every replay. The default of 2% is roughly how much US inflation has varied in recent decades; set it to 0 to use the fixed mean rate every year. Only used by the random return model.+- **Manage surplus - Assume any unspent money is spent** - what happens to money the plan doesn't spend in a year, such as income beyond your spending. Unticked (the default), a **Surplus cash** pot holds everything the plan doesn't spend and is drawn on first when spending needs funding; tick it and unspent money simply leaves the plan. See [Income](#income) for the details.### Investment Pots@@ -83,6 +84,25 @@ Drag a pot's row to reorder the list - the order matters if you choose to drainThe access age setting is what lets the report model the classic "bridge gap": retiring at 48 with a big pension you can't open until 57, and a smaller pot that has to carry you across those nine years. If the bridge pot runs dry too soon, the plan fails - even though the pension money exists.:::+### Income++++Income streams are money you receive each year without drawing on your pots - a state pension, a defined-benefit pension, an annuity, rental income, or part-time work in early retirement. They matter because they pay for your spending _first_: with £40,000 of yearly spending and a £12,000 state pension, the pots only need to fund £28,000, and the withdrawal rules and the failure test both work on that smaller amount. Each stream has:++- **Income name** - anything you like, such as "State pension".+- **From age** and **To age** - the years the income arrives, inclusive at both ends. Leave **From age** blank to start now, and **To age** blank to keep receiving it until the end of the plan.+- **Amount (per year)** - the gross yearly amount, in today's money, before any tax.+- **Tax (%)** (or **Taxable portion (%)** with the bands model) - how the income is taxed, exactly as for pot withdrawals: an effective rate under the flat model, or the share that counts as taxable income under the bands model. Under the bands model, income fills your lower tax bands first, so any pot withdrawal in the same year is taxed at the correct, higher marginal rate.+- **Adjust by inflation** - tick this for income that rises with prices (most state pensions do); untick it for a fixed amount, such as a level annuity, which buys a little less each year as prices rise.++Income you don't need is **unspent**: once the year's contributions paid from it and its spending are covered, anything left is dealt with according to the **Manage surplus** setting on the Plan Details tab:++- **Assume any unspent money is spent** unticked (the default for new plans): a **Surplus cash** pot sits at the top of your pots. Income beyond your spending is saved into it at the start of the year (so it earns that year's return), and it is always the first pot drawn on when spending needs funding. It starts empty and holds cash - no access age, no tax, no fees - and its settings can't be changed in the pots list. Tick the setting to remove it, along with any contributions paid into it.+- **Ticked**: unspent money leaves the plan - it isn't invested and doesn't help later years. The run drill-in and the cashflow chart both point out unspent income so it doesn't go unnoticed, and you can route specific amounts into a pot with a contribution whose **Paid from** is that income stream. Plans saved before this setting existed keep this behaviour; untick the box to add the Surplus cash pot.++A plan whose income covers its spending doesn't need the pots at all, and empty pots are not a failure on their own - the plan only fails in a year whose spending can't be paid for from income and pots together.+### Contributions@@ -91,6 +111,7 @@ If you're still earning, you can model the money you add to your pots each year- **Contribution name** - anything you like, such as "Pension contributions".- **Into pot** - the pot the money is paid into. A pot can receive any number of contributions, and contributions can go into a pot that is still locked for withdrawals - the access age only controls when money can come _out_.+- **Paid from** - where the money comes from. **Outside the plan** (the default) means money the simulation doesn't otherwise know about. Choosing one of your [income streams](#income) instead pays the contribution out of that income: it is capped at what the stream brings in that year, and it is zero in years the stream pays nothing. Tick **Before tax** for a workplace pension or salary sacrifice - the contribution is deducted before the income's tax is worked out, so it lowers that year's tax bill.- **From age** and **To age** - the years the contribution runs, inclusive at both ends. Leave **From age** blank to start now, and **To age** blank to keep contributing until the end of the plan.- **Amount (per year)** - how much is added each year, in today's money. The money is paid in at the start of each year, so it earns that year's investment return.- **Adjust by inflation** - tick this if the contribution will grow with prices over time (for example, a percentage of a salary that keeps pace with inflation). Untick it for a fixed amount, which buys a little less each year as prices rise.@@ -107,7 +128,7 @@ Contributions pair naturally with a spending phase set to 0: while you're workin- **Drain pots in order**: empty the first pot in your list before touching the next - for example, spend your taxable account first and let the pension keep compounding. Pots that haven't reached their access age are skipped until they unlock.- **Spend from the best performer first**: each year, the withdrawal comes from the pot that earned the highest return _last_ year. This is the classic "bucket strategy" instinct: after a stock crash, live off your cash and give the crashed pot time to recover; in a boom year, spend from stocks and leave the cash reserve alone. The first year (when there's no track record yet) uses your listed order, and locked pots are skipped here too.- **Keep pots at their target mix**: each pot's share of your starting balances becomes its target weight, and withdrawals come from whichever pots have grown above their target - most overweight first - pulling the portfolio back toward the mix you chose. This behaves like the best-performer option in booms and crashes (trim stocks after a good run, spend cash and bonds after a crash) but without slowly drifting your money into low-growth pots, because it always steers back to your chosen mix. If you want a permanent cash buffer, give the cash pot the share you want to maintain and this order will keep it topped up in spirit - by spending it only when it's above its target share.-- **Withdrawal rule** and **Minimum withdrawal** - see the next section.+- **Withdrawal rule** and **Minimum spending** - see the next section.The inflation settings that grow your spending over time live on the [Plan Details](#plan-details) tab.@@ -122,6 +143,8 @@ Withdrawing money from a pension or a taxable account usually costs more than thWith either model, the run drill-in shows each year's gross withdrawal with the tax paid underneath, so you can see exactly what your spending actually costs.+[Income streams](#income) are taxed the same way, using their own rate or taxable portion. Under the bands model the year's income is banded first and the pot withdrawals are taxed as the slice above it - so a taxable pension that uses up your tax-free allowance makes every withdrawal that year cost more, just as it does in real life.+:::noteThis is a deliberate approximation, not a tax calculator. It doesn't track capital-gains cost basis, model frozen thresholds, or know any country's actual rules - and tax law changes every year. Treat the rates and bands as your own honest estimates.:::@@ -132,11 +155,11 @@ By default, the simulation withdraws the same (inflation-adjusted) amount everyAll the rules share a few ideas:-- Your **spending phases** set the planned amounts. The rules wake up in your first year of planned spending: that year takes the planned amount (only a **Minimum withdrawal** set higher than it can override that), and from the next year onward the rule adjusts what's actually taken - independently in every replay, reacting to how that replay is going. Zero-spend years (for example, working years before retirement) neither trigger nor move the rules. A cut or raise carries across phase boundaries: if the rule cut your spending by 10% during a rough patch, the next phase's amount starts 10% lower too.+- Your **spending phases** set the planned amounts. The rules wake up in your first year of planned spending: that year takes the planned amount (only a **Minimum spending** set higher than it can override that), and from the next year onward the rule adjusts what's actually taken - independently in every replay, reacting to how that replay is going. Zero-spend years (for example, working years before retirement) neither trigger nor move the rules. A cut or raise carries across phase boundaries: if the rule cut your spending by 10% during a rough patch, the next phase's amount starts 10% lower too.- Rules usually improve your **success rate** by cutting spending in bad times, but that safety isn't free - you get it by living on less. Keep an eye on the **Median total withdrawn** stat to see what a rule costs you in income.- Rules only see the wealth you can actually spend. If a pension is locked until its access age, it doesn't earn you spending raises while a bridge pot pays the bills - the rules watch the accessible pots, and the pension starts counting the moment it unlocks.-If you set a **Minimum withdrawal**, your yearly spending never drops below that amount, no matter what the rule says. It only applies in years you actually plan to spend - a spending phase set to 0 (for example, years before retirement while your salary covers your costs) takes nothing. Like your spending phases, it's an amount in today's money - it rises with inflation so its spending power holds steady.+If you set a **Minimum spending**, your yearly spending never drops below that amount, no matter what the rule says - it is the lowest amount you need to live on, so when the rule cuts below it the plan is lifted back up to it and that is what gets spent. [Income streams](#income) count towards it, so the pots only withdraw enough to top your spending up to the floor - a 12,000 floor with a 10,000 state pension means the pots never pay less than 2,000. It only applies in years you actually plan to spend - a spending phase set to 0 (for example, years before retirement while your salary covers your costs) takes nothing. Like your spending phases, it's an amount in today's money - it rises with inflation so its spending power holds steady.### Guardrails (Guyton-Klinger)@@ -162,7 +185,7 @@ By default, every money figure in the results is shown in **today's money** - wh-- **Success rate** - the big number: the percentage of replays in which your money lasted the full time. There's no single "right" target, but many planners aim for 80–90%.+- **Success rate** - the big number: the percentage of replays in which every year's spending was paid for, from income and pots together. There's no single "right" target, but many planners aim for 80–90%. (Running the pots down to nothing isn't a failure by itself - only a year whose spending goes unfunded is.)- **Median ending balance** - in the middle-of-the-road replay, how much was left at the end.- **Median total withdrawn** - how much income the middle replay actually paid you over the whole period. Especially useful when comparing withdrawal rules.- **Chance of running out of money** - the flip side of the success rate.@@ -184,16 +207,16 @@ The dropdown above the chart switches views. **Single worst run** shows the one-Switch the results view from **Chart** to **Cashflow** to see the money moving in and out of your pots each year, for one simulated run at a time:+Switch the results view from **Chart** to **Cashflow** to see the money flowing through your hands each year, for one simulated run at a time:-- **Above zero**: money coming in - each pot's withdrawal for the year (one color per pot), plus each contribution being paid in (one color per contribution).-- **Below zero**: money going out - the year's planned spending, colored by the spending phase it belongs to, plus the tax paid on withdrawals.+- **Above zero**: money coming in - each pot's withdrawal for the year (one color per pot), plus each income stream (one color per stream).+- **Below zero**: money going out - the year's planned spending, colored by the spending phase it belongs to; the tax paid on withdrawals and income; each contribution being paid into a pot (one color per contribution); and money saved into your surplus pot, if you keep unspent money.-Management fees don't appear here - they are charged inside the pots and never pass through your hands, and the run detail table lists them.+Management fees don't appear here - they are charged inside the pots and never pass through your hands, and the run detail table lists them. Income you didn't need shows up as inflows that outweigh the outflows, and the tooltip names the unspent amount.On a run that fails, the chart doesn't stop at the failure year: the remaining years keep showing the spending the plan still called for, dimmed, with nothing coming in to fund it - so the size of the gap is visible at a glance. Those dimmed bars are held at the failure year's level - its price level, since a dead run no longer experiences inflation, and any cut or raise a withdrawal rule had in force at the time.-The spending bars show the _plan_ - the phase amount, adjusted for inflation and any withdrawal rule - rather than the money actually delivered. That's what makes trouble visible: in a shortfall year the withdrawal bars fall visibly short of the spending bar, and when a minimum withdrawal forces out more than the plan asked for, the bars overshoot it.+The spending bars show the _plan_ - the phase amount, adjusted for inflation, any withdrawal rule and the minimum spending floor - rather than the money actually delivered. That's what makes trouble visible: in a shortfall year the withdrawal bars fall visibly short of the spending bar.Use the dropdown above the chart to pick which run to look at: the worst run, a typically-bad or typically-good outcome (the 25th and 75th percentiles), the median, or the best run. These are the same runs the **Jump to** dropdown in the runs view lands on. The chart also appears above the year-by-year table when you click into any individual run, so you can see that specific run's flows at a glance.@@ -207,11 +230,11 @@ This bar chart only counts the replays that failed, showing at which age they ra-Switch the results view from **Chart** to **Runs** to see every replay listed from worst outcome to best. Rather than paging through thousands of runs, use the **Jump to** dropdown to go straight to the worst, median or best run - or the 25th/75th percentile for a typically-bad or typically-good outcome - with the run highlighted so you can click into it. Click any run to walk through it year by year: the balance at the start of each year, the contributions paid in (when your plan has any), the withdrawal taken, the investment growth in that year (as money and as a percentage), the year's inflation rate (when inflation is enabled), and the balance at the end. Expand a year with the arrow at the start of its row (or use **Expand all years**) for the fully labeled breakdown: the withdrawal split into gross, tax and money to spend; when a withdrawal rule is active, a sentence showing how the rule arrived at that year's amount (and whether the minimum withdrawal stepped in); the contributions added; the fees paid; and a small table showing each pot's balance at the start of the year, what was contributed into it, what it contributed to the withdrawal, how much of that counted as taxable income, the tax paid on its share, the fee it was charged that year, its return that year, and its ending balance - so you can watch, for example, the cash pot covering spending after a crash while the stock pots are left alone. With the tax-bands model, the per-pot tax is the year's tax bill shared out in proportion to each pot's taxable income.+Switch the results view from **Chart** to **Runs** to see every replay listed from worst outcome to best. Rather than paging through thousands of runs, use the **Jump to** dropdown to go straight to the worst, median or best run - or the 25th/75th percentile for a typically-bad or typically-good outcome - with the run highlighted so you can click into it. Click any run to walk through it year by year: the balance at the start of each year, the contributions paid in (when your plan has any, including money saved into the Surplus cash pot), the net income received (when your plan has income streams), the withdrawal taken, what was actually spent (income and withdrawal together, net of tax - shown in red when it fell short of the plan), the investment growth in that year (as money and as a percentage), the year's inflation rate (when inflation is enabled), and the balance at the end. Expand a year with the arrow at the start of its row (or use **Expand all years**) and it opens with a short plain-English summary of what happened that year and why: any change the withdrawal rule made and what triggered it, whether the minimum spending floor stepped in, how the year's spending was funded (income, pots, or a shortfall), and where any money the plan didn't spend went. Below it sits the pot table described further down. Click **Show the working** for the fully labeled breakdown behind the summary: the income received, split into gross, tax and net (and per stream when you have several), with any unspent income called out; the withdrawal split into gross, tax and money to spend; how the year's spending compared with the plan (as planned, or short by an amount); when a withdrawal rule is active, a sentence showing how the rule arrived at that year's amount (and whether the minimum spending floor stepped in); the contributions added; the fees paid; and a small table showing each pot's balance at the start of the year, what was contributed into it (for the Surplus cash pot, the money saved into it that year), what it contributed to the withdrawal, how much of that counted as taxable income, the tax paid on its share, the fee it was charged that year, its return that year, and its ending balance - so you can watch, for example, the cash pot covering spending after a crash while the stock pots are left alone. With the tax-bands model, the per-pot tax is the year's tax bill shared out in proportion to each pot's taxable income.-Above the year-by-year table, a summary line totals the run: how much was withdrawn over the whole replay, how much of that went to tax, and how much was paid in fees on top.+Above the year-by-year table, a summary line totals the run: how much was withdrawn over the whole replay, how much of that went to tax, how much was paid in fees on top, and - when the plan has income streams - how much income was received and the tax paid on it.If a run failed while money was still locked in an inaccessible pot, the table says so explicitly, so you can tell the difference between "the market ate my savings" and "the money existed but I couldn't reach it yet."diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-cashflow-chart.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-cashflow-chart.pngindex d6f38ec4bd..f9db147b3b 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-cashflow-chart.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-cashflow-chart.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.pngindex f2337dc59c..219dd694f8 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.pngindex e8d2d366bd..316d2ff291 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.pngindex 412f70f28a..d4832b6c61 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-income.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-income.pngnew file mode 100644index 0000000000..7f69ac86bdBinary files /dev/null and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-income.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.pngindex c5d13585e9..b0164e3784 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.pngindex b49bfc245d..fe6ecd4e0d 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.pngindex 65c9b470f2..6e6f055da5 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.pngindex 1499bab997..1b938856af 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.pngindex 432bc32cfd..38b418452b 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.pngindex 9980156712..1118218ed2 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.pngindex 636951a7f7..d12bc46d8e 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png differdiff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.pngindex 26371ace6b..38b63fffa1 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png differdiff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 4a0e6da2fe..2b4875fc02 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -223,6 +223,11 @@ export type MonteCarloPotMeta = {feeAdjustsWithInflation?: boolean;/** Yearly fee as a fraction of the end-of-year balance (0.0022 = 0.22%) */annualFeeRate?: number;+ /**+ * The plan's surplus pot: unspent money is saved into it each year and+ * it is drawn on before any other pot. At most one pot is flagged.+ */+ isSurplus?: boolean;};/** One recurring yearly contribution into a pot over an age window */@@ -239,6 +244,37 @@ export type MonteCarloContributionMeta = {annualAmount?: number;/** Whether the amount rises with inflation */adjustsWithInflation?: boolean;+ /**+ * Income stream the contribution is paid out of; null/absent = money+ * from outside the plan+ */+ sourceIncomeStreamId?: string | null;+ /**+ * Whether an income-sourced contribution comes out of the stream's+ * gross before its tax is worked out (salary sacrifice)+ */+ beforeTax?: boolean;+};++/**+ * One recurring yearly income received without drawing on the pots+ * (state pension, annuity, rental, part-time work) over an age window+ */+export type MonteCarloIncomeStreamMeta = {+ id: string;+ name?: string;+ /** Age the income starts (inclusive); null/absent = starts now */+ fromAge?: number | null;+ /** Age the income stops (inclusive); null/absent = end of plan */+ toAge?: number | null;+ /** Yearly gross amount in minor units, in today's money */+ annualAmount?: number;+ /** Whether the amount rises with inflation */+ adjustsWithInflation?: boolean;+ /** Flat tax model: effective tax rate on the income (0.2 = 20%) */+ taxRate?: number;+ /** Bands tax model: share of the income that counts as taxable */+ taxableFraction?: number;};export type MonteCarloTaxModel = 'flat' | 'bands';@@ -261,10 +297,12 @@ export type MonteCarloWidget = AbstractWidget<returnModel?: MonteCarloReturnModel;withdrawalRule?: MonteCarloWithdrawalRuleMeta;/** Minimum annual withdrawal in minor units; 0 or absent = no floor */- minimumWithdrawal?: number;+ minimumSpending?: number;spendingPhases?: MonteCarloSpendingPhaseMeta[];/** Recurring yearly contributions into pots */contributions?: MonteCarloContributionMeta[];+ /** Recurring yearly income that pays for spending before the pots */+ incomeStreams?: MonteCarloIncomeStreamMeta[];/** Mean yearly inflation as a decimal fraction; null = flat withdrawals */inflationMean?: number | null;/** Yearly inflation volatility as a decimal fraction; 0 = fixed rate */diff --git a/upcoming-release-notes/monte-carlo-income-streams.md b/upcoming-release-notes/monte-carlo-income-streams.mdnew file mode 100644index 0000000000..eb3cedbea9--- /dev/null+++ b/upcoming-release-notes/monte-carlo-income-streams.md@@ -0,0 +1,6 @@+---+category: Enhancement+authors: [MikesGlitch]+---++Add income streams to the Monte Carlo report