Apply stock splits to holdings
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
5306bc5e1Record stock splits against a security2d77ae942Apply stock splits in the holding calculators4c0e180c2Document split precision and which splits a portfolio applies9dad3f2fdPin splits across two accounts and a same-day sale to zeroc37f78ffdRound a split to the share count the column can hold8f72fee78Carry a split through a day that has no pricee0da8da65Bring a stale provider snapshot forward before walking it backc66f34c08Restate a carried cost basis for the post-split share count
16 files changed, 817 insertions(+), 19 deletions(-)
Security::Splitstores the ex-date plus the ratio as two integers (new shares per old, exact).scale/unscaleround to the 18-placeqtyscale. 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 afterfromand on or beforeto, or 1 when there are none.Holding::ForwardCalculatorapplies a split at the open of its ex-date, before that day's trades.Holding::ReverseCalculatorundoes 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 newPortfolioSnapshot#effective_dates. A snapshot with no dates is treated as current, as it was before.Holding::CostBasisTrackerrescales its running quantity at a split.Holding::Gapfillable: a gap-filled day that crosses an ex-date is restated.amountis 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_splitscreatessecurity_splits: a uuid id,security_id(FK,on_delete: :cascade),ex_date,numerator,denominatorandsource, all NOT NULL, plus timestamps.- A unique index on
[security_id, ex_date]. - Check constraints
security_splits_positive_terms(both terms > 0) andsecurity_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 errorsbin/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_URLis set in this environment. Provider::OpenaiTest#extra_headers...fails on Ruby 3.3'sHash#inspectformat; the pin is 3.4.- 2 ActiveStorage variant tests fail because no image processor is installed here.
- CI is authoritative.
- 5 Anthropic provider/settings tests fail because
bin/rubocopon the 16 changed files: no offensesbundle exec erb_lint: not applicable, since no ERB changednpm run lint: not applicable, since no JS changedbin/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_rubyandscan_jsall pass. - Upstream
AGENTS.md, read at live upstreammain(0da863b78, unchanged since75638bce0):- 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
mainhas moved on since the cut, but no upstream migration shares20260928100000. 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 path | What protects it |
|---|---|
| Forward / reverse calculators | With 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::Materializer | A 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::Splitrecords 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.
| Author | Lines added | Lines removed |
|---|---|---|
| jaysbeekay | 817 | 19 |