"""Finding splits in the trace they leave behind. There is no free structured feed of US stock splits. What there is, in a dataset that keeps every filing's own version of a period, is the trace: a split forces a company to restate every earlier per-share figure by the split ratio. Two filings covering the same quarter, one before the split and one after, differ by exactly that factor. That is a stronger signal than the obvious one. A jump in shares outstanding looks the same for a two-for-one split and for an equity raise that doubled the count; only a split reaches back and rewrites the past. Three methods are combined, each labelled: xbrl_tag the filer tagged the conversion ratio itself eps_restatement an earlier period's EPS was restated by a clean ratio share_count shares outstanding jumped by a clean ratio `xbrl_tag` is authority. `eps_restatement` covers three times as many companies and agrees with the tagged ratio for 79% of the firms where both exist. `share_count` is never used alone -- it cannot tell a split from an issuance -- only to corroborate. """ from __future__ import annotations import logging from datetime import UTC, datetime import polars as pl from .schema import SPLIT_SCHEMA, align, empty_frame LOGGER = logging.getLogger(__name__) # Ratios a split is actually declared in. # # Written out rather than generated. The first version of this list was also # written out and omitted six-for-one, which made Deckers' 2024 split invisible # -- the evidence was there, the ratio was not in the table. The fix was to # complete the list, not to accept any simple fraction: generating them gave a # hundred and forty ratios, and an ordinary 1.83x restatement then resolved to # "eleven-for-six". # # Nothing between 0.85 and 1.18 is admitted at all. A five percent stock # dividend and a five percent restatement leave the same trace, and calling one # the other would put a phantom split into the adjustment factors. FORWARD_RATIOS: tuple[tuple[float, str], ...] = ( (1.25, "5:4"), (4 / 3, "4:3"), (1.5, "3:2"), (5 / 3, "5:3"), (1.75, "7:4"), (1.8, "9:5"), (2.0, "2:1"), (2.5, "5:2"), (3.0, "3:1"), (3.5, "7:2"), (4.0, "4:1"), (5.0, "5:1"), (6.0, "6:1"), (7.0, "7:1"), (8.0, "8:1"), (9.0, "9:1"), (10.0, "10:1"), (12.0, "12:1"), (15.0, "15:1"), (20.0, "20:1"), (25.0, "25:1"), (30.0, "30:1"), ) # Reverse splits run to much larger denominators: a shell consolidating # one-for-a-thousand to regain a listing is routine. REVERSE_DENOMINATORS: tuple[int, ...] = ( 2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 16, 20, 25, 30, 35, 40, 50, 60, 75, 80, 100, 120, 150, 200, 250, 300, 400, 500, 750, 1000, ) KNOWN_RATIOS: tuple[tuple[float, str], ...] = tuple( sorted( { **{round(1 / denominator, 10): f"1:{denominator}" for denominator in REVERSE_DENOMINATORS}, **{round(ratio, 10): label for ratio, label in FORWARD_RATIOS}, }.items() ) ) # Tight enough that no two admitted ratios can claim the same measurement. RATIO_TOLERANCE = 0.01 # One restated figure is not evidence: a single period whose EPS happens to land # on a clean ratio after a correction produced a four-for-one Tesla split in # 2020 that never happened. Two is the floor for publishing at all. # # Above the floor the count grades the claim instead of gating it. A real split # restates every prior period a filing shows -- Apple's 2020 split left 36 of # them -- so a handful is weaker evidence than a pile, and the reader should be # told which they have rather than have the thin cases silently removed. MIN_RESTATEMENT_EVIDENCE = 2 STRONG_RESTATEMENT_EVIDENCE = 4 # An extreme ratio is where a tiny denominator does the most damage: earnings of # minus two cents restated to minus forty dollars is a genuine one-for-a- # thousand consolidation, and so is a rounding change on a company whose EPS # never left the third decimal. Shells really do consolidate at these ratios -- # 4 305 of the reverse splits found here are theirs -- so the answer is not to # refuse them but to demand the corroboration that separates the two. EXTREME_RATIO_HIGH = 50.0 EXTREME_RATIO_LOW = 0.02 SPLIT_RATIO_TAGS = ( "StockholdersEquityNoteStockSplitConversionRatio1", "StockholdersEquityNoteStockSplitConversionRatio", "StockholdersEquityNoteStockSplitConversionRatio2", ) def snap_ratio(value: float | None) -> tuple[float, str] | None: """The declared ratio a measurement corresponds to, or nothing.""" if value is None or value <= 0: return None for ratio, label in KNOWN_RATIOS: if abs(value - ratio) <= RATIO_TOLERANCE * ratio: return ratio, label return None def _snapped(column: str) -> pl.Expr: expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.Float64)) for ratio, _label in KNOWN_RATIOS: tolerance = RATIO_TOLERANCE * ratio expr = expr.when( (pl.col(column) > ratio - tolerance) & (pl.col(column) < ratio + tolerance) ).then(pl.lit(ratio)) return expr.otherwise(pl.lit(None, dtype=pl.Float64)) def _label() -> pl.Expr: expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.String)) for ratio, label in KNOWN_RATIOS: expr = expr.when(pl.col("ratio") == ratio).then(pl.lit(label)) return expr.otherwise(pl.lit(None, dtype=pl.String)) def from_restatements(fundamentals: pl.LazyFrame | pl.DataFrame) -> pl.DataFrame: """Splits inferred from per-share figures being restated. Both EPS and the weighted share count are used, and they move in opposite directions: after a two-for-one split the restated EPS is half of what was first reported, and the restated share count is double. Taking the ratio in the direction that yields the split factor for each keeps the two comparable. """ lazy = fundamentals.lazy() if isinstance(fundamentals, pl.DataFrame) else fundamentals per_share = ["eps_diluted", "eps_basic"] counts = ["shares_diluted_weighted", "shares_basic_weighted"] frame = ( lazy.filter(pl.col("concept").is_in([*per_share, *counts])) .filter(pl.col("value").is_not_null() & (pl.col("value").abs() > 0.01)) .collect() ) if frame.is_empty(): return empty_frame(SPLIT_SCHEMA) grouped = ( frame.sort("accepted_at") .group_by(["cik", "concept", "period_end", "quarters"]) .agg( pl.col("value").first().alias("first_value"), pl.col("value").last().alias("last_value"), pl.col("accepted_at").first().alias("detected_after"), pl.col("accepted_at").last().alias("detected_before"), pl.len().alias("reports"), ) .filter(pl.col("reports") > 1) ) grouped = grouped.with_columns( pl.when(pl.col("concept").is_in(per_share)) .then(pl.col("first_value") / pl.col("last_value")) .otherwise(pl.col("last_value") / pl.col("first_value")) .alias("measured") ) grouped = grouped.with_columns(_snapped("measured").alias("ratio")).filter( pl.col("ratio").is_not_null() ) if grouped.is_empty(): return empty_frame(SPLIT_SCHEMA) # Every period the company restated by the same factor is evidence of one # split, not of many, so the windows are combined. # # The tight combination is the intersection: the split happened after the # last filing that still used the old numbers and before the first that # used the new. That intersection can be empty, and when it is, it is not # an arithmetic slip -- it means the evidence spans more than one event at # the same ratio, a company that split two-for-one twice. Falling back to # the union keeps a window that certainly contains them, instead of # publishing one that ends before it starts. events = ( grouped.group_by(["cik", "ratio"]) .agg( pl.col("detected_after").max().alias("tight_after"), pl.col("detected_before").min().alias("tight_before"), pl.col("detected_after").min().alias("wide_after"), pl.col("detected_before").max().alias("wide_before"), pl.col("period_end").max().alias("effective_period_end"), pl.len().cast(pl.Int32).alias("evidence_observations"), pl.col("concept").unique().sort().str.join("|").alias("corroborated_by"), ) .with_columns( pl.lit("eps_restatement").alias("method"), _label().alias("ratio_label"), (pl.col("ratio") < 1).alias("is_reverse"), ) .with_columns( (pl.col("tight_after") <= pl.col("tight_before")).alias("_tight"), ) .with_columns( pl.when(pl.col("_tight")) .then(pl.col("tight_after")) .otherwise(pl.col("wide_after")) .alias("detected_after"), pl.when(pl.col("_tight")) .then(pl.col("tight_before")) .otherwise(pl.col("wide_before")) .alias("detected_before"), ) ) enough = pl.when( (pl.col("ratio") >= EXTREME_RATIO_HIGH) | (pl.col("ratio") <= EXTREME_RATIO_LOW) ).then(pl.lit(STRONG_RESTATEMENT_EVIDENCE)).otherwise(pl.lit(MIN_RESTATEMENT_EVIDENCE)) return align(events.filter(pl.col("evidence_observations") >= enough), SPLIT_SCHEMA) def from_tags(facts: pl.LazyFrame | pl.DataFrame) -> pl.DataFrame: """Splits the filer tagged with a conversion ratio.""" lazy = facts.lazy() if isinstance(facts, pl.DataFrame) else facts frame = ( lazy.filter(pl.col("tag").is_in(SPLIT_RATIO_TAGS)) .filter(pl.col("value").is_not_null() & (pl.col("value") > 0) & (pl.col("value") < 200)) .select("cik", "value", "period_end", "accepted_at") .collect() ) if frame.is_empty(): return empty_frame(SPLIT_SCHEMA) # A filer may write a three-for-two split as 1.5 or as its reciprocal. # Both readings are snapped and whichever lands on a declared ratio wins. frame = frame.with_columns( pl.coalesce([_snapped("value"), _snapped_reciprocal()]).alias("ratio") ).filter(pl.col("ratio").is_not_null()) if frame.is_empty(): return empty_frame(SPLIT_SCHEMA) events = ( frame.group_by(["cik", "ratio"]) .agg( pl.col("accepted_at").min().alias("detected_after"), pl.col("accepted_at").min().alias("detected_before"), pl.col("period_end").max().alias("effective_period_end"), pl.len().cast(pl.Int32).alias("evidence_observations"), ) .with_columns( pl.lit("xbrl_tag").alias("method"), pl.lit("tagged_ratio").alias("corroborated_by"), _label().alias("ratio_label"), (pl.col("ratio") < 1).alias("is_reverse"), ) ) return align(events, SPLIT_SCHEMA) def _snapped_reciprocal() -> pl.Expr: expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.Float64)) for ratio, _label in KNOWN_RATIOS: tolerance = RATIO_TOLERANCE * ratio expr = expr.when( (1 / pl.col("value") > ratio - tolerance) & (1 / pl.col("value") < ratio + tolerance) ).then(pl.lit(ratio)) return expr.otherwise(pl.lit(None, dtype=pl.Float64)) def combine(tagged: pl.DataFrame, inferred: pl.DataFrame) -> pl.DataFrame: """One row per split, with the strongest method that found it. A split found both ways is one split with high confidence, not two rows. A split found only by restatement keeps the medium label: it agreed with the tagged ratio for 79% of the companies where both exist, which is worth publishing and not worth calling certain. """ if tagged.is_empty() and inferred.is_empty(): return empty_frame(SPLIT_SCHEMA) both = pl.concat([tagged, inferred], how="vertical_relaxed") ranked = ( both.with_columns( pl.col("method").replace_strict({"xbrl_tag": 0, "eps_restatement": 1}, default=2) .alias("_rank") ) .sort(["cik", "ratio", "_rank"]) .group_by(["cik", "ratio"], maintain_order=True) .agg( pl.all().exclude("_rank").first(), pl.col("method").n_unique().alias("_methods"), ) ) ranked = ranked.with_columns( pl.when(pl.col("_methods") > 1) .then(pl.lit("high")) .when(pl.col("method") == "xbrl_tag") .then(pl.lit("high")) .when(pl.col("evidence_observations") >= STRONG_RESTATEMENT_EVIDENCE) .then(pl.lit("medium")) .otherwise(pl.lit("low")) .alias("confidence"), pl.when(pl.col("_methods") > 1) .then(pl.lit("xbrl_tag+eps_restatement")) .otherwise(pl.col("corroborated_by")) .alias("corroborated_by"), pl.lit(datetime.now(UTC)).alias("inserted_at"), ) return align(ranked, SPLIT_SCHEMA).sort(["cik", "detected_before"])