Add a realised P&L timeline to the portfolio hub
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.
- A transfer out looks exactly like a sale. Both carry a negative
qty, so a bareqty < 0filter books the full market value of every position a user moved between their own accounts as a realised gain.Trade::INTERNAL_MOVEMENT_LABELSis filtered in SQL — and note it is deliberately narrower thanTransaction::INTERNAL_MOVEMENT_LABELS, which also carriesExchange; a security-for-security exchange can genuinely dispose of an appreciated asset. - 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.
- A missing rate is not a rate of 1.
- 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
mainat6ef977d - Does not collide with the PRs in flight. #164 and #165 both edit
performance.rb; this touches neither it norreturn_scope.rb, so it can land in any order relative to them. 2.4 is deliberately not in this PR: it rendersmetrics[: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_lossis average-cost at time of sale, and changing the cost method is its own decision); backfilling the Reports card onto this model; bucketing that followsPeriod#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_ROWSis 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.
| File | Change |
|---|---|
app/models/portfolio/realized_gains.rb | New 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.rb | Holding.preload_avg_costs — the P40 batch, lifted so both callers share it |
app/models/portfolio/section_registry.rb | realized_gains section, its bar payload, year-carrying axis ticks |
app/models/trade.rb | preloaded_holdings= writer that clears the realized_gain_loss memo |
app/models/user.rb | default_portfolio_section_order reads SectionRegistry::KEYS so the lists cannot drift |
app/controllers/reports_controller.rb | Assigns through the writer instead of instance_variable_set |
app/views/portfolios/_realized_gains.html.erb | New partial |
config/locales/views/portfolios/en.yml | New strings |
config/locales/views/portfolios/de.yml | German for the new strings |
config/portfolio_contract_tests.yml | P41 citations |
docs/portfolio/methodology.md | P41 |
test/models/portfolio/realized_gains_test.rb | 13 tests |
test/controllers/portfolios_controller_test.rb | Render coverage for the partial |
test/models/portfolio/section_registry_test.rb | Section ordering, axis ticks |
test/models/trade_test.rb | The writer clears the memo |
test/models/user_test.rb | Default order follows KEYS |
test/support/portfolio_returns_test_helper.rb | sell_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_ROWSis unchanged. - Any gate test has an observed failing mutation transcript attached — not done. See Validation.
- Fixtures used as evidence assert internal consistency —
holding_snapshotcarries an explicitcost_basisso every expected figure is hand-computable (2 shares, average 100, sold at 150 → 300 proceeds against 200 basis → 100). - Financial calculations use
BigDecimaland documented rounding points —BigDecimalthroughout;Moneyonly 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
| Check | Result |
|---|---|
ruby -c on all changed Ruby files | Syntax OK |
config/locales/views/portfolios/en.yml parses; keys resolve | Verified with yaml.safe_load |
bin/rails test (portfolio, trade, holding, investment_statement, portfolios_controller, reports_controller, i18n) | 282 runs, 1255 assertions, 0 failures |
bin/rubocop | 2093 files, no offenses |
bin/rails portfolio:verify_contract_coverage | 41 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 checkreports the full dependency set missing; the only gem ABI present is3.3.0. .ruby-versionpins 3.4.9, and it cannot be built here —rbenv install 3.4.9fails withcurl: (22) 403oncache.ruby-lang.org, an egress-policy denial the proxy records asconnect_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_costsfails the query-count test withExpected: 9; removing therealized_gain_lossmemo clear frompreloaded_holdings=fails withNoMethodError: undefined method 'value' for nil; forcingvisible: falsefails the render test withfound 0; pinning the axis tick to"%b"fails with two identicalMarlabels. (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_costused 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_controlleris untouched. The partial mounts it as it stands; the earlier generalisation of it was reverted inb2e11366. 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")mirrorsPagesController#build_money_flow_dataexactly, including the short-label fallback for locales where%b %Yis not short.en.ymlandde.ymlboth gain the strings — every other hub section is translated inde.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_yearis a realI18n.lformat, since a typo would surface at render time rather than in CI — is declined with evidence:config/locales/defaults/en.yml:57definesen.date.formats.short_month_year: "%b %Y", and eleven other locales define it too. Its UX question aboutvisible: 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#valueiscurrent - previous, andMoney#-neither converts nor raises across currencies, soTrade#calculate_realized_gain_losssubtracts 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 toTrade, which Reports shares, so it is not fixed here. This PR declines to print it instead: such a disposal is excluded as:mixed_currencyand surfaced to the user, alongsidemissing_cost_basisandmissing_exchange_rate(671b5aaf). - Follow-up opened: #167 —
ReportsController#build_gains_by_tax_treatmentandPortfolio::RealizedGainsnow 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-existingTrend#valuecurrency 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.