Count deposits and withdrawals, not trades, as investment contributions

Merged
AR
13d ago
+998-89

Fixes #5069

Summary

InvestmentStatement::Totals now computes contributions and withdrawals from Portfolio::FlowClassifier:

  • It embeds the classifier's sql_joins and sql_case in its existing single aggregate query.
  • The scope is the account ids the card already uses (the family's visible investment and crypto accounts that are included in reports, for this user), plus the Trade Republic Cash account that settles their trades (see below).
  • contributions = Σ |amount| of external_inflow rows, and withdrawals = Σ |amount| of external_outflow rows, converted into the family currency by the rule the other totals use since #3983 (ExchangeRate.rate_sql): the rate on the entry date, else the latest stored rate before it, else the earliest one after it. A row in a currency with no stored rate at all is left out of both sums, never counted at 1.
  • A row counts only when it records a flow. That means it is labelled Contribution, Withdrawal or Transfer, has a transfer kind, or is a leg of a confirmed Transfer whose other leg is outside the scope. Transfer::Creator and Transfer#confirm! give both legs a transfer kind; a link written another way (an import, an older row) can leave them standard. Such a standard leg counts when its other leg is outside the scope, and not when it is inside: the classifier resolves a link only for a transfer kind or label and reads any other row by its sign, so a move between two accounts in the scope would count on both sides.

Trade Republic:

  • With its Cash account linked, Trade Republic books every trade's cash on that account, which is a depository account, and links it to the Portfolio or Crypto account as a confirmed transfer (TradeRepublicAccount::ActivitiesProcessor#link_settlement_counterpart!). With only the investment accounts in scope, each buy counted as a contribution and each sale as a withdrawal.
  • TradeRepublicAccount.settlement_account_ids_for returns the Cash account of each connection whose Portfolio or Crypto account is on the card. The totals read it as part of the scope when it passes the same report and visibility filters as the investment accounts (InvestmentStatement#totals_account_ids).
  • The settlement pairs are then internal, like a buy paid from an investment account's own cash. Money counts once, where it enters or leaves the broker: a confirmed transfer between the Cash account and an account outside the scope, such as the user's bank.
  • As on the other accounts, a cash row on the Cash account counts only when it records a flow. Card purchases and other unlinked rows there count on neither side.
  • Trade Republic Cash has an IBAN and a card, and many users run it as their current account. So on that account a credit card or loan payment to another account in Sure (cc_payment, loan_payment; cc_payment also covers any other liability account) is not a withdrawal either, unless the user labelled it Contribution, Withdrawal or Transfer. It is spending, like the card purchases there, and a salary paid in is not counted either. Counted, every card bill would lower net contributions. A transfer to the user's own bank or savings account is still a withdrawal, and a card payment from an investment account still counts. InvestmentStatement passes the settlement account ids to Totals for this.
  • Dividends and interest that Trade Republic books on the Cash account are now in the card's income. With both accounts linked, it books them there, not on the portfolio, so the card used to show none. The Cash balance itself stays out of the portfolio value, so the card shows interest on a balance it does not include.
  • Only this provider's settlement account is followed, not every account of the same connection. A bank connection with a checking and a brokerage account would otherwise make every deposit from that checking account internal, and it would never be counted. A Portfolio connected without its Cash account is unchanged.

What counts and what does not:

  • Counts: Contribution/Withdrawal rows; transfers to or from an account outside the scope (a bank account, for example); positions journalled in or out.
  • Does not count:
    • buys, sells, reinvestments, sweeps and exchanges;
    • transfers between two accounts in the scope. A confirmed transfer between two in-scope accounts is internal even when its legs are labelled Contribution/Withdrawal, as the classifier decides;
    • unlabelled and Other cash rows, whatever their sign.
  • Pending and excluded rows are left out, as they already are for income. So are pending (unconfirmed) transfer suggestions: until the user confirms one, each leg counts as what its label says.

Changes to the classifier (Portfolio::FlowClassifier), in both its SQL and Ruby forms:

  • Only a confirmed Transfer links two legs. Auto-matched transfers start as pending, and Transfer#confirm! documents that an unconfirmed suggestion never moves budgets or reports. Before this change, a pending suggestion between two in-scope accounts made both of its labelled legs internal.
  • The counterpart entry is looked up only among the scope's accounts. That is all the CASE asks of it, and the card's recorded-flow rule reads a missing counterpart as an out-of-scope leg. entries has no index on entryable_id, so without this bound the join read every Transaction entry in the database.
  • A transaction on two transfers is read once, through the one on the side its sign allows. Transfer#transfer_has_opposite_amounts requires a leg to be the inflow while its amount is negative and the outflow while it is positive, but only when the transfer is saved. A leg's amount can change sign afterwards (a provider re-sync writes it again), and the leg can then become another transfer's leg on the other side. A single join would return both rows and count it twice. So the transfers are joined once per side: the transfer on the side the sign allows (the outflow while the amount is positive, else the inflow) wins, and the other side is used only when there is none. The sign chooses between transfers and never drops one. A leg whose sign flipped with no second transfer, or a pair negated together (a Trade Republic settlement re-synced with the opposite sign), keeps its link. The Ruby form (#confirmed_transfer_for) looks up the confirmed transfer on the sign's side, then on the other side.
  • The security-transfer check is a grouped join, not a correlated EXISTS. The scope's live Transfer trades are grouped by date, security and quantity, with the lowest and highest account id of each group, and left-joined on the entry's date, security and opposite quantity. A leg in another account exists exactly when either id differs from the entry's own. Grouping keeps the join to one row per entry. The answer is the same; the planner priced the EXISTS against the whole scope for every row, so its estimate grew with the square of the entries.

Caching:

  • The totals cache key now also includes a version of the transfers that touch the card's accounts (count and max updated_at).
  • Linking, confirming or removing a transfer between two existing transactions does not always write to either entry, so entries_cache_version alone missed it.
  • The account-id hash in the key also covers which of the accounts settle trades, since that changes what counts on them.

Other changes:

  • The old trade sums are still available as PeriodTotals#buys and #sells. Nothing renders them today.
  • dividends, interest and trades_count are unchanged. The query now also reads the transactions that can be flows, but the income columns still match on the Dividend/Interest labels, and trades_count still counts trades.id.
  • The totals cache key moves from v2 to v3, because two cached fields change meaning.

No view, locale or controller changes. The card and the dashboard keep their labels, which are now accurate.

Notes for review

  • Why the classifier and not InvestmentFlowStatement. InvestmentFlowStatement reads only Contribution/Withdrawal labels. It misses a Transfer-labelled row (SnapTrade transfers, Coinbase, Indexa) and an unlabelled transfer from a bank account. It also does not use the card's account scope. The classifier is the rule the returns engine (#4197) builds on, so the card and the coming returns figures will count flows the same way.

  • Why unlabelled and Other rows are left out. For an unlabelled, non-transfer cash Transaction, the classifier falls back to the sign. Some providers write activity that is not a flow that way:

    • SimpleFIN records every investment activity, buys and sales included, as an unlabelled standard Transaction.
    • Plaid maps its investment type cash, which covers dividends and interest, to Other.
    • SnapTrade's MERGER/ADJUSTMENT, REBATE and JOURNAL rows are also Other.

    Counting these by sign would turn a SimpleFIN rebalance or a Plaid dividend back into a contribution. A manual cash deposit counts once it is labelled Contribution, or entered as a transfer from a bank account.

  • Query speed. The query has to read cash rows, not only trades, so it does more work than before. To keep that down:

    • It reads only trades, income rows and the rows that can be flows.
    • It classifies each row once, in a LATERAL ... OFFSET 0 subquery.
    • It looks up each row's exchange rate once, in a second lateral subquery, instead of writing rate_sql into each of the six sums. Written six times, its two correlated lookups were priced six times per row, and that alone put the estimate past jit_above_cost in the planner-cost test.
    • The classifier's security-transfer check is a grouped hash join (see above).
    • The transfers are joined once per side, and each join keeps the OR probe on both transfer columns and checks the side with a CASE on the amount's sign on top of it. Choosing one transfer in a LATERAL ... ORDER BY ... LIMIT 1 instead gives one row even for two transfers on the same side, but it took the query out of its parallel plan, raised the 5-year estimate to about 890k and ran three to four times slower (740–920 ms). Writing the side check inside the OR, as (inflow AND amount < 0) OR (outflow AND amount > 0), kept the index probe, but the estimate grew nine times and the 5-year query took about 670 ms.

    Measured on a synthetic family with 3 investment accounts and 55k investment entries over 5 years, plus 30k checking rows, a Trade Republic Cash account with 10k card payments and one settlement pair a day, and 300k entries in another family. Medians of 9 uncached runs, two runs each, alternating with main on the same database. For the three investment accounts, a 5-year period took 166–176 ms against 49–66 ms on main, 1 year 50–53 ms (35–36 ms on main), and 30 days 24–26 ms (about 5 ms on main). The speed work leaves the results unchanged, and no planner hints or session settings are used.

    At 5 years the planner's estimate (about 247k) is above jit_above_cost (100k), so JIT runs, but it stays under the 500k at which Postgres also inlines and optimizes the JIT code. Most of that estimate is the two transfers joins' OR probes. Rewriting a join as a UNION ALL or as equality joins lowered the estimate on an earlier revision, but the plan went serial and was no faster, so it is not done here. The new cache-key part (transfers_version) takes about 10–16 ms on this data, and it runs on every request that reads the totals, cache hits included. The 30-day cost is mostly the counterpart join, which reads the scope's Transaction entries: without an index on entries.entryable_id, no better plan exists.

  • Trade Republic and the transfer sign, measured. Same runs, with a single join that filters by sign timed alongside. At 5 years, three accounts take 166–176 ms against 131–142 ms with that filter; with the Cash account in the scope, which adds its 11.8k rows, 192–202 ms against 155–161 ms. At 1 year it is 50–53 ms against 41–47 ms, and at 30 days the two are within noise (24–28 ms). The second transfers join is the cost: the 5-year estimate goes from 136k to 247k. The single join without a sign check, as on the current PR head, timed within noise of the filter. Finding the Cash account is one more query; the account-id lookup takes 2–3 ms.

  • The Investment Flows section still differs (follow-up). InvestmentFlowStatement reads only Contribution/Withdrawal labels, with its own account scope. A Transfer-labelled row (SnapTrade transfers) or an unlabelled transfer from a bank account still appears on the card but not in Flows. Pointing Flows at these totals would change its own tests and scope, so it is left for a follow-up and not done here.

  • Known limits:

    • A cash move between two of the user's broker accounts that is not linked as a Transfer counts on both sides: as a withdrawal from one and a contribution to the other.
    • A security transferred in with a zero amount counts as 0. #4198 values those.
    • Security transfers are paired by whether an opposite leg exists, not by how many. If a position moves from A to B and the same quantity of the same security leaves C on the same day, all three legs are internal, so C's outflow is not counted as a withdrawal. This is the classifier's existing rule; the card now shows it.
    • Removing a link resets its surviving leg to a standard, unlabelled transaction (Transfer#release_transactions), and such a row is not counted. Unlinking a bank deposit, or deleting its bank-side entry or the bank account, therefore removes that contribution from the card, unless the investment-side leg carries a Contribution label.
    • A Trade Republic deposit that is not linked to a bank account in Sure is an unlabelled row on the Cash account, so it is not counted, unless it is labelled Contribution. Money that reaches the Cash account another way (a salary paid into it) and is then invested is not counted either. What the importer stores for a deposit (its event type, the title, the status subtitle and the payment reference) cannot tell a transfer from the user's own bank from a salary or a payment from someone else, so these rows are not counted by event type. A user whose bank is not in Sure can label the deposits by hand, or with a Rule (account is the Cash account, transaction details contain INCOMING_TRANSFER, or BANK_TRANSACTION_INCOMING in a second Rule, set the investment activity label to Contribution), and the label survives a re-sync. A follow-up PR will match the transfer's counterparty IBAN against the login's Trade Republic reference accounts, so deposits from and payouts to the user's own bank count without a Rule.
    • If the Trade Republic Cash account is excluded from reports, or is not in the viewing user's finances (another member's account that is not shared with them), it is outside the card like any other account. That user then sees each settlement as a contribution or a withdrawal again, as before this change.
    • Interest Trade Republic pays on the Cash account is in the card's income, while the Cash balance is not in the portfolio value.
    • The Cash account is read when either the Portfolio or the Crypto account is on the card. If only one of them is, the other's settlement legs on the Cash account are still internal by their Buy/Sell label, so money spent from Cash on the excluded account is not counted as a withdrawal.
    • Only liability payments out of Trade Republic Cash are left out. A loan paid out into it, or a card refund paid into it, is a transfer from outside the scope and counts as a contribution. The rule goes by the transaction's kind, which Transfer::Creator and Transfer#confirm! set from the account the money goes to; a row whose kind is stale is read by that stale kind.
    • A transaction that is the same side (say, the inflow) of two confirmed transfers can be counted twice, when that is the side its sign allows or it has no confirmed transfer on that side. Transfer validates inflow_transaction_id and outflow_transaction_id as unique, but the table has a unique index on the pair only. So rows written around the validations (insert_all) can create it, and so can two writers racing past the validations (a sync linking a settlement while the user links the same row by hand, for example).
    • buys and sells are summed by quantity, as main's direction branches were, so a trade labelled Transfer or Contribution (a position journalled in or out) is also in them. Nothing renders them yet.
  • #4082, question 4. This takes the "external inflows only" reading. A Reinvestment is internal, so it is no longer counted as a contribution.

Tests

New tests in InvestmentStatementTest:

  • A deposit and the buy it funds count once. A 1,000 deposit and an 800 buy give contributions 1,000 and buys 800. Before the fix: 800.
  • A buy paid for with cash already in the account is not a contribution. A 500 buy and a 200 sell give contributions and withdrawals of 0, buys 500 and sells 200. Before the fix: 500 / 200.
  • A withdrawal counts. A labelled 150 withdrawal plus a 250 linked transfer to a checking account give withdrawals of 400. Before the fix: 0.
  • A transfer between two investment accounts in scope counts on neither side. This covers a linked transfer and a linked pair whose legs are labelled Withdrawal/Contribution. It is a guard and passes before the fix too, because the old code ignored every transfer.
  • The mixed case. Trades, labelled flows, an unlabelled investment_contribution row and a linked transfer from checking, plus pending, excluded and out-of-period rows that must be ignored. This replaces the test that pinned the trade-only reading.
  • A foreign-currency deposit converts at the entry date's rate.
  • A deposit in a currency with no stored rate at all is left out, not counted at 1, and so is a withdrawal in it.
  • A deposit with no rate on its day uses the nearest stored rate, as income does.
  • An unconfirmed transfer suggestion does not change contributions or withdrawals. Labelled 40/40 legs joined by a pending auto-match stay 40/40.
  • Creating, confirming and removing a transfer each refresh the cached totals, including a confirmed link that does not touch either entry.
  • An Other cash row is neither a contribution nor a withdrawal (Plaid cash dividends).
  • An unlabelled cash row is neither (SimpleFIN buys and sales).
  • A confirmed transfer with unlabelled standard legs counts only when its other leg is off the card. An unlabelled and an Other pair between two investment accounts give 0 / 0; the same kind of link from a checking account then gives a 300 contribution.
  • A security transfer with two opposite legs in scope is read once. Contributions 0, buys 500, sells 1,000, 3 trades. Withdrawals is not asserted (see the known limit on security transfers).
  • Totals leave the JIT setting of the caller's transaction as it was.
  • The totals query is planned below jit_above_cost (4,500 trades, 1,500 of them Transfer).

Portfolio::FlowClassifierTest gets two new tests:

  • A pending transfer suggestion links nothing until it is confirmed. It checks both forms, before and after confirm!.
  • A security transfer's opposite leg in its own account is not its counterpart. It checks both forms, before and after a leg in another account joins, with fixed account ids in both orders, so both halves of the lowest/highest account-id check are tested.

The "link wins" test now confirms its transfer. It used to rely on a pending one.

Trade Republic and the sign check. The Trade Republic tests run its real sync (TradeRepublicAccount::ActivitiesProcessor) on a connection with both accounts linked:

  • Trade Republic buys and sales settled on its Cash account are neither contributions nor withdrawals. A 1,024.92 buy and a 529 sale give 0 / 0, buys 1,024.92 and 2 trades. Before this change, contributions were 1,024.92.
  • A bank deposit into Trade Republic Cash counts once, not again when it buys shares. A 2,000 deposit linked to the bank account (a suggestion, then confirmed), an 800 buy, a 12.50 dividend and a card payment give contributions 2,000, withdrawals 0, buys 800 and dividends 12.50. Before this change, contributions were 800.
  • A checking account on the same connection as a brokerage account stays off the card. Both are Plaid accounts of one item, and a 500 transfer from the checking account is still a 500 contribution. This guards the scope: following every account of a connection would make it 0.
  • A transaction that became another transfer's leg after a sign change counts once. An inflow leg from checking turns positive and becomes the outflow of a second confirmed transfer, to a savings account. Withdrawals are 100. Before the sign check, they were 200.
  • A transfer between two investment accounts stays internal when a leg changes sign. With one leg flipped and then both, contributions and withdrawals stay 0 / 0. A sign filter gave a 200 withdrawal with one flipped and 200 / 200 with both.
  • A Trade Republic settlement whose amounts were negated together is still internal. It gives 0 / 0. A sign filter gave a 500 withdrawal.
  • Credit card and loan payments from Trade Republic Cash are not withdrawals. An 800 card payment, a 400 loan payment and a 300 transfer to the bank give withdrawals of 300, and 1,100 once the card payment is labelled Withdrawal. With the Cash account in scope but without this rule, they gave 1,500.
  • A credit card payment from an investment account is a withdrawal, 250. This guards the scope of the rule above.
  • Portfolio::FlowClassifierTest: a transaction on two transfers is linked on the side its sign allows, a transfer leg whose sign changed keeps its link when it has no other transfer, and extra transfers written around the validations do not change a transaction's link (two extra confirmed transfers on the other side, then a pending one on the sign's side). Each checks the Ruby and SQL forms, and the first and last check that the joins return one row for the entry.

Five existing tests now assert buys/sells where they asserted the trade-based contributions/withdrawals, among them #3983's "totals leave out a trade in a currency with no rate at all". The two cache tests' stubs include the two new keys.

On main, 26 of the 136 tests in the two files fail (22 failures and 4 errors). On the PR's current head (38447e902), 7 of the new tests fail: the two Trade Republic tests, the negated settlement, the card and loan payment test, the double-link test, and the classifier's two-transfer and extra-transfer tests. The checking-account guard, the flipped-leg tests and the investment-account card payment test pass there, as guards. A single join filtered by sign, as in the intermediate commit 2a94aad39, fails the two flipped-leg tests and the negated settlement. The Other and unlabelled tests pass there too, since main ignores cash rows; they guard the new classification.

These suites pass, 1,411 runs with 0 failures: investment statement, Portfolio::FlowClassifier and the other portfolio model tests, InvestmentFlowStatement, transfer, the reports and pages controllers, the exchange rate model tests, the Trade Republic model tests, account, income statement and the IBKR account processor. Rubocop is clean.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Investment totals now show buy and sell activity separately from contributions and withdrawals.
    • Eligible Trade Republic settlement activity is included in investment totals.
  • Bug Fixes
    • Contributions and withdrawals more accurately reflect external cash flows, excluding internal transfers and unrecorded cash entries.
    • Confirmed transfers and linked transfer updates are reflected in totals, while pending transfers remain separate from confirmed internal transfers.
    • Foreign-currency trade and income activity is more accurately reflected in totals.