From 88625d6b70923e68342bdb464176309752f108a3 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 19:04:08 -0500 Subject: [PATCH] =?UTF-8?q?T-70:=20M1.2c=20=E2=80=94=20`tools/curate-etl`:?= =?UTF-8?q?=20pure=20`corporate=5Factions`=20builder=20(splits=20+=20divid?= =?UTF-8?q?ends=20+=20OTC=20continuation=20/=20Shumway=20terminal=20delist?= =?UTF-8?q?ing=20rows)=20with=20local=20benchmark=20(no=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 35 +- tools/curate-etl/src/bench.rs | 207 ++++ tools/curate-etl/src/cli.rs | 46 +- tools/curate-etl/src/corporate_actions.rs | 1100 +++++++++++++++++++++ tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/main.rs | 44 +- 6 files changed, 1429 insertions(+), 9 deletions(-) create mode 100644 tools/curate-etl/src/corporate_actions.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 6464046a..1ea6103b 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core and the `M1.2b` pure `adj_factors` builder. +Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, and the `M1.2c` pure `corporate_actions` event-log builder. ## Scope & Sign Conventions @@ -37,7 +37,22 @@ Rules: 5. **`cum_total_factor`:** `cum_split_factor` multiplied by the product of per-row dividend factors over this row and all later rows of the same key (inclusive of the row's own `ex_date`). 6. **Validation & overflow guards:** Non-finite or `<= 0.0` split ratios (`InvalidSplitRatio`), non-finite or `< 0.0` dividend cash (`InvalidDividendCash`), empty/whitespace currency on positive cash (`EmptyDividendCurrency`), conflicting same-day dividend currencies (`ConflictingDividendCurrency`), and overflow/underflow of any combined or cumulative factor (`FactorOverflow`) return a typed `AdjError` without panicking. -Deferred out of `src/adj.rs`: cross-currency dividend FX conversion (waits for `fx_1d`), `known_at` timestamp derivation, and `corporate_actions` delisting / Shumway rows. +Deferred out of `src/adj.rs`: cross-currency dividend FX conversion (waits for `fx_1d`). Point-in-time `known_at` clamping and delisting / Shumway rows live in `src/corporate_actions.rs`. + +## `corporate_actions` Builder (`M1.2c`) + +`build_corporate_actions` (`src/corporate_actions.rs`) turns split (`qmSplits`), cash-dividend (`qmDividends`), and Pass 6 delisting outcome streams into a deterministically sorted event log matching the `corporate_actions/part.parquet` columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, declared_date, kind, ratio, cash_amount, currency, successor_listing_id, terminal_return, known_at, known_at_source`). + +Rules: +1. **Splits (`kind = "split"`):** Same `ratio = new_shares / old_shares` convention as `src/split.rs`. `ratio == 1.0` no-ops are dropped and counted in `stats.split_noops_dropped`. Non-finite or `<= 0.0` ratios return `CorporateActionError::InvalidSplitRatio`. +2. **Dividends (`kind = "dividend"`):** Local `currency` and `cash` are preserved unchanged (deliberately omitting `usdFxRate`). `cash == 0.0` events are dropped and counted in `stats.dividend_zero_cash_dropped`. Multiple dividends on the same `(key, ex_date)` remain separate event-log rows. Non-finite or `< 0.0` cash returns `InvalidDividendCash`; empty/whitespace currency on positive cash returns `EmptyDividendCurrency`. +3. **Point-in-time `known_at` clamping:** Uses `declared_date` when present and `<= ex_date` (`known_at_source = "declared_date"`). Otherwise falls back to `ex_date` (`known_at_source = "ex_date_fallback"`), preserving the raw `declared_date` on the row and counting `declared_date > ex_date` in `stats.declared_after_ex_date` so `known_at_date <= ex_date` always holds. +4. **Delistings (Pass 6):** + - `successor_key = Some(s), terminal_return = None` → one `otc_delist_transfer` row (`ex_date = known_at_date = delist_date`, `known_at_source = "delist_date"`). + - `successor_key = None, terminal_return = Some(r)` → one `delisting` row (`r` must be finite and in `[-1.0, 0.0]`, normalizing `-0.0` to `0.0`, else `InvalidTerminalReturn`). + - Both `None` → dropped and counted in `stats.delist_without_outcome`. + - Both `Some` → `CorporateActionError::ConflictingDelistingOutcome`. +5. **Determinism & accounting:** Output rows are sorted by `(key, ex_date, kind, declared_date, ratio_bits, cash_bits, currency, successor_key, terminal_return_bits, known_at_date, known_at_source)` so any input permutation yields byte-identical output, and `stats` satisfies `in == out + dropped` per kind and `known_at_declared_date + known_at_ex_date_fallback + known_at_delist_date == rows_out`. ## Local Benchmarks @@ -68,7 +83,21 @@ Command: `cargo run --release -p curate-etl --offline -- bench-adj` - Build: `rows_out=986702`, `keys_out=20000`, `elapsed=242.94 ms`, `throughput=4116183 events/s`, `latency=242.94 ns/event`, `checksum=17888280.062 (0x41710f4180ff5d60)` (bitwise identical across back-to-back runs) - Stats: `split_noops=1988`, `zero_div=9527`, `missing_prev_close=19089`, `currency_mismatch=19147`, `not_below_prev_close=9693` -## Deferred Follow-Ups (`M1.2c+` / `M2`) +### `bench-corporate-actions` + +Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` `i32` `listing_id` keys spanning `1990-01-01..=2025-12-31` with ~4% splits, ~92% USD/CAD dividends, and ~4% delisting outcomes (default `1,000,000` mixed events), timing only `build_corporate_actions`: + +```bash +cargo run --release -p curate-etl --offline -- bench-corporate-actions [events] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-corporate-actions` + +- Input: `events=1000000`, `splits=39872`, `dividends=920134`, `delistings=39994`, `keys=20000` +- Build: `rows_out=980694`, `keys_out=20000`, `elapsed=107.48 ms`, `throughput=9303979 events/s`, `latency=107.48 ns/event`, `checksum=0xbfd2ceda373762f5` (identical across back-to-back runs) +- Stats: `split_noops=1963`, `zero_div=9302`, `delist_no_outcome=8041`, `otc_transfers=11942`, `delistings=20011`, `declared=758098`, `ex_fallback=190643`, `declared_after_ex=19108`, `delist_date=31953` + +## Deferred Follow-Ups (`M1.2d+` / `M2`) This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (requiring crates.io access) will add: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 4be639db..b707fbc7 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -4,15 +4,21 @@ use std::hint::black_box; use std::time::Instant; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; +use crate::corporate_actions::{ + build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent, + DividendActionEvent, SplitActionEvent, +}; use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable}; pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000; +pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; +const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; /// Deterministic SplitMix64 generator (zero external dependencies). @@ -232,6 +238,169 @@ pub fn run_adj_benchmark(events: usize) -> Result { }) } +/// Summary metrics produced by [`run_corporate_actions_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CorporateActionsBenchReport { + pub events: usize, + pub splits_in: usize, + pub dividends_in: usize, + pub delistings_in: usize, + pub key_count: usize, + pub rows_out: usize, + pub keys_out: usize, + pub build_elapsed_ms: f64, + pub events_per_sec: f64, + pub ns_per_event: f64, + pub checksum: u64, + pub stats: CorporateActionsStats, +} + +#[inline] +fn mix_u64(state: u64, value: u64) -> u64 { + let mut x = state ^ value.wrapping_mul(0x9E37_79B9_7F4A_7C15); + x = x.rotate_left(27).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x ^ (x >> 31) +} + +/// Runs the fixed-seed `build_corporate_actions` benchmark for `events` mixed split, dividend, +/// and delisting events. +/// +/// Generates `events` deterministic events across `20_000` `i32` `listing_id` keys spanning +/// `1990-01-01..=2025-12-31` (~4% splits with `1.0` no-ops and declared/missing/late dates, +/// ~92% USD/CAD dividends with `0.0` drops and declared/missing/late dates, ~4% delistings with +/// OTC transfers, `-0.3`/`-1.0` terminal returns, and no-outcome drops), times only +/// [`build_corporate_actions`], and returns throughput plus a deterministic `u64` checksum. +pub fn run_corporate_actions_benchmark( + events: usize, +) -> Result { + let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let date_span = (max_date - min_date + 1) as u64; + + let mut rng = SplitMix64::new(CORPORATE_ACTIONS_BENCH_SEED); + let mut splits: Vec<(i32, SplitActionEvent)> = Vec::with_capacity(events / 20); + let mut dividends: Vec<(i32, DividendActionEvent)> = Vec::with_capacity(events); + let mut delistings: Vec<(i32, DelistingOutcomeEvent)> = Vec::with_capacity(events / 20); + + for _ in 0..events { + let key = ((rng.next_u64() as usize) % BENCH_KEY_COUNT) as i32 + 1; + let ex_date = min_date + (rng.next_u64() % date_span) as i32; + let kind_roll = rng.next_u64() % 100; + + if kind_roll < 4 { + let ratio_roll = rng.next_u64() % 20; + let ratio = if ratio_roll == 0 { + 1.0 + } else { + SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()] + }; + let decl_roll = rng.next_u64() % 100; + let declared_date = if decl_roll < 30 { + Some(ex_date - 14) + } else if decl_roll < 32 { + Some(ex_date + 3) + } else { + None + }; + splits.push(( + key, + SplitActionEvent { + ex_date, + ratio, + declared_date, + }, + )); + } else if kind_roll < 96 { + let curr = if key % 5 == 0 { "CAD" } else { "USD" }; + let cash_roll = rng.next_u64() % 100; + let cash = if cash_roll == 0 { + 0.0 + } else { + ((rng.next_u64() % 150) + 5) as f64 * 0.01 + }; + let decl_roll = rng.next_u64() % 100; + let declared_date = if decl_roll < 82 { + Some(ex_date - 21) + } else if decl_roll < 84 { + Some(ex_date + 2) + } else { + None + }; + dividends.push(( + key, + DividendActionEvent { + ex_date, + cash, + currency: curr.to_string(), + declared_date, + }, + )); + } else { + let outcome_roll = rng.next_u64() % 10; + let (successor_key, terminal_return) = match outcome_roll { + 0..=2 => (Some(key + BENCH_KEY_COUNT as i32), None), + 3..=5 => (None, Some(-0.3)), + 6..=7 => (None, Some(-1.0)), + _ => (None, None), + }; + delistings.push(( + key, + DelistingOutcomeEvent { + delist_date: ex_date, + successor_key, + terminal_return, + }, + )); + } + } + + let splits_in = splits.len(); + let dividends_in = dividends.len(); + let delistings_in = delistings.len(); + + let build_start = Instant::now(); + let built = build_corporate_actions(splits, dividends, delistings)?; + let build_elapsed = build_start.elapsed(); + let build_elapsed_secs = build_elapsed.as_secs_f64(); + let build_elapsed_ms = build_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &built.rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.ex_date as u64); + hash = mix_u64(hash, row.declared_date.map_or(u64::MAX, |d| d as u64)); + hash = mix_u64(hash, row.kind as u64); + hash = mix_u64(hash, row.ratio.map_or(0, f64::to_bits)); + hash = mix_u64(hash, row.cash_amount.map_or(0, f64::to_bits)); + let curr_bits = row.currency.as_deref().map_or(0u64, |c| { + c.bytes() + .fold(0u64, |acc, b| acc.wrapping_shl(8) | u64::from(b)) + }); + hash = mix_u64(hash, curr_bits); + hash = mix_u64(hash, row.successor_key.map_or(u64::MAX, |k| k as u64)); + hash = mix_u64(hash, row.terminal_return.map_or(0, f64::to_bits)); + hash = mix_u64(hash, row.known_at_date as u64); + hash = mix_u64(hash, row.known_at_source as u64); + } + let checksum = black_box(hash); + let (events_per_sec, ns_per_event) = compute_rates(events, build_elapsed_secs); + + Ok(CorporateActionsBenchReport { + events, + splits_in, + dividends_in, + delistings_in, + key_count: BENCH_KEY_COUNT, + rows_out: built.stats.rows_out, + keys_out: built.stats.keys_out, + build_elapsed_ms, + events_per_sec, + ns_per_event, + checksum, + stats: built.stats, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -312,4 +481,42 @@ mod tests { assert_eq!(report.events_per_sec, 0.0); assert_eq!(report.ns_per_event, 0.0); } + + #[test] + fn corporate_actions_benchmark_small_run_is_deterministic() { + let a = run_corporate_actions_benchmark(5_000).unwrap(); + let b = run_corporate_actions_benchmark(5_000).unwrap(); + + assert_eq!(a.events, 5_000); + assert_eq!(a.splits_in + a.dividends_in + a.delistings_in, 5_000); + assert_eq!(a.key_count, BENCH_KEY_COUNT); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.keys_out, b.keys_out); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.events_per_sec.is_finite() && a.events_per_sec >= 0.0); + assert!(a.ns_per_event.is_finite() && a.ns_per_event >= 0.0); + assert!(a.stats.splits_out > 0); + assert!(a.stats.dividends_out > 0); + assert!(a.stats.otc_delist_transfers_out > 0); + assert!(a.stats.delistings_out > 0); + assert!(a.stats.delist_without_outcome > 0); + assert!(a.stats.declared_after_ex_date > 0); + } + + #[test] + fn corporate_actions_benchmark_zero_events_handles_cleanly() { + let report = run_corporate_actions_benchmark(0).unwrap(); + assert_eq!(report.events, 0); + assert_eq!(report.splits_in, 0); + assert_eq!(report.dividends_in, 0); + assert_eq!(report.delistings_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.keys_out, 0); + assert_eq!(report.stats, CorporateActionsStats::default()); + assert_eq!(report.checksum, 0); + assert_eq!(report.events_per_sec, 0.0); + assert_eq!(report.ns_per_event, 0.0); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index fa8ea153..4886d036 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -3,7 +3,9 @@ //! Kept inside the library crate so CLI argument parsing tests run under //! `cargo test --workspace --lib --offline`. -use crate::bench::{DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BENCH_ROWS}; +use crate::bench::{ + DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, +}; /// Parsed CLI command to execute. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -12,6 +14,7 @@ pub enum CliAction { Version, BenchSplit(usize), BenchAdj(usize), + BenchCorporateActions(usize), } /// Formats full help text including binary name and version. @@ -22,8 +25,9 @@ pub fn format_usage(name: &str, version: &str) -> String { Usage:\n\ {name} [--help | -h]\n\ {name} [--version | -V]\n\ - {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ - {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})" + {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ + {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ + {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})" ) } @@ -34,7 +38,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} [--help | -h]\n\ {name} [--version | -V]\n\ {name} bench-split [rows]\n\ - {name} bench-adj [events]" + {name} bench-adj [events]\n\ + {name} bench-corporate-actions [events]" ) } @@ -63,6 +68,18 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-adj", _, ..] => Err("too many arguments for bench-adj".to_string()), + ["bench-corporate-actions"] => Ok(CliAction::BenchCorporateActions( + DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + )), + ["bench-corporate-actions", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCorporateActions(n)), + _ => Err(format!( + "invalid event count '{raw}' (expected a positive integer)" + )), + }, + ["bench-corporate-actions", _, ..] => { + Err("too many arguments for bench-corporate-actions".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -132,13 +149,32 @@ mod tests { } #[test] - fn usage_strings_mention_both_benchmarks() { + fn parses_and_validates_bench_corporate_actions_args() { + assert_eq!( + parse_args(&to_args(&["bench-corporate-actions"])), + Ok(CliAction::BenchCorporateActions( + DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-corporate-actions", "500000"])), + Ok(CliAction::BenchCorporateActions(500_000)) + ); + assert!(parse_args(&to_args(&["bench-corporate-actions", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-corporate-actions", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-corporate-actions", "10", "20"])).is_err()); + } + + #[test] + fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); assert!(full.contains("bench-split")); assert!(full.contains("bench-adj")); + assert!(full.contains("bench-corporate-actions")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); assert!(short.contains("bench-adj")); + assert!(short.contains("bench-corporate-actions")); } } diff --git a/tools/curate-etl/src/corporate_actions.rs b/tools/curate-etl/src/corporate_actions.rs new file mode 100644 index 00000000..5215745b --- /dev/null +++ b/tools/curate-etl/src/corporate_actions.rs @@ -0,0 +1,1100 @@ +//! Pure, in-memory `corporate_actions` builder (`qmSplits` + `qmDividends` + Pass 6 delistings). +//! +//! Produces deterministically sorted event-log rows matching the `corporate_actions/part.parquet` +//! columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, declared_date, kind, ratio, +//! cash_amount, currency, successor_listing_id, terminal_return, known_at, known_at_source`): +//! - Splits use the same convention as [`crate::split`]: `ratio = new_shares / old_shares`. +//! `ratio == 1.0` no-ops are dropped and counted; non-finite or `<= 0.0` ratios return a typed +//! error. +//! - Dividends carry their local `currency` unchanged (deliberately omitting `usdFxRate`). +//! `cash == 0.0` events are dropped and counted; multiple dividends on the same `(key, ex_date)` +//! remain separate rows. +//! - Point-in-time `known_at_date` uses `declared_date` when present and `<= ex_date` +//! (`KnownAtSource::DeclaredDate`), and falls back to `ex_date` (`KnownAtSource::ExDateFallback`) +//! when `declared_date` is missing or `> ex_date` (preserving the raw `declared_date` and +//! counting late declarations in `stats.declared_after_ex_date`). +//! - Delisting outcomes mirror Pass 6 (`otc_delist_transfer` when `successor_key` is present, +//! `delisting` with `terminal_return` in `[-1.0, 0.0]` when no successor exists, dropped and +//! counted when neither is present, and rejected when both are set). + +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; + +/// Kind of corporate action event stored in `corporate_actions`. +/// +/// Variant declaration order defines the deterministic tie-break sort order: +/// `Split < Dividend < OtcDelistTransfer < Delisting`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum CorporateActionKind { + Split, + Dividend, + OtcDelistTransfer, + Delisting, +} + +impl CorporateActionKind { + /// Stable wire/Parquet string representation. + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::Split => "split", + Self::Dividend => "dividend", + Self::OtcDelistTransfer => "otc_delist_transfer", + Self::Delisting => "delisting", + } + } +} + +impl fmt::Display for CorporateActionKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Provenance of `known_at_date` for a curated [`CorporateActionRow`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum KnownAtSource { + DeclaredDate, + ExDateFallback, + DelistDate, +} + +impl KnownAtSource { + /// Stable wire/Parquet string representation. + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::DeclaredDate => "declared_date", + Self::ExDateFallback => "ex_date_fallback", + Self::DelistDate => "delist_date", + } + } +} + +impl fmt::Display for KnownAtSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Input split event for [`build_corporate_actions`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SplitActionEvent { + /// Ex-split date as days since 1970-01-01 (UTC Gregorian). + pub ex_date: i32, + /// `new_shares / old_shares` (e.g. `10.0` for 10:1 forward, `0.05` for 1:20 reverse). + pub ratio: f64, + /// Optional declaration date as epoch days. + pub declared_date: Option, +} + +/// Input cash-dividend event for [`build_corporate_actions`]. +/// +/// Deliberately omits `usdFxRate` (contract: ignore `qmDividends.usdFxRate`). +#[derive(Debug, Clone, PartialEq)] +pub struct DividendActionEvent { + /// Ex-dividend date as days since 1970-01-01 (UTC Gregorian). + pub ex_date: i32, + /// Cash dividend amount per share (must be finite and `>= 0.0`). + pub cash: f64, + /// Local dividend currency code (e.g. `"USD"`, `"CAD"`). Must be non-empty when `cash > 0.0`. + pub currency: String, + /// Optional declaration date as epoch days. + pub declared_date: Option, +} + +/// Input delisting outcome event (mirrors Pass 6 output) for [`build_corporate_actions`]. +#[derive(Debug, Clone, PartialEq)] +pub struct DelistingOutcomeEvent { + /// Effective delisting date as days since 1970-01-01 (UTC Gregorian). + pub delist_date: i32, + /// OTC continuation successor key (e.g. `SIVB` -> `SIVBQ`), mutually exclusive with `terminal_return`. + pub successor_key: Option, + /// Terminal delisting return in `[-1.0, 0.0]` (e.g. `-0.3` Shumway, `-1.0` total loss). + pub terminal_return: Option, +} + +/// A single curated `corporate_actions` event-log row. +#[derive(Debug, Clone, PartialEq)] +pub struct CorporateActionRow { + pub key: K, + pub ex_date: i32, + pub declared_date: Option, + pub kind: CorporateActionKind, + pub ratio: Option, + pub cash_amount: Option, + pub currency: Option, + pub successor_key: Option, + pub terminal_return: Option, + pub known_at_date: i32, + pub known_at_source: KnownAtSource, +} + +/// Accounting and provenance summary counters produced by [`build_corporate_actions`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CorporateActionsStats { + pub splits_in: usize, + pub splits_out: usize, + pub split_noops_dropped: usize, + pub dividends_in: usize, + pub dividends_out: usize, + pub dividend_zero_cash_dropped: usize, + pub delistings_in: usize, + pub otc_delist_transfers_out: usize, + pub delistings_out: usize, + pub delist_without_outcome: usize, + pub rows_out: usize, + pub keys_out: usize, + pub known_at_declared_date: usize, + pub known_at_ex_date_fallback: usize, + pub declared_after_ex_date: usize, + pub known_at_delist_date: usize, +} + +/// Output of [`build_corporate_actions`]: deterministically sorted rows plus stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CorporateActionsBuild { + pub rows: Vec>, + pub stats: CorporateActionsStats, +} + +/// Typed validation errors returned by [`build_corporate_actions`]. +#[derive(Debug, Clone, PartialEq)] +pub enum CorporateActionError { + /// A split ratio was non-finite (`NaN`, `+/-inf`) or `<= 0.0`. + InvalidSplitRatio { ex_date: i32, ratio: f64 }, + /// A dividend cash amount was non-finite (`NaN`, `+/-inf`) or `< 0.0`. + InvalidDividendCash { ex_date: i32, cash: f64 }, + /// A positive cash dividend had an empty or whitespace-only currency. + EmptyDividendCurrency { ex_date: i32 }, + /// A terminal delisting return was non-finite or outside `[-1.0, 0.0]`. + InvalidTerminalReturn { + delist_date: i32, + terminal_return: f64, + }, + /// A delisting outcome specified both `successor_key` and `terminal_return`. + ConflictingDelistingOutcome { delist_date: i32 }, +} + +impl fmt::Display for CorporateActionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidSplitRatio { ex_date, ratio } => { + write!( + f, + "invalid split ratio {ratio} on epoch day {ex_date}: must be finite and > 0" + ) + } + Self::InvalidDividendCash { ex_date, cash } => { + write!( + f, + "invalid dividend cash {cash} on epoch day {ex_date}: must be finite and >= 0" + ) + } + Self::EmptyDividendCurrency { ex_date } => { + write!( + f, + "empty dividend currency on epoch day {ex_date} for positive cash dividend" + ) + } + Self::InvalidTerminalReturn { + delist_date, + terminal_return, + } => { + write!( + f, + "invalid terminal delisting return {terminal_return} on epoch day {delist_date}: must be finite and in [-1.0, 0.0]" + ) + } + Self::ConflictingDelistingOutcome { delist_date } => { + write!( + f, + "conflicting delisting outcome on epoch day {delist_date}: successor_key and terminal_return are mutually exclusive" + ) + } + } + } +} + +impl Error for CorporateActionError {} + +#[inline] +fn resolve_known_at( + ex_date: i32, + declared_date: Option, + stats: &mut CorporateActionsStats, +) -> (i32, KnownAtSource) { + match declared_date { + Some(declared) if declared <= ex_date => { + stats.known_at_declared_date += 1; + (declared, KnownAtSource::DeclaredDate) + } + Some(_) => { + stats.known_at_ex_date_fallback += 1; + stats.declared_after_ex_date += 1; + (ex_date, KnownAtSource::ExDateFallback) + } + None => { + stats.known_at_ex_date_fallback += 1; + (ex_date, KnownAtSource::ExDateFallback) + } + } +} + +#[inline] +fn opt_f64_bits(value: Option) -> Option { + value.map(f64::to_bits) +} + +#[inline] +fn cmp_rows(a: &CorporateActionRow, b: &CorporateActionRow) -> Ordering { + a.key + .cmp(&b.key) + .then_with(|| a.ex_date.cmp(&b.ex_date)) + .then_with(|| a.kind.cmp(&b.kind)) + .then_with(|| a.declared_date.cmp(&b.declared_date)) + .then_with(|| opt_f64_bits(a.ratio).cmp(&opt_f64_bits(b.ratio))) + .then_with(|| opt_f64_bits(a.cash_amount).cmp(&opt_f64_bits(b.cash_amount))) + .then_with(|| a.currency.cmp(&b.currency)) + .then_with(|| a.successor_key.cmp(&b.successor_key)) + .then_with(|| opt_f64_bits(a.terminal_return).cmp(&opt_f64_bits(b.terminal_return))) + .then_with(|| a.known_at_date.cmp(&b.known_at_date)) + .then_with(|| a.known_at_source.cmp(&b.known_at_source)) +} + +/// Builds deterministically sorted `corporate_actions` rows from splits, dividends, and delisting +/// outcomes. +/// +/// Output ordering is invariant to input ordering and satisfies: +/// - `splits_in == splits_out + split_noops_dropped` +/// - `dividends_in == dividends_out + dividend_zero_cash_dropped` +/// - `delistings_in == otc_delist_transfers_out + delistings_out + delist_without_outcome` +/// - `rows_out == rows.len() == known_at_declared_date + known_at_ex_date_fallback + known_at_delist_date` +pub fn build_corporate_actions( + splits: S, + dividends: D, + delistings: L, +) -> Result, CorporateActionError> +where + K: Ord + Clone, + S: IntoIterator, + D: IntoIterator, + L: IntoIterator)>, +{ + let splits_iter = splits.into_iter(); + let dividends_iter = dividends.into_iter(); + let delistings_iter = delistings.into_iter(); + + let cap = splits_iter + .size_hint() + .0 + .saturating_add(dividends_iter.size_hint().0) + .saturating_add(delistings_iter.size_hint().0); + + let mut rows: Vec> = Vec::with_capacity(cap); + let mut stats = CorporateActionsStats::default(); + + for (key, event) in splits_iter { + stats.splits_in += 1; + if !event.ratio.is_finite() || event.ratio <= 0.0 { + return Err(CorporateActionError::InvalidSplitRatio { + ex_date: event.ex_date, + ratio: event.ratio, + }); + } + if event.ratio == 1.0 { + stats.split_noops_dropped += 1; + continue; + } + let (known_at_date, known_at_source) = + resolve_known_at(event.ex_date, event.declared_date, &mut stats); + stats.splits_out += 1; + rows.push(CorporateActionRow { + key, + ex_date: event.ex_date, + declared_date: event.declared_date, + kind: CorporateActionKind::Split, + ratio: Some(event.ratio), + cash_amount: None, + currency: None, + successor_key: None, + terminal_return: None, + known_at_date, + known_at_source, + }); + } + + for (key, event) in dividends_iter { + stats.dividends_in += 1; + if !event.cash.is_finite() || event.cash < 0.0 { + return Err(CorporateActionError::InvalidDividendCash { + ex_date: event.ex_date, + cash: event.cash, + }); + } + if event.cash == 0.0 { + stats.dividend_zero_cash_dropped += 1; + continue; + } + if event.currency.trim().is_empty() { + return Err(CorporateActionError::EmptyDividendCurrency { + ex_date: event.ex_date, + }); + } + let (known_at_date, known_at_source) = + resolve_known_at(event.ex_date, event.declared_date, &mut stats); + stats.dividends_out += 1; + rows.push(CorporateActionRow { + key, + ex_date: event.ex_date, + declared_date: event.declared_date, + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(event.cash), + currency: Some(event.currency), + successor_key: None, + terminal_return: None, + known_at_date, + known_at_source, + }); + } + + for (key, event) in delistings_iter { + stats.delistings_in += 1; + match (event.successor_key, event.terminal_return) { + (Some(_), Some(_)) => { + return Err(CorporateActionError::ConflictingDelistingOutcome { + delist_date: event.delist_date, + }); + } + (None, None) => { + stats.delist_without_outcome += 1; + } + (Some(successor_key), None) => { + stats.otc_delist_transfers_out += 1; + stats.known_at_delist_date += 1; + rows.push(CorporateActionRow { + key, + ex_date: event.delist_date, + declared_date: None, + kind: CorporateActionKind::OtcDelistTransfer, + ratio: None, + cash_amount: None, + currency: None, + successor_key: Some(successor_key), + terminal_return: None, + known_at_date: event.delist_date, + known_at_source: KnownAtSource::DelistDate, + }); + } + (None, Some(raw_return)) => { + if !raw_return.is_finite() || !(-1.0..=0.0).contains(&raw_return) { + return Err(CorporateActionError::InvalidTerminalReturn { + delist_date: event.delist_date, + terminal_return: raw_return, + }); + } + let terminal_return = if raw_return == 0.0 { 0.0 } else { raw_return }; + stats.delistings_out += 1; + stats.known_at_delist_date += 1; + rows.push(CorporateActionRow { + key, + ex_date: event.delist_date, + declared_date: None, + kind: CorporateActionKind::Delisting, + ratio: None, + cash_amount: None, + currency: None, + successor_key: None, + terminal_return: Some(terminal_return), + known_at_date: event.delist_date, + known_at_source: KnownAtSource::DelistDate, + }); + } + } + } + + rows.sort_unstable_by(cmp_rows); + + let mut keys_out = 0usize; + let mut prev_key: Option<&K> = None; + for row in &rows { + if prev_key != Some(&row.key) { + keys_out += 1; + prev_key = Some(&row.key); + } + } + stats.keys_out = keys_out; + stats.rows_out = rows.len(); + + Ok(CorporateActionsBuild { rows, stats }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::split::ymd_to_epoch_days; + + fn empty_splits() -> std::iter::Empty<(K, SplitActionEvent)> { + std::iter::empty() + } + + fn empty_dividends() -> std::iter::Empty<(K, DividendActionEvent)> { + std::iter::empty() + } + + fn empty_delistings() -> std::iter::Empty<(K, DelistingOutcomeEvent)> { + std::iter::empty() + } + + fn assert_stats_conservation(build: &CorporateActionsBuild) { + let s = &build.stats; + assert_eq!(s.splits_in, s.splits_out + s.split_noops_dropped); + assert_eq!(s.dividends_in, s.dividends_out + s.dividend_zero_cash_dropped); + assert_eq!( + s.delistings_in, + s.otc_delist_transfers_out + s.delistings_out + s.delist_without_outcome + ); + assert_eq!(s.rows_out, build.rows.len()); + assert_eq!( + s.rows_out, + s.splits_out + s.dividends_out + s.otc_delist_transfers_out + s.delistings_out + ); + assert_eq!( + s.rows_out, + s.known_at_declared_date + s.known_at_ex_date_fallback + s.known_at_delist_date + ); + } + + fn assert_rows_bit_identical( + a: &[CorporateActionRow], + b: &[CorporateActionRow], + ) { + assert_eq!(a.len(), b.len()); + for (ra, rb) in a.iter().zip(b.iter()) { + assert_eq!(ra.key, rb.key); + assert_eq!(ra.ex_date, rb.ex_date); + assert_eq!(ra.declared_date, rb.declared_date); + assert_eq!(ra.kind, rb.kind); + assert_eq!(opt_f64_bits(ra.ratio), opt_f64_bits(rb.ratio)); + assert_eq!(opt_f64_bits(ra.cash_amount), opt_f64_bits(rb.cash_amount)); + assert_eq!(ra.currency, rb.currency); + assert_eq!(ra.successor_key, rb.successor_key); + assert_eq!( + opt_f64_bits(ra.terminal_return), + opt_f64_bits(rb.terminal_return) + ); + assert_eq!(ra.known_at_date, rb.known_at_date); + assert_eq!(ra.known_at_source, rb.known_at_source); + } + } + + #[test] + fn enum_as_str_and_display_are_stable() { + assert_eq!(CorporateActionKind::Split.as_str(), "split"); + assert_eq!(CorporateActionKind::Dividend.as_str(), "dividend"); + assert_eq!( + CorporateActionKind::OtcDelistTransfer.as_str(), + "otc_delist_transfer" + ); + assert_eq!(CorporateActionKind::Delisting.as_str(), "delisting"); + assert_eq!(format!("{}", CorporateActionKind::Split), "split"); + assert_eq!( + format!("{}", CorporateActionKind::OtcDelistTransfer), + "otc_delist_transfer" + ); + + assert_eq!(KnownAtSource::DeclaredDate.as_str(), "declared_date"); + assert_eq!(KnownAtSource::ExDateFallback.as_str(), "ex_date_fallback"); + assert_eq!(KnownAtSource::DelistDate.as_str(), "delist_date"); + assert_eq!(format!("{}", KnownAtSource::DeclaredDate), "declared_date"); + assert_eq!(format!("{}", KnownAtSource::DelistDate), "delist_date"); + } + + #[test] + fn splits_forward_reverse_noop_and_invalid_ratios() { + let d_nvda = ymd_to_epoch_days(2024, 6, 10).unwrap(); + let d_nvda_decl = ymd_to_epoch_days(2024, 5, 22).unwrap(); + let d_nexm = ymd_to_epoch_days(2025, 6, 18).unwrap(); + + let built = build_corporate_actions( + [ + ( + "NVDA".to_string(), + SplitActionEvent { + ex_date: d_nvda, + ratio: 10.0, + declared_date: Some(d_nvda_decl), + }, + ), + ( + "NEXM.V".to_string(), + SplitActionEvent { + ex_date: d_nexm, + ratio: 0.05, + declared_date: None, + }, + ), + ( + "NOOP".to_string(), + SplitActionEvent { + ex_date: d_nvda, + ratio: 1.0, + declared_date: Some(d_nvda_decl), + }, + ), + ], + empty_dividends(), + empty_delistings(), + ) + .unwrap(); + + assert_stats_conservation(&built); + assert_eq!(built.stats.splits_in, 3); + assert_eq!(built.stats.splits_out, 2); + assert_eq!(built.stats.split_noops_dropped, 1); + assert_eq!(built.stats.keys_out, 2); + assert_eq!(built.rows.len(), 2); + + // Sorted ascending by key: "NEXM.V" < "NVDA" + let r0 = &built.rows[0]; + assert_eq!(r0.key, "NEXM.V"); + assert_eq!(r0.kind, CorporateActionKind::Split); + assert_eq!(r0.ex_date, d_nexm); + assert_eq!(r0.declared_date, None); + assert_eq!(r0.ratio, Some(0.05)); + assert_eq!(r0.cash_amount, None); + assert_eq!(r0.currency, None); + assert_eq!(r0.successor_key, None); + assert_eq!(r0.terminal_return, None); + assert_eq!(r0.known_at_date, d_nexm); + assert_eq!(r0.known_at_source, KnownAtSource::ExDateFallback); + + let r1 = &built.rows[1]; + assert_eq!(r1.key, "NVDA"); + assert_eq!(r1.kind, CorporateActionKind::Split); + assert_eq!(r1.ex_date, d_nvda); + assert_eq!(r1.declared_date, Some(d_nvda_decl)); + assert_eq!(r1.ratio, Some(10.0)); + assert_eq!(r1.known_at_date, d_nvda_decl); + assert_eq!(r1.known_at_source, KnownAtSource::DeclaredDate); + + for bad_ratio in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, -0.0, -2.0] { + let err = build_corporate_actions( + [( + "BAD".to_string(), + SplitActionEvent { + ex_date: d_nvda, + ratio: bad_ratio, + declared_date: None, + }, + )], + empty_dividends(), + empty_delistings(), + ) + .unwrap_err(); + assert!( + matches!(err, CorporateActionError::InvalidSplitRatio { ex_date, .. } if ex_date == d_nvda), + "expected InvalidSplitRatio for {bad_ratio}, got {err:?}" + ); + assert!(!err.to_string().is_empty()); + } + } + + #[test] + fn dividends_cad_same_day_multiple_zero_drop_and_errors() { + let d_ex = ymd_to_epoch_days(2024, 11, 15).unwrap(); + let d_decl = ymd_to_epoch_days(2024, 10, 30).unwrap(); + + let built = build_corporate_actions( + empty_splits(), + [ + ( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d_ex, + cash: 1.42, + currency: "CAD".to_string(), + declared_date: Some(d_decl), + }, + ), + ( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d_ex, + cash: 0.25, + currency: "CAD".to_string(), + declared_date: Some(d_decl), + }, + ), + // Zero cash with empty currency is dropped before currency validation. + ( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d_ex, + cash: 0.0, + currency: String::new(), + declared_date: None, + }, + ), + ], + empty_delistings(), + ) + .unwrap(); + + assert_stats_conservation(&built); + assert_eq!(built.stats.dividends_in, 3); + assert_eq!(built.stats.dividends_out, 2); + assert_eq!(built.stats.dividend_zero_cash_dropped, 1); + assert_eq!(built.stats.keys_out, 1); + assert_eq!(built.rows.len(), 2); + + // Event log preserves both same-day dividends, ordered by cash bits (0.25 < 1.42). + assert_eq!(built.rows[0].kind, CorporateActionKind::Dividend); + assert_eq!(built.rows[0].cash_amount, Some(0.25)); + assert_eq!(built.rows[0].currency.as_deref(), Some("CAD")); + assert_eq!(built.rows[0].ratio, None); + assert_eq!(built.rows[1].kind, CorporateActionKind::Dividend); + assert_eq!(built.rows[1].cash_amount, Some(1.42)); + assert_eq!(built.rows[1].currency.as_deref(), Some("CAD")); + + for bad_cash in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01] { + let err = build_corporate_actions( + empty_splits(), + [( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d_ex, + cash: bad_cash, + currency: "CAD".to_string(), + declared_date: None, + }, + )], + empty_delistings(), + ) + .unwrap_err(); + assert!( + matches!(err, CorporateActionError::InvalidDividendCash { ex_date, .. } if ex_date == d_ex), + "expected InvalidDividendCash for {bad_cash}, got {err:?}" + ); + assert!(!err.to_string().is_empty()); + } + + for bad_curr in ["", " ", "\t\n"] { + let err = build_corporate_actions( + empty_splits(), + [( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d_ex, + cash: 0.50, + currency: bad_curr.to_string(), + declared_date: None, + }, + )], + empty_delistings(), + ) + .unwrap_err(); + assert_eq!( + err, + CorporateActionError::EmptyDividendCurrency { ex_date: d_ex } + ); + assert!(!err.to_string().is_empty()); + } + } + + #[test] + fn point_in_time_known_at_clamping_and_mixed_invariant() { + let ex = ymd_to_epoch_days(2024, 8, 15).unwrap(); + let before = ymd_to_epoch_days(2024, 8, 1).unwrap(); + let after = ymd_to_epoch_days(2024, 8, 20).unwrap(); + + let built = build_corporate_actions( + [ + // declared < ex -> declared_date + ( + "K1".to_string(), + SplitActionEvent { + ex_date: ex, + ratio: 2.0, + declared_date: Some(before), + }, + ), + // declared == ex -> declared_date + ( + "K2".to_string(), + SplitActionEvent { + ex_date: ex, + ratio: 3.0, + declared_date: Some(ex), + }, + ), + // declared == None -> ex_date_fallback + ( + "K3".to_string(), + SplitActionEvent { + ex_date: ex, + ratio: 4.0, + declared_date: None, + }, + ), + // declared > ex -> ex_date_fallback, preserves raw declared_date, counts declared_after_ex_date + ( + "K4".to_string(), + SplitActionEvent { + ex_date: ex, + ratio: 5.0, + declared_date: Some(after), + }, + ), + ], + [( + "K5".to_string(), + DividendActionEvent { + ex_date: ex, + cash: 0.75, + currency: "USD".to_string(), + declared_date: Some(after), + }, + )], + empty_delistings(), + ) + .unwrap(); + + assert_stats_conservation(&built); + assert_eq!(built.stats.known_at_declared_date, 2); + assert_eq!(built.stats.known_at_ex_date_fallback, 3); + assert_eq!(built.stats.declared_after_ex_date, 2); + assert_eq!(built.stats.known_at_delist_date, 0); + + // K1: declared < ex + assert_eq!(built.rows[0].key, "K1"); + assert_eq!(built.rows[0].known_at_date, before); + assert_eq!(built.rows[0].known_at_source, KnownAtSource::DeclaredDate); + + // K2: declared == ex + assert_eq!(built.rows[1].key, "K2"); + assert_eq!(built.rows[1].known_at_date, ex); + assert_eq!(built.rows[1].known_at_source, KnownAtSource::DeclaredDate); + + // K3: missing declared_date + assert_eq!(built.rows[2].key, "K3"); + assert_eq!(built.rows[2].declared_date, None); + assert_eq!(built.rows[2].known_at_date, ex); + assert_eq!(built.rows[2].known_at_source, KnownAtSource::ExDateFallback); + + // K4: declared > ex (split) + assert_eq!(built.rows[3].key, "K4"); + assert_eq!(built.rows[3].declared_date, Some(after)); + assert_eq!(built.rows[3].known_at_date, ex); + assert_eq!(built.rows[3].known_at_source, KnownAtSource::ExDateFallback); + + // K5: declared > ex (dividend) + assert_eq!(built.rows[4].key, "K5"); + assert_eq!(built.rows[4].declared_date, Some(after)); + assert_eq!(built.rows[4].known_at_date, ex); + assert_eq!(built.rows[4].known_at_source, KnownAtSource::ExDateFallback); + + for row in &built.rows { + assert!( + row.known_at_date <= row.ex_date, + "look-ahead leakage on row {row:?}" + ); + } + } + + #[test] + fn delisting_otc_transfer_terminal_returns_and_validation() { + let d_sivb = ymd_to_epoch_days(2023, 3, 28).unwrap(); + let d_shumway = ymd_to_epoch_days(2022, 6, 30).unwrap(); + let d_bankrupt = ymd_to_epoch_days(2024, 11, 7).unwrap(); + let d_zero = ymd_to_epoch_days(2024, 12, 2).unwrap(); + + let built = build_corporate_actions( + empty_splits(), + empty_dividends(), + [ + // SIVB -> SIVBQ OTC continuation + ( + "SIVB".to_string(), + DelistingOutcomeEvent { + delist_date: d_sivb, + successor_key: Some("SIVBQ".to_string()), + terminal_return: None, + }, + ), + // Shumway NYSE/AMEX -30% + ( + "DELIST_30".to_string(), + DelistingOutcomeEvent { + delist_date: d_shumway, + successor_key: None, + terminal_return: Some(-0.3), + }, + ), + // Total loss -100% + ( + "DELIST_100".to_string(), + DelistingOutcomeEvent { + delist_date: d_bankrupt, + successor_key: None, + terminal_return: Some(-1.0), + }, + ), + // -0.0 boundary normalized to +0.0 + ( + "DELIST_ZERO".to_string(), + DelistingOutcomeEvent { + delist_date: d_zero, + successor_key: None, + terminal_return: Some(-0.0), + }, + ), + // Neither set -> dropped & counted + ( + "NO_OUTCOME".to_string(), + DelistingOutcomeEvent { + delist_date: d_zero, + successor_key: None, + terminal_return: None, + }, + ), + ], + ) + .unwrap(); + + assert_stats_conservation(&built); + assert_eq!(built.stats.delistings_in, 5); + assert_eq!(built.stats.otc_delist_transfers_out, 1); + assert_eq!(built.stats.delistings_out, 3); + assert_eq!(built.stats.delist_without_outcome, 1); + assert_eq!(built.stats.known_at_delist_date, 4); + assert_eq!(built.rows.len(), 4); + + let r_100 = built.rows.iter().find(|r| r.key == "DELIST_100").unwrap(); + assert_eq!(r_100.kind, CorporateActionKind::Delisting); + assert_eq!(r_100.ex_date, d_bankrupt); + assert_eq!(r_100.declared_date, None); + assert_eq!(r_100.successor_key, None); + assert_eq!(r_100.terminal_return, Some(-1.0)); + assert_eq!(r_100.known_at_date, d_bankrupt); + assert_eq!(r_100.known_at_source, KnownAtSource::DelistDate); + + let r_30 = built.rows.iter().find(|r| r.key == "DELIST_30").unwrap(); + assert_eq!(r_30.kind, CorporateActionKind::Delisting); + assert_eq!(r_30.terminal_return, Some(-0.3)); + + let r_zero = built.rows.iter().find(|r| r.key == "DELIST_ZERO").unwrap(); + assert_eq!(r_zero.kind, CorporateActionKind::Delisting); + assert_eq!( + opt_f64_bits(r_zero.terminal_return), + Some(0.0_f64.to_bits()) + ); + + let r_sivb = built.rows.iter().find(|r| r.key == "SIVB").unwrap(); + assert_eq!(r_sivb.kind, CorporateActionKind::OtcDelistTransfer); + assert_eq!(r_sivb.ex_date, d_sivb); + assert_eq!(r_sivb.declared_date, None); + assert_eq!(r_sivb.successor_key.as_deref(), Some("SIVBQ")); + assert_eq!(r_sivb.terminal_return, None); + assert_eq!(r_sivb.known_at_date, d_sivb); + assert_eq!(r_sivb.known_at_source, KnownAtSource::DelistDate); + + for bad_return in [0.1, -1.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let err = build_corporate_actions( + empty_splits(), + empty_dividends(), + [( + "BAD".to_string(), + DelistingOutcomeEvent { + delist_date: d_shumway, + successor_key: None, + terminal_return: Some(bad_return), + }, + )], + ) + .unwrap_err(); + assert!( + matches!(err, CorporateActionError::InvalidTerminalReturn { delist_date, .. } if delist_date == d_shumway), + "expected InvalidTerminalReturn for {bad_return}, got {err:?}" + ); + assert!(!err.to_string().is_empty()); + } + + let err = build_corporate_actions( + empty_splits(), + empty_dividends(), + [( + "BOTH".to_string(), + DelistingOutcomeEvent { + delist_date: d_sivb, + successor_key: Some("BOTHQ".to_string()), + terminal_return: Some(-0.55), + }, + )], + ) + .unwrap_err(); + assert_eq!( + err, + CorporateActionError::ConflictingDelistingOutcome { + delist_date: d_sivb + } + ); + assert!(!err.to_string().is_empty()); + } + + #[test] + fn shuffled_mixed_fixture_is_bit_deterministic_and_conserves_stats() { + let d1 = ymd_to_epoch_days(2023, 3, 28).unwrap(); + let d2 = ymd_to_epoch_days(2024, 6, 10).unwrap(); + let d1_decl = ymd_to_epoch_days(2023, 3, 10).unwrap(); + let d2_late = ymd_to_epoch_days(2024, 6, 15).unwrap(); + + let splits = vec![ + ( + "AAPL".to_string(), + SplitActionEvent { + ex_date: d2, + ratio: 4.0, + declared_date: Some(d1_decl), + }, + ), + ( + "AAPL".to_string(), + SplitActionEvent { + ex_date: d1, + ratio: 1.0, + declared_date: None, + }, + ), + ( + "RY.TO".to_string(), + SplitActionEvent { + ex_date: d2, + ratio: 0.5, + declared_date: Some(d2_late), + }, + ), + ( + "AAPL".to_string(), + SplitActionEvent { + ex_date: d2, + ratio: 2.0, + declared_date: Some(d1_decl), + }, + ), + ]; + + let dividends = vec![ + ( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d2, + cash: 1.25, + currency: "CAD".to_string(), + declared_date: Some(d1_decl), + }, + ), + ( + "RY.TO".to_string(), + DividendActionEvent { + ex_date: d2, + cash: 1.25, + currency: "USD".to_string(), + declared_date: Some(d1_decl), + }, + ), + ( + "AAPL".to_string(), + DividendActionEvent { + ex_date: d2, + cash: 0.25, + currency: "USD".to_string(), + declared_date: None, + }, + ), + ( + "AAPL".to_string(), + DividendActionEvent { + ex_date: d1, + cash: 0.0, + currency: "".to_string(), + declared_date: None, + }, + ), + ]; + + let delistings = vec![ + ( + "SIVB".to_string(), + DelistingOutcomeEvent { + delist_date: d1, + successor_key: Some("SIVBQ".to_string()), + terminal_return: None, + }, + ), + ( + "OLDCO".to_string(), + DelistingOutcomeEvent { + delist_date: d2, + successor_key: None, + terminal_return: Some(-0.55), + }, + ), + ( + "OLDCO".to_string(), + DelistingOutcomeEvent { + delist_date: d2, + successor_key: None, + terminal_return: Some(-1.0), + }, + ), + ( + "QUIET".to_string(), + DelistingOutcomeEvent { + delist_date: d1, + successor_key: None, + terminal_return: None, + }, + ), + ]; + + let baseline = + build_corporate_actions(splits.clone(), dividends.clone(), delistings.clone()).unwrap(); + assert_stats_conservation(&baseline); + for row in &baseline.rows { + assert!(row.known_at_date <= row.ex_date); + } + + let perms: [[usize; 4]; 5] = [ + [3, 2, 1, 0], + [1, 3, 0, 2], + [2, 0, 3, 1], + [0, 3, 2, 1], + [2, 1, 0, 3], + ]; + + for perm in perms { + let sp = perm.iter().map(|&i| splits[i].clone()); + let dv = perm.iter().rev().map(|&i| dividends[i].clone()); + let dl = perm.iter().map(|&i| delistings[i].clone()); + let candidate = build_corporate_actions(sp, dv, dl).unwrap(); + assert_eq!(candidate.stats, baseline.stats); + assert_rows_bit_identical(&candidate.rows, &baseline.rows); + } + } + + #[test] + fn empty_inputs_return_empty_rows_and_zero_stats() { + let built = build_corporate_actions( + empty_splits::(), + empty_dividends(), + empty_delistings(), + ) + .unwrap(); + assert!(built.rows.is_empty()); + assert_eq!(built.stats, CorporateActionsStats::default()); + assert_stats_conservation(&built); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index aec92b70..cb3852db 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -3,12 +3,18 @@ pub mod adj; pub mod bench; pub mod cli; +pub mod corporate_actions; pub mod split; pub use adj::{ adj_factors_after, build_adj_factors, AdjBuildStats, AdjError, AdjFactorBuild, AdjFactorRow, DividendEvent, }; +pub use corporate_actions::{ + build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow, + CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, + KnownAtSource, SplitActionEvent, +}; pub use split::{ unadjust_ohlcv, unadjust_price, unadjust_volume, ymd_to_epoch_days, OhlcvBar, SplitEntry, SplitError, SplitEvent, SplitTable, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 53b8771f..fd5d7701 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -3,7 +3,9 @@ use std::env; use std::process::ExitCode; -use curate_etl::bench::{run_adj_benchmark, run_split_benchmark}; +use curate_etl::bench::{ + run_adj_benchmark, run_corporate_actions_benchmark, run_split_benchmark, +}; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; const NAME: &str = env!("CARGO_PKG_NAME"); @@ -80,6 +82,46 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchCorporateActions(events)) => { + let report = match run_corporate_actions_benchmark(events) { + Ok(report) => report, + Err(err) => { + eprintln!("error: corporate_actions benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-corporate-actions"); + println!( + " input: events={} splits={} dividends={} delistings={} keys={}", + report.events, + report.splits_in, + report.dividends_in, + report.delistings_in, + report.key_count + ); + println!( + " build: rows_out={} keys_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}", + report.rows_out, + report.keys_out, + report.build_elapsed_ms, + report.events_per_sec, + report.ns_per_event, + report.checksum + ); + println!( + " stats: split_noops={} zero_div={} delist_no_outcome={} otc_transfers={} delistings={} declared={} ex_fallback={} declared_after_ex={} delist_date={}", + report.stats.split_noops_dropped, + report.stats.dividend_zero_cash_dropped, + report.stats.delist_without_outcome, + report.stats.otc_delist_transfers_out, + report.stats.delistings_out, + report.stats.known_at_declared_date, + report.stats.known_at_ex_date_fallback, + report.stats.declared_after_ex_date, + report.stats.known_at_delist_date + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME));