Skip to content

A local-first personal finance app

:bar_chart: Monte carlo contributions (#8641)

Michael Clark85b30f586f46
diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx
index 3c889368d4..586a574205 100644
--- a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx
+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarlo.tsx
@@ -483,6 +483,7 @@ export function MonteCarlo() {
simulationIndex={selectedRunIndex}
simulationCount={result.simulationCount}
startAge={config.currentAge}
+ hasContributions={config.contributions.length > 0}
onBack={() => setSelectedRun(null)}
/>
) : (
@@ -589,14 +590,15 @@ export function MonteCarlo() {
<Paragraph>
<Trans>
Each scenario replays your retirement with a different sequence of
- yearly investment returns. Every year the withdrawal is taken
- first, then each pot grows or shrinks with that year&apos;s
- return. Pots with an access age stay invested but can&apos;t fund
- withdrawals until you reach it - if the accessible pots can&apos;t
- cover a year&apos;s withdrawal, the plan counts as having run out,
- even if locked pots still hold money. The shaded bands show the
- range of outcomes across all scenarios: the darker band covers the
- middle half, and the lighter band covers 80% of them.
+ yearly investment returns. Every year, any contributions are added
+ at the start, then the withdrawal is taken, and then each pot
+ grows or shrinks with that year&apos;s return. Pots with an access
+ age stay invested but can&apos;t fund withdrawals until you reach
+ it - if the accessible pots can&apos;t cover a year&apos;s
+ withdrawal, the plan counts as having run out, even if locked pots
+ still hold money. The shaded bands show the range of outcomes
+ across all scenarios: the darker band covers the middle half, and
+ the lighter band covers 80% of them.
</Trans>
</Paragraph>
<Paragraph>
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.tsx
index a6cb2b2a78..427f6e6e62 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
@@ -18,6 +18,7 @@ import type {
import { css } from '@emotion/css';
import { v4 as uuidv4 } from 'uuid';
+import { MonteCarloContributions } from '#components/reports/reports/monte-carlo/MonteCarloContributions';
import { MonteCarloHelpTooltip } from '#components/reports/reports/monte-carlo/MonteCarloHelpTooltip';
import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';
import { MonteCarloPotConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloPotConfiguration';
@@ -42,7 +43,12 @@ import {
import { MonteCarloTaxConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloTaxConfiguration';
import { MonteCarloWithdrawalRuleConfiguration } from '#components/reports/reports/monte-carlo/MonteCarloWithdrawalRuleConfiguration';
-type ConfigurationTab = 'plan' | 'pots' | 'withdrawals' | 'tax';
+type ConfigurationTab =
+ | 'plan'
+ | 'pots'
+ | 'contributions'
+ | 'withdrawals'
+ | 'tax';
const PLAN_GROUP_FIELDS_STYLE = {
flexDirection: 'row',
@@ -131,6 +137,12 @@ export function MonteCarloConfiguration({
>
<Trans>Investment pots</Trans>
</ModeButton>
+ <ModeButton
+ selected={activeTab === 'contributions'}
+ onSelect={() => setActiveTab('contributions')}
+ >
+ <Trans>Contributions</Trans>
+ </ModeButton>
<ModeButton
selected={activeTab === 'withdrawals'}
onSelect={() => setActiveTab('withdrawals')}
@@ -145,23 +157,42 @@ export function MonteCarloConfiguration({
</ModeButton>
</View>
- <Text style={{ color: theme.pageText }}>
- {activeTab === 'plan'
- ? t(
- 'Who this plan is for and how the simulation generates market returns.',
- )
- : activeTab === 'pots'
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
+ <Text style={{ color: theme.pageText }}>
+ {activeTab === 'plan'
? t(
- 'The invested accounts your plan draws from - each with its own balance, allocation, and return assumptions. Drag rows to reorder pots; expand a row for access, tax and fee settings.',
+ 'Who this plan is for and how the simulation generates market returns.',
)
- : activeTab === 'withdrawals'
+ : activeTab === 'pots'
? t(
- 'How much you take out each year, and optional rules that adjust it as markets move.',
+ 'The invested accounts your plan draws from - each with its own balance, allocation, and return assumptions. Drag rows to reorder pots; expand a row for access, tax and fee settings.',
)
- : t(
- 'How withdrawals are taxed - your spending is what you keep after tax.',
- )}
- </Text>
+ : activeTab === 'contributions'
+ ? t(
+ "Money you add to your pots each year, in today's money - for example pension or savings deposits while you're still earning.",
+ )
+ : activeTab === 'withdrawals'
+ ? t(
+ 'How much you take out each year, and optional rules that adjust it as markets move.',
+ )
+ : t(
+ 'How withdrawals are taxed - your spending is what you keep after tax.',
+ )}
+ </Text>
+ {activeTab === 'contributions' && (
+ <MonteCarloHelpTooltip>
+ <Trans>
+ Each contribution is paid in at the start of every year in its age
+ window (both ages inclusive), so it earns that year&apos;s return.
+ Leave the ages blank for &ldquo;now&rdquo; and &ldquo;the end of
+ the plan&rdquo;. Tick Adjust by inflation to keep the
+ amount&apos;s buying power constant; untick it for a fixed amount
+ that shrinks in real terms. A pot can receive any number of
+ contributions - even one that is still locked for withdrawals.
+ </Trans>
+ </MonteCarloHelpTooltip>
+ )}
+ </View>
{/* Plan details */}
{activeTab === 'plan' && (
@@ -411,6 +442,10 @@ export function MonteCarloConfiguration({
onRemove={() =>
onConfigChange({
pots: config.pots.filter(other => other.id !== pot.id),
+ // A removed pot takes its contributions with it
+ contributions: config.contributions.filter(
+ contribution => contribution.potId !== pot.id,
+ ),
})
}
/>
@@ -433,6 +468,17 @@ export function MonteCarloConfiguration({
</View>
)}
+ {/* Contributions */}
+ {activeTab === 'contributions' && (
+ <MonteCarloContributions
+ contributions={config.contributions}
+ pots={config.pots}
+ currentAge={config.currentAge}
+ targetAge={config.targetAge}
+ onConfigChange={onConfigChange}
+ />
+ )}
+
{/* Spending */}
{activeTab === 'withdrawals' && (
<View>
diff --git a/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsx b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsx
new file mode 100644
index 0000000000..df623dec0b
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/reports/monte-carlo/MonteCarloContributions.tsx
@@ -0,0 +1,236 @@
+import { Trans, useTranslation } from 'react-i18next';
+
+import { Button } from '@actual-app/components/button';
+import { SvgDelete } from '@actual-app/components/icons/v0';
+import { SvgAdd } from '@actual-app/components/icons/v1';
+import { Input } from '@actual-app/components/input';
+import { Select } from '@actual-app/components/select';
+import { styles } from '@actual-app/components/styles';
+import { Text } from '@actual-app/components/text';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+import { v4 as uuidv4 } from 'uuid';
+
+import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';
+import { MonteCarloNumberInput } from '#components/reports/reports/monte-carlo/MonteCarloNumberInput';
+import {
+ createMonteCarloContribution,
+ MAX_AMOUNT,
+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';
+import type {
+ MonteCarloConfig,
+ MonteCarloContribution,
+ MonteCarloPot,
+} from '#components/reports/reports/monte-carlo/monteCarloSimulation';
+import { Field, Row, TableHeader } from '#components/table';
+import { FinancialInput } from '#components/util/FinancialInput';
+
+const CONTRIBUTION_ROW_HEIGHT = 43;
+
+type MonteCarloContributionsProps = {
+ contributions: MonteCarloContribution[];
+ pots: MonteCarloPot[];
+ currentAge: number;
+ targetAge: number;
+ onConfigChange: (changes: Partial<MonteCarloConfig>) => void;
+};
+
+export function MonteCarloContributions({
+ contributions,
+ pots,
+ currentAge,
+ targetAge,
+ onConfigChange,
+}: MonteCarloContributionsProps) {
+ const { t } = useTranslation();
+
+ function updateContribution(
+ contributionId: string,
+ changes: Partial<MonteCarloContribution>,
+ ) {
+ onConfigChange({
+ contributions: contributions.map(contribution =>
+ contribution.id === contributionId
+ ? { ...contribution, ...changes }
+ : contribution,
+ ),
+ });
+ }
+
+ function removeContribution(contributionId: string) {
+ onConfigChange({
+ contributions: contributions.filter(
+ contribution => contribution.id !== contributionId,
+ ),
+ });
+ }
+
+ function addContribution() {
+ onConfigChange({
+ contributions: [
+ ...contributions,
+ createMonteCarloContribution(uuidv4(), pots[0].id),
+ ],
+ });
+ }
+
+ if (pots.length === 0) {
+ return (
+ <Text style={{ color: theme.pageText }}>
+ <Trans>
+ Add an investment pot first - contributions are paid into a pot.
+ </Trans>
+ </Text>
+ );
+ }
+
+ const potOptions = pots.map(
+ (pot, potIndex) =>
+ [pot.id, pot.name || t('Pot {{number}}', { number: potIndex + 1 })] as [
+ string,
+ string,
+ ],
+ );
+
+ return (
+ <View style={{ gap: 10 }}>
+ <View style={{ ...styles.tableContainer, flex: 'unset' }}>
+ <TableHeader>
+ <Field width="flex" style={{ minWidth: 150 }}>
+ <Trans>Contribution name</Trans>
+ </Field>
+ <Field width="flex" style={{ minWidth: 160 }}>
+ <Trans>Into pot</Trans>
+ </Field>
+ <Field width="flex" style={{ minWidth: 100 }}>
+ <Trans>From age</Trans>
+ </Field>
+ <Field width="flex" style={{ minWidth: 100 }}>
+ <Trans>To age</Trans>
+ </Field>
+ <Field width="flex" style={{ minWidth: 140 }}>
+ <Trans>Amount (per year)</Trans>
+ </Field>
+ <Field width="flex" style={{ minWidth: 170 }} />
+ <Field width={36} />
+ </TableHeader>
+
+ {contributions.map((contribution, index) => (
+ <Row
+ key={contribution.id}
+ collapsed
+ height={CONTRIBUTION_ROW_HEIGHT}
+ style={{
+ backgroundColor: theme.tableBackground,
+ ':hover': { backgroundColor: theme.tableRowBackgroundHover },
+ }}
+ >
+ <Field width="flex" style={{ minWidth: 150 }} truncate={false}>
+ <Input
+ defaultValue={contribution.name}
+ placeholder={t('Contribution {{number}}', {
+ number: index + 1,
+ })}
+ aria-label={t('Contribution name')}
+ onUpdate={newName => {
+ if (newName !== contribution.name) {
+ updateContribution(contribution.id, { name: newName });
+ }
+ }}
+ />
+ </Field>
+
+ <Field width="flex" style={{ minWidth: 160 }} truncate={false}>
+ <Select
+ value={contribution.potId}
+ onChange={value =>
+ updateContribution(contribution.id, { potId: value })
+ }
+ options={potOptions}
+ />
+ </Field>
+
+ <Field width="flex" style={{ minWidth: 100 }} truncate={false}>
+ <MonteCarloNumberInput
+ value={contribution.fromAge}
+ aria-label={t('From age')}
+ allowEmpty
+ roundToInteger
+ min={currentAge}
+ max={contribution.toAge ?? targetAge}
+ step={1}
+ placeholder={t('Now')}
+ onCommit={newValue =>
+ updateContribution(contribution.id, { fromAge: newValue })
+ }
+ />
+ </Field>
+
+ <Field width="flex" style={{ minWidth: 100 }} truncate={false}>
+ <MonteCarloNumberInput
+ value={contribution.toAge}
+ aria-label={t('To age')}
+ allowEmpty
+ roundToInteger
+ min={contribution.fromAge ?? currentAge}
+ max={targetAge}
+ step={1}
+ placeholder={t('End of plan')}
+ onCommit={newValue =>
+ updateContribution(contribution.id, { toAge: newValue })
+ }
+ />
+ </Field>
+
+ <Field width="flex" style={{ minWidth: 140 }} truncate={false}>
+ <FinancialInput
+ value={contribution.annualAmount}
+ aria-label={t('Amount (per year)')}
+ onUpdate={value => {
+ const newAmount = Math.min(MAX_AMOUNT, Math.max(0, value));
+ if (newAmount !== contribution.annualAmount) {
+ updateContribution(contribution.id, {
+ annualAmount: newAmount,
+ });
+ }
+ }}
+ />
+ </Field>
+
+ <Field width="flex" style={{ minWidth: 170 }} truncate={false}>
+ <LabeledCheckbox
+ id={`contribution-inflation-${contribution.id}`}
+ checked={contribution.adjustsWithInflation}
+ onChange={event =>
+ updateContribution(contribution.id, {
+ adjustsWithInflation: event.target.checked,
+ })
+ }
+ >
+ <Trans>Adjust by inflation</Trans>
+ </LabeledCheckbox>
+ </Field>
+
+ <Field width={36} truncate={false} style={{ alignItems: 'center' }}>
+ <Button
+ variant="bare"
+ aria-label={t('Remove contribution')}
+ onPress={() => removeContribution(contribution.id)}
+ style={{ padding: 6 }}
+ >
+ <SvgDelete width={12} height={12} />
+ </Button>
+ </Field>
+ </Row>
+ ))}
+ </View>
+
+ <View style={{ flexDirection: 'row' }}>
+ <Button onPress={addContribution}>
+ <SvgAdd width={10} height={10} style={{ marginRight: 5 }} />
+ <Trans>Add contribution</Trans>
+ </Button>
+ </View>
+ </View>
+ );
+}
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.tsx
index f0582e0904..00903d13aa 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
@@ -29,12 +29,21 @@ const AMOUNT_CELL_STYLE = {
textAlign: 'right',
} as const;
+// Pot mini-table cells must not shrink, so on narrow screens the panel
+// pushes the shared scroll container wider instead of clipping columns
+const POT_CELL_STYLE = {
+ flexShrink: 0,
+ textAlign: 'right',
+} as const;
+
type MonteCarloRunDetailTableProps = {
rows: MonteCarloRunDetailRow[];
pots: MonteCarloPot[];
simulationIndex: number;
simulationCount: number;
startAge: number;
+ /** Show the Contributions columns (the plan has contributions set up) */
+ hasContributions: boolean;
onBack: () => void;
};
@@ -44,6 +53,7 @@ export function MonteCarloRunDetailTable({
simulationIndex,
simulationCount,
startAge,
+ hasContributions,
onBack,
}: MonteCarloRunDetailTableProps) {
const { t } = useTranslation();
@@ -173,6 +183,11 @@ export function MonteCarloRunDetailTable({
<Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>
<Trans>Starting balance</Trans>
</Text>
+ {hasContributions && (
+ <Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>
+ <Trans>Contributions</Trans>
+ </Text>
+ )}
<Text style={{ ...GROUP_HEADING_STYLE, ...AMOUNT_CELL_STYLE }}>
<Trans>Withdrawal</Trans>
</Text>
@@ -192,9 +207,11 @@ export function MonteCarloRunDetailTable({
{rows.map(row => {
const isFailureRow = row === lastRow && !hasSurvived;
const isExpanded = expandedYears.has(row.year);
- // Growth applies to what stayed invested after the withdrawal;
- // no growth on a failure year (the plan stops there)
- const growthBase = row.startBalance - row.withdrawal;
+ // Growth applies to what stayed invested after contributions
+ // came in and the withdrawal went out; no growth on a failure
+ // year (the plan stops there)
+ const growthBase =
+ row.startBalance + row.contributions - row.withdrawal;
const growthPct =
!isFailureRow && growthBase > 0
? (row.growth / growthBase) * 100
@@ -241,6 +258,15 @@ export function MonteCarloRunDetailTable({
</FinancialText>
</PrivacyFilter>
</Text>
+ {hasContributions && (
+ <Text style={AMOUNT_CELL_STYLE}>
+ <PrivacyFilter>
+ <FinancialText as="span">
+ {format(row.contributions, 'financial')}
+ </FinancialText>
+ </PrivacyFilter>
+ </Text>
+ )}
<Text style={AMOUNT_CELL_STYLE}>
<PrivacyFilter>
<FinancialText as="span">
@@ -319,6 +345,20 @@ export function MonteCarloRunDetailTable({
</FinancialText>
</PrivacyFilter>
</Text>
+ {row.contributions > 0 && (
+ <Text style={{ fontSize: 13, color: theme.pageText }}>
+ <PrivacyFilter>
+ <FinancialText as="span">
+ {t(
+ 'Contributions: {{amount}}, added at the start of the year.',
+ {
+ amount: format(row.contributions, 'financial'),
+ },
+ )}
+ </FinancialText>
+ </PrivacyFilter>
+ </Text>
+ )}
{row.feesPaid > 0 && (
<Text style={{ fontSize: 13, color: theme.pageText }}>
<PrivacyFilter>
@@ -352,7 +392,12 @@ export function MonteCarloRunDetailTable({
)}
{pots.length > 0 && (
- <View style={{ marginTop: 6, maxWidth: 1010 }}>
+ <View
+ style={{
+ marginTop: 6,
+ maxWidth: hasContributions ? 1150 : 1010,
+ }}
+ >
<View
style={{
flexDirection: 'row',
@@ -373,17 +418,28 @@ export function MonteCarloRunDetailTable({
<Text
style={{
...GROUP_HEADING_STYLE,
+ ...POT_CELL_STYLE,
width: 130,
- textAlign: 'right',
}}
>
<Trans>Start balance</Trans>
</Text>
+ {hasContributions && (
+ <Text
+ style={{
+ ...GROUP_HEADING_STYLE,
+ ...POT_CELL_STYLE,
+ width: 130,
+ }}
+ >
+ <Trans>Contributed</Trans>
+ </Text>
+ )}
<Text
style={{
...GROUP_HEADING_STYLE,
+ ...POT_CELL_STYLE,
width: 130,
- textAlign: 'right',
}}
>
<Trans>Withdrawn</Trans>
@@ -391,8 +447,8 @@ export function MonteCarloRunDetailTable({
<Text
style={{
...GROUP_HEADING_STYLE,
+ ...POT_CELL_STYLE,
width: 110,
- textAlign: 'right',
}}
>
<Trans>Taxable</Trans>
@@ -400,6 +456,7 @@ export function MonteCarloRunDetailTable({
<View
style={{
width: 110,
+ flexShrink: 0,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
@@ -424,6 +481,7 @@ export function MonteCarloRunDetailTable({
<View
style={{
width: 110,
+ flexShrink: 0,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
@@ -446,8 +504,8 @@ export function MonteCarloRunDetailTable({
<Text
style={{
...GROUP_HEADING_STYLE,
+ ...POT_CELL_STYLE,
width: 90,
- textAlign: 'right',
}}
>
<Trans>Return (%)</Trans>
@@ -455,8 +513,8 @@ export function MonteCarloRunDetailTable({
<Text
style={{
...GROUP_HEADING_STYLE,
+ ...POT_CELL_STYLE,
width: 130,
- textAlign: 'right',
}}
>
<Trans>End balance</Trans>
@@ -479,7 +537,7 @@ export function MonteCarloRunDetailTable({
number: potIndex + 1,
})}
</Text>
- <Text style={{ width: 130, textAlign: 'right' }}>
+ <Text style={{ ...POT_CELL_STYLE, width: 130 }}>
<PrivacyFilter>
<FinancialText as="span">
{format(
@@ -489,7 +547,19 @@ export function MonteCarloRunDetailTable({
</FinancialText>
</PrivacyFilter>
</Text>
- <Text style={{ width: 130, textAlign: 'right' }}>
+ {hasContributions && (
+ <Text style={{ ...POT_CELL_STYLE, width: 130 }}>
+ <PrivacyFilter>
+ <FinancialText as="span">
+ {format(
+ row.potContributions[potIndex] ?? 0,
+ 'financial',
+ )}
+ </FinancialText>
+ </PrivacyFilter>
+ </Text>
+ )}
+ <Text style={{ ...POT_CELL_STYLE, width: 130 }}>
<PrivacyFilter>
<FinancialText as="span">
{format(
@@ -499,7 +569,7 @@ export function MonteCarloRunDetailTable({
</FinancialText>
</PrivacyFilter>
</Text>
- <Text style={{ width: 110, textAlign: 'right' }}>
+ <Text style={{ ...POT_CELL_STYLE, width: 110 }}>
<PrivacyFilter>
<FinancialText as="span">
{format(
@@ -509,7 +579,7 @@ export function MonteCarloRunDetailTable({
</FinancialText>
</PrivacyFilter>
</Text>
- <Text style={{ width: 110, textAlign: 'right' }}>
+ <Text style={{ ...POT_CELL_STYLE, width: 110 }}>
<PrivacyFilter>
<FinancialText as="span">
{format(
@@ -519,7 +589,7 @@ export function MonteCarloRunDetailTable({
</FinancialText>
</PrivacyFilter>
</Text>
- <Text style={{ width: 110, textAlign: 'right' }}>
+ <Text style={{ ...POT_CELL_STYLE, width: 110 }}>
<PrivacyFilter>
<FinancialText as="span">
{format(
@@ -531,8 +601,8 @@ export function MonteCarloRunDetailTable({
</Text>
<Text
style={{
+ ...POT_CELL_STYLE,
width: 90,
- textAlign: 'right',
color:
potReturn == null
? theme.pageText
@@ -547,7 +617,7 @@ export function MonteCarloRunDetailTable({
</FinancialText>
)}
</Text>
- <Text style={{ width: 130, textAlign: 'right' }}>
+ <Text style={{ ...POT_CELL_STYLE, width: 130 }}>
<PrivacyFilter>
<FinancialText as="span">
{format(
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.ts
index ca0bd99e33..6c91f6f20b 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
@@ -9,7 +9,26 @@ import {
runMonteCarloSimulation,
WITHDRAWAL_RULE_DEFAULTS,
} from './monteCarloSimulation';
-import type { MonteCarloParams, MonteCarloPot } from './monteCarloSimulation';
+import type {
+ MonteCarloContribution,
+ MonteCarloParams,
+ MonteCarloPot,
+} from './monteCarloSimulation';
+
+function makeContribution(
+ overrides: Partial<MonteCarloContribution> = {},
+): MonteCarloContribution {
+ return {
+ id: 'contribution-1',
+ name: 'Test contribution',
+ potId: 'pot-1',
+ fromAge: null,
+ toAge: null,
+ annualAmount: 1_000_000,
+ adjustsWithInflation: false,
+ ...overrides,
+ };
+}
function makePot(overrides: Partial<MonteCarloPot> = {}): MonteCarloPot {
return {
@@ -46,6 +65,7 @@ function makeParams(
spendingPhases: [
{ id: 'phase-1', name: '', fromAge: null, annualWithdrawal },
],
+ contributions: [],
inflationMean: null,
inflationStdDev: 0,
taxModel: 'flat',
@@ -1699,6 +1719,311 @@ describe('runMonteCarloSimulation', () => {
expect(flatFees[2]).toBeLessThan(flatFees[0]);
});
+ it('adds contributions at the start of each year', () => {
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 0,
+ horizonYears: 3,
+ captureRunDetail: 0,
+ contributions: [makeContribution({ annualAmount: 10_000 })],
+ },
+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },
+ ),
+ );
+
+ const rows = result.runDetail!;
+ expect(rows.map(row => row.startBalance)).toEqual([
+ 100_000, 110_000, 120_000,
+ ]);
+ expect(rows.map(row => row.contributions)).toEqual([
+ 10_000, 10_000, 10_000,
+ ]);
+ expect(rows.map(row => row.endBalance)).toEqual([
+ 110_000, 120_000, 130_000,
+ ]);
+ });
+
+ it("an inflation-adjusted contribution stays constant in today's money", () => {
+ const base = {
+ annualWithdrawal: 0,
+ horizonYears: 3,
+ inflationMean: 0.05,
+ inflationStdDev: 0,
+ deflateToTodaysMoney: true,
+ captureRunDetail: 0,
+ };
+ const potSettings = {
+ startingBalance: 100_000,
+ expectedReturnMean: 0,
+ returnStdDev: 0,
+ };
+ const adjusted = runMonteCarloSimulation(
+ makeParams(
+ {
+ ...base,
+ contributions: [
+ makeContribution({
+ annualAmount: 10_000,
+ adjustsWithInflation: true,
+ }),
+ ],
+ },
+ potSettings,
+ ),
+ );
+ expect(adjusted.runDetail!.map(row => row.contributions)).toEqual([
+ 10_000, 10_000, 10_000,
+ ]);
+
+ // A flat contribution buys less each year as prices rise
+ const flat = runMonteCarloSimulation(
+ makeParams(
+ {
+ ...base,
+ contributions: [makeContribution({ annualAmount: 10_000 })],
+ },
+ potSettings,
+ ),
+ );
+ const flatContributions = flat.runDetail!.map(row => row.contributions);
+ expect(flatContributions[0]).toBe(10_000);
+ expect(flatContributions[1]).toBeLessThan(10_000);
+ expect(flatContributions[2]).toBeLessThan(flatContributions[1]);
+ });
+
+ it('respects the contribution age window, inclusive on both ends', () => {
+ // currentAge is 60, so years 3-4 are ages 62-63
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 0,
+ horizonYears: 5,
+ captureRunDetail: 0,
+ contributions: [
+ makeContribution({ annualAmount: 10_000, fromAge: 62, toAge: 63 }),
+ ],
+ },
+ { startingBalance: 100_000, expectedReturnMean: 0, returnStdDev: 0 },
+ ),
+ );
+
+ expect(result.runDetail!.map(row => row.contributions)).toEqual([
+ 0, 0, 10_000, 10_000, 0,
+ ]);
+ });
+
+ it('deposits into locked pots - access age only gates withdrawals', () => {
+ const result = runMonteCarloSimulation(
+ makeParams({
+ annualWithdrawal: 0,
+ horizonYears: 2,
+ captureRunDetail: 0,
+ contributions: [
+ makeContribution({ potId: 'locked-pot', annualAmount: 10_000 }),
+ ],
+ pots: [
+ makePot({
+ id: 'open-pot',
+ startingBalance: 50_000,
+ expectedReturnMean: 0,
+ returnStdDev: 0,
+ }),
+ makePot({
+ id: 'locked-pot',
+ startingBalance: 20_000,
+ expectedReturnMean: 0,
+ returnStdDev: 0,
+ accessAge: 100,
+ }),
+ ],
+ }),
+ );
+
+ const rows = result.runDetail!;
+ expect(rows[0].potContributions).toEqual([0, 10_000]);
+ expect(rows[1].potBalances).toEqual([50_000, 40_000]);
+ });
+
+ it('ignores reversed and beyond-horizon contribution windows', () => {
+ // currentAge 60 with a 5-year horizon simulates ages 60-64. A
+ // reversed window can never match an age, and a window starting at
+ // the final age (65) is past the last simulated year - both must
+ // contribute nothing rather than misbehave.
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 0,
+ horizonYears: 5,
+ captureRunDetail: 0,
+ contributions: [
+ makeContribution({
+ id: 'reversed',
+ annualAmount: 10_000,
+ fromAge: 63,
+ toAge: 61,
+ }),
+ makeContribution({
+ id: 'too-late',
+ annualAmount: 10_000,
+ fromAge: 65,
+ }),
+ ],
+ },
+ { startingBalance: 50_000, expectedReturnMean: 0, returnStdDev: 0 },
+ ),
+ );
+
+ for (const row of result.runDetail!) {
+ expect(row.contributions).toBe(0);
+ }
+ expect(result.runDetail![4].endBalance).toBe(50_000);
+ });
+
+ it('emits one pot contribution entry per pot even without contributions', () => {
+ // A contribution into a pot that no longer exists is ignored, but the
+ // captured rows must still carry a per-pot array in pot order, like
+ // every other per-pot field
+ const result = runMonteCarloSimulation(
+ makeParams({
+ annualWithdrawal: 0,
+ horizonYears: 2,
+ captureRunDetail: 0,
+ contributions: [
+ makeContribution({ potId: 'deleted-pot', annualAmount: 10_000 }),
+ ],
+ pots: [
+ makePot({
+ id: 'pot-a',
+ startingBalance: 50_000,
+ expectedReturnMean: 0,
+ returnStdDev: 0,
+ }),
+ makePot({
+ id: 'pot-b',
+ startingBalance: 20_000,
+ expectedReturnMean: 0,
+ returnStdDev: 0,
+ }),
+ ],
+ }),
+ );
+
+ for (const row of result.runDetail!) {
+ expect(row.contributions).toBe(0);
+ expect(row.potContributions).toEqual([0, 0]);
+ expect(row.potContributions).toHaveLength(row.potWithdrawals.length);
+ }
+ });
+
+ it('keeps an empty pot alive while contributions are still coming', () => {
+ // A pure accumulation plan: nothing saved yet, no spending, steady
+ // deposits - this must not be declared depleted at the start
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 0,
+ horizonYears: 5,
+ captureRunDetail: 0,
+ contributions: [makeContribution({ annualAmount: 10_000 })],
+ },
+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },
+ ),
+ );
+
+ expect(result.successRate).toBe(1);
+ expect(result.runDetail!.map(row => row.endBalance)).toEqual([
+ 10_000, 20_000, 30_000, 40_000, 50_000,
+ ]);
+ for (
+ let simulationIndex = 0;
+ simulationIndex < result.simulationCount;
+ simulationIndex++
+ ) {
+ expect(result.depletionYearBySimulation[simulationIndex]).toBe(-1);
+ }
+ });
+
+ it('an empty zero-spend plan survives until delayed contributions begin', () => {
+ // Nothing saved and nothing spent for the first two years; deposits
+ // only start at age 62. The empty early years must not read as a
+ // funding shortfall.
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 0,
+ horizonYears: 5,
+ captureRunDetail: 0,
+ contributions: [
+ makeContribution({ annualAmount: 10_000, fromAge: 62 }),
+ ],
+ },
+ { startingBalance: 0, expectedReturnMean: 0, returnStdDev: 0 },
+ ),
+ );
+
+ expect(result.successRate).toBe(1);
+ expect(result.runDetail!.map(row => row.endBalance)).toEqual([
+ 0, 0, 10_000, 20_000, 30_000,
+ ]);
+ });
+
+ it('a funding shortfall still fails the plan despite pending contributions', () => {
+ // Spending outstrips the pot in year 1; deposits starting at age 70
+ // arrive too late to save it
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 20_000,
+ horizonYears: 15,
+ contributions: [
+ makeContribution({ annualAmount: 5_000, fromAge: 70 }),
+ ],
+ },
+ { startingBalance: 10_000, expectedReturnMean: 0, returnStdDev: 0 },
+ ),
+ );
+
+ expect(result.successRate).toBe(0);
+ expect(result.medianDepletionYear).toBe(1);
+ });
+
+ it('a contributing year reconciles column by column in the run detail', () => {
+ const result = runMonteCarloSimulation(
+ makeParams(
+ {
+ annualWithdrawal: 8_000,
+ horizonYears: 3,
+ captureRunDetail: 0,
+ contributions: [makeContribution({ annualAmount: 10_000 })],
+ },
+ {
+ startingBalance: 100_000,
+ expectedReturnMean: 0,
+ returnStdDev: 0,
+ annualFeeFixed: 1_000,
+ },
+ ),
+ );
+
+ const rows = result.runDetail!;
+ expect(rows.map(row => row.endBalance)).toEqual([
+ 101_000, 102_000, 103_000,
+ ]);
+ for (const row of rows) {
+ expect(
+ row.startBalance +
+ row.contributions -
+ row.withdrawal +
+ row.growth -
+ row.feesPaid,
+ ).toBe(row.endBalance);
+ expect(
+ row.potContributions.reduce((sum, amount) => sum + amount, 0),
+ ).toBe(row.contributions);
+ }
+ });
+
it('fees alone can deplete a plan', () => {
const result = runMonteCarloSimulation(
makeParams(
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.ts
index 19db110708..06651395f4 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
@@ -1,6 +1,7 @@
import { MAX_SAFE_NUMBER } from '@actual-app/core/shared/util';
import type {
MonteCarloAllocationPreset,
+ MonteCarloContributionMeta,
MonteCarloPotMeta,
MonteCarloReturnModel,
MonteCarloSpendingPhaseMeta,
@@ -105,6 +106,37 @@ export function sortMonteCarloSpendingPhases(
);
}
+/** One recurring yearly contribution into a pot over an age window */
+export type MonteCarloContribution = {
+ id: string;
+ name: string;
+ /** The pot the contribution is paid into */
+ potId: string;
+ /** Age the contribution starts (inclusive); null = starts now */
+ fromAge: number | null;
+ /** Age the contribution stops (inclusive); null = end of plan */
+ toAge: number | null;
+ /** Yearly amount in minor units, in today's money */
+ annualAmount: number;
+ /** Whether the amount rises with inflation */
+ adjustsWithInflation: boolean;
+};
+
+export function createMonteCarloContribution(
+ id: string,
+ potId: string,
+): MonteCarloContribution {
+ return {
+ id,
+ name: '',
+ potId,
+ fromAge: null,
+ toAge: null,
+ annualAmount: 1_000_000, // 10,000.00 in minor units
+ adjustsWithInflation: true,
+ };
+}
+
/** One invested pot with its own balance and return assumptions */
export type MonteCarloPot = {
id: string;
@@ -211,6 +243,8 @@ export type MonteCarloConfig = {
minimumWithdrawal: number;
/** The planned spending path; each phase runs until the next one starts */
spendingPhases: MonteCarloSpendingPhase[];
+ /** Recurring yearly contributions paid into pots */
+ contributions: MonteCarloContribution[];
/** Mean yearly inflation as a decimal fraction; null = flat withdrawals */
inflationMean: number | null;
/** Yearly inflation volatility as a decimal fraction; 0 = fixed rate */
@@ -232,6 +266,7 @@ export const MONTE_CARLO_DEFAULTS: MonteCarloConfig = {
withdrawalRule: WITHDRAWAL_RULE_DEFAULTS,
minimumWithdrawal: 0,
spendingPhases: [createMonteCarloSpendingPhase('phase-1')],
+ contributions: [],
inflationMean: 0.025,
inflationStdDev: 0.02,
taxModel: 'flat',
@@ -300,6 +335,25 @@ function spendingPhaseFromMeta(
};
}
+function contributionFromMeta(
+ contributionMeta: MonteCarloContributionMeta,
+ index: number,
+): MonteCarloContribution {
+ const defaults = createMonteCarloContribution(
+ contributionMeta.id || `contribution-${index + 1}`,
+ contributionMeta.potId ?? '',
+ );
+ return {
+ ...defaults,
+ name: contributionMeta.name ?? defaults.name,
+ fromAge: contributionMeta.fromAge ?? null,
+ toAge: contributionMeta.toAge ?? null,
+ annualAmount: contributionMeta.annualAmount ?? defaults.annualAmount,
+ adjustsWithInflation:
+ contributionMeta.adjustsWithInflation ?? defaults.adjustsWithInflation,
+ };
+}
+
export function monteCarloConfigFromMeta(
meta: MonteCarloWidget['meta'] | undefined,
): MonteCarloConfig {
@@ -316,6 +370,9 @@ export function monteCarloConfigFromMeta(
spendingPhases: meta?.spendingPhases?.length
? meta.spendingPhases.map(spendingPhaseFromMeta)
: [createMonteCarloSpendingPhase('phase-1')],
+ contributions: meta?.contributions?.length
+ ? meta.contributions.map(contributionFromMeta)
+ : [],
inflationMean:
meta?.inflationMean !== undefined
? meta.inflationMean
@@ -366,8 +423,13 @@ export type MonteCarloRunDetailRow = {
endBalance: number;
/** End-of-year balance per pot, in the order the pots are configured */
potBalances: number[];
- /** Start-of-year balance per pot, before the withdrawal, same order */
+ /** Start-of-year balance per pot, before contributions and the
+ * withdrawal, same order */
potStartBalances: number[];
+ /** Contributions paid in at the start of this year */
+ contributions: number;
+ /** Contribution each pot received at the start of the year, same order */
+ potContributions: number[];
/** How much of this year's withdrawal each pot funded (gross), same order */
potWithdrawals: number[];
/**
@@ -832,6 +894,46 @@ export function runMonteCarloSimulation(
plannedTodayByYear[year] = amount;
}
+ // Planned contributions per pot per year, in today's money - split into
+ // an inflation-adjusted and a flat portion so a year's deposit is
+ // flat + adjusted × cumulativeInflation. Deterministic and shared by
+ // every replay. Contributions into unknown pots (e.g. a pot that was
+ // deleted) are ignored.
+ const flatContributionsByYear: Float64Array[] = [];
+ const adjustedContributionsByYear: Float64Array[] = [];
+ for (let year = 0; year <= horizonYears; year++) {
+ flatContributionsByYear.push(new Float64Array(potCount));
+ adjustedContributionsByYear.push(new Float64Array(potCount));
+ }
+ // While deposits are still to come, an empty pot isn't a dead plan -
+ // depletion is only declared after the final contribution year
+ let lastContributionYear = 0;
+ let hasContributions = false;
+ for (const contribution of params.contributions) {
+ const potIndex = pots.findIndex(pot => pot.id === contribution.potId);
+ const amount = clamp(contribution.annualAmount, 0, MAX_AMOUNT);
+ if (potIndex === -1 || amount <= 0) {
+ continue;
+ }
+ for (let year = 1; year <= horizonYears; year++) {
+ const age = params.currentAge + year - 1;
+ if (contribution.fromAge != null && age < contribution.fromAge) {
+ continue;
+ }
+ if (contribution.toAge != null && age > contribution.toAge) {
+ continue;
+ }
+ const target = contribution.adjustsWithInflation
+ ? adjustedContributionsByYear
+ : flatContributionsByYear;
+ target[year][potIndex] += amount;
+ hasContributions = true;
+ if (year > lastContributionYear) {
+ lastContributionYear = year;
+ }
+ }
+ }
+
// When showing values in today's money, outputs are discounted by each
// replay's own realized inflation path
const deflate = params.deflateToTodaysMoney === true && inflationMean != null;
@@ -932,6 +1034,42 @@ export function runMonteCarloSimulation(
if (!depleted) {
const startDeflator = deflate ? 1 / cumulativeInflation : 1;
const planned = plannedTodayByYear[year] * cumulativeInflation;
+
+ // Contributions land at the start of the year, before the
+ // withdrawal: new money can fund this year's spending and earns
+ // this year's return. Locked pots receive deposits too - the
+ // access age only gates withdrawals.
+ let contributionsThisYear = 0;
+ let preContributionPotBalances: number[] | null = null;
+ // Always sized to the pots when capturing, like the other per-pot
+ // arrays, so captured rows keep one entry per pot even in plans
+ // with no contributions
+ const capturedPotContributions =
+ runDetail && simulationIndex === captureIndex
+ ? new Array<number>(potCount).fill(0)
+ : null;
+ if (hasContributions) {
+ if (capturedPotContributions) {
+ // The drill-in shows contributions as their own step, so its
+ // Start balance column needs the pre-contribution snapshot
+ preContributionPotBalances = Array.from(potBalances);
+ }
+ const flatContributions = flatContributionsByYear[year];
+ const adjustedContributions = adjustedContributionsByYear[year];
+ for (let potIndex = 0; potIndex < potCount; potIndex++) {
+ const deposit =
+ flatContributions[potIndex] +
+ adjustedContributions[potIndex] * cumulativeInflation;
+ if (deposit > 0) {
+ potBalances[potIndex] += deposit;
+ total += deposit;
+ contributionsThisYear += deposit;
+ if (capturedPotContributions) {
+ capturedPotContributions[potIndex] = deposit;
+ }
+ }
+ }
+ }
let withdrawal: number;
// Only pots that have reached their access age can fund this year's
@@ -1049,9 +1187,11 @@ export function runMonteCarloSimulation(
const capturedPotFees = capturedPotReturns
? new Array<number>(potCount).fill(0)
: null;
- // Snapshot taken now, before the withdrawal touches the balances
+ // Snapshot taken before the withdrawal touches the balances; with
+ // contributions in play, the pre-contribution snapshot from the
+ // top of the year is the displayed starting point
const capturedPotStartBalances = capturedPotReturns
- ? Array.from(potBalances)
+ ? (preContributionPotBalances ?? Array.from(potBalances))
: null;
// Net capacity: what withdrawing every accessible penny would
@@ -1071,7 +1211,10 @@ export function runMonteCarloSimulation(
accessibleTotal - taxForTakes(cumulativeInflation);
}
- if (accessibleNetCapacity <= netRequired) {
+ // A shortfall needs an actual requirement: a zero-spend year with
+ // nothing accessible (e.g. before delayed contributions start, or
+ // while every pot is still locked) is not a failure
+ if (netRequired > 0 && accessibleNetCapacity <= netRequired) {
fundingShortfall = true;
// The accessible pots can't cover this year's spending (locked
// pots may still hold money, but the plan failed to fund it);
@@ -1189,9 +1332,14 @@ export function runMonteCarloSimulation(
}
if (total <= 0) {
total = 0;
- depleted = true;
- simulationDepletionYear = year;
- depletionCounts[year]++;
+ // An empty balance with deposits still to come isn't a dead
+ // plan - future contributions re-seed the pots. This year's
+ // deposits have already landed, so >= is the right bound.
+ if (year >= lastContributionYear) {
+ depleted = true;
+ simulationDepletionYear = year;
+ depletionCounts[year]++;
+ }
}
}
@@ -1232,9 +1380,12 @@ export function runMonteCarloSimulation(
}
if (total <= 0) {
total = 0;
- depleted = true;
- simulationDepletionYear = year;
- depletionCounts[year]++;
+ // Same future-deposits guard as the post-growth check
+ if (year >= lastContributionYear) {
+ depleted = true;
+ simulationDepletionYear = year;
+ depletionCounts[year]++;
+ }
}
}
const endDeflator = deflate ? 1 / cumulativeInflation : 1;
@@ -1282,12 +1433,25 @@ export function runMonteCarloSimulation(
}
return parts.map(toSafeAmount);
};
- const startBalance = emit(yearStartTotal, startDeflator);
+ // The displayed starting balance excludes contributions - the
+ // drill-in's chain is start + contributions - withdrawal +
+ // growth - fees = end
+ const startBalance = emit(
+ yearStartTotal - contributionsThisYear,
+ startDeflator,
+ );
+ const contributions = emit(contributionsThisYear, startDeflator);
const withdrawal = emit(withdrawalTaken, startDeflator);
const taxPaid = emit(withdrawalTaken - netDelivered, startDeflator);
const base = {
year,
startBalance,
+ contributions,
+ potContributions: emitParts(
+ capturedPotContributions,
+ startDeflator,
+ contributions,
+ ),
withdrawal,
taxPaid,
potWithdrawals: emitParts(
diff --git a/packages/desktop-client/src/components/util/FinancialInput.tsx b/packages/desktop-client/src/components/util/FinancialInput.tsx
index 2f3759f5d0..0b92a0ddb7 100644
--- a/packages/desktop-client/src/components/util/FinancialInput.tsx
+++ b/packages/desktop-client/src/components/util/FinancialInput.tsx
@@ -1,12 +1,22 @@
import { useEffect, useRef, useState } from 'react';
import type { FocusEvent } from 'react';
+import { useResponsive } from '@actual-app/components/hooks/useResponsive';
import { Input } from '@actual-app/components/input';
import type { InputProps } from '@actual-app/components/input';
import { styles } from '@actual-app/components/styles';
import type { IntegerAmount } from '@actual-app/core/shared/util';
+import { css, cx } from '@emotion/css';
import { useFormat } from '#hooks/useFormat';
+import { usePrivacyMode } from '#hooks/usePrivacyMode';
+
+// In privacy mode the amount renders in the redaction font, with the same
+// reveal affordance as PrivacyFilter: squiggles at rest, readable while
+// hovered or being edited
+const REDACTED_INPUT_CLASS = css({
+ '&:not(:focus):not(:hover)': { fontFamily: 'Redacted Script' },
+});
type FinancialInputProps = Omit<
InputProps,
@@ -26,9 +36,13 @@ export function FinancialInput({
onBlur,
onFocus,
onEnter,
+ className,
...restProps
}: FinancialInputProps) {
const format = useFormat();
+ const privacyMode = usePrivacyMode();
+ // Like PrivacyFilter, redaction is desktop-only for now
+ const { isNarrowWidth } = useResponsive();
const inputRef = useRef<HTMLInputElement>(null);
const [internalValue, setInternalValue] = useState(() =>
format(integerValue, 'financial'),
@@ -88,6 +102,19 @@ export function FinancialInput({
{...restProps}
ref={setInputRef}
value={internalValue || ''}
+ className={
+ privacyMode && !isNarrowWidth
+ ? // The caller's className may be react-aria's function form, so
+ // compose through it rather than assuming a string
+ renderProps =>
+ cx(
+ typeof className === 'function'
+ ? className(renderProps)
+ : className,
+ REDACTED_INPUT_CLASS,
+ )
+ : className
+ }
style={{ ...restProps.style, ...styles.tnum }}
onChangeValue={handleChange}
onFocus={handleFocus}
diff --git a/packages/docs/docs/experimental/monte-carlo-analysis.md b/packages/docs/docs/experimental/monte-carlo-analysis.md
index 62dafda1e4..ba7b881932 100644
--- a/packages/docs/docs/experimental/monte-carlo-analysis.md
+++ b/packages/docs/docs/experimental/monte-carlo-analysis.md
@@ -36,7 +36,7 @@ The report works immediately with sensible example numbers filled in, so you can
## Setting Up Your Plan
-The configuration area at the top of the report is organized into three tabs.
+The configuration area at the top of the report is organized into five tabs.
### Plan Details
@@ -79,6 +79,20 @@ Drag a pot's row to reorder the list - the order matters if you choose to drain
The access age setting is what lets the report model the classic "bridge gap": retiring at 48 with a big pension you can't open until 57, and a smaller pot that has to carry you across those nine years. If the bridge pot runs dry too soon, the plan fails - even though the pension money exists.
:::
+### Contributions
+
+![The Contributions tab](/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png)
+
+If you're still earning, you can model the money you add to your pots each year - pension deposits or brokerage savings, anything that tops up a pot on a regular basis. Each contribution has:
+
+- **Contribution name** - anything you like, such as "Pension contributions".
+- **Into pot** - the pot the money is paid into. A pot can receive any number of contributions, and contributions can go into a pot that is still locked for withdrawals - the access age only controls when money can come _out_.
+- **From age** and **To age** - the years the contribution runs, inclusive at both ends. Leave **From age** blank to start now, and **To age** blank to keep contributing until the end of the plan.
+- **Amount (per year)** - how much is added each year, in today's money. The money is paid in at the start of each year, so it earns that year's investment return.
+- **Adjust by inflation** - tick this if the contribution will grow with prices over time (for example, a percentage of a salary that keeps pace with inflation). Untick it for a fixed amount, which buys a little less each year as prices rise.
+
+Contributions pair naturally with a spending phase set to 0: while you're working, salary covers your costs and the plan only accumulates; from your retirement age, contributions stop and spending begins.
+
### Spending
![The Spending tab](/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png)
@@ -172,7 +186,7 @@ This bar chart only counts the replays that failed, showing at which age they ra
![The simulation runs table](/img/experimental/monte-carlo-analysis/monte-carlo-runs.png)
-Switch the results view from **Chart** to **Runs** to see every replay listed from worst outcome to best. Rather than paging through thousands of runs, use the **Jump to** dropdown to go straight to the worst, median or best run - or the 25th/75th percentile for a typically-bad or typically-good outcome - with the run highlighted so you can click into it. Click any run to walk through it year by year: the balance at the start of each year, the withdrawal taken, the investment growth in that year (as money and as a percentage), and the balance at the end. Expand a year with the arrow at the start of its row (or use **Expand all years**) for the fully labeled breakdown: the withdrawal split into gross, tax and money to spend; the fees paid; and a small table showing each pot's balance at the start of the year, what it contributed to the withdrawal, how much of that counted as taxable income, the tax paid on its share, the fee it was charged that year, its return that year, and its ending balance - so you can watch, for example, the cash pot covering spending after a crash while the stock pots are left alone. With the tax-bands model, the per-pot tax is the year's tax bill shared out in proportion to each pot's taxable income.
+Switch the results view from **Chart** to **Runs** to see every replay listed from worst outcome to best. Rather than paging through thousands of runs, use the **Jump to** dropdown to go straight to the worst, median or best run - or the 25th/75th percentile for a typically-bad or typically-good outcome - with the run highlighted so you can click into it. Click any run to walk through it year by year: the balance at the start of each year, the contributions paid in (when your plan has any), the withdrawal taken, the investment growth in that year (as money and as a percentage), and the balance at the end. Expand a year with the arrow at the start of its row (or use **Expand all years**) for the fully labeled breakdown: the withdrawal split into gross, tax and money to spend; the contributions added; the fees paid; and a small table showing each pot's balance at the start of the year, what was contributed into it, what it contributed to the withdrawal, how much of that counted as taxable income, the tax paid on its share, the fee it was charged that year, its return that year, and its ending balance - so you can watch, for example, the cash pot covering spending after a crash while the stock pots are left alone. With the tax-bands model, the per-pot tax is the year's tax bill shared out in proportion to each pot's taxable income.
![The simulation run table](/img/experimental/monte-carlo-analysis/monte-carlo-run.png)
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png
index 5affbf3dc9..f480100df6 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-chart.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png
new file mode 100644
index 0000000000..e8d2d366bd
Binary files /dev/null and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-contributions.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png
index e45891a788..412f70f28a 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-histogram.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png
index 775f612442..7bc1ea7ac6 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-overview.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png
index 8f40ad1725..fc00155414 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-plan-details.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png
index c1ede83dbd..65c9b470f2 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-pots.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png
index 05a30f07fa..1499bab997 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-results.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png
index 05056926be..32c0ae329b 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-run.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png
index 1dc4a01dbf..9980156712 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-runs.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png
index e505f89b20..636951a7f7 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-tax.png differ
diff --git a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png
index 745ee7358f..26371ace6b 100644
Binary files a/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png and b/packages/docs/static/img/experimental/monte-carlo-analysis/monte-carlo-withdrawals.png differ
diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.ts
index db9d0ec0f0..25550496f3 100644
--- a/packages/loot-core/src/types/models/dashboard.ts
+++ b/packages/loot-core/src/types/models/dashboard.ts
@@ -217,6 +217,22 @@ export type MonteCarloPotMeta = {
annualFeeRate?: number;
};
+/** One recurring yearly contribution into a pot over an age window */
+export type MonteCarloContributionMeta = {
+ id: string;
+ name?: string;
+ /** The pot the contribution is paid into */
+ potId?: string;
+ /** Age the contribution starts (inclusive); null/absent = starts now */
+ fromAge?: number | null;
+ /** Age the contribution stops (inclusive); null/absent = end of plan */
+ toAge?: number | null;
+ /** Yearly amount in minor units, in today's money */
+ annualAmount?: number;
+ /** Whether the amount rises with inflation */
+ adjustsWithInflation?: boolean;
+};
+
export type MonteCarloTaxModel = 'flat' | 'bands';
/** One tax band: income from `from` upward taxed at `rate` */
@@ -239,6 +255,8 @@ export type MonteCarloWidget = AbstractWidget<
/** Minimum annual withdrawal in minor units; 0 or absent = no floor */
minimumWithdrawal?: number;
spendingPhases?: MonteCarloSpendingPhaseMeta[];
+ /** Recurring yearly contributions into pots */
+ contributions?: MonteCarloContributionMeta[];
/** Mean yearly inflation as a decimal fraction; null = flat withdrawals */
inflationMean?: number | null;
/** Yearly inflation volatility as a decimal fraction; 0 = fixed rate */
diff --git a/upcoming-release-notes/monte-carlo-contributions.md b/upcoming-release-notes/monte-carlo-contributions.md
new file mode 100644
index 0000000000..f69a671bc2
--- /dev/null
+++ b/upcoming-release-notes/monte-carlo-contributions.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [MikesGlitch]
+---
+
+Add yearly contributions to the Monte Carlo analysis report