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
72 changes: 72 additions & 0 deletions src/viewer/app/combine.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/// <reference types="bun" />
/// <reference types="node" />
/// <reference lib="esnext" />
// The combine math of a Summary over several sources; every number is made up
import { expect, test } from 'bun:test';
import { PNL_KINDS, combinedTotals, cut, incomeReceived, pnlByKind, slicesOf, taxTreatment } from './combine';

test('combined totals: dollars summed, Total return % = Σ return ÷ Σ put in, Today over the balance before it', () => {
const fid = { balance: 52000.1, putIn: 40000, dividends: 1200.05, today: 84.12 };
const k401 = { balance: 10000, putIn: 9000, dividends: 300, today: null };
const c = combinedTotals([fid, k401]);
expect([c.balance, c.putIn, c.dividends, c.total, c.growth, c.today]).toEqual([62000.1, 49000, 1500.05, 13000.1, 11500.05, 84.12]);
expect(c.totalPct).toBeCloseTo((13000.1 / 49000) * 100);
// not the average of the two percents
expect(c.totalPct).not.toBeCloseTo((((52000.1 - 40000) / 40000) * 100 + ((10000 - 9000) / 9000) * 100) / 2);
// the 401k adds $0 to Today, its balance is in the base of the percent
expect(c.todayPct).toBeCloseTo((84.12 / (62000.1 - 84.12)) * 100);
expect(combinedTotals([])).toEqual({ balance: 0, putIn: 0, dividends: 0, total: 0, totalPct: null, growth: 0, today: 0, todayPct: null });
});

test('profit and loss by kind: rows and columns add up to the total return; a kind a source does not have is "--" and $0', () => {
const t = pnlByKind([
{ id: 'investment', putIn: 1000, kinds: { interest: 10, ordinary: 20, qualified: 30, shortTerm: -5, longTerm: 40, unrealized: 100.1 } },
{ id: 'retirement', putIn: 500, kinds: { interest: 1, ordinary: 2, qualified: 3, shortTerm: 0, longTerm: 4, unrealized: 50.2 } },
{ id: 'k401', putIn: 2000, kinds: { earnings: 70, unrealized: 130.3 } },
]);
expect(t.rows.map((r) => r.kind)).toEqual(PNL_KINDS.slice());
expect(t.rows.find((r) => r.kind === 'earnings')!.cells).toEqual([null, null, 70]);
expect(t.rows.find((r) => r.kind === 'qualified')!.cells).toEqual([30, 3, null]);
expect(t.rows.find((r) => r.kind === 'unrealized')!.total).toBe(280.6);
expect(t.columns.map((c) => c.total)).toEqual([195.1, 60.2, 200.3]);
expect(t.total).toBe(455.6);
expect(t.total).toBe(t.rows.reduce((s, r) => Math.round((s + r.total) * 100) / 100, 0));
expect(t.putIn).toBe(3500);
expect(t.columns[2]!.pct).toBeCloseTo(10.015);
expect(t.pct).toBeCloseTo((455.6 / 3500) * 100);
});

test('income received by how it is taxed: qualified + ordinary and interest = taxable; taxable + tax-free + deferred + 401k = the total', () => {
const r = incomeReceived([
{ shelter: null, interest: 1.1, ordinary: 2.2, qualified: 3.3 },
{ shelter: null, interest: 0, ordinary: 0.1, qualified: 0.2 },
{ shelter: 'free', interest: 0.5, ordinary: 1, qualified: 2 },
{ shelter: 'deferred', interest: 0, ordinary: 0, qualified: 4 },
], 7.77);
expect(r).toEqual({ total: 22.17, taxable: 6.9, qualified: 3.5, ordinary: 3.4, taxFree: 3.5, deferred: 4, k401: 7.77 });
expect(incomeReceived([])).toEqual({ total: 0, taxable: 0, qualified: 0, ordinary: 0, taxFree: 0, deferred: 0, k401: 0 });
});

test('slices: dollars of a name summed over the sources, percents from the summed dollars, the largest first', () => {
const s = slicesOf([['ETFs', 100.1], ['Stocks', 50], ['ETFs', 49.9, 'with the 401k fund'], ['Cash', 0], ['Mutual funds', 50]]);
expect(s.map((x) => [x.name, x.value])).toEqual([['ETFs', 150], ['Stocks', 50], ['Mutual funds', 50]]);
expect(s[0]!.note).toBe('with the 401k fund');
expect(s.map((x) => x.pct)).toEqual([60, 20, 20]);
expect(slicesOf([])).toEqual([]);
});

test('an amount cut by shares adds up to the cent, the last part takes the rounding', () => {
const parts = cut(100, { a: 1, b: 1, c: 1 });
expect(parts).toEqual([['a', 33.33], ['b', 33.33], ['c', 33.34]]);
expect(Math.round(parts.reduce((s, [, v]) => s + v * 100, 0))).toBe(10000);
expect(cut(10, { roth: 0, pretax: 0 })).toEqual([['roth', 0], ['pretax', 10]]);
expect(cut(5, {})).toEqual([]);
});

test('tax treatment: taxable, tax-free later (Roth IRAs + the 401k\'s Roth part), taxed when taken out (the rest of the retirement money)', () => {
const s = taxTreatment({ taxable: 1000, roth: 300, deferred: 200, k401: { balance: 1000, putIn: { roth: 250, pretax: 500, employer: 250 } } });
expect(s.map((x) => [x.name, x.value])).toEqual([['Taxed when taken out', 950], ['Taxable', 1000], ['Tax-free later (Roth)', 550]].sort((a, b) => (b[1] as number) - (a[1] as number)));
expect(s.reduce((x, y) => x + y.value, 0)).toBe(2500);
expect(s.reduce((x, y) => x + y.pct, 0)).toBeCloseTo(100);
expect(taxTreatment({ taxable: 10, roth: 0, deferred: 0 }).map((x) => x.name)).toEqual(['Taxable']);
});
117 changes: 117 additions & 0 deletions src/viewer/app/combine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/// <reference lib="esnext" />
// The math of a Summary over several sources (the scope tree plan, owner 2026-12-03: "mathematically everything should be
// correct"; Fidelity first, then ADP mykplan; where data can be combined a Combined view, below it what cannot). Every
// dollar is summed from cents, every percent is worked out again from the summed dollars, never an average of percents;
// two different things are never summed (Fidelity's cost basis is the cost of the positions held, the 401k's is the money
// put in: the combined card shows Money put in instead). Pure: the UI uses it once the 401k joins the tree
import type { Shelter } from '../../shared/tax';
import type { Slice } from './derive';
import { sumUsd } from './series';

const pctOf = (part: number, whole: number): number | null => (whole > 0 ? (part / whole) * 100 : null);

/** one source (or account) of the balance: `today` null where the source has no daily price (the 401k: priced once a day after the close) */
export interface BalancePart { balance: number; putIn: number; dividends: number; today: number | null }
export interface CombinedTotals { balance: number; putIn: number; dividends: number; total: number; totalPct: number | null; growth: number; today: number; todayPct: number | null }

/**
* The head of the combined Balance card: balance, money put in and dividends summed; Total return = balance - money put
* in, its percent = Σ return / Σ put in; Growth = Total return - dividends; Today = Σ today of the sources that have one,
* its percent over the balance before it (balance - today), the 401k's balance in that base
*/
export function combinedTotals(parts: readonly BalancePart[]): CombinedTotals {
const balance = sumUsd(parts.map((p) => p.balance));
const putIn = sumUsd(parts.map((p) => p.putIn));
const dividends = sumUsd(parts.map((p) => p.dividends));
const total = sumUsd([balance, -putIn]);
const today = sumUsd(parts.map((p) => p.today ?? 0));
return { balance, putIn, dividends, total, totalPct: pctOf(total, putIn), growth: sumUsd([total, -dividends]), today, todayPct: pctOf(today, balance - today) };
}

/** the owner's sub-levels of a result (2026-12-03): interest and dividends, realized, unrealized; `earnings` is the 401k's one number, not split */
export const PNL_KINDS = ['interest', 'ordinary', 'qualified', 'earnings', 'shortTerm', 'longTerm', 'unrealized'] as const;
export type PnlKind = (typeof PNL_KINDS)[number];
/** a column of the table: Investment, Retirement, the 401k...; a kind the source does not have is left out (shown "--", counted as $0) */
export interface PnlColumn { id: string; kinds: Partial<Record<PnlKind, number>>; putIn: number }
export interface PnlByKind {
rows: Array<{ kind: PnlKind; cells: Array<number | null>; total: number }>;
columns: Array<{ id: string; total: number; putIn: number; pct: number | null }>;
total: number; putIn: number; pct: number | null;
}

/**
* Profit and loss by kind: the kinds as rows, the columns as given; the Total column = Σ of the row, the Total return row
* = Σ of the column, Return % = the column's total ÷ its money put in, the last cell Σ return ÷ Σ put in
*/
export function pnlByKind(columns: readonly PnlColumn[]): PnlByKind {
const rows = PNL_KINDS.map((kind) => {
const cells = columns.map((c) => (c.kinds[kind] === undefined ? null : c.kinds[kind]!));
return { kind, cells, total: sumUsd(cells.map((v) => v ?? 0)) };
});
const cols = columns.map((c, i) => { const total = sumUsd(rows.map((r) => r.cells[i] ?? 0)); return { id: c.id, total, putIn: c.putIn, pct: pctOf(total, c.putIn) }; });
const total = sumUsd(cols.map((c) => c.total));
const putIn = sumUsd(cols.map((c) => c.putIn));
return { rows, columns: cols, total, putIn, pct: pctOf(total, putIn) };
}

/** what a Fidelity account received in a window, by kind */
export interface Received { shelter: Shelter | null; interest: number; ordinary: number; qualified: number }
export interface IncomeReceived { total: number; taxable: number; qualified: number; ordinary: number; taxFree: number; deferred: number; k401: number }

/**
* Income received in one window (MTD, QTD, YTD) by how it is taxed: the dividends and interest paid into the shown Fidelity
* accounts (taxable ones: qualified, and ordinary with the interest; Roth: tax-free; other retirement: tax-deferred) and
* the 401k's dividends and earnings of the same window (not taxed while inside the plan). Only what was received is
* combined: an expected payment needs the pay dates of positions, which only Fidelity has
*/
export function incomeReceived(fidelity: readonly Received[], k401 = 0): IncomeReceived {
const all = (r: Received) => sumUsd([r.interest, r.ordinary, r.qualified]);
const taxable = fidelity.filter((r) => !r.shelter);
const qualified = sumUsd(taxable.map((r) => r.qualified));
const ordinary = sumUsd(taxable.map((r) => sumUsd([r.ordinary, r.interest])));
const taxFree = sumUsd(fidelity.filter((r) => r.shelter === 'free').map(all));
const deferred = sumUsd(fidelity.filter((r) => r.shelter === 'deferred').map(all));
const taxableSum = sumUsd([qualified, ordinary]);
return { total: sumUsd([taxableSum, taxFree, deferred, k401]), taxable: taxableSum, qualified, ordinary, taxFree, deferred, k401 };
}

/** an allocation of several sources: the dollars of a name summed, the percent of each from the summed dollars, the largest first; an empty slice left out */
export function slicesOf(pairs: ReadonlyArray<readonly [name: string, value: number, note?: string]>): Slice[] {
const by = new Map<string, { name: string; cents: number; note?: string }>();
pairs.forEach(([name, value, note]) => {
const s = by.get(name) ?? { name, cents: 0 };
s.cents += Math.round(value * 100);
if (note && s.note === undefined) s.note = note;
by.set(name, s);
});
const list = Array.from(by.values()).filter((s) => s.cents !== 0);
const total = list.reduce((x, s) => x + s.cents, 0);
return list.sort((a, b) => b.cents - a.cents).map((s) => ({ name: s.name, value: s.cents / 100, pct: total > 0 ? (s.cents / total) * 100 : 0, ...(s.note ? { note: s.note } : {}) }));
}

/** an amount cut by shares to the cent: the last part takes what the rounding left, so the parts add up to the amount */
export function cut(amount: number, shares: Readonly<Record<string, number>>): Array<[string, number]> {
const keys = Object.keys(shares);
const whole = keys.reduce((s, k) => s + shares[k]!, 0);
const total = Math.round(amount * 100);
let left = total;
return keys.map((k, i) => {
const c = i === keys.length - 1 ? left : whole > 0 ? Math.round((total * shares[k]!) / whole) : 0;
left -= c;
return [k, c / 100];
});
}

/** the balances by how they are taxed later: the Fidelity accounts by shelter, the 401k by the money each of its sources put in */
export interface TaxTreatmentInput { taxable: number; roth: number; deferred: number; k401?: { balance: number; putIn: { roth: number; pretax: number; employer: number } } }
export const TAX_TREATMENT_WORDS = { taxable: 'Taxable', free: 'Tax-free later (Roth)', deferred: 'Taxed when taken out' };

/**
* Tax treatment of the whole scope: taxable accounts; tax-free later = the Roth IRAs + the 401k's Roth part; taxed when
* taken out = the other retirement accounts + the 401k's pre-tax and employer parts. The 401k's balance is cut the way
* its own Tax allocation card cuts it: by the money each source put in, the last part takes the rounding
*/
export function taxTreatment(v: TaxTreatmentInput, words = TAX_TREATMENT_WORDS): Slice[] {
const k = v.k401 ? Object.fromEntries(cut(v.k401.balance, v.k401.putIn)) as Record<'roth' | 'pretax' | 'employer', number> : { roth: 0, pretax: 0, employer: 0 };
return slicesOf([[words.taxable, v.taxable], [words.free, sumUsd([v.roth, k.roth])], [words.deferred, sumUsd([v.deferred, k.pretax, k.employer])]]);
}
74 changes: 74 additions & 0 deletions src/viewer/app/series.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/// <reference types="bun" />
/// <reference types="node" />
/// <reference lib="esnext" />
// Several balance series as one: carried values, the combined line, a period's change per series then summed. Made-up numbers
import { expect, test } from 'bun:test';
import { mergeSeries, periodChange, pointAt, sumUsd, type Series } from './series';

const p = (date: string, value: number) => ({ date, value });

test('the last known point at or before a day; nothing before the first', () => {
const pts = [p('2026-10-01', 100), p('2026-10-05', 110), p('2026-10-31', 130)];
expect(pointAt(pts, '2026-09-30')).toBeNull();
expect(pointAt(pts, '2026-10-01')).toEqual(p('2026-10-01', 100));
expect(pointAt(pts, '2026-10-20')).toEqual(p('2026-10-05', 110));
expect(pointAt(pts, '2026-12-01')).toEqual(p('2026-10-31', 130));
expect(pointAt([], '2026-10-01')).toBeNull();
});

test('dollars are added as cents: 0.1 + 0.2 is 0.3', () => {
expect(sumUsd([0.1, 0.2])).toBe(0.3);
expect(sumUsd([1000.005, -0.005])).toBe(1000.01);
expect(sumUsd([])).toBe(0);
});

test('one line of a daily series and a month-end one: from the first day both have a value, the 401k carried between its points', () => {
const daily: Series = { id: 'f1', flows: [], points: [p('2026-09-29', 90), p('2026-09-30', 95), p('2026-10-01', 100), p('2026-10-02', 101.1), p('2026-10-30', 102.2)] };
const k: Series = { id: 'k', flows: [], points: [p('2026-09-30', 1000), p('2026-10-31', 1100)] };
const m = mergeSeries([daily, k]);
expect(m.map((x) => [x.date, x.value])).toEqual([['2026-09-30', 1095], ['2026-10-01', 1100], ['2026-10-02', 1101.1], ['2026-10-30', 1102.2], ['2026-10-31', 1202.2]]);
// a hover says which day each part is from
expect(m[2]!.parts).toEqual([{ id: 'f1', date: '2026-10-02', value: 101.1 }, { id: 'k', date: '2026-09-30', value: 1000 }]);
expect(mergeSeries([])).toEqual([]);
expect(mergeSeries([{ id: 'empty', points: [], flows: [] }, k]).map((x) => x.value)).toEqual([1000, 1100]);
});

test('a period: change = end - start, gain = change - money put in, the gain percent the Modified Dietz way', () => {
// $1000 on Oct 1, $500 put in on Oct 6 (half of the 10 days), $1600 on Oct 11: change 600, gain 100 over 1000 + 500 x 0.5
const s: Series = { id: 'a', points: [p('2026-10-01', 1000), p('2026-10-06', 1550), p('2026-10-11', 1600)], flows: [{ date: '2026-10-06', net: 500 }] };
const c = periodChange([s], '2026-10-01');
expect([c.start, c.end, c.flows, c.change, c.gain]).toEqual([1000, 1600, 500, 600, 100]);
expect(c.changePct).toBeCloseTo(60);
expect(c.gainPct).toBeCloseTo(8);
// a flow on the start day is already in the start value: not counted again
expect(periodChange([{ ...s, flows: [{ date: '2026-10-01', net: 500 }] }], '2026-10-01').flows).toBe(0);
});

test('per series: its own start (the last point not after the period start, else its first), its own flows; then summed', () => {
const f: Series = { id: 'f', points: [p('2026-08-29', 2000), p('2026-09-02', 2100), p('2026-12-02', 2400)], flows: [{ date: '2026-10-15', net: 200 }] };
// the 401k: month ends only, so its start for a period from Sep 1 is Aug 31; and its last point is a day older
const k: Series = { id: 'k', points: [p('2026-08-31', 5000), p('2026-11-30', 6000), p('2026-12-01', 6050)], flows: [{ date: '2026-09-15', net: 400 }, { date: '2026-10-15', net: 400 }, { date: '2026-12-02', net: 400 }] };
const c = periodChange([f, k], '2026-09-01');
expect(c.rows.map((r) => [r.id, r.from, r.to, r.start, r.end, r.flows])).toEqual([['f', '2026-08-29', '2026-12-02', 2000, 2400, 200], ['k', '2026-08-31', '2026-12-01', 5000, 6050, 800]]);
expect([c.start, c.end, c.flows, c.change, c.gain]).toEqual([7000, 8450, 1000, 1450, 450]);
// the percents come from the summed dollars, never the average of each source's percent
expect(c.changePct).toBeCloseTo((1450 / 7000) * 100);
const average = ((periodChange([f], '2026-09-01').changePct! + periodChange([k], '2026-09-01').changePct!) / 2);
expect(average).toBeCloseTo(20.5);
expect(c.changePct).not.toBeCloseTo(average);
});

test('a transfer between two shown accounts nets to zero; with one of them alone it is a deposit or a withdrawal', () => {
const a: Series = { id: 'a', points: [p('2026-10-01', 1000), p('2026-10-31', 520)], flows: [{ date: '2026-10-20', net: -500 }] };
const b: Series = { id: 'b', points: [p('2026-10-01', 300), p('2026-10-31', 810)], flows: [{ date: '2026-10-20', net: 500 }] };
const both = periodChange([a, b], '2026-10-01');
expect([both.flows, both.change, both.gain]).toEqual([0, 30, 30]);
expect(periodChange([b], '2026-10-01').flows).toBe(500);
expect(periodChange([a], '2026-10-01').gain).toBe(20);
});

test('nothing to compare: no series, no points, no start', () => {
expect(periodChange([], '2026-10-01')).toEqual({ rows: [], start: 0, end: 0, flows: 0, change: 0, gain: 0, changePct: null, gainPct: null });
const zero = periodChange([{ id: 'z', points: [p('2026-10-01', 0), p('2026-10-02', 0)], flows: [] }], '2026-10-01');
expect([zero.changePct, zero.gainPct]).toEqual([null, null]);
});
Loading