Add family-wide investment value, holdings and gains series

Closed
JA
11d ago
+975-25

Part of #4078

Part of #3494

What: adds family-wide investment series: InvestmentStatement#value_series, #holdings_value_series and #gains_series. Each charts the family's Investment and Crypto accounts together over a period, in the family currency, the way net worth charts every account, cached under the family key plus share, holdings, currency and accounts versions. Two helpers shared with the net worth charts are pulled out first: BalanceSheet::HistoricalAccountScope.active_until_dates (a disabled account's cut-off) and Balance::LinkedInvestmentSeriesNormalizer.trim_to_supported_history.
Why: a portfolio chart and the return calculations need a daily family-wide value, and nothing provides one. Nothing is drawn yet.
Start reading: InvestmentStatement#value_series and fetch_series in app/models/investment_statement.rb, then InvestmentStatement::HistoricalScope.
Key tests (test/models/investment_statement_test.rb, test/models/investment_statement/historical_scope_test.rb):

  • "value_series sums the per-account balance series on every date of the period"
  • "value_series is historical where portfolio_value is live, so a closed account diverges"
  • "a closed broker keeps its history before a newer broker's first activity"
  • "every series cache key is reused while nothing it reads changes"
  • "active_until_dates covers only disabled accounts, cut off the day before disabling"

Behaviour change: none visible. The scope is historical, like net worth's: a disabled broker keeps its history up to the day before it was disabled, so the series' last point can differ from portfolio_value. The net worth builders now call the shared cut-off helper with the same body, and the linked-sparkline aggregate's first point gets a flat trend after a trim (the sparkline does not show per-point trends). No migration.

Size: +245 / −22 outside tests, across 6 files.
Fork pre-flight: jaysbeekay/sure#362 (same branch; merged on the fork).

Full description and evidence

Updated 2026-11-05. Upstream main (529d7de76) is merged in. No change to this PR's own files. Full suite on 53516edb1: 14,686 runs, 0 failures, 0 errors.

Summary

This adds a family-wide value series for investments: InvestmentStatement#value_series, #holdings_value_series and #gains_series. Each charts the family's Investment and Crypto accounts together over a period, in the family currency, the same way the net worth series charts every account. Nothing is drawn yet. A later portfolio chart, and return calculations that need a daily value, read these series.

The design choice to know about: the account scope is historical, like net worth's. A disabled broker keeps its history up to the day before it was disabled. So the series' last point can differ from portfolio_value, which only sees visible accounts, when a disabled account still had a balance before its cut-off. Closing an account shouldn't change what the family held last March.

Two helpers that the series shares with the net worth charts come first, as a separate commit:

  • 01cc0134d Share the cut-off and supported-history trim helpers
  • 49d431a40 Add family-wide investment value, holdings and gains series
  • 39c1df5a7 Refresh the series cache when a provider link is removed (from review: an unlink clears account_provider_id without touching updated_at, and the supported-history trim reads that column)
  • 8401948d2 Pin the hand-worked totals in the value series test (from review: the sum comparison builds its expectation with the same Balance::ChartSeriesBuilder the statement calls)
  • 0c4a00af3 Key portfolio series on family currency and accounts (from review: a currency change, or deleting an account with no holdings that isn't the newest, moved nothing in the key)
  • ac92684d4 Test that portfolio series keys are reused when nothing changes

What changed

BalanceSheet::HistoricalAccountScope.active_until_dates(accounts) (new class method)

  • Returns { account_id => date } for each disabled account: the day before disabled_at, or before updated_at when disabled_at is unset. Active and draft accounts are left out.
  • BalanceSheet::NetWorthSeriesBuilder and BalanceSheet::NetWorthBreakdownSeriesBuilder each had a private copy of this rule. Both now call this method, with the same body, so the three charts drop a closed account on the same day.

Balance::LinkedInvestmentSeriesNormalizer.trim_to_supported_history(series, account_ids:) (new class method)

  • The trim aggregate_account_ids already applied to its own balance series, pulled out so a caller that builds its own series can use it. It drops the points before the date every linked account in account_ids has real history for. An unlinked account has no such date, so the series is returned untouched.
  • After a trim, the new first point gets a flat trend (flatten_first_trend, public on the class). Its old trend compared it with a point the chart no longer draws.
  • aggregate_account_ids now calls it. The instance-level #normalize isn't touched.

InvestmentStatement::HistoricalScope (new)

  • #accounts: BalanceSheet::HistoricalAccountScope#relation limited to Investment and Crypto. That's the same relation net worth uses, so it includes disabled and draft accounts, excludes accounts excluded from reports or pending deletion, and with a user applies included_in_finances_for. It loads once per instance.
  • #account_ids, and #active_until_dates from the helper above.

InvestmentStatement#value_series, #holdings_value_series, #gains_series (period: defaults to Period.last_30_days)

  • Each builds Balance::ChartSeriesBuilder over historical_scope.account_ids, with account_active_until_dates: historical_scope.active_until_dates, and calls balance_series, holdings_balance_series or gains_series.
  • The result goes through trim_to_supported_history for the scope's accounts, so a linked broker's zero rows before its first snapshot aren't charted.
  • #historical_scope is public, so later model code can use the same accounts and cut-off dates.

Caching

  • Rails.cache under family.build_cache_key(..., invalidate_on_data_updates: true), as the net worth series does. The key also carries:
    • a share version (count and latest updated_at), because revoking a share deletes a row, which moves neither timestamp in the family key.
    • a holdings version, because the gains series reads holdings.cost_basis, which a manual edit rewrites in place, and the trim reads provider holdings.
    • family.currency, because every series is converted to it, and a profile currency change neither syncs nor writes an account.
    • Family#accounts_status_version (account count and latest updated_at, as the transactions index caches use), because deleting an account with no holdings that isn't the most recently updated one moves neither timestamp in the family key nor the holdings version.
  • A per-instance memo per kind and period, so a render that asks for the same series twice runs one query.

Demo data

No demo data change. There is no UI to show it on yet.

Screenshots

None. No UI.

Migration notes

No migration.

Verification

The tests were written to fail first. With the app files reset to main (00dd977fb), the 19 new series and scope tests error, because the methods and the scope class don't exist there. Two other new tests pass on main on purpose. They pin behaviour this PR must not change: aggregate_account_ids still trims, and the breakdown builder still cuts a disabled account off. The breakages below show both are live.

New tests:

  • test/models/investment_statement_test.rb:
    • value_series equals the sum of the per-account series on every date. Three accounts (USD, EUR at a stored rate, and one disabled). The expected cut-off is worked out in the test, separately from HistoricalScope. The totals are also pinned by hand (1900 on the three days up to the disabled account's cut-off, 1800 on the three after), because the sum comparison shares Balance::ChartSeriesBuilder with the code under test.
    • a disabled account counts on its cut-off date and not the day after
    • the series is historical where portfolio_value is live, so they differ for a closed account
    • an empty family gets a zero series
    • a linked account's zero rows before its first provider activity aren't charted
    • holdings_value_series and gains_series call the matching builder method
    • the builder is built once per period per instance
    • the cache key changes when a share is revoked, when a cost basis is edited by hand, and when a holding is deleted (for every series kind)
    • every series cache key changes when the family currency changes, and when an account without holdings is deleted; both failed before the fix, on 6075b20f1, with identical keys
    • every series cache key is reused while nothing it reads changes (the negative case: a key that moved on every request would pass the tests above)
  • test/models/investment_statement/historical_scope_test.rb: the types and statuses in scope, cut-off dates (with and without disabled_at), draft accounts having no cut-off, a share without include_in_finances, and one accounts query per instance
  • test/models/balance/linked_investment_series_normalizer_test.rb: trim_to_supported_history drops the leading points, flattens the first trend and leaves an unlinked series untouched. aggregate_account_ids still trims, and Series#trend, which the sparkline renders, is taken from the trimmed points.
  • test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb: a disabled account counts in the month before its cut-off and not after

I also broke each part on purpose and reran the affected test files. A test failed for every break, with no errors:

BreakageCaught by
Cut-off on the disabled day, not the day before5 tests, incl. the net worth series test already on main
disabled_at ignored (always updated_at)4 tests, incl. the breakdown test
Cut-off given to every account4 tests, incl. net worth and the draft-account test
Trim keeps the stale first trendtrim test
aggregate_account_ids skips the trimaggregate test
Series not trimmedleading-zeros test
Builder gets no cut-off dates2 series tests
Scope not limited to Investment/Cryptoscope types test
Scope reads visible accounts only7 tests
Scope ignores the usershared-account test
Cache key without the holdings version3 cache key tests
Cache key without the share versionshare-revoked test
Cache key without family.currencycurrency-change test
Cache key without the accounts versionaccount-deletion test
Accounts version reduced to the latest updated_at (no count)account-deletion test
Accounts version made to vary per requestkey-reused test
No per-instance memomemo test
holdings_value_series / gains_series read the balance seriesthe matching delegation test
value_series ignores its period2 series tests
NetWorthSeriesBuilder passes no cut-offnet worth series test already on main
NetWorthBreakdownSeriesBuilder passes no cut-offbreakdown test
Balance::ChartSeriesBuilder drops the FX rate from end_balancethe hand-worked totals in the value_series sum test (the sum comparison alone still passes, since both sides move)

Commands, on ac92684d4:

  • bin/rails test: 11,846 runs, 54,632 assertions, 0 failures, 0 errors, 34 skips
  • bin/rubocop -f github on the changed files: no offenses
  • bundle exec erb_lint: not applicable (no ERB)
  • npm run lint: not applicable (no JS)
  • bin/brakeman --no-pager -q: no warnings

Size: 209 added and 18 removed in app/, 492 added in test/.

Blast radius

Who else hits these lines, and what do they pass?

  • BalanceSheet::HistoricalAccountScope.active_until_dates. Called by NetWorthSeriesBuilder with its historical accounts and by NetWorthBreakdownSeriesBuilder with each group's accounts, the same lists they passed to their private copies. The body is the one both copies had, so net worth output is unchanged. test/models/balance_sheet_test.rb's "net worth series preserves disabled history" test, already on main, passes unchanged and fails if either builder stops passing the cut-off.
  • Balance::LinkedInvestmentSeriesNormalizer.aggregate_account_ids. Its only caller is AccountableSparklinesController#aggregate_normalized_series, for linked Investment/Crypto sparklines. The points it keeps and their values are unchanged. The only difference is the first kept point's own trend after a trim, now flat. A per-point trend is read only by the chart tooltip, and shared/_sparkline renders with use-tooltip-value: false. The figure next to the sparkline is Series#trend, which compares the first and last values, so it's unchanged too. aggregate_accounts delegates to it and has no other callers.
  • Balance::LinkedInvestmentSeriesNormalizer#normalize (the per-account chart) isn't touched.
  • Balance::ChartSeriesBuilder isn't touched. The new series pass it the same arguments the net worth builder does.

What else reads what I changed the reading of? git grep -n "disabled_at ||\|ChartSeriesBuilder.new" over app/:

  • BalanceSheet::NetWorthSeriesBuilder and BalanceSheet::NetWorthBreakdownSeriesBuilder: the two copies of the cut-off rule. Both now use the helper.
  • Account::Chartable: a single account, already trimmed by #normalize. Unchanged.
  • Assistant::Function::GetBalanceSheet#historical_data and Goal#balance_series_values: they read visible accounts only, so there's no disabled account to cut off. Unchanged.
  • AccountableSparklinesController#build_series: unlinked sparklines, visible accounts, no trim. Unchanged.

Review round, 2026-11-06 (head ef384c1be)

  • 64bc09be2: the family value, holdings-value and gains series trim only the dates before any linked account has history (trim_to_supported_history(..., history_start: :earliest)). A broker closed before a newer one linked keeps its points, and so does an open older broker. The accountable sparkline aggregate keeps the common start. Full suite: 14691 runs, 0 failures.
  • ef384c1be: the series cache key now carries the history trim (series_history_start, which fetch_series also reads), so series cached under the common start are not served after the switch. The test fails first; dropping the token, or hard-coding the trim in fetch_series, fails it. Full suite: 14692 runs, 0 failures.

Summary by CodeRabbit

  • New Features
    • Investment history now includes portfolio value, holdings value, and unrealized gains charts, with a default view of the last 30 days.
    • Historical investment and net worth charts retain disabled accounts’ balances through their final active dates.
  • Bug Fixes
    • Investment charts omit values from before an account’s supported history and avoid misleading trends at the start of available history.
    • Historical net worth reflects disabled accounts’ balances only for dates when they were active.