Add a realised P&L timeline to the portfolio hub

Merged
JA
3mo ago
+972-69

Summary

Delivers PR 2.6 of #121 — triage plan.

Realised gains exist in the app today only as a single-period total grouped by tax treatment, computed in ReportsController#build_investment_metrics (reports_controller.rb:519-600) and rendered by reports/_investment_performance.html.erb:156-168. There is no view of realised P&L over time, and the logic sits in a controller rather than a model.

Portfolio::RealizedGains buckets disposals by the month they settled, over the same historical_scope the return figures use, and the portfolio hub gains a section for it.

Four rules the naive version gets wrong

Each is taken from code that already gets it right, not invented.

  1. A transfer out looks exactly like a sale. Both carry a negative qty, so a bare qty < 0 filter books the full market value of every position a user moved between their own accounts as a realised gain. Trade::INTERNAL_MOVEMENT_LABELS is filtered in SQL — and note it is deliberately narrower than Transaction::INTERNAL_MOVEMENT_LABELS, which also carries Exchange; a security-for-security exchange can genuinely dispose of an appreciated asset.
  2. A realised gain is locked at the moment of sale, so it converts at that day's rate, never today's. Marking a two-year-old disposal to today's rate restates a number the user already has on a tax document.
  3. A missing rate is not a rate of 1.
  4. A disposal whose cost basis cannot be determined is not a zero gain.

Two deliberate departures from the existing code

ExchangeRate.rates_for could not be used. It is the batch helper that exists for exactly this, but its last line is result[currency] = rate&.rate || 1 — a pair it cannot find comes back at parity with a log line, so the caller cannot tell "one to one" from "no idea". The #121 readiness review settled this for the whole engine ("do not use parity fallback"), and Portfolio::DailyReturns already refuses it, raising rate_missing instead. Rates are read directly here; a disposal that cannot be converted is reported, not counted at par.

This was found by writing the test first: the guard was dead code until the helper was replaced, and the missing_exchange_rate test would have passed against a figure silently converted at 1:1.

An undeterminable cost basis is excluded and counted, not folded to zero. reports_controller.rb:588 does gain ? convert_trade.call(...) : 0, which drags a total toward zero with no signal that anything is missing. #excluded_trades reports both reasons and the section surfaces them, the same way 2.3 treats a holding with no cost basis.

Scope and dependencies

  • Issue: #121 (PR 2.6 of the ladder). 2.1–2.3 landed in #148 (08f63dc); 2.5 was closed as already delivered in the readiness review
  • Parent PR/branch, if stacked: none — branched from main at 6ef977d
  • Does not collide with the PRs in flight. #164 and #165 both edit performance.rb; this touches neither it nor return_scope.rb, so it can land in any order relative to them. 2.4 is deliberately not in this PR: it renders metrics[:mwr], whose meaning #165 changes, and building the UI against a semantic still under review means rebuilding it
  • Intentionally out of scope: tax-treatment grouping (that view exists in Reports); wash-sale and lot-level accounting (realized_gain_loss is average-cost at time of sale, and changing the cost method is its own decision); backfilling the Reports card onto this model; bucketing that follows Period#interval — realised sells are sparse, so daily buckets are mostly empty bars, and monthly is fixed for now
  • No returns-contract row is added. A return answers "how did the money perform"; this answers "what was crystallised, and when". EXPECTED_ROWS is untouched. The section's semantics do belong to the methodology contract, where P32–P38 hold the hub's other sections, so P41 states its six rules and cites the tests: the gate now verifies 41 methodology and 17 returns rows

Files changed

18 files, +903 / −69.

FileChange
app/models/portfolio/realized_gains.rbNew PORO: monthly buckets, exclusions, direct FX
app/models/investment_statement.rb#realized_gains(period:) on historical_scope; #preload_avg_costs delegates to Holding
app/models/holding.rbHolding.preload_avg_costs — the P40 batch, lifted so both callers share it
app/models/portfolio/section_registry.rbrealized_gains section, its bar payload, year-carrying axis ticks
app/models/trade.rbpreloaded_holdings= writer that clears the realized_gain_loss memo
app/models/user.rbdefault_portfolio_section_order reads SectionRegistry::KEYS so the lists cannot drift
app/controllers/reports_controller.rbAssigns through the writer instead of instance_variable_set
app/views/portfolios/_realized_gains.html.erbNew partial
config/locales/views/portfolios/en.ymlNew strings
config/locales/views/portfolios/de.ymlGerman for the new strings
config/portfolio_contract_tests.ymlP41 citations
docs/portfolio/methodology.mdP41
test/models/portfolio/realized_gains_test.rb13 tests
test/controllers/portfolios_controller_test.rbRender coverage for the partial
test/models/portfolio/section_registry_test.rbSection ordering, axis ticks
test/models/trade_test.rbThe writer clears the memo
test/models/user_test.rbDefault order follows KEYS
test/support/portfolio_returns_test_helper.rbsell_trade, holding_snapshot

app/javascript/controllers/bar_chart_controller.js is not in the diff. An earlier revision changed it; b2e11366 reverted that, and the partial uses the shared controller as it stands.

Evidence checklist

  • Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
  • Contract rows touched by this change name existing tests — none are touched; no row is added and EXPECTED_ROWS is unchanged.
  • Any gate test has an observed failing mutation transcript attached — not done. See Validation.
  • Fixtures used as evidence assert internal consistency — holding_snapshot carries an explicit cost_basis so every expected figure is hand-computable (2 shares, average 100, sold at 150 → 300 proceeds against 200 basis → 100).
  • Financial calculations use BigDecimal and documented rounding points — BigDecimal throughout; Money only at the view edge; the only rounding is .to_f.round(2) on the chart payload, which is presentation.
  • De-identification uses token-shape allowlists; no personal data is included.
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented here.

Validation

CheckResult
ruby -c on all changed Ruby filesSyntax OK
config/locales/views/portfolios/en.yml parses; keys resolveVerified with yaml.safe_load
bin/rails test (portfolio, trade, holding, investment_statement, portfolios_controller, reports_controller, i18n)282 runs, 1255 assertions, 0 failures
bin/rubocop2093 files, no offenses
bin/rails portfolio:verify_contract_coverage41 methodology and 17 returns rows verified

Superseded. The suite now runs, in the repository's own dev container (sure_devcontainer-app-1), on the pinned Ruby 3.4.9 against its Postgres. The note below records why an earlier environment could not, and is kept only so the claim it replaces is not silently dropped:

  • No gems are installed at all. bundle check reports the full dependency set missing; the only gem ABI present is 3.3.0.
  • .ruby-version pins 3.4.9, and it cannot be built here — rbenv install 3.4.9 fails with curl: (22) 403 on cache.ruby-lang.org, an egress-policy denial the proxy records as connect_rejected. Per the proxy's own guidance, policy denials are reported rather than routed around.
  • No Postgres server is running (client only).

So CI on the pinned Ruby is the authoritative run, and if it is red, that is this PR's to fix.

Risks, blockers, and follow-up

  • No mutation transcript. Done. Each fix in this PR was broken deliberately and the guard watched to fail: removing Holding.preload_avg_costs fails the query-count test with Expected: 9; removing the realized_gain_loss memo clear from preloaded_holdings= fails with NoMethodError: undefined method 'value' for nil; forcing visible: false fails the render test with found 0; pinning the axis tick to "%b" fails with two identical Mar labels. (Original note:) The checklist item above is unticked for that reason, and it is part of why this is a draft. The mutations the plan named — drop the internal-movement filter, use today's FX, fold an unpriced trade to zero, remove the holdings preload — each need a real runner. The route is CI scratch branches; that costs CI runs on your repo and I have not started it without your word.
  • The query-count tests assert constancy, not a number. 2 disposals and 6 must cost the same. There are now two: one over a stored cost basis, and one over holdings with none — the provider-synced case, where Holding#avg_cost used to fall back per security (measured: 9 queries for 2 disposals, 21 for 6). The second is the one that fails if the batch is removed.
  • bar_chart_controller is untouched. The partial mounts it as it stands; the earlier generalisation of it was reverted in b2e11366. Losses therefore render in that controller's gray rather than a destructive red — an open decision for the owner, not an oversight.
  • I18n.l(bucket.month, format: "%b") mirrors PagesController#build_money_flow_data exactly, including the short-label fallback for locales where %b %Y is not short. en.yml and de.yml both gain the strings — every other hub section is translated in de.yml, so this one is too. Other locales fall back, which is the convention here.
  • The light-touch Gatekeeper review landed (CLAUDE.md step 4) and found no blockers. Its one concrete finding — verify :short_month_year is a real I18n.l format, since a typo would surface at render time rather than in CI — is declined with evidence: config/locales/defaults/en.yml:57 defines en.date.formats.short_month_year: "%b %Y", and eleven other locales define it too. Its UX question about visible: realized_gains.any? is open for the repository owner. (An earlier revision of this section said no review had landed; it had not at the time of writing, and it has since.)
  • Follow-up opened: #169 — a realised gain is understated for a foreign-listed holding. Trend#value is current - previous, and Money#- neither converts nor raises across currencies, so Trade#calculate_realized_gain_loss subtracts a basis in the holding's currency from proceeds in the trade's. Measured: a USD account holding a EUR-listed security reports 150 USD of gain where the correct figure is 250 — a 40% understatement. The arithmetic belongs to Trade, which Reports shares, so it is not fixed here. This PR declines to print it instead: such a disposal is excluded as :mixed_currency and surfaced to the user, alongside missing_cost_basis and missing_exchange_rate (671b5aaf).
  • Follow-up opened: #167 — ReportsController#build_gains_by_tax_treatment and Portfolio::RealizedGains now compute the same figure by different rules (a nil basis folds to zero there and is excluded here; FX falls back to parity there and is refused here; different account scopes), so the same period can show two totals. Backfilling Reports was out of scope here; #167 carries it, along with the pre-existing Trend#value currency pairing.
  • Next unblocked issue: 2.4, once #164 and #165 settle. #151 and #142 remain needs:design, and #158 is explicitly gated behind #142 Phase 1.