Add a net contributions series read from the daily returns
Part of #326
Upstream pre-flight for the model half of we-promise/sure#4008, rebuilt on Portfolio::DailyReturns. It replaces the pre-flight jaysbeekay/sure#343 (we-promise/sure#4028), which stays open until the owner decides how to retire it. Base: up/portfolio-journal-flows (jaysbeekay/sure#373).
The upstream PR is NOT YET OPENED (awaiting owner approval). When it is: same branch, same commit.
Supersedes #4028. Same feature and the same public methods, rebuilt on the portfolio daily returns PRs so the line and the returns value money the same way. #4028 will be closed in favour of this PR.
Stacked on DAILY_RETURNS_PR and JOURNAL_FLOWS_PR (which are stacked on #3557). This branch is built on the journal flows branch (up/portfolio-journal-flows). Until those merge, GitHub shows their commits here as well. This PR's own commits are the two after up/portfolio-journal-flows:
31dbd9fbeAdd a net contributions series read from the daily returnsfee7d0579Cover arrivals, empty days and anchor-day flows in net contributions
As each parent merges I'll rebase onto main, so only these commits are left. The chart that draws this series is a separate PR stacked on this one (CHART_PR, fork pre-flight jaysbeekay/sure#381, which supersedes #4029).
Part of #4008
Fork pre-flight PR: jaysbeekay/sure#380 (pull/380), same branch, same commit
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 this replaces #4028. #4028 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_flowandcomposition_flowfromPortfolio::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_understated?(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_understated?
- 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_builderhelper. The understated 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 understated check then returns true.
Differences from #4028's tests. Kept by name where the behaviour is the same. Changed:
| #4028 test | Here | Why |
|---|---|---|
| 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 rate | an 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 amount | a security journalled in or out counts at its position value | a 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 understated (1,500, understated) | a flow with no rate on its own date is valued at the last known rate (2,600, not understated) | 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 example | net contributions open at the opening value and step up by a deposit on its date | same fixture and figures |
Added: "a fee, a buy and a sell leave net contributions unchanged" (beside #4028's "fees, interest, buys and sells"), "a security journalled in counts at its value", "an unpriced journal makes net contributions understated", "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 understated", "an unvalued flow on an explicit anchor day does not make the line understated".
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/balance/chart_series_builder_test.rbandtest/models/account/chartable_test.rb: 53 runs, 0 failures.- I broke each part on purpose and reran those two files. A test caught every break:
| Breakage | Caught by |
|---|---|
| Explicit anchor opens at open plus flows, not the anchor day's close | anchor test + 2 linked Chartable tests |
| Composition flow dropped | account joins the scope later |
| External flow dropped | 16 tests |
| First day's flows not added | deposit on the first balance day |
Understated ignores rate_missing | flow could not be valued + Chartable understated test |
| Understated ignores the unpriced journal | unpriced journal test |
| Understated counts every suppressed day | empty opening day |
| Anchor day's flows counted for understated | unvalued flow on an explicit anchor day |
| Understated reads past the sampled dates | flow after the sampled dates |
| Anchor ignored | anchor test + 2 linked Chartable tests |
| Chartable passes no anchor | 2 linked Chartable tests |
| Chartable keeps the builder's point on the anchor date | coarse-interval test |
| Chartable's trend reads the builder's points, not the replaced ones | coarse-interval test |
:net_contributions view not accepted | 3 Chartable tests (ArgumentError) |
| DailyReturns converts flows at the entry date's rate | previous day's rate test |
| DailyReturns converts the opening value at the first day's own rate | opening value test |
| DailyReturns stops valuing journals | both journal tests |
Commands, on fee7d0579:
bin/rails test: 10,703 runs, 0 failures, 0 errors, 33 skipsbin/rubocopon the changed files: no offensesbundle 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_seriesis called byAssistant::Function::GetAccounts,Loan::PayoffChartandUI::Account::Chart, always with a balance view or none. They take exactly the path they took before. Onlyview: :net_contributionsreturns early. The memo key and builder arguments are unchanged, and the existing "generates series and memoizes" test passes unchanged.Balance::ChartSeriesBuilderis also built byGoal,Assistant::Function::GetBalanceSheet,Balance::LinkedInvestmentSeriesNormalizer,BalanceSheet::NetWorthSeriesBuilder,BalanceSheet::NetWorthBreakdownSeriesBuilderandAccountableSparklinesController. None of them calls the new methods, and the balance and gains queries are untouched.- This makes
Balance::ChartSeriesBuilderthe first caller ofPortfolio::DailyReturns(grep -rn "DailyReturns.new" appfinds only this one). It passes the builder'saccount_ids, itscurrency(the account's own, for the account chart) and itsaccount_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) andGoal#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.
When this is rebased onto main: #4009 changed Balance::LinkedInvestmentSeriesNormalizer so that a daily chart's first point on the first provider-activity date is the balance before that day's activity. The journal flows base predates #4009. I checked this by cherry-picking #4009 onto this branch. One test fails: "a linked account's net contributions open where its trimmed value line does". Both lines now open at the pre-activity value (0 in that fixture), and the contributions line then adds the anchor day's close (1,600) plus the later deposit (300), so it reaches 1,900. That counts the anchor day's 100 market move as money put in, and the gap reads 0 where the account gained 100. The anchor has to move with #4009 (open at the pre-activity value and add the anchor day's flows too), with that test's expected figures updated. I'll make that change in the rebase onto main, where it can be tested. It can't be tested on this base, which doesn't have #4009.
The disabled-account cutoffs (account_active_until_dates) that #4028's own query ignored are passed through to DailyReturns here, so an account's flows after its cutoff don't move the line.