Stop fetching prices for securities no account still holds

Merged
JA
1mo ago
+472-73

Fixes #3856.

Problem

Sure kept asking the price provider for new prices after a position in a security closed.

  • Daily importer. MarketDataImporter#import_security_prices looped over every online security and requested prices through today, whether or not any account still held it.
  • Account sync. Account::MarketDataImporter capped a sold security at its last holding date. Holding materialization carries zero-quantity rows through today, so that cap moved forward every day. The existing test only put the zero row on the sale date, so it didn't catch this.

On providers with tight limits (the issue mentions Yahoo Finance), those requests use up the rate limit for nothing.

What changes

  • Security::Price::ImportWindows works out each account's price window per security: from the first trade or positive holding to the last non-zero trade or last positive holding. An open position, whether current or reopened, runs to today. Zero-quantity rows carried past a sale no longer extend the window.
  • Account sync uses those windows.
  • The daily importer combines the windows of every account with holdings or trades, taking the earliest start and latest end per security. It then fetches only those securities, once each. A security another account still holds keeps updating.
  • Reopened positions still fetch through today before holdings are rematerialized. That covers a new, backdated or edited manual trade, long or short, and a buy after a provider snapshot. A zero holding written after every trade change takes precedence over the raw trade sum, which can disagree after a reverse split. A deleted closing trade leaves nothing to compare, so it is picked up on the next sync.
  • Security details (name, logo, website) still refresh for every online security. Only price fetching is narrowed.

Behaviour to be aware of

  • Account status doesn't close a position. Draft, disabled and pending-deletion accounts still count while their holdings or trades exist.
  • One-time backfill. A provider-held position that closed without any trades now gets a one-time historical price backfill through its last positive holding date. After that, later syncs skip it.
  • Query cost. The daily importer now makes about five database reads per account with holdings or trades, in place of one start-date query per security. Measured locally: 1,000 accounts holding 20 shared tickers took 5,007 queries and 1.84 s, growing linearly with accounts.
  • Paths not covered. Two paths can still request quotes outside these importers: the scheduled Security::HealthChecker, and Security#current_price, which fetches today's price on demand when a page reads it (an old trade or holding, for example). This PR doesn't change either.

Validation

  • New and updated tests in test/models/security/price/import_windows_test.rb, test/models/market_data_importer_test.rb and test/models/account/market_data_importer_test.rb cover:
    • zero holdings carried through today;
    • a shared security, one account closed and one still holding it;
    • repeated syncs after closure, including after another account has extended the shared prices;
    • a reopened position, both manual and provider-held;
    • the reverse-split case;
    • the provider-only backfill;
    • snapshot mode with clear_cache: true.
  • Each regression test was checked to fail with its fix reverted.
  • Focused run: 28 tests, 53 assertions, 0 failures.
  • Full suite, on the same file tree in my fork: 10,340 tests, 43,503 assertions, 0 failures, 0 errors, 33 skips.
  • RuboCop on the changed files: no offences.
  • This repository's CI workflows (unit and system tests, Ruby and JS lint, Ruby and JS scans) passed on a byte-identical tree in my fork.

The branch is cut from main at 20352e1a0, which is current.

My fork's trial run of this change is jaysbeekay/sure#268. Different branch, same files: this PR's branch, up/3856-closed-security-prices, has two commits on 20352e1a0, and its file tree is byte-identical to jaysbeekay/sure#268's head a7875f6da (the ^{tree} hashes match). jaysbeekay/sure#268 carries the review history that led here. I keep this branch's history free of my fork's issue numbers.

Rebased onto main (6 Oct)

Rebased onto main at ea38fa6a3; the commits carry the same changes under new SHAs. SHAs elsewhere in this description refer to the commits as they were before.

  • a8c712b9a → a20dc3363 Stop fetching prices for securities no account still holds
  • 27ef27124 → f5883dec5 Reopen a manual position on any trade change, long or short

bin/rails test on f5883dec5: 10,591 runs, 45,047 assertions, 0 failures, 0 errors, 33 skips. bin/rubocop on the changed files: no offenses.

Summary by CodeRabbit

  • Bug Fixes
    • Price history now covers the period a security was held, stopping when a position closes and extending again if it is repurchased.
    • Closed positions with complete price history are no longer fetched unnecessarily, including during snapshot updates.
    • When a security is shared across accounts, price updates continue through the latest date it is held in any account.
    • Provider-held positions with zero-quantity holdings are backfilled through their last positive holding date, without repeating completed fetches.