A local-first personal finance app
:chart_with_upwards_trend: Monte carlo investment phases (#9233)
Michael Clark8d59f30cfb36
diff --git a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.tsindex 5e26b92bda..f9f50bed1a 100644--- a/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts+++ b/packages/desktop-client/src/components/reports/graphs/util/monteCarloCashflowChart.test.ts@@ -37,6 +37,7 @@ function makePot(id: string, name = ''): MonteCarloPot {feeAdjustsWithInflation: false,annualFeeRate: 0,isSurplus: false,+ investmentPhases: [],};}diff --git a/packages/desktop-client/src/components/reports/graphs/util/monteCarloPotBalancesChart.test.ts b/packages/desktop-client/src/components/reports/graphs/util/monteCarloPotBalancesChart.test.tsindex 43a628e1f1..8666ea694d 100644--- a/packages/desktop-client/src/components/reports/graphs/util/monteCarloPotBalancesChart.test.ts+++ b/packages/desktop-client/src/components/reports/graphs/util/monteCarloPotBalancesChart.test.ts@@ -35,6 +35,7 @@ function makePot(id: string, name = '', isSurplus = false): MonteCarloPot {feeAdjustsWithInflation: false,annualFeeRate: 0,isSurplus,+ investmentPhases: [],};}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsxindex d36cd9cbf0..d15b4bc560 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloConfiguration.tsx@@ -646,6 +646,8 @@ export function MonteCarloConfiguration({// The surplus pot is managed by the Manage surplus togglecanRemove={ordinaryPotCount > 1 && !pot.isSurplus}usesHistoricalReturns={config.returnModel !== 'normal'}+ currentAge={config.currentAge}+ targetAge={config.targetAge}usesTaxBands={config.taxModel === 'bands'}onPotChange={changes => onPotChange(pot.id, changes)}onRemove={() =>diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloInvestmentPhaseRow.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloInvestmentPhaseRow.tsxnew file mode 100644index 0000000000..fdb4a2f74f--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloInvestmentPhaseRow.tsx@@ -0,0 +1,349 @@+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+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,+ MonteCarloInvestmentTransition,+} from '@actual-app/core/types/models';++import { FinancialText } from '#components/FinancialText';+import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';+import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';+import {+ getAllocationChange,+ getHistoricalMixStats,+ getMixShareTotal,+ getPotAssetWeights,+ isMixIncomplete,+ MAX_AMOUNT,+ MAX_ANNUAL_FEE_RATE,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type { MonteCarloInvestmentPhase } 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';++type MonteCarloInvestmentPhaseRowProps = {+ phase: MonteCarloInvestmentPhase;+ /** The plan's ages, bounding the from-age */+ currentAge: number;+ targetAge: number;+ /** True when a historical return model is active */+ usesHistoricalReturns: boolean;+ onPhaseChange: (changes: Partial<MonteCarloInvestmentPhase>) => void;+ onRemove: () => void;+};++/**+ * One investment phase of a pot: from a given age, the allocation (or+ * hand-typed return and volatility) and fees the pot switches or glides+ * to. Mirrors the pot row's own controls.+ */+export function MonteCarloInvestmentPhaseRow({+ phase,+ currentAge,+ targetAge,+ usesHistoricalReturns,+ onPhaseChange,+ onRemove,+}: MonteCarloInvestmentPhaseRowProps) {+ const { t } = useTranslation();++ // As on the pot row: a mix under a historical model shows its measured+ // history rather than editable assumptions+ const assetWeights = usesHistoricalReturns ? getPotAssetWeights(phase) : null;+ const historicalMixStats =+ assetWeights != null ? getHistoricalMixStats(assetWeights) : null;+ const mixIsIncomplete = isMixIncomplete(phase);++ return (+ <View+ style={{+ gap: 10,+ paddingTop: 10,+ borderTop: `1px solid ${theme.tableBorder}`,+ }}+ >+ <View+ style={{+ flexDirection: 'row',+ flexWrap: 'wrap',+ alignItems: 'flex-end',+ gap: 20,+ }}+ >+ <View style={{ width: 110 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>From age</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={phase.fromAge}+ aria-label={t('From age')}+ roundToInteger+ min={currentAge + 1}+ max={targetAge}+ step={1}+ onCommit={newValue =>+ onPhaseChange({ fromAge: newValue ?? currentAge + 1 })+ }+ />+ </View>++ <View style={{ width: 250 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Transition</Trans>+ </Text>+ </View>+ <Select+ value={phase.transition}+ onChange={value =>+ onPhaseChange({+ transition: value as MonteCarloInvestmentTransition,+ })+ }+ options={[+ ['at-once', t('At once')],+ ['gradual', t('Gradually from the previous phase')],+ ]}+ />+ </View>++ <View style={{ width: 210 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Portfolio allocation</Trans>+ </Text>+ </View>+ <Select+ value={phase.allocationPreset}+ onChange={value =>+ onPhaseChange(+ getAllocationChange(value as MonteCarloAllocationPreset, phase),+ )+ }+ 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-mix', t('Custom mix')],+ ['custom', t('Custom')],+ ]}+ />+ </View>++ <View style={{ width: 130 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Expected return (%)</Trans>+ </Text>+ </View>+ {historicalMixStats != null ? (+ <Text style={{ color: theme.tableText, paddingBottom: 6 }}>+ <FinancialText as="span">+ {t('{{value}} (historical)', {+ value: `${(historicalMixStats.mean * 100).toFixed(1)}%`,+ })}+ </FinancialText>+ </Text>+ ) : (+ <MonteCarloNumberInput+ value={phase.expectedReturnMean}+ aria-label={t('Expected return (%)')}+ scale={100}+ min={-100}+ max={100}+ onCommit={newValue =>+ onPhaseChange({+ expectedReturnMean: newValue ?? 0,+ allocationPreset:+ phase.allocationPreset === 'custom-mix'+ ? 'custom-mix'+ : 'custom',+ })+ }+ />+ )}+ </View>++ <View style={{ width: 130 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Volatility (%)</Trans>+ </Text>+ </View>+ {historicalMixStats != null ? (+ <Text style={{ color: theme.tableText, paddingBottom: 6 }}>+ <FinancialText as="span">+ {t('{{value}} (historical)', {+ value: `${(historicalMixStats.stdDev * 100).toFixed(1)}%`,+ })}+ </FinancialText>+ </Text>+ ) : (+ <MonteCarloNumberInput+ value={phase.returnStdDev}+ aria-label={t('Volatility (std dev %)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPhaseChange({+ returnStdDev: newValue ?? 0,+ allocationPreset:+ phase.allocationPreset === 'custom-mix'+ ? 'custom-mix'+ : 'custom',+ })+ }+ />+ )}+ </View>++ <View style={{ width: 140 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Fixed yearly fee</Trans>+ </Text>+ </View>+ <FinancialInput+ value={phase.annualFeeFixed}+ onUpdate={value =>+ onPhaseChange({+ annualFeeFixed: Math.min(MAX_AMOUNT, Math.max(0, value)),+ })+ }+ />+ </View>++ <LabeledCheckbox+ id={`investment-phase-fee-inflation-${phase.id}`}+ checked={phase.feeAdjustsWithInflation}+ onChange={event =>+ onPhaseChange({ feeAdjustsWithInflation: event.target.checked })+ }+ style={{ flex: 'unset', paddingBottom: 6 }}+ >+ <Trans>Adjust by inflation</Trans>+ </LabeledCheckbox>++ <View style={{ width: 130 }}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Fee (% of balance)</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={phase.annualFeeRate}+ aria-label={t('Fee (% of balance)')}+ scale={100}+ min={0}+ max={MAX_ANNUAL_FEE_RATE * 100}+ step={0.01}+ onCommit={newValue =>+ onPhaseChange({ annualFeeRate: newValue ?? 0 })+ }+ />+ </View>++ <Button+ variant="bare"+ aria-label={t('Remove investment phase')}+ onPress={onRemove}+ style={{ padding: 6, marginBottom: 2 }}+ >+ <SvgDelete width={10} height={10} />+ </Button>+ </View>++ {phase.allocationPreset === 'custom-mix' && (+ <View style={{ gap: 10 }}>+ <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>Stocks (%)</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={phase.allocationStocks}+ aria-label={t('Stocks (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPhaseChange({ allocationStocks: newValue ?? 0 })+ }+ />+ </View>+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Bonds (%)</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={phase.allocationBonds}+ aria-label={t('Bonds (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPhaseChange({ allocationBonds: newValue ?? 0 })+ }+ />+ </View>+ <View style={FIELD_STYLE}>+ <View style={FIELD_LABEL_ROW_STYLE}>+ <Text style={FIELD_LABEL_STYLE}>+ <Trans>Cash (%)</Trans>+ </Text>+ </View>+ <MonteCarloNumberInput+ value={phase.allocationCash}+ aria-label={t('Cash (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPhaseChange({ allocationCash: newValue ?? 0 })+ }+ />+ </View>+ </View>+ {mixIsIncomplete && (+ <Text style={{ color: theme.errorText }}>+ <Trans>+ The allocation must total 100% - currently{' '}+ {{+ total: `${parseFloat((getMixShareTotal(phase) * 100).toFixed(2))}%`,+ }}+ . Until it does, this phase uses its expected return and+ volatility instead of the mix.+ </Trans>+ </Text>+ )}+ </View>+ )}+ </View>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsxindex cee922d2f7..021369e96b 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotConfiguration.tsx@@ -6,6 +6,7 @@ import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';import { SvgDelete } from '@actual-app/components/icons/v0';import {+ SvgAdd,SvgCheveronDown,SvgCheveronRight,} from '@actual-app/components/icons/v1';@@ -16,21 +17,30 @@ 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 { v4 as uuidv4 } from 'uuid';import { FinancialText } from '#components/FinancialText';import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';+import { MonteCarloInvestmentPhaseRow } from '#components/reports/reports/monte-carlo/MonteCarloInvestmentPhaseRow';import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';import { POT_COLUMNS } from '#components/reports/reports/monte-carlo/MonteCarloPotsTableHeader';import {- ALLOCATION_PRESETS,+ createMonteCarloInvestmentPhase,+ getAllocationChange,getHistoricalMixStats,+ getMixShareTotal,getPotAssetWeights,+ isMixIncomplete,MAX_AMOUNT,MAX_ANNUAL_FEE_RATE,MAX_WITHDRAWAL_TAX_RATE,+ resolveInvestmentPhases,+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';+import type {+ MonteCarloInvestmentPhase,+ MonteCarloPot,} 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,@@ -53,6 +63,9 @@ type MonteCarloPotConfigurationProps = ComponentPropsWithoutRef<usesHistoricalReturns: boolean;/** True when the bands tax model is active */usesTaxBands: boolean;+ /** The plan's ages, bounding the investment phases' from-ages */+ currentAge: number;+ targetAge: number;onPotChange: (changes: Partial<MonteCarloPot>) => void;onRemove: () => void;};@@ -63,6 +76,8 @@ export function MonteCarloPotConfiguration({canRemove,usesHistoricalReturns,usesTaxBands,+ currentAge,+ targetAge,onPotChange,onRemove,...props@@ -82,15 +97,41 @@ export function MonteCarloPotConfiguration({// A custom mix only counts once its shares total 100% (matching// getPotAssetWeights, tolerance included); until then the pot falls// back to its manual return/volatility and the UI warns- const sanitizeShare = (share: number) =>- Number.isFinite(share) && share > 0 ? share : 0;- const mixShareTotal =- sanitizeShare(pot.allocationStocks) +- sanitizeShare(pot.allocationBonds) +- sanitizeShare(pot.allocationCash);- const isMixIncomplete =- pot.allocationPreset === 'custom-mix' &&- Math.abs(mixShareTotal - 1) >= 1e-9;+ const mixShareTotal = getMixShareTotal(pot);+ const mixIsIncomplete = isMixIncomplete(pot);++ function updateInvestmentPhase(+ phaseId: string,+ changes: Partial<MonteCarloInvestmentPhase>,+ ) {+ onPotChange({+ investmentPhases: pot.investmentPhases.map(phase =>+ phase.id === phaseId ? { ...phase, ...changes } : phase,+ ),+ });+ }++ // Once a phase starts at the plan's end there is nowhere later to put+ // another one+ const sortedPhases = resolveInvestmentPhases(pot, currentAge);+ const latestPhase = sortedPhases[sortedPhases.length - 1];+ const canAddInvestmentPhase =+ latestPhase == null || latestPhase.fromAge < targetAge;++ function addInvestmentPhase() {+ // Start from the latest phase so only the differences need typing,+ // ten years on (or at the plan's end if that's sooner)+ const fromAge = Math.min(+ targetAge,+ (latestPhase?.fromAge ?? currentAge) + 10,+ );+ onPotChange({+ investmentPhases: [+ ...pot.investmentPhases,+ createMonteCarloInvestmentPhase(uuidv4(), latestPhase ?? pot, fromAge),+ ],+ });+ }// 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@@ -350,31 +391,9 @@ export function MonteCarloPotConfiguration({value={pot.allocationPreset}onChange={value => {const preset = value as MonteCarloAllocationPreset;- if (preset === 'custom') {- onPotChange({ allocationPreset: preset });- } else if (preset === 'custom-mix') {- // Seed the mix from the preset being left, so tweaking- // a preset (e.g. 80/20 to 85/15) starts from its shares- const presetWeights =- pot.allocationPreset !== 'custom-mix'- ? getPotAssetWeights(pot)- : null;- onPotChange({- allocationPreset: preset,- ...(presetWeights != null && {- allocationStocks: presetWeights.stocks,- allocationBonds: presetWeights.bonds,- allocationCash: presetWeights.cash,- }),- });- // The mix's share inputs live in the expanded panel+ onPotChange(getAllocationChange(preset, pot));+ if (preset === 'custom-mix') {setIsExpanded(true);- } else {- onPotChange({- allocationPreset: preset,- expectedReturnMean: ALLOCATION_PRESETS[preset].mean,- returnStdDev: ALLOCATION_PRESETS[preset].stdDev,- });}}}options={[@@ -572,7 +591,7 @@ export function MonteCarloPotConfiguration({/></View></View>- {isMixIncomplete && (+ {mixIsIncomplete && (// width 0 keeps the message from widening the group (it// would push the other groups aside); minWidth stretches// it back to the share inputs' width, wrapping the text@@ -761,6 +780,61 @@ export function MonteCarloPotConfiguration({</View></View></View>++ <View style={{ gap: 10, flexBasis: '100%' }}>+ <View+ style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}+ >+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Investment phases</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ Change what this pot is invested in - its allocation or return+ and volatility, and its fees - from a given age. The settings+ above apply until the first phase begins.+ <br />+ <br />+ At once switches on that birthday. Gradually moves there in a+ straight line from the previous phase's start age,+ arriving at the age you set - the classic glide path, such as+ 60% stocks / 40% bonds by 65. The cost of switching+ investments isn't modelled.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <Text style={{ color: theme.pageText }}>+ <Trans>From now: the settings above.</Trans>+ </Text>+ {resolveInvestmentPhases(pot, -Infinity).map(phase => (+ <MonteCarloInvestmentPhaseRow+ key={phase.id}+ phase={phase}+ currentAge={currentAge}+ targetAge={targetAge}+ usesHistoricalReturns={usesHistoricalReturns}+ onPhaseChange={changes =>+ updateInvestmentPhase(phase.id, changes)+ }+ onRemove={() =>+ onPotChange({+ investmentPhases: pot.investmentPhases.filter(+ other => other.id !== phase.id,+ ),+ })+ }+ />+ ))}+ <Button+ variant="bare"+ isDisabled={!canAddInvestmentPhase}+ onPress={addInvestmentPhase}+ style={{ alignSelf: 'flex-start' }}+ >+ <SvgAdd width={10} height={10} style={{ marginRight: 5 }} />+ <Trans>Add investment phase</Trans>+ </Button>+ </View></View>)}</GridListItem>diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsxindex a84f8af188..dfb9dbc5a1 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloRunDetailTable.tsx@@ -20,6 +20,7 @@ import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/Mimport {getMonteCarloPotLabel,getMonteCarloSurplusPotLabel,+ getPotInvestmentAtAge,} from '#components/reports/reports/monte-carlo/monteCarloSimulation';import type {MonteCarloIncomeStream,@@ -94,6 +95,38 @@ export function MonteCarloRunDetailTable({const hasIncome = incomeStreams.length > 0;const surplusPotName = getMonteCarloSurplusPotLabel(pots, t);const hasSurplusPot = pots.some(pot => pot.isSurplus);+ // Only worth a column when something changes over the plan+ const hasInvestmentPhases = pots.some(pot => pot.investmentPhases.length > 0);++ // "72% stocks, 28% bonds" for a mix (only the parts the pot holds), or+ // the return a mix-less pot draws around, in the year of the given age+ function getAllocationText(pot: MonteCarloPot, age: number) {+ const investment = getPotInvestmentAtAge(pot, startAge, age);+ if (investment.weights == null) {+ return t('Custom, {{mean}} return', {+ mean: `${(investment.mean * 100).toFixed(1)}%`,+ });+ }+ const percent = (share: number) => Math.round(share * 100);+ const parts: string[] = [];+ if (percent(investment.weights.stocks) > 0) {+ parts.push(+ t('{{share}}% stocks', { share: percent(investment.weights.stocks) }),+ );+ }+ if (percent(investment.weights.bonds) > 0) {+ parts.push(+ t('{{share}}% bonds', { share: percent(investment.weights.bonds) }),+ );+ }+ if (percent(investment.weights.cash) > 0) {+ parts.push(+ t('{{share}}% cash', { share: percent(investment.weights.cash) }),+ );+ }+ return parts.join(', ');+ }+const lastRow = rows[rows.length - 1];const hasSurvived = lastRow != null && lastRow.endBalance > 0;// Present whenever the plan has inflation enabled@@ -890,7 +923,9 @@ export function MonteCarloRunDetailTable({<Viewstyle={{marginTop: 14,- maxWidth: hasContributions ? 1150 : 1010,+ maxWidth:+ (hasContributions ? 1150 : 1010) ++ (hasInvestmentPhases ? 170 : 0),}}><View@@ -910,6 +945,27 @@ export function MonteCarloRunDetailTable({><Trans>Pot</Trans></Text>+ {hasInvestmentPhases && (+ <View+ style={{+ width: 160,+ flexShrink: 0,+ flexDirection: 'row',+ alignItems: 'center',+ gap: 4,+ }}+ >+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Allocation</Trans>+ </Text>+ <MonteCarloHelpTooltip placement="bottom start">+ <Trans>+ What the pot was invested in that year,+ following its investment phases.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ )}<Textstyle={{...GROUP_HEADING_STYLE,@@ -1043,6 +1099,14 @@ export function MonteCarloRunDetailTable({<Text style={{ flex: 1, minWidth: 120 }}>{getMonteCarloPotLabel(pots, potIndex, t)}</Text>+ {hasInvestmentPhases && (+ <Text style={{ width: 160, flexShrink: 0 }}>+ {getAllocationText(+ pot,+ startAge + row.year - 1,+ )}+ </Text>+ )}<Text style={{ ...POT_CELL_STYLE, width: 130 }}><PrivacyFilter><FinancialText as="span">diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.tsindex 2e246b5713..46e02c091c 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.test.ts@@ -1,11 +1,14 @@import { describe, expect, it } from 'vitest';import {+ ALLOCATION_PRESETS,+ createMonteCarloInvestmentPhase,getHistoricalMixStats,getHistoricalPresetStats,getMonteCarloHorizonYears,getMonteCarloPotLabel,getPotAssetWeights,+ getPotInvestmentAtAge,MAX_AMOUNT,MAX_HORIZON_YEARS,MIN_HORIZON_YEARS,@@ -18,6 +21,7 @@ import {import type {MonteCarloContribution,MonteCarloIncomeStream,+ MonteCarloInvestmentPhase,MonteCarloParams,MonteCarloPot,} from './monteCarloSimulation';@@ -74,6 +78,7 @@ function makePot(overrides: Partial<MonteCarloPot> = {}): MonteCarloPot {feeAdjustsWithInflation: false,annualFeeRate: 0,isSurplus: false,+ investmentPhases: [],...overrides,};}@@ -148,6 +153,27 @@ describe('surplus pot defaults', () => {});});+ it('drops saved investment phases that have no start age', () => {+ const config = monteCarloConfigFromMeta({+ pots: [+ {+ id: 'saved-pot',+ allocationPreset: 'equity-100',+ investmentPhases: [+ { id: 'no-age', allocationPreset: 'cash' },+ { id: 'at-70', fromAge: 70, allocationPreset: 'cash' },+ ],+ },+ ],+ });+ const [pot] = config.pots;+ expect(pot.investmentPhases.map(phase => phase.id)).toEqual(['at-70']);+ // The pot's own allocation still applies before the first phase+ expect(getPotInvestmentAtAge(pot, 52, 60).weights).toEqual(+ getPotAssetWeights(pot),+ );+ });+it('keeps saved plans without a surplus pot unchanged', () => {const config = monteCarloConfigFromMeta({pots: [{ id: 'saved-pot', startingBalance: 500_000 }],@@ -3510,6 +3536,284 @@ describe('runMonteCarloSimulation', () => {});});+describe('investment phases', () => {+ // makePot keeps its own 6% mean whatever the preset; these tests want+ // the preset's illustrative numbers so the glide arithmetic is readable+ const stocksPot = makePot({+ allocationPreset: 'equity-100',+ expectedReturnMean: ALLOCATION_PRESETS['equity-100'].mean,+ returnStdDev: ALLOCATION_PRESETS['equity-100'].stdDev,+ });+ const flatHistory = [+ { year: 2000, stocks: 0.1, bonds: 0, cash: 0, inflation: 0 },+ ];++ function phase(+ overrides: Partial<MonteCarloInvestmentPhase> & { fromAge: number },+ ): MonteCarloInvestmentPhase {+ return {+ ...createMonteCarloInvestmentPhase('phase', stocksPot, overrides.fromAge),+ ...overrides,+ };+ }++ describe('getPotInvestmentAtAge', () => {+ it('is the pot itself when it has no phases', () => {+ const investment = getPotInvestmentAtAge(stocksPot, 60, 75);+ expect(investment.weights).toEqual({ stocks: 1, bonds: 0, cash: 0 });+ expect(investment.mean).toBe(ALLOCATION_PRESETS['equity-100'].mean);+ expect(investment.feeRate).toBe(0);+ });++ it('switches at once on the phase birthday', () => {+ const pot = makePot({+ allocationPreset: 'equity-100',+ investmentPhases: [+ phase({ fromAge: 65, allocationPreset: 'cash', annualFeeRate: 0.01 }),+ ],+ });+ expect(getPotInvestmentAtAge(pot, 60, 64).weights).toEqual({+ stocks: 1,+ bonds: 0,+ cash: 0,+ });+ expect(getPotInvestmentAtAge(pot, 60, 64).feeRate).toBe(0);+ expect(getPotInvestmentAtAge(pot, 60, 65).weights).toEqual({+ stocks: 0,+ bonds: 0,+ cash: 1,+ });+ expect(getPotInvestmentAtAge(pot, 60, 65).feeRate).toBe(0.01);+ });++ it('glides in a straight line from the previous start age to the phase age', () => {+ // 100% stocks now, 60/40 by 70: a 4% shift a year from age 60+ const pot = makePot({+ allocationPreset: 'equity-100',+ expectedReturnMean: 0.07,+ investmentPhases: [+ phase({+ fromAge: 70,+ transition: 'gradual',+ allocationPreset: 'equity-60',+ expectedReturnMean: ALLOCATION_PRESETS['equity-60'].mean,+ }),+ ],+ });+ expect(getPotInvestmentAtAge(pot, 60, 60).weights).toEqual({+ stocks: 1,+ bonds: 0,+ cash: 0,+ });+ const halfway = getPotInvestmentAtAge(pot, 60, 65);+ expect(halfway.weights!.stocks).toBeCloseTo(0.8, 10);+ expect(halfway.weights!.bonds).toBeCloseTo(0.2, 10);+ expect(halfway.mean).toBeCloseTo(0.065, 10);+ expect(getPotInvestmentAtAge(pot, 60, 70).weights!.stocks).toBeCloseTo(+ 0.6,+ 10,+ );+ expect(getPotInvestmentAtAge(pot, 60, 80).weights!.stocks).toBeCloseTo(+ 0.6,+ 10,+ );+ });++ it('glides return and volatility, without a mix, to or from a hand-typed phase', () => {+ const pot = makePot({+ allocationPreset: 'equity-100',+ expectedReturnMean: 0.07,+ returnStdDev: 0.15,+ investmentPhases: [+ phase({+ fromAge: 70,+ transition: 'gradual',+ allocationPreset: 'custom',+ expectedReturnMean: 0.03,+ returnStdDev: 0.05,+ }),+ ],+ });+ const halfway = getPotInvestmentAtAge(pot, 60, 65);+ expect(halfway.weights).toBeNull();+ expect(halfway.mean).toBeCloseTo(0.05, 10);+ expect(halfway.stdDev).toBeCloseTo(0.1, 10);+ });++ it('treats phases already reached as the starting point', () => {+ const pot = makePot({+ allocationPreset: 'equity-100',+ investmentPhases: [+ phase({ fromAge: 55, allocationPreset: 'cash' }),+ phase({ fromAge: 60, allocationPreset: 'equity-40' }),+ ],+ });+ // Both phases lie at or before the current age of 60; the latest wins+ expect(getPotInvestmentAtAge(pot, 60, 60).weights).toEqual(+ getPotAssetWeights(makePot({ allocationPreset: 'equity-40' })),+ );+ expect(getPotInvestmentAtAge(pot, 60, 90).weights).toEqual(+ getPotAssetWeights(makePot({ allocationPreset: 'equity-40' })),+ );+ });++ it('orders phases by age however they were entered', () => {+ const pot = makePot({+ allocationPreset: 'equity-100',+ investmentPhases: [+ phase({ fromAge: 80, allocationPreset: 'cash' }),+ phase({ fromAge: 70, allocationPreset: 'equity-40' }),+ ],+ });+ expect(getPotInvestmentAtAge(pot, 60, 75).weights).toEqual(+ getPotAssetWeights(makePot({ allocationPreset: 'equity-40' })),+ );+ expect(getPotInvestmentAtAge(pot, 60, 85).weights).toEqual(+ getPotAssetWeights(makePot({ allocationPreset: 'cash' })),+ );+ });++ it('glides fees and keeps the earlier inflation setting until the switch', () => {+ const pot = makePot({+ annualFeeRate: 0,+ annualFeeFixed: 0,+ feeAdjustsWithInflation: false,+ investmentPhases: [+ phase({+ fromAge: 70,+ transition: 'gradual',+ annualFeeRate: 0.01,+ annualFeeFixed: 1_000,+ feeAdjustsWithInflation: true,+ }),+ ],+ });+ const halfway = getPotInvestmentAtAge(pot, 60, 65);+ expect(halfway.feeRate).toBeCloseTo(0.005, 10);+ expect(halfway.feeFixed).toBe(500);+ expect(halfway.feeAdjusts).toBe(false);+ expect(getPotInvestmentAtAge(pot, 60, 70).feeAdjusts).toBe(true);+ });+ });++ describe('in the engine', () => {+ it('applies an at-once switch from the phase year under a historical model', () => {+ // Stocks return 10% every year, cash 0%: growth stops at the switch+ const result = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-sequence',+ historicalReturns: flatHistory,+ inflationMean: null,+ currentAge: 60,+ annualWithdrawal: 0,+ horizonYears: 4,+ },+ {+ startingBalance: 100_000,+ allocationPreset: 'equity-100',+ investmentPhases: [+ phase({ fromAge: 62, allocationPreset: 'cash' }),+ ],+ },+ ),+ );+ expect(result.percentileBands.map(band => band.p50)).toEqual([+ 100_000, 110_000, 121_000, 121_000, 121_000,+ ]);+ });++ it('glides the blended return under a historical model', () => {+ // Halfway to cash at 61 the pot is half stocks: 5% that year+ const result = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-sequence',+ historicalReturns: flatHistory,+ inflationMean: null,+ currentAge: 60,+ annualWithdrawal: 0,+ horizonYears: 3,+ },+ {+ startingBalance: 100_000,+ allocationPreset: 'equity-100',+ investmentPhases: [+ phase({+ fromAge: 62,+ transition: 'gradual',+ allocationPreset: 'cash',+ }),+ ],+ },+ ),+ );+ expect(result.percentileBands.map(band => band.p50)).toEqual([+ 100_000, 110_000, 115_500, 115_500,+ ]);+ });++ it('switches the expected return under the random model', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ inflationMean: null,+ currentAge: 60,+ annualWithdrawal: 0,+ horizonYears: 4,+ },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ investmentPhases: [+ phase({+ fromAge: 62,+ allocationPreset: 'custom',+ expectedReturnMean: 0.02,+ returnStdDev: 0,+ }),+ ],+ },+ ),+ );+ expect(result.percentileBands.map(band => band.p50)).toEqual([+ 100_000, 105_000, 110_250, 112_455, 114_704,+ ]);+ });++ it('charges the phase fee from its year', () => {+ const result = runMonteCarloSimulation(+ makeParams(+ {+ inflationMean: null,+ currentAge: 60,+ annualWithdrawal: 0,+ horizonYears: 4,+ },+ {+ startingBalance: 100_000,+ expectedReturnMean: 0,+ returnStdDev: 0,+ investmentPhases: [+ phase({+ fromAge: 62,+ allocationPreset: 'custom',+ expectedReturnMean: 0,+ returnStdDev: 0,+ annualFeeRate: 0.1,+ }),+ ],+ },+ ),+ );+ expect(result.percentileBands.map(band => band.p50)).toEqual([+ 100_000, 100_000, 100_000, 90_000, 81_000,+ ]);+ });+ });+});+describe('getHistoricalPresetStats', () => {const history = [{ year: 2000, stocks: 0.1, bonds: 0.05, cash: 0.02, inflation: 0 },diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.tsindex 30a5bfb7f6..ae292bf201 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/monteCarloSimulation.ts@@ -3,6 +3,8 @@ import type {MonteCarloAllocationPreset,MonteCarloContributionMeta,MonteCarloIncomeStreamMeta,+ MonteCarloInvestmentPhaseMeta,+ MonteCarloInvestmentTransition,MonteCarloPotMeta,MonteCarloReturnModel,MonteCarloSpendingPhaseMeta,@@ -140,6 +142,194 @@ export function getHistoricalPresetStats(return stats;}+/**+ * The sum of a custom mix's shares as entered (invalid or negative shares+ * count as 0), for the editor's "must total 100%" check+ */+export function getMixShareTotal(+ fields: Pick<+ MonteCarloInvestmentFields,+ 'allocationStocks' | 'allocationBonds' | 'allocationCash'+ >,+): number {+ const sanitize = (share: number) =>+ Number.isFinite(share) && share > 0 ? share : 0;+ return (+ sanitize(fields.allocationStocks) ++ sanitize(fields.allocationBonds) ++ sanitize(fields.allocationCash)+ );+}++/** True for a custom mix whose shares don't total 100% (float dust allowed) */+export function isMixIncomplete(+ fields: Pick<+ MonteCarloInvestmentFields,+ | 'allocationPreset'+ | 'allocationStocks'+ | 'allocationBonds'+ | 'allocationCash'+ >,+): boolean {+ return (+ fields.allocationPreset === 'custom-mix' &&+ Math.abs(getMixShareTotal(fields) - 1) >= 1e-9+ );+}++/**+ * The field changes the editor applies when an allocation is picked: a+ * preset fills in its illustrative return and volatility, a custom mix is+ * seeded with the shares of the mix being left, and Custom keeps the+ * typed numbers+ */+export function getAllocationChange(+ preset: MonteCarloAllocationPreset,+ current: MonteCarloInvestmentFields,+): Partial<MonteCarloInvestmentFields> {+ if (preset === 'custom') {+ return { allocationPreset: preset };+ }+ if (preset === 'custom-mix') {+ const presetWeights =+ current.allocationPreset !== 'custom-mix'+ ? getPotAssetWeights(current)+ : null;+ return {+ allocationPreset: preset,+ ...(presetWeights != null && {+ allocationStocks: presetWeights.stocks,+ allocationBonds: presetWeights.bonds,+ allocationCash: presetWeights.cash,+ }),+ };+ }+ return {+ allocationPreset: preset,+ expectedReturnMean: ALLOCATION_PRESETS[preset].mean,+ returnStdDev: ALLOCATION_PRESETS[preset].stdDev,+ };+}++/** What a pot is invested in, and what it costs, in one simulated year */+export type MonteCarloPotInvestment = {+ /** Asset mix for the historical models; null = normal draws */+ weights: MonteCarloAssetWeights | null;+ mean: number;+ stdDev: number;+ feeRate: number;+ feeFixed: number;+ feeAdjusts: boolean;+};++function getInvestment(+ fields: MonteCarloInvestmentFields,+): MonteCarloPotInvestment {+ return {+ weights: getPotAssetWeights(fields),+ mean: fields.expectedReturnMean,+ stdDev: Math.max(0, fields.returnStdDev),+ feeRate: clamp(fields.annualFeeRate ?? 0, 0, MAX_ANNUAL_FEE_RATE),+ feeFixed: clamp(fields.annualFeeFixed ?? 0, 0, MAX_AMOUNT),+ feeAdjusts: fields.feeAdjustsWithInflation ?? false,+ };+}++function lerp(from: number, to: number, fraction: number) {+ return from + (to - from) * fraction;+}++// A straight-line blend between two investments. The mix only glides+// when both ends have one; a glide to or from a hand-typed pot falls back+// to normal draws around the blended return and volatility+function lerpInvestment(+ from: MonteCarloPotInvestment,+ to: MonteCarloPotInvestment,+ fraction: number,+): MonteCarloPotInvestment {+ return {+ weights:+ from.weights != null && to.weights != null+ ? {+ stocks: lerp(from.weights.stocks, to.weights.stocks, fraction),+ bonds: lerp(from.weights.bonds, to.weights.bonds, fraction),+ cash: lerp(from.weights.cash, to.weights.cash, fraction),+ }+ : null,+ mean: lerp(from.mean, to.mean, fraction),+ stdDev: lerp(from.stdDev, to.stdDev, fraction),+ feeRate: lerp(from.feeRate, to.feeRate, fraction),+ feeFixed: lerp(from.feeFixed, to.feeFixed, fraction),+ feeAdjusts: from.feeAdjusts,+ };+}++/**+ * The pot's investment phases that still lie ahead, sorted by age.+ * Phases already reached (from-age at or below the current age) are not+ * ahead; the latest of them is the pot's starting point instead+ */+export function resolveInvestmentPhases(+ pot: Pick<MonteCarloPot, 'investmentPhases'>,+ currentAge: number,+): MonteCarloInvestmentPhase[] {+ return pot.investmentPhases+ .filter(+ phase => Number.isFinite(phase.fromAge) && phase.fromAge > currentAge,+ )+ .sort((phaseA, phaseB) => phaseA.fromAge - phaseB.fromAge);+}++/**+ * What a pot is invested in at a given age. The pot's own fields apply+ * from the current age (or the latest phase the user has already passed),+ * each later phase takes over at its from-age, and a 'gradual' phase is+ * approached in a straight line from the previous phase's start age so it+ * is fully in place at its own from-age. The engine builds its per-year+ * tables from this and the run detail reads it directly, so the two+ * can't disagree+ */+export function getPotInvestmentAtAge(+ pot: MonteCarloPot,+ currentAge: number,+ age: number,+): MonteCarloPotInvestment {+ const reached = pot.investmentPhases+ .filter(+ phase => Number.isFinite(phase.fromAge) && phase.fromAge <= currentAge,+ )+ .sort((phaseA, phaseB) => phaseA.fromAge - phaseB.fromAge);+ const base: MonteCarloInvestmentFields =+ reached.length > 0 ? reached[reached.length - 1] : pot;+ const phases = resolveInvestmentPhases(pot, currentAge);++ let activeIndex = -1;+ for (let index = 0; index < phases.length; index++) {+ if (phases[index].fromAge <= age) {+ activeIndex = index;+ } else {+ break;+ }+ }+ const active = getInvestment(activeIndex < 0 ? base : phases[activeIndex]);+ const activeStart =+ activeIndex < 0 ? currentAge : phases[activeIndex].fromAge;+ const next = phases[activeIndex + 1];+ if (+ next == null ||+ next.transition !== 'gradual' ||+ next.fromAge <= activeStart+ ) {+ return active;+ }+ const fraction = clamp(+ (age - activeStart) / (next.fromAge - activeStart),+ 0,+ 1,+ );+ return lerpInvestment(active, getInvestment(next), fraction);+}+/*** Money inputs above this are clamped (1e14 minor units = 1 trillion major* units); keeps even heavily compounded results within the range the@@ -326,6 +516,32 @@ export function createMonteCarloIncomeStream(}/** One invested pot with its own balance and return assumptions */+/** The fields that describe what a pot is invested in and what it costs */+export type MonteCarloInvestmentFields = Pick<+ MonteCarloPot,+ | 'allocationPreset'+ | 'allocationStocks'+ | 'allocationBonds'+ | 'allocationCash'+ | 'expectedReturnMean'+ | 'returnStdDev'+ | 'annualFeeFixed'+ | 'feeAdjustsWithInflation'+ | 'annualFeeRate'+>;++/**+ * A change to a pot's investment from a given age. The pot's own+ * investment fields apply until its first phase begins; see+ * getPotInvestmentAtAge for how phases and gradual transitions resolve+ */+export type MonteCarloInvestmentPhase = MonteCarloInvestmentFields & {+ id: string;+ /** Age the phase takes effect (inclusive) */+ fromAge: number;+ transition: MonteCarloInvestmentTransition;+};+export type MonteCarloPot = {id: string;name: string;@@ -363,8 +579,43 @@ export type MonteCarloPot = {* is flagged; none = unspent money leaves the plan.*/isSurplus: boolean;+ /** Later changes to the pot's investment, by age (any order) */+ investmentPhases: MonteCarloInvestmentPhase[];};+function pickInvestmentFields(+ source: MonteCarloInvestmentFields,+): MonteCarloInvestmentFields {+ return {+ allocationPreset: source.allocationPreset,+ allocationStocks: source.allocationStocks,+ allocationBonds: source.allocationBonds,+ allocationCash: source.allocationCash,+ expectedReturnMean: source.expectedReturnMean,+ returnStdDev: source.returnStdDev,+ annualFeeFixed: source.annualFeeFixed,+ feeAdjustsWithInflation: source.feeAdjustsWithInflation,+ annualFeeRate: source.annualFeeRate,+ };+}++/**+ * A new phase that starts as a copy of `source` (the pot, or the phase+ * before it), so the user only changes what differs+ */+export function createMonteCarloInvestmentPhase(+ id: string,+ source: MonteCarloInvestmentFields,+ fromAge: number,+): MonteCarloInvestmentPhase {+ return {+ ...pickInvestmentFields(source),+ id,+ fromAge,+ transition: 'at-once',+ };+}+export function createMonteCarloPot(id: string): MonteCarloPot {return {id,@@ -384,6 +635,7 @@ export function createMonteCarloPot(id: string): MonteCarloPot {feeAdjustsWithInflation: false,annualFeeRate: 0,isSurplus: false,+ investmentPhases: [],};}@@ -405,6 +657,7 @@ export function createMonteCarloSurplusPot(id: string): MonteCarloPot {withdrawalTaxRate: 0,taxableFraction: 0,isSurplus: true,+ investmentPhases: [],};}@@ -560,9 +813,39 @@ export function getMonteCarloHorizonYears();}+function hasStartAge(+ phaseMeta: MonteCarloInvestmentPhaseMeta,+): phaseMeta is MonteCarloInvestmentPhaseMeta & { fromAge: number } {+ return Number.isFinite(phaseMeta.fromAge);+}++function investmentPhaseFromMeta(+ phaseMeta: MonteCarloInvestmentPhaseMeta & { fromAge: number },+ pot: MonteCarloInvestmentFields,+ index: number,+): MonteCarloInvestmentPhase {+ // Missing fields fall back to the pot's own settings, so a phase that+ // only changes the allocation keeps the pot's fees+ return {+ id: phaseMeta.id || `phase-${index + 1}`,+ fromAge: phaseMeta.fromAge,+ transition: phaseMeta.transition ?? 'at-once',+ allocationPreset: phaseMeta.allocationPreset ?? pot.allocationPreset,+ allocationStocks: phaseMeta.allocationStocks ?? pot.allocationStocks,+ allocationBonds: phaseMeta.allocationBonds ?? pot.allocationBonds,+ allocationCash: phaseMeta.allocationCash ?? pot.allocationCash,+ expectedReturnMean: phaseMeta.expectedReturnMean ?? pot.expectedReturnMean,+ returnStdDev: phaseMeta.returnStdDev ?? pot.returnStdDev,+ annualFeeFixed: phaseMeta.annualFeeFixed ?? pot.annualFeeFixed,+ feeAdjustsWithInflation:+ phaseMeta.feeAdjustsWithInflation ?? pot.feeAdjustsWithInflation,+ annualFeeRate: phaseMeta.annualFeeRate ?? pot.annualFeeRate,+ };+}+function potFromMeta(potMeta: MonteCarloPotMeta, index: number): MonteCarloPot {const defaults = createMonteCarloPot(potMeta.id || `pot-${index + 1}`);- return {+ const pot: MonteCarloPot = {...defaults,name: potMeta.name ?? defaults.name,startingBalance: potMeta.startingBalance ?? defaults.startingBalance,@@ -583,6 +866,17 @@ function potFromMeta(potMeta: MonteCarloPotMeta, index: number): MonteCarloPot {annualFeeRate: potMeta.annualFeeRate ?? defaults.annualFeeRate,isSurplus: potMeta.isSurplus ?? defaults.isSurplus,};+ return {+ ...pot,+ // A phase without a start age can't be placed, so it is dropped rather+ // than treated as already reached, which would override the pot's own+ // settings+ investmentPhases: (potMeta.investmentPhases ?? [])+ .filter(hasStartAge)+ .map((phaseMeta, phaseIndex) =>+ investmentPhaseFromMeta(phaseMeta, pot, phaseIndex),+ ),+ };}function taxBandFromMeta(@@ -1022,8 +1316,6 @@ export function runMonteCarloSimulation(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';@@ -1090,17 +1382,6 @@ export function runMonteCarloSimulation(incomeTaxableFractions.some(fraction => fraction > 0): incomeTaxRates.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 sufficientconst maxTaxRate =@@ -1357,34 +1638,6 @@ export function runMonteCarloSimulation(: HISTORICAL_ANNUAL_RETURNS;const historyCount = history.length;- // For historical models, each pot with an asset mix (a preset's fixed- // mix, or a custom mix's own shares) gets the blended return of that mix- // in every historical year. Pots without one ('custom', or a custom mix- // whose shares sum to zero) keep using normal draws around their own- // mean/volatility.- const potHistoricalReturns: Array<Float64Array | null> = pots.map(pot => {- if (returnModel === 'normal') {- return null;- }- const weights = getPotAssetWeights(pot);- if (weights == null) {- return null;- }- 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;@@ -1394,6 +1647,60 @@ export function runMonteCarloSimulation(MAX_HORIZON_YEARS,);+ // --- Investment by year ------------------------------------------------+ // What each pot is invested in, and what it costs, in every simulated+ // year - the pot's own settings until its investment phases take over+ // (see getPotInvestmentAtAge). Historical models blend each year's real+ // returns by that year's asset mix; pots without a mix that year+ // ('custom', an incomplete custom mix, or a glide to or from one) draw+ // normally around that year's mean and volatility.+ const potWeightsByYear: Array<Array<MonteCarloAssetWeights | null>> = [];+ const potMeanByYear: Float64Array[] = [];+ const potStdDevByYear: Float64Array[] = [];+ const potFeeRateByYear: Float64Array[] = [];+ const potFeeFixedByYear: Float64Array[] = [];+ const potFeeAdjustsByYear: Uint8Array[] = [];+ // Whether any pot's return comes from a normal draw in that year (the+ // whole normal model, plus mix-less pots in historical modes); the+ // shared market shock is only drawn in such years+ const hasNormalDrawPotByYear = new Uint8Array(horizonYears + 1);+ let hasFees = false;+ for (let potIndex = 0; potIndex < potCount; potIndex++) {+ const weights: Array<MonteCarloAssetWeights | null> = new Array(+ horizonYears + 1,+ ).fill(null);+ const means = new Float64Array(horizonYears + 1);+ const stdDevs = new Float64Array(horizonYears + 1);+ const feeRates = new Float64Array(horizonYears + 1);+ const feeFixeds = new Float64Array(horizonYears + 1);+ const feeAdjusts = new Uint8Array(horizonYears + 1);+ for (let year = 1; year <= horizonYears; year++) {+ const investment = getPotInvestmentAtAge(+ pots[potIndex],+ params.currentAge,+ params.currentAge + year - 1,+ );+ weights[year] = returnModel === 'normal' ? null : investment.weights;+ if (weights[year] == null) {+ hasNormalDrawPotByYear[year] = 1;+ }+ means[year] = investment.mean;+ stdDevs[year] = investment.stdDev;+ feeRates[year] = investment.feeRate;+ feeFixeds[year] = investment.feeFixed;+ feeAdjusts[year] = investment.feeAdjusts ? 1 : 0;+ if (investment.feeRate > 0 || investment.feeFixed > 0) {+ hasFees = true;+ }+ }+ potWeightsByYear.push(weights);+ potMeanByYear.push(means);+ potStdDevByYear.push(stdDevs);+ potFeeRateByYear.push(feeRates);+ potFeeFixedByYear.push(feeFixeds);+ potFeeAdjustsByYear.push(feeAdjusts);+ }+// 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.@@ -2135,16 +2442,19 @@ export function runMonteCarloSimulation(potBalances[surplusPotIndex] += surplusSavedThisYear;}- const marketShock = hasNormalDrawPot ? nextNormal() : 0;+ const marketShock = hasNormalDrawPotByYear[year] ? nextNormal() : 0;total = 0;for (let potIndex = 0; potIndex < potCount; potIndex++) {if (potBalances[potIndex] > 0) {- const blended = potHistoricalReturns[potIndex];+ const weights = potWeightsByYear[potIndex][year];const yearReturn =- blended && historyIndex >= 0- ? blended[historyIndex]- : potMeans[potIndex] + potStdDevs[potIndex] * marketShock;+ weights != null && historyIndex >= 0+ ? weights.stocks * history[historyIndex].stocks ++ weights.bonds * history[historyIndex].bonds ++ weights.cash * history[historyIndex].cash+ : potMeanByYear[potIndex][year] ++ potStdDevByYear[potIndex][year] * marketShock;if (capturedPotReturns) {capturedPotReturns[potIndex] = yearReturn;}@@ -2189,9 +2499,9 @@ export function runMonteCarloSimulation(continue;}const fee =- potBalances[potIndex] * potFeeRates[potIndex] +- potFeeFixed[potIndex] *- (potFeeAdjusts[potIndex] ? cumulativeInflation : 1);+ potBalances[potIndex] * potFeeRateByYear[potIndex][year] ++ potFeeFixedByYear[potIndex][year] *+ (potFeeAdjustsByYear[potIndex][year] ? cumulativeInflation : 1);const charged = Math.min(potBalances[potIndex], fee);potBalances[potIndex] -= charged;feesThisYear += charged;diff --git a/packages/docs/docs/experimental/monte-carlo-analysis.md b/packages/docs/docs/experimental/monte-carlo-analysis.mdindex 88f3784479..fc922d57bd 100644--- a/packages/docs/docs/experimental/monte-carlo-analysis.md+++ b/packages/docs/docs/experimental/monte-carlo-analysis.md@@ -79,6 +79,7 @@ A _pot_ is a chunk of invested money - a pension or retirement account, an inves- **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.+- **Investment phases** - change what the pot is invested in, and what it costs, from a given age. The pot's own allocation, return, volatility and fees apply until the first phase begins; each phase sets a **From age** and its own allocation (a preset, a custom mix, or hand-typed return and volatility) and fees. **Transition** decides how the pot gets there: **At once** switches on that birthday, while **Gradually from the previous phase** moves in a straight line from the previous phase's start age and arrives at the age you set. That makes a glide path one row: a pot that is 100% stocks today with a phase of "60% stocks / 40% bonds, from age 65, gradually" shifts a little more into bonds every year and is at 60/40 on your 65th birthday. A later "Cash, at once, from 80" would then move the whole pot to cash at 80. Phases work with every return model - the historical models blend each year's real returns by that year's mix - and the run drill-in shows each pot's allocation year by year once a pot has phases. Switching investments is free in the simulation; any dealing costs or tax on the switch are not modelled.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).@@ -242,7 +243,7 @@ This bar chart only counts the replays that failed, showing at which age they ra<img width="1344" alt="The simulation runs table with the median run highlighted and the Jump to dropdown boxed" src="/img/experimental/monte-carlo-analysis/[email protected]" />-Switch the results view from **Chart** to **Runs** to see every replay listed from worst outcome to best. Rather than paging through thousands of runs, use the **Jump to** dropdown to go straight to the worst, median or best run - or the 25th/75th percentile for a typically-bad or typically-good outcome - with the run highlighted so you can click into it. Click any run to walk through it year by year: the balance at the start of each year, the contributions paid in (when your plan has any, including money saved into the Surplus cash pot), the net income received (when your plan has income streams), the withdrawal taken, what was actually spent (income and withdrawal together, net of tax - shown in red when it fell short of the plan), the investment growth in that year (as money and as a percentage), the year's inflation rate (when inflation is enabled), and the balance at the end. Expand a year with the arrow at the start of its row (or use **Expand all years**) and it opens with a short plain-English summary of what happened that year and why: any change the withdrawal rule made and what triggered it, whether the minimum spending floor stepped in, how the year's spending was funded (income, pots, or a shortfall), and where any money the plan didn't spend went. Below it sits the pot table described further down. Click **Show the working** for the fully labeled breakdown behind the summary: the income received, split into gross, tax and net (and per stream when you have several), with any unspent income called out; the withdrawal split into gross, tax and money to spend; how the year's spending compared with the plan (as planned, or short by an amount); when a withdrawal rule is active, a sentence showing how the rule arrived at that year's amount (and whether the minimum spending floor stepped in); the contributions added; the fees paid; and a small table showing each pot's balance at the start of the year, what was contributed into it (for the Surplus cash pot, the money saved into it that year), what it contributed to the withdrawal, how much of that counted as taxable income, the tax paid on its share, the fee it was charged that year, its return that year, and its ending balance - so you can watch, for example, the cash pot covering spending after a crash while the stock pots are left alone. With the tax-bands model, the per-pot tax is the year's tax bill shared out in proportion to each pot's taxable income.+Switch the results view from **Chart** to **Runs** to see every replay listed from worst outcome to best. Rather than paging through thousands of runs, use the **Jump to** dropdown to go straight to the worst, median or best run - or the 25th/75th percentile for a typically-bad or typically-good outcome - with the run highlighted so you can click into it. Click any run to walk through it year by year: the balance at the start of each year, the contributions paid in (when your plan has any, including money saved into the Surplus cash pot), the net income received (when your plan has income streams), the withdrawal taken, what was actually spent (income and withdrawal together, net of tax - shown in red when it fell short of the plan), the investment growth in that year (as money and as a percentage), the year's inflation rate (when inflation is enabled), and the balance at the end. Expand a year with the arrow at the start of its row (or use **Expand all years**) and it opens with a short plain-English summary of what happened that year and why: any change the withdrawal rule made and what triggered it, whether the minimum spending floor stepped in, how the year's spending was funded (income, pots, or a shortfall), and where any money the plan didn't spend went. Below it sits the pot table described further down. Click **Show the working** for the fully labeled breakdown behind the summary: the income received, split into gross, tax and net (and per stream when you have several), with any unspent income called out; the withdrawal split into gross, tax and money to spend; how the year's spending compared with the plan (as planned, or short by an amount); when a withdrawal rule is active, a sentence showing how the rule arrived at that year's amount (and whether the minimum spending floor stepped in); the contributions added; the fees paid; and a small table showing each pot's balance at the start of the year, what it was invested in that year (when a pot has investment phases), what was contributed into it (for the Surplus cash pot, the money saved into it that year), what it contributed to the withdrawal, how much of that counted as taxable income, the tax paid on its share, the fee it was charged that year, its return that year, and its ending balance - so you can watch, for example, the cash pot covering spending after a crash while the stock pots are left alone. With the tax-bands model, the per-pot tax is the year's tax bill shared out in proportion to each pot's taxable income.<img width="1344" alt="A single run with its cashflow chart, run summary and year-by-year table" src="/img/experimental/monte-carlo-analysis/[email protected]" />@@ -255,5 +256,6 @@ If a run failed while money was still locked in an inaccessible pot, the table s- **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.+- **Investment phases switch for free.** A pot that changes investments at an age, or glides between them, pays no dealing costs or tax on the switch. A gradual glide between hand-typed return and volatility figures moves both in a straight line, which slightly overstates the volatility of the in-between years.- **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/static/img/experimental/monte-carlo-analysis/[email protected] b/packages/docs/static/img/experimental/monte-carlo-analysis/[email protected]index 9c11646d22..29f8d6db6f 100644Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/[email protected] and b/packages/docs/static/img/experimental/monte-carlo-analysis/[email protected] differdiff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 0e468e033e..83e87dfb15 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -187,6 +187,35 @@ export type MonteCarloSpendingPhaseMeta = {annualWithdrawal?: number;};+/** How a later investment phase takes over from the previous one */+export type MonteCarloInvestmentTransition = 'at-once' | 'gradual';++/**+ * A change to what a pot is invested in from a given age: its allocation+ * (or hand-typed return and volatility) and its fees. The pot's own+ * fields are its settings until the first phase begins+ */+export type MonteCarloInvestmentPhaseMeta = {+ id: string;+ /** Age the phase takes effect (inclusive) */+ fromAge?: number;+ /**+ * 'gradual' glides from the previous phase's settings, starting at that+ * phase's own start age and arriving at fromAge; 'at-once' switches on+ * the birthday+ */+ transition?: MonteCarloInvestmentTransition;+ allocationPreset?: MonteCarloAllocationPreset;+ allocationStocks?: number;+ allocationBonds?: number;+ allocationCash?: number;+ expectedReturnMean?: number;+ returnStdDev?: number;+ annualFeeFixed?: number;+ feeAdjustsWithInflation?: boolean;+ annualFeeRate?: number;+};+export type MonteCarloPotMeta = {id: string;name?: string;@@ -229,6 +258,8 @@ export type MonteCarloPotMeta = {* it is drawn on before any other pot. At most one pot is flagged.*/isSurplus?: boolean;+ /** Later changes to the pot's investment, by age */+ investmentPhases?: MonteCarloInvestmentPhaseMeta[];};/** One recurring yearly contribution into a pot over an age window */diff --git a/upcoming-release-notes/monte-carlo-investment-phases.md b/upcoming-release-notes/monte-carlo-investment-phases.mdnew file mode 100644index 0000000000..5c55ae253e--- /dev/null+++ b/upcoming-release-notes/monte-carlo-investment-phases.md@@ -0,0 +1,6 @@+---+category: Features+authors: [MikesGlitch]+---++Add investment phases to Monte Carlo pots so a pot's allocation and fees can change with age