A local-first personal finance app
:chart_with_upwards_trend: Monte carlo - Cashflow chart (#8903)
Michael Clark59bde67ba662
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 0c63e2c367..f23bb81575 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -64,6 +64,8 @@"#components/reports/monthRange": "./src/components/reports/monthRange.ts","#components/reports/graphs/showActivity": "./src/components/reports/graphs/showActivity.ts","#components/reports/graphs/util/computePadding": "./src/components/reports/graphs/util/computePadding.ts",+ "#components/reports/graphs/util/monteCarloCashflowChart": "./src/components/reports/graphs/util/monteCarloCashflowChart.ts",+ "#components/reports/graphs/util/useMonteCarloTickFormatter": "./src/components/reports/graphs/util/useMonteCarloTickFormatter.ts","#components/reports/numberFormatter": "./src/components/reports/numberFormatter.ts","#components/reports/ReportOptions": "./src/components/reports/ReportOptions.ts","#components/reports/reportRanges": "./src/components/reports/reportRanges.ts",diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsxnew file mode 100644index 0000000000..193da4c5ef--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraph.tsx@@ -0,0 +1,161 @@+import { useTranslation } from 'react-i18next';++import type { CSSProperties } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import {+ Bar,+ CartesianGrid,+ Cell,+ ComposedChart,+ ReferenceLine,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts';++import { useRechartsAnimation } from '#components/reports/chart-theme';+import { Container } from '#components/reports/Container';+import { MonteCarloCashflowGraphTooltip } from '#components/reports/graphs/MonteCarloCashflowGraphTooltip';+import { MonteCarloCashflowLegendGroup } from '#components/reports/graphs/MonteCarloCashflowLegendGroup';+import { computePadding } from '#components/reports/graphs/util/computePadding';+import { buildMonteCarloCashflowChart } from '#components/reports/graphs/util/monteCarloCashflowChart';+import { useMonteCarloTickFormatter } from '#components/reports/graphs/util/useMonteCarloTickFormatter';+import type {+ MonteCarloContribution,+ MonteCarloPot,+ MonteCarloRunDetailRow,+ MonteCarloSpendingPhase,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { useFormat } from '#hooks/useFormat';++const MAX_BAR_SIZE = 50;++/** Bars for years after the plan ran out are dimmed to this opacity */+const UNFUNDED_BAR_OPACITY = 0.45;++type MonteCarloCashflowGraphProps = {+ /** Applies to the whole block (chart plus legend); the chart itself is Container's default height */+ style?: CSSProperties;+ /** The captured run to chart, one row per simulated year */+ rows: MonteCarloRunDetailRow[];+ pots: MonteCarloPot[];+ contributions: MonteCarloContribution[];+ spendingPhases: MonteCarloSpendingPhase[];+ /** The user's current age; the x-axis shows startAge + year - 1 */+ startAge: number;+};++/**+ * Yearly cashflow of a single simulated run as stacked bars: money in+ * above zero, money out below. See buildMonteCarloCashflowChart for+ * what the series are and how spending is attributed.+ */+export function MonteCarloCashflowGraph({+ style,+ rows,+ pots,+ contributions,+ spendingPhases,+ startAge,+}: MonteCarloCashflowGraphProps) {+ const { t } = useTranslation();+ const format = useFormat();+ const tickFormatter = useMonteCarloTickFormatter();+ const animationProps = useRechartsAnimation({ animationDuration: 1000 });++ const { data, inflowSeries, outflowSeries, tooltipGroups, stackExtents } =+ buildMonteCarloCashflowChart({+ rows,+ pots,+ contributions,+ spendingPhases,+ startAge,+ translate: t,+ });++ return (+ <View style={style}>+ <Container>+ {(width, height) => (+ <ComposedChart+ width={width}+ height={height}+ stackOffset="sign"+ data={data}+ margin={{+ top: 15,+ right: 0,+ left: computePadding(stackExtents, value =>+ format(value, 'financial-no-decimals'),+ ),+ bottom: 10,+ }}+ >+ <CartesianGrid strokeDasharray="3 3" vertical={false} />+ <XAxis+ dataKey="age"+ tick={{ fill: theme.pageText }}+ tickLine={{ stroke: theme.pageText }}+ minTickGap={30}+ />+ <YAxis+ tickFormatter={tickFormatter}+ tick={{ fill: theme.pageText }}+ tickLine={{ stroke: theme.pageText }}+ />+ <Tooltip+ content={+ <MonteCarloCashflowGraphTooltip groups={tooltipGroups} />+ }+ isAnimationActive={false}+ cursor={{ fill: 'transparent' }}+ />+ <ReferenceLine y={0} stroke={theme.pageText} />+ {[...inflowSeries, ...outflowSeries].map(series => (+ <Bar+ key={series.key}+ dataKey={`amounts.${series.key}`}+ stackId="flow"+ fill={series.color}+ maxBarSize={MAX_BAR_SIZE}+ {...animationProps}+ >+ {/* Only spending remains after the plan runs out; dim it+ so those years read as planned-but-unfunded */}+ {series.kind === 'phase' &&+ data.map(point => (+ <Cell+ key={point.year}+ fill={series.color}+ fillOpacity={+ point.afterDepletion ? UNFUNDED_BAR_OPACITY : 1+ }+ />+ ))}+ </Bar>+ ))}+ </ComposedChart>+ )}+ </Container>+ <View+ style={{+ flexDirection: 'row',+ flexWrap: 'wrap',+ columnGap: 40,+ rowGap: 10,+ marginTop: 10,+ }}+ >+ <MonteCarloCashflowLegendGroup+ heading={t('Money in')}+ series={inflowSeries}+ />+ <MonteCarloCashflowLegendGroup+ heading={t('Money out')}+ series={outflowSeries}+ />+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsxnew file mode 100644index 0000000000..e786c2d53b--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowGraphTooltip.tsx@@ -0,0 +1,127 @@+import { useTranslation } from 'react-i18next';++import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import { css } from '@emotion/css';++import { FinancialText } from '#components/FinancialText';+import { MonteCarloCashflowSwatch } from '#components/reports/graphs/MonteCarloCashflowSwatch';+import type {+ MonteCarloCashflowDataPoint,+ MonteCarloCashflowTooltipGroup,+} from '#components/reports/graphs/util/monteCarloCashflowChart';+import { useFormat } from '#hooks/useFormat';++type PayloadItem = {+ payload: MonteCarloCashflowDataPoint;+};++type MonteCarloCashflowGraphTooltipProps = {+ active?: boolean;+ payload?: PayloadItem[];+ groups: MonteCarloCashflowTooltipGroup[];+};++const VALUE_ROW_STYLE = css({+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 20,+});++const LABEL_STYLE = css({+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ gap: 6,+});++export function MonteCarloCashflowGraphTooltip({+ active,+ payload,+ groups,+}: MonteCarloCashflowGraphTooltipProps) {+ const { t } = useTranslation();+ const format = useFormat();++ if (!active || !payload || payload.length === 0) {+ return null;+ }+ const point = payload[0].payload;+ // Only series with money moving this year, and only groups with any+ const sections = groups+ .map(group => {+ const members = group.series+ .map(series => ({ ...series, value: point.amounts[series.key] ?? 0 }))+ .filter(series => series.value !== 0);+ return {+ ...group,+ members,+ total: members.reduce((sum, series) => sum + series.value, 0),+ };+ })+ .filter(group => group.members.length > 0);++ return (+ <div+ className={css({+ zIndex: 1000,+ pointerEvents: 'none',+ borderRadius: 2,+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',+ backgroundColor: theme.menuBackground,+ color: theme.menuItemText,+ padding: 10,+ })}+ >+ <div style={{ marginBottom: 10 }}>+ <strong>{t('Age {{age}}', { age: point.age })}</strong>+ </div>+ {point.afterDepletion && (+ <div+ style={{ marginBottom: 10, maxWidth: 220, color: theme.errorText }}+ >+ {t('The pots had already run out - this spending went unfunded.')}+ </div>+ )}+ <div style={{ lineHeight: 1.5 }}>+ {sections.map(group => (+ <View key={group.key}>+ <View className={VALUE_ROW_STYLE}>+ <View className={LABEL_STYLE}>+ {!group.listMembers && (+ <MonteCarloCashflowSwatch color={group.members[0].color} />+ )}+ <strong>{group.heading}</strong>+ </View>+ <strong>+ <FinancialText>+ {format(group.total, 'financial')}+ </FinancialText>+ </strong>+ </View>+ {group.listMembers &&+ group.members.map(member => (+ <View+ key={member.key}+ className={VALUE_ROW_STYLE}+ style={{ paddingLeft: 16 }}+ >+ <View className={LABEL_STYLE}>+ <MonteCarloCashflowSwatch color={member.color} />+ <div>{member.label}</div>+ </View>+ <div>+ <FinancialText>+ {format(member.value, 'financial')}+ </FinancialText>+ </div>+ </View>+ ))}+ </View>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowLegendGroup.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowLegendGroup.tsxnew file mode 100644index 0000000000..adb28e62b1--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowLegendGroup.tsx@@ -0,0 +1,41 @@+import { Text } from '@actual-app/components/text';+import { View } from '@actual-app/components/view';++import { MonteCarloCashflowSwatch } from '#components/reports/graphs/MonteCarloCashflowSwatch';+import type { MonteCarloCashflowSeries } from '#components/reports/graphs/util/monteCarloCashflowChart';+import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';++type MonteCarloCashflowLegendGroupProps = {+ heading: string;+ series: MonteCarloCashflowSeries[];+};++/** One heading + swatch-row group of the cashflow chart's legend */+export function MonteCarloCashflowLegendGroup({+ heading,+ series,+}: MonteCarloCashflowLegendGroupProps) {+ return (+ <View style={{ gap: 6 }}>+ <Text style={GROUP_HEADING_STYLE}>{heading}</Text>+ <View+ style={{+ flexDirection: 'row',+ flexWrap: 'wrap',+ columnGap: 15,+ rowGap: 4,+ }}+ >+ {series.map(entry => (+ <View+ key={entry.key}+ style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}+ >+ <MonteCarloCashflowSwatch color={entry.color} size={12} />+ <Text>{entry.label}</Text>+ </View>+ ))}+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowSwatch.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowSwatch.tsxnew file mode 100644index 0000000000..3fd4e9a52e--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloCashflowSwatch.tsx@@ -0,0 +1,24 @@+import { View } from '@actual-app/components/view';++type MonteCarloCashflowSwatchProps = {+ color: string;+ size?: number;+};++/** The colour square that identifies a series in the cashflow chart's legend and tooltip */+export function MonteCarloCashflowSwatch({+ color,+ size = 10,+}: MonteCarloCashflowSwatchProps) {+ return (+ <View+ style={{+ width: size,+ height: size,+ borderRadius: 2,+ flexShrink: 0,+ backgroundColor: color,+ }}+ />+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsxindex 97f541469a..4e5a1cae15 100644--- a/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsx+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsx@@ -21,10 +21,9 @@ import {VIEW_DATA_KEYS,} from '#components/reports/graphs/MonteCarloGraphTooltip';import { computePadding } from '#components/reports/graphs/util/computePadding';-import { MAX_FORMATTABLE_AMOUNT } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { useMonteCarloTickFormatter } from '#components/reports/graphs/util/useMonteCarloTickFormatter';import type { MonteCarloPercentileBand } from '#components/reports/reports/monte-carlo/monteCarloSimulation';import { useFormat } from '#hooks/useFormat';-import { usePrivacyMode } from '#hooks/usePrivacyMode';type MonteCarloGraphProps = {style?: CSSProperties;@@ -46,8 +45,8 @@ export function MonteCarloGraph({compact = false,showTooltip = true,}: MonteCarloGraphProps) {- const privacyMode = usePrivacyMode();const format = useFormat();+ const tickFormatter = useMonteCarloTickFormatter();const animationProps = useRechartsAnimation({ animationDuration: 1000 });const data: FanChartDataPoint[] = percentileBands.map(band => ({@@ -66,19 +65,6 @@ export function MonteCarloGraph({worstRun: worstRunPath?.[band.year],}));- const tickFormatter = (tick: number) => {- if (privacyMode) {- return '...';- }- // Recharts can synthesize ticks above the (already clamped) data- // maximum; keep them within what the formatter accepts- const safeTick = Math.min(- Math.max(Math.round(tick), -MAX_FORMATTABLE_AMOUNT),- MAX_FORMATTABLE_AMOUNT,- );- return `${format(safeTick, 'financial-no-decimals')}`;- };-return (<Containerstyle={{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.tsnew file mode 100644index 0000000000..a1666bfc85--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts@@ -0,0 +1,249 @@+import type { TFunction } from 'i18next';+import { describe, expect, it } from 'vitest';++import type {+ MonteCarloContribution,+ MonteCarloPot,+ MonteCarloRunDetailRow,+ MonteCarloSpendingPhase,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';++import { buildMonteCarloCashflowChart } from './monteCarloCashflowChart';++// Interpolates like i18next so labels can be asserted literally+const translate = ((key: string, options?: Record<string, unknown>) =>+ key.replace(/{{\w+}}/g, placeholder => {+ const name = placeholder.slice('{{'.length, -'}}'.length);+ return String(options?.[name]);+ })) as unknown as TFunction;++function makePot(id: string, name = ''): MonteCarloPot {+ return {+ id,+ name,+ startingBalance: 0,+ allocationPreset: 'custom',+ allocationStocks: 0.6,+ allocationBonds: 0.4,+ allocationCash: 0,+ expectedReturnMean: 0,+ returnStdDev: 0,+ accessAge: null,+ accountId: null,+ withdrawalTaxRate: 0,+ taxableFraction: 1,+ annualFeeFixed: 0,+ feeAdjustsWithInflation: false,+ annualFeeRate: 0,+ };+}++function makeContribution(id: string, name = ''): MonteCarloContribution {+ return {+ id,+ name,+ potId: 'pot-1',+ fromAge: null,+ toAge: null,+ annualAmount: 0,+ adjustsWithInflation: false,+ };+}++function makePhase(+ id: string,+ fromAge: number | null,+ name = '',+): MonteCarloSpendingPhase {+ return { id, name, fromAge, annualWithdrawal: 0 };+}++function makeRow(+ overrides: Partial<MonteCarloRunDetailRow> & { year: number },+): MonteCarloRunDetailRow {+ return {+ startBalance: 0,+ withdrawal: 0,+ plannedSpending: 0,+ growth: 0,+ endBalance: 0,+ potBalances: [],+ potStartBalances: [],+ inflation: null,+ contributions: 0,+ potContributions: [],+ contributionAmounts: [],+ potWithdrawals: [],+ potTaxes: [],+ potTaxables: [],+ taxPaid: 0,+ feesPaid: 0,+ potFees: [],+ potReturns: [],+ ...overrides,+ };+}++const pots = [makePot('pot-1', 'Pension'), makePot('pot-2')];+const contributions = [+ makeContribution('contribution-1', 'Salary sacrifice'),+ makeContribution('contribution-2'),+];+const phases = [makePhase('phase-1', null, 'Early'), makePhase('phase-2', 62)];++describe('buildMonteCarloCashflowChart', () => {+ it('builds one series per pot, active contribution and phase', () => {+ const rows = [+ makeRow({+ year: 1,+ potWithdrawals: [30_000, 10_000],+ contributionAmounts: [5_000, 0],+ plannedSpending: 38_000,+ taxPaid: 2_000,+ }),+ ];+ const chart = buildMonteCarloCashflowChart({+ rows,+ pots,+ contributions,+ spendingPhases: phases,+ startAge: 60,+ translate,+ });++ expect(+ chart.inflowSeries.map(series => [series.kind, series.label]),+ ).toEqual([+ ['pot', 'Pension'],+ ['pot', 'Pot 2'],+ // The second contribution never deposits anything, so no series+ ['contribution', 'Salary sacrifice'],+ ]);+ expect(+ chart.outflowSeries.map(series => [series.kind, series.label]),+ ).toEqual([+ ['phase', 'Early'],+ ['phase', 'Phase 2'],+ ['tax', 'Tax'],+ ]);+ expect(chart.tooltipGroups.map(group => group.key)).toEqual([+ 'withdrawals',+ 'contributions',+ 'tax',+ 'spending',+ ]);++ const [point] = chart.data;+ expect(point.age).toBe(60);+ expect(point.afterDepletion).toBe(false);+ expect(point.amounts).toEqual({+ pot0: 30_000,+ pot1: 10_000,+ contribution0: 5_000,+ contribution1: 0,+ // Age 60 is before phase 2 starts, so the plan belongs to phase 1+ phase0: -38_000,+ phase1: 0,+ tax0: -2_000,+ });+ expect(chart.stackExtents).toEqual([45_000, -40_000]);+ });++ it('attributes each year to the phase active at that age', () => {+ const rows = [+ makeRow({ year: 1, plannedSpending: 100 }),+ makeRow({ year: 2, plannedSpending: 200 }),+ makeRow({ year: 3, plannedSpending: 300 }),+ ];+ const chart = buildMonteCarloCashflowChart({+ rows,+ pots,+ contributions: [],+ spendingPhases: phases,+ startAge: 60,+ translate,+ });++ // Ages 60, 61 fall in phase 1; age 62 switches to phase 2+ expect(+ chart.data.map(point => [point.amounts.phase0, point.amounts.phase1]),+ ).toEqual([+ [-100, 0],+ [-200, 0],+ [0, -300],+ ]);+ });++ it('omits tax and contribution groups when nothing was paid', () => {+ const chart = buildMonteCarloCashflowChart({+ rows: [makeRow({ year: 1, potWithdrawals: [100, 0] })],+ pots,+ contributions,+ spendingPhases: phases,+ startAge: 60,+ translate,+ });++ expect(chart.outflowSeries.map(series => series.kind)).toEqual([+ 'phase',+ 'phase',+ ]);+ expect(chart.tooltipGroups.map(group => group.key)).toEqual([+ 'withdrawals',+ 'spending',+ ]);+ });++ it('falls back to a single phase when none are configured', () => {+ const chart = buildMonteCarloCashflowChart({+ rows: [makeRow({ year: 1, plannedSpending: 500 })],+ pots,+ contributions: [],+ spendingPhases: [],+ startAge: 60,+ translate,+ });++ expect(chart.outflowSeries.map(series => series.label)).toEqual([+ 'Phase 1',+ ]);+ expect(chart.data[0].amounts.phase0).toBe(-500);+ });++ it('numbers unnamed phases as the editor lists them', () => {+ // Configured out of age order: the later-starting phase comes first+ const chart = buildMonteCarloCashflowChart({+ rows: [],+ pots,+ contributions: [],+ spendingPhases: [makePhase('late', 70), makePhase('early', null)],+ startAge: 60,+ translate,+ });++ // Resolved (age) order is early, late - but labels keep editor numbers+ expect(chart.outflowSeries.map(series => series.label)).toEqual([+ 'Phase 2',+ 'Phase 1',+ ]);+ });++ it('flags the synthetic years after a failure', () => {+ const chart = buildMonteCarloCashflowChart({+ rows: [+ makeRow({ year: 1, plannedSpending: 100 }),+ makeRow({ year: 2, plannedSpending: 100, afterDepletion: true }),+ ],+ pots,+ contributions: [],+ spendingPhases: phases,+ startAge: 60,+ translate,+ });++ expect(chart.data.map(point => point.afterDepletion)).toEqual([+ false,+ true,+ ]);+ });+});diff --git a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.ts b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.tsnew file mode 100644index 0000000000..906af8562a--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.ts@@ -0,0 +1,238 @@+import { theme } from '@actual-app/components/theme';+import type { TFunction } from 'i18next';++import { getColorScale } from '#components/reports/chart-theme';+import {+ getActiveSpendingPhase,+ resolveSpendingPhases,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type {+ MonteCarloContribution,+ MonteCarloPot,+ MonteCarloRunDetailRow,+ MonteCarloSpendingPhase,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';++export type MonteCarloCashflowSeriesKind =+ | 'pot'+ | 'contribution'+ | 'phase'+ | 'tax';++/** One stacked bar series of the cashflow chart */+export type MonteCarloCashflowSeries = {+ /** Identifies the series' entry in each data point's amounts */+ key: string;+ kind: MonteCarloCashflowSeriesKind;+ label: string;+ color: string;+};++/**+ * A headed section of the cashflow tooltip - e.g. "Withdrawals" with a+ * row per pot. A single-series group (Tax) sets listMembers false so+ * the heading row alone carries its value.+ */+export type MonteCarloCashflowTooltipGroup = {+ key: string;+ heading: string;+ series: MonteCarloCashflowSeries[];+ listMembers: boolean;+};++/** One charted year */+export type MonteCarloCashflowDataPoint = {+ year: number;+ age: number;+ /** A synthetic year after the plan ran out: spending with no funding */+ afterDepletion: boolean;+ /** 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 */+ inflowSeries: MonteCarloCashflowSeries[];+ /** Series stacked below zero: planned spending by phase, then tax */+ outflowSeries: MonteCarloCashflowSeries[];+ tooltipGroups: MonteCarloCashflowTooltipGroup[];+ /** Each year's total money in and total money out, for axis padding */+ stackExtents: number[];+};++type BuildMonteCarloCashflowChartInput = {+ /** The captured run to chart, one row per simulated year */+ rows: MonteCarloRunDetailRow[];+ pots: MonteCarloPot[];+ contributions: MonteCarloContribution[];+ spendingPhases: MonteCarloSpendingPhase[];+ /** The user's current age; a row's age is startAge + year - 1 */+ startAge: number;+ translate: TFunction;+};++function seriesKey(kind: MonteCarloCashflowSeriesKind, index: number) {+ return `${kind}${index}`;+}++/**+ * 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.+ */+export function buildMonteCarloCashflowChart({+ rows,+ pots,+ contributions,+ spendingPhases,+ startAge,+ translate,+}: BuildMonteCarloCashflowChartInput): MonteCarloCashflowChart {+ const colorScale = getColorScale('qualitative');+ const phases = resolveSpendingPhases(spendingPhases);+ const hasTax = rows.some(row => row.taxPaid !== 0);++ // 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 exhausted+ const 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],+ }));+ // 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' as const,+ label:+ contribution.name ||+ translate('Contribution {{number}}', {+ number: contributionIndex + 1,+ }),+ color:+ colorScale[+ (pots.length + contributionIndex) % colorScale.length+ ],+ },+ ]+ : [],+ );+ const phaseSeries: MonteCarloCashflowSeries[] = phases.map(+ (phase, phaseIndex) => {+ // Numbered as the spending editor lists them (the resolved list is+ // sorted by age); the default stand-in phase reads as Phase 1+ const configuredIndex = spendingPhases.indexOf(phase);+ return {+ key: seriesKey('phase', phaseIndex),+ kind: 'phase',+ label:+ phase.name ||+ translate('Phase {{number}}', {+ number: configuredIndex === -1 ? 1 : configuredIndex + 1,+ }),+ color:+ colorScale[colorScale.length - 1 - (phaseIndex % colorScale.length)],+ };+ },+ );+ const taxSeries: MonteCarloCashflowSeries = {+ key: seriesKey('tax', 0),+ kind: 'tax',+ label: translate('Tax'),+ color: theme.reportsNumberNegative,+ };++ const inflowSeries = [...potSeries, ...contributionSeries];+ const outflowSeries = [...phaseSeries, ...(hasTax ? [taxSeries] : [])];++ // Tax sits between Withdrawals and Spending so the deduction chain+ // reads in order: gross withdrawal, minus tax, leaves spending+ const tooltipGroups: MonteCarloCashflowTooltipGroup[] = [+ {+ key: 'withdrawals',+ heading: translate('Withdrawals'),+ series: potSeries,+ listMembers: true,+ },+ ...(contributionSeries.length > 0+ ? [+ {+ key: 'contributions',+ heading: translate('Contributions'),+ series: contributionSeries,+ listMembers: true,+ },+ ]+ : []),+ ...(hasTax+ ? [+ {+ key: 'tax',+ heading: translate('Tax'),+ series: [taxSeries],+ listMembers: false,+ },+ ]+ : []),+ {+ key: 'spending',+ heading: translate('Spending'),+ series: phaseSeries,+ listMembers: true,+ },+ ];++ const data = rows.map((row): MonteCarloCashflowDataPoint => {+ const age = startAge + row.year - 1;+ const amounts: Record<string, number> = {};+ potSeries.forEach((series, potIndex) => {+ amounts[series.key] = row.potWithdrawals[potIndex] ?? 0;+ });+ contributions.forEach((_, contributionIndex) => {+ amounts[seriesKey('contribution', contributionIndex)] =+ row.contributionAmounts[contributionIndex] ?? 0;+ });+ // The year's planned spend belongs to whichever phase is active+ const activePhase = getActiveSpendingPhase(phases, age);+ phaseSeries.forEach((series, phaseIndex) => {+ amounts[series.key] =+ phases[phaseIndex] === activePhase ? -row.plannedSpending : 0;+ });+ if (hasTax) {+ amounts[taxSeries.key] = -row.taxPaid;+ }+ return {+ year: row.year,+ age,+ afterDepletion: row.afterDepletion === true,+ amounts,+ };+ });++ const stackExtents = data.flatMap(point => [+ sumAmounts(point, inflowSeries),+ sumAmounts(point, outflowSeries),+ ]);++ return { data, inflowSeries, outflowSeries, tooltipGroups, stackExtents };+}++function sumAmounts(+ point: MonteCarloCashflowDataPoint,+ series: MonteCarloCashflowSeries[],+) {+ return series.reduce(+ (sum, entry) => sum + (point.amounts[entry.key] ?? 0),+ 0,+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/util/useMonteCarloTickFormatter.ts b/packages/desktop-client/src/components/reports/graphs/util/useMonteCarloTickFormatter.tsnew file mode 100644index 0000000000..07028df2a8--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/util/useMonteCarloTickFormatter.ts@@ -0,0 +1,25 @@+import { MAX_FORMATTABLE_AMOUNT } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { useFormat } from '#hooks/useFormat';+import { usePrivacyMode } from '#hooks/usePrivacyMode';++/**+ * Y-axis tick formatter shared by the Monte Carlo charts: redacted in+ * privacy mode, otherwise the amount without decimals. Recharts can+ * synthesize ticks beyond the (already clamped) data extremes, so ticks+ * are kept within what the formatter accepts.+ */+export function useMonteCarloTickFormatter() {+ const privacyMode = usePrivacyMode();+ const format = useFormat();++ return (tick: number) => {+ if (privacyMode) {+ return '...';+ }+ const safeTick = Math.min(+ Math.max(Math.round(tick), -MAX_FORMATTABLE_AMOUNT),+ MAX_FORMATTABLE_AMOUNT,+ );+ return `${format(safeTick, 'financial-no-decimals')}`;+ };+}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 452a8b9f8d..a940b83e8f 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@@ -19,6 +19,7 @@ import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';import { MobileBackButton } from '#components/mobile/MobileBackButton';import { MobilePageHeader, Page, PageHeader } from '#components/Page';import { PrivacyFilter } from '#components/PrivacyFilter';+import { MonteCarloCashflowGraph } from '#components/reports/graphs/MonteCarloCashflowGraph';import { MonteCarloGraph } from '#components/reports/graphs/MonteCarloGraph';import type { MonteCarloGraphView } from '#components/reports/graphs/MonteCarloGraphTooltip';import { MonteCarloHistogram } from '#components/reports/graphs/MonteCarloHistogram';@@ -26,11 +27,15 @@ import { LoadingIndicator } from '#components/reports/LoadingIndicator';import { MonteCarloConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloConfiguration';import { HISTORICAL_ANNUAL_RETURNS } from '#components/reports/reports/monte-carlo/monteCarloHistoricalReturns';import { MonteCarloRunDetailTable } from '#components/reports/reports/monte-carlo/MonteCarloRunDetailTable';-import { MonteCarloRunsTable } from '#components/reports/reports/monte-carlo/MonteCarloRunsTable';+import {+ getRunPercentileOptions,+ MonteCarloRunsTable,+} from '#components/reports/reports/monte-carlo/MonteCarloRunsTable';import {getMonteCarloHorizonYears,MONTE_CARLO_DEFAULTS,monteCarloConfigFromMeta,+ rankSimulationsWorstFirst,runMonteCarloSimulation,} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import type { MonteCarloConfig } from '#components/reports/reports/monte-carlo/monteCarloSimulation';@@ -62,7 +67,13 @@ export function MonteCarlo() {const [config, setConfig] = useState<MonteCarloConfig>(MONTE_CARLO_DEFAULTS);const [graphView, setGraphView] = useState<MonteCarloGraphView>('all');- const [resultsView, setResultsView] = useState<'chart' | 'runs'>('chart');+ const [resultsView, setResultsView] = useState<'chart' | 'cashflow' | 'runs'>(+ 'chart',+ );+ // Which run the cashflow view charts, as a percentile of the worst-first+ // ranking (0 = worst run, 1 = best run) - the runs table's Jump to+ // percentiles, so both land on the same runs+ const [cashflowPercentile, setCashflowPercentile] = useState(0.5);const [showTodaysMoney, setShowTodaysMoney] = useState(true);// A selected run refers to a specific simulation, so the selection is// stored with the config it belongs to and silently expires when the@@ -160,15 +171,44 @@ export function MonteCarlo() {};const result = runMonteCarloSimulation(simulationParams);+ // The cashflow view charts one run picked by percentile of the same+ // worst-first ranking the runs table shows+ let cashflowRunIndex: number | null = null;+ if (resultsView === 'cashflow') {+ const rankedRunIndices = rankSimulationsWorstFirst(+ result.endingBalances,+ result.depletionYearBySimulation,+ );+ const scenarioRank = Math.round(+ cashflowPercentile * (result.simulationCount - 1),+ );+ cashflowRunIndex = rankedRunIndices[scenarioRank];+ }++ // The run whose year-by-year detail is on screen: the cashflow view's+ // scenario, or the drill-in's selection from the runs table+ const detailRunIndex =+ resultsView === 'cashflow' ? cashflowRunIndex : selectedRunIndex;+// Runs are seeded, so re-running with a capture index reproduces the// selected run exactly; only computed while a run is being inspectedconst runDetailRows =- selectedRunIndex != null+ detailRunIndex != null? runMonteCarloSimulation({...simulationParams,- captureRunDetail: selectedRunIndex,+ captureRunDetail: detailRunIndex,}).runDetail: null;+ // After a failure the capture continues with synthetic unfunded years+ // for the cashflow chart; the year-by-year table ends at the failure+ const fundedRunDetailRows =+ runDetailRows?.filter(row => !row.afterDepletion) ?? null;+ const cashflowGraphProps = {+ pots: resolvedConfig.pots,+ contributions: resolvedConfig.contributions,+ spendingPhases: resolvedConfig.spendingPhases,+ startAge: config.currentAge,+ };// The age the simulation actually runs to (differs from targetAge only// when the configured ages produce a clamped horizon)@@ -409,6 +449,8 @@ export function MonteCarlo() {<Text style={{ ...styles.mediumText, fontWeight: 600 }}>{resultsView === 'chart' ? (<Trans>Portfolio performance</Trans>+ ) : resultsView === 'cashflow' ? (+ <Trans>Cashflow</Trans>) : (<Trans>Simulation runs</Trans>)}@@ -420,6 +462,12 @@ export function MonteCarlo() {><Trans>Chart</Trans></ModeButton>+ <ModeButton+ selected={resultsView === 'cashflow'}+ onSelect={() => setResultsView('cashflow')}+ >+ <Trans>Cashflow</Trans>+ </ModeButton><ModeButtonselected={resultsView === 'runs'}onSelect={() => setResultsView('runs')}@@ -443,6 +491,14 @@ export function MonteCarlo() {style={{ width: 280 }}/>)}+ {resultsView === 'cashflow' && (+ <Select+ value={String(cashflowPercentile)}+ onChange={value => setCashflowPercentile(Number(value))}+ options={getRunPercentileOptions(t)}+ style={{ width: 200 }}+ />+ )}</View>{resultsView === 'chart' ? (<>@@ -476,15 +532,46 @@ export function MonteCarlo() {style={{ height: '100%', flex: 1 }}/></>- ) : selectedRunIndex != null && runDetailRows != null ? (+ ) : resultsView === 'cashflow' ? (+ runDetailRows != null && (+ <>+ <Text+ style={{+ color: theme.pageText,+ marginBottom: 10,+ flexShrink: 0,+ }}+ >+ <Trans>+ Money flowing in and out each year of this simulated run:+ withdrawals and contributions above zero, planned spending+ and tax below.+ </Trans>+ </Text>+ <MonteCarloCashflowGraph+ rows={runDetailRows}+ {...cashflowGraphProps}+ />+ </>+ )+ ) : selectedRunIndex != null &&+ runDetailRows != null &&+ fundedRunDetailRows != null ? (<MonteCarloRunDetailTable- rows={runDetailRows}+ rows={fundedRunDetailRows}pots={resolvedConfig.pots}simulationIndex={selectedRunIndex}simulationCount={result.simulationCount}startAge={config.currentAge}hasContributions={config.contributions.length > 0}withdrawalRule={resolvedConfig.withdrawalRule}+ cashflowGraph={+ <MonteCarloCashflowGraph+ rows={runDetailRows}+ {...cashflowGraphProps}+ style={{ marginBottom: 15 }}+ />+ }onBack={() => setSelectedRun(null)}/>) : (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 f787c91cea..ad066c0da6 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@@ -1,4 +1,5 @@import { Fragment, useState } from 'react';+import type { ReactNode } from 'react';import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';@@ -55,6 +56,8 @@ type MonteCarloRunDetailTableProps = {hasContributions: boolean;/** The configured rule, quoted in the per-year explanations */withdrawalRule: MonteCarloWithdrawalRuleConfig;+ /** Rendered between the header row and the table - the cashflow chart */+ cashflowGraph?: ReactNode;onBack: () => void;};@@ -66,6 +69,7 @@ export function MonteCarloRunDetailTable({startAge,hasContributions,withdrawalRule,+ cashflowGraph,onBack,}: MonteCarloRunDetailTableProps) {const { t } = useTranslation();@@ -321,6 +325,8 @@ export function MonteCarloRunDetailTable({</Button></View>+ {cashflowGraph}+<Text style={{ fontSize: 13, color: theme.pageText, marginBottom: 10 }}><PrivacyFilter><FinancialText as="span">{getTotalsSentence()}</FinancialText>diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsxindex 554a3d25a5..3248150c04 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx@@ -9,6 +9,7 @@ import { View } from '@actual-app/components/view';import { FinancialText } from '#components/FinancialText';import { PrivacyFilter } from '#components/PrivacyFilter';+import { rankSimulationsWorstFirst } from '#components/reports/reports/monte-carlo/monteCarloSimulation';import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';import { useFormat } from '#hooks/useFormat';@@ -16,6 +17,23 @@ const PAGE_SIZE = 20;type SortOrder = 'worst-first' | 'best-first';+/**+ * The percentiles of the worst-first ranking a user can jump to (0 =+ * worst run, 1 = best run), as Select options. Shared with the cashflow+ * chart's scenario picker so both land on the same runs.+ */+export function getRunPercentileOptions(+ translate: (key: string) => string,+): Array<[string, string]> {+ return [+ ['0', translate('Worst run')],+ ['0.25', translate('25th percentile')],+ ['0.5', translate('Median run')],+ ['0.75', translate('75th percentile')],+ ['1', translate('Best run')],+ ];+}+type MonteCarloRunsTableProps = {endingBalances: Float64Array;depletionYearBySimulation: Int32Array;@@ -52,34 +70,10 @@ export function MonteCarloRunsTable({setHighlightedRank(rank);}- // Rank every run: by ending balance, using the depletion year to order- // the failed runs (which all end at zero) among themselves- const rankedIndices = Array.from(- { length: simulationCount },- (_, index) => index,+ const rankedIndices = rankSimulationsWorstFirst(+ endingBalances,+ depletionYearBySimulation,);- rankedIndices.sort((runA, runB) => {- const balanceDiff = endingBalances[runA] - endingBalances[runB];- if (balanceDiff !== 0) {- return balanceDiff;- }- // Survivors (-1) rank after any depleted run; explicit branches so- // two survivors compare as a tie instead of Infinity - Infinity- const runADepletionYear = depletionYearBySimulation[runA];- const runBDepletionYear = depletionYearBySimulation[runB];- const runASurvived = runADepletionYear === -1;- const runBSurvived = runBDepletionYear === -1;- if (runASurvived && runBSurvived) {- return 0;- }- if (runASurvived) {- return 1;- }- if (runBSurvived) {- return -1;- }- return runADepletionYear - runBDepletionYear;- });if (sortOrder === 'best-first') {rankedIndices.reverse();}@@ -250,14 +244,7 @@ export function MonteCarloRunsTable({jumpToPercentile(Number(value));}}}- options={[- ['', t('Jump to…')],- ['0', t('Worst run')],- ['0.25', t('25th percentile')],- ['0.5', t('Median run')],- ['0.75', t('75th percentile')],- ['1', t('Best run')],- ]}+ options={[['', t('Jump to…')], ...getRunPercentileOptions(t)]}style={{ width: 170 }}/><Buttondiff --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 7847db62f9..60bce62d04 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@@ -540,6 +540,231 @@ describe('runMonteCarloSimulation', () => {]);});+ it('captures the planned spending, inflation-adjusted, on each row', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ horizonYears: 3,+ inflationMean: 0.1,+ inflationStdDev: 0,+ captureRunDetail: 0,+ },+ { startingBalance: 1_000_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.plannedSpending)).toEqual([+ 10_000, 11_000, 12_100,+ ]);+ // Fully funded and untaxed, so the withdrawal matches the plan+ expect(rows.map(row => row.withdrawal)).toEqual([10_000, 11_000, 12_100]);+ });++ it('captures each contribution separately on the rows', () => {+ // One flat and one inflation-adjusted contribution into the same pot,+ // with different age windows+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 0,+ horizonYears: 3,+ inflationMean: 0.1,+ inflationStdDev: 0,+ contributions: [+ makeContribution({+ id: 'contribution-1',+ annualAmount: 10_000,+ adjustsWithInflation: false,+ }),+ makeContribution({+ id: 'contribution-2',+ annualAmount: 5_000,+ fromAge: 61,+ adjustsWithInflation: true,+ }),+ ],+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ // Age 60: only the flat one; 61: 5,000 x 1.1; 62: 5,000 x 1.21+ expect(rows.map(row => row.contributionAmounts)).toEqual([+ [10_000, 0],+ [10_000, 5_500],+ [10_000, 6_050],+ ]);+ // Each year's parts reconcile with the row's contribution total+ for (const row of rows) {+ const partsTotal = row.contributionAmounts.reduce(+ (sum, amount) => sum + amount,+ 0,+ );+ expect(partsTotal).toBe(row.contributions);+ }+ });++ it('captures zero planned spending through accumulation phases', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ spendingPhases: [+ { id: 'phase-1', name: '', fromAge: null, annualWithdrawal: 0 },+ { id: 'phase-2', name: '', fromAge: 62, annualWithdrawal: 24_000 },+ ],+ horizonYears: 4,+ captureRunDetail: 0,+ },+ { startingBalance: 1_000_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ // Ages 60-61 accumulate, ages 62-63 spend+ expect(result.runDetail!.map(row => row.plannedSpending)).toEqual([+ 0, 0, 24_000, 24_000,+ ]);+ });++ it('planned spending stays below the withdrawal 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+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 4_000,+ horizonYears: 2,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ minimumWithdrawal: 4_000,+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: -0.5, returnStdDev: 0 },+ ),+ );++ const cutYear = result.runDetail![1];+ expect(cutYear.minimumApplied).toBe(true);+ if (cutYear.ruleExplanation?.kind !== 'factor') {+ throw new Error('expected a factor rule explanation');+ }+ expect(cutYear.plannedSpending).toBe(cutYear.ruleExplanation.adjusted);+ expect(cutYear.withdrawal).toBe(4_000);+ expect(cutYear.plannedSpending).toBeLessThan(cutYear.withdrawal);+ });++ it('planned spending stays above the withdrawal on a shortfall year', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ horizonYears: 2,+ captureRunDetail: 0,+ },+ { startingBalance: 5_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const shortfallYear = result.runDetail![0];+ expect(shortfallYear.plannedSpending).toBe(10_000);+ expect(shortfallYear.withdrawal).toBe(5_000);+ expect(shortfallYear.endBalance).toBe(0);++ // The year after the failure is still captured - as a synthetic+ // unfunded row for the cashflow chart+ const unfundedYear = result.runDetail![1];+ expect(unfundedYear.afterDepletion).toBe(true);+ expect(unfundedYear.plannedSpending).toBe(10_000);+ expect(unfundedYear.withdrawal).toBe(0);+ expect(unfundedYear.endBalance).toBe(0);+ });++ it('captures the unfunded years after a failure at frozen prices', () => {+ // Fails in year 2; the remaining years chart the plan's spending at+ // the price level reached by the failure year, since no further+ // inflation is realized on a dead run+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ horizonYears: 4,+ inflationMean: 0.1,+ inflationStdDev: 0,+ captureRunDetail: 0,+ },+ { startingBalance: 15_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows).toHaveLength(4);+ // Year 1 spends 10,000; year 2 needs 11,000 but only 5,000 remains+ expect(rows.map(row => row.afterDepletion ?? false)).toEqual([+ false,+ false,+ true,+ true,+ ]);+ expect(rows.map(row => row.withdrawal)).toEqual([10_000, 5_000, 0, 0]);+ // The failure year still realizes its own inflation (cumulative+ // 1.21 after year 2); the unfunded years stay at that level rather+ // than compounding on+ expect(rows.map(row => row.plannedSpending)).toEqual([+ 10_000, 11_000, 12_100, 12_100,+ ]);+ // No inflation is realized on synthetic years+ expect(rows[2].inflation).toBeNull();+ expect(rows[3].inflation).toBeNull();+ // Per-pot arrays keep their shape+ expect(rows[3].potWithdrawals).toEqual([0]);+ expect(rows[3].potBalances).toEqual([0]);+ });++ it('keeps the rule-adjusted plan on the unfunded years after a failure', () => {+ // Guardrails keeps cutting spending as the crash drives the withdrawal+ // rate up, until the pot can't fund even the cut amount. The tail must+ // carry that running cut forward, not jump back to the full schedule+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 4_000,+ horizonYears: 12,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ captureRunDetail: 0,+ },+ { startingBalance: 100_000, expectedReturnMean: -0.5, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ const fundedRows = rows.filter(row => !row.afterDepletion);+ const failureRow = fundedRows[fundedRows.length - 1];+ const unfundedRows = rows.filter(row => row.afterDepletion);+ expect(unfundedRows.length).toBeGreaterThan(0);+ // The failure year's plan already carried several compounded cuts+ expect(failureRow.plannedSpending).toBeLessThan(4_000);+ for (const row of unfundedRows) {+ expect(row.plannedSpending).toBe(failureRow.plannedSpending);+ }+ });++ it('captures no synthetic rows for a surviving run', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 1_000, horizonYears: 5, captureRunDetail: 0 },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.runDetail!).toHaveLength(5);+ expect(+ result.runDetail!.every(row => row.afterDepletion === undefined),+ ).toBe(true);+ });+it('keeps custom pots on normal draws in historical modes', () => {// An absurd history that would explode the balance if it were usedconst historical = runMonteCarloSimulation(@@ -1442,10 +1667,13 @@ describe('runMonteCarloSimulation', () => {expect(row.growth).toBe(Math.round(balance - afterWithdrawal));}- // Rows stop at the depletion year- const lastRow = rows![rows!.length - 1];- expect(lastRow.year).toBe(result.medianDepletionYear);- expect(lastRow.endBalance).toBe(0);+ // Funded rows stop at the depletion year; the capture continues to+ // the horizon with synthetic unfunded rows for the cashflow chart+ const fundedRows = rows!.filter(row => !row.afterDepletion);+ const lastFundedRow = fundedRows[fundedRows.length - 1];+ expect(lastFundedRow.year).toBe(result.medianDepletionYear);+ expect(lastFundedRow.endBalance).toBe(0);+ expect(rows!).toHaveLength(30);});it('replays a volatile run identically to the original', () => {@@ -1466,8 +1694,10 @@ describe('runMonteCarloSimulation', () => {Math.round(original.endingBalances[simulationIndex]),);} else {- expect(rows).toHaveLength(depletionYear);- expect(rows[rows.length - 1].endBalance).toBe(0);+ expect(rows).toHaveLength(original.horizonYears);+ const fundedRows = rows.filter(row => !row.afterDepletion);+ expect(fundedRows).toHaveLength(depletionYear);+ expect(fundedRows[fundedRows.length - 1].endBalance).toBe(0);}});@@ -1496,7 +1726,8 @@ describe('runMonteCarloSimulation', () => {);const rows = result.runDetail!;- const failureRow = rows[rows.length - 1];+ const fundedRows = rows.filter(row => !row.afterDepletion);+ const failureRow = fundedRows[fundedRows.length - 1];// y1 70, y2 40, y3 10 accessible; year 4 fails with 10 reachableexpect(failureRow.year).toBe(4);expect(failureRow.withdrawal).toBe(10);@@ -1746,8 +1977,10 @@ describe('runMonteCarloSimulation', () => {expect(result.successRate).toBe(0);expect(result.medianDepletionYear).toBe(10);+ // 10 funded years plus 2 synthetic unfunded years to the horizonconst rows = result.runDetail!;- expect(rows).toHaveLength(10);+ expect(rows).toHaveLength(12);+ expect(rows.filter(row => !row.afterDepletion)).toHaveLength(10);for (const row of rows.slice(0, 9)) {expect(row.withdrawal).toBe(10_000);expect(row.taxPaid).toBe(2_000);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 b883a51389..3bbd8d45a6 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@@ -203,6 +203,40 @@ export function sortMonteCarloSpendingPhases();}+/**+ * The phases the engine actually runs: sorted by starting age, with a+ * default phase standing in when none are configured. Resolve once and+ * pass the result to getActiveSpendingPhase.+ */+export function resolveSpendingPhases(+ phases: MonteCarloSpendingPhase[],+): MonteCarloSpendingPhase[] {+ return phases.length+ ? sortMonteCarloSpendingPhases(phases)+ : [createMonteCarloSpendingPhase('phase-1')];+}++/**+ * The phase active at the given age from a resolved (sorted) list: the+ * last phase that has started, or the earliest phase before any has.+ * The engine's planned-spending schedule and the cashflow chart's phase+ * attribution both resolve through here so they can't disagree.+ */+export function getActiveSpendingPhase(+ resolvedPhases: MonteCarloSpendingPhase[],+ age: number,+): MonteCarloSpendingPhase {+ let active = resolvedPhases[0];+ for (const phase of resolvedPhases) {+ if (phase.fromAge == null || phase.fromAge <= age) {+ active = phase;+ } else {+ break;+ }+ }+ return active;+}+/** One recurring yearly contribution into a pot over an age window */export type MonteCarloContribution = {id: string;@@ -569,6 +603,12 @@ export type MonteCarloRunDetailRow = {startBalance: number;/** Amount actually withdrawn (the accessible remainder on failure) */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+ */+ plannedSpending: number;/** Investment gain/loss applied after the withdrawal */growth: number;endBalance: number;@@ -584,6 +624,11 @@ export type MonteCarloRunDetailRow = {contributions: number;/** Contribution each pot received at the start of the year, same order */potContributions: number[];+ /**+ * Deposit each configured contribution made this year, in the order the+ * contributions are configured (zero outside its age window)+ */+ contributionAmounts: number[];/** How much of this year's withdrawal each pot funded (gross), same order */potWithdrawals: number[];/**@@ -621,6 +666,14 @@ export type MonteCarloRunDetailRow = {* their access age - the plan failed despite this locked balance*/inaccessibleBalance?: number;+ /**+ * A synthetic year after the plan ran out: nothing was withdrawn or+ * earned, and plannedSpending records what the plan still called for+ * (at the failure year's price level - inflation stops being realized+ * once the run is depleted). The cashflow chart plots these; the run+ * detail table hides them.+ */+ afterDepletion?: boolean;};export type MonteCarloPercentileBand = {@@ -712,6 +765,45 @@ function percentileOfSorted(sorted: Float64Array, percentile: number) {return sorted[lower] * (1 - weight) + sorted[upper] * weight;}+/**+ * Every simulation index ranked worst-first: by ending balance, using the+ * depletion year to order the failed runs (which all end at zero) among+ * themselves. Shared by the runs table and the cashflow scenario picker so+ * percentile jumps land on the same runs.+ */+export function rankSimulationsWorstFirst(+ endingBalances: Float64Array,+ depletionYearBySimulation: Int32Array,+): number[] {+ const rankedIndices = Array.from(+ { length: endingBalances.length },+ (_, index) => index,+ );+ rankedIndices.sort((runA, runB) => {+ const balanceDiff = endingBalances[runA] - endingBalances[runB];+ if (balanceDiff !== 0) {+ return balanceDiff;+ }+ // Survivors (-1) rank after any depleted run; explicit branches so+ // two survivors compare as a tie instead of Infinity - Infinity+ const runADepletionYear = depletionYearBySimulation[runA];+ const runBDepletionYear = depletionYearBySimulation[runB];+ const runASurvived = runADepletionYear === -1;+ const runBSurvived = runBDepletionYear === -1;+ if (runASurvived && runBSurvived) {+ return 0;+ }+ if (runASurvived) {+ return 1;+ }+ if (runBSurvived) {+ return -1;+ }+ return runADepletionYear - runBDepletionYear;+ });+ return rankedIndices;+}+/*** Runs the drawdown simulation with i.i.d. normal annual returns.*@@ -1044,21 +1136,15 @@ export function runMonteCarloSimulation(// The planned spending path in today's money: the active phase's amount// for every year. Inflation is applied per simulation, since each replay// draws its own inflation path when volatility is set.- const spendingPhases = params.spendingPhases.length- ? sortMonteCarloSpendingPhases(params.spendingPhases)- : [createMonteCarloSpendingPhase('phase-1')];+ const spendingPhases = resolveSpendingPhases(params.spendingPhases);const plannedTodayByYear = new Float64Array(horizonYears + 1);for (let year = 1; year <= horizonYears; year++) {const age = params.currentAge + year - 1;- let amount = clamp(spendingPhases[0].annualWithdrawal, 0, MAX_AMOUNT);- for (const phase of spendingPhases) {- if (phase.fromAge == null || phase.fromAge <= age) {- amount = clamp(phase.annualWithdrawal, 0, MAX_AMOUNT);- } else {- break;- }- }- plannedTodayByYear[year] = amount;+ plannedTodayByYear[year] = clamp(+ getActiveSpendingPhase(spendingPhases, age).annualWithdrawal,+ 0,+ MAX_AMOUNT,+ );}// The first year with planned spending - withdrawal rules anchor here@@ -1072,22 +1158,34 @@ export function runMonteCarloSimulation(}}- // Planned contributions per pot per year, in today's money - split into- // an inflation-adjusted and a flat portion so a year's deposit is+ // 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. Contributions into unknown pots (e.g. a pot that was- // deleted) are ignored.+ // 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.+ const 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 yearlet lastContributionYear = 0;let hasContributions = false;- for (const contribution of params.contributions) {+ for (+ let contributionIndex = 0;+ contributionIndex < contributionCount;+ contributionIndex+++ ) {+ 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) {@@ -1101,10 +1199,14 @@ export function runMonteCarloSimulation(if (contribution.toAge != null && age > contribution.toAge) {continue;}- const target = contribution.adjustsWithInflation+ const byPot = contribution.adjustsWithInflation? adjustedContributionsByYear: flatContributionsByYear;- target[year][potIndex] += amount;+ const byContribution = contribution.adjustsWithInflation+ ? adjustedContributionAmountsByYear+ : flatContributionAmountsByYear;+ byPot[year][potIndex] += amount;+ byContribution[year][contributionIndex] = amount;hasContributions = true;if (year > lastContributionYear) {lastContributionYear = year;@@ -1226,12 +1328,32 @@ 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++) {@@ -1406,6 +1528,13 @@ 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// only offers it alongside a rule); with no rule active the planned// spending is taken as-is. It guards against rule-driven cuts, so@@ -1707,6 +1836,7 @@ export function runMonteCarloSimulation(const base = {year,startBalance,+ plannedSpending: emit(plannedSpendingThisYear, startDeflator),...(capturedRuleExplanation != null && {ruleExplanation: capturedRuleExplanation,}),@@ -1719,6 +1849,11 @@ export function runMonteCarloSimulation(startDeflator,contributions,),+ contributionAmounts: emitParts(+ capturedContributionAmounts,+ startDeflator,+ contributions,+ ),withdrawal,taxPaid,potWithdrawals: emitParts(@@ -1789,8 +1924,46 @@ export function runMonteCarloSimulation(balancesByYear[year][simulationIndex] = toSafeAmount(total * endDeflator,);+ } else if (runDetail && simulationIndex === captureIndex) {+ // 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)+ const frozenDeflator = deflate ? 1 / cumulativeInflation : 1;+ runDetail.push({+ year,+ afterDepletion: true,+ startBalance: 0,+ plannedSpending: toSafeAmount(+ Math.round(+ plannedTodayByYear[year] *+ adjustmentFactor *+ cumulativeInflation *+ frozenDeflator,+ ),+ ),+ withdrawal: 0,+ growth: 0,+ endBalance: 0,+ potBalances: new Array<number>(potCount).fill(0),+ potStartBalances: new Array<number>(potCount).fill(0),+ inflation: null,+ contributions: 0,+ potContributions: new Array<number>(potCount).fill(0),+ contributionAmounts: new Array<number>(contributionCount).fill(0),+ potWithdrawals: new Array<number>(potCount).fill(0),+ potTaxes: new Array<number>(potCount).fill(0),+ potTaxables: new Array<number>(potCount).fill(0),+ taxPaid: 0,+ feesPaid: 0,+ potFees: new Array<number>(potCount).fill(0),+ potReturns: new Array<number | null>(potCount).fill(null),+ });}- // Post-depletion years stay at zero (total is 0 here)+ // Post-depletion years otherwise stay at zero (total is 0 here)}withdrawnTotals[simulationIndex] = withdrawnSum;diff --git a/packages/docs/docs/experimental/monte-carlo-analysis.md b/packages/docs/docs/experimental/monte-carlo-analysis.mdindex 2d90fadafb..41b72f6b5b 100644--- a/packages/docs/docs/experimental/monte-carlo-analysis.md+++ b/packages/docs/docs/experimental/monte-carlo-analysis.md@@ -180,6 +180,23 @@ The chart shows your total balance from your current age to your target age - buThe dropdown above the chart switches views. **Single worst run** shows the one unluckiest replay in full. The **Worst-case**, **Pessimistic**, **Median** and **Optimistic** views each trace a single percentile - for example, the pessimistic line is the level that 70% of replays stayed above.+### The Cashflow Chart++++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:++- **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.++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.++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.++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.+### When Did the Pot Run Out?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.pngnew file mode 100644index 0000000000..d6f38ec4bdBinary files /dev/null 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 f480100df6..f2337dc59c 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-overview.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.pngindex c98fea0294..c5d13585e9 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-run.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.pngindex 4c63ab23b2..432bc32cfd 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/upcoming-release-notes/monte-carlo-cashflow-chart.md b/upcoming-release-notes/monte-carlo-cashflow-chart.mdnew file mode 100644index 0000000000..8b31407b2c--- /dev/null+++ b/upcoming-release-notes/monte-carlo-cashflow-chart.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MikesGlitch]+---++Add a cashflow chart to the Monte Carlo report showing yearly money in and out of your pots for a chosen scenario