T-70: M1.2c — tools/curate-etl: pure corporate_actions builder (splits + dividends + OTC continuation / Shumway terminal delisting rows) with local benchmark (no new crates)

This commit is contained in:
Studio 2026-11-27 19:04:08 -05:00
parent 141a3a6d2b
commit 88625d6b70
6 changed files with 1429 additions and 9 deletions

View file

@ -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:

View file

@ -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<AdjBenchReport, AdjError> {
})
}
/// 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<CorporateActionsBenchReport, CorporateActionError> {
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<i32>)> = 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);
}
}

View file

@ -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<CliAction, String> {
)),
},
["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::<usize>() {
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"));
}
}

File diff suppressed because it is too large Load diff

View file

@ -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,

View file

@ -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));