Apply stock splits to holdings

Merged
JA
2mo ago
+817-19

Summary

Holdings now follow stock splits. From a split's ex-date, share counts scale by the ratio, and price and cost per share move by the inverse, so position value and total cost don't change. Splits are stored per security, beside its prices, because a split is a fact about the instrument and securities are shared across families.

This PR changes calculation only. Nothing writes a split yet: no provider importer, no form, no seed. Until a later slice adds a source, security_splits is empty in every deployment and every calculator path below reduces to its current behaviour.

Fork pre-flight for upstream PR we-promise/sure#3850, which links back here. Fixes we-promise/sure#3781. Fork issue: #249, under epic #118.

Same branch, same commit: we-promise/sure#3850 is opened from up/security-splits, so the two PRs cannot diverge. Base is mirror/upstream-main. The branch was cut from upstream main at 75638bce0, so the diff is what upstream will see.

What changed

  • 5306bc5e1 Record stock splits against a security
  • 2d77ae942 Apply stock splits in the holding calculators
  • 4c0e180c2 Document split precision and which splits a portfolio applies
  • 9dad3f2fd Pin splits across two accounts and a same-day sale to zero
  • c37f78ffd Round a split to the share count the column can hold
  • 8f72fee78 Carry a split through a day that has no price
  • e0da8da65 Bring a stale provider snapshot forward before walking it back
  • c66f34c08 Restate a carried cost basis for the post-split share count

16 files changed, 817 insertions(+), 19 deletions(-)

  • Security::Split stores the ex-date plus the ratio as two integers (new shares per old, exact). scale/unscale round to the 18-place qty scale. Otherwise a 1-for-3 split of 10 shares leaves about 3e-31 of a share after a full sale, and the cost-basis reset and the transfer "cost unknown" release never fire.
  • Security#split_factor_between(from, to) returns the product of the ratios for splits after from and on or before to, or 1 when there are none.
  • Holding::ForwardCalculator applies a split at the open of its ex-date, before that day's trades.
  • Holding::ReverseCalculator undoes a split when walking back past its ex-date. It also carries a stale provider snapshot forward through any splits between the snapshot's date and today, which it reads from the new PortfolioSnapshot#effective_dates. A snapshot with no dates is treated as current, as it was before.
  • Holding::CostBasisTracker rescales its running quantity at a split.
  • Holding::Gapfillable: a gap-filled day that crosses an ex-date is restated. amount is recomputed from qty × price rather than carried.
  • Holding::Materializer: a cost basis carried past the last provider snapshot is divided by the cumulative split factor. The source and lock rules are unchanged. Splits are read once per materialisation.

Demo data

No demo data needed. Nothing in the app writes a split yet, so Demo::Generator has no split to produce and nothing on screen changes. Demo data belongs with the slice that adds a split source.

Screenshots

None. There is no UI change.

Migration notes

  • 20260928100000_create_security_splits creates security_splits: a uuid id, security_id (FK, on_delete: :cascade), ex_date, numerator, denominator and source, all NOT NULL, plus timestamps.
  • A unique index on [security_id, ex_date].
  • Check constraints security_splits_positive_terms (both terms > 0) and security_splits_not_one_to_one (numerator ≠ denominator).
  • The migration is additive. No existing table or row is changed, there is no backfill, and nothing needs running after deploy.

Verification

Local, Ruby 3.3.6 with the version pin overridden locally because 3.4.9 could not be installed here; PostgreSQL 16; head c66f34c08.

  • bin/rails test test/models/holding test/models/security test/models/security_test.rb test/models/holding_test.rb: 252 runs, 821 assertions, 0 failures, 0 errors
  • bin/rails test (full suite): 10,197 runs, 42,898 assertions, 4 failures, 3 errors, 33 skips. The same 7 fail identically on a branch without this change, and none is in code this PR touches:
    • 5 Anthropic provider/settings tests fail because ANTHROPIC_BASE_URL is set in this environment.
    • Provider::OpenaiTest#extra_headers... fails on Ruby 3.3's Hash#inspect format; the pin is 3.4.
    • 2 ActiveStorage variant tests fail because no image processor is installed here.
    • CI is authoritative.
  • bin/rubocop on the 16 changed files: no offenses
  • bundle exec erb_lint: not applicable, since no ERB changed
  • npm run lint: not applicable, since no JS changed
  • bin/brakeman --no-pager: 0 warnings
  • Each of the four later commits says in its message which new test fails when the change is reverted.
  • CI at c66f34c08: test_unit, test_system, lint, lint_js, scan_ruby and scan_js all pass.
  • Upstream AGENTS.md, read at live upstream main (0da863b78, unchanged since 75638bce0):
    • All 8 commit subjects are 72 characters or fewer; the longest is 61.
    • The migration uses the current ActiveRecord::Migration[8.1].
    • No ERB, JS or API files changed, so the UI and API rules don't apply.
    • Upstream main has moved on since the cut, but no upstream migration shares 20260928100000. The branch needs bringing up to date before we-promise/sure#3850 leaves draft.

Blast radius

Every investment account sync runs through these calculators: Balance::Materializer → Holding::Materializer → Holding::ForwardCalculator or Holding::ReverseCalculator, and both of those call Holding.gapfill. What protects each shared path:

Shared pathWhat protects it
Forward / reverse calculatorsWith no split in range, the ratio lookup returns nil and the position is left untouched. The existing calculator tests pass unchanged.
Holding.gapfill (only callers are the two calculators)The restatement runs only when a carried holding crosses an ex-date. Splits are read once for the whole set, not per filled day.
Holding::PortfolioSnapshot (only caller is Holding::Materializer)#to_h returns the same hash as before. #effective_dates is additive, and a snapshot without dates reads as current.
Cost basis carried by Holding::MaterializerA factor of 1 with no splits, so it's a no-op. Source and lock rules are untouched.
Security (shared across families)has_many :splits, dependent: :destroy, plus the FK's on_delete: :cascade. Deleting a security removes its splits.
  • Add Security::Split records with validated ratios, unique ex-dates per security, and cascading deletion.
  • Apply splits to forward and reverse holding calculations, cost-basis tracking, gap-filled holdings, and provider cost-basis carry-forward.
  • Preserve total cost basis across splits and round scaled quantities to the stored 18-decimal precision.
  • Add regression tests for split calculations, ex-date trades, missing prices, provider snapshots, and split validation.
  • The migration adds the split table but does not populate split records. Import, manual entry, and split-feed support remain out of scope.
AuthorLines addedLines removed
jaysbeekay81719