A local-first personal finance app
:bar_chart: Monte Carlo Analysis report (#8551)
Michael Clarkc274f08a1f9f
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex b24b024ff8..d0b86bae58 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -64,6 +64,10 @@"#components/reports/numberFormatter": "./src/components/reports/numberFormatter.ts","#components/reports/ReportOptions": "./src/components/reports/ReportOptions.ts","#components/reports/reportRanges": "./src/components/reports/reportRanges.ts",+ "#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/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","#components/reports/spreadsheets/cash-flow-spreadsheet": "./src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx",diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsxindex 112d8276f9..08a0cd80f4 100644--- a/packages/desktop-client/src/components/reports/Overview.tsx+++ b/packages/desktop-client/src/components/reports/Overview.tsx@@ -64,6 +64,7 @@ import { CustomReportListCards } from './reports/CustomReportListCards';import { FormulaCard } from './reports/FormulaCard';import { MarkdownCard } from './reports/MarkdownCard';import { MissingReportCard } from './reports/MissingReportCard';+import { MonteCarloCard } from './reports/monte-carlo/MonteCarloCard';import { NetWorthCard } from './reports/NetWorthCard';import { SankeyCard } from './reports/SankeyCard';import { SpendingCard } from './reports/SpendingCard';@@ -114,6 +115,7 @@ export function Overview({ dashboard }: OverviewProps) {const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';const budgetAnalysisReportEnabled = useFeatureFlag('budgetAnalysisReport');const balanceForecastReportEnabled = useFeatureFlag('balanceForecastReport');+ const monteCarloReportEnabled = useFeatureFlag('monteCarloReport');const formulaMode = useFeatureFlag('formulaMode');@@ -612,6 +614,14 @@ export function Overview({ dashboard }: OverviewProps) {},]: []),+ ...(monteCarloReportEnabled+ ? [+ {+ name: 'monte-carlo-card' as const,+ text: t('Monte Carlo analysis'),+ },+ ]+ : []),{name: 'markdown-card' as const,text: t('Text widget'),@@ -912,6 +922,16 @@ export function Overview({ dashboard }: OverviewProps) {onMetaChange(item, newMeta)}/>+ ) : widget.type === 'monte-carlo-card' &&+ monteCarloReportEnabled ? (+ <MonteCarloCard+ widgetId={item.i}+ isEditing={isEditing}+ meta={widget.meta}+ onMetaChange={newMeta =>+ onMetaChange(item, newMeta)+ }+ />) : null}</ErrorBoundary></div>diff --git a/packages/desktop-client/src/components/reports/ReportRouter.tsx b/packages/desktop-client/src/components/reports/ReportRouter.tsxindex d33a184405..670e3696d8 100644--- a/packages/desktop-client/src/components/reports/ReportRouter.tsx+++ b/packages/desktop-client/src/components/reports/ReportRouter.tsx@@ -13,6 +13,7 @@ import { CashFlow } from './reports/CashFlow';import { Crossover } from './reports/Crossover';import { CustomReport } from './reports/CustomReport';import { Formula } from './reports/Formula';+import { MonteCarlo } from './reports/monte-carlo/MonteCarlo';import { NetWorth } from './reports/NetWorth';import { Sankey } from './reports/Sankey';import { Spending } from './reports/Spending';@@ -35,6 +36,7 @@ export function ReportRouter() {const balanceForecastReportEnabled = useFeatureFlag('balanceForecastReport');const budgetAnalysisReportEnabled = useFeatureFlag('budgetAnalysisReport');const sankeyReportEnabled = useFeatureFlag('sankeyReport');+ const monteCarloReportEnabled = useFeatureFlag('monteCarloReport');return (<Routes>@@ -224,6 +226,26 @@ export function ReportRouter() {/></>)}+ {monteCarloReportEnabled && (+ <>+ <Route+ path="/monte-carlo"+ element={+ <ReportBoundary>+ <MonteCarlo />+ </ReportBoundary>+ }+ />+ <Route+ path="/monte-carlo/:id"+ element={+ <ReportBoundary>+ <MonteCarlo />+ </ReportBoundary>+ }+ />+ </>+ )}{sankeyReportEnabled && (<><Routediff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsxnew file mode 100644index 0000000000..97f541469a--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloGraph.tsx@@ -0,0 +1,167 @@+import type { CSSProperties } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import {+ Area,+ CartesianGrid,+ ComposedChart,+ Line,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts';++import { useRechartsAnimation } from '#components/reports/chart-theme';+import { Container } from '#components/reports/Container';+import type {+ FanChartDataPoint,+ MonteCarloGraphView,+} from '#components/reports/graphs/MonteCarloGraphTooltip';+import {+ MonteCarloGraphTooltip,+ 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 type { MonteCarloPercentileBand } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { useFormat } from '#hooks/useFormat';+import { usePrivacyMode } from '#hooks/usePrivacyMode';++type MonteCarloGraphProps = {+ style?: CSSProperties;+ percentileBands: MonteCarloPercentileBand[];+ /** The user's current age; the x-axis shows startAge + year */+ startAge: number;+ worstRunPath?: number[];+ view?: MonteCarloGraphView;+ compact?: boolean;+ showTooltip?: boolean;+};++export function MonteCarloGraph({+ style,+ percentileBands,+ startAge,+ worstRunPath,+ view = 'all',+ compact = false,+ showTooltip = true,+}: MonteCarloGraphProps) {+ const privacyMode = usePrivacyMode();+ const format = useFormat();+ const animationProps = useRechartsAnimation({ animationDuration: 1000 });++ const data: FanChartDataPoint[] = percentileBands.map(band => ({+ year: band.year,+ age: startAge + band.year,+ band80: [band.p10, band.p90],+ band50: [band.p25, band.p75],+ p5: band.p5,+ p10: band.p10,+ p25: band.p25,+ p30: band.p30,+ p50: band.p50,+ p70: band.p70,+ p75: band.p75,+ p90: band.p90,+ 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 (+ <Container+ style={{+ ...style,+ ...(compact && { height: 'auto' }),+ }}+ >+ {(width, height) => (+ <ComposedChart+ width={width}+ height={height}+ data={data}+ margin={{+ top: compact ? 0 : 15,+ right: 0,+ left: compact+ ? 0+ : computePadding(+ data.map(point => point.p90),+ value => format(value, 'financial-no-decimals'),+ ),+ bottom: compact ? 0 : 10,+ }}+ >+ {!compact && <CartesianGrid strokeDasharray="3 3" />}+ <XAxis+ dataKey="age"+ hide={compact}+ tick={{ fill: theme.pageText }}+ tickLine={{ stroke: theme.pageText }}+ />+ <YAxis+ hide={compact}+ tickFormatter={tickFormatter}+ tick={{ fill: theme.pageText }}+ tickLine={{ stroke: theme.pageText }}+ />+ {showTooltip && (+ <Tooltip+ content={<MonteCarloGraphTooltip view={view} />}+ isAnimationActive={false}+ />+ )}+ {view === 'all' ? (+ <>+ <Area+ type="monotone"+ dataKey="band80"+ stroke="none"+ fill={theme.reportsChartFill}+ fillOpacity={0.15}+ {...animationProps}+ />+ <Area+ type="monotone"+ dataKey="band50"+ stroke="none"+ fill={theme.reportsChartFill}+ fillOpacity={0.3}+ {...animationProps}+ />+ <Line+ type="monotone"+ dataKey="p50"+ dot={false}+ stroke={theme.reportsChartFill}+ strokeWidth={2}+ {...animationProps}+ />+ </>+ ) : (+ <Area+ type="monotone"+ dataKey={VIEW_DATA_KEYS[view]}+ stroke={theme.reportsChartFill}+ strokeWidth={2}+ fill={theme.reportsChartFill}+ fillOpacity={0.08}+ {...animationProps}+ />+ )}+ </ComposedChart>+ )}+ </Container>+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloGraphTooltip.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloGraphTooltip.tsxnew file mode 100644index 0000000000..2ec6dd79aa--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloGraphTooltip.tsx@@ -0,0 +1,133 @@+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 { useFormat } from '#hooks/useFormat';++export type MonteCarloGraphView =+ | 'all'+ | 'single-worst'+ | 'worst-case'+ | 'pessimistic'+ | 'median'+ | 'optimistic';++export type FanChartDataPoint = {+ year: number;+ age: number;+ band80: [number, number];+ band50: [number, number];+ p5: number;+ p10: number;+ p25: number;+ p30: number;+ p50: number;+ p70: number;+ p75: number;+ p90: number;+ worstRun?: number;+};++// Single source of truth for which data point each focused view plots -+// the graph draws this key and the tooltip reads the same one+export const VIEW_DATA_KEYS = {+ 'single-worst': 'worstRun',+ 'worst-case': 'p5',+ pessimistic: 'p30',+ median: 'p50',+ optimistic: 'p70',+} as const satisfies Record<+ Exclude<MonteCarloGraphView, 'all'>,+ keyof FanChartDataPoint+>;++type PayloadItem = {+ payload: FanChartDataPoint;+};++type MonteCarloGraphTooltipProps = {+ active?: boolean;+ payload?: PayloadItem[];+ view?: MonteCarloGraphView;+};++export function MonteCarloGraphTooltip({+ active,+ payload,+ view = 'all',+}: MonteCarloGraphTooltipProps) {+ const { t } = useTranslation();+ const format = useFormat();++ if (active && payload && payload.length) {+ const point = payload[0].payload;+ const singleViewLabels: Record<+ Exclude<MonteCarloGraphView, 'all'>,+ string+ > = {+ 'single-worst': t('Single worst run:'),+ 'worst-case': t('Worst-case (5th percentile):'),+ pessimistic: t('Pessimistic (30th percentile):'),+ median: t('Median (50th percentile):'),+ optimistic: t('Optimistic (70th percentile):'),+ };+ const rows =+ view === 'all'+ ? [+ { label: t('Best 10%:'), value: point.p90 },+ { label: t('Top quartile:'), value: point.p75 },+ { label: t('Median:'), value: point.p50 },+ { label: t('Bottom quartile:'), value: point.p25 },+ { label: t('Worst 10%:'), value: point.p10 },+ ]+ : [+ {+ label: singleViewLabels[view],+ value: point[VIEW_DATA_KEYS[view]] ?? 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>+ {point.year === 0+ ? t('Start (age {{age}})', { age: point.age })+ : t('Age {{age}}', { age: point.age })}+ </strong>+ </div>+ <div style={{ lineHeight: 1.5 }}>+ {rows.map(row => (+ <View+ key={row.label}+ className={css({+ display: 'flex',+ flexDirection: 'row',+ justifyContent: 'space-between',+ gap: 20,+ })}+ >+ <div>{row.label}</div>+ <div>+ <FinancialText>{format(row.value, 'financial')}</FinancialText>+ </div>+ </View>+ ))}+ </div>+ </div>+ );+ }+ return null;+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloHistogram.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloHistogram.tsxnew file mode 100644index 0000000000..b29119ae6d--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloHistogram.tsx@@ -0,0 +1,88 @@+import type { CSSProperties } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import {+ Bar,+ BarChart,+ CartesianGrid,+ ReferenceLine,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts';++import { useRechartsAnimation } from '#components/reports/chart-theme';+import { Container } from '#components/reports/Container';+import { MonteCarloHistogramTooltip } from '#components/reports/graphs/MonteCarloHistogramTooltip';++type MonteCarloHistogramProps = {+ style?: CSSProperties;+ depletionHistogram: Array<{ year: number; count: number }>;+ /** The user's current age; the x-axis shows the failure year's age */+ startAge: number;+ medianDepletionYear: number | null;+ simulationCount: number;+ showTooltip?: boolean;+};++export function MonteCarloHistogram({+ style,+ depletionHistogram,+ startAge,+ medianDepletionYear,+ simulationCount,+ showTooltip = true,+}: MonteCarloHistogramProps) {+ const animationProps = useRechartsAnimation({ animationDuration: 1000 });++ const data = depletionHistogram.map(entry => ({+ ...entry,+ // The age of the year that couldn't be funded, matching the drill-in+ age: startAge + entry.year - 1,+ }));++ return (+ <Container style={style}>+ {(width, height) => (+ <BarChart+ width={width}+ height={height}+ data={data}+ margin={{ top: 15, right: 0, left: 20, bottom: 10 }}+ >+ <CartesianGrid strokeDasharray="3 3" />+ <XAxis+ dataKey="age"+ tick={{ fill: theme.pageText }}+ tickLine={{ stroke: theme.pageText }}+ />+ <YAxis+ allowDecimals={false}+ tick={{ fill: theme.pageText }}+ tickLine={{ stroke: theme.pageText }}+ />+ {showTooltip && (+ <Tooltip+ content={+ <MonteCarloHistogramTooltip simulationCount={simulationCount} />+ }+ isAnimationActive={false}+ cursor={{ fill: 'transparent' }}+ />+ )}+ {medianDepletionYear != null && (+ <ReferenceLine+ x={startAge + medianDepletionYear - 1}+ stroke={theme.noticeText}+ strokeDasharray="4 4"+ />+ )}+ <Bar+ dataKey="count"+ fill={theme.reportsNumberNegative}+ {...animationProps}+ />+ </BarChart>+ )}+ </Container>+ );+}diff --git a/packages/desktop-client/src/components/reports/graphs/MonteCarloHistogramTooltip.tsx b/packages/desktop-client/src/components/reports/graphs/MonteCarloHistogramTooltip.tsxnew file mode 100644index 0000000000..dd566a9ba9--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/MonteCarloHistogramTooltip.tsx@@ -0,0 +1,53 @@+import { useTranslation } from 'react-i18next';++import { theme } from '@actual-app/components/theme';+import { css } from '@emotion/css';++type PayloadItem = {+ payload: {+ year: number;+ age: number;+ count: number;+ };+};++type MonteCarloHistogramTooltipProps = {+ active?: boolean;+ payload?: PayloadItem[];+ simulationCount: number;+};++export function MonteCarloHistogramTooltip({+ active,+ payload,+ simulationCount,+}: MonteCarloHistogramTooltipProps) {+ const { t } = useTranslation();++ if (active && payload && payload.length) {+ const point = payload[0].payload;+ 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,+ })}+ >+ {t(+ '{{failedCount}} of {{total}} scenarios ran out of money at age {{age}}',+ {+ failedCount: point.count,+ total: simulationCount,+ age: point.age,+ },+ )}+ </div>+ );+ }+ return null;+}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.tsxnew file mode 100644index 0000000000..3c889368d4--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx@@ -0,0 +1,636 @@+import { useEffect, useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';+import { useParams } from 'react-router';++import { Button } from '@actual-app/components/button';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { ModeButton } from '@actual-app/components/mode-button';+import { Paragraph } from '@actual-app/components/paragraph';+import { Select } 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';+import { View } from '@actual-app/components/view';+import type { MonteCarloWidget } from '@actual-app/core/types/models';++import { EditablePageHeaderTitle } from '#components/EditablePageHeaderTitle';+import { FinancialText } from '#components/FinancialText';+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 { MonteCarloGraph } from '#components/reports/graphs/MonteCarloGraph';+import type { MonteCarloGraphView } from '#components/reports/graphs/MonteCarloGraphTooltip';+import { MonteCarloHistogram } from '#components/reports/graphs/MonteCarloHistogram';+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 {+ getMonteCarloHorizonYears,+ MONTE_CARLO_DEFAULTS,+ monteCarloConfigFromMeta,+ runMonteCarloSimulation,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type { MonteCarloConfig } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { useResolvedMonteCarloConfig } from '#components/reports/reports/monte-carlo/useResolvedMonteCarloConfig';+import { useDashboardWidget } from '#hooks/useDashboardWidget';+import { useFormat } from '#hooks/useFormat';+import { useNavigate } from '#hooks/useNavigate';+import { addNotification } from '#notifications/notificationsSlice';+import { useDispatch } from '#redux';+import { useUpdateDashboardWidgetMutation } from '#reports/mutations';++const firstYear = HISTORICAL_ANNUAL_RETURNS[0].year;+const lastYear =+ HISTORICAL_ANNUAL_RETURNS[HISTORICAL_ANNUAL_RETURNS.length - 1].year;++export function MonteCarlo() {+ const params = useParams();+ const { data: widget, isLoading } = useDashboardWidget<MonteCarloWidget>({+ id: params.id,+ type: 'monte-carlo-card',+ });++ const { t } = useTranslation();+ const dispatch = useDispatch();+ const format = useFormat();+ const navigate = useNavigate();+ const { isNarrowWidth } = useResponsive();++ const [config, setConfig] = useState<MonteCarloConfig>(MONTE_CARLO_DEFAULTS);+ const [graphView, setGraphView] = useState<MonteCarloGraphView>('all');+ const [resultsView, setResultsView] = useState<'chart' | 'runs'>('chart');+ 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+ // config changes - no effect, no wasted render with a stale selection+ const [selectedRun, setSelectedRun] = useState<{+ forConfig: MonteCarloConfig;+ index: number;+ } | null>(null);+ const [selectionsInitialized, setSelectionsInitialized] = useState(false);++ const selectedRunIndex =+ selectedRun != null && selectedRun.forConfig === config+ ? selectedRun.index+ : null;++ const resolvedConfig = useResolvedMonteCarloConfig(config);++ // reset when widget changes+ useEffect(() => {+ setSelectionsInitialized(false);+ }, [widget?.id]);++ // initialize once when the widget (if any) is available+ useEffect(() => {+ if (selectionsInitialized || isLoading) {+ return;+ }++ setConfig(monteCarloConfigFromMeta(widget?.meta));+ setSelectionsInitialized(true);+ }, [selectionsInitialized, isLoading, widget?.meta]);++ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();++ async function onSaveWidget() {+ // The save button only renders when a widget exists+ if (!widget) {+ return;+ }++ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ // Persist the resolved config so linked pots' stored balances+ // stay fresh as a fallback while live balances load+ ...resolvedConfig,+ },+ },+ },+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );+ },+ },+ );+ }++ const title = widget?.meta?.name || t('Monte Carlo Analysis');+ const onSaveWidgetName = async (newName: string) => {+ // The editable title only renders when a widget exists+ if (!widget) {+ return;+ }++ const name = newName || t('Monte Carlo Analysis');+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },+ },+ });+ };++ if (isLoading || !selectionsInitialized) {+ return <LoadingIndicator />;+ }++ const simulationParams = {+ ...resolvedConfig,+ horizonYears: getMonteCarloHorizonYears(resolvedConfig),+ deflateToTodaysMoney: showTodaysMoney,+ };+ const result = runMonteCarloSimulation(simulationParams);++ // Runs are seeded, so re-running with a capture index reproduces the+ // selected run exactly; only computed while a run is being inspected+ const runDetailRows =+ selectedRunIndex != null+ ? runMonteCarloSimulation({+ ...simulationParams,+ captureRunDetail: selectedRunIndex,+ }).runDetail+ : null;++ // The age the simulation actually runs to (differs from targetAge only+ // when the configured ages produce a clamped horizon)+ const endAge = config.currentAge + result.horizonYears;+ const successPercent = Math.round(result.successRate * 1000) / 10;+ const depletionPercent = Math.round((1 - result.successRate) * 1000) / 10;+ const failedCount = result.depletionHistogram.reduce(+ (sum, entry) => sum + entry.count,+ 0,+ );+ const hasFailures = failedCount > 0;+ const successColor =+ result.successRate >= 0.75+ ? theme.reportsNumberPositive+ : result.successRate >= 0.5+ ? theme.warningText+ : theme.reportsNumberNegative;++ return (+ <Page+ header={+ isNarrowWidth ? (+ <MobilePageHeader+ title={title}+ leftContent={+ <MobileBackButton onPress={() => navigate('/reports')} />+ }+ />+ ) : (+ <PageHeader+ title={+ widget ? (+ <EditablePageHeaderTitle+ title={title}+ onSave={onSaveWidgetName}+ />+ ) : (+ title+ )+ }+ />+ )+ }+ padding={0}+ >+ <View+ style={{+ flex: 1,+ overflowY: 'auto',+ paddingLeft: !isNarrowWidth ? 20 : 10,+ paddingRight: !isNarrowWidth ? 20 : 10,+ paddingBottom: 20,+ gap: 10,+ }}+ >+ {/* Configuration */}+ <View style={{ flexShrink: 0 }}>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '10px 0',+ flexShrink: 0,+ }}+ >+ <Text+ style={{+ ...styles.mediumText,+ fontWeight: 600,+ }}+ >+ <Trans>Configuration</Trans>+ </Text>+ {widget && (+ <Button variant="primary" onPress={onSaveWidget}>+ <Trans>Save widget</Trans>+ </Button>+ )}+ </View>+ <MonteCarloConfiguration+ config={resolvedConfig}+ onConfigChange={changes =>+ setConfig(prev => ({ ...prev, ...changes }))+ }+ />+ </View>++ {/* Results */}+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: 10,+ padding: '10px 0',+ flexShrink: 0,+ }}+ >+ <Text+ style={{+ ...styles.mediumText,+ fontWeight: 600,+ }}+ >+ <Trans>Results</Trans>+ </Text>+ <LabeledCheckbox+ id="mc-todays-money"+ checked={showTodaysMoney}+ onChange={event => setShowTodaysMoney(event.target.checked)}+ style={{ flex: 'unset' }}+ >+ <Trans>Show values in today's money</Trans>+ </LabeledCheckbox>+ </View>++ {/* Headline stats */}+ <View+ style={{+ backgroundColor: theme.tableBackground,+ padding: 20,+ flexShrink: 0,+ gap: 15,+ }}+ >+ <View+ style={{+ flexDirection: 'row',+ flexWrap: 'wrap',+ gap: 40,+ rowGap: 20,+ alignItems: 'flex-start',+ }}+ >+ <View style={{ gap: 4 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Success rate</Trans>+ </Text>+ <Text+ style={{+ ...styles.veryLargeText,+ color: successColor,+ }}+ >+ <FinancialText as="span">{`${successPercent}%`}</FinancialText>+ </Text>+ </View>+ <View style={{ gap: 4 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Median ending balance</Trans>+ </Text>+ <Text style={{ ...styles.mediumText, fontWeight: 500 }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(result.medianEndingBalance, 'financial')}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ </View>+ <View style={{ gap: 4 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Median total withdrawn</Trans>+ </Text>+ <Text style={{ ...styles.mediumText, fontWeight: 500 }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(result.medianTotalWithdrawn, 'financial')}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ </View>+ <View style={{ gap: 4 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Chance of running out of money</Trans>+ </Text>+ <Text style={{ ...styles.mediumText, fontWeight: 500 }}>+ <FinancialText as="span">{`${depletionPercent}%`}</FinancialText>+ </Text>+ </View>+ {result.medianDepletionYear != null && (+ <View style={{ gap: 4 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Typical failure runs out at</Trans>+ </Text>+ <Text style={{ ...styles.mediumText, fontWeight: 500 }}>+ {t('Age {{age}}', {+ // Ages here are the failure year itself, matching the+ // drill-in's failure row+ age: config.currentAge + result.medianDepletionYear - 1,+ })}+ </Text>+ </View>+ )}+ </View>+ <View style={{ marginTop: 10, gap: 5 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Summary</Trans>+ </Text>+ <Text>+ {t(+ 'In {{successPercent}}% of {{simulationCount}} simulated scenarios, your pot lasted until age {{endAge}}.',+ {+ successPercent,+ simulationCount: result.simulationCount,+ endAge,+ },+ )}+ </Text>+ </View>+ </View>++ {/* Portfolio performance chart / simulation runs table */}+ <View+ style={{+ backgroundColor: theme.tableBackground,+ padding: 20,+ paddingBottom: resultsView === 'chart' ? 10 : 20,+ ...(resultsView === 'chart' && { height: 470 }),+ flexShrink: 0,+ }}+ >+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: 10,+ marginBottom: 10,+ flexShrink: 0,+ }}+ >+ <View+ style={{ flexDirection: 'row', alignItems: 'center', gap: 15 }}+ >+ <Text style={{ ...styles.mediumText, fontWeight: 600 }}>+ {resultsView === 'chart' ? (+ <Trans>Portfolio performance</Trans>+ ) : (+ <Trans>Simulation runs</Trans>+ )}+ </Text>+ <View style={{ flexDirection: 'row', gap: 5 }}>+ <ModeButton+ selected={resultsView === 'chart'}+ onSelect={() => setResultsView('chart')}+ >+ <Trans>Chart</Trans>+ </ModeButton>+ <ModeButton+ selected={resultsView === 'runs'}+ onSelect={() => setResultsView('runs')}+ >+ <Trans>Runs</Trans>+ </ModeButton>+ </View>+ </View>+ {resultsView === 'chart' && (+ <Select+ value={graphView}+ onChange={value => setGraphView(value as MonteCarloGraphView)}+ options={[+ ['all', t('All scenarios')],+ ['single-worst', t('Single worst run')],+ ['worst-case', t('Worst-case scenario (5th percentile)')],+ ['pessimistic', t('Pessimistic scenario (30th percentile)')],+ ['median', t('Median scenario (50th percentile)')],+ ['optimistic', t('Optimistic scenario (70th percentile)')],+ ]}+ style={{ width: 280 }}+ />+ )}+ </View>+ {resultsView === 'chart' ? (+ <>+ {graphView !== 'all' && (+ <Text+ style={{+ color: theme.pageText,+ marginBottom: 10,+ flexShrink: 0,+ }}+ >+ {graphView === 'single-worst'+ ? t(+ 'The unluckiest of all {{simulationCount}} simulated runs - the one that ran out of money earliest.',+ { simulationCount: result.simulationCount },+ )+ : graphView === 'worst-case'+ ? t('95% of scenarios stayed above this line.')+ : graphView === 'pessimistic'+ ? t('70% of scenarios stayed above this line.')+ : graphView === 'median'+ ? t('Half of scenarios stayed above this line.')+ : t('30% of scenarios stayed above this line.')}+ </Text>+ )}+ <MonteCarloGraph+ percentileBands={result.percentileBands}+ startAge={config.currentAge}+ worstRunPath={result.worstRunPath}+ view={graphView}+ style={{ height: '100%', flex: 1 }}+ />+ </>+ ) : selectedRunIndex != null && runDetailRows != null ? (+ <MonteCarloRunDetailTable+ rows={runDetailRows}+ pots={resolvedConfig.pots}+ simulationIndex={selectedRunIndex}+ simulationCount={result.simulationCount}+ startAge={config.currentAge}+ onBack={() => setSelectedRun(null)}+ />+ ) : (+ <MonteCarloRunsTable+ endingBalances={result.endingBalances}+ depletionYearBySimulation={result.depletionYearBySimulation}+ totalWithdrawnBySimulation={result.totalWithdrawnBySimulation}+ startAge={config.currentAge}+ onSelectRun={simulationIndex =>+ setSelectedRun({ forConfig: config, index: simulationIndex })+ }+ />+ )}+ </View>++ {/* Depletion histogram */}+ <View+ style={{+ backgroundColor: theme.tableBackground,+ padding: 20,+ flexShrink: 0,+ }}+ >+ <Text+ style={{+ ...styles.mediumText,+ fontWeight: 600,+ marginBottom: 5,+ }}+ >+ <Trans>When did the pot run out?</Trans>+ </Text>+ {hasFailures ? (+ <>+ <Text style={{ color: theme.pageText, marginBottom: 10 }}>+ {t(+ 'Only the {{failedCount}} of {{simulationCount}} scenarios that ran out of money are shown here - the other {{survivedCount}} kept a positive balance for the full horizon.',+ {+ failedCount,+ simulationCount: result.simulationCount,+ survivedCount: result.simulationCount - failedCount,+ },+ )}+ </Text>+ <View style={{ height: 200, flexShrink: 0 }}>+ <MonteCarloHistogram+ depletionHistogram={result.depletionHistogram}+ startAge={config.currentAge}+ medianDepletionYear={result.medianDepletionYear}+ simulationCount={result.simulationCount}+ style={{ height: 200 }}+ />+ </View>+ <View style={{ marginTop: 10, flexShrink: 0 }}>+ <Text style={{ color: theme.pageText }}>+ {t(+ 'Worst case: money ran out at age {{worst}}. Among failures, the typical depletion age was {{median}}; the luckiest failure lasted until age {{best}}.',+ {+ worst:+ config.currentAge ++ (result.earliestDepletionYear ?? 1) -+ 1,+ median:+ config.currentAge ++ (result.medianDepletionYear ?? 1) -+ 1,+ best:+ config.currentAge ++ (result.latestDepletionYear ?? 1) -+ 1,+ },+ )}+ </Text>+ </View>+ </>+ ) : (+ <Paragraph>+ <Trans>+ The pot survived the full time horizon in every simulated+ scenario.+ </Trans>+ </Paragraph>+ )}+ </View>++ {/* Description */}+ <View+ style={{+ backgroundColor: theme.tableBackground,+ padding: 20,+ userSelect: 'none',+ flexShrink: 0,+ }}+ >+ <Text+ style={{+ ...styles.mediumText,+ fontWeight: 600,+ marginBottom: 10,+ }}+ >+ <Trans>How does this simulation work?</Trans>+ </Text>+ <Paragraph>+ <Trans>+ Each scenario replays your retirement with a different sequence of+ yearly investment returns. Every year the withdrawal is taken+ first, 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 across all scenarios: the darker band covers the+ middle half, and the lighter band covers 80% of them.+ </Trans>+ </Paragraph>+ <Paragraph>+ {config.returnModel === 'normal' ? (+ <Trans>+ Keep in mind this is a simplified model: returns are drawn+ independently each year from a normal distribution, which+ ignores sequence-of-returns clustering, fat tails, fees, and+ taxes. Treat the results as a rough guide, not a guarantee.+ </Trans>+ ) : config.returnModel === 'historical-bootstrap' ? (+ <Trans>+ Returns are actual US market years ({{ firstYear }}–+ {{ lastYear }}, S&P 500 / 10-year Treasuries / T-bills,+ Damodaran data) drawn in random order for each pot's+ allocation mix. Real crash years are included, but multi-year+ momentum is lost by shuffling, fees and taxes are ignored, and+ US history has been unusually good, so results may be optimistic+ for globally diversified portfolios.+ </Trans>+ ) : (+ <Trans>+ Each scenario replays actual US market history ({{ firstYear }}+ –{{ lastYear }}, S&P 500 / 10-year Treasuries /+ T-bills, Damodaran data) starting from a different year,+ wrapping around the end of the data. This preserves real crashes+ and recoveries, but there are only as many scenarios as start+ years, fees and taxes are ignored, and US history may be+ optimistic for globally diversified portfolios.+ </Trans>+ )}+ </Paragraph>+ </View>+ </View>+ </Page>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsxnew file mode 100644index 0000000000..ae0795e223--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloCard.tsx@@ -0,0 +1,118 @@+import { useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Block } from '@actual-app/components/block';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import type { MonteCarloWidget } from '@actual-app/core/types/models';++import { FinancialText } from '#components/FinancialText';+import { PrivacyFilter } from '#components/PrivacyFilter';+import { MonteCarloGraph } from '#components/reports/graphs/MonteCarloGraph';+import { ReportCard } from '#components/reports/ReportCard';+import { ReportCardName } from '#components/reports/ReportCardName';+import {+ getMonteCarloHorizonYears,+ monteCarloConfigFromMeta,+ runMonteCarloSimulation,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { useResolvedMonteCarloConfig } from '#components/reports/reports/monte-carlo/useResolvedMonteCarloConfig';++// Stable default so an unsaved widget doesn't bust the simulation's+// memoization on every re-render (e.g. hover state changes)+const EMPTY_META: NonNullable<MonteCarloWidget['meta']> = {};++type MonteCarloCardProps = {+ widgetId: string;+ isEditing?: boolean;+ meta?: MonteCarloWidget['meta'];+ onMetaChange: (newMeta: MonteCarloWidget['meta']) => void;+};++export function MonteCarloCard({+ widgetId,+ isEditing,+ meta = EMPTY_META,+ onMetaChange,+}: MonteCarloCardProps) {+ const { t } = useTranslation();+ const { isNarrowWidth } = useResponsive();++ const [nameMenuOpen, setNameMenuOpen] = useState(false);+ const [isCardHovered, setIsCardHovered] = useState(false);++ const config = monteCarloConfigFromMeta(meta);+ const resolvedConfig = useResolvedMonteCarloConfig(config);+ const result = runMonteCarloSimulation({+ ...resolvedConfig,+ horizonYears: getMonteCarloHorizonYears(resolvedConfig),+ deflateToTodaysMoney: true,+ });++ const endAge = config.currentAge + result.horizonYears;+ const successPercent = Math.round(result.successRate * 1000) / 10;++ return (+ <ReportCard+ widgetId={widgetId}+ isEditing={isEditing}+ disableClick={nameMenuOpen}+ to={`/reports/monte-carlo/${widgetId}`}+ onRename={() => setNameMenuOpen(true)}+ >+ <View+ style={{ flex: 1 }}+ onPointerEnter={() => setIsCardHovered(true)}+ onPointerLeave={() => setIsCardHovered(false)}+ >+ <View style={{ flexDirection: 'row', padding: 20 }}>+ <View style={{ flex: 1 }}>+ <ReportCardName+ name={meta?.name || t('Monte Carlo Analysis')}+ isEditing={nameMenuOpen}+ onChange={newName => {+ onMetaChange({+ ...meta,+ name: newName,+ });+ setNameMenuOpen(false);+ }}+ onClose={() => setNameMenuOpen(false)}+ />+ </View>+ <View style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>+ <Block+ style={{+ ...styles.mediumText,+ fontWeight: 500,+ marginBottom: 5,+ }}+ >+ <PrivacyFilter activationFilters={[!isCardHovered]}>+ <FinancialText>{`${successPercent}%`}</FinancialText>+ </PrivacyFilter>+ </Block>+ <Block+ style={{+ fontSize: 12,+ color: theme.pageTextSubdued,+ }}+ >+ <Trans>Success rate to age {{ age: endAge }}</Trans>+ </Block>+ </View>+ </View>++ <MonteCarloGraph+ percentileBands={result.percentileBands}+ startAge={config.currentAge}+ compact+ showTooltip={!isEditing && !isNarrowWidth}+ style={{ height: 'auto', flex: 1 }}+ />+ </View>+ </ReportCard>+ );+}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.tsxnew file mode 100644index 0000000000..a6cb2b2a78--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx@@ -0,0 +1,525 @@+import { useState } from 'react';+import type { DragItem } from 'react-aria';+import { DropIndicator, GridList, useDragAndDrop } from 'react-aria-components';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgAdd } from '@actual-app/components/icons/v1';+import { ModeButton } from '@actual-app/components/mode-button';+import { Select } 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';+import { View } from '@actual-app/components/view';+import type {+ MonteCarloReturnModel,+ MonteCarloWithdrawalStrategy,+} from '@actual-app/core/types/models';+import { css } from '@emotion/css';+import { v4 as uuidv4 } from 'uuid';++import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+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,+ MAX_SIMULATION_COUNT,+ MIN_SIMULATION_COUNT,+ MONTE_CARLO_DEFAULTS,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type {+ MonteCarloConfig,+ MonteCarloPot,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { MonteCarloSpendingPhases } from '#components/reports/reports/monte-carlo/MonteCarloSpendingPhases';+import {+ FIELD_LABEL_ROW_STYLE,+ FIELD_LABEL_STYLE,+ FIELD_STYLE,+ GROUP_HEADING_STYLE,+} from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { MonteCarloTaxConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloTaxConfiguration';+import { MonteCarloWithdrawalRuleConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration';++type ConfigurationTab = 'plan' | 'pots' | 'withdrawals' | 'tax';++const PLAN_GROUP_FIELDS_STYLE = {+ flexDirection: 'row',+ gap: 20,+ alignItems: 'flex-end',+} as const;++type MonteCarloConfigurationProps = {+ config: MonteCarloConfig;+ onConfigChange: (changes: Partial<MonteCarloConfig>) => void;+};++export function MonteCarloConfiguration({+ config,+ onConfigChange,+}: MonteCarloConfigurationProps) {+ const { t } = useTranslation();+ const [activeTab, setActiveTab] = useState<ConfigurationTab>('plan');++ function onPotChange(potId: string, changes: Partial<MonteCarloPot>) {+ onConfigChange({+ pots: config.pots.map(pot =>+ pot.id === potId ? { ...pot, ...changes } : pot,+ ),+ });+ }++ const { dragAndDropHooks } = useDragAndDrop({+ getItems: keys =>+ [...keys].map(key => ({ 'text/plain': String(key) }) as DragItem),+ renderDropIndicator: target => (+ <DropIndicator+ target={target}+ className={css({+ '&[data-drop-target]': {+ height: 4,+ backgroundColor: theme.tableBorderSeparator,+ opacity: 1,+ borderRadius: 4,+ },+ })}+ />+ ),+ onReorder: event => {+ const [movedKey] = event.keys;+ const fromIndex = config.pots.findIndex(pot => pot.id === movedKey);+ const targetIndex = config.pots.findIndex(+ pot => pot.id === event.target.key,+ );+ if (fromIndex === -1 || targetIndex === -1) {+ return;+ }++ const newPots = [...config.pots];+ const [movedPot] = newPots.splice(fromIndex, 1);+ let insertIndex =+ targetIndex + (event.target.dropPosition === 'after' ? 1 : 0);+ if (fromIndex < insertIndex) {+ insertIndex -= 1;+ }+ newPots.splice(insertIndex, 0, movedPot);+ onConfigChange({ pots: newPots });+ },+ });++ return (+ <View+ style={{+ backgroundColor: theme.tableBackground,+ padding: 20,+ flexShrink: 0,+ gap: 15,+ }}+ >+ {/* Tab bar */}+ <View style={{ flexDirection: 'row', gap: 5 }}>+ <ModeButton+ selected={activeTab === 'plan'}+ onSelect={() => setActiveTab('plan')}+ >+ <Trans>Plan details</Trans>+ </ModeButton>+ <ModeButton+ selected={activeTab === 'pots'}+ onSelect={() => setActiveTab('pots')}+ >+ <Trans>Investment pots</Trans>+ </ModeButton>+ <ModeButton+ selected={activeTab === 'withdrawals'}+ onSelect={() => setActiveTab('withdrawals')}+ >+ <Trans>Spending</Trans>+ </ModeButton>+ <ModeButton+ selected={activeTab === 'tax'}+ onSelect={() => setActiveTab('tax')}+ >+ <Trans>Tax</Trans>+ </ModeButton>+ </View>++ <Text style={{ color: theme.pageText }}>+ {activeTab === 'plan'+ ? t(+ 'Who this plan is for and how the simulation generates market returns.',+ )+ : activeTab === 'pots'+ ? t(+ 'The invested accounts your plan draws from - each with its own balance, allocation, and return assumptions. Drag rows to reorder pots; expand a row for access, tax and fee settings.',+ )+ : 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>++ {/* Plan details */}+ {activeTab === 'plan' && (+ <View+ style={{+ flexDirection: 'row',+ flexWrap: 'wrap',+ alignItems: 'flex-start',+ rowGap: 20,+ columnGap: 40,+ }}+ >+ <View style={{ gap: 10 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Your plan</Trans>+ </Text>+ <View style={PLAN_GROUP_FIELDS_STYLE}>+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Your current age</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={config.currentAge}+ aria-label={t('Your current age')}+ roundToInteger+ min={16}+ max={119}+ step={1}+ onCommit={newValue =>+ onConfigChange({+ currentAge: newValue ?? MONTE_CARLO_DEFAULTS.currentAge,+ })+ }+ />+ </View>++ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Pot must last until age</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={config.targetAge}+ aria-label={t('Pot must last until age')}+ roundToInteger+ min={config.currentAge + 1}+ max={120}+ step={1}+ onCommit={newValue =>+ onConfigChange({+ targetAge: newValue ?? MONTE_CARLO_DEFAULTS.targetAge,+ })+ }+ />+ </View>+ </View>+ </View>++ <View style={{ gap: 10 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Inflation</Trans>+ </Text>+ <View style={PLAN_GROUP_FIELDS_STYLE}>+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Mean (%)</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ The average yearly rise in prices. When set, your planned+ spending grows with it so your spending power is+ maintained.+ <br />+ <br />+ Leave blank to keep withdrawals flat.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <MonteCarloNumberInput+ value={config.inflationMean}+ aria-label={t('Inflation mean (%)')}+ scale={100}+ allowEmpty+ min={0}+ max={100}+ placeholder={t('None')}+ onCommit={newValue =>+ onConfigChange({ inflationMean: newValue })+ }+ />+ </View>++ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Std dev (%)</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ 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.+ <br />+ <br />+ Around 2% matches how much US inflation has varied in+ recent decades. Set to 0 to use the fixed mean rate every+ year.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <MonteCarloNumberInput+ value={config.inflationStdDev}+ aria-label={t('Inflation std dev (%)')}+ scale={100}+ min={0}+ max={50}+ disabled={config.inflationMean == null}+ onCommit={newValue =>+ onConfigChange({ inflationStdDev: newValue ?? 0 })+ }+ />+ </View>+ </View>+ </View>++ <View style={{ gap: 10 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Simulation</Trans>+ </Text>+ <View style={PLAN_GROUP_FIELDS_STYLE}>+ <View style={{ width: 250 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Return model</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ How each simulated year's investment return is+ generated.+ <br />+ <br />+ Random: drawn from a normal distribution around each+ pot's expected return and volatility. All pots+ experience the same market conditions each year, scaled by+ their own volatility.+ <br />+ <br />+ Historical, shuffled: drawn from actual US market years+ (1928 onwards) in random order.+ <br />+ <br />+ Historical sequences: replays real market history, one+ scenario per starting year. Pots with a Custom allocation+ always use their own return and volatility.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <Select+ value={config.returnModel}+ onChange={value =>+ onConfigChange({+ returnModel: value as MonteCarloReturnModel,+ })+ }+ options={[+ ['normal', t('Random (normal distribution)')],+ ['historical-bootstrap', t('Historical returns, shuffled')],+ ['historical-sequence', t('Historical sequences (replay)')],+ ]}+ />+ </View>++ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Simulations</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ How many random scenarios to run. More simulations give a+ steadier result but take slightly longer.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <MonteCarloNumberInput+ value={config.simulationCount}+ aria-label={t('Simulations')}+ roundToInteger+ min={MIN_SIMULATION_COUNT}+ max={MAX_SIMULATION_COUNT}+ step={500}+ // Sequence replay runs one scenario per historical start year+ disabled={config.returnModel === 'historical-sequence'}+ onCommit={newValue =>+ onConfigChange({+ simulationCount: newValue ?? MIN_SIMULATION_COUNT,+ })+ }+ />+ </View>+ </View>+ </View>+ </View>+ )}++ {/* Investment pots. Future settings like fees belong in their own+ tab alongside these. */}+ {activeTab === 'pots' && (+ <View>+ <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' }}>+ <MonteCarloPotsTableHeader />+ <GridList+ aria-label={t('Investment pots')}+ // Without this, typing in the pot fields moves the list+ // highlight to whichever pot name matches the keystroke+ disallowTypeAhead+ // Let Tab move between the fields inside pot rows instead of+ // jumping out of the list (default ARIA grid behavior)+ keyboardNavigationBehavior="tab"+ items={config.pots}+ dependencies={[config, onConfigChange]}+ dragAndDropHooks={dragAndDropHooks}+ >+ {pot => (+ <MonteCarloPotConfiguration+ key={pot.id}+ pot={pot}+ potNumber={config.pots.indexOf(pot) + 1}+ canRemove={config.pots.length > 1}+ usesHistoricalReturns={config.returnModel !== 'normal'}+ usesTaxBands={config.taxModel === 'bands'}+ onPotChange={changes => onPotChange(pot.id, changes)}+ onRemove={() =>+ onConfigChange({+ pots: config.pots.filter(other => other.id !== pot.id),+ })+ }+ />+ )}+ </GridList>+ </View>+ </View>+ <View style={{ flexDirection: 'row', marginTop: 10 }}>+ <Button+ onPress={() =>+ onConfigChange({+ pots: [...config.pots, createMonteCarloPot(uuidv4())],+ })+ }+ >+ <SvgAdd width={10} height={10} style={{ marginRight: 5 }} />+ <Trans>Add pot</Trans>+ </Button>+ </View>+ </View>+ )}++ {/* Spending */}+ {activeTab === 'withdrawals' && (+ <View>+ <MonteCarloSpendingPhases+ phases={config.spendingPhases}+ currentAge={config.currentAge}+ targetAge={config.targetAge}+ onPhasesChange={phases =>+ onConfigChange({ spendingPhases: phases })+ }+ />+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 20 }}>+ <View style={{ width: 220 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Withdrawal order</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ How the annual withdrawal is taken when you have more than+ one pot.+ <br />+ <br />+ Proportionally: split across pots based on their current+ balances.+ <br />+ <br />+ In pot order: drain the first pot before touching the next,+ in the order listed on the Investment pots tab.+ <br />+ <br />+ Best performer first: each year, drain the pot with the+ highest return last year - e.g. spend cash after a stock+ crash so the crashed pot can recover, and spend stocks in+ boom years. The first year uses the listed order.+ <br />+ <br />+ Keep pots at their target mix: withdrawals come from+ whichever pots have grown above their share of your starting+ mix, pulling the portfolio back toward it - trim stocks+ after a boom, spend cash and bonds after a crash.+ <br />+ <br />+ Pots that haven't reached their access age yet are+ skipped until they unlock.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <Select+ value={config.withdrawalStrategy}+ onChange={value =>+ onConfigChange({+ withdrawalStrategy: value as MonteCarloWithdrawalStrategy,+ })+ }+ options={[+ ['proportional', t('Split proportionally across pots')],+ ['sequential', t('Drain pots in order')],+ ['best-performer', t('Spend from the best performer first')],+ ['target-mix', t('Keep pots at their target mix')],+ ]}+ />+ </View>+ </View>+ <MonteCarloWithdrawalRuleConfiguration+ rule={config.withdrawalRule}+ minimumWithdrawal={config.minimumWithdrawal}+ onRuleChange={changes =>+ onConfigChange({+ withdrawalRule: { ...config.withdrawalRule, ...changes },+ })+ }+ onMinimumWithdrawalChange={value =>+ onConfigChange({ minimumWithdrawal: value })+ }+ />+ </View>+ )}++ {/* Tax */}+ {activeTab === 'tax' && (+ <MonteCarloTaxConfiguration+ taxModel={config.taxModel}+ taxBands={config.taxBands}+ onConfigChange={onConfigChange}+ />+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloHelpTooltip.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloHelpTooltip.tsxnew file mode 100644index 0000000000..4d67cb358e--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloHelpTooltip.tsx@@ -0,0 +1,53 @@+import { useState } from 'react';+import type { ComponentPropsWithoutRef, ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgQuestion } from '@actual-app/components/icons/v1';+import { styles } from '@actual-app/components/styles';+import { Text } from '@actual-app/components/text';+import { Tooltip } from '@actual-app/components/tooltip';+import { View } from '@actual-app/components/view';++type MonteCarloHelpTooltipProps = {+ /** The explanatory text, typically a Trans block */+ children: ReactNode;+ placement?: ComponentPropsWithoutRef<typeof Tooltip>['placement'];+};++/**+ * The report's standard question-mark help icon. The explanation shows on+ * hover, and also while the trigger has keyboard focus - the shared+ * Tooltip only tracks the mouse, so focus is wired up here through its+ * triggerProps escape hatch.+ */+export function MonteCarloHelpTooltip({+ children,+ placement = 'bottom start',+}: MonteCarloHelpTooltipProps) {+ const { t } = useTranslation();+ const [isFocused, setIsFocused] = useState(false);++ return (+ <Tooltip+ content={+ <View style={{ maxWidth: 300 }}>+ <Text>{children}</Text>+ </View>+ }+ placement={placement}+ style={styles.tooltip}+ triggerProps={isFocused ? { isOpen: true } : {}}+ >+ <Button+ variant="bare"+ aria-label={t('Help')}+ onFocus={() => setIsFocused(true)}+ onBlur={() => setIsFocused(false)}+ style={{ padding: 0, minHeight: 'auto' }}+ >+ <SvgQuestion height={12} width={12} />+ </Button>+ </Tooltip>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloNumberInput.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloNumberInput.tsxnew file mode 100644index 0000000000..ad305bb19f--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloNumberInput.tsx@@ -0,0 +1,123 @@+import { useEffect, useRef, useState } from 'react';+import type { CSSProperties } from 'react';++import { Input } from '@actual-app/components/input';+import { css } from '@emotion/css';++// Plain numeric text input - no browser spin buttons+const NUMBER_INPUT_CLASS = css({+ '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {+ WebkitAppearance: 'none',+ margin: 0,+ },+ MozAppearance: 'textfield',+});++type MonteCarloNumberInputProps = {+ /** Committed value; a fraction when scale is 100, plain number otherwise */+ value: number | null;+ /** Called on blur/Enter, only when the parsed value actually changed */+ onCommit: (value: number | null) => void;+ /** 100 for percentage fields (0.06 shown as 6), 1 for plain numbers */+ scale?: number;+ /** When true, clearing the field commits null instead of the minimum */+ allowEmpty?: boolean;+ roundToInteger?: boolean;+ min: number;+ max: number;+ step?: number;+ placeholder?: string;+ disabled?: boolean;+ /** Accessible name; pass the field's visible label text */+ 'aria-label'?: string;+ /** Extra styles, e.g. for compact inline inputs inside a sentence */+ style?: CSSProperties;+};++function toDisplayText(value: number | null, scale: number) {+ return value == null ? '' : String(Number((value * scale).toFixed(4)));+}++export function MonteCarloNumberInput({+ value,+ onCommit,+ scale = 1,+ allowEmpty = false,+ roundToInteger = false,+ min,+ max,+ step = 0.1,+ placeholder,+ disabled = false,+ 'aria-label': ariaLabel,+ style,+}: MonteCarloNumberInputProps) {+ const inputRef = useRef<HTMLInputElement>(null);+ const [text, setText] = useState(() => toDisplayText(value, scale));+ const [isFocused, setIsFocused] = useState(false);++ // Reflect outside changes (e.g. an allocation preset auto-fill) while the+ // field isn't being edited+ useEffect(() => {+ if (!isFocused) {+ setText(toDisplayText(value, scale));+ }+ }, [value, scale, isFocused]);++ function commit(currentText: string) {+ const trimmed = currentText.trim();+ if (trimmed === '') {+ if (allowEmpty) {+ if (value !== null) {+ onCommit(null);+ }+ return;+ }+ // Revert to the last committed value+ setText(toDisplayText(value, scale));+ return;+ }++ const parsed = Number(trimmed);+ if (isNaN(parsed)) {+ setText(toDisplayText(value, scale));+ return;+ }++ const rounded = roundToInteger ? Math.round(parsed) : parsed;+ const clamped = Math.min(max, Math.max(min, rounded));+ const newValue = clamped / scale;+ setText(toDisplayText(newValue, scale));+ if (newValue !== value) {+ onCommit(newValue);+ }+ }++ return (+ <Input+ ref={inputRef}+ type="number"+ className={NUMBER_INPUT_CLASS}+ min={min}+ max={max}+ step={step}+ value={text}+ placeholder={placeholder}+ disabled={disabled}+ aria-label={ariaLabel}+ style={style}+ onChangeValue={setText}+ onFocus={() => {+ setIsFocused(true);+ // Highlight the whole value so typing replaces it, matching the+ // currency inputs+ setTimeout(() => inputRef.current?.select(), 0);+ }}+ onBlur={event => {+ setIsFocused(false);+ commit(event.currentTarget.value);+ }}+ onEnter={commit}+ />+ );+}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.tsxnew file mode 100644index 0000000000..00cc70fc45--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx@@ -0,0 +1,469 @@+import { useState } from 'react';+import type { ComponentPropsWithoutRef } from 'react';+import { GridListItem } from 'react-aria-components';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+import {+ SvgCheveronDown,+ SvgCheveronRight,+} from '@actual-app/components/icons/v1';+import { Input } from '@actual-app/components/input';+import { Select } from '@actual-app/components/select';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import type { MonteCarloAllocationPreset } from '@actual-app/core/types/models';+import { css } from '@emotion/css';++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 { POT_COLUMNS } from '#components/reports/reports/monte-carlo/MonteCarloPotsTableHeader';+import {+ ALLOCATION_PRESETS,+ MAX_AMOUNT,+ MAX_ANNUAL_FEE_RATE,+ MAX_WITHDRAWAL_TAX_RATE,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type { MonteCarloPot } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import {+ FIELD_LABEL_ROW_STYLE,+ FIELD_LABEL_STYLE,+ FIELD_STYLE,+ GROUP_HEADING_STYLE,+} from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { Field, Row } from '#components/table';+import { FinancialInput } from '#components/util/FinancialInput';+import { useAccounts } from '#hooks/useAccounts';++const POT_ROW_HEIGHT = 43;++type MonteCarloPotConfigurationProps = ComponentPropsWithoutRef<+ typeof GridListItem<MonteCarloPot>+> & {+ pot: MonteCarloPot;+ potNumber: number;+ canRemove: boolean;+ /** True when a historical return model is active */+ usesHistoricalReturns: boolean;+ /** True when the bands tax model is active */+ usesTaxBands: boolean;+ onPotChange: (changes: Partial<MonteCarloPot>) => void;+ onRemove: () => void;+};++export function MonteCarloPotConfiguration({+ pot,+ potNumber,+ canRemove,+ usesHistoricalReturns,+ usesTaxBands,+ onPotChange,+ onRemove,+ ...props+}: MonteCarloPotConfigurationProps) {+ const { t } = useTranslation();+ const { data: accounts = [] } = useAccounts();+ const [isExpanded, setIsExpanded] = useState(false);++ // Historical models derive this pot's returns from its allocation mix;+ // the manual return/volatility only apply to Custom pots there+ const isManualReturnDisabled =+ usesHistoricalReturns && pot.allocationPreset !== 'custom';++ // A linked account that has since been closed or deleted isn't in the+ // open-accounts list; keep it represented so the stored link doesn't+ // display as a blank selection+ const openAccounts = accounts.filter(account => account.closed === 0);+ const linkedAccount = accounts.find(account => account.id === pot.accountId);+ const missingLinkedOptions: Array<[string, string]> =+ pot.accountId != null &&+ !openAccounts.some(account => account.id === pot.accountId)+ ? [+ [+ pot.accountId,+ linkedAccount+ ? t('{{name}} (closed)', { name: linkedAccount.name })+ : t('Unavailable account'),+ ],+ ]+ : [];++ return (+ <GridListItem+ textValue={pot.name || t('Pot {{number}}', { number: potNumber })}+ 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}+ truncate={false}+ style={{ alignItems: 'center' }}+ >+ <Button+ variant="bare"+ aria-label={+ isExpanded ? t('Hide more settings') : t('Show more settings')+ }+ onPress={() => setIsExpanded(!isExpanded)}+ style={{ padding: 6 }}+ >+ {isExpanded ? (+ <SvgCheveronDown width={14} height={14} />+ ) : (+ <SvgCheveronRight width={14} height={14} />+ )}+ </Button>+ </Field>++ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.name }}+ truncate={false}+ >+ <Input+ // Uncontrolled on purpose: committing on blur keeps typing+ // snappy since every config change re-runs the simulation+ defaultValue={pot.name}+ placeholder={t('Pot {{number}}', { number: potNumber })}+ onUpdate={newName => {+ if (newName !== pot.name) {+ onPotChange({ name: newName });+ }+ }}+ />+ </Field>++ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.startingBalance }}+ truncate={false}+ >+ <FinancialInput+ value={pot.startingBalance}+ // Typing a different balance takes manual control: the pot+ // unlinks from its account and keeps the typed value. The+ // changed-check stops a mere tab-through from unlinking.+ onUpdate={value => {+ const newBalance = Math.min(MAX_AMOUNT, Math.max(0, value));+ if (newBalance !== pot.startingBalance) {+ onPotChange({+ startingBalance: newBalance,+ accountId: null,+ });+ }+ }}+ />+ </Field>++ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.linkedAccount }}+ truncate={false}+ >+ <Select+ value={pot.accountId ?? ''}+ onChange={value =>+ onPotChange({ accountId: value === '' ? null : value })+ }+ options={[+ ['', t('None')],+ ...missingLinkedOptions,+ ...openAccounts.map(+ account => [account.id, account.name] as [string, string],+ ),+ ]}+ />+ </Field>++ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.allocation }}+ truncate={false}+ >+ <Select+ value={pot.allocationPreset}+ onChange={value => {+ const preset = value as MonteCarloAllocationPreset;+ if (preset === 'custom') {+ onPotChange({ allocationPreset: preset });+ } else {+ onPotChange({+ allocationPreset: preset,+ expectedReturnMean: ALLOCATION_PRESETS[preset].mean,+ returnStdDev: ALLOCATION_PRESETS[preset].stdDev,+ });+ }+ }}+ options={[+ ['equity-100', t('100% stocks')],+ ['equity-80', t('80% stocks / 20% bonds')],+ ['equity-60', t('60% stocks / 40% bonds')],+ ['equity-40', t('40% stocks / 60% bonds')],+ ['cash', t('Cash / money market')],+ ['custom', t('Custom')],+ ]}+ />+ </Field>++ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.expectedReturn }}+ truncate={false}+ >+ <MonteCarloNumberInput+ value={pot.expectedReturnMean}+ aria-label={t('Expected return (%)')}+ scale={100}+ min={-100}+ max={100}+ disabled={isManualReturnDisabled}+ onCommit={newValue =>+ onPotChange({+ expectedReturnMean: newValue ?? 0,+ allocationPreset: 'custom',+ })+ }+ />+ </Field>++ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.volatility }}+ truncate={false}+ >+ <MonteCarloNumberInput+ value={pot.returnStdDev}+ aria-label={t('Volatility (std dev %)')}+ scale={100}+ min={0}+ max={100}+ disabled={isManualReturnDisabled}+ onCommit={newValue =>+ onPotChange({+ returnStdDev: newValue ?? 0,+ allocationPreset: 'custom',+ })+ }+ />+ </Field>++ <Field+ width={POT_COLUMNS.remove}+ truncate={false}+ style={{ alignItems: 'center' }}+ >+ {canRemove && (+ <Button+ variant="bare"+ aria-label={t('Remove pot')}+ onPress={onRemove}+ style={{ padding: 6 }}+ >+ <SvgDelete width={12} height={12} />+ </Button>+ )}+ </Field>+ </Row>++ {isExpanded && (+ <View+ style={{+ backgroundColor: theme.tableBackground,+ borderBottom: `1px solid ${theme.tableBorder}`,+ padding: '12px 15px 16px',+ flexDirection: 'row',+ flexWrap: 'wrap',+ alignItems: 'flex-start',+ rowGap: 15,+ columnGap: 40,+ }}+ >+ <View style={{ gap: 10 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Access</Trans>+ </Text>+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Accessible from age</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Some pots can't be touched until a certain age - e.g.+ personal pensions. Until then the pot stays invested and+ keeps growing, but can't fund withdrawals.+ <br />+ <br />+ Leave blank if the pot is available now.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <MonteCarloNumberInput+ value={pot.accessAge}+ aria-label={t('Accessible from age')}+ allowEmpty+ roundToInteger+ min={16}+ max={120}+ step={1}+ placeholder={t('Immediately')}+ onCommit={newValue => onPotChange({ accessAge: newValue })}+ />+ </View>+ </View>++ <View style={{ gap: 10 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Tax</Trans>+ </Text>+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ {usesTaxBands ? (+ <Trans>Taxable portion (%)</Trans>+ ) : (+ <Trans>Tax (%)</Trans>+ )}+ </Text>+ <MonteCarloHelpTooltip>+ {usesTaxBands ? (+ <Trans>+ The share of a withdrawal from this pot that counts as+ taxable income under your tax bands - e.g. a pension with+ a 25% tax-free portion is 75, a tax-free account is 0, and+ a taxable account is roughly the share of each withdrawal+ that is gains.+ </Trans>+ ) : (+ <Trans>+ The effective tax rate on withdrawals from this pot. Your+ spending is what you keep after tax, so the simulation+ withdraws extra to cover it - e.g. a tax-free account is+ 0, a pension blending its tax-free portion with income tax+ might be around 15, and a taxable account its effective+ gains rate.+ </Trans>+ )}+ </MonteCarloHelpTooltip>+ </View>+ {usesTaxBands ? (+ <MonteCarloNumberInput+ value={pot.taxableFraction}+ aria-label={t('Taxable portion (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPotChange({ taxableFraction: newValue ?? 1 })+ }+ />+ ) : (+ <MonteCarloNumberInput+ value={pot.withdrawalTaxRate}+ aria-label={t('Tax (%)')}+ scale={100}+ min={0}+ max={MAX_WITHDRAWAL_TAX_RATE * 100}+ onCommit={newValue =>+ onPotChange({ withdrawalTaxRate: newValue ?? 0 })+ }+ />+ )}+ </View>+ </View>++ <View style={{ gap: 10 }}>+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Fees</Trans>+ </Text>+ <View+ style={{+ flexDirection: 'row',+ flexWrap: 'wrap',+ alignItems: 'flex-end',+ gap: 20,+ }}+ >+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Fixed yearly fee</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ The sum of all fixed yearly costs on this pot - e.g.+ adviser or platform fees - charged at the end of each+ year.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <FinancialInput+ value={pot.annualFeeFixed}+ onUpdate={value => {+ const newFee = Math.min(MAX_AMOUNT, Math.max(0, value));+ if (newFee !== pot.annualFeeFixed) {+ onPotChange({ annualFeeFixed: newFee });+ }+ }}+ />+ </View>++ <LabeledCheckbox+ id={`pot-fee-inflation-${pot.id}`}+ checked={pot.feeAdjustsWithInflation}+ onChange={event =>+ onPotChange({+ feeAdjustsWithInflation: event.target.checked,+ })+ }+ style={{ flex: 'unset', paddingBottom: 6 }}+ >+ <Trans>Adjust by inflation</Trans>+ </LabeledCheckbox>++ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Fee (% of balance)</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ A yearly percentage of the pot's end-of-year balance+ - e.g. fund or platform charges.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <MonteCarloNumberInput+ value={pot.annualFeeRate}+ aria-label={t('Fee (% of balance)')}+ scale={100}+ min={0}+ max={MAX_ANNUAL_FEE_RATE * 100}+ step={0.01}+ onCommit={newValue =>+ onPotChange({ annualFeeRate: newValue ?? 0 })+ }+ />+ </View>+ </View>+ </View>+ </View>+ )}+ </GridListItem>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotsTableHeader.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotsTableHeader.tsxnew file mode 100644index 0000000000..5eca4f51d2--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotsTableHeader.tsx@@ -0,0 +1,119 @@+import { Trans } from 'react-i18next';++import { Text } from '@actual-app/components/text';+import { View } from '@actual-app/components/view';++import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import { Field, TableHeader } from '#components/table';++// Shared by the header and the pot rows so the columns line up. The+// drag/expand/remove columns are fixed; the rest flex evenly, with these+// minimum widths so labels and controls don't get crushed on narrow+// windows. Access, tax and fee settings live in the expandable panel+// under each row, not in columns.+export const POT_COLUMNS = {+ expand: 36,+ name: 150,+ startingBalance: 120,+ linkedAccount: 160,+ allocation: 190,+ expectedReturn: 150,+ volatility: 170,+ remove: 36,+} as const;++const HEADER_LABEL_STYLE = {+ flexDirection: 'row',+ alignItems: 'center',+ gap: 5,+ whiteSpace: 'nowrap',+} as const;++export function MonteCarloPotsTableHeader() {+ return (+ <TableHeader>+ <Field width={POT_COLUMNS.expand} />+ <Field width="flex" style={{ minWidth: POT_COLUMNS.name }}>+ <Trans>Pot name</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: POT_COLUMNS.startingBalance }}>+ <Trans>Starting balance</Trans>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.linkedAccount }}+ truncate={false}+ >+ <View style={HEADER_LABEL_STYLE}>+ <Text>+ <Trans>Linked account</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Use an account's live balance as this pot's starting+ balance, so the plan stays up to date on its own.+ <br />+ <br />+ Typing a starting balance manually unlinks the pot - handy for+ what-if experiments.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.allocation }}+ truncate={false}+ >+ <View style={HEADER_LABEL_STYLE}>+ <Text>+ <Trans>Portfolio allocation</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ A one-click starting point that fills in a typical expected return+ and volatility for the selected mix of stocks and bonds. You can+ still override both values.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.expectedReturn }}+ truncate={false}+ >+ <View style={HEADER_LABEL_STYLE}>+ <Text>+ <Trans>Expected return (%)</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ The average yearly investment return before inflation. Each+ simulated year draws a random return around this average.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </Field>+ <Field+ width="flex"+ style={{ minWidth: POT_COLUMNS.volatility }}+ truncate={false}+ >+ <View style={HEADER_LABEL_STYLE}>+ <Text>+ <Trans>Volatility (std dev %)</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ How much returns swing from year to year. Higher volatility means+ bigger ups and downs, which makes running out of money more likely+ even with the same average return.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ </Field>+ <Field width={POT_COLUMNS.remove} />+ </TableHeader>+ );+}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.tsxnew file mode 100644index 0000000000..f0582e0904--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx@@ -0,0 +1,586 @@+import { Fragment, useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import {+ SvgCheveronDown,+ SvgCheveronRight,+} from '@actual-app/components/icons/v1';+import { styles } from '@actual-app/components/styles';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+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 type {+ MonteCarloPot,+ MonteCarloRunDetailRow,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { useFormat } from '#hooks/useFormat';++// The minWidth keeps amounts readable on narrow screens - the table+// scrolls sideways instead of letting columns collapse into each other+const AMOUNT_CELL_STYLE = {+ flex: 1,+ minWidth: 110,+ textAlign: 'right',+} as const;++type MonteCarloRunDetailTableProps = {+ rows: MonteCarloRunDetailRow[];+ pots: MonteCarloPot[];+ simulationIndex: number;+ simulationCount: number;+ startAge: number;+ onBack: () => void;+};++export function MonteCarloRunDetailTable({+ rows,+ pots,+ simulationIndex,+ simulationCount,+ startAge,+ onBack,+}: MonteCarloRunDetailTableProps) {+ const { t } = useTranslation();+ const format = useFormat();+ const [expandedYears, setExpandedYears] = useState<Set<number>>(new Set());++ const lastRow = rows[rows.length - 1];+ const hasSurvived = lastRow != null && lastRow.endBalance > 0;+ const allExpanded = rows.length > 0 && expandedYears.size === rows.length;++ function toggleYear(year: number) {+ setExpandedYears(previous => {+ const next = new Set(previous);+ if (next.has(year)) {+ next.delete(year);+ } else {+ next.add(year);+ }+ return next;+ });+ }++ // Run-level cost of the plan: what left the pots, and how much of it+ // went to tax and fees rather than spending+ let totalWithdrawn = 0;+ let totalTax = 0;+ let totalFees = 0;+ for (const row of rows) {+ totalWithdrawn += row.withdrawal;+ totalTax += row.taxPaid;+ totalFees += row.feesPaid;+ }++ // Four sentence variants so each language can phrase the combinations+ // naturally+ function getTotalsSentence() {+ const total = format(totalWithdrawn, 'financial');+ const tax = format(totalTax, 'financial');+ const fees = format(totalFees, 'financial');+ if (totalTax > 0 && totalFees > 0) {+ return t(+ 'Total withdrawn over this run: {{total}}, of which {{tax}} tax, plus {{fees}} paid in fees.',+ { total, tax, fees },+ );+ }+ if (totalTax > 0) {+ return t(+ 'Total withdrawn over this run: {{total}}, of which {{tax}} tax.',+ { total, tax },+ );+ }+ if (totalFees > 0) {+ return t(+ 'Total withdrawn over this run: {{total}}, plus {{fees}} paid in fees.',+ { total, fees },+ );+ }+ return t('Total withdrawn over this run: {{total}}.', { total });+ }++ return (+ <View>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 15,+ marginBottom: 10,+ }}+ >+ <Button onPress={onBack}>+ <Trans>Back to all runs</Trans>+ </Button>+ <Text style={{ fontWeight: 600 }}>+ {hasSurvived+ ? t('Run {{number}} of {{total}} - survived to age {{age}}', {+ number: simulationIndex + 1,+ total: simulationCount,+ age: lastRow ? startAge + lastRow.year : startAge,+ })+ : t('Run {{number}} of {{total}} - ran out at age {{age}}', {+ number: simulationIndex + 1,+ total: simulationCount,+ // The failure row's own age: the year the withdrawal+ // couldn't be funded+ age: lastRow ? startAge + lastRow.year - 1 : startAge,+ })}+ </Text>+ <Button+ variant="bare"+ onPress={() =>+ setExpandedYears(+ allExpanded ? new Set() : new Set(rows.map(row => row.year)),+ )+ }+ style={{ marginLeft: 'auto', color: theme.pageText }}+ >+ {allExpanded ? (+ <Trans>Collapse all years</Trans>+ ) : (+ <Trans>Expand all years</Trans>+ )}+ </Button>+ </View>++ <Text style={{ fontSize: 13, color: theme.pageText, marginBottom: 10 }}>+ <PrivacyFilter>+ <FinancialText as="span">{getTotalsSentence()}</FinancialText>+ </PrivacyFilter>+ </Text>++ <View style={{ ...styles.horizontalScrollbar, overflowX: 'auto' }}>+ <View style={{ minWidth: 'fit-content' }}>+ {/* Header row */}+ <View+ style={{+ flexDirection: 'row',+ paddingBottom: 8,+ borderBottom: `1px solid ${theme.tableBorder}`,+ gap: 10,+ }}+ >+ <View style={{ width: 36 }} />+ <Text style={{ ...GROUP_HEADING_STYLE, width: 60 }}>+ <Trans>Age</Trans>+ </Text>+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>+ <Trans>Starting balance</Trans>+ </Text>+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>+ <Trans>Withdrawal</Trans>+ </Text>+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>+ <Trans>Investment growth</Trans>+ </Text>+ <Text+ style={{ ...GROUP_HEADING_STYLE, width: 90, textAlign: 'right' }}+ >+ <Trans>Return (%)</Trans>+ </Text>+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>+ <Trans>Ending balance</Trans>+ </Text>+ </View>++ {rows.map(row => {+ const isFailureRow = row === lastRow && !hasSurvived;+ const isExpanded = expandedYears.has(row.year);+ // Growth applies to what stayed invested after the withdrawal;+ // no growth on a failure year (the plan stops there)+ const growthBase = row.startBalance - row.withdrawal;+ const growthPct =+ !isFailureRow && growthBase > 0+ ? (row.growth / growthBase) * 100+ : null;+ const netSpending = row.withdrawal - row.taxPaid;+ return (+ <Fragment key={row.year}>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ padding: '6px 0',+ borderBottom: `1px solid ${theme.tableBorder}`,+ gap: 10,+ }}+ >+ <View style={{ width: 36, alignItems: 'center' }}>+ <Button+ variant="bare"+ aria-label={+ isExpanded+ ? t("Hide this year's breakdown")+ : t("Show this year's breakdown")+ }+ onPress={() => toggleYear(row.year)}+ style={{ padding: 4 }}+ >+ {isExpanded ? (+ <SvgCheveronDown width={14} height={14} />+ ) : (+ <SvgCheveronRight width={14} height={14} />+ )}+ </Button>+ </View>+ <Text style={{ width: 60 }}>+ <FinancialText as="span">+ {String(startAge + row.year - 1)}+ </FinancialText>+ </Text>+ <Text style={AMOUNT_CELL_STYLE}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(row.startBalance, 'financial')}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text style={AMOUNT_CELL_STYLE}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(row.withdrawal, 'financial')}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text+ style={{+ ...AMOUNT_CELL_STYLE,+ color:+ row.growth >= 0+ ? theme.reportsNumberPositive+ : theme.reportsNumberNegative,+ }}+ >+ {!isFailureRow && (+ <PrivacyFilter>+ <FinancialText as="span">+ {format(row.growth, 'financial')}+ </FinancialText>+ </PrivacyFilter>+ )}+ </Text>+ <Text+ style={{+ width: 90,+ textAlign: 'right',+ color:+ row.growth >= 0+ ? theme.reportsNumberPositive+ : theme.reportsNumberNegative,+ }}+ >+ {growthPct != null && (+ <FinancialText as="span">{`${growthPct.toFixed(2)}%`}</FinancialText>+ )}+ </Text>+ <Text style={AMOUNT_CELL_STYLE}>+ <PrivacyFilter>+ <FinancialText as="span">+ {/* On a bridge-gap failure the true remaining balance+ is the locked money, not zero */}+ {format(+ row.inaccessibleBalance ?? row.endBalance,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ </View>++ {isExpanded && (+ <View+ style={{+ borderBottom: `1px solid ${theme.tableBorder}`,+ padding: '10px 12px 12px 46px',+ gap: 4,+ }}+ >+ <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>+ {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>+ )}++ {pots.length > 0 && (+ <View style={{ marginTop: 6, maxWidth: 1010 }}>+ <View+ style={{+ flexDirection: 'row',+ gap: 10,+ paddingBottom: 4,+ borderBottom: `1px solid ${theme.tableBorder}`,+ }}+ >+ <Text+ style={{+ ...GROUP_HEADING_STYLE,+ flex: 1,+ minWidth: 120,+ }}+ >+ <Trans>Pot</Trans>+ </Text>+ <Text+ style={{+ ...GROUP_HEADING_STYLE,+ width: 130,+ textAlign: 'right',+ }}+ >+ <Trans>Start balance</Trans>+ </Text>+ <Text+ style={{+ ...GROUP_HEADING_STYLE,+ width: 130,+ textAlign: 'right',+ }}+ >+ <Trans>Withdrawn</Trans>+ </Text>+ <Text+ style={{+ ...GROUP_HEADING_STYLE,+ width: 110,+ textAlign: 'right',+ }}+ >+ <Trans>Taxable</Trans>+ </Text>+ <View+ style={{+ width: 110,+ flexDirection: 'row',+ justifyContent: 'flex-end',+ alignItems: 'center',+ gap: 4,+ }}+ >+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Tax paid</Trans>+ </Text>+ <MonteCarloHelpTooltip placement="bottom end">+ <Trans>+ With tax bands, the year's tax is worked+ out on all pots' taxable income together,+ then shared here in proportion to each+ pot's taxable income - so every taxable+ pound bears the year's average rate, even+ from a small pot. With a flat rate per pot, each+ pot's tax is exact.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <View+ style={{+ width: 110,+ flexDirection: 'row',+ justifyContent: 'flex-end',+ alignItems: 'center',+ gap: 4,+ }}+ >+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Fees</Trans>+ </Text>+ <MonteCarloHelpTooltip placement="bottom end">+ <Trans>+ Charged at the end of the year, on the+ pot's balance after that year's growth+ but before the fee itself is deducted - so the+ end balance is the post-growth balance minus+ this fee.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <Text+ style={{+ ...GROUP_HEADING_STYLE,+ width: 90,+ textAlign: 'right',+ }}+ >+ <Trans>Return (%)</Trans>+ </Text>+ <Text+ style={{+ ...GROUP_HEADING_STYLE,+ width: 130,+ textAlign: 'right',+ }}+ >+ <Trans>End balance</Trans>+ </Text>+ </View>+ {pots.map((pot, potIndex) => {+ const potReturn = row.potReturns[potIndex];+ return (+ <View+ key={pot.id}+ style={{+ flexDirection: 'row',+ gap: 10,+ padding: '3px 0',+ }}+ >+ <Text style={{ flex: 1, minWidth: 120 }}>+ {pot.name ||+ t('Pot {{number}}', {+ number: potIndex + 1,+ })}+ </Text>+ <Text style={{ width: 130, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ row.potStartBalances[potIndex] ?? 0,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text style={{ width: 130, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ row.potWithdrawals[potIndex] ?? 0,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text style={{ width: 110, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ row.potTaxables[potIndex] ?? 0,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text style={{ width: 110, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ row.potTaxes[potIndex] ?? 0,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text style={{ width: 110, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ row.potFees[potIndex] ?? 0,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ <Text+ style={{+ width: 90,+ textAlign: 'right',+ color:+ potReturn == null+ ? theme.pageText+ : potReturn >= 0+ ? theme.reportsNumberPositive+ : theme.reportsNumberNegative,+ }}+ >+ {potReturn != null && (+ <FinancialText as="span">+ {`${(potReturn * 100).toFixed(2)}%`}+ </FinancialText>+ )}+ </Text>+ <Text style={{ width: 130, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ row.potBalances[potIndex] ?? 0,+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ </View>+ );+ })}+ </View>+ )}+ </View>+ )}+ </Fragment>+ );+ })}+ </View>+ </View>++ {lastRow?.inaccessibleBalance != null && (+ <Text style={{ marginTop: 10, color: theme.pageText }}>+ {t(+ 'The plan failed at age {{age}} with {{amount}} still locked in pots that had not reached their access age.',+ {+ age: startAge + lastRow.year - 1,+ amount: format(lastRow.inaccessibleBalance, 'financial'),+ },+ )}+ </Text>+ )}+ </View>+ );+}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.tsxnew file mode 100644index 0000000000..554a3d25a5--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunsTable.tsx@@ -0,0 +1,284 @@+import { useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { Select } from '@actual-app/components/select';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { FinancialText } from '#components/FinancialText';+import { PrivacyFilter } from '#components/PrivacyFilter';+import { GROUP_HEADING_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { useFormat } from '#hooks/useFormat';++const PAGE_SIZE = 20;++type SortOrder = 'worst-first' | 'best-first';++type MonteCarloRunsTableProps = {+ endingBalances: Float64Array;+ depletionYearBySimulation: Int32Array;+ totalWithdrawnBySimulation: Float64Array;+ startAge: number;+ onSelectRun: (simulationIndex: number) => void;+};++export function MonteCarloRunsTable({+ endingBalances,+ depletionYearBySimulation,+ totalWithdrawnBySimulation,+ startAge,+ onSelectRun,+}: MonteCarloRunsTableProps) {+ const { t } = useTranslation();+ const format = useFormat();++ const [sortOrder, setSortOrder] = useState<SortOrder>('worst-first');+ const [page, setPage] = useState(0);+ const [highlightedRank, setHighlightedRank] = useState<number | null>(null);++ const simulationCount = endingBalances.length;++ // Jump straight to a given percentile of the ranked outcomes (0 = worst,+ // 1 = best), landing on its page and highlighting the exact run+ function jumpToPercentile(percentile: number) {+ const worstFirstRank = Math.round(percentile * (simulationCount - 1));+ const rank =+ sortOrder === 'worst-first'+ ? worstFirstRank+ : simulationCount - 1 - worstFirstRank;+ setPage(Math.floor(rank / PAGE_SIZE));+ 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,+ );+ 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();+ }++ const pageCount = Math.max(1, Math.ceil(simulationCount / PAGE_SIZE));+ const currentPage = Math.min(page, pageCount - 1);+ const pageStart = currentPage * PAGE_SIZE;+ const pageIndices = rankedIndices.slice(pageStart, pageStart + PAGE_SIZE);++ return (+ <View>+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: 10,+ marginBottom: 10,+ }}+ >+ <Text>+ {t('Showing {{from}}-{{to}} of {{total}} runs', {+ from: pageStart + 1,+ to: pageStart + pageIndices.length,+ total: simulationCount,+ })}+ </Text>+ <Select+ value={sortOrder}+ onChange={value => {+ setSortOrder(value as SortOrder);+ setPage(0);+ setHighlightedRank(null);+ }}+ options={[+ ['worst-first', t('Worst outcomes first')],+ ['best-first', t('Best outcomes first')],+ ]}+ style={{ width: 200 }}+ />+ </View>++ {/* Header row */}+ <View+ style={{+ flexDirection: 'row',+ paddingBottom: 8,+ paddingLeft: 8,+ paddingRight: 8,+ borderBottom: `1px solid ${theme.tableBorder}`,+ gap: 10,+ }}+ >+ <Text style={{ ...GROUP_HEADING_STYLE, width: 80 }}>+ <Trans>Rank</Trans>+ </Text>+ <Text style={{ ...GROUP_HEADING_STYLE, flex: 1 }}>+ <Trans>Outcome</Trans>+ </Text>+ <Text+ style={{ ...GROUP_HEADING_STYLE, width: 160, textAlign: 'right' }}+ >+ <Trans>Ending balance</Trans>+ </Text>+ <Text+ style={{ ...GROUP_HEADING_STYLE, width: 160, textAlign: 'right' }}+ >+ <Trans>Total withdrawn</Trans>+ </Text>+ </View>++ {pageIndices.map((simulationIndex, rowNumber) => {+ const depletionYear = depletionYearBySimulation[simulationIndex];+ const hasSurvived = depletionYear === -1;+ const isHighlighted = highlightedRank === pageStart + rowNumber;+ return (+ <Button+ key={simulationIndex}+ variant="bare"+ onPress={() => onSelectRun(simulationIndex)}+ style={{+ padding: '8px 0',+ borderBottom: `1px solid ${theme.tableBorder}`,+ borderRadius: 0,+ ...(isHighlighted && {+ backgroundColor: theme.tableRowBackgroundHighlight,+ }),+ }}+ >+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ flex: 1,+ gap: 10,+ paddingLeft: 8,+ paddingRight: 8,+ }}+ >+ <Text style={{ width: 80, textAlign: 'left' }}>+ <FinancialText as="span">+ {String(pageStart + rowNumber + 1)}+ </FinancialText>+ </Text>+ <Text+ style={{+ flex: 1,+ textAlign: 'left',+ color: hasSurvived+ ? theme.reportsNumberPositive+ : theme.reportsNumberNegative,+ }}+ >+ {hasSurvived+ ? t('Survived')+ : t('Ran out at age {{age}}', {+ // The age of the year that couldn't be funded, matching+ // the drill-in's failure row+ age: startAge + depletionYear - 1,+ })}+ </Text>+ <Text style={{ width: 160, textAlign: 'right' }}>+ {hasSurvived ? (+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ Math.round(endingBalances[simulationIndex]),+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ ) : (+ <FinancialText as="span">-</FinancialText>+ )}+ </Text>+ <Text style={{ width: 160, textAlign: 'right' }}>+ <PrivacyFilter>+ <FinancialText as="span">+ {format(+ Math.round(totalWithdrawnBySimulation[simulationIndex]),+ 'financial',+ )}+ </FinancialText>+ </PrivacyFilter>+ </Text>+ </View>+ </Button>+ );+ })}+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ gap: 10,+ // Stays pinned right, and drops to its own line when the jump+ // links need the full width+ marginLeft: 'auto',+ marginTop: 10,+ }}+ >+ <Select+ // An action picker, not a setting: the value stays on the+ // placeholder so it always reads "Jump to..." at rest+ value=""+ onChange={value => {+ if (value !== '') {+ 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')],+ ]}+ style={{ width: 170 }}+ />+ <Button+ isDisabled={currentPage === 0}+ onPress={() => {+ setPage(currentPage - 1);+ setHighlightedRank(null);+ }}+ >+ <Trans>Previous</Trans>+ </Button>+ <Button+ isDisabled={currentPage >= pageCount - 1}+ onPress={() => {+ setPage(currentPage + 1);+ setHighlightedRank(null);+ }}+ >+ <Trans>Next</Trans>+ </Button>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloSpendingPhases.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloSpendingPhases.tsxnew file mode 100644index 0000000000..1ba01c81dc--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloSpendingPhases.tsx@@ -0,0 +1,250 @@+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 { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import { v4 as uuidv4 } from 'uuid';++import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';+import {+ createMonteCarloSpendingPhase,+ MAX_AMOUNT,+ sortMonteCarloSpendingPhases,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type { MonteCarloSpendingPhase } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { FIELD_LABEL_STYLE } from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { Field, Row, TableHeader } from '#components/table';+import { FinancialInput } from '#components/util/FinancialInput';++// Fixed remove column; the rest flex evenly with these minimum widths+const PHASE_COLUMNS = {+ name: 150,+ fromAge: 110,+ until: 110,+ spending: 150,+ remove: 36,+} as const;++const PHASE_ROW_HEIGHT = 43;++type MonteCarloSpendingPhasesProps = {+ phases: MonteCarloSpendingPhase[];+ currentAge: number;+ targetAge: number;+ onPhasesChange: (phases: MonteCarloSpendingPhase[]) => void;+};++export function MonteCarloSpendingPhases({+ phases,+ currentAge,+ targetAge,+ onPhasesChange,+}: MonteCarloSpendingPhasesProps) {+ const { t } = useTranslation();++ function updatePhase(+ phaseId: string,+ changes: Partial<MonteCarloSpendingPhase>,+ ) {+ onPhasesChange(+ sortMonteCarloSpendingPhases(+ phases.map(phase =>+ phase.id === phaseId ? { ...phase, ...changes } : phase,+ ),+ ),+ );+ }++ function removePhase(phaseId: string) {+ const remaining = phases.filter(phase => phase.id !== phaseId);+ // The first phase always starts immediately+ if (remaining.length > 0 && remaining[0].fromAge != null) {+ remaining[0] = { ...remaining[0], fromAge: null };+ }+ onPhasesChange(remaining);+ }++ function addPhase() {+ const lastFrom = phases[phases.length - 1]?.fromAge ?? currentAge;+ const fromAge = Math.max(+ currentAge + 1,+ Math.min(targetAge - 1, lastFrom + 10),+ );+ onPhasesChange(+ sortMonteCarloSpendingPhases([+ ...phases,+ createMonteCarloSpendingPhase(uuidv4(), fromAge),+ ]),+ );+ }++ return (+ <View style={{ gap: 10, marginBottom: 20 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 5 }}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Spending phases</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Your yearly spending doesn't have to stay the same for the+ whole plan. Each phase sets the yearly amount from a given age until+ the next phase begins - for example, more in your active early years+ and less later on.+ <br />+ <br />+ Amounts are in today's money; the inflation settings on the+ Plan details tab are applied on top.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>++ <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: PHASE_COLUMNS.name }}>+ <Trans>Phase name</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: PHASE_COLUMNS.fromAge }}>+ <Trans>From age</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: PHASE_COLUMNS.until }}>+ <Trans>Until</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: PHASE_COLUMNS.spending }}>+ <Trans>Yearly spending</Trans>+ </Field>+ <Field width={PHASE_COLUMNS.remove} />+ </TableHeader>++ {phases.map((phase, index) => {+ const nextPhase = phases[index + 1];+ return (+ <Row+ key={phase.id}+ collapsed+ height={PHASE_ROW_HEIGHT}+ style={{+ backgroundColor: theme.tableBackground,+ ':hover': { backgroundColor: theme.tableRowBackgroundHover },+ }}+ >+ <Field+ width="flex"+ style={{ minWidth: PHASE_COLUMNS.name }}+ truncate={false}+ >+ <Input+ // Uncontrolled on purpose: committing on blur keeps typing+ // snappy since every config change re-runs the simulation+ defaultValue={phase.name}+ placeholder={t('Phase {{number}}', { number: index + 1 })}+ onUpdate={newName => {+ if (newName !== phase.name) {+ updatePhase(phase.id, { name: newName });+ }+ }}+ />+ </Field>++ <Field+ width="flex"+ style={{ minWidth: PHASE_COLUMNS.fromAge }}+ truncate={false}+ >+ {index === 0 ? (+ <Text style={{ color: theme.tableText }}>+ {t('Now ({{age}})', { age: currentAge })}+ </Text>+ ) : (+ <MonteCarloNumberInput+ value={phase.fromAge}+ aria-label={t('From age')}+ roundToInteger+ min={currentAge + 1}+ max={targetAge}+ step={1}+ onCommit={newValue =>+ updatePhase(phase.id, {+ fromAge: newValue ?? currentAge + 1,+ })+ }+ />+ )}+ </Field>++ <Field+ width="flex"+ style={{ minWidth: PHASE_COLUMNS.until }}+ truncate={false}+ >+ <Text style={{ color: theme.tableText }}>+ {nextPhase?.fromAge != null+ ? t('Age {{age}}', { age: nextPhase.fromAge - 1 })+ : t('Onwards')}+ </Text>+ </Field>++ <Field+ width="flex"+ style={{ minWidth: PHASE_COLUMNS.spending }}+ truncate={false}+ >+ <FinancialInput+ value={phase.annualWithdrawal}+ onUpdate={value =>+ updatePhase(phase.id, {+ annualWithdrawal: Math.min(+ MAX_AMOUNT,+ Math.max(0, value),+ ),+ })+ }+ />+ </Field>++ <Field+ width={PHASE_COLUMNS.remove}+ truncate={false}+ style={{ alignItems: 'center' }}+ >+ {phases.length > 1 && (+ <Button+ variant="bare"+ aria-label={t('Remove phase')}+ onPress={() => removePhase(phase.id)}+ style={{ padding: 6 }}+ >+ <SvgDelete width={12} height={12} />+ </Button>+ )}+ </Field>+ </Row>+ );+ })}+ </View>+ </View>++ <View style={{ flexDirection: 'row' }}>+ <Button onPress={addPhase}>+ <SvgAdd width={10} height={10} style={{ marginRight: 5 }} />+ <Trans>Add phase</Trans>+ </Button>+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloTaxConfiguration.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloTaxConfiguration.tsxnew file mode 100644index 0000000000..e5eda82f5b--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloTaxConfiguration.tsx@@ -0,0 +1,217 @@+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 { Select } 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';+import { View } from '@actual-app/components/view';+import type { MonteCarloTaxModel } from '@actual-app/core/types/models';+import { v4 as uuidv4 } from 'uuid';++import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';+import {+ createMonteCarloTaxBand,+ MAX_AMOUNT,+ MAX_TAX_BAND_RATE,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type {+ MonteCarloConfig,+ MonteCarloTaxBand,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import {+ FIELD_LABEL_ROW_STYLE,+ FIELD_LABEL_STYLE,+} from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { Field, Row, TableHeader } from '#components/table';+import { FinancialInput } from '#components/util/FinancialInput';++const BAND_ROW_HEIGHT = 43;++function sortBands(bands: MonteCarloTaxBand[]) {+ return [...bands].sort((bandA, bandB) => bandA.from - bandB.from);+}++type MonteCarloTaxConfigurationProps = {+ taxModel: MonteCarloTaxModel;+ taxBands: MonteCarloTaxBand[];+ onConfigChange: (changes: Partial<MonteCarloConfig>) => void;+};++export function MonteCarloTaxConfiguration({+ taxModel,+ taxBands,+ onConfigChange,+}: MonteCarloTaxConfigurationProps) {+ const { t } = useTranslation();++ function updateBand(bandId: string, changes: Partial<MonteCarloTaxBand>) {+ onConfigChange({+ taxBands: sortBands(+ taxBands.map(band =>+ band.id === bandId ? { ...band, ...changes } : band,+ ),+ ),+ });+ }++ function removeBand(bandId: string) {+ const remaining = taxBands.filter(band => band.id !== bandId);+ // The first band always starts at zero income+ if (remaining.length > 0 && remaining[0].from !== 0) {+ remaining[0] = { ...remaining[0], from: 0 };+ }+ onConfigChange({ taxBands: remaining });+ }++ function addBand() {+ const lastFrom = taxBands[taxBands.length - 1]?.from ?? 0;+ onConfigChange({+ taxBands: sortBands([+ ...taxBands,+ createMonteCarloTaxBand(uuidv4(), lastFrom + 2_500_000),+ ]),+ });+ }++ return (+ <View style={{ gap: 10 }}>+ <View style={{ width: 250 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Tax model</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Your yearly spending is what you keep after tax; the simulation+ withdraws extra to cover the tax.+ <br />+ <br />+ Flat rate: each pot has one effective tax rate on its withdrawals+ - simple and jurisdiction-free.+ <br />+ <br />+ Tax bands: enter your own progressive bands, and each pot declares+ how much of a withdrawal counts as taxable income. The bands apply+ to each year's combined taxable withdrawals.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <Select+ value={taxModel}+ onChange={value =>+ onConfigChange({ taxModel: value as MonteCarloTaxModel })+ }+ options={[+ ['flat', t('Flat rate per pot')],+ ['bands', t('Tax bands (progressive)')],+ ]}+ />+ </View>++ {taxModel === 'flat' ? (+ <Text style={{ color: theme.pageText }}>+ <Trans>+ Set each pot's Tax (%) on the Investment pots tab. Leave it at+ 0 for tax-free pots.+ </Trans>+ </Text>+ ) : (+ <>+ <Text style={{ color: theme.pageText }}>+ <Trans>+ Amounts are yearly taxable income in today's money - the+ thresholds rise with inflation. Set each pot's Taxable+ portion (%) on the Investment pots tab.+ </Trans>+ </Text>++ <View style={{ ...styles.tableContainer, flex: 'unset' }}>+ <TableHeader>+ <Field width="flex" style={{ minWidth: 160 }}>+ <Trans>Income from</Trans>+ </Field>+ <Field width="flex" style={{ minWidth: 140 }}>+ <Trans>Taxed at (%)</Trans>+ </Field>+ <Field width={36} />+ </TableHeader>++ {taxBands.map((band, index) => (+ <Row+ key={band.id}+ collapsed+ height={BAND_ROW_HEIGHT}+ style={{+ backgroundColor: theme.tableBackground,+ ':hover': { backgroundColor: theme.tableRowBackgroundHover },+ }}+ >+ <Field width="flex" style={{ minWidth: 160 }} truncate={false}>+ {index === 0 ? (+ <Text style={{ color: theme.tableText }}>+ <Trans>First earnings</Trans>+ </Text>+ ) : (+ <FinancialInput+ value={band.from}+ onUpdate={value => {+ const newFrom = Math.min(+ MAX_AMOUNT,+ Math.max(0, value),+ );+ if (newFrom !== band.from) {+ updateBand(band.id, { from: newFrom });+ }+ }}+ />+ )}+ </Field>++ <Field width="flex" style={{ minWidth: 140 }} truncate={false}>+ <MonteCarloNumberInput+ value={band.rate}+ aria-label={t('Taxed at (%)')}+ scale={100}+ min={0}+ max={MAX_TAX_BAND_RATE * 100}+ onCommit={newValue =>+ updateBand(band.id, { rate: newValue ?? 0 })+ }+ />+ </Field>++ <Field+ width={36}+ truncate={false}+ style={{ alignItems: 'center' }}+ >+ {taxBands.length > 1 && (+ <Button+ variant="bare"+ aria-label={t('Remove band')}+ onPress={() => removeBand(band.id)}+ style={{ padding: 6 }}+ >+ <SvgDelete width={12} height={12} />+ </Button>+ )}+ </Field>+ </Row>+ ))}+ </View>++ <View style={{ flexDirection: 'row' }}>+ <Button onPress={addBand}>+ <SvgAdd width={10} height={10} style={{ marginRight: 5 }} />+ <Trans>Add band</Trans>+ </Button>+ </View>+ </>+ )}+ </View>+ );+}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.tsxnew file mode 100644index 0000000000..30e2035403--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration.tsx@@ -0,0 +1,326 @@+import { Trans, useTranslation } from 'react-i18next';++import { Select } from '@actual-app/components/select';+import { Text } from '@actual-app/components/text';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import type { MonteCarloWithdrawalRuleType } from '@actual-app/core/types/models';++import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';+import { MAX_AMOUNT } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type { MonteCarloWithdrawalRuleConfig } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import {+ FIELD_LABEL_ROW_STYLE,+ FIELD_LABEL_STYLE,+ FIELD_STYLE,+} from '#components/reports/reports/monte-carlo/monteCarloStyles';+import { FinancialInput } from '#components/util/FinancialInput';++const SENTENCE_STYLE = {+ color: theme.pageText,+ // Room for the inline inputs without cramped line wrapping+ lineHeight: 2.6,+} as const;++const INLINE_INPUT_STYLE = {+ width: 70,+ display: 'inline-block',+ textAlign: 'center',+ margin: '0 6px',+} as const;++type MonteCarloWithdrawalRuleConfigurationProps = {+ rule: MonteCarloWithdrawalRuleConfig;+ minimumWithdrawal: number;+ onRuleChange: (changes: Partial<MonteCarloWithdrawalRuleConfig>) => void;+ onMinimumWithdrawalChange: (value: number) => void;+};++export function MonteCarloWithdrawalRuleConfiguration({+ rule,+ minimumWithdrawal,+ onRuleChange,+ onMinimumWithdrawalChange,+}: MonteCarloWithdrawalRuleConfigurationProps) {+ const { t } = useTranslation();++ return (+ <View style={{ marginTop: 20, gap: 10 }}>+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 20 }}>+ <View style={{ width: 250 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Withdrawal rule</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Dynamic strategies that adjust your withdrawal each year based+ on how the pots are doing, instead of blindly taking the same+ inflation-adjusted amount.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <Select+ value={rule.type}+ onChange={value =>+ onRuleChange({ type: value as MonteCarloWithdrawalRuleType })+ }+ options={[+ ['none', t('None (fixed withdrawals)')],+ ['guardrails', t('Guardrails (Guyton-Klinger)')],+ ['ratcheting', t('Ratcheting (Kitces)')],+ ['floor-ceiling', t('Floor & ceiling (Bengen)')],+ ['boundaries', t('Boundaries')],+ ]}+ />+ </View>++ {rule.type !== 'none' && (+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Minimum withdrawal</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.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <FinancialInput+ value={minimumWithdrawal}+ onUpdate={value =>+ onMinimumWithdrawalChange(+ Math.min(MAX_AMOUNT, Math.max(0, value)),+ )+ }+ />+ </View>+ )}+ </View>++ {rule.type === 'guardrails' && (+ <View>+ <Text style={SENTENCE_STYLE}>+ <Text style={{ fontWeight: 600 }}>+ <Trans>Capital preservation rule:</Trans>+ </Text>{' '}+ <Trans>+ If the withdrawal rate rises more than+ <MonteCarloNumberInput+ value={rule.preservationTriggerPct}+ aria-label={t('Capital preservation trigger (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ preservationTriggerPct: newValue ?? 0 })+ }+ />+ % above the planned rate, cut withdrawals by+ <MonteCarloNumberInput+ value={rule.preservationCutPct}+ aria-label={t('Capital preservation cut (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ preservationCutPct: newValue ?? 0 })+ }+ />+ %.+ </Trans>+ </Text>+ <Text style={SENTENCE_STYLE}>+ <Text style={{ fontWeight: 600 }}>+ <Trans>Prosperity rule:</Trans>+ </Text>{' '}+ <Trans>+ If the withdrawal rate falls more than+ <MonteCarloNumberInput+ value={rule.prosperityTriggerPct}+ aria-label={t('Prosperity trigger (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ prosperityTriggerPct: newValue ?? 0 })+ }+ />+ % below the planned rate, raise withdrawals by+ <MonteCarloNumberInput+ value={rule.prosperityIncreasePct}+ aria-label={t('Prosperity raise (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ prosperityIncreasePct: newValue ?? 0 })+ }+ />+ %.+ </Trans>+ </Text>+ </View>+ )}++ {rule.type === 'ratcheting' && (+ <Text style={SENTENCE_STYLE}>+ <Trans>+ If the accessible balance stays above+ <MonteCarloNumberInput+ value={rule.balanceThresholdMultiple}+ aria-label={t('Balance threshold multiple')}+ min={1}+ max={10}+ step={0.1}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ balanceThresholdMultiple: newValue ?? 1.5 })+ }+ />+ times its starting level for+ <MonteCarloNumberInput+ value={rule.consecutiveYears}+ aria-label={t('Years in a row')}+ roundToInteger+ min={1}+ max={30}+ step={1}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ consecutiveYears: newValue ?? 1 })+ }+ />+ years in a row, raise withdrawals by+ <MonteCarloNumberInput+ value={rule.ratchetIncreasePct}+ aria-label={t('Ratchet raise (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ ratchetIncreasePct: newValue ?? 0 })+ }+ />+ %.+ </Trans>+ </Text>+ )}++ {rule.type === 'floor-ceiling' && (+ <Text style={SENTENCE_STYLE}>+ <Trans>+ Each year, withdraw the starting rate's share of the current+ accessible balance, but never more than+ <MonteCarloNumberInput+ value={rule.ceilingPct}+ aria-label={t('Ceiling above planned amount (%)')}+ scale={100}+ min={0}+ max={200}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue => onRuleChange({ ceilingPct: newValue ?? 0 })}+ />+ % above or+ <MonteCarloNumberInput+ value={rule.floorPct}+ aria-label={t('Floor below planned amount (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue => onRuleChange({ floorPct: newValue ?? 0 })}+ />+ % below the planned amount.+ </Trans>+ </Text>+ )}++ {rule.type === 'boundaries' && (+ <View>+ <Text style={SENTENCE_STYLE}>+ <Trans>+ If the withdrawal rate rises above+ <MonteCarloNumberInput+ value={rule.upperRateThreshold}+ aria-label={t('Upper withdrawal rate threshold (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ upperRateThreshold: newValue ?? 0 })+ }+ />+ %, cut withdrawals by+ <MonteCarloNumberInput+ value={rule.upperCutPct}+ aria-label={t('Cut when above the upper threshold (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ upperCutPct: newValue ?? 0 })+ }+ />+ %.+ </Trans>+ </Text>+ <Text style={SENTENCE_STYLE}>+ <Trans>+ If the withdrawal rate falls below+ <MonteCarloNumberInput+ value={rule.lowerRateThreshold}+ aria-label={t('Lower withdrawal rate threshold (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ lowerRateThreshold: newValue ?? 0 })+ }+ />+ %, raise withdrawals by+ <MonteCarloNumberInput+ value={rule.lowerIncreasePct}+ aria-label={t('Raise when below the lower threshold (%)')}+ scale={100}+ min={0}+ max={100}+ style={INLINE_INPUT_STYLE}+ onCommit={newValue =>+ onRuleChange({ lowerIncreasePct: newValue ?? 0 })+ }+ />+ %.+ </Trans>+ </Text>+ </View>+ )}++ {rule.type !== 'none' && (+ <Text style={{ color: theme.pageText, fontSize: 13 }}>+ {rule.type === 'guardrails'+ ? t(+ 'A deliberate spending-phase change is not counted as drift. The rule adjusts your planned spending year by year, independently in every scenario, and only looks at the pots you can currently access - locked pots count from the moment they unlock.',+ )+ : t(+ 'The rule adjusts your planned spending year by year, independently in every scenario, and only looks at the pots you can currently access - locked pots count from the moment they unlock.',+ )}+ </Text>+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloHistoricalReturns.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloHistoricalReturns.tsnew file mode 100644index 0000000000..503f56dbb5--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloHistoricalReturns.ts@@ -0,0 +1,118 @@+// Historical annual nominal returns for US asset classes, used by the+// historical return models. stocks = S&P 500 total return (incl. dividends),+// bonds = US 10-year Treasury total return, cash = 3-month T-bill.+//+// Source: Aswath Damodaran, NYU Stern - 'Historical Returns on Stocks,+// Bonds and Bills', https://pages.stern.nyu.edu/~adamodar/New_Home_Page/datafile/histretSP.html+// Data range: 1928-2025. Regenerate by re-extracting that table.+//+// Note: this is US data - the best freely available long-run series. It+// likely overstates outcomes for globally diversified portfolios.++export type HistoricalAnnualReturn = {+ year: number;+ stocks: number;+ bonds: number;+ cash: number;+};++export const HISTORICAL_ANNUAL_RETURNS: HistoricalAnnualReturn[] = [+ { year: 1928, stocks: 0.4381, bonds: 0.0084, cash: 0.0308 },+ { year: 1929, stocks: -0.083, bonds: 0.042, cash: 0.0316 },+ { year: 1930, stocks: -0.2512, bonds: 0.0454, cash: 0.0455 },+ { year: 1931, stocks: -0.4384, bonds: -0.0256, cash: 0.0231 },+ { year: 1932, stocks: -0.0864, bonds: 0.0879, cash: 0.0107 },+ { year: 1933, stocks: 0.4998, bonds: 0.0186, cash: 0.0096 },+ { year: 1934, stocks: -0.0119, bonds: 0.0796, cash: 0.0028 },+ { year: 1935, stocks: 0.4674, bonds: 0.0447, cash: 0.0017 },+ { year: 1936, stocks: 0.3194, bonds: 0.0502, cash: 0.0017 },+ { year: 1937, stocks: -0.3534, bonds: 0.0138, cash: 0.0028 },+ { year: 1938, stocks: 0.2928, bonds: 0.0421, cash: 0.0007 },+ { year: 1939, stocks: -0.011, bonds: 0.0441, cash: 0.0005 },+ { year: 1940, stocks: -0.1067, bonds: 0.054, cash: 0.0004 },+ { year: 1941, stocks: -0.1277, bonds: -0.0202, cash: 0.0013 },+ { year: 1942, stocks: 0.1917, bonds: 0.0229, cash: 0.0034 },+ { year: 1943, stocks: 0.2506, bonds: 0.0249, cash: 0.0038 },+ { year: 1944, stocks: 0.1903, bonds: 0.0258, cash: 0.0038 },+ { year: 1945, stocks: 0.3582, bonds: 0.038, cash: 0.0038 },+ { year: 1946, stocks: -0.0843, bonds: 0.0313, cash: 0.0038 },+ { year: 1947, stocks: 0.052, bonds: 0.0092, cash: 0.006 },+ { year: 1948, stocks: 0.057, bonds: 0.0195, cash: 0.0105 },+ { year: 1949, stocks: 0.183, bonds: 0.0466, cash: 0.0112 },+ { year: 1950, stocks: 0.3081, bonds: 0.0043, cash: 0.012 },+ { year: 1951, stocks: 0.2368, bonds: -0.003, cash: 0.0152 },+ { year: 1952, stocks: 0.1815, bonds: 0.0227, cash: 0.0172 },+ { year: 1953, stocks: -0.0121, bonds: 0.0414, cash: 0.0189 },+ { year: 1954, stocks: 0.5256, bonds: 0.0329, cash: 0.0094 },+ { year: 1955, stocks: 0.326, bonds: -0.0134, cash: 0.0172 },+ { year: 1956, stocks: 0.0744, bonds: -0.0226, cash: 0.0262 },+ { year: 1957, stocks: -0.1046, bonds: 0.068, cash: 0.0322 },+ { year: 1958, stocks: 0.4372, bonds: -0.021, cash: 0.0177 },+ { year: 1959, stocks: 0.1206, bonds: -0.0265, cash: 0.0339 },+ { year: 1960, stocks: 0.0034, bonds: 0.1164, cash: 0.0287 },+ { year: 1961, stocks: 0.2664, bonds: 0.0206, cash: 0.0235 },+ { year: 1962, stocks: -0.0881, bonds: 0.0569, cash: 0.0277 },+ { year: 1963, stocks: 0.2261, bonds: 0.0168, cash: 0.0316 },+ { year: 1964, stocks: 0.1642, bonds: 0.0373, cash: 0.0355 },+ { year: 1965, stocks: 0.124, bonds: 0.0072, cash: 0.0395 },+ { year: 1966, stocks: -0.0997, bonds: 0.0291, cash: 0.0486 },+ { year: 1967, stocks: 0.238, bonds: -0.0158, cash: 0.0429 },+ { year: 1968, stocks: 0.1081, bonds: 0.0327, cash: 0.0534 },+ { year: 1969, stocks: -0.0824, bonds: -0.0501, cash: 0.0667 },+ { year: 1970, stocks: 0.0356, bonds: 0.1675, cash: 0.0639 },+ { year: 1971, stocks: 0.1422, bonds: 0.0979, cash: 0.0433 },+ { year: 1972, stocks: 0.1876, bonds: 0.0282, cash: 0.0406 },+ { year: 1973, stocks: -0.1431, bonds: 0.0366, cash: 0.0704 },+ { year: 1974, stocks: -0.259, bonds: 0.0199, cash: 0.0785 },+ { year: 1975, stocks: 0.37, bonds: 0.0361, cash: 0.0579 },+ { year: 1976, stocks: 0.2383, bonds: 0.1598, cash: 0.0498 },+ { year: 1977, stocks: -0.0698, bonds: 0.0129, cash: 0.0526 },+ { year: 1978, stocks: 0.0651, bonds: -0.0078, cash: 0.0718 },+ { year: 1979, stocks: 0.1852, bonds: 0.0067, cash: 0.1005 },+ { year: 1980, stocks: 0.3174, bonds: -0.0299, cash: 0.1139 },+ { year: 1981, stocks: -0.047, bonds: 0.082, cash: 0.1404 },+ { year: 1982, stocks: 0.2042, bonds: 0.3281, cash: 0.1109 },+ { year: 1983, stocks: 0.2234, bonds: 0.032, cash: 0.0895 },+ { year: 1984, stocks: 0.0615, bonds: 0.1373, cash: 0.0992 },+ { year: 1985, stocks: 0.3124, bonds: 0.2571, cash: 0.0772 },+ { year: 1986, stocks: 0.1849, bonds: 0.2428, cash: 0.0615 },+ { year: 1987, stocks: 0.0581, bonds: -0.0496, cash: 0.0596 },+ { year: 1988, stocks: 0.1654, bonds: 0.0822, cash: 0.0689 },+ { year: 1989, stocks: 0.3148, bonds: 0.1769, cash: 0.0839 },+ { year: 1990, stocks: -0.0306, bonds: 0.0624, cash: 0.0775 },+ { year: 1991, stocks: 0.3023, bonds: 0.15, cash: 0.0554 },+ { year: 1992, stocks: 0.0749, bonds: 0.0936, cash: 0.0351 },+ { year: 1993, stocks: 0.0997, bonds: 0.1421, cash: 0.0307 },+ { year: 1994, stocks: 0.0133, bonds: -0.0804, cash: 0.0437 },+ { year: 1995, stocks: 0.372, bonds: 0.2348, cash: 0.0566 },+ { year: 1996, stocks: 0.2268, bonds: 0.0143, cash: 0.0515 },+ { year: 1997, stocks: 0.331, bonds: 0.0994, cash: 0.052 },+ { year: 1998, stocks: 0.2834, bonds: 0.1492, cash: 0.0491 },+ { year: 1999, stocks: 0.2089, bonds: -0.0825, cash: 0.0478 },+ { year: 2000, stocks: -0.0903, bonds: 0.1666, cash: 0.06 },+ { year: 2001, stocks: -0.1185, bonds: 0.0557, cash: 0.0348 },+ { year: 2002, stocks: -0.2197, bonds: 0.1512, cash: 0.0164 },+ { year: 2003, stocks: 0.2836, bonds: 0.0038, cash: 0.0103 },+ { year: 2004, stocks: 0.1074, bonds: 0.0449, cash: 0.014 },+ { year: 2005, stocks: 0.0483, bonds: 0.0287, cash: 0.0322 },+ { year: 2006, stocks: 0.1561, bonds: 0.0196, cash: 0.0485 },+ { year: 2007, stocks: 0.0548, bonds: 0.1021, cash: 0.0448 },+ { year: 2008, stocks: -0.3655, bonds: 0.201, cash: 0.014 },+ { year: 2009, stocks: 0.2594, bonds: -0.1112, cash: 0.0015 },+ { year: 2010, stocks: 0.1482, bonds: 0.0846, cash: 0.0014 },+ { year: 2011, stocks: 0.021, bonds: 0.1604, cash: 0.0005 },+ { year: 2012, stocks: 0.1589, bonds: 0.0297, cash: 0.0009 },+ { year: 2013, stocks: 0.3215, bonds: -0.091, cash: 0.0006 },+ { year: 2014, stocks: 0.1352, bonds: 0.1075, cash: 0.0003 },+ { year: 2015, stocks: 0.0138, bonds: 0.0128, cash: 0.0005 },+ { year: 2016, stocks: 0.1177, bonds: 0.0069, cash: 0.0032 },+ { year: 2017, stocks: 0.2161, bonds: 0.028, cash: 0.0095 },+ { year: 2018, stocks: -0.0423, bonds: -0.0002, cash: 0.0197 },+ { year: 2019, stocks: 0.3121, bonds: 0.0964, cash: 0.0211 },+ { year: 2020, stocks: 0.1802, bonds: 0.1133, cash: 0.0036 },+ { year: 2021, stocks: 0.2847, bonds: -0.0442, cash: 0.0004 },+ { year: 2022, stocks: -0.1804, bonds: -0.1783, cash: 0.0209 },+ { year: 2023, stocks: 0.2606, bonds: 0.0388, cash: 0.0528 },+ { year: 2024, stocks: 0.2488, bonds: -0.0164, cash: 0.0518 },+ { year: 2025, stocks: 0.1778, bonds: 0.078, cash: 0.0421 },+];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.tsnew file mode 100644index 0000000000..ca0bd99e33--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts@@ -0,0 +1,1775 @@+import { describe, expect, it } from 'vitest';++import {+ getMonteCarloHorizonYears,+ MAX_AMOUNT,+ MAX_HORIZON_YEARS,+ MIN_HORIZON_YEARS,+ MIN_SIMULATION_COUNT,+ runMonteCarloSimulation,+ WITHDRAWAL_RULE_DEFAULTS,+} from './monteCarloSimulation';+import type { MonteCarloParams, MonteCarloPot } from './monteCarloSimulation';++function makePot(overrides: Partial<MonteCarloPot> = {}): MonteCarloPot {+ return {+ id: 'pot-1',+ name: 'Test pot',+ startingBalance: 50_000_000,+ allocationPreset: 'custom',+ expectedReturnMean: 0.06,+ returnStdDev: 0.1,+ accessAge: null,+ accountId: null,+ withdrawalTaxRate: 0,+ taxableFraction: 1,+ annualFeeFixed: 0,+ feeAdjustsWithInflation: false,+ annualFeeRate: 0,+ ...overrides,+ };+}++function makeParams(+ overrides: Partial<MonteCarloParams> & { annualWithdrawal?: number } = {},+ potOverrides: Partial<MonteCarloPot> = {},+): MonteCarloParams {+ // Convenience: a plain annualWithdrawal becomes a single spending phase+ const { annualWithdrawal = 2_000_000, ...rest } = overrides;+ return {+ pots: [makePot(potOverrides)],+ withdrawalStrategy: 'proportional',+ returnModel: 'normal',+ withdrawalRule: WITHDRAWAL_RULE_DEFAULTS,+ minimumWithdrawal: 0,+ currentAge: 60,+ spendingPhases: [+ { id: 'phase-1', name: '', fromAge: null, annualWithdrawal },+ ],+ inflationMean: null,+ inflationStdDev: 0,+ taxModel: 'flat',+ taxBands: [],+ horizonYears: 30,+ simulationCount: 1000,+ seed: 42,+ ...rest,+ };+}++// Independent restatement of the deterministic (zero volatility) recurrence:+// withdrawal at the start of each year, then growth on the remainder.+function deterministicDepletionYear(+ startingBalance: number,+ withdrawal: number,+ annualReturn: number,+ inflationRate: number | null,+ horizonYears: number,+) {+ let balance = startingBalance;+ let currentWithdrawal = withdrawal;+ for (let year = 1; year <= horizonYears; year++) {+ balance -= currentWithdrawal;+ if (balance <= 0) {+ return year;+ }+ balance *= 1 + annualReturn;+ if (inflationRate != null) {+ currentWithdrawal *= 1 + inflationRate;+ }+ }+ return null;+}++describe('getMonteCarloHorizonYears', () => {+ it('derives the horizon from the configured ages', () => {+ expect(getMonteCarloHorizonYears({ currentAge: 60, targetAge: 90 })).toBe(+ 30,+ );+ expect(getMonteCarloHorizonYears({ currentAge: 62.4, targetAge: 90 })).toBe(+ 28,+ );+ });++ it('clamps degenerate and oversized ranges', () => {+ expect(getMonteCarloHorizonYears({ currentAge: 90, targetAge: 60 })).toBe(+ MIN_HORIZON_YEARS,+ );+ expect(getMonteCarloHorizonYears({ currentAge: 70, targetAge: 70 })).toBe(+ MIN_HORIZON_YEARS,+ );+ expect(getMonteCarloHorizonYears({ currentAge: 0, targetAge: 500 })).toBe(+ MAX_HORIZON_YEARS,+ );+ });+});++describe('runMonteCarloSimulation', () => {+ it('matches the closed-form depletion year with zero volatility', () => {+ const params = makeParams(+ { annualWithdrawal: 10_000, horizonYears: 30 },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ );+ const expectedYear = deterministicDepletionYear(+ 100_000,+ 10_000,+ 0.05,+ null,+ 30,+ );+ expect(expectedYear).not.toBeNull();++ const result = runMonteCarloSimulation(params);++ expect(result.successRate).toBe(0);+ expect(result.medianDepletionYear).toBe(expectedYear);+ expect(result.earliestDepletionYear).toBe(expectedYear);+ expect(result.latestDepletionYear).toBe(expectedYear);++ const histogramEntry = result.depletionHistogram.find(+ entry => entry.count > 0,+ );+ expect(histogramEntry?.year).toBe(expectedYear);+ expect(histogramEntry?.count).toBe(result.simulationCount);+ });++ it('survives the full horizon when returns outpace withdrawals', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 3_000, horizonYears: 30 },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ ),+ );++ expect(result.successRate).toBe(1);+ expect(result.medianDepletionYear).toBeNull();+ expect(result.earliestDepletionYear).toBeNull();+ expect(result.depletionHistogram.every(entry => entry.count === 0)).toBe(+ true,+ );+ // Pot should have grown: withdrawals are 3% of a pot earning 5%+ expect(result.medianEndingBalance).toBeGreaterThan(100_000);+ });++ it('always succeeds with no withdrawals', () => {+ const result = runMonteCarloSimulation(+ makeParams({ annualWithdrawal: 0 }, { returnStdDev: 0.2 }),+ );+ expect(result.successRate).toBe(1);+ });++ it('depletes in year one when the withdrawal exceeds the pot', () => {+ const result = runMonteCarloSimulation(+ makeParams({ annualWithdrawal: 20_000 }, { startingBalance: 10_000 }),+ );+ expect(result.successRate).toBe(0);+ expect(result.medianDepletionYear).toBe(1);+ expect(result.depletionHistogram[0]).toEqual({+ year: 1,+ count: result.simulationCount,+ });+ });++ it('grows withdrawals by the inflation rate', () => {+ // pot 200, withdrawal 50, no growth, 100% inflation:+ // y1: 200-50=150 (w -> 100); y2: 150-100=50 (w -> 200); y3: depleted+ const inflated = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 50, inflationMean: 1, horizonYears: 10 },+ {+ startingBalance: 200,+ expectedReturnMean: 0,+ returnStdDev: 0,+ },+ ),+ );+ expect(inflated.medianDepletionYear).toBe(3);++ // Flat withdrawals last one year longer: y4 hits exactly 0+ const flat = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 50, inflationMean: null, horizonYears: 10 },+ {+ startingBalance: 200,+ expectedReturnMean: 0,+ returnStdDev: 0,+ },+ ),+ );+ expect(flat.medianDepletionYear).toBe(4);+ });++ it('is deterministic for a given seed', () => {+ const firstRun = runMonteCarloSimulation(makeParams({ seed: 7 }));+ const secondRun = runMonteCarloSimulation(makeParams({ seed: 7 }));+ expect(firstRun).toEqual(secondRun);++ const differentSeedRun = runMonteCarloSimulation(makeParams({ seed: 8 }));+ expect(differentSeedRun.successRate).not.toBe(firstRun.successRate);+ });++ it('produces ordered percentile bands', () => {+ const result = runMonteCarloSimulation(+ makeParams({}, { returnStdDev: 0.15 }),+ );+ for (const band of result.percentileBands) {+ expect(band.p5).toBeLessThanOrEqual(band.p10);+ expect(band.p10).toBeLessThanOrEqual(band.p25);+ expect(band.p25).toBeLessThanOrEqual(band.p30);+ expect(band.p30).toBeLessThanOrEqual(band.p50);+ expect(band.p50).toBeLessThanOrEqual(band.p70);+ expect(band.p70).toBeLessThanOrEqual(band.p75);+ expect(band.p75).toBeLessThanOrEqual(band.p90);+ }+ expect(result.percentileBands).toHaveLength(result.horizonYears + 1);+ expect(result.percentileBands[0].p10).toBe(50_000_000);+ expect(result.percentileBands[0].p90).toBe(50_000_000);+ });++ it('reports cumulative depletion probability', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 2_500_000 },+ { startingBalance: 30_000_000, returnStdDev: 0.15 },+ ),+ );+ const probabilities = result.depletionProbabilityByYear;+ expect(probabilities[0]).toBe(0);+ for (let year = 1; year < probabilities.length; year++) {+ expect(probabilities[year]).toBeGreaterThanOrEqual(+ probabilities[year - 1],+ );+ }+ expect(probabilities[result.horizonYears]).toBeCloseTo(+ 1 - result.successRate,+ 10,+ );+ });++ it('tracks the single worst run', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 2_500_000 },+ { startingBalance: 30_000_000, returnStdDev: 0.15 },+ ),+ );+ expect(result.worstRunPath).toHaveLength(result.horizonYears + 1);+ expect(result.worstRunPath[0]).toBe(30_000_000);++ // The worst run is the one that depletes earliest: its path hits zero+ // exactly at the earliest depletion year and stays there+ const firstZeroYear = result.worstRunPath.findIndex(+ balance => balance === 0,+ );+ expect(firstZeroYear).toBe(result.earliestDepletionYear);+ for (let year = firstZeroYear; year < result.worstRunPath.length; year++) {+ expect(result.worstRunPath[year]).toBe(0);+ }+ });++ it('treats two identical half-size pots the same as one pot', () => {+ // Holds even with volatility, since all pots share each year's market+ // shock+ for (const returnStdDev of [0, 0.15]) {+ const singlePot = runMonteCarloSimulation(+ makeParams({}, { startingBalance: 50_000_000, returnStdDev }),+ );++ for (const strategy of ['proportional', 'sequential'] as const) {+ const twoPots = runMonteCarloSimulation(+ makeParams({+ withdrawalStrategy: strategy,+ pots: [+ makePot({+ id: 'a',+ startingBalance: 25_000_000,+ returnStdDev,+ }),+ makePot({+ id: 'b',+ startingBalance: 25_000_000,+ returnStdDev,+ }),+ ],+ }),+ );++ expect(twoPots.successRate).toBe(singlePot.successRate);+ expect(twoPots.medianEndingBalance).toBe(singlePot.medianEndingBalance);+ expect(twoPots.percentileBands).toEqual(singlePot.percentileBands);+ }+ }+ });++ it('gives identically-invested pots identical yearly returns', () => {+ const result = runMonteCarloSimulation(+ makeParams({+ captureRunDetail: 7,+ pots: [+ makePot({ id: 'isa', startingBalance: 25_000_000 }),+ makePot({ id: 'pension', startingBalance: 25_000_000 }),+ ],+ }),+ );++ const rows = result.runDetail!;+ expect(rows.length).toBeGreaterThan(0);+ for (const row of rows) {+ if (row.potReturns[0] != null && row.potReturns[1] != null) {+ expect(row.potReturns[0]).toBe(row.potReturns[1]);+ }+ }+ });++ it('applies the withdrawal strategy across pots', () => {+ // Two pots of 100 each, withdrawal 50/year over 2 years, no volatility.+ // Pot A earns 0%, pot B earns 100%.+ const pots = [+ makePot({+ id: 'a',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'b',+ startingBalance: 100,+ expectedReturnMean: 1,+ returnStdDev: 0,+ }),+ ];++ // Sequential drains pot A first, leaving pot B compounding untouched:+ // y1: A 100-50=50, B 100*2=200; y2: A 0, B 200*2=400 -> total 400+ const sequential = runMonteCarloSimulation(+ makeParams({+ pots,+ withdrawalStrategy: 'sequential',+ annualWithdrawal: 50,+ horizonYears: 2,+ }),+ );+ expect(sequential.medianEndingBalance).toBe(400);++ // Proportional takes some from the growing pot each year:+ // y1: A 75, B 75*2=150 (total 225); y2: factor 1-50/225,+ // A 58.33, B 116.67*2=233.33 -> total ~292+ const proportional = runMonteCarloSimulation(+ makeParams({+ pots,+ withdrawalStrategy: 'proportional',+ annualWithdrawal: 50,+ horizonYears: 2,+ }),+ );+ expect(proportional.medianEndingBalance).toBe(292);++ // Draining the low-return pot first should always come out ahead here+ expect(sequential.medianEndingBalance).toBeGreaterThan(+ proportional.medianEndingBalance,+ );+ });++ it('matches deterministic growth when bootstrapping a one-year history', () => {+ // With a single historical year, every bootstrap draw is that year's+ // return, so the run must match a zero-volatility 5% projection+ const historical = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-bootstrap',+ historicalReturns: [+ { year: 2000, stocks: 0.05, bonds: 0.02, cash: 0.01 },+ ],+ annualWithdrawal: 3_000,+ horizonYears: 30,+ },+ { startingBalance: 100_000, allocationPreset: 'equity-100' },+ ),+ );+ const deterministic = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 3_000, horizonYears: 30 },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ ),+ );+ expect(historical.percentileBands).toEqual(deterministic.percentileBands);+ });++ it('runs one scenario per start year in sequence mode', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-sequence',+ historicalReturns: [+ { year: 2000, stocks: 1, bonds: 0, cash: 0 },+ { year: 2001, stocks: -0.5, bonds: 0, cash: 0 },+ ],+ annualWithdrawal: 10,+ horizonYears: 2,+ },+ { startingBalance: 100, allocationPreset: 'equity-100' },+ ),+ );++ // start 2000: y1 (100-10)*2 = 180, y2 (180-10)*0.5 = 85+ // start 2001: y1 (100-10)*0.5 = 45, y2 (45-10)*2 = 70+ expect(result.simulationCount).toBe(2);+ expect(result.successRate).toBe(1);+ expect(result.percentileBands[2].p90).toBe(84);+ expect(result.medianEndingBalance).toBe(78); // midpoint of 70 and 85+ });++ it('keeps custom pots on normal draws in historical modes', () => {+ // An absurd history that would explode the balance if it were used+ const historical = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-bootstrap',+ historicalReturns: [{ year: 2000, stocks: 9, bonds: 9, cash: 9 }],+ },+ { expectedReturnMean: 0.05, returnStdDev: 0 },+ ),+ );+ const normal = runMonteCarloSimulation(+ makeParams({}, { expectedReturnMean: 0.05, returnStdDev: 0 }),+ );+ expect(historical.percentileBands).toEqual(normal.percentileBands);+ });++ it('guardrails raise withdrawals when the pot races ahead', () => {+ // 4% initial rate with steady 20% growth: the withdrawal rate quickly+ // falls below 80% of the initial rate, triggering prosperity increases+ const base = makeParams(+ { annualWithdrawal: 4_000, horizonYears: 20 },+ { startingBalance: 100_000, expectedReturnMean: 0.2, returnStdDev: 0 },+ );+ const withoutRule = runMonteCarloSimulation(base);+ const withRule = runMonteCarloSimulation({+ ...base,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ });++ expect(withoutRule.medianTotalWithdrawn).toBe(20 * 4_000);+ expect(withRule.medianTotalWithdrawn).toBeGreaterThan(+ withoutRule.medianTotalWithdrawn,+ );+ expect(withRule.successRate).toBe(1);+ });++ it('does not treat a planned phase change as guardrails drift', () => {+ // On-track plan stepping from a 1% to a 2% planned rate at year 11:+ // guardrails measures drift against the planned phase path, so the+ // deliberate jump must not trigger a preservation cut by itself+ const result = runMonteCarloSimulation(+ makeParams(+ {+ horizonYears: 13,+ captureRunDetail: 0,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ spendingPhases: [+ {+ id: 'phase-1',+ name: '',+ fromAge: null,+ annualWithdrawal: 10_000,+ },+ { id: 'phase-2', name: '', fromAge: 70, annualWithdrawal: 20_000 },+ ],+ },+ { startingBalance: 1_000_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([+ ...new Array(10).fill(10_000),+ ...new Array(3).fill(20_000),+ ]);+ });++ it('boundaries cut withdrawals and extend survival', () => {+ // 10% withdrawal rate on a flat pot depletes in exactly year 10+ const base = makeParams(+ { annualWithdrawal: 10_000, horizonYears: 30 },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ );+ const withoutRule = runMonteCarloSimulation(base);+ expect(withoutRule.medianDepletionYear).toBe(10);++ const withRule = runMonteCarloSimulation({+ ...base,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'boundaries' },+ });+ expect(withRule.medianDepletionYear ?? Infinity).toBeGreaterThan(10);+ // The extra years come at the cost of income+ expect(withRule.medianTotalWithdrawn).toBeLessThanOrEqual(100_000);+ });++ it('floor-ceiling scales withdrawals with the pot within limits', () => {+ const base = makeParams(+ { annualWithdrawal: 10_000, horizonYears: 30 },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ );+ const withRule = runMonteCarloSimulation({+ ...base,+ withdrawalRule: {+ ...WITHDRAWAL_RULE_DEFAULTS,+ type: 'floor-ceiling',+ floorPct: 0.5,+ ceilingPct: 0.5,+ },+ });++ // Withdrawing ~10% of a shrinking pot (floored at 5,000/year) lasts far+ // longer than a fixed 10,000/year, which dies in year 10+ expect(withRule.medianDepletionYear ?? Infinity).toBeGreaterThan(14);+ });++ it('ratcheting increases withdrawals after consecutive years above the threshold', () => {+ const base = makeParams(+ { annualWithdrawal: 1_000, horizonYears: 20 },+ { startingBalance: 100_000, expectedReturnMean: 0.3, returnStdDev: 0 },+ );+ const withoutRule = runMonteCarloSimulation(base);+ const withRule = runMonteCarloSimulation({+ ...base,+ withdrawalRule: {+ ...WITHDRAWAL_RULE_DEFAULTS,+ type: 'ratcheting',+ balanceThresholdMultiple: 1.5,+ consecutiveYears: 3,+ ratchetIncreasePct: 0.5,+ },+ });++ expect(withoutRule.medianTotalWithdrawn).toBe(20 * 1_000);+ expect(withRule.medianTotalWithdrawn).toBeGreaterThan(+ withoutRule.medianTotalWithdrawn,+ );+ });++ it('minimum withdrawal floor neutralizes rule cuts', () => {+ const base = makeParams(+ { annualWithdrawal: 10_000, horizonYears: 30 },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ );+ const withoutRule = runMonteCarloSimulation(base);+ const cutsFloored = runMonteCarloSimulation({+ ...base,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'boundaries' },+ minimumWithdrawal: 10_000,+ });++ expect(cutsFloored.percentileBands).toEqual(withoutRule.percentileBands);+ expect(cutsFloored.medianTotalWithdrawn).toBe(+ withoutRule.medianTotalWithdrawn,+ );+ });++ it('takes nothing in zero-spend phases even with a minimum withdrawal', () => {+ // 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+ // The horizon stops before spend-down drift would cross the+ // preservation trigger, so retirement withdrawals stay at the+ // planned amount and the assertions are exact+ const result = runMonteCarloSimulation(+ makeParams(+ {+ horizonYears: 8,+ captureRunDetail: 0,+ minimumWithdrawal: 15_000,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ spendingPhases: [+ { id: 'working', name: '', fromAge: null, annualWithdrawal: 0 },+ { id: 'retired', name: '', fromAge: 65, annualWithdrawal: 40_000 },+ ],+ },+ { startingBalance: 500_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ // currentAge is 60, so years 1-5 (ages 60-64) are the zero phase+ for (const row of rows.slice(0, 5)) {+ expect(row.withdrawal).toBe(0);+ }+ // From 65 the planned spending applies, already above the floor+ for (const row of rows.slice(5)) {+ expect(row.withdrawal).toBe(40_000);+ }+ });++ it("keeps the minimum withdrawal 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 it+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ horizonYears: 8,+ inflationMean: 0.05,+ inflationStdDev: 0,+ deflateToTodaysMoney: true,+ captureRunDetail: 0,+ minimumWithdrawal: 8_000,+ withdrawalRule: {+ ...WITHDRAWAL_RULE_DEFAULTS,+ type: 'guardrails',+ preservationTriggerPct: 0.1,+ preservationCutPct: 0.5,+ },+ },+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows).toHaveLength(8);+ expect(rows[0].withdrawal).toBe(10_000);+ // Year 2's 50% cut lands well below the floor, so the floor binds+ expect(rows[1].withdrawal).toBe(8_000);+ for (const row of rows.slice(1)) {+ expect(row.withdrawal).toBeGreaterThanOrEqual(8_000);+ }+ });++ it('fails when accessible pots run dry before a locked pot unlocks', () => {+ // Current age 60; the big pot only unlocks at 120, far past the horizon.+ // The accessible pot funds 30/year from 100: y1 70, y2 40, y3 10, then+ // year 4 can't be covered - the locked money doesn't save the plan.+ const result = runMonteCarloSimulation(+ makeParams({+ pots: [+ makePot({+ id: 'isa',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 1_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ accessAge: 120,+ }),+ ],+ annualWithdrawal: 30,+ horizonYears: 20,+ }),+ );++ expect(result.successRate).toBe(0);+ expect(result.medianDepletionYear).toBe(4);+ });++ it('survives when the locked pot unlocks in time', () => {+ // Same setup, but the pension unlocks at 63 - exactly year 4, just as+ // the accessible pot runs out+ const result = runMonteCarloSimulation(+ makeParams({+ pots: [+ makePot({+ id: 'isa',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 1_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ accessAge: 63,+ }),+ ],+ annualWithdrawal: 30,+ horizonYears: 20,+ }),+ );++ expect(result.successRate).toBe(1);+ });++ it('treats an access age at or below the current age as immediate', () => {+ const immediate = runMonteCarloSimulation(+ makeParams({}, { accessAge: null }),+ );+ const alreadyReached = runMonteCarloSimulation(+ makeParams({}, { accessAge: 40 }),+ );+ expect(alreadyReached).toEqual(immediate);+ });++ 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+ const result = runMonteCarloSimulation(+ makeParams({+ withdrawalStrategy: 'sequential',+ pots: [+ makePot({+ id: 'locked-first',+ startingBalance: 1_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ accessAge: 120,+ }),+ makePot({+ id: 'open-second',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ ],+ annualWithdrawal: 10,+ horizonYears: 20,+ }),+ );++ expect(result.medianDepletionYear).toBe(10);+ });++ it('best-performer order drains the pot with the highest return last year', () => {+ // Pot A (0% return) is listed first, pot B earns 50% every year.+ // Year 1 has no returns yet, so the listed order drains A; from year+ // 2 onward B is always last year's best performer and gets drained.+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 10,+ horizonYears: 4,+ withdrawalStrategy: 'best-performer',+ captureRunDetail: 0,+ pots: [+ makePot({+ id: 'a',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'b',+ startingBalance: 100,+ expectedReturnMean: 0.5,+ returnStdDev: 0,+ }),+ ],+ }),+ );++ // Hand recurrence: y1 drains A then B grows 50%; y2-y4 drain B only+ expect(result.runDetail!.map(row => row.potBalances)).toEqual([+ [90, 150],+ [90, 210],+ [90, 300],+ [90, 435],+ ]);+ expect(result.runDetail!.map(row => row.potWithdrawals)).toEqual([+ [10, 0],+ [0, 10],+ [0, 10],+ [0, 10],+ ]);+ });++ it('best-performer order switches pots as the market flips', () => {+ // Alternating real years: stocks crash, boom, crash, boom while cash+ // stays flat. After a crash the cash pot funds the withdrawal (stocks+ // left to recover); after a boom the stocks pot funds it.+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 100,+ horizonYears: 4,+ withdrawalStrategy: 'best-performer',+ returnModel: 'historical-sequence',+ captureRunDetail: 0,+ historicalReturns: [+ { year: 2001, stocks: -0.5, bonds: 0, cash: 0 },+ { year: 2002, stocks: 1, bonds: 0, cash: 0 },+ { year: 2003, stocks: -0.5, bonds: 0, cash: 0 },+ { year: 2004, stocks: 1, bonds: 0, cash: 0 },+ ],+ pots: [+ makePot({+ id: 'stocks',+ startingBalance: 1_000,+ allocationPreset: 'equity-100',+ }),+ makePot({+ id: 'cash',+ startingBalance: 1_000,+ allocationPreset: 'cash',+ }),+ ],+ }),+ );++ // y1: listed order drains stocks, then the crash halves them;+ // y2: cash beat stocks last year -> drain cash, stocks double back;+ // y3: stocks boomed last year -> drain stocks, then they halve;+ // y4: cash beat stocks again -> drain cash, stocks double back+ expect(result.runDetail!.map(row => row.potBalances)).toEqual([+ [450, 1_000],+ [900, 900],+ [400, 900],+ [800, 800],+ ]);+ });++ it('best-performer order falls back to the listed order on ties', () => {+ // Identical pots share every market shock, so their returns always+ // tie and best-performer must behave exactly like draining in order+ const pots = [+ makePot({ id: 'a', startingBalance: 25_000_000 }),+ makePot({ id: 'b', startingBalance: 25_000_000 }),+ ];+ const sequential = runMonteCarloSimulation(+ makeParams({ withdrawalStrategy: 'sequential', pots }),+ );+ const bestPerformer = runMonteCarloSimulation(+ makeParams({ withdrawalStrategy: 'best-performer', pots }),+ );++ expect(bestPerformer.successRate).toBe(sequential.successRate);+ expect(bestPerformer.percentileBands).toEqual(sequential.percentileBands);+ expect(bestPerformer.medianTotalWithdrawn).toBe(+ sequential.medianTotalWithdrawn,+ );+ });++ it('target-mix order withdraws from overweight pots back toward the mix', () => {+ // 50/50 starting mix; pot B doubles every year while A is flat, so B+ // is always the overweight pot and funds every withdrawal after year 1+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 30,+ horizonYears: 3,+ withdrawalStrategy: 'target-mix',+ captureRunDetail: 0,+ pots: [+ makePot({+ id: 'a',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'b',+ startingBalance: 100,+ expectedReturnMean: 1,+ returnStdDev: 0,+ }),+ ],+ }),+ );++ // y1: both pots sit exactly at target, so each gives up its share+ // (15 each); afterwards only B is ever above its ideal balance+ expect(result.runDetail!.map(row => row.potBalances)).toEqual([+ [85, 170],+ [85, 280],+ [85, 500],+ ]);+ expect(result.runDetail!.map(row => row.potWithdrawals)).toEqual([+ [15, 15],+ [0, 30],+ [0, 30],+ ]);+ });++ it('target-mix order matches proportional when pots never drift', () => {+ // Identical returns keep every pot exactly at its target share, so+ // pulling toward the mix and splitting proportionally take the same+ // amounts from the same pots+ const pots = [+ makePot({ id: 'a', startingBalance: 30_000_000 }),+ makePot({ id: 'b', startingBalance: 20_000_000 }),+ ];+ const proportional = runMonteCarloSimulation(+ makeParams({ withdrawalStrategy: 'proportional', pots }),+ );+ const targetMix = runMonteCarloSimulation(+ makeParams({ withdrawalStrategy: 'target-mix', pots }),+ );++ expect(targetMix.successRate).toBe(proportional.successRate);+ expect(+ Math.abs(+ targetMix.medianEndingBalance - proportional.medianEndingBalance,+ ),+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(+ targetMix.medianTotalWithdrawn - proportional.medianTotalWithdrawn,+ ),+ ).toBeLessThanOrEqual(1);+ });++ it('guardrails ignore a booming locked pot during a bridge', () => {+ // Accessible bridge pot drains while a locked pension quintuples: the+ // rule must measure the withdrawal rate against accessible wealth and+ // CUT spending, not hand out prosperity raises against locked money+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 10_000,+ horizonYears: 5,+ captureRunDetail: 0,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'guardrails' },+ pots: [+ makePot({+ id: 'bridge',+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 1_000_000,+ expectedReturnMean: 0.2,+ returnStdDev: 0,+ accessAge: 120,+ }),+ ],+ }),+ );++ // Reference rate is 10% of the accessible start; the draining bridge+ // pot pushes the rate past the guardrail and spending steps down+ expect(result.runDetail!.map(row => row.withdrawal)).toEqual([+ 10_000, 10_000, 9_000, 8_100, 7_290,+ ]);+ });++ it('ratcheting ignores a booming locked pot during a bridge', () => {+ // Pre-fix, total wealth (locked pension included) crossing the+ // threshold ratcheted spending up while only the bridge pot could pay+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 10_000,+ horizonYears: 5,+ captureRunDetail: 0,+ withdrawalRule: { ...WITHDRAWAL_RULE_DEFAULTS, type: 'ratcheting' },+ pots: [+ makePot({+ id: 'bridge',+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 1_000_000,+ expectedReturnMean: 0.5,+ returnStdDev: 0,+ accessAge: 120,+ }),+ ],+ }),+ );++ expect(result.runDetail!.map(row => row.withdrawal)).toEqual([+ 10_000, 10_000, 10_000, 10_000, 10_000,+ ]);+ });++ it('reports per-run summaries consistent with the aggregates', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 2_500_000 },+ { startingBalance: 30_000_000, returnStdDev: 0.15 },+ ),+ );++ expect(result.endingBalances).toHaveLength(result.simulationCount);+ expect(result.depletionYearBySimulation).toHaveLength(+ result.simulationCount,+ );+ expect(result.totalWithdrawnBySimulation).toHaveLength(+ result.simulationCount,+ );++ let survived = 0;+ for (+ let simulationIndex = 0;+ simulationIndex < result.simulationCount;+ simulationIndex+++ ) {+ if (result.depletionYearBySimulation[simulationIndex] === -1) {+ survived++;+ } else {+ // Depleted runs end at zero+ expect(result.endingBalances[simulationIndex]).toBe(0);+ }+ }+ expect(survived / result.simulationCount).toBe(result.successRate);+ });++ it('captures a run year by year matching the closed-form recurrence', () => {+ const params = makeParams(+ { annualWithdrawal: 10_000, horizonYears: 30, captureRunDetail: 0 },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ );+ const result = runMonteCarloSimulation(params);+ const rows = result.runDetail;+ expect(rows).toBeDefined();++ // Replicate the recurrence independently+ let balance = 100_000;+ for (const row of rows!) {+ expect(row.startBalance).toBe(Math.round(balance));+ if (balance <= 10_000) {+ // Depletion year: only the remainder could be withdrawn+ expect(row.withdrawal).toBe(Math.round(balance));+ expect(row.endBalance).toBe(0);+ break;+ }+ expect(row.withdrawal).toBe(10_000);+ const afterWithdrawal = balance - 10_000;+ balance = afterWithdrawal * 1.05;+ expect(row.endBalance).toBe(Math.round(balance));+ 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);+ });++ it('replays a volatile run identically to the original', () => {+ const base = makeParams({}, { returnStdDev: 0.15 });+ const original = runMonteCarloSimulation(base);++ const simulationIndex = 123;+ const replay = runMonteCarloSimulation({+ ...base,+ captureRunDetail: simulationIndex,+ });+ const rows = replay.runDetail!;++ const depletionYear = original.depletionYearBySimulation[simulationIndex];+ if (depletionYear === -1) {+ expect(rows).toHaveLength(original.horizonYears);+ expect(rows[rows.length - 1].endBalance).toBe(+ Math.round(original.endingBalances[simulationIndex]),+ );+ } else {+ expect(rows).toHaveLength(depletionYear);+ expect(rows[rows.length - 1].endBalance).toBe(0);+ }+ });++ it('marks locked money on a captured bridge-gap failure row', () => {+ const result = runMonteCarloSimulation(+ makeParams({+ pots: [+ makePot({+ id: 'isa',+ startingBalance: 100,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 1_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ accessAge: 120,+ }),+ ],+ annualWithdrawal: 30,+ horizonYears: 20,+ captureRunDetail: 0,+ }),+ );++ const rows = result.runDetail!;+ const failureRow = rows[rows.length - 1];+ // y1 70, y2 40, y3 10 accessible; year 4 fails with 10 reachable+ expect(failureRow.year).toBe(4);+ expect(failureRow.withdrawal).toBe(10);+ // The locked pension is not an investment loss+ expect(failureRow.growth).toBe(0);+ expect(failureRow.endBalance).toBe(0);+ expect(failureRow.inaccessibleBalance).toBe(1_000);+ // Per-pot view: the ISA was consumed, the pension stayed locked+ expect(failureRow.potBalances).toEqual([0, 1_000]);+ expect(rows[0].potBalances).toEqual([70, 1_000]);+ // The shortfall year took the ISA's last 10; the locked pension+ // funded nothing in any year+ expect(rows[0].potWithdrawals).toEqual([30, 0]);+ expect(failureRow.potWithdrawals).toEqual([10, 0]);+ // Zero-volatility pots return exactly 0% each year; on the failure year+ // no returns are applied at all+ expect(rows[0].potReturns).toEqual([0, 0]);+ expect(failureRow.potReturns).toEqual([null, null]);+ });++ it('switches spending phases at their starting age', () => {+ // 30/year for the first 10 years (ages 60-69), 20/year onwards+ const result = runMonteCarloSimulation(+ makeParams(+ {+ spendingPhases: [+ { id: 'a', name: '', fromAge: null, annualWithdrawal: 30 },+ { id: 'b', name: '', fromAge: 70, annualWithdrawal: 20 },+ ],+ horizonYears: 20,+ },+ { startingBalance: 1_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.successRate).toBe(1);+ expect(result.medianTotalWithdrawn).toBe(30 * 10 + 20 * 10);+ });++ it('applies inflation from the simulation start across phase switches', () => {+ // 100% inflation; phase 2 starts in year 3 (age 62):+ // y1: 10x1 = 10; y2: 10x2 = 20; y3: 20x4 = 80+ const result = runMonteCarloSimulation(+ makeParams(+ {+ spendingPhases: [+ { id: 'a', name: '', fromAge: null, annualWithdrawal: 10 },+ { id: 'b', name: '', fromAge: 62, annualWithdrawal: 20 },+ ],+ inflationMean: 1,+ horizonYears: 3,+ captureRunDetail: 0,+ },+ { startingBalance: 1_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.runDetail!.map(row => row.withdrawal)).toEqual([10, 20, 80]);+ expect(result.medianTotalWithdrawn).toBe(110);+ });++ it('keeps rule adjustments across phase boundaries', () => {+ // Boundaries rule cuts 10% in year 2 (rate 1000/9000 > 10%); the cut+ // factor must still discount the smaller phase-2 amount in year 3+ const result = runMonteCarloSimulation(+ makeParams(+ {+ spendingPhases: [+ { id: 'a', name: '', fromAge: null, annualWithdrawal: 1_000 },+ { id: 'b', name: '', fromAge: 62, annualWithdrawal: 500 },+ ],+ withdrawalRule: {+ ...WITHDRAWAL_RULE_DEFAULTS,+ type: 'boundaries',+ upperRateThreshold: 0.1,+ upperCutPct: 0.1,+ lowerRateThreshold: 0,+ lowerIncreasePct: 0,+ },+ horizonYears: 3,+ captureRunDetail: 0,+ },+ { startingBalance: 10_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.runDetail!.map(row => row.withdrawal)).toEqual([+ 1_000,+ 900, // 10% cut+ 450, // phase-2 amount 500 x the persisted 0.9 factor+ ]);+ });++ it('ignores the minimum withdrawal 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 None+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ minimumWithdrawal: 20_000,+ horizonYears: 10,+ },+ { startingBalance: 500_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.medianTotalWithdrawn).toBe(10 * 10_000);+ });++ it("shows flat real withdrawals when deflating to today's money", () => {+ // Nominal withdrawals grow with inflation; in today's money the planned+ // spending reads as a constant amount and the total is years x amount+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ inflationMean: 0.1,+ horizonYears: 5,+ deflateToTodaysMoney: true,+ captureRunDetail: 0,+ },+ { startingBalance: 1_000_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ expect(result.runDetail!.map(row => row.withdrawal)).toEqual([+ 10_000, 10_000, 10_000, 10_000, 10_000,+ ]);+ expect(result.medianTotalWithdrawn).toBe(5 * 10_000);+ });++ it('deflated results match an equivalent real-return simulation', () => {+ // Deflating a nominal simulation must equal simulating directly with+ // the real return: (1 + nominal) / (1 + inflation) - 1+ const deflated = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ inflationMean: 1,+ horizonYears: 10,+ deflateToTodaysMoney: true,+ },+ {+ startingBalance: 200_000,+ expectedReturnMean: 1.1, // 110% nominal+ returnStdDev: 0,+ },+ ),+ );+ const real = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 10_000, inflationMean: null, horizonYears: 10 },+ {+ startingBalance: 200_000,+ expectedReturnMean: 2.1 / 2 - 1, // 5% real+ returnStdDev: 0,+ },+ ),+ );++ for (let year = 0; year <= 10; year++) {+ expect(+ Math.abs(+ deflated.percentileBands[year].p50 - real.percentileBands[year].p50,+ ),+ ).toBeLessThanOrEqual(1);+ }+ expect(+ Math.abs(deflated.medianEndingBalance - real.medianEndingBalance),+ ).toBeLessThanOrEqual(1);+ });++ it('is deterministic with inflation volatility and differs from a fixed rate', () => {+ const volatileParams = makeParams(+ { inflationMean: 0.025, inflationStdDev: 0.04 },+ { returnStdDev: 0.15 },+ );+ const firstRun = runMonteCarloSimulation(volatileParams);+ const secondRun = runMonteCarloSimulation(volatileParams);+ expect(firstRun).toEqual(secondRun);++ const fixed = runMonteCarloSimulation(+ makeParams(+ { inflationMean: 0.025, inflationStdDev: 0 },+ { returnStdDev: 0.15 },+ ),+ );+ expect(firstRun.successRate).not.toBe(fixed.successRate);++ // Percentile ordering holds under inflation volatility too+ for (const band of firstRun.percentileBands) {+ expect(band.p10).toBeLessThanOrEqual(band.p50);+ expect(band.p50).toBeLessThanOrEqual(band.p90);+ }+ });++ it('shows flat real withdrawals even under volatile inflation', () => {+ // However wild the drawn inflation path, deflating by that same path+ // must bring the planned spending back to its flat today's-money amount+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 10_000,+ inflationMean: 0.1,+ inflationStdDev: 0.5,+ horizonYears: 5,+ deflateToTodaysMoney: true,+ captureRunDetail: 3,+ },+ {+ startingBalance: 100_000_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ },+ ),+ );++ expect(result.runDetail!.map(row => row.withdrawal)).toEqual([+ 10_000, 10_000, 10_000, 10_000, 10_000,+ ]);+ });++ it('clamps out-of-range inputs', () => {+ const result = runMonteCarloSimulation(+ makeParams({ simulationCount: 50, horizonYears: 500 }),+ );+ expect(result.simulationCount).toBe(MIN_SIMULATION_COUNT);+ expect(result.horizonYears).toBe(MAX_HORIZON_YEARS);+ });++ it('flat tax grosses up withdrawals to deliver the net spending', () => {+ // 20% tax pot: delivering 8,000 net costs 10,000 gross each year, so+ // 95,000 funds nine full years and fails in year ten with the last+ // 5,000 delivering only 4,000 net+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 8_000, horizonYears: 12, captureRunDetail: 0 },+ {+ startingBalance: 95_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ withdrawalTaxRate: 0.2,+ },+ ),+ );++ expect(result.successRate).toBe(0);+ expect(result.medianDepletionYear).toBe(10);+ const rows = result.runDetail!;+ expect(rows).toHaveLength(10);+ for (const row of rows.slice(0, 9)) {+ expect(row.withdrawal).toBe(10_000);+ expect(row.taxPaid).toBe(2_000);+ }+ expect(rows[9].withdrawal).toBe(5_000);+ expect(rows[9].taxPaid).toBe(1_000);+ expect(rows[9].endBalance).toBe(0);+ });++ it('flat tax applies per pot as sequential order crosses pots', () => {+ // Tax-free ISA pays the first three years at face value; once it runs+ // dry the 25%-taxed pension must gross up to 13,333 for the same+ // 10,000 of spending+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 10_000,+ horizonYears: 5,+ withdrawalStrategy: 'sequential',+ captureRunDetail: 0,+ pots: [+ makePot({+ id: 'isa',+ startingBalance: 30_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ withdrawalTaxRate: 0.25,+ }),+ ],+ }),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([+ 10_000, 10_000, 10_000, 13_333, 13_333,+ ]);+ expect(rows.map(row => row.taxPaid)).toEqual([0, 0, 0, 3_333, 3_333]);+ expect(rows[3].potWithdrawals).toEqual([0, 13_333]);+ // Flat-model tax attributes exactly to the pot that paid it; the+ // taxable amount is the whole take for a pot with a nonzero rate+ expect(rows[0].potTaxes).toEqual([0, 0]);+ expect(rows[3].potTaxes).toEqual([0, 3_333]);+ expect(rows[0].potTaxables).toEqual([0, 0]);+ expect(rows[3].potTaxables).toEqual([0, 13_333]);+ });++ it('tax bands gross up progressively over the taxable income', () => {+ // Bands: first 10,000 tax-free, 20% above. Delivering 18,000 net+ // needs 20,000 gross (tax 2,000 on the 10,000 above the threshold)+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 18_000,+ horizonYears: 3,+ captureRunDetail: 0,+ taxModel: 'bands',+ taxBands: [+ { id: 'a', from: 0, rate: 0 },+ { id: 'b', from: 10_000, rate: 0.2 },+ ],+ },+ { startingBalance: 200_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([20_000, 20_000, 20_000]);+ expect(rows.map(row => row.taxPaid)).toEqual([2_000, 2_000, 2_000]);+ });++ it('tax bands pool taxable income across pots by taxable fraction', () => {+ // Proportional split takes half the gross from each pot; only the+ // pension half is 75% taxable, so taxable income is 0.375x the gross.+ // Solving 0.925g = 38,000 gives g = 41,081 for 40,000 net+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 40_000,+ horizonYears: 1,+ captureRunDetail: 0,+ taxModel: 'bands',+ taxBands: [+ { id: 'a', from: 0, rate: 0 },+ { id: 'b', from: 10_000, rate: 0.2 },+ ],+ pots: [+ makePot({+ id: 'isa',+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ taxableFraction: 0,+ }),+ makePot({+ id: 'pension',+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ taxableFraction: 0.75,+ }),+ ],+ }),+ );++ const row = result.runDetail![0];+ expect(row.withdrawal).toBe(41_081);+ expect(row.taxPaid).toBe(1_081);+ // Raw takes are 20,540.5 each; the parts reconcile to the 41,081+ // total (equal remainders break toward the earlier pot) instead of+ // both rounding up to a sum of 41,082+ expect(row.potWithdrawals).toEqual([20_541, 20_540]);+ // Bands-model tax prorates by taxable share: the tax-free pot+ // contributes no taxable income, so the pension carries all the tax+ expect(row.potTaxes).toEqual([0, 1_081]);+ // Taxable amounts: take x taxable fraction (20,540.54 x 0.75)+ expect(row.potTaxables).toEqual([0, 15_405]);+ });++ it("tax band thresholds are in today's money and rise with inflation", () => {+ // With 5% fixed inflation the nominal gross grows every year, but in+ // today's money the withdrawal and tax stay exactly 20,000 and 2,000+ // because the thresholds inflate along with spending+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 18_000,+ horizonYears: 4,+ inflationMean: 0.05,+ inflationStdDev: 0,+ deflateToTodaysMoney: true,+ captureRunDetail: 0,+ taxModel: 'bands',+ taxBands: [+ { id: 'a', from: 0, rate: 0 },+ { id: 'b', from: 10_000, rate: 0.2 },+ ],+ },+ { startingBalance: 500_000, expectedReturnMean: 0, returnStdDev: 0 },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.withdrawal)).toEqual([+ 20_000, 20_000, 20_000, 20_000,+ ]);+ expect(rows.map(row => row.taxPaid)).toEqual([2_000, 2_000, 2_000, 2_000]);+ });++ it('a single tax band behaves like the same flat rate', () => {+ const flat = runMonteCarloSimulation(+ makeParams({}, { withdrawalTaxRate: 0.25 }),+ );+ const bands = runMonteCarloSimulation(+ makeParams(+ {+ taxModel: 'bands',+ taxBands: [{ id: 'a', from: 0, rate: 0.25 }],+ },+ { taxableFraction: 1 },+ ),+ );++ expect(bands.successRate).toBe(flat.successRate);+ expect(+ Math.abs(bands.medianEndingBalance - flat.medianEndingBalance),+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(bands.medianTotalWithdrawn - flat.medianTotalWithdrawn),+ ).toBeLessThanOrEqual(1);+ });++ it('zero-rate tax configurations match the untaxed engine exactly', () => {+ const untaxed = runMonteCarloSimulation(makeParams());+ const zeroBands = runMonteCarloSimulation(+ makeParams({+ taxModel: 'bands',+ taxBands: [{ id: 'a', from: 0, rate: 0 }],+ }),+ );++ expect(zeroBands.percentileBands).toEqual(untaxed.percentileBands);+ expect(zeroBands.successRate).toBe(untaxed.successRate);+ });++ it('deducts a fixed yearly fee at the end of each year', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 0, horizonYears: 3, captureRunDetail: 0 },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeFixed: 1_000,+ },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.endBalance)).toEqual([99_000, 98_000, 97_000]);+ expect(rows.map(row => row.feesPaid)).toEqual([1_000, 1_000, 1_000]);+ // Growth stays pure market performance (zero here) - fees are separate+ expect(rows.map(row => row.growth)).toEqual([0, 0, 0]);+ });++ it('deducts a percentage fee from the end-of-year balance', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 0, horizonYears: 3, captureRunDetail: 0 },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeRate: 0.01,+ },+ ),+ );++ const rows = result.runDetail!;+ expect(rows.map(row => row.endBalance)).toEqual([99_000, 98_010, 97_030]);+ expect(rows.map(row => row.feesPaid)).toEqual([1_000, 990, 980]);+ });++ it("captures each pot's own fee in the run detail", () => {+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 0,+ horizonYears: 2,+ captureRunDetail: 0,+ pots: [+ makePot({+ id: 'fixed-fee',+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeFixed: 1_000,+ }),+ makePot({+ id: 'rate-fee',+ startingBalance: 200_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeRate: 0.01,+ }),+ makePot({+ id: 'no-fee',+ startingBalance: 50_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ }),+ ],+ }),+ );++ const rows = result.runDetail!;+ // Year 1: 1,000 fixed; 1% of 200,000; nothing from the fee-free pot+ expect(rows[0].potFees).toEqual([1_000, 2_000, 0]);+ // Year 2: the percentage pot's balance shrank to 198,000+ expect(rows[1].potFees).toEqual([1_000, 1_980, 0]);+ // Each year opens with the previous year's post-fee balances+ expect(rows[0].potStartBalances).toEqual([100_000, 200_000, 50_000]);+ expect(rows[1].potStartBalances).toEqual([99_000, 198_000, 50_000]);+ for (const row of rows) {+ expect(row.potFees.reduce((sum, fee) => sum + fee, 0)).toBe(row.feesPaid);+ expect(+ row.potStartBalances.reduce((sum, balance) => sum + balance, 0),+ ).toBe(row.startBalance);+ expect(row.potBalances.reduce((sum, balance) => sum + balance, 0)).toBe(+ row.endBalance,+ );+ }+ });++ it('rounds per-pot amounts so they sum exactly to the row totals', () => {+ // Each pot's raw fee is 10.5: rounded independently both would show+ // 11, summing to 22 against a fees-paid total of 21. The largest-+ // remainder split keeps the parts reconciled with the total instead.+ const result = runMonteCarloSimulation(+ makeParams({+ annualWithdrawal: 0,+ horizonYears: 1,+ captureRunDetail: 0,+ pots: [+ makePot({+ id: 'pot-a',+ startingBalance: 1_050,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeRate: 0.01,+ }),+ makePot({+ id: 'pot-b',+ startingBalance: 1_050,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeRate: 0.01,+ }),+ ],+ }),+ );++ const row = result.runDetail![0];+ expect(row.feesPaid).toBe(21);+ // Equal remainders break ties toward the earlier pot+ expect(row.potFees).toEqual([11, 10]);+ });++ it("keeps an inflation-adjusted fixed fee constant in today's money", () => {+ const base = {+ annualWithdrawal: 0,+ horizonYears: 3,+ inflationMean: 0.05,+ inflationStdDev: 0,+ deflateToTodaysMoney: true,+ captureRunDetail: 0,+ };+ const adjusted = runMonteCarloSimulation(+ makeParams(base, {+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeFixed: 1_000,+ feeAdjustsWithInflation: true,+ }),+ );+ expect(adjusted.runDetail!.map(row => row.feesPaid)).toEqual([+ 1_000, 1_000, 1_000,+ ]);++ // A non-adjusted fee shrinks in real terms as prices rise+ const flat = runMonteCarloSimulation(+ makeParams(base, {+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeFixed: 1_000,+ }),+ );+ const flatFees = flat.runDetail!.map(row => row.feesPaid);+ expect(flatFees[0]).toBeLessThan(1_000);+ expect(flatFees[2]).toBeLessThan(flatFees[0]);+ });++ it('fees alone can deplete a plan', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ { annualWithdrawal: 0, horizonYears: 5 },+ {+ startingBalance: 1_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeFixed: 400,+ },+ ),+ );++ expect(result.successRate).toBe(0);+ expect(result.medianDepletionYear).toBe(3);+ });++ it('keeps every output formatter-safe under absurdly large configs', () => {+ // A trillion at 100% yearly growth over a century overflows the safe+ // integer range many times over; the engine must clamp instead of+ // producing values the app's formatter refuses to render+ const result = runMonteCarloSimulation(+ makeParams(+ {+ annualWithdrawal: 1_000_000,+ horizonYears: 100,+ captureRunDetail: 0,+ },+ {+ // Over-cap input: clamped to MAX_AMOUNT before simulating+ startingBalance: 9_000_000_000_000_000,+ expectedReturnMean: 1,+ returnStdDev: 0.5,+ },+ ),+ );++ expect(result.percentileBands[0].p50).toBe(MAX_AMOUNT);++ // Outputs are capped at 2^50 - a factor of two below the formatter's+ // 2^51 - 1 limit, leaving room for chart axes to round ticks upward+ const maxFormattable = 2 ** 50;+ for (const band of result.percentileBands) {+ expect(band.p5).toBeGreaterThanOrEqual(0);+ expect(band.p90).toBeLessThanOrEqual(maxFormattable);+ }+ for (+ let simulationIndex = 0;+ simulationIndex < result.simulationCount;+ simulationIndex+++ ) {+ expect(result.endingBalances[simulationIndex]).toBeLessThanOrEqual(+ maxFormattable,+ );+ expect(+ result.totalWithdrawnBySimulation[simulationIndex],+ ).toBeLessThanOrEqual(maxFormattable);+ }+ for (const row of result.runDetail!) {+ const values = [+ row.startBalance,+ row.withdrawal,+ row.growth,+ row.endBalance,+ ...row.potBalances,+ ...row.potWithdrawals,+ ];+ for (const value of values) {+ expect(Number.isSafeInteger(value)).toBe(true);+ expect(Math.abs(value)).toBeLessThanOrEqual(maxFormattable);+ }+ }+ });+});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.tsnew file mode 100644index 0000000000..19db110708--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts@@ -0,0 +1,1466 @@+import { MAX_SAFE_NUMBER } from '@actual-app/core/shared/util';+import type {+ MonteCarloAllocationPreset,+ MonteCarloPotMeta,+ MonteCarloReturnModel,+ MonteCarloSpendingPhaseMeta,+ MonteCarloTaxBandMeta,+ MonteCarloTaxModel,+ MonteCarloWidget,+ MonteCarloWithdrawalRuleMeta,+ MonteCarloWithdrawalStrategy,+} from '@actual-app/core/types/models';++import { HISTORICAL_ANNUAL_RETURNS } from './monteCarloHistoricalReturns';+import type { HistoricalAnnualReturn } from './monteCarloHistoricalReturns';++// Illustrative nominal annual return assumptions for the allocation presets.+// These are deliberately easy to tweak; they only auto-fill the mean/stdDev+// inputs in the UI - the simulation itself reads just the numeric values.+export const ALLOCATION_PRESETS: Record<+ Exclude<MonteCarloAllocationPreset, 'custom'>,+ { mean: number; stdDev: number }+> = {+ 'equity-100': { mean: 0.07, stdDev: 0.15 },+ 'equity-80': { mean: 0.065, stdDev: 0.12 },+ 'equity-60': { mean: 0.06, stdDev: 0.1 },+ 'equity-40': { mean: 0.05, stdDev: 0.075 },+ cash: { mean: 0.03, stdDev: 0.015 },+};++// Asset mix behind each preset, used by the historical return models to+// blend the stocks/bonds/cash series into a single yearly return per pot+const PRESET_ASSET_WEIGHTS: Record<+ Exclude<MonteCarloAllocationPreset, 'custom'>,+ { stocks: number; bonds: number; cash: number }+> = {+ 'equity-100': { stocks: 1, bonds: 0, cash: 0 },+ 'equity-80': { stocks: 0.8, bonds: 0.2, cash: 0 },+ 'equity-60': { stocks: 0.6, bonds: 0.4, cash: 0 },+ 'equity-40': { stocks: 0.4, bonds: 0.6, cash: 0 },+ cash: { stocks: 0, bonds: 0, cash: 1 },+};++/**+ * Money inputs above this are clamped (1e14 minor units = 1 trillion major+ * units); keeps even heavily compounded results within the range the+ * app's formatter accepts+ */+export const MAX_AMOUNT = 100_000_000_000_000;++/**+ * The largest integer amount loot-core's safeNumber will format (tighter+ * than MAX_SAFE_INTEGER so display division stays exact). Chart axes must+ * clamp synthesized tick values to this before formatting.+ */+export const MAX_FORMATTABLE_AMOUNT = MAX_SAFE_NUMBER;++export const MIN_SIMULATION_COUNT = 1000;+export const MAX_SIMULATION_COUNT = 10000;+export const MIN_HORIZON_YEARS = 1;+export const MAX_HORIZON_YEARS = 100;++// Upper bounds shared by the engine's input clamps and the UI's inputs,+// so validation and simulation can't drift apart+export const MAX_WITHDRAWAL_TAX_RATE = 0.75;+export const MAX_TAX_BAND_RATE = 0.99;+export const MAX_ANNUAL_FEE_RATE = 0.1;++// Fixed PRNG seed so identical inputs always produce identical results -+// keeps the headline numbers stable across re-renders and tests exact.+const DEFAULT_SIMULATION_SEED = 1234;++/** One phase of the planned spending path */+export type MonteCarloSpendingPhase = {+ id: string;+ name: string;+ /** Age the phase begins (inclusive); null = starts immediately */+ fromAge: number | null;+ /** Yearly spending in minor units, in today's money */+ annualWithdrawal: number;+};++export function createMonteCarloSpendingPhase(+ id: string,+ fromAge: number | null = null,+): MonteCarloSpendingPhase {+ return {+ id,+ name: '',+ fromAge,+ annualWithdrawal: 2_000_000, // 20,000.00 in minor units+ };+}++/**+ * Phases ordered by starting age (no-age phase first) - the order the+ * engine resolves them in, shared with the UI so they can't disagree+ */+export function sortMonteCarloSpendingPhases(+ phases: MonteCarloSpendingPhase[],+): MonteCarloSpendingPhase[] {+ return [...phases].sort(+ (phaseA, phaseB) =>+ (phaseA.fromAge ?? -Infinity) - (phaseB.fromAge ?? -Infinity),+ );+}++/** One invested pot with its own balance and return assumptions */+export type MonteCarloPot = {+ id: string;+ name: string;+ startingBalance: number; // integer minor units (cents)+ allocationPreset: MonteCarloAllocationPreset;+ expectedReturnMean: number; // decimal fraction+ returnStdDev: number; // decimal fraction+ /** Age from which the pot can fund withdrawals; null = immediately */+ accessAge: number | null;+ /**+ * Account whose live balance supplies the starting balance (resolved by+ * the UI before the simulation runs); null = manually entered balance+ */+ accountId: string | null;+ /** Flat tax model: effective tax rate on withdrawals (decimal fraction) */+ withdrawalTaxRate: number;+ /** Bands tax model: share of a withdrawal counted as taxable income */+ taxableFraction: number;+ /** Fixed yearly fee in minor units, today's money */+ annualFeeFixed: number;+ /** Whether the fixed fee rises with inflation */+ feeAdjustsWithInflation: boolean;+ /** Yearly fee as a fraction of the end-of-year balance */+ annualFeeRate: number;+};++export function createMonteCarloPot(id: string): MonteCarloPot {+ return {+ id,+ name: '',+ startingBalance: 50_000_000, // 500,000.00 in minor units+ allocationPreset: 'equity-60',+ expectedReturnMean: ALLOCATION_PRESETS['equity-60'].mean,+ returnStdDev: ALLOCATION_PRESETS['equity-60'].stdDev,+ accessAge: null,+ accountId: null,+ withdrawalTaxRate: 0,+ taxableFraction: 1,+ annualFeeFixed: 0,+ feeAdjustsWithInflation: false,+ annualFeeRate: 0,+ };+}++/** One tax band: annual taxable income from `from` upward taxed at `rate` */+export type MonteCarloTaxBand = {+ id: string;+ /** Threshold in minor units, in today's money */+ from: number;+ /** Decimal fraction (0.2 = 20%) */+ rate: number;+};++export function createMonteCarloTaxBand(+ id: string,+ from = 0,+): MonteCarloTaxBand {+ return { id, from, rate: 0 };+}++/**+ * The full set of simulation settings the user can configure. Stored in the+ * widget meta; new configuration options (withdrawal rules, fees, ...) should+ * be added here so the configuration UI and the engine stay in sync.+ */+/** Fully-populated withdrawal rule settings; `type` picks the active rule */+export type MonteCarloWithdrawalRuleConfig =+ Required<MonteCarloWithdrawalRuleMeta>;++export const WITHDRAWAL_RULE_DEFAULTS: MonteCarloWithdrawalRuleConfig = {+ type: 'none',+ // Guardrails (Guyton-Klinger's canonical 20% bands with 10% adjustments)+ prosperityTriggerPct: 0.2,+ prosperityIncreasePct: 0.1,+ preservationTriggerPct: 0.2,+ preservationCutPct: 0.1,+ // Ratcheting (Kitces)+ balanceThresholdMultiple: 1.5,+ consecutiveYears: 3,+ ratchetIncreasePct: 0.05,+ // Floor & ceiling (Bengen)+ floorPct: 0.15,+ ceilingPct: 0.2,+ // Boundaries+ upperRateThreshold: 0.06,+ upperCutPct: 0.1,+ lowerRateThreshold: 0.04,+ lowerIncreasePct: 0.05,+};++export type MonteCarloConfig = {+ pots: MonteCarloPot[];+ /** How the annual withdrawal is taken across pots */+ withdrawalStrategy: MonteCarloWithdrawalStrategy;+ /**+ * How yearly returns are generated: random normal draws, random samples+ * of historical years, or replays of actual historical sequences+ */+ 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;+ /** The planned spending path; each phase runs until the next one starts */+ spendingPhases: MonteCarloSpendingPhase[];+ /** Mean yearly inflation as a decimal fraction; null = flat withdrawals */+ inflationMean: number | null;+ /** Yearly inflation volatility as a decimal fraction; 0 = fixed rate */+ inflationStdDev: number;+ /** How withdrawals are taxed: flat rate per pot, or progressive bands */+ taxModel: MonteCarloTaxModel;+ /** Bands model: progressive bands over annual taxable income */+ taxBands: MonteCarloTaxBand[];+ currentAge: number;+ /** Age the pot must last to; the horizon is targetAge - currentAge */+ targetAge: number;+ simulationCount: number;+};++export const MONTE_CARLO_DEFAULTS: MonteCarloConfig = {+ pots: [createMonteCarloPot('pot-1')],+ withdrawalStrategy: 'proportional',+ returnModel: 'normal',+ withdrawalRule: WITHDRAWAL_RULE_DEFAULTS,+ minimumWithdrawal: 0,+ spendingPhases: [createMonteCarloSpendingPhase('phase-1')],+ inflationMean: 0.025,+ inflationStdDev: 0.02,+ taxModel: 'flat',+ taxBands: [createMonteCarloTaxBand('band-1')],+ currentAge: 60,+ targetAge: 90,+ simulationCount: 5000,+};++/** Simulated years, derived from the configured ages */+export function getMonteCarloHorizonYears(+ config: Pick<MonteCarloConfig, 'currentAge' | 'targetAge'>,+): number {+ return clamp(+ Math.round(config.targetAge - config.currentAge),+ MIN_HORIZON_YEARS,+ MAX_HORIZON_YEARS,+ );+}++function potFromMeta(potMeta: MonteCarloPotMeta, index: number): MonteCarloPot {+ const defaults = createMonteCarloPot(potMeta.id || `pot-${index + 1}`);+ return {+ ...defaults,+ name: potMeta.name ?? defaults.name,+ startingBalance: potMeta.startingBalance ?? defaults.startingBalance,+ allocationPreset: potMeta.allocationPreset ?? defaults.allocationPreset,+ expectedReturnMean:+ potMeta.expectedReturnMean ?? defaults.expectedReturnMean,+ returnStdDev: potMeta.returnStdDev ?? defaults.returnStdDev,+ accessAge: potMeta.accessAge ?? null,+ accountId: potMeta.accountId ?? null,+ withdrawalTaxRate: potMeta.withdrawalTaxRate ?? defaults.withdrawalTaxRate,+ taxableFraction: potMeta.taxableFraction ?? defaults.taxableFraction,+ annualFeeFixed: potMeta.annualFeeFixed ?? defaults.annualFeeFixed,+ feeAdjustsWithInflation:+ potMeta.feeAdjustsWithInflation ?? defaults.feeAdjustsWithInflation,+ annualFeeRate: potMeta.annualFeeRate ?? defaults.annualFeeRate,+ };+}++function taxBandFromMeta(+ bandMeta: MonteCarloTaxBandMeta,+ index: number,+): MonteCarloTaxBand {+ const defaults = createMonteCarloTaxBand(bandMeta.id || `band-${index + 1}`);+ return {+ ...defaults,+ from: bandMeta.from ?? defaults.from,+ rate: bandMeta.rate ?? defaults.rate,+ };+}++function spendingPhaseFromMeta(+ phaseMeta: MonteCarloSpendingPhaseMeta,+ index: number,+): MonteCarloSpendingPhase {+ const defaults = createMonteCarloSpendingPhase(+ phaseMeta.id || `phase-${index + 1}`,+ );+ return {+ ...defaults,+ name: phaseMeta.name ?? defaults.name,+ fromAge: phaseMeta.fromAge ?? null,+ annualWithdrawal: phaseMeta.annualWithdrawal ?? defaults.annualWithdrawal,+ };+}++export function monteCarloConfigFromMeta(+ meta: MonteCarloWidget['meta'] | undefined,+): MonteCarloConfig {+ return {+ pots: meta?.pots?.length+ ? meta.pots.map(potFromMeta)+ : [createMonteCarloPot('pot-1')],+ 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,+ spendingPhases: meta?.spendingPhases?.length+ ? meta.spendingPhases.map(spendingPhaseFromMeta)+ : [createMonteCarloSpendingPhase('phase-1')],+ inflationMean:+ meta?.inflationMean !== undefined+ ? meta.inflationMean+ : MONTE_CARLO_DEFAULTS.inflationMean,+ inflationStdDev:+ meta?.inflationStdDev ?? MONTE_CARLO_DEFAULTS.inflationStdDev,+ taxModel: meta?.taxModel ?? MONTE_CARLO_DEFAULTS.taxModel,+ taxBands: meta?.taxBands?.length+ ? meta.taxBands.map(taxBandFromMeta)+ : [createMonteCarloTaxBand('band-1')],+ currentAge: meta?.currentAge ?? MONTE_CARLO_DEFAULTS.currentAge,+ targetAge: meta?.targetAge ?? MONTE_CARLO_DEFAULTS.targetAge,+ simulationCount:+ meta?.simulationCount ?? MONTE_CARLO_DEFAULTS.simulationCount,+ };+}++// The engine mostly thinks in years; callers derive horizonYears from the+// configured ages via getMonteCarloHorizonYears. currentAge is still needed+// to know when each pot's access age is reached.+export type MonteCarloParams = Omit<MonteCarloConfig, 'targetAge'> & {+ horizonYears: number;+ seed?: number;+ /** Override the bundled historical dataset (used in tests) */+ historicalReturns?: HistoricalAnnualReturn[];+ /**+ * Sim index to capture year-by-year detail for. Because runs are seeded,+ * re-running with the same params reproduces any run exactly.+ */+ captureRunDetail?: number;+ /**+ * Convert all monetary outputs to today's money by discounting with the+ * configured inflation rate. Success rates and depletion timing are+ * unaffected - this only changes how balances and withdrawals read.+ */+ deflateToTodaysMoney?: boolean;+};++/** One simulated year of a single captured run, values in minor units */+export type MonteCarloRunDetailRow = {+ year: number;+ /** Total balance at the start of the year, before the withdrawal */+ startBalance: number;+ /** Amount actually withdrawn (the accessible remainder on failure) */+ withdrawal: number;+ /** Investment gain/loss applied after the withdrawal */+ growth: number;+ endBalance: number;+ /** End-of-year balance per pot, in the order the pots are configured */+ potBalances: number[];+ /** Start-of-year balance per pot, before the withdrawal, same order */+ potStartBalances: number[];+ /** How much of this year's withdrawal each pot funded (gross), same order */+ potWithdrawals: number[];+ /**+ * Tax attributed to each pot's withdrawal: exact under the flat model,+ * prorated by taxable-income share under the bands model+ */+ potTaxes: number[];+ /**+ * The slice of each pot's withdrawal assessed for tax: taxable fraction+ * of the take under the bands model, the whole take under a nonzero+ * flat rate, 0 with no tax+ */+ potTaxables: number[];+ /** Tax paid out of this year's gross withdrawal (0 with no tax model) */+ taxPaid: number;+ /** Management fees charged at the end of this year */+ feesPaid: number;+ /** Fee each pot was charged at the end of the year, same order as pots */+ potFees: number[];+ /**+ * The return each pot actually experienced that year, as a decimal+ * fraction; null when the pot had no balance or the plan failed+ */+ potReturns: Array<number | null>;+ /**+ * Set on a failure year when money remained in pots that hadn't reached+ * their access age - the plan failed despite this locked balance+ */+ inaccessibleBalance?: number;+};++export type MonteCarloPercentileBand = {+ /** 0 = starting point, 1..horizonYears = end of that year */+ year: number;+ p5: number;+ p10: number;+ p25: number;+ p30: number;+ p50: number;+ p70: number;+ p75: number;+ p90: number;+};++export type MonteCarloResult = {+ /** Fraction (0..1) of simulations that survived the full horizon */+ successRate: number;+ percentileBands: MonteCarloPercentileBand[];+ /** One entry per year 1..horizonYears; count of sims depleted in that year */+ depletionHistogram: Array<{ year: number; count: number }>;+ /** Cumulative depletion probability, indexed by year (0..horizonYears) */+ depletionProbabilityByYear: number[];+ /** Median ending balance across all simulations, in minor units */+ medianEndingBalance: number;+ /**+ * Median across simulations of the total amount actually withdrawn over+ * the horizon, in minor units - shows the income cost of withdrawal rules+ */+ medianTotalWithdrawn: number;+ /** Median depletion year among failed simulations, or null if none failed */+ medianDepletionYear: number | null;+ earliestDepletionYear: number | null;+ latestDepletionYear: number | null;+ /**+ * Balance path (year 0..horizonYears, minor units) of the single unluckiest+ * simulation: the one that ran out of money earliest, or the one with the+ * lowest ending balance if none ran out.+ */+ worstRunPath: number[];+ /** Final balance of every simulation, in minor units */+ endingBalances: Float64Array;+ /** Depletion year per simulation; -1 = survived the full horizon */+ depletionYearBySimulation: Int32Array;+ /** Total amount withdrawn over the horizon per simulation */+ totalWithdrawnBySimulation: Float64Array;+ /** Year-by-year rows for the simulation requested via captureRunDetail */+ runDetail?: MonteCarloRunDetailRow[];+ simulationCount: number;+ horizonYears: number;+};++function clamp(value: number, min: number, max: number) {+ return Math.min(max, Math.max(min, value));+}++// Small deterministic PRNG (mulberry32) - no dependencies needed.+function mulberry32(seed: number) {+ let state = seed >>> 0;+ return function next() {+ state |= 0;+ state = (state + 0x6d2b79f5) | 0;+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;+ };+}++// Standard normal draw via the Box-Muller transform.+function makeNormalSampler(random: () => number) {+ return function nextNormal() {+ // Avoid log(0) by shifting the first uniform draw into (0, 1]+ const uniform1 = 1 - random();+ const uniform2 = random();+ return (+ Math.sqrt(-2 * Math.log(uniform1)) * Math.cos(2 * Math.PI * uniform2)+ );+ };+}++function percentileOfSorted(sorted: Float64Array, percentile: number) {+ const position = (sorted.length - 1) * percentile;+ const lower = Math.floor(position);+ const upper = Math.ceil(position);+ if (lower === upper) {+ return sorted[lower];+ }+ const weight = position - lower;+ return sorted[lower] * (1 - weight) + sorted[upper] * weight;+}++/**+ * Runs the drawdown simulation with i.i.d. normal annual returns.+ *+ * Each year, in each simulation: the withdrawal is taken at the start of the+ * year across the pots that have reached their access age (proportionally to+ * their balances, or draining pots in order); if the accessible pots can't+ * cover it the simulation is marked depleted for that year (balances clamped+ * to 0 for the rest of the path), even if locked pots still hold money;+ * otherwise each pot gets its own randomly drawn return for the year. When an+ * inflation rate is set, next year's withdrawal grows by it. Returns are+ * nominal - inflation only grows withdrawals, so it is never double-counted.+ * Pot returns are drawn independently (no cross-pot correlation).+ */+export function runMonteCarloSimulation(+ params: MonteCarloParams,+): MonteCarloResult {+ const pots = params.pots.length > 0 ? params.pots : MONTE_CARLO_DEFAULTS.pots;+ const potCount = pots.length;+ const potStartBalances = pots.map(pot =>+ clamp(pot.startingBalance, 0, MAX_AMOUNT),+ );+ const potMeans = pots.map(pot => pot.expectedReturnMean);+ const potStdDevs = pots.map(pot => Math.max(0, pot.returnStdDev));+ const isSequential = params.withdrawalStrategy === 'sequential';+ const isBestPerformer = params.withdrawalStrategy === 'best-performer';+ const isTargetMix = params.withdrawalStrategy === 'target-mix';+ // Best-performer order: each pot's return from the previous simulated+ // year, and a reusable index buffer for the per-year drain order+ const previousReturns = new Float64Array(potCount);+ const drainOrder = pots.map((_, index) => index);+ // Target-mix order: each pot's target weight is its share of the+ // starting balances; this holds each pot's ideal post-withdrawal balance+ const potIdealBalances = new Float64Array(potCount);+ // Per-pot gross takes for the year being processed (scratch buffer)+ const potTakes = new Float64Array(potCount);++ // First simulation year (1-based) in which each pot can fund withdrawals.+ // The year-y withdrawal happens at age currentAge + (y - 1).+ const potAccessFromYear = pots.map(pot =>+ pot.accessAge == null+ ? 1+ : Math.max(1, Math.round(pot.accessAge - params.currentAge) + 1),+ );++ // --- Tax --------------------------------------------------------------+ // Spending is a net-of-tax requirement; withdrawals are gross. The flat+ // model taxes each pot's take at its own effective rate; the bands model+ // taxes the year's combined taxable income progressively.+ const taxModel: MonteCarloTaxModel = params.taxModel ?? 'flat';+ const potTaxRates = pots.map(pot =>+ clamp(pot.withdrawalTaxRate ?? 0, 0, MAX_WITHDRAWAL_TAX_RATE),+ );+ const potTaxableFractions = pots.map(pot =>+ clamp(pot.taxableFraction ?? 1, 0, 1),+ );+ // Bands sorted ascending, with a guaranteed 0-threshold first band so+ // income below the first user threshold is untaxed+ const taxBands = (params.taxBands ?? [])+ .map(band => ({+ from: clamp(band.from, 0, MAX_AMOUNT),+ rate: clamp(band.rate, 0, MAX_TAX_BAND_RATE),+ }))+ .sort((bandA, bandB) => bandA.from - bandB.from);+ if (taxBands.length === 0 || taxBands[0].from > 0) {+ taxBands.unshift({ from: 0, rate: 0 });+ }+ const hasTax =+ taxModel === 'bands'+ ? taxBands.some(band => band.rate > 0) &&+ potTaxableFractions.some(fraction => fraction > 0)+ : potTaxRates.some(rate => rate > 0);++ // --- Fees --------------------------------------------------------------+ const potFeeFixed = pots.map(pot =>+ clamp(pot.annualFeeFixed ?? 0, 0, MAX_AMOUNT),+ );+ const potFeeAdjusts = pots.map(pot => pot.feeAdjustsWithInflation ?? false);+ const potFeeRates = pots.map(pot =>+ clamp(pot.annualFeeRate ?? 0, 0, MAX_ANNUAL_FEE_RATE),+ );+ const hasFees =+ potFeeFixed.some(fee => fee > 0) || potFeeRates.some(rate => rate > 0);++ // Worst-case share of a gross withdrawal lost to tax; used to skip the+ // per-year shortfall precheck when capacity is comfortably sufficient+ const maxTaxRate =+ taxModel === 'bands'+ ? Math.max(0, ...taxBands.map(band => band.rate))+ : Math.max(0, ...potTaxRates);+ const minNetFactor = 1 - maxTaxRate;++ // Progressive tax on an annual taxable income, in today's money+ function bandTax(taxableIncome: number) {+ let tax = 0;+ for (let bandIndex = 0; bandIndex < taxBands.length; bandIndex++) {+ if (taxableIncome <= taxBands[bandIndex].from) {+ break;+ }+ const upper =+ bandIndex + 1 < taxBands.length+ ? taxBands[bandIndex + 1].from+ : Infinity;+ tax +=+ taxBands[bandIndex].rate *+ (Math.min(taxableIncome, upper) - taxBands[bandIndex].from);+ }+ return tax;+ }++ // 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) {+ if (!hasTax) {+ return 0;+ }+ if (taxModel === 'flat') {+ let tax = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ tax += potTakes[potIndex] * potTaxRates[potIndex];+ }+ return tax;+ }+ let taxable = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ taxable += potTakes[potIndex] * potTaxableFractions[potIndex];+ }+ return bandTax(taxable / cumulativeInflationNow) * cumulativeInflationNow;+ }++ // The slice of each pot's take (currently in potTakes) that was assessed+ // for tax: the taxable fraction under the bands model, or the whole take+ // under a nonzero flat rate. Used only for the captured run's drill-in.+ function captureTaxables(into: number[]) {+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ into[potIndex] =+ taxModel === 'bands'+ ? potTakes[potIndex] * potTaxableFractions[potIndex]+ : potTaxRates[potIndex] > 0+ ? potTakes[potIndex]+ : 0;+ }+ }++ // Attribute a year's tax to pots for the drill-in: exact per pot under+ // the flat model; under the bands model (where tax is computed on pooled+ // income) prorated by each pot's share of the taxable income+ function attributeTaxToPots(totalTax: number, into: number[]) {+ if (totalTax <= 0) {+ return;+ }+ if (taxModel === 'flat') {+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ into[potIndex] = potTakes[potIndex] * potTaxRates[potIndex];+ }+ return;+ }+ let taxableTotal = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ taxableTotal += potTakes[potIndex] * potTaxableFractions[potIndex];+ }+ if (taxableTotal <= 0) {+ return;+ }+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ into[potIndex] =+ totalTax *+ ((potTakes[potIndex] * potTaxableFractions[potIndex]) / taxableTotal);+ }+ }++ // 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).+ function computeTakes(+ grossTotal: number,+ year: number,+ accessibleTotal: number,+ lastAccessibleIndex: number,+ ) {+ potTakes.fill(0);+ if (grossTotal <= 0 || accessibleTotal <= 0) {+ return;+ }+ if (isSequential || isBestPerformer) {+ if (isBestPerformer) {+ // Drain the pot with the highest return last year first; ties+ // (and year 1, with no returns yet) fall back to the listed+ // order via the stable sort+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ drainOrder[potIndex] = potIndex;+ }+ drainOrder.sort(+ (potA, potB) => previousReturns[potB] - previousReturns[potA],+ );+ }+ let remaining = grossTotal;+ for (+ let orderIndex = 0;+ orderIndex < potCount && remaining > 0;+ orderIndex+++ ) {+ const potIndex = isBestPerformer ? drainOrder[orderIndex] : orderIndex;+ if (year < potAccessFromYear[potIndex]) {+ continue;+ }+ const take = Math.min(potBalances[potIndex], remaining);+ potTakes[potIndex] = take;+ remaining -= take;+ }+ } else if (isTargetMix) {+ // Withdraw so the accessible pots move back toward their target mix+ // (weights = shares of the starting balances, renormalized over+ // whichever pots are unlocked this year): each pot ideally ends at+ // its target share of the post-withdrawal total, so the withdrawal+ // comes from overweight pots, most overweight first+ let targetAccessible = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ if (year >= potAccessFromYear[potIndex]) {+ targetAccessible += potStartBalances[potIndex];+ }+ }+ const remainingTotal = accessibleTotal - grossTotal;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ drainOrder[potIndex] = potIndex;+ potIdealBalances[potIndex] =+ year >= potAccessFromYear[potIndex] && targetAccessible > 0+ ? (potStartBalances[potIndex] / targetAccessible) * remainingTotal+ : 0;+ }+ drainOrder.sort(+ (potA, potB) =>+ potBalances[potB] -+ potIdealBalances[potB] -+ (potBalances[potA] - potIdealBalances[potA]),+ );+ let remaining = grossTotal;+ for (+ let orderIndex = 0;+ orderIndex < potCount && remaining > 0;+ orderIndex+++ ) {+ const potIndex = drainOrder[orderIndex];+ if (year < potAccessFromYear[potIndex]) {+ continue;+ }+ const excess = potBalances[potIndex] - potIdealBalances[potIndex];+ if (excess <= 0) {+ continue;+ }+ const take = Math.min(remaining, potBalances[potIndex], excess);+ potTakes[potIndex] = take;+ remaining -= take;+ }+ // Float-drift safety net: drain any accessible pot for whatever+ // tiny residue the excess passes left behind+ for (let potIndex = 0; potIndex < potCount && remaining > 0; potIndex++) {+ if (year < potAccessFromYear[potIndex]) {+ continue;+ }+ const take = Math.min(+ potBalances[potIndex] - potTakes[potIndex],+ remaining,+ );+ potTakes[potIndex] += take;+ 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)+ let remaining = grossTotal;+ for (let potIndex = 0; potIndex < lastAccessibleIndex; potIndex++) {+ if (year < potAccessFromYear[potIndex]) {+ continue;+ }+ const take = grossTotal * (potBalances[potIndex] / accessibleTotal);+ potTakes[potIndex] = take;+ remaining -= take;+ }+ if (lastAccessibleIndex >= 0) {+ potTakes[lastAccessibleIndex] = remaining;+ }+ }+ }++ const returnModel = params.returnModel;+ const history = params.historicalReturns?.length+ ? params.historicalReturns+ : HISTORICAL_ANNUAL_RETURNS;+ const historyCount = history.length;++ // For historical models, each preset pot gets the blended return of its+ // asset mix in every historical year. 'custom' pots have no asset mix, so+ // they keep using normal draws around their own mean/volatility.+ const potHistoricalReturns: Array<Float64Array | null> = pots.map(pot => {+ if (returnModel === 'normal' || pot.allocationPreset === 'custom') {+ return null;+ }+ const weights = PRESET_ASSET_WEIGHTS[pot.allocationPreset];+ const blended = new Float64Array(historyCount);+ for (let historyIndex = 0; historyIndex < historyCount; historyIndex++) {+ blended[historyIndex] =+ weights.stocks * history[historyIndex].stocks ++ weights.bonds * history[historyIndex].bonds ++ weights.cash * history[historyIndex].cash;+ }+ return blended;+ });+ // Whether any pot's return comes from a normal draw (the whole normal+ // model, plus custom pots in historical modes)+ const hasNormalDrawPot = potHistoricalReturns.some(+ blended => blended === null,+ );++ const inflationMean = params.inflationMean;+ const inflationStdDev =+ inflationMean != null ? Math.max(0, params.inflationStdDev) : 0;+ const horizonYears = clamp(+ Math.round(params.horizonYears),+ MIN_HORIZON_YEARS,+ MAX_HORIZON_YEARS,+ );++ // 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 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;+ }++ // When showing values in today's money, outputs are discounted by each+ // replay's own realized inflation path+ const deflate = params.deflateToTodaysMoney === true && inflationMean != null;+ // Sequence replay runs exactly one scenario per historical start year+ // (wrapping around the end of the dataset); the simulation count input+ // doesn't apply there+ const simulationCount =+ returnModel === 'historical-sequence'+ ? historyCount+ : clamp(+ Math.round(params.simulationCount),+ MIN_SIMULATION_COUNT,+ MAX_SIMULATION_COUNT,+ );++ const random = mulberry32(params.seed ?? DEFAULT_SIMULATION_SEED);+ const nextNormal = makeNormalSampler(random);++ // Year-major balance buffers (totals across pots): balancesByYear[year][simulationIndex]+ const balancesByYear: Float64Array[] = [];+ for (let year = 0; year <= horizonYears; year++) {+ balancesByYear.push(new Float64Array(simulationCount));+ }++ const depletionCounts = new Array<number>(horizonYears + 1).fill(0);+ let survivedCount = 0;++ // The unluckiest simulation: earliest depletion, or lowest ending balance+ let worstSimIndex = 0;+ let worstDepletionYear = Infinity;+ let worstFinalBalance = Infinity;++ const startingTotal = potStartBalances.reduce(+ (sum, balance) => sum + balance,+ 0,+ );+ const potBalances = new Float64Array(potCount);++ const rule = params.withdrawalRule;+ const minimumWithdrawal = clamp(params.minimumWithdrawal, 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.+ // Capped a factor of two below MAX_FORMATTABLE_AMOUNT so chart axes can+ // round their top tick above the data maximum and still format it+ const maxEmitted = 2 ** 50;+ function toSafeAmount(value: number) {+ return clamp(value, -maxEmitted, maxEmitted);+ }+ // Starting wealth that is accessible in each simulated year. Withdrawal+ // rules measure rates against the pots that can actually fund spending -+ // a locked pension mustn't earn prosperity raises during a bridge, and+ // starts counting the moment it unlocks+ const accessibleStartByYear = new Float64Array(horizonYears + 1);+ for (let year = 1; year <= horizonYears; year++) {+ let accessibleStart = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ if (year >= potAccessFromYear[potIndex]) {+ accessibleStart += potStartBalances[potIndex];+ }+ }+ accessibleStartByYear[year] = accessibleStart;+ }++ const initialRate =+ accessibleStartByYear[1] > 0+ ? plannedTodayByYear[1] / accessibleStartByYear[1]+ : 0;+ const withdrawnTotals = new Float64Array(simulationCount);+ const depletionYearBySimulation = new Int32Array(simulationCount).fill(-1);++ const captureIndex = params.captureRunDetail ?? -1;+ const runDetail: MonteCarloRunDetailRow[] | undefined =+ captureIndex >= 0 && captureIndex < simulationCount ? [] : undefined;++ for (+ let simulationIndex = 0;+ simulationIndex < simulationCount;+ simulationIndex+++ ) {+ potBalances.set(potStartBalances);+ previousReturns.fill(0);+ let total = startingTotal;+ // Cuts/raises from the withdrawal rule compound here, applied on top of+ // the planned spending path (so they persist across spending phases)+ let adjustmentFactor = 1;+ // This replay's realized inflation path: each year draws its own rate+ // when inflation volatility is set+ let cumulativeInflation = 1;+ let ratchetStreak = 0;+ let withdrawnSum = 0;+ let depleted = false;+ let simulationDepletionYear = Infinity;++ balancesByYear[0][simulationIndex] = toSafeAmount(total);++ for (let year = 1; year <= horizonYears; year++) {+ if (!depleted) {+ const startDeflator = deflate ? 1 / cumulativeInflation : 1;+ const planned = plannedTodayByYear[year] * cumulativeInflation;+ let withdrawal: number;++ // Only pots that have reached their access age can fund this year's+ // withdrawal; locked pots stay invested but untouchable+ let accessibleTotal = 0;+ let lastAccessibleIndex = -1;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ if (year >= potAccessFromYear[potIndex]) {+ accessibleTotal += potBalances[potIndex];+ lastAccessibleIndex = potIndex;+ }+ }++ // Apply the dynamic withdrawal rule before taking this year's+ // withdrawal (from year 2 - year 1 always uses the planned amount).+ // Rules evaluate accessible wealth only: locked pots can't fund+ // spending, so they must not drive cuts or raises until they unlock+ if (year > 1 && rule.type === 'floor-ceiling') {+ // Recompute rule: a fixed share of the accessible balance, kept+ // within limits around the planned spending+ withdrawal = clamp(+ initialRate * accessibleTotal,+ planned * (1 - rule.floorPct),+ planned * (1 + rule.ceilingPct),+ );+ } else {+ if (+ year > 1 &&+ rule.type !== 'none' &&+ accessibleTotal > 0 &&+ accessibleStartByYear[year] > 0+ ) {+ const currentRate = (planned * adjustmentFactor) / accessibleTotal;+ if (rule.type === 'guardrails') {+ // Drift is measured against the planned spending path, not+ // the year-1 rate, so a deliberate phase change doesn't+ // 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];+ if (+ currentRate >+ referenceRate * (1 + rule.preservationTriggerPct)+ ) {+ adjustmentFactor *= 1 - rule.preservationCutPct;+ } else if (+ currentRate <+ referenceRate * (1 - rule.prosperityTriggerPct)+ ) {+ adjustmentFactor *= 1 + rule.prosperityIncreasePct;+ }+ } else if (rule.type === 'ratcheting') {+ if (+ accessibleTotal >+ accessibleStartByYear[year] * rule.balanceThresholdMultiple+ ) {+ ratchetStreak++;+ if (ratchetStreak >= rule.consecutiveYears) {+ adjustmentFactor *= 1 + rule.ratchetIncreasePct;+ ratchetStreak = 0;+ }+ } else {+ ratchetStreak = 0;+ }+ } else if (rule.type === 'boundaries') {+ if (currentRate > rule.upperRateThreshold) {+ adjustmentFactor *= 1 - rule.upperCutPct;+ } else if (currentRate < rule.lowerRateThreshold) {+ adjustmentFactor *= 1 + rule.lowerIncreasePct;+ }+ }+ }+ withdrawal = planned * adjustmentFactor;+ }+ // 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+ // 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;+ if (+ rule.type !== 'none' &&+ minimumWithdrawal > 0 &&+ planned > 0 &&+ withdrawal < minimumThisYear+ ) {+ withdrawal = minimumThisYear;+ }++ const yearStartTotal = total;+ // The spending requirement is net of tax; withdrawalTaken is the+ // gross that leaves the pots to deliver it+ const netRequired = withdrawal;+ let withdrawalTaken: number;+ let netDelivered: number;+ let fundingShortfall = false;++ // Per-pot balances at the point of failure: accessible pots are+ // consumed, locked pots keep their money+ let failurePotSnapshot: number[] | null = null;+ const capturedPotReturns =+ runDetail && simulationIndex === captureIndex+ ? new Array<number | null>(potCount).fill(null)+ : null;+ const capturedPotWithdrawals = capturedPotReturns+ ? new Array<number>(potCount).fill(0)+ : null;+ const capturedPotTaxes = capturedPotReturns+ ? new Array<number>(potCount).fill(0)+ : null;+ const capturedPotTaxables = capturedPotReturns+ ? new Array<number>(potCount).fill(0)+ : null;+ const capturedPotFees = capturedPotReturns+ ? new Array<number>(potCount).fill(0)+ : null;+ // Snapshot taken now, before the withdrawal touches the balances+ const capturedPotStartBalances = capturedPotReturns+ ? Array.from(potBalances)+ : null;++ // Net capacity: what withdrawing every accessible penny would+ // actually deliver after tax. The full-drain split is only worth+ // computing when a shortfall is actually possible - even taxed at+ // the highest marginal rate, capacity above the requirement means+ // the plan funds this year+ let accessibleNetCapacity = accessibleTotal;+ if (hasTax && accessibleTotal * minNetFactor <= netRequired) {+ computeTakes(+ accessibleTotal,+ year,+ accessibleTotal,+ lastAccessibleIndex,+ );+ accessibleNetCapacity =+ accessibleTotal - taxForTakes(cumulativeInflation);+ }++ if (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);+ // they get emptied for whatever net they can deliver+ withdrawnSum = toSafeAmount(+ withdrawnSum + accessibleTotal * startDeflator,+ );+ withdrawalTaken = accessibleTotal;+ netDelivered = Math.max(0, accessibleNetCapacity);+ if (runDetail && simulationIndex === captureIndex) {+ failurePotSnapshot = Array.from(potBalances, (balance, potIndex) =>+ year >= potAccessFromYear[potIndex] ? 0 : Math.round(balance),+ );+ if (capturedPotWithdrawals) {+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ capturedPotWithdrawals[potIndex] =+ year >= potAccessFromYear[potIndex]+ ? potBalances[potIndex]+ : 0;+ }+ }+ if (capturedPotTaxes) {+ // potTakes still holds the everything-accessible split from+ // the net-capacity check above+ attributeTaxToPots(+ accessibleTotal - netDelivered,+ capturedPotTaxes,+ );+ }+ if (capturedPotTaxables && hasTax) {+ captureTaxables(capturedPotTaxables);+ }+ }+ potBalances.fill(0);+ total = 0;+ depleted = true;+ simulationDepletionYear = year;+ depletionCounts[year]++;+ } else {+ // Solve the gross withdrawal that delivers the net requirement:+ // g = net + tax(takes(g)). Tax is piecewise linear in g with+ // marginal rates < 1, so this fixed point converges geometrically+ let grossTotal = netRequired;+ if (hasTax) {+ for (let iteration = 0; iteration < 40; iteration++) {+ computeTakes(+ grossTotal,+ year,+ accessibleTotal,+ lastAccessibleIndex,+ );+ const next = netRequired + taxForTakes(cumulativeInflation);+ if (Math.abs(next - grossTotal) <= 1e-7 * Math.max(1, next)) {+ grossTotal = next;+ break;+ }+ grossTotal = next;+ }+ grossTotal = Math.min(grossTotal, accessibleTotal);+ }++ computeTakes(grossTotal, year, accessibleTotal, lastAccessibleIndex);+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ potBalances[potIndex] -= potTakes[potIndex];+ }+ withdrawnSum = toSafeAmount(+ withdrawnSum + grossTotal * startDeflator,+ );+ withdrawalTaken = grossTotal;+ netDelivered = netRequired;++ if (capturedPotWithdrawals) {+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ capturedPotWithdrawals[potIndex] = potTakes[potIndex];+ }+ }+ if (capturedPotTaxes) {+ attributeTaxToPots(grossTotal - netRequired, capturedPotTaxes);+ }+ if (capturedPotTaxables && hasTax) {+ captureTaxables(capturedPotTaxables);+ }++ // Every pot experiences the same market year: historical models+ // pick one history year for all pots, and normally-drawn pots+ // share one market shock scaled by their own volatility. Pots+ // holding the same investments therefore earn the same return.+ let historyIndex = -1;+ if (returnModel === 'historical-bootstrap') {+ historyIndex = Math.floor(random() * historyCount);+ } else if (returnModel === 'historical-sequence') {+ historyIndex = (simulationIndex + year - 1) % historyCount;+ }+ const marketShock = hasNormalDrawPot ? nextNormal() : 0;++ total = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ if (potBalances[potIndex] > 0) {+ const blended = potHistoricalReturns[potIndex];+ const yearReturn =+ blended && historyIndex >= 0+ ? blended[historyIndex]+ : potMeans[potIndex] + potStdDevs[potIndex] * marketShock;+ if (capturedPotReturns) {+ capturedPotReturns[potIndex] = yearReturn;+ }+ previousReturns[potIndex] = yearReturn;+ potBalances[potIndex] *= 1 + yearReturn;+ if (potBalances[potIndex] <= 0) {+ // A sub-(-100%) return draw wiped this pot out+ potBalances[potIndex] = 0;+ }+ }+ total += potBalances[potIndex];+ }+ if (total <= 0) {+ total = 0;+ depleted = true;+ simulationDepletionYear = year;+ depletionCounts[year]++;+ }+ }++ // Realize this year's inflation, drawing a random rate when+ // volatility is set (fixed mean otherwise)+ if (inflationMean != null) {+ const yearInflation =+ inflationStdDev > 0+ ? Math.max(-0.9, inflationMean + inflationStdDev * nextNormal())+ : inflationMean;+ cumulativeInflation *= 1 + yearInflation;+ }++ // Management fees come out at the end of the year, after growth+ // and inflation: a percentage of each pot's balance plus a fixed+ // amount (optionally inflation-adjusted so it stays constant in+ // today's money). Fees can deplete a plan on their own.+ let feesThisYear = 0;+ if (hasFees && !fundingShortfall && total > 0) {+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ if (potBalances[potIndex] <= 0) {+ continue;+ }+ const fee =+ potBalances[potIndex] * potFeeRates[potIndex] ++ potFeeFixed[potIndex] *+ (potFeeAdjusts[potIndex] ? cumulativeInflation : 1);+ const charged = Math.min(potBalances[potIndex], fee);+ potBalances[potIndex] -= charged;+ feesThisYear += charged;+ if (capturedPotFees) {+ capturedPotFees[potIndex] = charged;+ }+ }+ total = 0;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ total += potBalances[potIndex];+ }+ if (total <= 0) {+ total = 0;+ depleted = true;+ simulationDepletionYear = year;+ depletionCounts[year]++;+ }+ }+ const endDeflator = deflate ? 1 / cumulativeInflation : 1;++ if (runDetail && simulationIndex === captureIndex) {+ // Every emitted amount is deflated, rounded, and kept within the+ // formatter-safe range - one mechanism so a new field can't+ // forget the wrapper+ const emit = (value: number, deflator: number) =>+ toSafeAmount(Math.round(value * deflator));+ // Per-pot amounts are rounded so they sum exactly to their row's+ // already-rounded total: floor each part, then hand the leftover+ // cents to the parts that lost the most in flooring (largest+ // remainder, ties to the lower pot index). Independently rounded+ // parts can visibly disagree with the total by a cent or two.+ const emitParts = (+ values: ArrayLike<number> | null,+ deflator: number,+ target: number,+ ) => {+ if (!values) {+ return [];+ }+ const scaled = Array.from(values, value => value * deflator);+ const parts = scaled.map(Math.floor);+ const shortfall =+ target - parts.reduce((sum, part) => sum + part, 0);+ if (shortfall < 0 || shortfall > parts.length) {+ // The parts don't reconcile with this target (safe-amount+ // clamping, or a degenerate float path) - fall back to+ // independent rounding rather than distorting them+ return Array.from(values, value => emit(value, deflator));+ }+ const byLargestRemainder = parts+ .map((_, partIndex) => partIndex)+ .sort(+ (partIndexA, partIndexB) =>+ scaled[partIndexB] -+ parts[partIndexB] -+ (scaled[partIndexA] - parts[partIndexA]) ||+ partIndexA - partIndexB,+ );+ for (let centIndex = 0; centIndex < shortfall; centIndex++) {+ parts[byLargestRemainder[centIndex]] += 1;+ }+ return parts.map(toSafeAmount);+ };+ const startBalance = emit(yearStartTotal, startDeflator);+ const withdrawal = emit(withdrawalTaken, startDeflator);+ const taxPaid = emit(withdrawalTaken - netDelivered, startDeflator);+ const base = {+ year,+ startBalance,+ withdrawal,+ taxPaid,+ potWithdrawals: emitParts(+ capturedPotWithdrawals,+ startDeflator,+ withdrawal,+ ),+ potTaxes: emitParts(capturedPotTaxes, startDeflator, taxPaid),+ // No displayed total to reconcile against+ potTaxables: (capturedPotTaxables ?? []).map(taxable =>+ emit(taxable, startDeflator),+ ),+ potStartBalances: emitParts(+ capturedPotStartBalances,+ startDeflator,+ startBalance,+ ),+ };+ if (fundingShortfall) {+ // The plan failed to fund this year's spending; any remaining+ // balance was locked in pots not yet accessible, not lost to+ // markets. Accessible pots gave up everything they had.+ const locked = emit(+ yearStartTotal - withdrawalTaken,+ startDeflator,+ );+ runDetail.push({+ ...base,+ growth: 0,+ feesPaid: 0,+ // No fees on a shortfall year - the plan stops before the+ // end-of-year charge+ potFees: (capturedPotFees ?? []).map(() => 0),+ endBalance: 0,+ // The snapshot is the locked money the failure note reports+ potBalances: emitParts(failurePotSnapshot, startDeflator, locked),+ potReturns: capturedPotReturns ?? [],+ ...(locked > 0 && { inaccessibleBalance: locked }),+ });+ } else {+ const feesPaid = emit(feesThisYear, endDeflator);+ const endBalance = emit(total, endDeflator);+ runDetail.push({+ ...base,+ // In today's money, growth is the real gain: the inflation+ // drag comes out of it. Fees are reported separately, so+ // growth stays pure market performance+ growth: toSafeAmount(+ Math.round(+ (total + feesThisYear) * endDeflator -+ (yearStartTotal - withdrawalTaken) * startDeflator,+ ),+ ),+ feesPaid,+ potFees: emitParts(capturedPotFees, endDeflator, feesPaid),+ endBalance,+ potBalances: emitParts(potBalances, endDeflator, endBalance),+ potReturns: (capturedPotReturns ?? []).map(potReturn =>+ potReturn == null+ ? null+ : (1 + potReturn) * (endDeflator / startDeflator) - 1,+ ),+ });+ }+ }++ // Store this replay's balance, in today's money when deflating+ balancesByYear[year][simulationIndex] = toSafeAmount(+ total * endDeflator,+ );+ }+ // Post-depletion years stay at zero (total is 0 here)+ }++ withdrawnTotals[simulationIndex] = withdrawnSum;+ if (simulationDepletionYear !== Infinity) {+ depletionYearBySimulation[simulationIndex] = simulationDepletionYear;+ }++ if (!depleted) {+ survivedCount++;+ }++ if (+ simulationDepletionYear < worstDepletionYear ||+ (simulationDepletionYear === worstDepletionYear &&+ total < worstFinalBalance)+ ) {+ worstSimIndex = simulationIndex;+ worstDepletionYear = simulationDepletionYear;+ worstFinalBalance = total;+ }+ }++ const worstRunPath: number[] = [];+ for (let year = 0; year <= horizonYears; year++) {+ worstRunPath.push(Math.round(balancesByYear[year][worstSimIndex]));+ }++ const percentileBands: MonteCarloPercentileBand[] = [];+ // The final year's sorted balances double as the median-ending-balance+ // source below, saving a second sort of the same array+ let finalSorted = new Float64Array(0);+ for (let year = 0; year <= horizonYears; year++) {+ const sorted = balancesByYear[year].slice().sort();+ if (year === horizonYears) {+ finalSorted = sorted;+ }+ percentileBands.push({+ year,+ p5: Math.round(percentileOfSorted(sorted, 0.05)),+ p10: Math.round(percentileOfSorted(sorted, 0.1)),+ p25: Math.round(percentileOfSorted(sorted, 0.25)),+ p30: Math.round(percentileOfSorted(sorted, 0.3)),+ p50: Math.round(percentileOfSorted(sorted, 0.5)),+ p70: Math.round(percentileOfSorted(sorted, 0.7)),+ p75: Math.round(percentileOfSorted(sorted, 0.75)),+ p90: Math.round(percentileOfSorted(sorted, 0.9)),+ });+ }++ const depletionHistogram: Array<{ year: number; count: number }> = [];+ for (let year = 1; year <= horizonYears; year++) {+ depletionHistogram.push({ year, count: depletionCounts[year] });+ }++ const depletionProbabilityByYear: number[] = [0];+ let cumulativeDepleted = 0;+ for (let year = 1; year <= horizonYears; year++) {+ cumulativeDepleted += depletionCounts[year];+ depletionProbabilityByYear.push(cumulativeDepleted / simulationCount);+ }++ // Earliest/median/latest failure years straight from the histogram+ // counts (no need to materialize one entry per failed simulation)+ const totalDepleted = simulationCount - survivedCount;+ let earliestDepletionYear: number | null = null;+ let latestDepletionYear: number | null = null;+ let medianDepletionYear: number | null = null;+ const medianTargetIndex = Math.floor((totalDepleted - 1) / 2);+ let seenDepleted = 0;+ for (let year = 1; year <= horizonYears; year++) {+ if (depletionCounts[year] === 0) {+ continue;+ }+ earliestDepletionYear ??= year;+ latestDepletionYear = year;+ if (medianDepletionYear == null) {+ seenDepleted += depletionCounts[year];+ if (seenDepleted > medianTargetIndex) {+ medianDepletionYear = year;+ }+ }+ }++ const withdrawnSorted = withdrawnTotals.slice().sort();++ return {+ successRate: survivedCount / simulationCount,+ percentileBands,+ depletionHistogram,+ depletionProbabilityByYear,+ medianEndingBalance: Math.round(percentileOfSorted(finalSorted, 0.5)),+ medianTotalWithdrawn: Math.round(percentileOfSorted(withdrawnSorted, 0.5)),+ medianDepletionYear,+ earliestDepletionYear,+ latestDepletionYear,+ worstRunPath,+ endingBalances: balancesByYear[horizonYears].slice(),+ depletionYearBySimulation,+ totalWithdrawnBySimulation: withdrawnTotals,+ runDetail,+ simulationCount,+ horizonYears,+ };+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloStyles.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloStyles.tsnew file mode 100644index 0000000000..97d008c968--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloStyles.ts@@ -0,0 +1,25 @@+import { theme } from '@actual-app/components/theme';++// Shared layout constants for the Monte Carlo configuration and results+// UI, so the visual language stays consistent across the report's files.++/** Small uppercase heading used for stat tiles, field groups and tables */+export const GROUP_HEADING_STYLE = {+ fontSize: 12,+ fontWeight: 600,+ letterSpacing: 0.5,+ textTransform: 'uppercase',+ color: theme.pageText,+} as const;++export const FIELD_STYLE = { width: 170 } as const;++export const FIELD_LABEL_STYLE = { fontWeight: 600 } as const;++export const FIELD_LABEL_ROW_STYLE = {+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: 6,+ minHeight: 18,+} as const;diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.tsnew file mode 100644index 0000000000..cda7269e68--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts@@ -0,0 +1,38 @@+import { useMemo } from 'react';++import type { MonteCarloConfig } from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import { useAccountBalances } from '#hooks/useAccountBalances';++/**+ * Resolves account-linked pots to their live balances: a linked pot takes+ * the account's current balance, falling back to its stored starting+ * balance until the live value arrives. Shared by the report page and the+ * dashboard card so both simulate the same portfolio.+ */+export function useResolvedMonteCarloConfig(+ config: MonteCarloConfig,+): MonteCarloConfig {+ const accountBalances = useAccountBalances(+ config.pots+ .map(pot => pot.accountId)+ .filter((id): id is string => id != null),+ );++ // Memoized by hand: this plain .ts file sits outside the React+ // Compiler's include (.tsx only), and the compiled consumers key their+ // auto-memoized simulation runs on this object's identity - a fresh+ // object every render would re-simulate on every unrelated re-render+ return useMemo(+ () => ({+ ...config,+ pots: config.pots.map(pot => {+ const balance =+ pot.accountId != null ? accountBalances[pot.accountId] : null;+ return balance != null+ ? { ...pot, startingBalance: Math.max(0, balance) }+ : pot;+ }),+ }),+ [config, accountBalances],+ );+}diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsxindex 7593c737b9..4964e9f084 100644--- a/packages/desktop-client/src/components/settings/Experimental.tsx+++ b/packages/desktop-client/src/components/settings/Experimental.tsx@@ -226,6 +226,12 @@ export function ExperimentalFeatures() {><Trans>Budget Analysis Report</Trans></FeatureToggle>+ <FeatureToggle+ flag="monteCarloReport"+ feedbackLink="https://github.com/actualbudget/actual/issues/8571"+ >+ <Trans>Monte Carlo Analysis Report</Trans>+ </FeatureToggle><FeatureToggleflag="enableBanking"feedbackLink="https://github.com/actualbudget/actual/issues/7799"diff --git a/packages/desktop-client/src/components/table.tsx b/packages/desktop-client/src/components/table.tsxindex d10ea2062f..95be609fb9 100644--- a/packages/desktop-client/src/components/table.tsx+++ b/packages/desktop-client/src/components/table.tsx@@ -1058,7 +1058,10 @@ export const Table = forwardRef(}if (scrollContainer.current && saveScrollWidth) {- setTimeout(saveScrollDelayed, 200);+ const timeout = setTimeout(saveScrollDelayed, 200);+ // Without this, the timer can fire after unmount and call setState+ // on a dead component (crashes test teardown)+ return () => clearTimeout(timeout);}});diff --git a/packages/desktop-client/src/hooks/useAccountBalances.ts b/packages/desktop-client/src/hooks/useAccountBalances.tsnew file mode 100644index 0000000000..26e90857d0--- /dev/null+++ b/packages/desktop-client/src/hooks/useAccountBalances.ts@@ -0,0 +1,51 @@+import { useLayoutEffect, useState } from 'react';++import { accountBalance } from '#spreadsheet/bindings';++import { useSpreadsheet } from './useSpreadsheet';++/**+ * Live balances for a set of accounts, keyed by account id. Values are+ * null until the spreadsheet reports them. Unlike useSheetValue this+ * accepts a variable-length list, binding one account-balance query per id.+ */+export function useAccountBalances(+ accountIds: string[],+): Record<string, number | null> {+ const spreadsheet = useSpreadsheet();+ const [balances, setBalances] = useState<Record<string, number | null>>({});++ // Re-bind only when the set of accounts actually changes+ const bindingKey = [...new Set(accountIds)].sort().join(',');++ useLayoutEffect(() => {+ if (bindingKey === '') {+ setBalances({});+ return;+ }++ let isMounted = true;+ const unbinds = bindingKey.split(',').map(accountId =>+ spreadsheet.bind('__global', accountBalance(accountId), result => {+ if (!isMounted) {+ return;+ }+ const value = typeof result.value === 'number' ? result.value : null;+ setBalances(previous =>+ previous[accountId] === value+ ? previous+ : { ...previous, [accountId]: value },+ );+ }),+ );++ return () => {+ isMounted = false;+ for (const unbind of unbinds) {+ unbind();+ }+ };+ }, [spreadsheet, bindingKey]);++ return balances;+}diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.tsindex 7e9b435ce5..976b5243d7 100644--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts@@ -15,6 +15,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {sankeyReport: false,akahuBankSync: false,mobileCalculator: false,+ monteCarloReport: false,};export function useFeatureFlag(name: FeatureFlag): boolean {diff --git a/packages/docs/docs-sidebar.js b/packages/docs/docs-sidebar.jsindex 110968388e..7cabc1adea 100644--- a/packages/docs/docs-sidebar.js+++ b/packages/docs/docs-sidebar.js@@ -219,6 +219,7 @@ const sidebars = {'experimental/formulas','experimental/balance-forecast-report','experimental/budget-analysis-report',+ 'experimental/monte-carlo-analysis','experimental/sankey-report',],},diff --git a/packages/docs/docs/experimental/monte-carlo-analysis.md b/packages/docs/docs/experimental/monte-carlo-analysis.mdnew file mode 100644index 0000000000..62dafda1e4--- /dev/null+++ b/packages/docs/docs/experimental/monte-carlo-analysis.md@@ -0,0 +1,189 @@+# Monte Carlo Analysis++<ExperimentalFeatureWarning />++## What Does This Report Do?++The Monte Carlo Analysis report helps you answer one of the biggest money questions there is: **"If I stop working and start living off my savings, will the money last?"**++Nobody knows what the stock market will do next year, let alone over the next 30 years. So instead of guessing once, this report guesses thousands of times. It replays your retirement over and over - 5,000 times by default - and in each replay the market has different luck: some replays hit a crash early on, some enjoy a long boom, most land somewhere in between.++At the end it tells you a simple, powerful number: **in what percentage of those replays did your money last as long as you needed it to?** If your plan survives in 85% of the replays, that's a much more honest answer than any single prediction could give you.++:::note+This report is a planning aid, not financial advice, and not a prediction. It can't know the future - it can only show you how your plan holds up across many possible futures.+:::++++## Turning the Report On++Monte Carlo Analysis is an experimental feature, so it's switched off until you enable it:++1. Open **Settings** from the sidebar.+2. Click **Show advanced settings**.+3. Open **Experimental features** and acknowledge the warning.+4. Tick **Monte Carlo Analysis Report**.++## Adding the Report to Your Dashboard++1. Go to **Reports** in the sidebar.+2. Click **Add new widget** and choose **Monte Carlo analysis**.+3. A card appears on your dashboard showing your success rate and a small chart. Click the card to open the full report.+4. After changing any settings in the full report, click **Save widget** so your setup is remembered next time.++The report works immediately with sensible example numbers filled in, so you can explore how it behaves before entering your own figures.++## Setting Up Your Plan++The configuration area at the top of the report is organized into three tabs.++### Plan Details++++The tab is organized into three small groups - **Your plan**, **Inflation** and **Simulation**:++- **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:+ - **Random (normal distribution)**: each year's return is drawn randomly around the expected return and volatility you set on each pot. Think of it as a weighted coin flip, year after year. Every pot lives through the same simulated market year - a good year is good for all your pots, scaled by each pot's volatility - so two pots holding the same investments earn the same return.+ - **Historical returns, shuffled**: instead of invented numbers, each simulated year is a real year from US market history (1928 onwards), picked in random order. Real crashes like 1931 and 2008 are in the deck.+ - **Historical sequences (replay)**: each replay is actual history, played in order from a different starting year - "what if you retired in 1929?", "what if you retired in 1972?", and so on. This is the strictest test of bad timing, because real crashes and recoveries happen in their true order.+- **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.+- **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.+- **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.++### Investment Pots++++A _pot_ is a chunk of invested money - a pension or retirement account, an investment account, a savings account. You can model one pot or several, each with its own settings:++- **Pot name** - anything you like, such as "Pension".+- **Starting balance** - how much is in the pot today. Enter it by hand, or use **Linked account** below to keep it up to date automatically.+- **Linked account** - link the pot to one of your accounts and its starting balance becomes that account's live balance, so the plan tracks reality without re-typing numbers. Typing a starting balance manually unlinks the pot and keeps your typed value - useful for what-if questions like "how big would this pot need to be?" - and you can re-link it any time with the picker.+- **Portfolio allocation** - a one-click preset that fills in a typical expected return and volatility for a given mix of stocks and bonds. A pot that's 100% stocks tends to grow faster but swings harder; a cash pot barely moves in either direction. You can always override the numbers, which switches the pot to **Custom**.+- **Expected return (%)** - the average yearly growth you expect from this pot, before inflation.+- **Volatility (std dev %)** - how much the returns swing from year to year. Two pots can have the same average return, but the one with higher volatility is riskier: bad early years can do damage that a smooth ride would avoid.+ Click the arrow at the start of a pot's row to expand its additional settings, organized into three groups:++- **Access - Accessible from age** - some pots can't be touched until a certain age; retirement accounts in many countries work this way. Leave this blank if the pot is available now. A locked pot stays invested and keeps growing - it just can't pay your bills until you reach the access age.+- **Tax - Tax (%)** (or **Taxable portion (%)** with the bands model) - how withdrawals from this pot are taxed; see [Tax](#tax) below. Leave at 0 for tax-free pots.+- **Fees** - what this pot costs you each year, charged at the end of every simulated year:+ - **Fixed yearly fee** - the sum of fixed costs like adviser or platform fees, as an amount. Tick **Adjust by inflation** if the fee will rise with prices over time (untick it for a contractually flat fee, which shrinks in real terms).+ - **Fee (% of balance)** - percentage charges like fund management fees, taken from the pot's end-of-year balance - e.g. 0.22 for a typical index fund platform.++Drag a pot's row to reorder the list - the order matters if you choose to drain pots one at a time (see [Spending](#spending) below).++:::tip+The 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.+:::++### Spending++++- **Spending phases** - how much you take out each year to live on. You can keep it simple with a single phase, or split your plan into phases with different amounts - for example, $30,000 a year for your first 10 years of retirement while you're travelling, then $20,000 a year onwards. Each phase sets a yearly amount from a chosen age until the next phase begins; the first phase always starts now. Amounts are in today's money - the inflation settings on the Plan Details tab are applied on top, so "$20,000 from age 65" always means $20,000 of today's spending power.+- **Withdrawal order** - only matters if you have more than one pot:+ - **Split proportionally across pots**: each year's withdrawal is taken from all pots in proportion to their size, so they shrink together.+ - **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.++The inflation settings that grow your spending over time live on the [Plan Details](#plan-details) tab.++### Tax++++Withdrawing money from a pension or a taxable account usually costs more than the amount you get to spend. The Tax tab lets the simulation account for that: **your yearly spending is always what you keep after tax**, and the simulation withdraws extra to cover the tax bill. Two models are available:++- **Flat rate per pot** (the default) - each pot gets one effective tax rate on its withdrawals, set in the pots table. A tax-free account is 0%. For a pension with a tax-free portion, blend it with your expected income tax rate - for example, 25% tax-free plus 20% tax on the rest works out around 15%. For a taxable investment account, estimate the effective rate on your typical withdrawal. This is deliberately simple and works for any country - you own the number.+- **Tax bands (progressive)** - enter your own tax brackets: yearly income thresholds and the rate above each one (your tax-free allowance is simply the first band at 0%). Each pot then declares its **Taxable portion (%)** - how much of a withdrawal counts as taxable income: a pension with a 25% tax-free lump portion is 75, a tax-free account is 0, and a taxable account is roughly the share of each withdrawal that is gains. The bands apply to each year's combined taxable withdrawals across all pots, and the thresholds are in today's money - they rise with inflation in the simulation.++With 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.++:::note+This 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.+:::++## Withdrawal Rules Explained++By default, the simulation withdraws the same (inflation-adjusted) amount every year, no matter what the market does. Real retirees usually don't behave that way - in a bad stretch they tighten their belts, and in a good stretch they allow themselves a bit more. Withdrawal rules teach the simulation to do the same.++All the rules share a few ideas:++- Your **spending phases** set the planned amounts. From the second year onward, the rule adjusts what's actually taken - independently in every replay, reacting to how that replay is going. 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.++### Guardrails (Guyton-Klinger)++Think of this as pay cuts and pay rises. The rule watches what percentage of your remaining money you're withdrawing each year. If your pots shrink so much that the percentage drifts well above where your plan says it should be, you take a pay cut (for example, 10% less). If your pots race ahead and the percentage falls well below it, you get a pay rise. You set how far the percentage must drift before the rule reacts, and how big the adjustment is. The drift is measured against your planned spending path, so moving into a deliberately higher or lower spending phase doesn't count as drift by itself - only market-driven changes do.++### Ratcheting (Kitces)++The optimist's rule: withdrawals only ever go **up**, never down. If your balance stays above a threshold (for example, 1.5 times what you started with) for several years in a row, you give yourself a raise. If markets fall, your spending simply stays where it is - the rule never cuts.++### Floor & Ceiling (Bengen)++Instead of a fixed amount, each year you withdraw a fixed **percentage of whatever the pots are currently worth** - so spending naturally falls in bad years and rises in good ones. To stop that swinging too wildly, the withdrawal is kept within a floor and a ceiling around your original (inflation-adjusted) amount.++### Boundaries++A simpler version of Guardrails: you set an upper and lower limit on the withdrawal percentage directly. Above the upper limit, spending is cut; below the lower limit, it's increased.++## Reading the Results++By default, every money figure in the results is shown in **today's money** - what the amounts would actually be worth in terms of today's prices, discounted by each replay's own inflation path. Untick **Show values in today's money** to see the raw future amounts instead; they'll look much bigger over long horizons, but most of that is inflation rather than real growth. The success rate and failure ages are the same either way.++### The Headline Numbers++++- **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%.+- **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.+- **Typical failure runs out at** - among the replays that failed, the typical age the money ran out.++### The Portfolio Performance Chart++++The chart shows your total balance from your current age to your target age - but instead of one line, it shows the whole range of futures at once:++- The **lighter band** covers 80% of all replays - at any age, 8 out of 10 replays landed inside it.+- The **darker band** covers the middle half of replays.+- The **line** is the median: half the replays did better, half did worse.++The 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.++### When Did the Pot Run Out?++++This bar chart only counts the replays that failed, showing at which age they ran out. If 900 of 5,000 replays failed, these bars add up to 900 - the other 4,100 kept a positive balance the whole way and don't appear here.++### Exploring Individual Runs++++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 withdrawal taken, the investment growth in that year (as money and as a percentage), 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; the fees paid; and a small table showing each pot's balance at the start of the 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.++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."++## Things to Keep in Mind++- **This is a model, not a prophecy.** A 90% success rate does not mean success is guaranteed - 1 in 10 of the simulated futures still failed.+- **The random model is simplified.** It draws each year independently, which ignores the way real crashes cluster together and the occasional extreme year. It also moves all pots in step - there's no independent luck per pot, so a bond-heavy pot dips a little in the same year a stock-heavy pot crashes. The historical models partly address the first point.+- **The historical data is US market data** (S&P 500 shares, US government bonds and bills, from 1928 onwards). US markets had an unusually good century, so results may be optimistic if your money is invested elsewhere.+- **Fees and taxes are approximations you control.** Each pot's fee settings model yearly costs explicitly - so enter expected returns _gross_ of those fees to avoid double-counting - and the [Tax](#tax) settings are effective-rate estimates, not a tax calculator.+- **Garbage in, garbage out.** The results are only as good as your estimates for returns, volatility, spending and inflation. Try a few variations - small changes to the withdrawal often move the success rate a lot.diff --git a/packages/docs/docs/reports/index.md b/packages/docs/docs/reports/index.mdindex e794c832b2..f06360da20 100644--- a/packages/docs/docs/reports/index.md+++ b/packages/docs/docs/reports/index.md@@ -28,6 +28,7 @@ The following are available as experimental features:- [Budget Analysis report](../experimental/budget-analysis-report.md)- [Balance Forecast report](../experimental/balance-forecast-report.md)- [Sankey report](../experimental/sankey-report.md)+- [Monte Carlo Analysis](../experimental/monte-carlo-analysis.md)## Cash Flow Graphdiff --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.pngnew file mode 100644index 0000000000..5affbf3dc9Binary files /dev/null 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-histogram.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.pngnew file mode 100644index 0000000000..e45891a788Binary files /dev/null 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-overview.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.pngnew file mode 100644index 0000000000..775f612442Binary files /dev/null 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.pngnew file mode 100644index 0000000000..8f40ad1725Binary files /dev/null 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.pngnew file mode 100644index 0000000000..c1ede83dbdBinary files /dev/null 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.pngnew file mode 100644index 0000000000..05a30f07faBinary files /dev/null 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.pngnew file mode 100644index 0000000000..05056926beBinary files /dev/null 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.pngnew file mode 100644index 0000000000..1dc4a01dbfBinary files /dev/null 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.pngnew file mode 100644index 0000000000..e505f89b20Binary files /dev/null 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.pngnew file mode 100644index 0000000000..745ee7358fBinary files /dev/null and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png differdiff --git a/packages/loot-core/src/server/dashboard/app.test.ts b/packages/loot-core/src/server/dashboard/app.test.tsindex 606c9e6d46..4d416f7e42 100644--- a/packages/loot-core/src/server/dashboard/app.test.ts+++ b/packages/loot-core/src/server/dashboard/app.test.ts@@ -25,6 +25,7 @@ const ALL_WIDGET_TYPES = allWidgetTypes('sankey-card','balance-forecast-card','age-of-money-card',+ 'monte-carlo-card',);describe('isWidgetType', () => {diff --git a/packages/loot-core/src/server/dashboard/app.ts b/packages/loot-core/src/server/dashboard/app.tsindex cffeca93a9..a5f35076fd 100644--- a/packages/loot-core/src/server/dashboard/app.ts+++ b/packages/loot-core/src/server/dashboard/app.ts@@ -45,6 +45,7 @@ export function isWidgetType('sankey-card','balance-forecast-card','age-of-money-card',+ 'monte-carlo-card',].includes(type);}diff --git a/packages/loot-core/src/shared/util.ts b/packages/loot-core/src/shared/util.tsindex ccf7658f67..fb2b1bf843 100644--- a/packages/loot-core/src/shared/util.ts+++ b/packages/loot-core/src/shared/util.ts@@ -423,7 +423,7 @@ export type IntegerAmount = number;// because we always do that on numbers, the app would potentially// display wrong numbers. Instead of `2**53` we use `2**51` which// gives division more room to be correct-const MAX_SAFE_NUMBER = 2 ** 51 - 1;+export const MAX_SAFE_NUMBER = 2 ** 51 - 1;const MIN_SAFE_NUMBER = -MAX_SAFE_NUMBER;export function safeNumber(value: number) {diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 865e9be3b0..b954f3bd5d 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -122,6 +122,136 @@ export type MarkdownWidget = AbstractWidget<{ content: string; text_align?: 'left' | 'right' | 'center' }>;+export type MonteCarloAllocationPreset =+ | 'equity-100'+ | 'equity-80'+ | 'equity-60'+ | 'equity-40'+ | 'cash'+ | 'custom';++export type MonteCarloWithdrawalStrategy =+ | 'proportional'+ | 'sequential'+ | 'best-performer'+ | 'target-mix';++export type MonteCarloReturnModel =+ | 'normal'+ | 'historical-bootstrap'+ | 'historical-sequence';++export type MonteCarloWithdrawalRuleType =+ | 'none'+ | 'guardrails'+ | 'ratcheting'+ | 'floor-ceiling'+ | 'boundaries';++// Parameters for all rule types are kept side by side so switching between+// rules in the UI preserves each rule's settings+export type MonteCarloWithdrawalRuleMeta = {+ type: MonteCarloWithdrawalRuleType;+ // Guardrails (Guyton-Klinger)+ prosperityTriggerPct?: number; // rate fell this fraction below initial+ prosperityIncreasePct?: number;+ preservationTriggerPct?: number; // rate rose this fraction above initial+ preservationCutPct?: number;+ // Ratcheting (Kitces)+ balanceThresholdMultiple?: number; // e.g. 1.5x initial balance+ consecutiveYears?: number;+ ratchetIncreasePct?: number;+ // Floor & ceiling (Bengen)+ floorPct?: number; // fraction below the inflation-adjusted initial+ ceilingPct?: number; // fraction above the inflation-adjusted initial+ // Boundaries+ upperRateThreshold?: number; // absolute withdrawal rate, e.g. 0.06+ upperCutPct?: number;+ lowerRateThreshold?: number;+ lowerIncreasePct?: number;+};++export type MonteCarloSpendingPhaseMeta = {+ id: string;+ name?: string;+ /**+ * Age the phase begins (inclusive). Null/absent = starts immediately;+ * only meaningful on the first phase.+ */+ fromAge?: number | null;+ /** Yearly spending in minor units, in today's money */+ annualWithdrawal?: number;+};++export type MonteCarloPotMeta = {+ id: string;+ name?: string;+ startingBalance?: number; // integer minor units (cents)+ allocationPreset?: MonteCarloAllocationPreset;+ expectedReturnMean?: number; // decimal fraction (0.06 = 6%)+ returnStdDev?: number; // decimal fraction+ /** Age from which the pot can fund withdrawals; null = immediately */+ accessAge?: number | null;+ /**+ * Account whose live balance supplies the starting balance;+ * null/undefined = manually entered balance+ */+ accountId?: string | null;+ /**+ * Flat tax model: effective tax rate on withdrawals from this pot as a+ * decimal fraction (0.15 = 15%)+ */+ withdrawalTaxRate?: number;+ /**+ * Bands tax model: share of a withdrawal that counts as taxable income+ * (pension ~0.75, tax-free account 0), as a decimal fraction+ */+ taxableFraction?: number;+ /** Fixed yearly fee in minor units, today's money */+ annualFeeFixed?: number;+ /** Whether the fixed fee rises with inflation */+ feeAdjustsWithInflation?: boolean;+ /** Yearly fee as a fraction of the end-of-year balance (0.0022 = 0.22%) */+ annualFeeRate?: number;+};++export type MonteCarloTaxModel = 'flat' | 'bands';++/** One tax band: income from `from` upward taxed at `rate` */+export type MonteCarloTaxBandMeta = {+ id: string;+ /** Annual taxable income threshold in minor units, today's money */+ from?: number;+ /** Decimal fraction (0.2 = 20%) */+ rate?: number;+};++export type MonteCarloWidget = AbstractWidget<+ 'monte-carlo-card',+ {+ name?: string;+ pots?: MonteCarloPotMeta[];+ withdrawalStrategy?: MonteCarloWithdrawalStrategy;+ returnModel?: MonteCarloReturnModel;+ withdrawalRule?: MonteCarloWithdrawalRuleMeta;+ /** Minimum annual withdrawal in minor units; 0 or absent = no floor */+ minimumWithdrawal?: number;+ spendingPhases?: MonteCarloSpendingPhaseMeta[];+ /** Mean yearly inflation as a decimal fraction; null = flat withdrawals */+ inflationMean?: number | null;+ /** Yearly inflation volatility as a decimal fraction; 0 = fixed rate */+ inflationStdDev?: number;+ /** How withdrawals are taxed; absent = 'flat' */+ taxModel?: MonteCarloTaxModel;+ /** Bands model: progressive tax bands over annual taxable income */+ taxBands?: MonteCarloTaxBandMeta[];+ currentAge?: number;+ /** Age the pot must last to; the horizon is targetAge - currentAge */+ targetAge?: number;+ simulationCount?: number;+ } | null+>;+export type AgeOfMoneyGranularity = 'daily' | 'weekly' | 'monthly';export type AgeOfMoneyWidget = AbstractWidget<@@ -142,6 +272,7 @@ type SpecializedWidget =| BudgetAnalysisWidget| CrossoverWidget| MarkdownWidget+ | MonteCarloWidget| SummaryWidget| CalendarWidget| FormulaWidgetdiff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.tsindex 0275589a4f..fc11e449f7 100644--- a/packages/loot-core/src/types/prefs.ts+++ b/packages/loot-core/src/types/prefs.ts@@ -10,7 +10,8 @@ export type FeatureFlag =| 'enableBanking'| 'sankeyReport'| 'akahuBankSync'- | 'mobileCalculator';+ | 'mobileCalculator'+ | 'monteCarloReport';/*** Cross-device preferences. These sync across devices when they are changed.diff --git a/upcoming-release-notes/add-monte-carlo-report.md b/upcoming-release-notes/add-monte-carlo-report.mdnew file mode 100644index 0000000000..e6ba4604cf--- /dev/null+++ b/upcoming-release-notes/add-monte-carlo-report.md@@ -0,0 +1,6 @@+---+category: Features+authors: [MikesGlitch]+---++Add experimental Monte Carlo analysis report that estimates how long your savings will last in retirement