Add a net contributions series to the account chart model

Merged
JA
18d ago
+3448-34

Moved 2026-11-18. we-promise/sure#4028 is closed and replaced by we-promise/sure#5296, which extends the returns stack (bottom: we-promise/sure#5129) on top of we-promise/sure#5285. This pre-flight was merged into the mirror earlier. The re-cut branch has a new pre-flight, #848, stacked on #847. up/net-contributions-model is at 93e678378 in both repositories: only this PR's own commit, replayed onto 9f2ad793f.

Part of #326

Upstream pre-flight for the model half of we-promise/sure#4008. Upstream PR: we-promise/sure#4028 (pull/4028, draft). How the two relate: same commits.

Updated 2026-10-15: the head moved from 8e5c9266c to f41a201b4, a clean merge of #444 at 1c42bcef9, which carries #443's overnight review fixes. Same commits as we-promise/sure#4028. The line reads Portfolio::DailyReturns, so a security journalled in before the line's start and first priced inside it now counts on its first priced day. No change to this PR's own files. Portfolio, balance and chartable tests on f41a201b4: 313 runs, 0 failures. Full suite on #344 at 87cdb576e: 11,939 runs, 0 failures, 0 errors.

Updated 2026-10-14: upstream parents opened as we-promise/sure#4197 (daily returns) and we-promise/sure#4198 (journal flows); this PR is stacked on them.

Updated 2026-10-14 (2), stack fix pass: the head moved from 0ca4e5360 to 8e5c9266c. Same commits as we-promise/sure#4028.

  • a36cd426b merges journal-flows-v2 at b2b6981e8 (#444), which carries #443's 51c7d69c5. That fixes the transfer fan-out raised as B1 in #344's nightly 6172435393: FlowClassifier#sql_joins now gives one row per entry. It also brings the flow FX, excluded-entry and missing-rate fixes and #444's journal carry, and it merges mirror a3bb5d991 (the branch was on 3e35aaa07). This branch's daily_returns.rb and its test were an older copy of #444's, so the add/add conflict was resolved by taking #444's version. The only tests dropped were the two that #443 deliberately replaced. git diff b2b6981e8 8e5c9266c is this PR's six files only.
  • 8e5c9266c updates two ChartSeriesBuilder tests that pinned the old flow rules. An excluded deposit now counts (a pending one does not), and a foreign deposit converts into the account's currency on its own date. The class comment says the same.
  • Evidence. Portfolio, balance and chartable tests: 271 runs, 0 failures. Brakeman reports 0 warnings. The full suite ran on #344's head, which contains this one: 11,932 runs, 54,863 assertions, 0 failures, 0 errors, 34 skips. The root cause (per-leg unique indexes on transfers) is raised separately as jaysbeekay/sure#459 / we-promise/sure#4225.

Rebuilt on 2026-10-08, on the owner's decision. The branch was force-pushed from b1b83c131 (its own flow query, built on we-promise/sure#3557's classifier alone) to fee7d0579, which reads Portfolio::DailyReturns. That makes it single-copy with fork main (Balance::ChartSeriesBuilder, from #337). The base changed from up/pending-sql-parity to up/portfolio-journal-flows (#373), so this diff shows only this PR's two commits. The rebuild was first opened as #380, which is now closed as a duplicate. cubic's thread on b1b83c131 (disabled-account cutoffs) is addressed: the cutoffs are passed to DailyReturns. Follow-ups: #382 (the opening-day anchor once we-promise/sure#4009 is in) and #383 (the "understated" wording).

Updated 2026-10-10: carries the fix for #382. Upstream we-promise/sure#4009 has merged (dd8f7326f on the mirror), which makes #382's defect live on this branch's line. up/net-contributions-model is now at bff73a1c1: #382's two commits from #384 (6b73626f0, 85fd585f4) plus bff73a1c1, which restates this branch's own "an unvalued flow on an explicit anchor day" test: it pinned the behaviour #382 reverses (the anchor day's flows now count, so an unvalued one makes the line understated). chartable_test.rb conflicted; the resolution keeps #382's rewritten tests and this branch's own "understated reports a flow with no rate" test. Fail-first on this branch: twelve #382 tests fail on the code before the fix and pass with it. Full suite on the branch: one failure, the known Provider::OpenaiTest Ruby 3.3 vs 3.4 string; brakeman 0 warnings. Not yet in the branch: #382's deferred flat-anchor-day edge, owned by the upstream-sync PR, and a rebase onto today's upstream main, which this stack still predates.

Updated 2026-10-13: rebased onto upstream main, owner's decision. Force-pushed from 27d8d992d to 1fb0df306, on upstream main 3e35aaa07 (we-promise/sure#3557 merged, so its commits are gone). This PR's base moved from up/portfolio-journal-flows to mirror/upstream-main, so its diff is exactly we-promise/sure#4028's: 18 commits, 9 files. It also fixes the equal-value anchor case from the nightly review 6120517777 (8fc7f6aed); details in comment 6144261361. Full suite on 1fb0df306: 11,874 runs, 0 failures, 0 errors, 34 skips.

The upstream description follows, as posted.


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. we-promise/sure#3557 has merged, so its commits are gone.

Stacked on we-promise/sure#4197 (daily returns, fork pre-flight jaysbeekay/sure#443) and we-promise/sure#4198 (journal flows, fork pre-flight jaysbeekay/sure#444). Each is cut from current main. This branch carries the same commits, so GitHub shows them here as well. On top of we-promise/sure#4198's head (d28a35d4a), 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 we-promise/sure#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

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

Part of we-promise/sure#4008

Fork pre-flight PR: jaysbeekay/sure#343 (pull/343), same commits (up/net-contributions-model at f41a201b4)

we-promise/sure#4009 is in. On a linked account's first provider-activity date, we-promise/sure#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 we-promise/sure#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. 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 (we-promise/sure#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, and 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.
  • A flow is left out only when its currency has no rate at all, or a journal has no price that day. The incomplete check then returns true. 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 at the previous day's rate (expects 2,100)DailyReturns converts a start-of-day flow at the previous day's rate. Rates: 1.1 the day before, 1.2 on the day.
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)same rule for the opening value
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/: 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
DailyReturns converts the opening value at the first day's own rateopening value test
DailyReturns stops valuing journalsboth journal tests
Chartable reads we-promise/sure#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

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 we-promise/sure#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 we-promise/sure#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.

Engine fix round merged down (2026-10-09)

up/portfolio-journal-flows (#373) is merged into this branch with a --no-ff merge (d317bf59f), clean, no force push. It brings the daily returns and journal flows fixes this series reads through Portfolio::DailyReturns:

  • a foreign account whose balance rows are all zero no longer flags a missing rate;
  • a journal valued from a rated holding no longer flags its entry currency's rate;
  • the unused scope_account_ids option is removed;
  • the test fixture refuses amounts finer than the four decimal places balances store.

Nothing in this branch's own code changed, and no fixture here needed adjusting. Targeted tests (portfolio models, chart_series_builder_test.rb, chartable_test.rb): 161 runs, 0 failures.

Updated 2026-10-13.

  • Owner decision, option (a): the equal-value anchor edge from #382 (a reset first point whose value equals the day's close is read as the close) is fixed in this branch at the rebase onto upstream main that brings in we-promise/sure#4009, before we-promise/sure#4028 leaves draft.
  • up/portfolio-journal-flows (#373, 351d120b7) is merged down as 27d8d992d. Full suite at the chain's top (#344, af9a07964): 10,726 runs, 0 failures, 0 errors, 33 skips.

Updated 2026-10-13: #383 fix, new head, new parent pre-flights.

  • #383, new head. 0ca4e5360, a fast-forward from 1fb0df306, renames net_contributions_understated? to net_contributions_incomplete? in Balance::ChartSeriesBuilder and Account::Chartable. The conditions are unchanged. A new builder test pins the case cubic raised on #344: an unvalued withdrawal makes the check true, and the line reads 1,100 higher than the same history with the withdrawal valued.
    • The renamed tests failed first on NoMethodError.
    • Mutations caught: dropping rate_missing (6 tests), dropping the denominator guard (1) and the delegator returning false (2).
    • Full suite on 0ca4e5360: 11,875 runs, 0 failures, 0 errors, 34 skips. Brakeman reports 0 warnings.
  • Stacked on #443 and #444. The parent layers now have their own pre-flights cut from current upstream main:
    • #443 (up/portfolio-daily-returns-v2, daily returns) replaces #372;
    • #444 (up/portfolio-journal-flows-v2, journal flows) replaces #373.
  • This branch's history is unchanged. It still carries their commits as rebased copies. Applying this PR's own nine commits onto #444's head reproduces this head's tree exactly: git diff against 0ca4e5360 is empty. On top of #444, the diff is this PR's six files only: chartable.rb, chart_series_builder.rb, linked_investment_series_normalizer.rb and their tests.
  • This PR's own commits are the eight listed above plus 0ca4e5360.