-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfire_math.js
More file actions
1239 lines (1086 loc) Β· 44.9 KB
/
fire_math.js
File metadata and controls
1239 lines (1086 loc) Β· 44.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* FIRE Calculator β Pure Calculation Module
* No DOM dependencies. All 8 withdrawal models + Monte Carlo + Delta Engine.
* MIT License Β· github.com/sandseb123/fire-calculator
*/
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Utility helpers
// ββββββββββββββββββββββββββββββββββββββββββββββ
function realReturn(nominal, inflation) {
return (1 + nominal) / (1 + inflation) - 1;
}
function clamp(val, min, max) {
return Math.max(min, Math.min(max, val));
}
// Seeded PRNG (Mulberry32) for reproducible Monte Carlo
function mulberry32(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// Box-Muller transform for normal distribution
function normalRandom(mean, stddev, rng) {
const u1 = rng();
const u2 = rng();
const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
return mean + stddev * z;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// SSA Actuarial Table (simplified, embedded)
// Life expectancy remaining at each age
// Source: SSA Period Life Table 2021
// ββββββββββββββββββββββββββββββββββββββββββββββ
const ACTUARIAL_TABLE = {
20: 58.5, 25: 53.7, 30: 48.9, 35: 44.2, 40: 39.5, 45: 34.9,
50: 30.4, 55: 26.1, 60: 21.9, 65: 18.0, 70: 14.4, 75: 11.2,
80: 8.4, 85: 6.1, 90: 4.3, 95: 3.0, 100: 2.1
};
function lifeExpectancyAt(age) {
const ages = Object.keys(ACTUARIAL_TABLE).map(Number).sort((a, b) => a - b);
if (age <= ages[0]) return ACTUARIAL_TABLE[ages[0]];
if (age >= ages[ages.length - 1]) return ACTUARIAL_TABLE[ages[ages.length - 1]];
// Linear interpolation
for (let i = 0; i < ages.length - 1; i++) {
if (age >= ages[i] && age <= ages[i + 1]) {
const frac = (age - ages[i]) / (ages[i + 1] - ages[i]);
return ACTUARIAL_TABLE[ages[i]] * (1 - frac) + ACTUARIAL_TABLE[ages[i + 1]] * frac;
}
}
return 20;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Default inputs
// ββββββββββββββββββββββββββββββββββββββββββββββ
const DEFAULTS = {
currentSavings: 50000,
monthlySavings: 2000,
annualSpending: 60000,
currentAge: 30,
targetAge: 65,
nominalReturn: 0.07,
inflation: 0.03,
withdrawalModel: 'bengen4',
assetAllocation: { stocks: 0.9, bonds: 0.1 },
retirementDuration: 30,
socialSecurity: 0,
otherIncome: 0,
taxRate: 0.12,
monteCarloRuns: 10000,
returnStdDev: 0.15,
randomSeed: null,
// Guardrails parameters
guardrailInitialRate: 0.05,
guardrailUpperBound: 0.035,
guardrailLowerBound: 0.06,
guardrailAdjustment: 0.10,
// CAPE
capeRatio: 34,
// Scenario library fields
scenarioOverrides: null,
};
function mergeInputs(user) {
return Object.assign({}, DEFAULTS, user);
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// FIRE Number calculators per model
// ββββββββββββββββββββββββββββββββββββββββββββββ
const MODELS = {
bengen4: {
name: '4% Rule (Bengen)',
rate: 0.04,
description: 'Withdraw 4% of portfolio in year 1, then adjust for inflation each year.',
bestFor: 'Default, widely cited. 30-year retirements.',
historicalSuccess: '~96% over 30-year periods',
risk: 'Sequence of returns in early years can permanently impair portfolio.',
},
conservative3: {
name: '3% Rule (Conservative)',
rate: 0.03,
description: 'Same as the 4% rule but with a 3% initial withdrawal for extra safety.',
bestFor: '40β50 year retirements or conservative planners.',
historicalSuccess: '~99% over 30-year periods',
risk: 'Requires a larger portfolio, may lead to significant unspent wealth.',
},
guardrails: {
name: 'Guardrails (Guyton-Klinger)',
rate: 0.05,
description: 'Start at ~5%, adjust spending up/down based on portfolio performance.',
bestFor: 'Flexible spenders willing to adjust lifestyle.',
historicalSuccess: '~95% with spending adjustments',
risk: 'Spending can drop 10β20% in bad markets.',
},
fixedDollar: {
name: 'Fixed Dollar',
rate: 0.04,
description: 'Withdraw a fixed dollar amount each year regardless of portfolio value.',
bestFor: 'Pensioners or those with very predictable spending.',
historicalSuccess: 'Depends on the fixed amount chosen',
risk: 'Inflation erodes purchasing power. Portfolio can deplete if amount is too high.',
},
fixedPercentage: {
name: 'Fixed Percentage',
rate: 0.04,
description: 'Withdraw a fixed percentage of the current portfolio value each year.',
bestFor: 'Those who can tolerate variable spending. Portfolio never fully depletes.',
historicalSuccess: 'Portfolio never reaches $0 (spending adjusts down)',
risk: 'Income can drop dramatically in bad markets.',
},
vpw: {
name: 'Variable Percentage Withdrawal (VPW)',
rate: null, // calculated dynamically
description: 'Withdrawal rate recalculated each year based on remaining years and returns.',
bestFor: 'Longevity-aware planning. Spending adjusts automatically.',
historicalSuccess: 'Portfolio never reaches $0',
risk: 'Spending varies year to year, can drop significantly.',
},
floorUpside: {
name: 'Floor-and-Upside',
rate: 0.04,
description: 'Guaranteed floor from safe assets (TIPS/annuity) plus variable upside from equities.',
bestFor: 'Risk-managed approach. Ensures basic needs are always met.',
historicalSuccess: 'Floor spending is guaranteed; upside varies',
risk: 'Requires splitting portfolio. Upside may underperform in bull markets.',
},
capeBased: {
name: 'CAPE-Based Withdrawal',
rate: null, // depends on current CAPE
description: 'Withdrawal rate adjusts based on current Shiller P/E ratio.',
bestFor: 'Market-condition aware planning.',
historicalSuccess: 'Debated β historical relationship may not hold',
risk: 'CAPE is backward-looking; may not predict future returns well.',
},
};
function getModelInfo(modelId) {
return MODELS[modelId] || MODELS.bengen4;
}
function getAllModels() {
return Object.keys(MODELS).map(id => ({ id, ...MODELS[id] }));
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Core: compute withdrawal rate for a given model
// ββββββββββββββββββββββββββββββββββββββββββββββ
function getWithdrawalRate(modelId, inputs) {
switch (modelId) {
case 'bengen4': return 0.04;
case 'conservative3': return 0.03;
case 'guardrails': return inputs.guardrailInitialRate || 0.05;
case 'fixedDollar': return 0.04;
case 'fixedPercentage': return 0.04;
case 'vpw': return computeVPWRate(inputs);
case 'floorUpside': return 0.04;
case 'capeBased': return computeCAPERate(inputs.capeRatio || 34);
default: return 0.04;
}
}
function computeVPWRate(inputs) {
const age = inputs.currentAge || 30;
const remainingYears = lifeExpectancyAt(age);
const r = realReturn(inputs.nominalReturn || 0.07, inputs.inflation || 0.03);
if (r <= 0 || remainingYears <= 0) return 0.04;
// PMT factor: r / (1 - (1+r)^-n)
const factor = r / (1 - Math.pow(1 + r, -remainingYears));
return clamp(factor, 0.02, 0.15);
}
function computeVPWRateAtAge(age, nominalReturn, inflation) {
const remainingYears = lifeExpectancyAt(age);
const r = realReturn(nominalReturn, inflation);
if (r <= 0 || remainingYears <= 1) return 0.10;
const factor = r / (1 - Math.pow(1 + r, -remainingYears));
return clamp(factor, 0.02, 0.15);
}
function computeCAPERate(cape) {
// Earnings yield as base, floored
if (!cape || cape <= 0) return 0.04;
const earningsYield = 1 / cape;
return clamp(earningsYield, 0.025, 0.06);
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// FIRE Number
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeFireNumber(inputs) {
const inp = mergeInputs(inputs);
const netSpending = Math.max(0, inp.annualSpending - inp.socialSecurity * 12 - inp.otherIncome);
const preTaxSpending = netSpending / (1 - inp.taxRate);
const swr = getWithdrawalRate(inp.withdrawalModel, inp);
return preTaxSpending / swr;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Years to FIRE (accumulation phase)
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeYearsToFire(inputs) {
const inp = mergeInputs(inputs);
const fireNumber = computeFireNumber(inp);
const annualSavings = inp.monthlySavings * 12;
const r = realReturn(inp.nominalReturn, inp.inflation);
if (inp.currentSavings >= fireNumber) return 0;
if (annualSavings <= 0 && r <= 0) return Infinity;
let portfolio = inp.currentSavings;
let years = 0;
const maxYears = 100;
while (portfolio < fireNumber && years < maxYears) {
portfolio = portfolio * (1 + r) + annualSavings;
years++;
}
return years >= maxYears ? Infinity : years;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Accumulation projection (year-by-year)
// ββββββββββββββββββββββββββββββββββββββββββββββ
function projectAccumulation(inputs) {
const inp = mergeInputs(inputs);
const fireNumber = computeFireNumber(inp);
const annualSavings = inp.monthlySavings * 12;
const r = realReturn(inp.nominalReturn, inp.inflation);
const years = [];
let portfolio = inp.currentSavings;
let age = inp.currentAge;
let fireDateReached = false;
// Apply scenario overrides
const overrides = inp.scenarioOverrides || {};
for (let y = 0; y <= 80 && age <= 100; y++) {
const yearOverride = overrides[y] || {};
const effectiveSavings = yearOverride.annualSavings !== undefined ? yearOverride.annualSavings : annualSavings;
const extraExpense = yearOverride.extraExpense || 0;
const extraIncome = yearOverride.extraIncome || 0;
const portfolioShock = yearOverride.portfolioShock || 0;
if (portfolioShock) {
portfolio *= (1 + portfolioShock); // e.g. -0.30 for 30% crash
}
years.push({
year: y,
age: age,
portfolio: Math.round(portfolio),
fireNumber: Math.round(fireNumber),
isFire: portfolio >= fireNumber,
});
if (!fireDateReached && portfolio >= fireNumber) {
fireDateReached = true;
}
portfolio = portfolio * (1 + r) + effectiveSavings + extraIncome - extraExpense;
age++;
}
return years;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Retirement drawdown simulation (single run)
// ββββββββββββββββββββββββββββββββββββββββββββββ
function simulateRetirement(inputs, annualReturns) {
const inp = mergeInputs(inputs);
const netSpending = Math.max(0, inp.annualSpending - inp.socialSecurity * 12 - inp.otherIncome);
const preTaxSpending = netSpending / (1 - inp.taxRate);
const fireNumber = computeFireNumber(inp);
let portfolio = fireNumber;
const duration = inp.retirementDuration;
const model = inp.withdrawalModel;
const yearlyData = [];
let withdrawal = 0;
let failed = false;
let failYear = null;
// Guardrails state
let guardrailSpending = portfolio * (inp.guardrailInitialRate || 0.05);
for (let y = 0; y < duration; y++) {
const ret = annualReturns[y] !== undefined ? annualReturns[y] : realReturn(inp.nominalReturn, inp.inflation);
const retirementAge = (inp.targetAge || inp.currentAge + computeYearsToFire(inp)) + y;
// Determine withdrawal based on model
// NOTE: Returns are real (inflation-adjusted), so all values are in today's
// dollars. Inflation-adjusting withdrawals (Bengen, conservative, CAPE) means
// "constant purchasing power" β in real terms, the withdrawal stays flat.
switch (model) {
case 'bengen4':
if (y === 0) withdrawal = portfolio * 0.04;
// In real terms, withdrawal stays constant (inflation already in returns)
break;
case 'conservative3':
if (y === 0) withdrawal = portfolio * 0.03;
// In real terms, withdrawal stays constant
break;
case 'guardrails': {
if (y === 0) {
guardrailSpending = portfolio * (inp.guardrailInitialRate || 0.05);
} else {
// No inflation adjustment needed β real returns already account for it
const currentRate = portfolio > 0 ? guardrailSpending / portfolio : 1;
if (currentRate > (inp.guardrailLowerBound || 0.06)) {
guardrailSpending *= (1 - (inp.guardrailAdjustment || 0.10));
} else if (currentRate < (inp.guardrailUpperBound || 0.035)) {
guardrailSpending *= (1 + (inp.guardrailAdjustment || 0.10));
}
}
withdrawal = guardrailSpending;
break;
}
case 'fixedDollar':
withdrawal = preTaxSpending; // fixed real amount
break;
case 'fixedPercentage':
withdrawal = portfolio * 0.04;
break;
case 'vpw': {
const vpwRate = computeVPWRateAtAge(retirementAge, inp.nominalReturn, inp.inflation);
withdrawal = portfolio * vpwRate;
break;
}
case 'floorUpside': {
const floor = preTaxSpending * 0.6; // 60% from safe assets
const upside = Math.max(0, portfolio * 0.04 - floor);
withdrawal = floor + upside;
break;
}
case 'capeBased': {
const capeRate = computeCAPERate(inp.capeRatio || 34);
if (y === 0) withdrawal = portfolio * capeRate;
// In real terms, withdrawal stays constant
break;
}
default:
if (y === 0) withdrawal = portfolio * 0.04;
}
if (portfolio <= 0) {
withdrawal = 0;
if (!failed) {
failed = true;
failYear = y;
}
} else {
withdrawal = Math.min(withdrawal, portfolio);
}
yearlyData.push({
year: y,
age: retirementAge,
portfolio: Math.round(portfolio),
withdrawal: Math.round(withdrawal),
});
portfolio = (portfolio - withdrawal) * (1 + ret);
if (portfolio < 0) portfolio = 0;
}
return {
yearlyData,
success: !failed,
failYear,
terminalValue: Math.round(portfolio),
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Monte Carlo simulation
// ββββββββββββββββββββββββββββββββββββββββββββββ
function monteCarloSimulation(inputs) {
const inp = mergeInputs(inputs);
const runs = inp.monteCarloRuns || 10000;
const duration = inp.retirementDuration;
const r = realReturn(inp.nominalReturn, inp.inflation);
const stddev = inp.returnStdDev || 0.15;
const seed = inp.randomSeed || Math.floor(Math.random() * 2147483647);
const rng = mulberry32(seed);
let successes = 0;
const failYears = [];
// Collect portfolio paths for percentile bands
const allPaths = [];
for (let i = 0; i < runs; i++) {
const returns = [];
for (let y = 0; y < duration; y++) {
returns.push(normalRandom(r, stddev, rng));
}
const result = simulateRetirement(inp, returns);
if (result.success) {
successes++;
} else {
failYears.push(result.failYear);
}
// Store portfolio values per year
allPaths.push(result.yearlyData.map(d => d.portfolio));
}
// Compute percentile bands
const p10 = [];
const p50 = [];
const p90 = [];
for (let y = 0; y < duration; y++) {
const vals = allPaths.map(p => p[y] || 0).sort((a, b) => a - b);
p10.push(Math.round(vals[Math.floor(runs * 0.10)]));
p50.push(Math.round(vals[Math.floor(runs * 0.50)]));
p90.push(Math.round(vals[Math.floor(runs * 0.90)]));
}
const successRate = successes / runs;
const avgFailYear = failYears.length > 0
? failYears.reduce((s, v) => s + v, 0) / failYears.length
: null;
return {
successRate,
successes,
runs,
seed,
p10,
p50,
p90,
avgFailYear,
failCount: runs - successes,
duration,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Coast FIRE
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeCoastFire(inputs) {
const inp = mergeInputs(inputs);
const fireNumber = computeFireNumber(inp);
const r = realReturn(inp.nominalReturn, inp.inflation);
const yearsToRetirement = (inp.targetAge || 65) - inp.currentAge;
if (yearsToRetirement <= 0 || r <= 0) {
return { coastNumber: fireNumber, reached: inp.currentSavings >= fireNumber, yearsToCoast: 0 };
}
const coastNumber = fireNumber / Math.pow(1 + r, yearsToRetirement);
const reached = inp.currentSavings >= coastNumber;
let yearsToCoast = 0;
if (!reached) {
const annualSavings = inp.monthlySavings * 12;
let portfolio = inp.currentSavings;
while (portfolio < coastNumber && yearsToCoast < 100) {
portfolio = portfolio * (1 + r) + annualSavings;
yearsToCoast++;
}
if (yearsToCoast >= 100) yearsToCoast = Infinity;
}
return {
coastNumber: Math.round(coastNumber),
fireNumber: Math.round(fireNumber),
reached,
yearsToCoast,
coastAge: inp.currentAge + yearsToCoast,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Barista FIRE
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeBaristaFire(inputs, partTimeIncome = 24000, healthcareSavings = 8400) {
const inp = mergeInputs(inputs);
const adjustedSpending = Math.max(0, inp.annualSpending - partTimeIncome - healthcareSavings);
const adjustedPreTax = adjustedSpending / (1 - inp.taxRate);
const swr = getWithdrawalRate(inp.withdrawalModel, inp);
const baristaFireNumber = adjustedPreTax / swr;
const standardFireNumber = computeFireNumber(inp);
const r = realReturn(inp.nominalReturn, inp.inflation);
const annualSavings = inp.monthlySavings * 12;
let portfolio = inp.currentSavings;
let yearsToBarista = 0;
while (portfolio < baristaFireNumber && yearsToBarista < 100) {
portfolio = portfolio * (1 + r) + annualSavings;
yearsToBarista++;
}
if (yearsToBarista >= 100) yearsToBarista = Infinity;
const yearsToFull = computeYearsToFire(inp);
return {
baristaFireNumber: Math.round(baristaFireNumber),
standardFireNumber: Math.round(standardFireNumber),
yearsToBarista,
yearsToFull,
yearsSaved: yearsToFull - yearsToBarista,
baristaAge: inp.currentAge + yearsToBarista,
partTimeIncome,
healthcareSavings,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Career Break cost
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeCareerBreakCost(inputs, breakStartAge, breakDurationYears = 1) {
const inp = mergeInputs(inputs);
const yearsWithout = computeYearsToFire(inp);
// Simulate with break: zero savings during break
const r = realReturn(inp.nominalReturn, inp.inflation);
const annualSavings = inp.monthlySavings * 12;
const fireNumber = computeFireNumber(inp);
const breakStart = breakStartAge - inp.currentAge;
let portfolio = inp.currentSavings;
let years = 0;
while (portfolio < fireNumber && years < 100) {
if (years >= breakStart && years < breakStart + breakDurationYears) {
portfolio = portfolio * (1 + r); // no savings during break
} else {
portfolio = portfolio * (1 + r) + annualSavings;
}
years++;
}
const yearsWith = years >= 100 ? Infinity : years;
return {
yearsWithoutBreak: yearsWithout,
yearsWithBreak: yearsWith,
costInYears: Math.round((yearsWith - yearsWithout) * 10) / 10,
breakStartAge,
breakDurationYears,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Geo-Arbitrage
// ββββββββββββββββββββββββββββββββββββββββββββββ
const GEO_PRESETS = {
portugal: { name: 'Portugal', multiplier: 0.55 },
mexico: { name: 'Mexico', multiplier: 0.45 },
thailand: { name: 'Thailand', multiplier: 0.40 },
colombia: { name: 'Colombia', multiplier: 0.42 },
texas: { name: 'Texas (from CA)', multiplier: 0.92 },
florida: { name: 'Florida (from CA)', multiplier: 0.96 },
tennessee: { name: 'Tennessee (from CA)', multiplier: 0.88 },
montana: { name: 'Montana (from CA)', multiplier: 0.91 },
};
function computeGeoArbitrage(inputs, colMultiplier = 0.55) {
const inp = mergeInputs(inputs);
const standardFireNumber = computeFireNumber(inp);
const standardYears = computeYearsToFire(inp);
const adjustedInputs = Object.assign({}, inp, {
annualSpending: inp.annualSpending * colMultiplier,
});
const geoFireNumber = computeFireNumber(adjustedInputs);
const geoYears = computeYearsToFire(adjustedInputs);
return {
standardFireNumber: Math.round(standardFireNumber),
geoFireNumber: Math.round(geoFireNumber),
standardYears,
geoYears,
yearsSaved: standardYears - geoYears,
colMultiplier,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Delta Engine β sensitivity analysis
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeDeltas(inputs) {
const inp = mergeInputs(inputs);
const baselineYears = computeYearsToFire(inp);
const targetYears = baselineYears - 1; // 1 year earlier
if (baselineYears === 0 || baselineYears === Infinity) {
return { baselineYears, deltas: [] };
}
const deltas = [];
// 1. Savings delta β binary search for monthly savings to move FIRE 1 year earlier
const savingsDelta = binarySearchDelta(
inp,
'monthlySavings',
inp.monthlySavings,
inp.monthlySavings + 50000,
targetYears
);
if (savingsDelta !== null) {
deltas.push({
type: 'savings',
label: 'Save more per month',
currentValue: inp.monthlySavings,
newValue: Math.round(savingsDelta),
delta: Math.round(savingsDelta - inp.monthlySavings),
unit: '$/month',
controllable: true,
});
}
// 2. Spending delta
const spendingDelta = binarySearchDelta(
inp,
'annualSpending',
0,
inp.annualSpending,
targetYears,
true // search downward
);
if (spendingDelta !== null) {
deltas.push({
type: 'spending',
label: 'Reduce annual spending',
currentValue: inp.annualSpending,
newValue: Math.round(spendingDelta),
delta: Math.round(inp.annualSpending - spendingDelta),
unit: '$/year',
controllable: true,
});
}
// 3. Return delta
const returnDelta = binarySearchDelta(
inp,
'nominalReturn',
inp.nominalReturn,
0.20,
targetYears
);
if (returnDelta !== null) {
deltas.push({
type: 'return',
label: 'Higher portfolio return',
currentValue: (inp.nominalReturn * 100).toFixed(1) + '%',
newValue: (returnDelta * 100).toFixed(1) + '%',
delta: ((returnDelta - inp.nominalReturn) * 100).toFixed(1) + '%',
unit: '',
controllable: false,
});
}
// Sort: controllable first, then by delta magnitude
deltas.sort((a, b) => {
if (a.controllable !== b.controllable) return a.controllable ? -1 : 1;
return 0;
});
return { baselineYears, targetYears, deltas };
}
function binarySearchDelta(inputs, field, lo, hi, targetYears, searchDown = false) {
const inp = mergeInputs(inputs);
let left = lo;
let right = hi;
for (let i = 0; i < 50; i++) {
const mid = (left + right) / 2;
const testInputs = Object.assign({}, inp, { [field]: mid });
const years = computeYearsToFire(testInputs);
if (searchDown) {
if (years <= targetYears) {
left = mid;
} else {
right = mid;
}
} else {
if (years <= targetYears) {
right = mid;
} else {
left = mid;
}
}
if (Math.abs(right - left) < 0.01) break;
}
const result = searchDown ? left : right;
// Verify the result actually achieves the target
const testInputs = Object.assign({}, inp, { [field]: result });
const achievedYears = computeYearsToFire(testInputs);
if (achievedYears <= targetYears + 0.5) return result;
return null;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// FIRE Type classifier
// ββββββββββββββββββββββββββββββββββββββββββββββ
function classifyFireType(inputs) {
const inp = mergeInputs(inputs);
const fireNumber = computeFireNumber(inp);
const types = [];
if (inp.annualSpending < 40000) types.push('Lean FIRE');
else if (inp.annualSpending <= 100000) types.push('Regular FIRE');
else types.push('Fat FIRE');
if (inp.targetAge < 50) types.push('FIRE RE (Early)');
const coast = computeCoastFire(inp);
if (coast.reached) types.push('Coast FIRE (reached)');
return {
fireNumber: Math.round(fireNumber),
annualSpending: inp.annualSpending,
types,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Milestones
// ββββββββββββββββββββββββββββββββββββββββββββββ
function computeMilestones(inputs) {
const inp = mergeInputs(inputs);
const targets = [100000, 250000, 500000, 1000000, 2000000, 5000000];
const r = realReturn(inp.nominalReturn, inp.inflation);
const annualSavings = inp.monthlySavings * 12;
const milestones = [];
let portfolio = inp.currentSavings;
let year = 0;
for (const target of targets) {
if (portfolio >= target) {
milestones.push({ target, year: 0, age: inp.currentAge, reached: true });
continue;
}
while (portfolio < target && year < 100) {
portfolio = portfolio * (1 + r) + annualSavings;
year++;
}
if (year < 100) {
milestones.push({ target, year, age: inp.currentAge + year, reached: false });
}
}
return milestones;
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Scenario Library β apply named templates
// ββββββββββββββββββββββββββββββββββββββββββββββ
const SCENARIO_TEMPLATES = {
kidIn3Years: {
name: 'Kid in 3 years',
description: 'Adds $15,000/year to expenses starting year 3 for 18 years. Childcare spike ($18k/year for years 3β8), then school-age reduction.',
apply(inputs) {
const overrides = {};
for (let y = 3; y < 21; y++) {
const childcare = y < 8 ? 18000 : 0;
overrides[y] = { extraExpense: 15000 + childcare };
}
return { scenarioOverrides: overrides };
},
},
sabbatical: {
name: '1-year sabbatical',
description: 'Zeros savings for 12 months at specified age. Portfolio continues compounding.',
apply(inputs, startYear = 5) {
const overrides = {};
overrides[startYear] = { annualSavings: 0 };
return { scenarioOverrides: overrides };
},
},
baristaAt45: {
name: 'Barista income at 45',
description: 'Adds $24,000/year part-time income from age 45. Healthcare savings of $8,400/year.',
apply(inputs) {
const startYear = 45 - (inputs.currentAge || 30);
const overrides = {};
for (let y = startYear; y < startYear + 20; y++) {
overrides[y] = { extraIncome: 24000 + 8400 };
}
return { scenarioOverrides: overrides };
},
},
lowerCostState: {
name: 'Move to lower-cost state',
description: 'Applies COL multiplier from specified year.',
apply(inputs, multiplier = 0.92) {
return { annualSpending: inputs.annualSpending * multiplier };
},
},
earlySS: {
name: 'Early Social Security (62)',
description: 'Adds reduced SS benefit (Γ0.70) from age 62.',
apply(inputs, monthlySS = 2000) {
return { socialSecurity: monthlySS * 0.70 };
},
},
healthcareShock: {
name: 'Healthcare cost shock',
description: 'One-time $50,000 healthcare expense in year 15.',
apply(inputs, year = 15) {
const overrides = {};
overrides[year] = { extraExpense: 50000 };
return { scenarioOverrides: overrides };
},
},
marketCrash: {
name: 'Market crash now',
description: 'Simulates 30% portfolio drop at current age.',
apply(inputs) {
const overrides = {};
overrides[0] = { portfolioShock: -0.30 };
return { scenarioOverrides: overrides };
},
},
partnerIncomeLoss: {
name: 'Partner income loss',
description: 'Removes a second income stream from specified year.',
apply(inputs, year = 5, lostIncome = 40000) {
const overrides = {};
for (let y = year; y < year + 30; y++) {
overrides[y] = { annualSavings: Math.max(0, (inputs.monthlySavings || 2000) * 12 - lostIncome) };
}
return { scenarioOverrides: overrides };
},
},
};
function getScenarioTemplates() {
return Object.keys(SCENARIO_TEMPLATES).map(id => ({
id,
name: SCENARIO_TEMPLATES[id].name,
description: SCENARIO_TEMPLATES[id].description,
}));
}
function applyScenarioTemplate(inputs, templateId, ...args) {
const template = SCENARIO_TEMPLATES[templateId];
if (!template) return inputs;
const overrides = template.apply(inputs, ...args);
return Object.assign({}, inputs, overrides);
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Assumption Inspector β generate current assumptions
// ββββββββββββββββββββββββββββββββββββββββββββββ
function getAssumptions(inputs) {
const inp = mergeInputs(inputs);
const r = realReturn(inp.nominalReturn, inp.inflation);
const swr = getWithdrawalRate(inp.withdrawalModel, inp);
const model = getModelInfo(inp.withdrawalModel);
return {
nominalReturn: (inp.nominalReturn * 100).toFixed(1) + '%',
inflation: (inp.inflation * 100).toFixed(1) + '%',
realReturn: (r * 100).toFixed(2) + '%',
realReturnFormula: `(1 + ${(inp.nominalReturn * 100).toFixed(1)}%) / (1 + ${(inp.inflation * 100).toFixed(1)}%) - 1 = ${(r * 100).toFixed(2)}%`,
returnInterpretation: 'Using real returns (inflation-adjusted).',
withdrawalModel: model.name,
withdrawalRate: (swr * 100).toFixed(2) + '%',
swrDefinition: model.description,
retirementDuration: `${inp.retirementDuration} years`,
taxRate: inp.taxRate > 0
? `${(inp.taxRate * 100).toFixed(0)}% effective rate applied to withdrawals.`
: 'Tax not modeled β your actual spending power will be lower.',
socialSecurity: inp.socialSecurity > 0
? `$${inp.socialSecurity}/month included.`
: 'Conservative β SS income not modeled.',
sequenceRiskMethod: `Monte Carlo with ${inp.monteCarloRuns.toLocaleString()} simulated return sequences. Std dev: ${(inp.returnStdDev * 100).toFixed(0)}%.`,
historicalData: 'Simulated returns only. Historical backtesting available in Advanced mode.',
monteCarloRuns: inp.monteCarloRuns,
};
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Plain-language result generators
// ββββββββββββββββββββββββββββββββββββββββββββββ
function generatePlainLanguageResult(inputs) {
const inp = mergeInputs(inputs);
const fireNumber = computeFireNumber(inp);
const years = computeYearsToFire(inp);
const retireAge = inp.currentAge + years;
const swr = getWithdrawalRate(inp.withdrawalModel, inp);
const model = getModelInfo(inp.withdrawalModel);
const mc = monteCarloSimulation(inp);
const netSpending = Math.max(0, inp.annualSpending - inp.socialSecurity * 12 - inp.otherIncome);
if (years === 0) {
return `Congratulations! You've already reached financial independence. Your portfolio of $${(inp.currentSavings).toLocaleString()} can support $${netSpending.toLocaleString()}/year in spending using the ${model.name}. Monte Carlo simulations show a ${Math.round(mc.successRate * 100)}% success rate over ${inp.retirementDuration} years.`;
}
if (years === Infinity) {
return `At your current savings rate, reaching financial independence would take an extremely long time. Consider increasing your monthly savings or reducing annual spending to make progress.`;
}
return `At your current savings rate, you'll reach financial independence in ${years} years β around age ${retireAge}. Your portfolio would be $${Math.round(fireNumber).toLocaleString()}, which can support $${netSpending.toLocaleString()}/year in spending (using the ${model.name}). Monte Carlo simulations show ${mc.successes} out of ${(mc.runs / 100)} simulated retirements succeeded over ${inp.retirementDuration} years.`;
}
function generateConfidenceBandInterpretation(mc, inputs) {
const inp = mergeInputs(inputs);
const retireAge = inp.targetAge || (inp.currentAge + computeYearsToFire(inp));
const endAge = retireAge + mc.duration;
const interpretation = {
p90: `In the best 10% of market scenarios, your portfolio stays strong through age ${endAge} and beyond. You'd have significant flexibility to increase spending or retire earlier.`,
p50: `In a typical market environment, your portfolio lasts through your planned retirement. This is a reasonable base case to plan around.`,
p10: mc.avgFailYear !== null
? `In the worst 10% of scenarios (similar to retiring in 1929 or 2000), your portfolio could be depleted by age ${Math.round(retireAge + mc.avgFailYear)}. This is the scenario to plan for.`
: `Even in tough market conditions, your plan shows resilience through the full retirement period.`,
successPlain: `${mc.successes} out of ${Math.round(mc.runs / 100)} simulated retirements still had money at age ${endAge}.${mc.failCount > 0 ? ` The ${Math.round(mc.failCount / 100)} that ran out did so mostly in scenarios with a severe downturn in years 2β5 of retirement.` : ''}`,
};
return interpretation;
}
function generateDeltaRecommendation(inputs) {
const deltas = computeDeltas(inputs);
if (deltas.baselineYears === 0) {
return "You've already reached FIRE! No changes needed.";
}
if (deltas.baselineYears === Infinity) {
return "At your current rate, FIRE is not reachable. Focus on increasing savings or reducing spending.";
}
const parts = [`You're ${deltas.baselineYears} years from FIRE.`];
for (const d of deltas.deltas) {
if (d.type === 'savings') {
parts.push(`Your biggest lever: saving $${d.delta.toLocaleString()}/month more pulls that to ${deltas.targetYears} years.`);
} else if (d.type === 'spending') {
parts.push(`Cutting $${d.delta.toLocaleString()}/year in spending gets you to ~${deltas.targetYears} years.`);
}
}
return parts.join(' ');
}
// ββββββββββββββββββββββββββββββββββββββββββββββ
// Full calculation β single entry point
// ββββββββββββββββββββββββββββββββββββββββββββββ
function calculate(inputs) {
const inp = mergeInputs(inputs);
const fireNumber = computeFireNumber(inp);