Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dist/advanced.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

181 changes: 154 additions & 27 deletions dist/advanced.js

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export type { Cadence, CurrencyCode, ContribStep, ProfitStep, RaiseStep, YieldStep, IncomeStep, LoanDraw, LumpRepayment, SpendingPhase, TaxConfig, IncomeSource, Asset, LiquidityEvent, FinancialItemCategory, FinancialItem, Scenario, TimelineRow, WithdrawalEvent, FanChartRow, Metrics, AssetClass, AssetClassId, ReturnCorrelationMatrix, RiskMetrics, ReturnProcess, InflationProcess, LongevityModel, Sex, ReturnSampler, InflationSampler, LongevitySampler, GlidePathStep, FrontierPoint, EfficientFrontierResult, ClaimingOptimizerResult, } from './types';
export type { Cadence, CurrencyCode, ContribStep, ProfitStep, RaiseStep, YieldStep, IncomeStep, LoanDraw, LumpRepayment, SpendingPhase, TaxConfig, IncomeSource, Asset, LiquidityEvent, FinancialItemCategory, FinancialItem, Scenario, TimelineRow, WithdrawalEvent, FanChartRow, Metrics, AssetClass, AssetClassId, ReturnCorrelationMatrix, RiskMetrics, ReturnProcess, InflationProcess, LongevityModel, Sex, ReturnSampler, InflationSampler, LongevitySampler, GlidePathStep, FrontierPoint, EfficientFrontierResult, ClaimingOptimizerResult, TaxResidence, TaxDomicile, TaxWrapper, TaxLot, TaxBreakdown, WrapperTaxResult, } from './types';
export { CadenceMultiplier, CURRENCY_MAP, DEFAULT_SCENARIO, type CurrencyInfo } from './defaults';
export { runProjection } from './projection';
export { runAdvancedProjection } from './advanced';
Expand All @@ -17,5 +17,7 @@ export { computeRiskMetrics, type MCRiskInputs } from './risk-metrics';
export { resolveWeights } from './glide-path';
export { computeEfficientFrontier } from './efficient-frontier';
export { optimizeSsClaiming, optimizePensionClaiming, optimizeAnnuityTiming, SSA_ADJUSTMENT_FACTORS, ANNUITY_RATE_TABLE, } from './claiming-optimizers';
export { computeWrapperTax, computeRMD, getWithholdingRate, RMD_DIVISOR_TABLE, WITHHOLDING_TREATY_TABLE, US_FEDERAL_TAX_BRACKETS_2025, UK_INCOME_TAX_BANDS_2025, } from './wrapper-tax';
export { TaxLotTracker } from './tax-lots';
export { getLogger, setLogLevel, setLogger, type Logger, type LogLevel } from './logger';
//# sourceMappingURL=index.d.ts.map
2 changes: 1 addition & 1 deletion dist/index.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ export { resolveWeights } from './glide-path.js';
export { computeEfficientFrontier } from './efficient-frontier.js';
// v0.5 — Claiming optimizers (ADR-036 / CONTRACT-019)
export { optimizeSsClaiming, optimizePensionClaiming, optimizeAnnuityTiming, SSA_ADJUSTMENT_FACTORS, ANNUITY_RATE_TABLE, } from './claiming-optimizers.js';
// v0.6 — Onshore/Offshore Tax (ADR-037 / CONTRACT-020)
export { computeWrapperTax, computeRMD, getWithholdingRate, RMD_DIVISOR_TABLE, WITHHOLDING_TREATY_TABLE, US_FEDERAL_TAX_BRACKETS_2025, UK_INCOME_TAX_BANDS_2025, } from './wrapper-tax.js';
export { TaxLotTracker } from './tax-lots.js';
// Logger utilities
export { getLogger, setLogLevel, setLogger } from './logger.js';
2 changes: 1 addition & 1 deletion dist/projection.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions dist/projection.js
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,9 @@ export function runProjection(scenario, overrideReturns) {
// asset_returns is null because we are not in multi-asset mode.
inflation_this_year: inflation_enabled ? inflation_pct / 100 : 0,
asset_returns: null,
// v0.6 additions — basic mode has no wrappers; defaults for compat.
tax_breakdown: null,
rmd_amount: rmdAmount,
};
log.debug('Year end', { age, end_balance: endBalance });
timeline.push(row);
Expand Down
37 changes: 37 additions & 0 deletions dist/tax-lots.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Tax-lot accounting for CGT computation (ADR-037 / CONTRACT-020).
*
* Tracks cost-basis lots per holding. On disposal, lots are selected using
* FIFO (oldest first) or HIFO (highest cost first) and realised gain is
* computed as proceeds - cost_basis.
*
* Pure, deterministic, no side effects.
*/
import type { TaxLot } from './types';
export declare class TaxLotTracker {
private lots;
constructor(initialLots?: TaxLot[]);
/** Add a new lot (contribution or purchase). */
addLot(year: number, amount: number, costBasis?: number): void;
/** Return a copy of all current lots. */
getLots(): TaxLot[];
/** Total market value across all lots. */
totalValue(): number;
/** Total cost basis across all lots. */
totalCostBasis(): number;
/**
* Dispose lots to cover a withdrawal amount.
*
* @param withdrawalAmount - The total proceeds to realise.
* @param method - 'FIFO' (oldest first) or 'HIFO' (highest cost first).
* @returns The realised gain (proceeds - cost_basis consumed).
*/
dispose(withdrawalAmount: number, method?: 'FIFO' | 'HIFO'): number;
/**
* Apply proportional growth to all lots (market value changes but cost
* basis stays fixed — unrealised gain increases).
*/
applyGrowth(growthRate: number): void;
private sortForDisposal;
}
//# sourceMappingURL=tax-lots.d.ts.map
1 change: 1 addition & 0 deletions dist/tax-lots.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

98 changes: 98 additions & 0 deletions dist/tax-lots.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* Tax-lot accounting for CGT computation (ADR-037 / CONTRACT-020).
*
* Tracks cost-basis lots per holding. On disposal, lots are selected using
* FIFO (oldest first) or HIFO (highest cost first) and realised gain is
* computed as proceeds - cost_basis.
*
* Pure, deterministic, no side effects.
*/
export class TaxLotTracker {
constructor(initialLots = []) {
this.lots = initialLots.map((l) => (Object.assign({}, l)));
}
/** Add a new lot (contribution or purchase). */
addLot(year, amount, costBasis) {
if (amount <= 0)
return;
this.lots.push({
year_acquired: year,
amount,
cost_basis: costBasis !== null && costBasis !== void 0 ? costBasis : amount,
});
}
/** Return a copy of all current lots. */
getLots() {
return this.lots.map((l) => (Object.assign({}, l)));
}
/** Total market value across all lots. */
totalValue() {
return this.lots.reduce((s, l) => s + l.amount, 0);
}
/** Total cost basis across all lots. */
totalCostBasis() {
return this.lots.reduce((s, l) => s + l.cost_basis, 0);
}
/**
* Dispose lots to cover a withdrawal amount.
*
* @param withdrawalAmount - The total proceeds to realise.
* @param method - 'FIFO' (oldest first) or 'HIFO' (highest cost first).
* @returns The realised gain (proceeds - cost_basis consumed).
*/
dispose(withdrawalAmount, method = 'FIFO') {
if (withdrawalAmount <= 0)
return 0;
// Sort lots for disposal order
const sorted = this.sortForDisposal(method);
let remaining = withdrawalAmount;
let totalCostConsumed = 0;
const kept = [];
for (const lot of sorted) {
if (remaining <= 0) {
kept.push(lot);
continue;
}
if (lot.amount <= remaining) {
// Consume entire lot
remaining -= lot.amount;
totalCostConsumed += lot.cost_basis;
}
else {
// Partial consumption
const fraction = remaining / lot.amount;
const costConsumed = lot.cost_basis * fraction;
totalCostConsumed += costConsumed;
kept.push({
year_acquired: lot.year_acquired,
amount: lot.amount - remaining,
cost_basis: lot.cost_basis - costConsumed,
});
remaining = 0;
}
}
this.lots = kept;
const actualProceeds = withdrawalAmount - remaining;
return actualProceeds - totalCostConsumed;
}
/**
* Apply proportional growth to all lots (market value changes but cost
* basis stays fixed — unrealised gain increases).
*/
applyGrowth(growthRate) {
for (const lot of this.lots) {
lot.amount *= 1 + growthRate;
}
}
sortForDisposal(method) {
const copy = this.lots.map((l) => (Object.assign({}, l)));
if (method === 'FIFO') {
copy.sort((a, b) => a.year_acquired - b.year_acquired);
}
else {
// HIFO: highest cost_basis first (minimises realised gain)
copy.sort((a, b) => b.cost_basis - a.cost_basis);
}
return copy;
}
}
45 changes: 45 additions & 0 deletions dist/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ export interface FinancialItem {
loan_start_age: number;
loan_credit_at_start: boolean;
loan_lump_repayments: LumpRepayment[];
/** Tax wrapper this item sits in. Default: 'Taxable'. */
wrapper?: TaxWrapper;
/** Initial cost basis for CGT computation. Default: 0. */
cost_basis?: number;
}
export interface Scenario {
[key: string]: unknown;
Expand Down Expand Up @@ -237,6 +241,20 @@ export interface Scenario {
pension_late_factor_pct?: number;
/** Percentage of portfolio used to purchase annuity at optimal age (default 0). */
annuity_purchase_pct?: number;
/** Residence jurisdiction for income/CGT (default: 'Custom'). */
tax_residence?: TaxResidence;
/** Domicile for estate/IHT and remittance basis (default: 'Non-Dom'). */
tax_domicile?: TaxDomicile;
/** Apply £30k remittance basis charge (UK non-dom only). Default: false. */
remittance_basis_charge?: boolean;
/** CGT lot disposal method. Default: 'FIFO'. */
cgt_method?: 'FIFO' | 'HIFO';
/** Treaty rate overrides. Key: 'source:resident', value: rate 0-1. */
withholding_overrides?: Record<string, number>;
/** FATCA reporting flag (display only). Default: false. */
fatca_reporting?: boolean;
/** CRS reporting flag (display only). Default: false. */
crs_reporting?: boolean;
}
/**
* One step in a glide-path allocation schedule.
Expand Down Expand Up @@ -323,6 +341,10 @@ export interface TimelineRow {
asset_returns: Record<string, number> | null;
/** True on the final row of an MC trial that was terminated by a stochastic longevity draw (not at end_age). */
death_sampled_this_trial?: boolean;
/** Per-wrapper tax breakdown for this year. Null when no wrappers are active. */
tax_breakdown?: TaxBreakdown | null;
/** Forced RMD withdrawal for this year (0 if not applicable). */
rmd_amount?: number;
}
export interface FanChartRow {
age: number;
Expand Down Expand Up @@ -371,6 +393,29 @@ export interface ReturnCorrelationMatrix {
* Sex designation used by the Gompertz and cohort longevity models.
*/
export type Sex = 'M' | 'F' | 'Unspecified';
export type TaxResidence = 'US' | 'UK' | 'Cayman' | 'UAE' | 'Singapore' | 'Custom';
export type TaxDomicile = 'US' | 'UK-Dom' | 'UK-Deemed-Dom' | 'UK-Non-Dom' | 'Non-Dom';
export type TaxWrapper = 'Taxable' | 'US-Traditional-401k' | 'US-Traditional-IRA' | 'US-Roth-401k' | 'US-Roth-IRA' | 'UK-SIPP' | 'UK-ISA' | 'UK-Onshore-Bond' | 'UK-Offshore-Bond' | 'Offshore-Trust' | 'Cayman-Exempt-Company';
export interface TaxLot {
year_acquired: number;
amount: number;
cost_basis: number;
}
export interface TaxBreakdown {
income_tax: number;
capital_gains_tax: number;
dividend_withholding: number;
rmd_forced_withdrawal: number;
remittance_basis_charge: number;
total: number;
}
export interface WrapperTaxResult {
wrapper: TaxWrapper;
gross_withdrawal: number;
tax_breakdown: TaxBreakdown;
net_withdrawal: number;
remaining_lots: TaxLot[];
}
/**
* Discriminated union describing the sampling process for annual returns.
* - LogNormal: current v0.3 behaviour (multivariate log-normal).
Expand Down
Loading
Loading