Add a net contributions series to the account chart model

Closed
JA
18d ago
+7604-470

Updated 2026-11-15: rebased onto the new portfolio stack. #4197 and #4198 were replaced by #5088 and #5089 (native stack #5133, rebased onto main; fork pre-flights jaysbeekay/sure#707 and jaysbeekay/sure#708). This branch is now one commit, 91375e09d, on top of up/portfolio-journal-flows-v3 (#5089). Its content equals the previous head (5000c1301) with main merged in, exactly; the earlier commit subjects are listed in its message. Its own diff is unchanged: the six files below. It stays a PR against main, so until #5088 and #5089 merge its diff includes them. To review this slice alone: up/portfolio-journal-flows-v3...up/net-contributions-model. Portfolio, balance and chartable tests on 91375e09d: 330 runs, 0 failures. Older notes below refer to #4197 and #4198, which are superseded.

Updated 2026-11-05. 8aa846b5b merges #4198's head, bringing #4197's bound-value marker fix (11bb8a1bd, 0e334559a) and upstream main (529d7de76). One conflict: upstream's sparkline cache key (#4675) and this PR's net contributions helpers both added private methods to Account::Chartable, and both are kept. No other change to this PR's own files. To review this slice alone: up/portfolio-journal-flows-v2...up/net-contributions-model. Merge bottom-up; main is merged down after each one. Full suite on 8aa846b5b: 14,802 runs, 0 failures, 0 errors.

Rebuilt on 2026-10-08. This branch was replaced in place: the feature and its public methods are the same, but the series now reads its flows from Portfolio::DailyReturns, so the line and the portfolio's returns value money the same way. The previous version (b1b83c131) had no reviews. The reason is under "Why it was rebuilt" below.

Rebased onto main (3e35aaa07) on 2026-10-13. #3557 has merged, so its commits are gone.

Updated 2026-10-14.

  • a36cd426b merges #4198's branch at b2b6981e8. It also brings upstream main a3bb5d991 (the branch was on 3e35aaa07). This branch's daily_returns.rb and its test were an older copy of #4198's (before the post-binding splice). The add/add conflict was resolved by taking #4198's version: the only tests dropped were the two that #4197 deliberately replaced. After the merge, this PR's diff on top of #4198 is again only its own six files (chartable.rb, chart_series_builder.rb, linked_investment_series_normalizer.rb and their tests).
  • 8e5c9266c updates two ChartSeriesBuilder tests that pinned the old flow rules. An excluded deposit now counts (a pending one still does not), and a foreign deposit converts into the account's currency on its own date. The class comment says the same.

Updated 2026-10-23. 2ca797345 merges #4198 at fc400f58f, which carries #4197 at c285e4a49 and the returns engine review fixes since 2026-10-15. No change to this PR's own files, and no net contributions test expectation changed. Net contributions, chart and portfolio model tests on 2ca797345: 306 runs, 0 failures. Full suite on #4029 at b6b9791da, which contains this head: 13,082 runs, 0 failures, 0 errors, 36 skips.

Updated 2026-10-15. f41a201b4 merges #4198 at 1c42bcef9, which carries #4197's review fixes. The net contributions line reads Portfolio::DailyReturns, so a security journalled in before the line's start and first priced inside it now counts as a contribution on that day, as the returns engine counts it. No change to this PR's own files.

Stacked on #5088 (daily returns, fork pre-flight jaysbeekay/sure#707) and #5089 (journal flows, fork pre-flight jaysbeekay/sure#708), in native stack #5133. They replace #4197 and #4198. This branch carries the same commits, so GitHub shows them here as well. On top of #4198's head (1c42bcef9), this PR's diff is six files: Account::Chartable, Balance::ChartSeriesBuilder, Balance::LinkedInvestmentSeriesNormalizer and their tests. This PR's own commits:

  • d0efa5a2d Add a net contributions series read from the daily returns
  • 7b31fb7a0 Cover arrivals, empty days and anchor-day flows in net contributions
  • ae735f220 Count the anchor day's flows in a linked account's contributions
  • 3cf9b844c Test how the chart reads the value line's anchor point
  • fff5d3855 Report an unvalued anchor-day flow as understated
  • f87a751af Re-express the anchor-day chart tests on #4009's reset
  • 8fc7f6aed Read the anchor point by the normalizer's rule, not its value
  • 1fb0df306 Pin that only the supported start date can be reset
  • 0ca4e5360 Name the unvalued-flow check for what it knows: incomplete
  • 8e5c9266c Follow the returns engine's flow rules in net contributions

The chart that draws this series is a separate PR stacked on this one (#4029, fork pre-flight jaysbeekay/sure#344), rebased the same way.

Part of #4008

Fork pre-flight PR: jaysbeekay/sure#343 (pull/343), same branch, same commit (up/net-contributions-model at 2ca797345)

#4009 is in. On a linked account's first provider-activity date, #4009 resets the value line's point to the balance before that day's activity. The contributions line opens at the balance held before that activity too, and counts the day's flows from the next point, so the gap there is the day's market move (jaysbeekay/sure#382). That reset point can equal the day's close, when a flow is offset by the market. So the line no longer decides by comparing values. It asks the normalizer, whose new resets_point_on?(date) is the same predicate normalize uses for the reset. 0ca4e5360 renames net_contributions_understated? to net_contributions_incomplete? (jaysbeekay/sure#383). An unvalued withdrawal pushes the line up, not down, so "understated" named a direction the check never computes. The conditions are unchanged.

Summary

This adds the model side of #4008: a "net contributions" series for an investment account. It shows how much has been put into the account, net of what was taken out, on the same dates as the Total value line. Nothing is drawn yet. The chart PR that follows uses this series.

Why it was rebuilt. The first version had its own query: a journalled security counted at its trade amount, and a foreign-currency flow converted at its entry date's rate. Portfolio::DailyReturns values the same flows differently: a journal at the position's value that day, and a flow at the previous day's rate, because a flow joins the start of the day (since 8e5c9266c, a foreign flow first converts into the account's currency on its own date; see "How flows are valued"). Two valuations meant the gap between the value line and this line could disagree with the return the portfolio reports for the same period. This PR reads the flows from Portfolio::DailyReturns instead, so there is one valuation and no second copy of the flow rules.

What changed

Balance::ChartSeriesBuilder#net_contributions_series(anchor_date: nil, dates: nil)

  • Starts from the opening value of the accounts' first balance row, then adds every day's external_flow and composition_flow from Portfolio::DailyReturns, which is always daily. The total is sampled on the value line's dates. It is anchored at the account's start, not the period's, so a period that starts late still opens at everything put in so far.
  • What counts as external is decided by Portfolio::FlowClassifier (#3557) inside DailyReturns, with the builder's accounts as the scope. Deposits, withdrawals, transfers from outside the scope and securities moved in or out move the line. Dividends, interest, fees, buys and sells don't.
  • An account that joins a multi-account scope later brings its opening value in on its first balance date, through DailyReturns' composition flow.
  • anchor_date (for a linked account's trimmed value line) opens the line at that day's closing value and adds only later flows.

Balance::ChartSeriesBuilder#net_contributions_incomplete?(anchor_date: nil, dates: nil)

  • True when a flow the line counts could not be valued. It reads the same rows: rate_missing, or a suppressed day with a positive denominator, which is a journal with no price that day. A day suppressed only because nothing was invested is not counted. The two methods share one memoized DailyReturns query.

Account#balance_series(view: :net_contributions) and Account#net_contributions_incomplete?

  • The series is sampled on the Total value line's own dates.
  • For a linked investment account whose value line is trimmed to supported history, the line starts on the trim date at that day's closing value. On a coarse interval, where the normalizer adds a synthetic opening point, the line starts from that same point.
  • The builder is memoized per period and interval, as before, through a private chart_series_builder helper. The incomplete check shares it.

How flows are valued (all from Portfolio::DailyReturns):

  • A deposit or withdrawal at its cash amount.
  • A security journalled in or out (a Transfer-labelled trade with amount: 0) at the position's value that day, from the holdings row.
  • A foreign-currency flow as the balance took it (since 8e5c9266c): into the account's currency on its own date, preferring the entry's own extra["exchange_rate"], then into the family's currency at the previous day's rate. A foreign-currency opening value at the previous day's rate. A date with no rate takes the last known one, or the earliest one after it.
  • An inbound journal with no price on its own day is booked on the first later day in the period on which its holding has a price (#4198, 8cb179e86). One dated before the period is booked on its first priced day inside the period (#4198, 1c42bcef9).
  • A flow is left out only when its currency has no rate at all, or a journal has no price that day and is not carried. The incomplete check returns true for either, and for an unpriced journal's own day even when it is carried. That holds for a deposit, which leaves the line too low, and for a withdrawal, which leaves it too high.

Differences from the first version's tests. Kept by name where the behaviour is the same. Changed:

First version's testHereWhy
a foreign-currency deposit converts at its entry date's rate (expects 2,200)a foreign-currency deposit converts into the account's currency on its own date (expects 2,200)Since 8e5c9266c, DailyReturns converts a foreign flow as the balance took it: into the account's currency on the deposit's own date (1.2), then into the family's currency at the previous day's rate (1 for a USD account). Rates: 1.1 the day before, 1.2 on the day. Before 8e5c9266c this test converted at the previous day's rate and expected 2,100.
an opening value in another currency converts at its date's ratean opening value in another currency converts at the previous day's rate (1.5 the day before, 1.6 on the day, expects 1,500)the opening value is a start-of-day balance, valued at the previous day's rate; 8e5c9266c does not change this test
a security journalled in or out counts at its trade amounta security journalled in or out counts at its position valuea journal is valued from the holdings price. Same figures (1,500, then 1,260). The fixture is now the amount: 0 journal shape. A Transfer-labelled trade that carries a cash amount is not a journal and flows at that amount.
a flow with no rate for its date is left out and makes net contributions incomplete (1,500, incomplete)a flow with no rate on its own date is valued at the last known rate (2,600, not incomplete)DailyReturns carries the last rate forward. "Left out" now means a currency with no rate at all, which "net contributions say when a flow could not be valued" covers.
net contributions follow the issue's examplenet contributions open at the opening value and step up by a deposit on its datesame fixture and figures

Added: "a fee, a buy and a sell leave net contributions unchanged" (beside the first version's "fees, interest, buys and sells"), "a security journalled in counts at its value", "an unpriced journal makes net contributions incomplete", "an account that joins the scope later adds its opening value on its first balance date", "an empty opening day does not make net contributions incomplete", "an unvalued flow on an explicit anchor day makes the line incomplete", "an unvalued withdrawal makes net contributions incomplete and leaves the line higher". With no rate the check is true, and the line reads 1,100 higher than the same history with the withdrawal valued.

Demo data

No demo data change needed. From the generator's code, the demo HSA account's quarterly transfers from checking should step the line up, and the other demo investment accounts, which only record buys, should keep it at the opening value. I haven't checked this on a running demo instance.

Screenshots

None. This PR has no UI. The chart PR has them.

Migration notes

No migration.

Verification

  • test/models/account/chartable_test.rb and test/models/balance/, measured before 2026-10-14 (on 0ca4e5360 or earlier): 146 runs, 0 failures.
  • I broke each part on purpose and reran those two files. A test caught every break:
BreakageCaught by
Explicit anchor opens at open plus flows, not the anchor day's closeanchor test + 2 linked Chartable tests
Composition flow droppedaccount joins the scope later
External flow dropped16 tests
First day's flows not addeddeposit on the first balance day
Incomplete ignores rate_missingflow could not be valued + Chartable incomplete test
Incomplete ignores the unpriced journalunpriced journal test
Incomplete counts every suppressed dayempty opening day
Anchor day's flows counted for incompleteunvalued flow on an explicit anchor day
Incomplete reads past the sampled datesflow after the sampled dates
Anchor ignoredanchor test + 2 linked Chartable tests
Chartable passes no anchor2 linked Chartable tests
Chartable keeps the builder's point on the anchor datecoarse-interval test
Chartable's trend reads the builder's points, not the replaced onescoarse-interval test
:net_contributions view not accepted3 Chartable tests (ArgumentError)
DailyReturns converts flows at the entry date's rateprevious day's rate test (run before 8e5c9266c, which replaced that test with "a foreign-currency deposit converts into the account's currency on its own date")
DailyReturns converts the opening value at the first day's own rateopening value test
DailyReturns stops valuing journalsboth journal tests
Chartable reads #4009's reset point by its value again"reset anchor point equals the day's close" test ([1500, 1800] for [1000, 1800]) + anchor point test + 3 linked Chartable tests
resets_point_on? drops the first-activity checkholdings-inception Chartable test + normalizer holdings test
resets_point_on? drops the supported-start checkresets_point_on? normalizer test
Chartable stops reading a prepended point as before activityanchor point test
Incomplete check ignores rate_missing (withdrawal case)"an unvalued withdrawal makes net contributions incomplete and leaves the line higher"
Account delegator returns false2 Chartable incomplete tests

Commands, on 0ca4e5360 (on main 3e35aaa07):

  • bin/rails test: 11875 runs, 54630 assertions, 0 failures, 0 errors, 34 skips
  • bin/rubocop on the changed files: no offenses
  • bundle exec erb_lint: not applicable (no ERB)
  • npm run lint: not applicable (no JS)
  • bin/brakeman: no warnings

On 8e5c9266c (2026-10-14):

  • targeted tests (portfolio, balance, chartable): 271 runs, 0 failures
  • bin/brakeman: no warnings

On f41a201b4 (2026-10-15):

  • targeted tests (portfolio, chart model, investment statement): 313 runs, 0 failures
  • bin/rails test: see #4029 (on 87cdb576e, which contains this head)

Blast radius

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

  • Account#balance_series is called by Assistant::Function::GetAccounts, Loan::PayoffChart and UI::Account::Chart, always with a balance view or none. They take exactly the path they took before. Only view: :net_contributions returns early. The memo key and builder arguments are unchanged, and the existing "generates series and memoizes" test passes unchanged.
  • Balance::ChartSeriesBuilder is also built by Goal, Assistant::Function::GetBalanceSheet, Balance::LinkedInvestmentSeriesNormalizer, BalanceSheet::NetWorthSeriesBuilder, BalanceSheet::NetWorthBreakdownSeriesBuilder and AccountableSparklinesController. None of them calls the new methods, and the balance and gains queries are untouched.
  • This makes Balance::ChartSeriesBuilder the first caller of Portfolio::DailyReturns (grep -rn "DailyReturns.new" app finds only this one). It passes the builder's account_ids, its currency (the account's own, for the account chart) and its account_active_until_dates, over a custom period from the first balance (or the anchor) to the last sampled date.

What else reads what this changes the reading of?

  • InvestmentStatement#net_contributions (buys minus sells, for a period) and Goal#net_contributed_for (balance minus market flows) use the same words for other measures. Both are left unchanged. Neither reads the classifier, and changing either would move figures that existing pages show.
  • Assets only. The line is drawn only for accounts that support trades, which are all assets, so no liability sign is applied.

Rebased onto main. As expected, three Chartable tests asserted the day's close as the value line's first point on the first provider-activity date. With #4009 that point is the balance before the day's activity, so f87a751af updates their figures. The contributions line already opened at the balance before that activity, so the gap is the day's market move from the next point, as on the coarse-interval path. The one gap #4009 left, a reset point that equals the close, is fixed in 8fc7f6aed with a test that fails without it.

The disabled-account cutoffs (account_active_until_dates) that the first version's query ignored are passed through to DailyReturns here, so an account's flows after its cutoff don't move the line.

Updated 2026-10-25. This branch's own commit messages were rewritten to drop references to the fork's issues and reviews, and comments that cited issue history now describe behaviour instead. No code changed apart from those comments. Commit SHAs quoted above predate the rewrite. The branch also merges current main.

Summary by CodeRabbit

  • New Features
    • Added a net contributions view to balance charts, showing cumulative contributions over time alongside account balances. The series reflects deposits, withdrawals, and transfers while excluding investment activity such as dividends, fees, interest, and trades.
    • For linked investment accounts, the view is anchored to the available investment-history start date and aligned with balance-history dates. It can indicate when some contributions could not be valued.