A local-first personal finance app
:chart_with_upwards_trend: Monte carlo - Historic sim - custom allocation mix (#8881)
Michael Clark221268355d11
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 3c445f738f..63f5b3eb87 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@@ -17,12 +17,15 @@ import { View } from '@actual-app/components/view';import type { MonteCarloAllocationPreset } from '@actual-app/core/types/models';import { css } from '@emotion/css';+import { FinancialText } from '#components/FinancialText';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,+ getHistoricalMixStats,+ getPotAssetWeights,MAX_AMOUNT,MAX_ANNUAL_FEE_RATE,MAX_WITHDRAWAL_TAX_RATE,@@ -68,10 +71,26 @@ export function MonteCarloPotConfiguration({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';+ // Historical models derive this pot's returns from its allocation mix,+ // so pots with one (presets and custom mixes) show the mix's measured+ // history instead of editable assumptions; the manual return/volatility+ // only apply to pots without a mix+ const assetWeights = usesHistoricalReturns ? getPotAssetWeights(pot) : null;+ const historicalMixStats =+ assetWeights != null ? getHistoricalMixStats(assetWeights) : null;++ // 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;// 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@@ -225,6 +244,23 @@ export function MonteCarloPotConfiguration({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+ setIsExpanded(true);} else {onPotChange({allocationPreset: preset,@@ -239,6 +275,7 @@ export function MonteCarloPotConfiguration({['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')],]}/>@@ -249,20 +286,37 @@ export function MonteCarloPotConfiguration({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',- })- }- />+ {historicalMixStats != null ? (+ // Historical models take real blended returns for pots with+ // an asset mix, so show what the mix actually measured+ // rather than an ignored assumption+ <Text style={{ color: theme.tableText }}>+ <FinancialText as="span">+ {t('{{value}} (historical)', {+ value: `${(historicalMixStats.mean * 100).toFixed(1)}%`,+ })}+ </FinancialText>+ </Text>+ ) : (+ <MonteCarloNumberInput+ value={pot.expectedReturnMean}+ aria-label={t('Expected return (%)')}+ scale={100}+ min={-100}+ max={100}+ onCommit={newValue =>+ onPotChange({+ expectedReturnMean: newValue ?? 0,+ // Typing a value only detaches a real preset; a custom+ // mix keeps its mix (these are its random-model inputs)+ allocationPreset:+ pot.allocationPreset === 'custom-mix'+ ? 'custom-mix'+ : 'custom',+ })+ }+ />+ )}</Field><Field@@ -270,20 +324,32 @@ export function MonteCarloPotConfiguration({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',- })- }- />+ {historicalMixStats != null ? (+ <Text style={{ color: theme.tableText }}>+ <FinancialText as="span">+ {t('{{value}} (historical)', {+ value: `${(historicalMixStats.stdDev * 100).toFixed(1)}%`,+ })}+ </FinancialText>+ </Text>+ ) : (+ <MonteCarloNumberInput+ value={pot.returnStdDev}+ aria-label={t('Volatility (std dev %)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPotChange({+ returnStdDev: newValue ?? 0,+ allocationPreset:+ pot.allocationPreset === 'custom-mix'+ ? 'custom-mix'+ : 'custom',+ })+ }+ />+ )}</Field><Field@@ -317,6 +383,107 @@ export function MonteCarloPotConfiguration({columnGap: 40,}}>+ {pot.allocationPreset === 'custom-mix' && (+ <View style={{ gap: 10 }}>+ <View+ style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}+ >+ <Text style={GROUP_HEADING_STYLE}>+ <Trans>Allocation</Trans>+ </Text>+ <MonteCarloHelpTooltip>+ <Trans>+ The share of this pot held in each asset class. The+ allocation must total 100% - until it does, the pot falls+ back to the expected return and volatility you enter.+ <br />+ <br />+ The mix drives this pot's returns under the historical+ return models. The random model still uses the expected+ return and volatility you enter.+ </Trans>+ </MonteCarloHelpTooltip>+ </View>+ <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={pot.allocationStocks}+ aria-label={t('Stocks (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPotChange({ 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={pot.allocationBonds}+ aria-label={t('Bonds (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPotChange({ 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={pot.allocationCash}+ aria-label={t('Cash (%)')}+ scale={100}+ min={0}+ max={100}+ onCommit={newValue =>+ onPotChange({ allocationCash: newValue ?? 0 })+ }+ />+ </View>+ </View>+ {isMixIncomplete && (+ // 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+ <Text+ style={{ color: theme.errorText, width: 0, minWidth: '100%' }}+ >+ <Trans>+ The allocation must total 100% - currently{' '}+ {{+ total: `${parseFloat((mixShareTotal * 100).toFixed(2))}%`,+ }}+ . Until it does, this pot uses your expected return and+ volatility instead of the mix.+ </Trans>+ </Text>+ )}+ </View>+ )}+<View style={{ gap: 10 }}><Text style={GROUP_HEADING_STYLE}><Trans>Access</Trans>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.tsxindex 5eca4f51d2..49fee8950e 100644--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotsTableHeader.tsx+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloPotsTableHeader.tsx@@ -73,7 +73,17 @@ export function MonteCarloPotsTableHeader() {<Trans>A one-click starting point that fills in a typical expected returnand volatility for the selected mix of stocks and bonds. You can- still override both values.+ still override both values, or pick Custom mix to enter your own+ stock, bond and cash percentages in the pot's expanded+ settings.+ <br />+ <br />+ With a historical return model, the mix is also the pot's+ real asset mix: its stock, bond and cash shares take each sampled+ year's actual S&P 500, 10-year Treasury and T-bill+ returns. Custom pots have no mix and always draw random returns+ from their typed values, so historical models only affect pots+ with one.</Trans></MonteCarloHelpTooltip></View>@@ -91,6 +101,12 @@ export function MonteCarloPotsTableHeader() {<Trans>The average yearly investment return before inflation. Eachsimulated year draws a random return around this average.+ <br />+ <br />+ Only used by the random model and by Custom pots - under a+ historical model, pots with an asset mix (a preset or a custom+ mix) take real returns for it instead, and this cell shows the+ mix's measured historical average.</Trans></MonteCarloHelpTooltip></View>@@ -109,6 +125,11 @@ export function MonteCarloPotsTableHeader() {How much returns swing from year to year. Higher volatility meansbigger ups and downs, which makes running out of money more likelyeven with the same average return.+ <br />+ <br />+ Only used by the random model and by Custom pots - under a+ historical model, pots with an asset mix show how much that mix+ really swung across the whole dataset.</Trans></MonteCarloHelpTooltip></View>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 77238872b9..2224c72b29 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,7 +1,10 @@import { describe, expect, it } from 'vitest';import {+ getHistoricalMixStats,+ getHistoricalPresetStats,getMonteCarloHorizonYears,+ getPotAssetWeights,MAX_AMOUNT,MAX_HORIZON_YEARS,MIN_HORIZON_YEARS,@@ -36,6 +39,9 @@ function makePot(overrides: Partial<MonteCarloPot> = {}): MonteCarloPot {name: 'Test pot',startingBalance: 50_000_000,allocationPreset: 'custom',+ allocationStocks: 0.6,+ allocationBonds: 0.4,+ allocationCash: 0,expectedReturnMean: 0.06,returnStdDev: 0.1,accessAge: null,@@ -553,6 +559,106 @@ describe('runMonteCarloSimulation', () => {expect(historical.percentileBands).toEqual(normal.percentileBands);});+ it('blends a custom mix like the preset with the same weights', () => {+ // A custom 80/20 mix must be indistinguishable from the equity-80+ // preset under a historical model - same blended series, same runs+ const preset = runMonteCarloSimulation(+ makeParams(+ { returnModel: 'historical-sequence' },+ { allocationPreset: 'equity-80' },+ ),+ );+ const customMix = runMonteCarloSimulation(+ makeParams(+ { returnModel: 'historical-sequence' },+ {+ allocationPreset: 'custom-mix',+ allocationStocks: 0.8,+ allocationBonds: 0.2,+ allocationCash: 0,+ },+ ),+ );+ expect(customMix.percentileBands).toEqual(preset.percentileBands);+ expect(customMix.successRate).toBe(preset.successRate);+ });++ it('falls back to normal draws when a custom mix does not total 100%', () => {+ // An incomplete mix is treated like a Custom pot: an absurd history+ // must not leak into its returns until the shares total 100%+ const incomplete = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-bootstrap',+ historicalReturns: [+ { year: 2000, stocks: 9, bonds: 9, cash: 9, inflation: 0 },+ ],+ },+ {+ allocationPreset: 'custom-mix',+ allocationStocks: 0.85,+ allocationBonds: 0.15,+ allocationCash: 1,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ ),+ );+ const normal = runMonteCarloSimulation(+ makeParams({}, { expectedReturnMean: 0.05, returnStdDev: 0 }),+ );+ expect(incomplete.percentileBands).toEqual(normal.percentileBands);+ });++ it('keeps a zero-share custom mix on normal draws in historical modes', () => {+ // With no usable mix the pot behaves like a Custom pot: an absurd+ // history must not leak into its returns+ const historical = runMonteCarloSimulation(+ makeParams(+ {+ returnModel: 'historical-bootstrap',+ historicalReturns: [+ { year: 2000, stocks: 9, bonds: 9, cash: 9, inflation: 0 },+ ],+ },+ {+ allocationPreset: 'custom-mix',+ allocationStocks: 0,+ allocationBonds: 0,+ allocationCash: 0,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ ),+ );+ const normal = runMonteCarloSimulation(+ makeParams({}, { expectedReturnMean: 0.05, returnStdDev: 0 }),+ );+ expect(historical.percentileBands).toEqual(normal.percentileBands);+ });++ it('a custom mix under the normal model uses the manual assumptions', () => {+ // The mix only drives historical models; random draws still come+ // from the pot's own expected return and volatility+ const customMix = runMonteCarloSimulation(+ makeParams(+ {},+ {+ allocationPreset: 'custom-mix',+ allocationStocks: 0.85,+ allocationBonds: 0.15,+ allocationCash: 0,+ expectedReturnMean: 0.05,+ returnStdDev: 0,+ },+ ),+ );+ const custom = runMonteCarloSimulation(+ makeParams({}, { expectedReturnMean: 0.05, returnStdDev: 0 }),+ );+ expect(customMix.percentileBands).toEqual(custom.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@@ -2298,3 +2404,98 @@ describe('runMonteCarloSimulation', () => {}});});++describe('getHistoricalPresetStats', () => {+ const history = [+ { year: 2000, stocks: 0.1, bonds: 0.05, cash: 0.02, inflation: 0 },+ { year: 2001, stocks: -0.1, bonds: 0.01, cash: 0.02, inflation: 0 },+ ];++ it('blends the series by the preset weights', () => {+ // equity-60: 0.6 x stocks + 0.4 x bonds -> [0.08, -0.056]+ const stats = getHistoricalPresetStats('equity-60', history);+ expect(stats.mean).toBeCloseTo(0.012, 12);+ // Sample standard deviation of two points equidistant from the mean+ expect(stats.stdDev).toBeCloseTo(0.068 * Math.sqrt(2), 12);+ });++ it('a cash preset tracks the cash series exactly', () => {+ const stats = getHistoricalPresetStats('cash', history);+ expect(stats.mean).toBeCloseTo(0.02, 12);+ expect(stats.stdDev).toBeCloseTo(0, 12);+ });++ it('returns plausible values for the real dataset', () => {+ const stats = getHistoricalPresetStats('equity-100');+ // Long-run US stocks: roughly 8-15% mean, 15-25% volatility+ expect(stats.mean).toBeGreaterThan(0.08);+ expect(stats.mean).toBeLessThan(0.15);+ expect(stats.stdDev).toBeGreaterThan(0.15);+ expect(stats.stdDev).toBeLessThan(0.25);+ });++ it('matches getHistoricalMixStats for the same weights', () => {+ const presetStats = getHistoricalPresetStats('equity-60', history);+ const mixStats = getHistoricalMixStats(+ { stocks: 0.6, bonds: 0.4, cash: 0 },+ history,+ );+ expect(mixStats).toEqual(presetStats);+ });+});++describe('getPotAssetWeights', () => {+ const mixPot = (stocks: number, bonds: number, cash: number) =>+ makePot({+ allocationPreset: 'custom-mix',+ allocationStocks: stocks,+ allocationBonds: bonds,+ allocationCash: cash,+ });++ it('returns the fixed mix behind a preset', () => {+ expect(+ getPotAssetWeights(makePot({ allocationPreset: 'equity-80' })),+ ).toEqual({ stocks: 0.8, bonds: 0.2, cash: 0 });+ });++ it('returns null for custom pots', () => {+ expect(+ getPotAssetWeights(makePot({ allocationPreset: 'custom' })),+ ).toBeNull();+ });++ it('returns a complete custom mix as-is', () => {+ expect(getPotAssetWeights(mixPot(0.85, 0.15, 0))).toEqual({+ stocks: 0.85,+ bonds: 0.15,+ cash: 0,+ });+ });++ it('tolerates float dust in a complete mix and returns exact weights', () => {+ // 0.7 + 0.3 = 0.9999999999999999 in floating point+ const weights = getPotAssetWeights(mixPot(0.7, 0.3, 0));+ expect(weights).not.toBeNull();+ if (weights == null) {+ throw new Error('expected weights');+ }+ expect(weights.stocks).toBeCloseTo(0.7, 12);+ expect(weights.bonds).toBeCloseTo(0.3, 12);+ expect(weights.stocks + weights.bonds + weights.cash).toBe(1);+ });++ it('ignores negative and non-finite shares', () => {+ expect(getPotAssetWeights(mixPot(1, -5, Number.NaN))).toEqual({+ stocks: 1,+ bonds: 0,+ cash: 0,+ });+ });++ it('returns null when the shares do not total 100%', () => {+ expect(getPotAssetWeights(mixPot(0, 0, 0))).toBeNull();+ expect(getPotAssetWeights(mixPot(0.5, 0.2, 0))).toBeNull();+ expect(getPotAssetWeights(mixPot(85, 15, 0))).toBeNull();+ });+});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 67d224c447..b4f278924c 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@@ -19,7 +19,7 @@ import type { HistoricalAnnualReturn } from './monteCarloHistoricalReturns';// 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'>,+ Exclude<MonteCarloAllocationPreset, 'custom' | 'custom-mix'>,{ mean: number; stdDev: number }> = {'equity-100': { mean: 0.07, stdDev: 0.15 },@@ -29,11 +29,18 @@ export const ALLOCATION_PRESETS: Record<cash: { mean: 0.03, stdDev: 0.015 },};+/** Relative shares of each asset class in a pot's portfolio */+export type MonteCarloAssetWeights = {+ stocks: number;+ bonds: number;+ cash: number;+};+// Asset mix behind each preset, used by the historical return models to// blend the stocks/bonds/cash series into a single yearly return per potconst PRESET_ASSET_WEIGHTS: Record<- Exclude<MonteCarloAllocationPreset, 'custom'>,- { stocks: number; bonds: number; cash: number }+ Exclude<MonteCarloAllocationPreset, 'custom' | 'custom-mix'>,+ MonteCarloAssetWeights> = {'equity-100': { stocks: 1, bonds: 0, cash: 0 },'equity-80': { stocks: 0.8, bonds: 0.2, cash: 0 },@@ -42,6 +49,96 @@ const PRESET_ASSET_WEIGHTS: Record<cash: { stocks: 0, bonds: 0, cash: 1 },};+/**+ * The asset mix that drives a pot's returns under the historical models:+ * the preset's fixed mix, or the pot's own shares for 'custom-mix'.+ * Null when the pot has no usable mix - 'custom' pots, or a custom mix+ * whose shares don't total 100% - and falls back to normal draws from+ * its manual return/volatility.+ */+export function getPotAssetWeights(+ pot: Pick<+ MonteCarloPot,+ | 'allocationPreset'+ | 'allocationStocks'+ | 'allocationBonds'+ | 'allocationCash'+ >,+): MonteCarloAssetWeights | null {+ if (pot.allocationPreset === 'custom') {+ return null;+ }+ if (pot.allocationPreset === 'custom-mix') {+ const sanitize = (share: number) =>+ Number.isFinite(share) && share > 0 ? share : 0;+ const stocks = sanitize(pot.allocationStocks);+ const bonds = sanitize(pot.allocationBonds);+ const cash = sanitize(pot.allocationCash);+ const total = stocks + bonds + cash;+ // Only a complete mix is usable; the tolerance absorbs float dust+ // like 0.7 + 0.3 = 0.9999999999999999+ if (Math.abs(total - 1) >= 1e-9) {+ return null;+ }+ // Divide the dust out so the returned weights sum to exactly 1+ return { stocks: stocks / total, bonds: bonds / total, cash: cash / total };+ }+ return PRESET_ASSET_WEIGHTS[pot.allocationPreset];+}++const historicalPresetStatsCache = new Map<+ Exclude<MonteCarloAllocationPreset, 'custom' | 'custom-mix'>,+ { mean: number; stdDev: number }+>();++/**+ * The measured mean and volatility (sample standard deviation) of an+ * asset mix's blended historical series - what a pot with that mix+ * actually experiences under the historical return models. The+ * `history` parameter exists for tests.+ */+export function getHistoricalMixStats(+ weights: MonteCarloAssetWeights,+ history: HistoricalAnnualReturn[] = HISTORICAL_ANNUAL_RETURNS,+): { mean: number; stdDev: number } {+ const blended = history.map(+ year =>+ weights.stocks * year.stocks ++ weights.bonds * year.bonds ++ weights.cash * year.cash,+ );+ const mean = blended.reduce((sum, value) => sum + value, 0) / blended.length;+ const variance =+ blended.length > 1+ ? blended.reduce((sum, value) => sum + (value - mean) ** 2, 0) /+ (blended.length - 1)+ : 0;+ return { mean, stdDev: Math.sqrt(variance) };+}++/**+ * `getHistoricalMixStats` for a preset's fixed mix; calls with the+ * default dataset are cached.+ */+export function getHistoricalPresetStats(+ preset: Exclude<MonteCarloAllocationPreset, 'custom' | 'custom-mix'>,+ history: HistoricalAnnualReturn[] = HISTORICAL_ANNUAL_RETURNS,+): { mean: number; stdDev: number } {+ const isDefaultHistory = history === HISTORICAL_ANNUAL_RETURNS;+ if (isDefaultHistory) {+ const cached = historicalPresetStatsCache.get(preset);+ if (cached != null) {+ return cached;+ }+ }++ const stats = getHistoricalMixStats(PRESET_ASSET_WEIGHTS[preset], history);+ if (isDefaultHistory) {+ historicalPresetStatsCache.set(preset, stats);+ }+ return stats;+}+/*** Money inputs above this are clamped (1e14 minor units = 1 trillion major* units); keeps even heavily compounded results within the range the@@ -143,6 +240,13 @@ export type MonteCarloPot = {name: string;startingBalance: number; // integer minor units (cents)allocationPreset: MonteCarloAllocationPreset;+ /**+ * Asset shares for the 'custom-mix' allocation, as decimal fractions.+ * Relative shares - normalized to sum to 1 by getPotAssetWeights+ */+ allocationStocks: number;+ allocationBonds: number;+ allocationCash: number;expectedReturnMean: number; // decimal fractionreturnStdDev: number; // decimal fraction/** Age from which the pot can fund withdrawals; null = immediately */@@ -170,6 +274,9 @@ export function createMonteCarloPot(id: string): MonteCarloPot {name: '',startingBalance: 50_000_000, // 500,000.00 in minor unitsallocationPreset: 'equity-60',+ allocationStocks: PRESET_ASSET_WEIGHTS['equity-60'].stocks,+ allocationBonds: PRESET_ASSET_WEIGHTS['equity-60'].bonds,+ allocationCash: PRESET_ASSET_WEIGHTS['equity-60'].cash,expectedReturnMean: ALLOCATION_PRESETS['equity-60'].mean,returnStdDev: ALLOCATION_PRESETS['equity-60'].stdDev,accessAge: null,@@ -294,6 +401,9 @@ function potFromMeta(potMeta: MonteCarloPotMeta, index: number): MonteCarloPot {name: potMeta.name ?? defaults.name,startingBalance: potMeta.startingBalance ?? defaults.startingBalance,allocationPreset: potMeta.allocationPreset ?? defaults.allocationPreset,+ allocationStocks: potMeta.allocationStocks ?? defaults.allocationStocks,+ allocationBonds: potMeta.allocationBonds ?? defaults.allocationBonds,+ allocationCash: potMeta.allocationCash ?? defaults.allocationCash,expectedReturnMean:potMeta.expectedReturnMean ?? defaults.expectedReturnMean,returnStdDev: potMeta.returnStdDev ?? defaults.returnStdDev,@@ -845,14 +955,19 @@ export function runMonteCarloSimulation(: 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.+ // 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' || pot.allocationPreset === 'custom') {+ if (returnModel === 'normal') {+ return null;+ }+ const weights = getPotAssetWeights(pot);+ if (weights == null) {return null;}- const weights = PRESET_ASSET_WEIGHTS[pot.allocationPreset];const blended = new Float64Array(historyCount);for (let historyIndex = 0; historyIndex < historyCount; historyIndex++) {blended[historyIndex] =diff --git a/packages/docs/docs/experimental/monte-carlo-analysis.md b/packages/docs/docs/experimental/monte-carlo-analysis.mdindex 8883356a72..199907757b 100644--- a/packages/docs/docs/experimental/monte-carlo-analysis.md+++ b/packages/docs/docs/experimental/monte-carlo-analysis.md@@ -49,6 +49,9 @@ The tab is organized into three small groups - **Your plan**, **Simulation** and- **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, and each sampled year brings its own actual US inflation with it, so high-inflation years keep their high-inflation markets.- **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. Each replayed year brings its own actual US inflation with it. This is the strictest test of bad timing, because real crashes and recoveries happen in their true order.++ Both historical models only take real returns for pots with an asset mix - an allocation preset, or a complete custom mix. A **Custom** pot always draws random returns around its own expected return and volatility, which is useful for assets history can't stand in for, such as an annuity or property. If every pot is Custom, a historical model's returns behave just like the random model's - though spending still follows each historical year's real inflation.+- **Simulations** - how many replays to run (1,000 to 10,000). More replays give steadier numbers but take slightly longer. When using historical sequences, this field is disabled because there is exactly one replay per historical starting year.- **Inflation - Mean (%)** - the average yearly rise in prices. When set, your planned spending grows with it so your spending power keeps up. Leave it blank to take exactly the same amount every year. With a historical return model, the two inflation inputs are replaced by an **Adjust spending with inflation** checkbox: each simulated year then uses that year's actual US inflation, keeping inflation and market returns paired the way they really were.- **Inflation - Std dev (%)** - real-world inflation bounces around from year to year rather than staying fixed. When set, each simulated year draws its own inflation rate around the mean, separately in every replay. The default of 2% is roughly how much US inflation has varied in recent decades; set it to 0 to use the fixed mean rate every year. Only used by the random return model.@@ -62,11 +65,12 @@ A _pot_ is a chunk of invested money - a pension or retirement account, an inves- **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**.+- **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**. If none of the presets match your portfolio, pick **Custom mix** and enter your own stock, bond and cash percentages in the pot's expanded settings - the allocation must total 100%, and until it does the pot falls back to the expected return and volatility you enter. With a historical return model, the mix (a preset's or a custom one) is also the pot's real asset mix - its stock, bond and cash shares take each sampled year's actual S&P 500, 10-year Treasury and T-bill returns, and the return and volatility cells show the mix's measured history instead of editable assumptions (only Custom pots, and a custom mix under the random model, keep using their typed values, via random draws).- **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:+ Click the arrow at the start of a pot's row to expand its additional settings, organized into groups:+- **Allocation - Stocks / Bonds / Cash (%)** - only shown for **Custom mix** pots: the pot's own asset shares, as described under Portfolio allocation above. Picking Custom mix in the allocation dropdown expands the row automatically, seeded with the shares of the preset you were on. The allocation must total 100% - a warning appears until it does, and in the meantime the pot uses its typed return and volatility.- **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:diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 78d50efc49..4a0e6da2fe 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -130,6 +130,7 @@ export type MonteCarloAllocationPreset =| 'equity-60'| 'equity-40'| 'cash'+ | 'custom-mix'| 'custom';export type MonteCarloWithdrawalStrategy =@@ -190,6 +191,13 @@ export type MonteCarloPotMeta = {name?: string;startingBalance?: number; // integer minor units (cents)allocationPreset?: MonteCarloAllocationPreset;+ /**+ * Asset shares for the 'custom-mix' allocation, as decimal fractions+ * (0.85 = 85%). Relative shares - they are normalized to sum to 1+ */+ allocationStocks?: number;+ allocationBonds?: number;+ allocationCash?: number;expectedReturnMean?: number; // decimal fraction (0.06 = 6%)returnStdDev?: number; // decimal fraction/** Age from which the pot can fund withdrawals; null = immediately */diff --git a/upcoming-release-notes/monte-carlo-custom-allocation-mix.md b/upcoming-release-notes/monte-carlo-custom-allocation-mix.mdnew file mode 100644index 0000000000..901008c79e--- /dev/null+++ b/upcoming-release-notes/monte-carlo-custom-allocation-mix.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MikesGlitch]+---++Monte Carlo: let pots use a custom stocks/bonds/cash allocation mix, and show each mix's measured historical return and volatility under the historical return models