Skip to content

feat(analytics): compute portfolio TWR from subperiod snapshots (#21) - #23

Open
jeffrey-graham wants to merge 1 commit into
HyperDevTools:mainfrom
jeffrey-graham:jeffrey-graham-patch-1
Open

jeffrey-graham wants to merge 1 commit into
HyperDevTools:mainfrom
jeffrey-graham:jeffrey-graham-patch-1

Conversation

@jeffrey-graham

@jeffrey-graham jeffrey-graham commented Nov 8, 2026 •

Copy link
Copy Markdown

Closes #21

Replaces the synthetic [roi / 200, roi / 200] two-half ROI split in computePortfolioFromTrades with real sequential subperiod compounding from chronological valuation and net cash-flow snapshots (PortfolioValuationSnapshot):

  • calculateTWRFromSnapshots(snapshots) (lib/analytics/portfolio.ts): Sorts snapshots chronologically, validates strictly increasing finite timestamps and positive starting subperiod valuations, computes each subperiod holding return as r_i = (V_end - CF_i - V_start) / V_start, and compounds via ((∏ (1 + r_i)) - 1) * 100.
  • Explicit unavailability signaling (PortfolioPerformance): Types timeWeightedReturn as number | null alongside twrAvailable: boolean so callers receive null / false whenever fewer than two valid chronological snapshots exist rather than a fabricated ROI split.
  • Worked numerical examples (verified in __tests__/analytics/portfolio.test.ts):
    • Compounded subperiods without external cash flows: $1,000 -> $1,100 (+10%) followed by $1,100 -> $1,320 (+20%) yields (1.10 * 1.20 - 1) * 100 = 32%.
    • Cash-flow invariance: Starting at $1,000, growing +10% to $1,100 with a +$900 deposit (V_end = $2,000, netCashFlow = 900 -> r_1 = (2000 - 900 - 1000) / 1000 = +10%), then declining -5% to $1,900 with a -$400 withdrawal (V_end = $1,500, netCashFlow = -400 -> r_2 = (1500 - (-400) - 2000) / 2000 = -5%) yields (1.10 * 0.95 - 1) * 100 = 4.5%, identical to an unadjusted $1,000 -> $1,100 -> $1,045 series.

Local Verification

  • npm run type-check -> 0 errors
  • npm run lint -> 0 warnings, 0 errors
  • npx jest --runInBand -> 8 suites passed (16 / 16 tests)
  • npm audit --omit=dev --audit-level=moderate & npm audit --audit-level=high -> passed (0 prod vulnerabilities; GitHub Actions CI awaiting maintainer approval)

@jeffrey-graham jeffrey-graham changed the title feat(analytics): calculate portfolio time-weighted return from real s… feat(analytics): compute portfolio TWR from subperiod snapshots (#21) Nov 12, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Calculate portfolio time-weighted return from real subperiod returns

1 participant