From 78411a2eb647642aed72f64b5593b149f9e063e8 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 18:13:34 -0500 Subject: [PATCH 1/3] =?UTF-8?q?T-65:=20M1.2b=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20pure=20`adj=5Ffactors`=20builder=20(qmSplits=20+=20qmDiv?= =?UTF-8?q?idends=20=E2=86=92=20per-ex-date=20split/dividend/cumulative=20?= =?UTF-8?q?factors)=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 | 43 +- tools/curate-etl/src/adj.rs | 1088 +++++++++++++++++++++++++++++++++ tools/curate-etl/src/bench.rs | 149 +++++ tools/curate-etl/src/cli.rs | 144 +++++ tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/main.rs | 136 ++--- 6 files changed, 1461 insertions(+), 105 deletions(-) create mode 100644 tools/curate-etl/src/adj.rs create mode 100644 tools/curate-etl/src/cli.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 3ae82aa7..8e6f71f9 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 and bar un-adjustment core. +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. ## Scope & Sign Conventions @@ -20,7 +20,28 @@ Aligned with `design/DATA-CONTRACTS.md` (§1 `qmSplits`, `eodPrices`, `eodIntrad - `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor` - `unadjust_ohlcv(bar, factor)` applies both so dollar volume (`raw_close * raw_volume == adj_close * adj_volume`) is invariant. -## Local Benchmark +## `adj_factors` Builder (`M1.2b`) + +`build_adj_factors` (`src/adj.rs`) turns split (`qmSplits`) and cash-dividend (`qmDividends`) event streams into sorted, unique per-`(key, ex_date)` rows matching the `adj_factors/part.parquet` columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, split_factor, div_cash, div_currency, cum_split_factor, cum_total_factor`), omitting `usdFxRate` per contract. + +> **Contract interpretation note:** `design/DATA-CONTRACTS.md` names `split_factor`, `div_cash`, `div_currency`, `cum_split_factor`, and `cum_total_factor` without writing formulas. Rules 3–5 below document this crate's back-adjustment divisor definitions so downstream consumers and reviewers can verify parity with `SplitTable::cum_factor_after`. + +Rules: +1. **Split normalization:** Drop `ratio == 1.0` no-ops (counted in `stats.split_noops_dropped`). Multiply same-day splits in `f64::total_cmp` order; if they cancel back to `1.0` (e.g. `2.0 * 0.5`), drop the split component (and omit the row if no dividend is present on that date). +2. **Dividend normalization:** Drop `cash == 0.0` events (counted in `stats.dividend_zero_cash_dropped`). Sum same-day same-currency cash dividends in `f64::total_cmp` order into `div_cash`. Split-only rows carry `div_cash = 0.0` and `div_currency = None`; dividend-only rows carry `split_factor = 1.0`. Two different dividend currencies on the same `(key, ex_date)` return `AdjError::ConflictingDividendCurrency`. +3. **`cum_split_factor` (back-adjustment divisor):** Product of `split_factor` over this row and all later rows of the same key (inclusive of the row's own `ex_date`). For any bar dated `d`, the first row with `ex_date > d` (`adj_factors_after(rows, key, d).0`) matches `SplitTable::cum_factor_after(key, d)` bitwise. +4. **Per-row dividend factor:** `prev_close / (prev_close - div_cash)` when `prev_close` (the raw close of the last session strictly before `ex_date`) is present, finite, `> div_cash > 0.0`, and `prev_close_currency == div_currency`. Otherwise falls back to `1.0` in strict priority order while preserving `div_cash` and `div_currency` on the row and incrementing the matching counter: + - `dividends_missing_prev_close` (`prev_close` is `None` or non-finite) + - `dividends_currency_mismatch` (`prev_close_currency != Some(div_currency)`) + - `dividends_not_below_prev_close` (`prev_close <= div_cash`) +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. + +## Local Benchmarks + +### `bench-split` Fixed-seed (`std`-only SplitMix64), zero-allocation hot-loop benchmark over `20,000` symbol keys and `19,000` forward/reverse split events spanning `1990-01-01..=2025-12-31` (default `10,000,000` bar lookups + `unadjust_volume`): @@ -28,14 +49,26 @@ Fixed-seed (`std`-only SplitMix64), zero-allocation hot-loop benchmark over `20, cargo run --release -p curate-etl --offline -- bench-split [rows] ``` -### Recorded Local Result - Command: `cargo run --release -p curate-etl --offline -- bench-split` - Table: `keys=20000`, `keys_with_splits=12153`, `events=18999`, `build=1.73 ms` - Run: `rows=10000000`, `elapsed=367.40 ms`, `throughput=27218476 rows/s`, `latency=36.74 ns/row`, `checksum=259124314244145.531` -## Deferred Follow-Ups (`M1.2b` / `M2`) +### `bench-adj` + +Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` `i32` `listing_id` keys spanning `1990-01-01..=2025-12-31` with ~4% splits and ~96% dividends (default `1,000,000` mixed events), timing only `build_adj_factors`: + +```bash +cargo run --release -p curate-etl --offline -- bench-adj [events] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-adj` + +- Input: `events=1000000`, `splits=39861`, `dividends=960139`, `keys=20000` +- Build: `rows_out=986702`, `keys_out=20000`, `elapsed=235.10 ms`, `throughput=4253442 events/s`, `latency=235.10 ns/event`, `checksum=17888280.062` +- 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`) 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/adj.rs b/tools/curate-etl/src/adj.rs new file mode 100644 index 00000000..fe0fcbe1 --- /dev/null +++ b/tools/curate-etl/src/adj.rs @@ -0,0 +1,1088 @@ +//! Pure, in-memory `adj_factors` builder (`qmSplits` + `qmDividends` -> per-ex-date factors). +//! +//! Produces sorted per-`(key, ex_date)` rows matching the `adj_factors/part.parquet` schema +//! columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, split_factor, div_cash, +//! div_currency, cum_split_factor, cum_total_factor`): +//! - Splits use the same sign convention as [`crate::split`]: `ratio = new_shares / old_shares` +//! (`10.0` for a 10:1 forward split, `0.05` for a 1:20 reverse split). +//! - `cum_split_factor` is the cumulative product of `split_factor` over this row and all later +//! rows of the same key (inclusive of the row's own `ex_date`), so for any bar dated `d`, the +//! first row with `ex_date > d` equals [`crate::split::SplitTable::cum_factor_after`]. +//! - Per-row dividend factor is `prev_close / (prev_close - div_cash)` when `prev_close` is +//! present, finite, `> div_cash > 0.0`, and matches `div_currency`; otherwise `1.0` with the +//! fallback reason counted in [`AdjBuildStats`]. +//! - `cum_total_factor = cum_split_factor * suffix_product(div_factor)`. + +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; + +use crate::split::SplitEvent; + +/// A single cash dividend event. +/// +/// Deliberately omits `usdFxRate` (contract: ignore `qmDividends.usdFxRate`). +#[derive(Debug, Clone, PartialEq)] +pub struct DividendEvent { + /// 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, + /// Dividend currency code (e.g. `"USD"`, `"CAD"`). Must be non-empty when `cash > 0.0`. + pub currency: String, + /// Raw (un-adjusted) close of the last session strictly before `ex_date`, if known. + pub prev_close: Option, + /// Currency of `prev_close`, if known. + pub prev_close_currency: Option, +} + +/// A single curated `adj_factors` row, unique per `(key, ex_date)`. +#[derive(Debug, Clone, PartialEq)] +pub struct AdjFactorRow { + pub key: K, + pub ex_date: i32, + pub split_factor: f64, + pub div_cash: f64, + pub div_currency: Option, + pub cum_split_factor: f64, + pub cum_total_factor: f64, +} + +/// Summary counters produced alongside the built [`AdjFactorRow`] vector. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AdjBuildStats { + pub split_events_in: usize, + pub split_noops_dropped: usize, + pub dividend_events_in: usize, + pub dividend_zero_cash_dropped: usize, + pub rows_out: usize, + pub keys_out: usize, + pub dividends_missing_prev_close: usize, + pub dividends_currency_mismatch: usize, + pub dividends_not_below_prev_close: usize, +} + +/// Output of [`build_adj_factors`]: sorted rows plus build statistics. +#[derive(Debug, Clone, PartialEq)] +pub struct AdjFactorBuild { + pub rows: Vec>, + pub stats: AdjBuildStats, +} + +/// Typed errors returned while validating inputs or computing cumulative factors. +#[derive(Debug, Clone, PartialEq)] +pub enum AdjError { + /// 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 }, + /// Two dividends on the same `(key, ex_date)` carried different currencies. + ConflictingDividendCurrency { + ex_date: i32, + first: String, + second: String, + }, + /// Combining or compounding split/dividend factors overflowed to infinity or underflowed to 0. + FactorOverflow { ex_date: i32, factor: f64 }, +} + +impl fmt::Display for AdjError { + 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::ConflictingDividendCurrency { + ex_date, + first, + second, + } => { + write!( + f, + "conflicting dividend currencies '{first}' and '{second}' on epoch day {ex_date}" + ) + } + Self::FactorOverflow { ex_date, factor } => { + write!( + f, + "adjustment factor overflow/underflow ({factor}) at epoch day {ex_date}" + ) + } + } + } +} + +impl Error for AdjError {} + +enum RawEvent { + Split(f64), + Dividend { + cash: f64, + currency: String, + prev_close: Option, + prev_close_currency: Option, + }, +} + +/// Deterministic preference rank for selecting a `prev_close` candidate when multiple dividend +/// records share the same `(key, ex_date)`. +#[inline] +fn prev_close_rank( + prev_close: Option, + prev_close_currency: Option<&str>, + div_currency: &str, +) -> u8 { + match prev_close { + Some(pc) if pc.is_finite() => { + if prev_close_currency == Some(div_currency) { + 3 + } else { + 2 + } + } + Some(_) => 1, + None => u8::from(prev_close_currency.is_some()), + } +} + +/// Deterministic comparison between two `prev_close` candidates so output is invariant to +/// input permutation of same-day dividends. +#[inline] +fn is_better_prev_close( + cand_close: Option, + cand_currency: Option<&str>, + best_close: Option, + best_currency: Option<&str>, + div_currency: &str, +) -> bool { + let cand_rank = prev_close_rank(cand_close, cand_currency, div_currency); + let best_rank = prev_close_rank(best_close, best_currency, div_currency); + if cand_rank != best_rank { + return cand_rank > best_rank; + } + let close_ord = match (cand_close, best_close) { + (Some(a), Some(b)) => a.total_cmp(&b), + (Some(_), None) => Ordering::Greater, + (None, Some(_)) => Ordering::Less, + (None, None) => Ordering::Equal, + }; + match close_ord { + Ordering::Greater => true, + Ordering::Less => false, + Ordering::Equal => cand_currency > best_currency, + } +} + +/// Builds sorted, per-`(key, ex_date)` adjustment factor rows from split and cash-dividend streams. +/// +/// - Rejects non-finite or `<= 0.0` split ratios with [`AdjError::InvalidSplitRatio`]. +/// - Drops `ratio == 1.0` split no-ops and counts them in `stats.split_noops_dropped`. +/// - Rejects non-finite or `< 0.0` dividend cash with [`AdjError::InvalidDividendCash`]. +/// - Drops `cash == 0.0` dividends and counts them in `stats.dividend_zero_cash_dropped`. +/// - Rejects empty/whitespace currency on positive dividends with [`AdjError::EmptyDividendCurrency`]. +/// - Coalesces same-day splits (multiplying in `f64::total_cmp` order) and same-day dividends +/// (summing in `f64::total_cmp` order; rejecting currency conflicts with +/// [`AdjError::ConflictingDividendCurrency`]). +/// - Computes right-to-left cumulative suffix factors per key, rejecting overflow or underflow +/// with [`AdjError::FactorOverflow`]. +pub fn build_adj_factors(splits: S, dividends: D) -> Result, AdjError> +where + K: Ord + Clone, + S: IntoIterator, + D: IntoIterator, +{ + let splits_iter = splits.into_iter(); + let divs_iter = dividends.into_iter(); + let cap = splits_iter + .size_hint() + .0 + .saturating_add(divs_iter.size_hint().0); + + let mut raw: Vec<(K, i32, RawEvent)> = Vec::with_capacity(cap); + let mut stats = AdjBuildStats::default(); + + for (key, event) in splits_iter { + stats.split_events_in += 1; + if !event.ratio.is_finite() || event.ratio <= 0.0 { + return Err(AdjError::InvalidSplitRatio { + ex_date: event.ex_date, + ratio: event.ratio, + }); + } + if event.ratio == 1.0 { + stats.split_noops_dropped += 1; + continue; + } + raw.push((key, event.ex_date, RawEvent::Split(event.ratio))); + } + + for (key, event) in divs_iter { + stats.dividend_events_in += 1; + if !event.cash.is_finite() || event.cash < 0.0 { + return Err(AdjError::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(AdjError::EmptyDividendCurrency { + ex_date: event.ex_date, + }); + } + raw.push(( + key, + event.ex_date, + RawEvent::Dividend { + cash: event.cash, + currency: event.currency, + prev_close: event.prev_close, + prev_close_currency: event.prev_close_currency, + }, + )); + } + + if raw.is_empty() { + return Ok(AdjFactorBuild { + rows: Vec::new(), + stats, + }); + } + + raw.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); + + let mut rows: Vec> = Vec::with_capacity(raw.len()); + let mut same_day_splits: Vec = Vec::new(); + let mut same_day_div_cash: Vec = Vec::new(); + let mut key_div_factors: Vec = Vec::new(); + + let total_raw = raw.len(); + let mut idx = 0usize; + + while idx < total_raw { + let key_start = idx; + let key = raw[key_start].0.clone(); + while idx < total_raw && raw[idx].0 == key { + idx += 1; + } + let key_end = idx; + + let key_rows_start = rows.len(); + key_div_factors.clear(); + + let mut day_idx = key_start; + while day_idx < key_end { + let ex_date = raw[day_idx].1; + let day_start = day_idx; + while day_idx < key_end && raw[day_idx].1 == ex_date { + day_idx += 1; + } + let day_end = day_idx; + + same_day_splits.clear(); + same_day_div_cash.clear(); + + let mut div_currency: Option = None; + let mut has_prev_candidate = false; + let mut best_prev_close: Option = None; + let mut best_prev_close_currency: Option = None; + + for (_, _, ev) in &raw[day_start..day_end] { + match ev { + RawEvent::Split(ratio) => same_day_splits.push(*ratio), + RawEvent::Dividend { + cash, + currency, + prev_close, + prev_close_currency, + } => { + match &div_currency { + None => div_currency = Some(currency.clone()), + Some(first) if first != currency => { + return Err(AdjError::ConflictingDividendCurrency { + ex_date, + first: first.clone(), + second: currency.clone(), + }); + } + Some(_) => {} + } + same_day_div_cash.push(*cash); + + if !has_prev_candidate + || is_better_prev_close( + *prev_close, + prev_close_currency.as_deref(), + best_prev_close, + best_prev_close_currency.as_deref(), + currency.as_str(), + ) + { + has_prev_candidate = true; + best_prev_close = *prev_close; + best_prev_close_currency = prev_close_currency.clone(); + } + } + } + } + + let mut split_factor = 1.0_f64; + if !same_day_splits.is_empty() { + same_day_splits.sort_unstable_by(f64::total_cmp); + let mut combined = same_day_splits[0]; + for &ratio in &same_day_splits[1..] { + combined *= ratio; + if !combined.is_finite() || combined <= 0.0 { + return Err(AdjError::FactorOverflow { + ex_date, + factor: combined, + }); + } + } + split_factor = combined; + } + let has_effective_split = split_factor != 1.0; + + let mut div_cash = 0.0_f64; + if !same_day_div_cash.is_empty() { + same_day_div_cash.sort_unstable_by(f64::total_cmp); + for &cash in &same_day_div_cash { + div_cash += cash; + if !div_cash.is_finite() { + return Err(AdjError::FactorOverflow { + ex_date, + factor: div_cash, + }); + } + } + } + let has_dividend = !same_day_div_cash.is_empty(); + + if !has_effective_split && !has_dividend { + continue; + } + + let div_factor = if let Some(ref curr) = div_currency { + match best_prev_close { + Some(pc) if pc.is_finite() => { + if best_prev_close_currency.as_deref() != Some(curr.as_str()) { + stats.dividends_currency_mismatch += 1; + 1.0 + } else if pc <= div_cash { + stats.dividends_not_below_prev_close += 1; + 1.0 + } else { + let denom = pc - div_cash; + let factor = pc / denom; + if !factor.is_finite() || factor <= 0.0 { + return Err(AdjError::FactorOverflow { ex_date, factor }); + } + factor + } + } + _ => { + stats.dividends_missing_prev_close += 1; + 1.0 + } + } + } else { + 1.0 + }; + + rows.push(AdjFactorRow { + key: key.clone(), + ex_date, + split_factor, + div_cash, + div_currency, + cum_split_factor: 1.0, + cum_total_factor: 1.0, + }); + key_div_factors.push(div_factor); + } + + if rows.len() > key_rows_start { + stats.keys_out += 1; + let mut running_split = 1.0_f64; + let mut running_div = 1.0_f64; + + if let Some(key_slice) = rows.get_mut(key_rows_start..) { + for (row, &div_factor) in + key_slice.iter_mut().rev().zip(key_div_factors.iter().rev()) + { + if row.split_factor != 1.0 { + running_split *= row.split_factor; + if !running_split.is_finite() || running_split <= 0.0 { + return Err(AdjError::FactorOverflow { + ex_date: row.ex_date, + factor: running_split, + }); + } + } + if div_factor != 1.0 { + running_div *= div_factor; + if !running_div.is_finite() || running_div <= 0.0 { + return Err(AdjError::FactorOverflow { + ex_date: row.ex_date, + factor: running_div, + }); + } + } + let cum_total = if running_div == 1.0 { + running_split + } else { + let prod = running_split * running_div; + if !prod.is_finite() || prod <= 0.0 { + return Err(AdjError::FactorOverflow { + ex_date: row.ex_date, + factor: prod, + }); + } + prod + }; + row.cum_split_factor = running_split; + row.cum_total_factor = cum_total; + } + } + } + } + + stats.rows_out = rows.len(); + Ok(AdjFactorBuild { rows, stats }) +} + +/// Zero-allocation binary-search helper returning `(cum_split_factor, cum_total_factor)` of the +/// first row for `key` with `ex_date > bar_date`, or `(1.0, 1.0)` if no such row exists. +/// +/// Assumes `rows` is sorted ascending by `(key, ex_date)` (as returned by [`build_adj_factors`]). +#[inline] +pub fn adj_factors_after(rows: &[AdjFactorRow], key: &K, bar_date: i32) -> (f64, f64) { + let idx = rows.partition_point(|row| match row.key.cmp(key) { + Ordering::Less => true, + Ordering::Equal => row.ex_date <= bar_date, + Ordering::Greater => false, + }); + match rows.get(idx) { + Some(row) if &row.key == key => (row.cum_split_factor, row.cum_total_factor), + _ => (1.0, 1.0), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::split::{ymd_to_epoch_days, SplitTable}; + + fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(1.0); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); + } + + fn div( + ex_date: i32, + cash: f64, + currency: &str, + prev_close: Option, + prev_close_currency: Option<&str>, + ) -> DividendEvent { + DividendEvent { + ex_date, + cash, + currency: currency.to_string(), + prev_close, + prev_close_currency: prev_close_currency.map(str::to_string), + } + } + + #[test] + fn nvda_splits_4_for_1_and_10_for_1_without_dividends() { + let d1 = ymd_to_epoch_days(2021, 7, 20).unwrap(); + let d2 = ymd_to_epoch_days(2024, 6, 10).unwrap(); + + let built = build_adj_factors( + [ + ( + "NVDA".to_string(), + SplitEvent { + ex_date: d2, + ratio: 10.0, + }, + ), + ( + "NVDA".to_string(), + SplitEvent { + ex_date: d1, + ratio: 4.0, + }, + ), + ], + std::iter::empty::<(String, DividendEvent)>(), + ) + .unwrap(); + + assert_eq!(built.rows.len(), 2); + assert_eq!(built.stats.rows_out, 2); + assert_eq!(built.stats.keys_out, 1); + assert_eq!(built.stats.split_events_in, 2); + assert_eq!(built.stats.dividend_events_in, 0); + + let r0 = &built.rows[0]; + assert_eq!(r0.key, "NVDA"); + assert_eq!(r0.ex_date, d1); + assert_eq!(r0.split_factor, 4.0); + assert_eq!(r0.div_cash, 0.0); + assert_eq!(r0.div_currency, None); + assert_eq!(r0.cum_split_factor, 40.0); + assert_eq!(r0.cum_total_factor, r0.cum_split_factor); + + let r1 = &built.rows[1]; + assert_eq!(r1.key, "NVDA"); + assert_eq!(r1.ex_date, d2); + assert_eq!(r1.split_factor, 10.0); + assert_eq!(r1.div_cash, 0.0); + assert_eq!(r1.div_currency, None); + assert_eq!(r1.cum_split_factor, 10.0); + assert_eq!(r1.cum_total_factor, r1.cum_split_factor); + } + + #[test] + fn cum_split_factor_matches_split_table_across_mixed_keys_and_exact_ex_dates() { + let mut state: u64 = 0x1234_5678_9ABC_DEF0; + let mut next_u64 = || { + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + }; + + let min_date = ymd_to_epoch_days(2005, 1, 1).unwrap(); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap(); + let span = (max_date - min_date + 1) as u64; + let ratios = [2.0, 3.0, 4.0, 0.5, 0.25, 0.05, 1.0]; + + let mut splits: Vec<(i32, SplitEvent)> = Vec::new(); + let mut dividends: Vec<(i32, DividendEvent)> = Vec::new(); + let mut interesting_dates: Vec<(i32, i32)> = Vec::new(); + + for _ in 0..400 { + let key = (next_u64() % 40) as i32; + let ex_date = min_date + (next_u64() % span) as i32; + let ratio = ratios[(next_u64() as usize) % ratios.len()]; + splits.push((key, SplitEvent { ex_date, ratio })); + interesting_dates.push((key, ex_date - 1)); + interesting_dates.push((key, ex_date)); + interesting_dates.push((key, ex_date + 1)); + } + + for _ in 0..800 { + let key = (next_u64() % 50) as i32; + let ex_date = min_date + (next_u64() % span) as i32; + let cash = ((next_u64() % 200) + 1) as f64 * 0.01; + dividends.push((key, div(ex_date, cash, "USD", Some(100.0), Some("USD")))); + interesting_dates.push((key, ex_date - 1)); + interesting_dates.push((key, ex_date)); + interesting_dates.push((key, ex_date + 1)); + } + + let table = SplitTable::from_events(splits.clone()).unwrap(); + let built = build_adj_factors(splits, dividends).unwrap(); + + for (key, bar_date) in interesting_dates { + let expected = table.cum_factor_after(&key, bar_date); + let (actual, _) = adj_factors_after(&built.rows, &key, bar_date); + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "mismatch for key={key} bar_date={bar_date}: adj={actual} split_table={expected}" + ); + } + + // Unknown key returns (1.0, 1.0) matching SplitTable. + assert_eq!(adj_factors_after(&built.rows, &999, min_date), (1.0, 1.0)); + assert_eq!(table.cum_factor_after(&999, min_date), 1.0); + } + + #[test] + fn reverse_split_noop_and_same_day_reciprocal_cancellation() { + let d1 = ymd_to_epoch_days(2025, 6, 18).unwrap(); + let d2 = ymd_to_epoch_days(2025, 7, 1).unwrap(); + let d3 = ymd_to_epoch_days(2025, 8, 1).unwrap(); + + let built = build_adj_factors( + [ + // NEXM.V-style 1:20 reverse split + ( + "NEXM.V".to_string(), + SplitEvent { + ex_date: d1, + ratio: 0.05, + }, + ), + // ratio == 1.0 no-op -> dropped + ( + "NOOP".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1.0, + }, + ), + // Same-day reciprocal splits alone -> cancelled, no row + ( + "CANCEL_ONLY".to_string(), + SplitEvent { + ex_date: d2, + ratio: 2.0, + }, + ), + ( + "CANCEL_ONLY".to_string(), + SplitEvent { + ex_date: d2, + ratio: 0.5, + }, + ), + // Same-day reciprocal splits paired with a dividend -> row kept with split_factor == 1.0 + ( + "CANCEL_WITH_DIV".to_string(), + SplitEvent { + ex_date: d3, + ratio: 2.0, + }, + ), + ( + "CANCEL_WITH_DIV".to_string(), + SplitEvent { + ex_date: d3, + ratio: 0.5, + }, + ), + ], + [( + "CANCEL_WITH_DIV".to_string(), + div(d3, 1.0, "USD", Some(50.0), Some("USD")), + )], + ) + .unwrap(); + + assert_eq!(built.stats.split_events_in, 6); + assert_eq!(built.stats.split_noops_dropped, 1); + assert_eq!(built.stats.rows_out, 2); + assert_eq!(built.stats.keys_out, 2); + + // Keys sorted ascending: "CANCEL_WITH_DIV" < "NEXM.V" + assert_eq!(built.rows[0].key, "CANCEL_WITH_DIV"); + assert_eq!(built.rows[0].ex_date, d3); + assert_eq!(built.rows[0].split_factor, 1.0); + assert_eq!(built.rows[0].div_cash, 1.0); + assert_eq!(built.rows[0].div_currency.as_deref(), Some("USD")); + assert_eq!(built.rows[0].cum_split_factor, 1.0); + assert_rel_eq(built.rows[0].cum_total_factor, 50.0 / 49.0, 1e-12); + + assert_eq!(built.rows[1].key, "NEXM.V"); + assert_eq!(built.rows[1].ex_date, d1); + assert_eq!(built.rows[1].split_factor, 0.05); + assert_eq!(built.rows[1].cum_split_factor, 0.05); + assert_eq!(built.rows[1].cum_total_factor, 0.05); + } + + #[test] + fn dividend_factor_compounds_into_earlier_split_cum_total_but_not_cum_split() { + let split_date = ymd_to_epoch_days(2023, 1, 10).unwrap(); + let div_date = ymd_to_epoch_days(2024, 3, 15).unwrap(); + + let built = build_adj_factors( + [( + "AAPL".to_string(), + SplitEvent { + ex_date: split_date, + ratio: 4.0, + }, + )], + [( + "AAPL".to_string(), + div(div_date, 2.0, "USD", Some(100.0), Some("USD")), + )], + ) + .unwrap(); + + assert_eq!(built.rows.len(), 2); + let expected_div_factor = 100.0 / 98.0; + + // Earlier split row: cum_split excludes dividend, cum_total includes it. + let r0 = &built.rows[0]; + assert_eq!(r0.ex_date, split_date); + assert_eq!(r0.split_factor, 4.0); + assert_eq!(r0.div_cash, 0.0); + assert_eq!(r0.div_currency, None); + assert_eq!(r0.cum_split_factor, 4.0); + assert_rel_eq(r0.cum_total_factor, 4.0 * expected_div_factor, 1e-12); + + // Later dividend row: split_factor == 1.0, cum_split == 1.0, cum_total == 100/98. + let r1 = &built.rows[1]; + assert_eq!(r1.ex_date, div_date); + assert_eq!(r1.split_factor, 1.0); + assert_eq!(r1.div_cash, 2.0); + assert_eq!(r1.div_currency.as_deref(), Some("USD")); + assert_eq!(r1.cum_split_factor, 1.0); + assert_rel_eq(r1.cum_total_factor, expected_div_factor, 1e-12); + } + + #[test] + fn same_day_split_and_multiple_dividends_merge_deterministically() { + let d = ymd_to_epoch_days(2024, 5, 1).unwrap(); + let d_zero = ymd_to_epoch_days(2024, 6, 1).unwrap(); + + let perms = [ + vec![ + div(d, 0.1, "USD", Some(100.0), Some("USD")), + div(d, 0.2, "USD", None, None), + div(d, 0.3, "USD", Some(100.0), Some("USD")), + div(d_zero, 0.0, "", None, None), + ], + vec![ + div(d, 0.3, "USD", Some(100.0), Some("USD")), + div(d, 0.1, "USD", None, None), + div(d_zero, 0.0, " ", None, None), + div(d, 0.2, "USD", Some(100.0), Some("USD")), + ], + ]; + + let mut baseline_cash_bits: Option = None; + let mut baseline_total_bits: Option = None; + + for div_list in perms { + let built = build_adj_factors( + [( + 101_i32, + SplitEvent { + ex_date: d, + ratio: 2.0, + }, + )], + div_list.into_iter().map(|ev| (101_i32, ev)), + ) + .unwrap(); + + assert_eq!(built.rows.len(), 1); + assert_eq!(built.stats.dividend_events_in, 4); + assert_eq!(built.stats.dividend_zero_cash_dropped, 1); + assert_eq!(built.stats.dividends_missing_prev_close, 0); + + let row = &built.rows[0]; + assert_eq!(row.key, 101); + assert_eq!(row.ex_date, d); + assert_eq!(row.split_factor, 2.0); + assert_rel_eq(row.div_cash, 0.6, 1e-12); + assert_eq!(row.div_currency.as_deref(), Some("USD")); + assert_eq!(row.cum_split_factor, 2.0); + assert_rel_eq(row.cum_total_factor, 2.0 * (100.0 / 99.4), 1e-12); + + match baseline_cash_bits { + None => baseline_cash_bits = Some(row.div_cash.to_bits()), + Some(bits) => assert_eq!(row.div_cash.to_bits(), bits), + } + match baseline_total_bits { + None => baseline_total_bits = Some(row.cum_total_factor.to_bits()), + Some(bits) => assert_eq!(row.cum_total_factor.to_bits(), bits), + } + } + } + + #[test] + fn dividend_fallbacks_preserve_cash_and_currency_and_increment_exact_counters() { + let d1 = ymd_to_epoch_days(2024, 1, 10).unwrap(); + let d2 = ymd_to_epoch_days(2024, 2, 10).unwrap(); + let d3 = ymd_to_epoch_days(2024, 3, 10).unwrap(); + let d4 = ymd_to_epoch_days(2024, 4, 10).unwrap(); + let d5 = ymd_to_epoch_days(2024, 5, 10).unwrap(); + let d6 = ymd_to_epoch_days(2024, 6, 10).unwrap(); + + let built = build_adj_factors( + std::iter::empty::<(String, SplitEvent)>(), + [ + // Missing prev_close (None) + ("F".to_string(), div(d1, 1.5, "USD", None, Some("USD"))), + // Missing prev_close (NaN) + ( + "F".to_string(), + div(d2, 1.5, "USD", Some(f64::NAN), Some("USD")), + ), + // Missing prev_close (Infinity) + ( + "F".to_string(), + div(d3, 1.5, "USD", Some(f64::INFINITY), Some("USD")), + ), + // Currency mismatch (CAD dividend vs USD close) + ( + "F".to_string(), + div(d4, 1.25, "CAD", Some(50.0), Some("USD")), + ), + // prev_close == div_cash + ( + "F".to_string(), + div(d5, 10.0, "USD", Some(10.0), Some("USD")), + ), + // prev_close < div_cash + ( + "F".to_string(), + div(d6, 12.0, "USD", Some(10.0), Some("USD")), + ), + ], + ) + .unwrap(); + + assert_eq!(built.rows.len(), 6); + assert_eq!(built.stats.dividends_missing_prev_close, 3); + assert_eq!(built.stats.dividends_currency_mismatch, 1); + assert_eq!(built.stats.dividends_not_below_prev_close, 2); + + for row in &built.rows { + assert_eq!(row.split_factor, 1.0); + assert_eq!(row.cum_split_factor, 1.0); + assert_eq!(row.cum_total_factor, 1.0); + assert!(row.div_cash > 0.0); + assert!(row.div_currency.is_some()); + } + assert_eq!(built.rows[3].div_cash, 1.25); + assert_eq!(built.rows[3].div_currency.as_deref(), Some("CAD")); + } + + #[test] + fn invalid_inputs_and_overflows_return_typed_errors() { + let d1 = ymd_to_epoch_days(2024, 1, 2).unwrap(); + let d2 = ymd_to_epoch_days(2024, 6, 3).unwrap(); + + // Invalid split ratios + for bad_ratio in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let err = build_adj_factors( + [( + "BAD".to_string(), + SplitEvent { + ex_date: d1, + ratio: bad_ratio, + }, + )], + std::iter::empty::<(String, DividendEvent)>(), + ) + .unwrap_err(); + assert!( + matches!(err, AdjError::InvalidSplitRatio { ex_date, .. } if ex_date == d1), + "expected InvalidSplitRatio for {bad_ratio}, got {err:?}" + ); + } + + // Invalid dividend cash + for bad_cash in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let err = build_adj_factors( + std::iter::empty::<(String, SplitEvent)>(), + [( + "BAD".to_string(), + div(d1, bad_cash, "USD", Some(100.0), Some("USD")), + )], + ) + .unwrap_err(); + assert!( + matches!(err, AdjError::InvalidDividendCash { ex_date, .. } if ex_date == d1), + "expected InvalidDividendCash for {bad_cash}, got {err:?}" + ); + } + + // Empty dividend currency on positive cash + for empty_curr in ["", " "] { + let err = build_adj_factors( + std::iter::empty::<(String, SplitEvent)>(), + [( + "BAD".to_string(), + div(d1, 1.0, empty_curr, Some(100.0), Some("USD")), + )], + ) + .unwrap_err(); + assert!(matches!( + err, + AdjError::EmptyDividendCurrency { ex_date } if ex_date == d1 + )); + } + + // Conflicting dividend currencies on the same (key, ex_date) + let conflict = build_adj_factors( + std::iter::empty::<(String, SplitEvent)>(), + [ + ( + "MIX".to_string(), + div(d1, 1.0, "USD", Some(100.0), Some("USD")), + ), + ( + "MIX".to_string(), + div(d1, 1.0, "CAD", Some(100.0), Some("CAD")), + ), + ], + ) + .unwrap_err(); + assert!(matches!( + conflict, + AdjError::ConflictingDividendCurrency { ex_date, .. } if ex_date == d1 + )); + + // Cumulative split overflow + let split_overflow = build_adj_factors( + [ + ( + "OVF".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e200, + }, + ), + ( + "OVF".to_string(), + SplitEvent { + ex_date: d2, + ratio: 1e200, + }, + ), + ], + std::iter::empty::<(String, DividendEvent)>(), + ) + .unwrap_err(); + assert!(matches!( + split_overflow, + AdjError::FactorOverflow { ex_date, .. } if ex_date == d1 + )); + + // Cumulative split underflow to 0.0 + let split_underflow = build_adj_factors( + [ + ( + "UDF".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e-200, + }, + ), + ( + "UDF".to_string(), + SplitEvent { + ex_date: d2, + ratio: 1e-200, + }, + ), + ], + std::iter::empty::<(String, DividendEvent)>(), + ) + .unwrap_err(); + assert!(matches!( + split_underflow, + AdjError::FactorOverflow { ex_date, .. } if ex_date == d1 + )); + + // Cumulative total overflow (split * div_factor > f64::MAX) + let total_overflow = build_adj_factors( + [( + "TOT".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e308, + }, + )], + [( + "TOT".to_string(), + div(d2, 90.0, "USD", Some(100.0), Some("USD")), + )], + ) + .unwrap_err(); + assert!(matches!( + total_overflow, + AdjError::FactorOverflow { ex_date, .. } if ex_date == d1 + )); + } + + #[test] + fn shuffled_inputs_are_strictly_sorted_and_unique_and_empty_input_is_zeroed() { + let empty = build_adj_factors( + std::iter::empty::<(i32, SplitEvent)>(), + std::iter::empty::<(i32, DividendEvent)>(), + ) + .unwrap(); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, AdjBuildStats::default()); + + let d1 = ymd_to_epoch_days(2020, 1, 15).unwrap(); + let d2 = ymd_to_epoch_days(2021, 6, 15).unwrap(); + let d3 = ymd_to_epoch_days(2022, 9, 15).unwrap(); + + let built = build_adj_factors( + [ + ( + 30_i32, + SplitEvent { + ex_date: d3, + ratio: 2.0, + }, + ), + ( + 10_i32, + SplitEvent { + ex_date: d2, + ratio: 3.0, + }, + ), + ( + 20_i32, + SplitEvent { + ex_date: d1, + ratio: 0.5, + }, + ), + ( + 10_i32, + SplitEvent { + ex_date: d1, + ratio: 2.0, + }, + ), + ], + [ + (30_i32, div(d1, 0.5, "USD", Some(50.0), Some("USD"))), + (10_i32, div(d2, 1.0, "USD", Some(100.0), Some("USD"))), + (20_i32, div(d3, 0.25, "CAD", Some(25.0), Some("CAD"))), + ], + ) + .unwrap(); + + assert_eq!(built.stats.keys_out, 3); + assert_eq!(built.stats.rows_out, built.rows.len()); + for pair in built.rows.windows(2) { + assert!( + (pair[0].key, pair[0].ex_date) < (pair[1].key, pair[1].ex_date), + "rows not strictly sorted: {:?} vs {:?}", + pair[0], + pair[1] + ); + } + } +} diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index a2764b13..4be639db 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -3,13 +3,16 @@ use std::hint::black_box; use std::time::Instant; +use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; 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 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 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). @@ -117,6 +120,118 @@ pub fn run_split_benchmark(rows: usize) -> Result { }) } +/// Summary metrics produced by [`run_adj_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AdjBenchReport { + pub events: usize, + pub split_events_in: usize, + pub dividend_events_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: f64, + pub stats: AdjBuildStats, +} + +/// Runs the fixed-seed `build_adj_factors` benchmark for `events` mixed split and dividend events. +/// +/// Generates `events` deterministic events across `20_000` `i32` `listing_id` keys spanning +/// `1990-01-01..=2025-12-31` (~4% splits including occasional `1.0` no-ops, ~96% dividends with +/// realistic USD/CAD home currencies and small fallback fractions), times only +/// [`build_adj_factors`], and returns throughput plus a deterministic checksum. +pub fn run_adj_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(ADJ_BENCH_SEED); + let mut splits: Vec<(i32, SplitEvent)> = Vec::with_capacity(events / 20); + let mut dividends: Vec<(i32, DividendEvent)> = Vec::with_capacity(events); + + 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()] + }; + splits.push((key, SplitEvent { ex_date, ratio })); + } else { + let (home_curr, alt_curr) = if key % 5 == 0 { + ("CAD", "USD") + } else { + ("USD", "CAD") + }; + let fallback_roll = rng.next_u64() % 100; + let cash = if fallback_roll == 5 { + 0.0 + } else { + ((rng.next_u64() % 150) + 5) as f64 * 0.01 + }; + let (prev_close, prev_close_currency) = match fallback_roll { + 0 | 1 => (None, Some(home_curr.to_string())), + 2 | 3 => ( + Some(20.0 + (rng.next_u64() % 200) as f64), + Some(alt_curr.to_string()), + ), + 4 => (Some(cash * 0.5), Some(home_curr.to_string())), + _ => ( + Some(20.0 + (rng.next_u64() % 200) as f64), + Some(home_curr.to_string()), + ), + }; + dividends.push(( + key, + DividendEvent { + ex_date, + cash, + currency: home_curr.to_string(), + prev_close, + prev_close_currency, + }, + )); + } + } + + let split_events_in = splits.len(); + let dividend_events_in = dividends.len(); + + let build_start = Instant::now(); + let built = build_adj_factors(splits, dividends)?; + 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 acc = 0.0_f64; + for row in &built.rows { + acc += row.cum_split_factor + row.cum_total_factor + row.div_cash; + } + let checksum = black_box(acc); + let (events_per_sec, ns_per_event) = compute_rates(events, build_elapsed_secs); + + Ok(AdjBenchReport { + events, + split_events_in, + dividend_events_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::*; @@ -163,4 +278,38 @@ mod tests { assert_eq!(report.rows_per_sec, 0.0); assert_eq!(report.ns_per_row, 0.0); } + + #[test] + fn adj_benchmark_small_run_is_deterministic() { + let a = run_adj_benchmark(5_000).unwrap(); + let b = run_adj_benchmark(5_000).unwrap(); + + assert_eq!(a.events, 5_000); + assert_eq!(a.split_events_in + a.dividend_events_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.to_bits(), b.checksum.to_bits()); + assert!(a.checksum.is_finite() && a.checksum > 0.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.dividends_missing_prev_close > 0); + assert!(a.stats.dividends_currency_mismatch > 0); + assert!(a.stats.dividends_not_below_prev_close > 0); + } + + #[test] + fn adj_benchmark_zero_events_handles_cleanly() { + let report = run_adj_benchmark(0).unwrap(); + assert_eq!(report.events, 0); + assert_eq!(report.split_events_in, 0); + assert_eq!(report.dividend_events_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.keys_out, 0); + assert_eq!(report.stats, AdjBuildStats::default()); + assert_eq!(report.checksum, 0.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 new file mode 100644 index 00000000..fa8ea153 --- /dev/null +++ b/tools/curate-etl/src/cli.rs @@ -0,0 +1,144 @@ +//! Command-line argument parsing for the `curate-etl` binary. +//! +//! 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}; + +/// Parsed CLI command to execute. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CliAction { + Help, + Version, + BenchSplit(usize), + BenchAdj(usize), +} + +/// Formats full help text including binary name and version. +pub fn format_usage(name: &str, version: &str) -> String { + format!( + "{name} {version}\n\ + \n\ + 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})" + ) +} + +/// Formats concise usage text for stderr on invalid invocations. +pub fn format_usage_stderr(name: &str) -> String { + format!( + "Usage:\n\ + {name} [--help | -h]\n\ + {name} [--version | -V]\n\ + {name} bench-split [rows]\n\ + {name} bench-adj [events]" + ) +} + +/// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. +pub fn parse_args(args: &[String]) -> Result { + let slices: Vec<&str> = args.iter().map(String::as_str).collect(); + match slices.as_slice() { + [] | ["--help"] | ["-h"] => Ok(CliAction::Help), + ["--version"] | ["-V"] => Ok(CliAction::Version), + [flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => { + Err(format!("unexpected argument '{extra}' after '{flag}'")) + } + ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), + ["bench-split", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-split", _, ..] => Err("too many arguments for bench-split".to_string()), + ["bench-adj"] => Ok(CliAction::BenchAdj(DEFAULT_ADJ_BENCH_EVENTS)), + ["bench-adj", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchAdj(n)), + _ => Err(format!( + "invalid event count '{raw}' (expected a positive integer)" + )), + }, + ["bench-adj", _, ..] => Err("too many arguments for bench-adj".to_string()), + [other, ..] => Err(format!("unknown argument '{other}'")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn to_args(items: &[&str]) -> Vec { + items.iter().map(|s| (*s).to_string()).collect() + } + + #[test] + fn parses_standalone_help_and_version_flags() { + assert_eq!(parse_args(&to_args(&[])), Ok(CliAction::Help)); + assert_eq!(parse_args(&to_args(&["--help"])), Ok(CliAction::Help)); + assert_eq!(parse_args(&to_args(&["-h"])), Ok(CliAction::Help)); + assert_eq!(parse_args(&to_args(&["--version"])), Ok(CliAction::Version)); + assert_eq!(parse_args(&to_args(&["-V"])), Ok(CliAction::Version)); + } + + #[test] + fn rejects_trailing_arguments_after_help_or_version() { + for invalid in [ + &["--help", "--unknown"][..], + &["-h", "extra"][..], + &["--version", "--offine"][..], + &["-V", "bench-split"][..], + ] { + let err = parse_args(&to_args(invalid)).unwrap_err(); + assert!( + err.contains("unexpected argument"), + "expected unexpected argument error for {invalid:?}, got: {err}" + ); + } + } + + #[test] + fn parses_and_validates_bench_split_and_unknown_args() { + assert_eq!( + parse_args(&to_args(&["bench-split"])), + Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-split", "100000"])), + Ok(CliAction::BenchSplit(100_000)) + ); + assert!(parse_args(&to_args(&["bench-split", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-split", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-split", "10", "20"])).is_err()); + assert!(parse_args(&to_args(&["--unknown"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_adj_args() { + assert_eq!( + parse_args(&to_args(&["bench-adj"])), + Ok(CliAction::BenchAdj(DEFAULT_ADJ_BENCH_EVENTS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-adj", "250000"])), + Ok(CliAction::BenchAdj(250_000)) + ); + assert!(parse_args(&to_args(&["bench-adj", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-adj", "x"])).is_err()); + assert!(parse_args(&to_args(&["bench-adj", "10", "20"])).is_err()); + } + + #[test] + fn usage_strings_mention_both_benchmarks() { + let full = format_usage("curate-etl", "0.1.0"); + assert!(full.contains("bench-split")); + assert!(full.contains("bench-adj")); + + let short = format_usage_stderr("curate-etl"); + assert!(short.contains("bench-split")); + assert!(short.contains("bench-adj")); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 86295e40..aec92b70 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -1,8 +1,14 @@ #![deny(clippy::all)] +pub mod adj; pub mod bench; +pub mod cli; pub mod split; +pub use adj::{ + adj_factors_after, build_adj_factors, AdjBuildStats, AdjError, AdjFactorBuild, AdjFactorRow, + DividendEvent, +}; 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 bf4e0396..9b86ba2c 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -3,64 +3,18 @@ use std::env; use std::process::ExitCode; -use curate_etl::bench::{run_split_benchmark, DEFAULT_BENCH_ROWS}; +use curate_etl::bench::{run_adj_benchmark, run_split_benchmark}; +use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; const NAME: &str = env!("CARGO_PKG_NAME"); const VERSION: &str = env!("CARGO_PKG_VERSION"); -fn print_usage() { - println!( - "{NAME} {VERSION}\n\ - \n\ - 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})" - ); -} - -fn print_usage_stderr() { - eprintln!( - "Usage:\n\ - {NAME} [--help | -h]\n\ - {NAME} [--version | -V]\n\ - {NAME} bench-split [rows]" - ); -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum CliAction { - Help, - Version, - BenchSplit(usize), -} - -fn parse_args(args: &[String]) -> Result { - let slices: Vec<&str> = args.iter().map(String::as_str).collect(); - match slices.as_slice() { - [] | ["--help"] | ["-h"] => Ok(CliAction::Help), - ["--version"] | ["-V"] => Ok(CliAction::Version), - [flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => { - Err(format!("unexpected argument '{extra}' after '{flag}'")) - } - ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), - ["bench-split", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-split", _, ..] => Err("too many arguments for bench-split".to_string()), - [other, ..] => Err(format!("unknown argument '{other}'")), - } -} - fn main() -> ExitCode { let args: Vec = env::args().skip(1).collect(); match parse_args(&args) { Ok(CliAction::Help) => { - print_usage(); + println!("{}", format_usage(NAME, VERSION)); ExitCode::SUCCESS } Ok(CliAction::Version) => { @@ -93,60 +47,42 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchAdj(events)) => { + let report = match run_adj_benchmark(events) { + Ok(report) => report, + Err(err) => { + eprintln!("error: adj benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-adj"); + println!( + " input: events={} splits={} dividends={} keys={}", + report.events, report.split_events_in, report.dividend_events_in, report.key_count + ); + println!( + " build: rows_out={} keys_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum={:.3}", + 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={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}", + report.stats.split_noops_dropped, + report.stats.dividend_zero_cash_dropped, + report.stats.dividends_missing_prev_close, + report.stats.dividends_currency_mismatch, + report.stats.dividends_not_below_prev_close + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); - print_usage_stderr(); + eprintln!("{}", format_usage_stderr(NAME)); ExitCode::FAILURE } } } - -#[cfg(test)] -mod tests { - use super::*; - - fn to_args(items: &[&str]) -> Vec { - items.iter().map(|s| (*s).to_string()).collect() - } - - #[test] - fn parses_standalone_help_and_version_flags() { - assert_eq!(parse_args(&to_args(&[])), Ok(CliAction::Help)); - assert_eq!(parse_args(&to_args(&["--help"])), Ok(CliAction::Help)); - assert_eq!(parse_args(&to_args(&["-h"])), Ok(CliAction::Help)); - assert_eq!(parse_args(&to_args(&["--version"])), Ok(CliAction::Version)); - assert_eq!(parse_args(&to_args(&["-V"])), Ok(CliAction::Version)); - } - - #[test] - fn rejects_trailing_arguments_after_help_or_version() { - for invalid in [ - &["--help", "--unknown"][..], - &["-h", "extra"][..], - &["--version", "--offine"][..], - &["-V", "bench-split"][..], - ] { - let err = parse_args(&to_args(invalid)).unwrap_err(); - assert!( - err.contains("unexpected argument"), - "expected unexpected argument error for {invalid:?}, got: {err}" - ); - } - } - - #[test] - fn parses_and_validates_bench_split_and_unknown_args() { - assert_eq!( - parse_args(&to_args(&["bench-split"])), - Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-split", "100000"])), - Ok(CliAction::BenchSplit(100_000)) - ); - assert!(parse_args(&to_args(&["bench-split", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-split", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-split", "10", "20"])).is_err()); - assert!(parse_args(&to_args(&["--unknown"])).is_err()); - } -} From f15dddcd22f7d6c92c021be89fba501f00878dba Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 18:20:59 -0500 Subject: [PATCH 2/3] =?UTF-8?q?T-65:=20M1.2b=20=E2=80=94=20`tools/curate-e?= =?UTF-8?q?tl`:=20pure=20`adj=5Ffactors`=20builder=20(qmSplits=20+=20qmDiv?= =?UTF-8?q?idends=20=E2=86=92=20per-ex-date=20split/dividend/cumulative=20?= =?UTF-8?q?factors)=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 | 2 +- tools/curate-etl/src/adj.rs | 45 ++++++++++++++++++++++-------------- tools/curate-etl/src/main.rs | 5 ++-- 3 files changed, 32 insertions(+), 20 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 8e6f71f9..6464046a 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -65,7 +65,7 @@ cargo run --release -p curate-etl --offline -- bench-adj [events] Command: `cargo run --release -p curate-etl --offline -- bench-adj` - Input: `events=1000000`, `splits=39861`, `dividends=960139`, `keys=20000` -- Build: `rows_out=986702`, `keys_out=20000`, `elapsed=235.10 ms`, `throughput=4253442 events/s`, `latency=235.10 ns/event`, `checksum=17888280.062` +- 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`) diff --git a/tools/curate-etl/src/adj.rs b/tools/curate-etl/src/adj.rs index fe0fcbe1..4fd28652 100644 --- a/tools/curate-etl/src/adj.rs +++ b/tools/curate-etl/src/adj.rs @@ -757,25 +757,32 @@ mod tests { let d = ymd_to_epoch_days(2024, 5, 1).unwrap(); let d_zero = ymd_to_epoch_days(2024, 6, 1).unwrap(); - let perms = [ - vec![ - div(d, 0.1, "USD", Some(100.0), Some("USD")), - div(d, 0.2, "USD", None, None), - div(d, 0.3, "USD", Some(100.0), Some("USD")), - div(d_zero, 0.0, "", None, None), - ], - vec![ - div(d, 0.3, "USD", Some(100.0), Some("USD")), - div(d, 0.1, "USD", None, None), - div(d_zero, 0.0, " ", None, None), - div(d, 0.2, "USD", Some(100.0), Some("USD")), - ], + // Three positive cash values whose unsorted left-to-right f64 sums differ bitwise: + // ((1.0 + 1e-16) + 1e-16) == 1.0, whereas ((1e-16 + 1e-16) + 1.0) > 1.0. + let c_small = 1e-16_f64; + let c_large = 1.0_f64; + assert_ne!( + ((c_large + c_small) + c_small).to_bits(), + ((c_small + c_small) + c_large).to_bits() + ); + let expected_cash = (c_small + c_small) + c_large; + + // One fixed fixture containing distinct finite same-currency prev_close values (99.5 vs + // 100.0) plus a missing prev_close and a zero-cash event; every permutation must coalesce + // to the exact same bit-identical cash sum and tie-broken prev_close (100.0). + let fixture = [ + div(d, c_large, "USD", Some(99.5), Some("USD")), + div(d, c_small, "USD", None, None), + div(d, c_small, "USD", Some(100.0), Some("USD")), + div(d_zero, 0.0, "", None, None), ]; + let perm_indices = [[0, 1, 2, 3], [2, 0, 3, 1], [1, 2, 0, 3], [3, 2, 1, 0]]; let mut baseline_cash_bits: Option = None; let mut baseline_total_bits: Option = None; - for div_list in perms { + for order in perm_indices { + let div_list = order.into_iter().map(|i| (101_i32, fixture[i].clone())); let built = build_adj_factors( [( 101_i32, @@ -784,7 +791,7 @@ mod tests { ratio: 2.0, }, )], - div_list.into_iter().map(|ev| (101_i32, ev)), + div_list, ) .unwrap(); @@ -797,10 +804,14 @@ mod tests { assert_eq!(row.key, 101); assert_eq!(row.ex_date, d); assert_eq!(row.split_factor, 2.0); - assert_rel_eq(row.div_cash, 0.6, 1e-12); + assert_eq!(row.div_cash.to_bits(), expected_cash.to_bits()); assert_eq!(row.div_currency.as_deref(), Some("USD")); assert_eq!(row.cum_split_factor, 2.0); - assert_rel_eq(row.cum_total_factor, 2.0 * (100.0 / 99.4), 1e-12); + assert_rel_eq( + row.cum_total_factor, + 2.0 * (100.0 / (100.0 - expected_cash)), + 1e-12, + ); match baseline_cash_bits { None => baseline_cash_bits = Some(row.div_cash.to_bits()), diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 9b86ba2c..53b8771f 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -61,13 +61,14 @@ fn main() -> ExitCode { report.events, report.split_events_in, report.dividend_events_in, report.key_count ); println!( - " build: rows_out={} keys_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum={:.3}", + " build: rows_out={} keys_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum={:.3} (0x{:016x})", report.rows_out, report.keys_out, report.build_elapsed_ms, report.events_per_sec, report.ns_per_event, - report.checksum + report.checksum, + report.checksum.to_bits() ); println!( " stats: split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}", From ea840a145df795671872750ce54c90d6cc5d88d3 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 18:26:20 -0500 Subject: [PATCH 3/3] T-65: tests --- tools/curate-etl/tests/adj_contract.rs | 477 +++++++++++++++++++++++++ 1 file changed, 477 insertions(+) create mode 100644 tools/curate-etl/tests/adj_contract.rs diff --git a/tools/curate-etl/tests/adj_contract.rs b/tools/curate-etl/tests/adj_contract.rs new file mode 100644 index 00000000..56624e58 --- /dev/null +++ b/tools/curate-etl/tests/adj_contract.rs @@ -0,0 +1,477 @@ +//! QA contract tests for the public `curate_etl` `adj_factors` API (T-65 / M1.2b). +//! +//! Uses only the crate's public surface plus independent reference computations, so these guard +//! the behaviour that later Parquet / back-adjustment consumers will rely on. + +use std::collections::BTreeMap; +use std::process::{Command, Output}; + +use curate_etl::bench::run_adj_benchmark; +use curate_etl::{ + adj_factors_after, build_adj_factors, ymd_to_epoch_days, AdjError, AdjFactorRow, DividendEvent, + SplitEvent, SplitTable, +}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn split(ex_date: i32, ratio: f64) -> SplitEvent { + SplitEvent { ex_date, ratio } +} + +fn div( + ex_date: i32, + cash: f64, + currency: &str, + prev_close: Option, + prev_close_currency: Option<&str>, +) -> DividendEvent { + DividendEvent { + ex_date, + cash, + currency: currency.to_string(), + prev_close, + prev_close_currency: prev_close_currency.map(str::to_string), + } +} + +fn no_splits() -> std::iter::Empty<(K, SplitEvent)> { + std::iter::empty() +} + +fn no_divs() -> std::iter::Empty<(K, DividendEvent)> { + std::iter::empty() +} + +fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(f64::MIN_POSITIVE); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); +} + +/// Fixed-seed SplitMix64 so fixtures are reproducible without external crates. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +/// Deterministic Fisher-Yates shuffle. +fn shuffle(items: &mut [T], rng: &mut Rng) { + for i in (1..items.len()).rev() { + let j = (rng.next() % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +#[test] +fn cum_split_matches_split_table_bitwise_on_every_day_of_a_dense_grid() { + // Arrange: few keys, a narrow date window and many events so same-day collisions + // (including reciprocal cancellations and 1.0 no-ops) are common. + let mut rng = Rng(0x7E57_AD1F_0000_0001); + let base = day(2020, 1, 1); + let ratios = [2.0, 0.5, 3.0, 1.0 / 3.0, 4.0, 0.25, 10.0, 0.05, 1.0]; + let mut splits = Vec::new(); + let mut divs = Vec::new(); + for _ in 0..300 { + let key = (rng.next() % 6) as i32; + let ex = base + (rng.next() % 40) as i32; + splits.push((key, split(ex, ratios[(rng.next() % 9) as usize]))); + } + for _ in 0..300 { + let key = (rng.next() % 7) as i32; + let ex = base + (rng.next() % 40) as i32; + divs.push((key, div(ex, 0.25, "USD", Some(50.0), Some("USD")))); + } + + // Act + let table = SplitTable::from_events(splits.clone()).expect("valid splits"); + let built = build_adj_factors(splits, divs).expect("valid build"); + + // Assert: every bar date from before the window to after it, for every key incl. a missing one. + for key in 0..8 { + for bar in (base - 2)..(base + 43) { + let expected = table.cum_factor_after(&key, bar); + let (actual, _) = adj_factors_after(&built.rows, &key, bar); + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "key={key} bar={bar}: adj={actual} table={expected}" + ); + } + } +} + +/// Independent oracle: recompute each row's cumulative factors as plain suffix products. +fn assert_suffix_products(rows: &[AdjFactorRow], div_factor: &BTreeMap<(i32, i32), f64>) { + for (i, row) in rows.iter().enumerate() { + let later: Vec<&AdjFactorRow> = + rows[i..].iter().take_while(|r| r.key == row.key).collect(); + let split_prod: f64 = later.iter().map(|r| r.split_factor).product(); + let div_prod: f64 = later + .iter() + .map(|r| div_factor.get(&(r.key, r.ex_date)).copied().unwrap_or(1.0)) + .product(); + assert_rel_eq(row.cum_split_factor, split_prod, 1e-12); + assert_rel_eq(row.cum_total_factor, split_prod * div_prod, 1e-12); + } +} + +#[test] +fn cumulative_factors_equal_independent_suffix_products() { + // Arrange: unique (key, date) per event so the expected per-row dividend factor is known. + let mut rng = Rng(0x7E57_AD1F_0000_0002); + let base = day(2010, 1, 1); + let mut splits = Vec::new(); + let mut divs = Vec::new(); + let mut expected_div = BTreeMap::new(); + for key in 0..20_i32 { + for slot in 0..30_i32 { + let ex = base + slot * 30 + key; + if rng.next() % 4 == 0 { + splits.push(( + key, + split(ex, [2.0, 0.1, 3.0, 0.5][(rng.next() % 4) as usize]), + )); + } else { + let cash = 0.01 * (1 + rng.next() % 300) as f64; + let pc = 10.0 + (rng.next() % 90) as f64; + expected_div.insert((key, ex), pc / (pc - cash)); + divs.push((key, div(ex, cash, "USD", Some(pc), Some("USD")))); + } + } + } + + // Act + let built = build_adj_factors(splits, divs).expect("valid build"); + + // Assert + assert_eq!(built.rows.len(), 20 * 30); + assert_suffix_products(&built.rows, &expected_div); +} + +#[test] +fn back_adjusted_closes_are_continuous_across_split_and_dividend_ex_dates() { + // Arrange: raw closes for a listing with a 4:1 split and a $2 dividend later. + let d_split = day(2024, 3, 4); + let d_div = day(2024, 6, 3); + let raw: [(i32, f64); 4] = [ + (d_split - 1, 400.0), // pre-split + (d_split, 100.0), // post-split, unchanged economics + (d_div - 1, 100.0), // cum-dividend + (d_div, 98.0), // ex-dividend drop by exactly the cash + ]; + let built = build_adj_factors( + [(7_i32, split(d_split, 4.0))], + [(7_i32, div(d_div, 2.0, "USD", Some(100.0), Some("USD")))], + ) + .expect("valid build"); + + // Act: total-return back-adjustment divides each raw close by the factor after its date. + let adj: Vec = raw + .iter() + .map(|&(d, close)| close / adj_factors_after(&built.rows, &7, d).1) + .collect(); + let split_only: Vec = raw + .iter() + .map(|&(d, close)| close / adj_factors_after(&built.rows, &7, d).0) + .collect(); + + // Assert: no jump on either ex-date for total return; split-only keeps the dividend drop. + assert_rel_eq(adj[0], adj[1], 1e-12); + assert_rel_eq(adj[2], adj[3], 1e-12); + assert_rel_eq(adj[3], 98.0, 1e-12); + assert_rel_eq(split_only[0], split_only[1], 1e-12); + assert_rel_eq(split_only[2], 100.0, 1e-12); + assert_rel_eq(split_only[3], 98.0, 1e-12); +} + +#[test] +fn full_input_permutations_produce_bitwise_identical_builds() { + // Arrange: one fixture with heavy same-day overlap of splits and dividends. + let mut rng = Rng(0x7E57_AD1F_0000_0003); + let base = day(2015, 1, 1); + let mut splits = Vec::new(); + let mut divs = Vec::new(); + for _ in 0..200 { + let key = (rng.next() % 5) as i32; + let ex = base + (rng.next() % 25) as i32; + splits.push(( + key, + split(ex, [2.0, 0.5, 3.0, 1.0][(rng.next() % 4) as usize]), + )); + } + for _ in 0..400 { + let key = (rng.next() % 5) as i32; + let ex = base + (rng.next() % 25) as i32; + let cash = [1.0, 1e-16, 0.1, 0.2, 0.0][(rng.next() % 5) as usize]; + let pc = match rng.next() % 4 { + 0 => None, + 1 => Some(99.5), + 2 => Some(100.0), + _ => Some(f64::NAN), + }; + divs.push((key, div(ex, cash, "USD", pc, Some("USD")))); + } + let baseline = build_adj_factors(splits.clone(), divs.clone()).expect("valid build"); + + for _ in 0..8 { + // Act + shuffle(&mut splits, &mut rng); + shuffle(&mut divs, &mut rng); + let again = build_adj_factors(splits.clone(), divs.clone()).expect("valid build"); + + // Assert + assert_eq!(again.stats, baseline.stats); + assert_eq!(again.rows.len(), baseline.rows.len()); + for (a, b) in again.rows.iter().zip(&baseline.rows) { + assert_eq!((a.key, a.ex_date), (b.key, b.ex_date)); + assert_eq!(a.split_factor.to_bits(), b.split_factor.to_bits()); + assert_eq!(a.div_cash.to_bits(), b.div_cash.to_bits()); + assert_eq!(a.div_currency, b.div_currency); + assert_eq!(a.cum_split_factor.to_bits(), b.cum_split_factor.to_bits()); + assert_eq!(a.cum_total_factor.to_bits(), b.cum_total_factor.to_bits()); + } + } +} + +#[test] +fn fallback_counters_follow_documented_priority_order() { + // Arrange: each event trips two fallback conditions; only the higher-priority one counts. + let d = |m| day(2024, m, 15); + let built = build_adj_factors( + no_splits::(), + [ + // non-finite prev_close + currency mismatch + (NaN <= cash is false) -> missing + (1, div(d(1), 1.0, "CAD", Some(f64::NAN), Some("USD"))), + // None prev_close with no currency at all -> missing + (1, div(d(2), 1.0, "USD", None, None)), + // currency mismatch + prev_close <= cash -> mismatch + (1, div(d(3), 5.0, "CAD", Some(1.0), Some("USD"))), + // finite prev_close but missing currency -> mismatch + (1, div(d(4), 1.0, "USD", Some(50.0), None)), + ], + ) + .expect("valid build"); + + assert_eq!(built.stats.dividends_missing_prev_close, 2); + assert_eq!(built.stats.dividends_currency_mismatch, 2); + assert_eq!(built.stats.dividends_not_below_prev_close, 0); + for row in &built.rows { + assert_eq!(row.cum_total_factor, 1.0); + assert!(row.div_cash > 0.0 && row.div_currency.is_some()); + } +} + +#[test] +fn same_day_dividends_prefer_a_matching_currency_prev_close() { + // Arrange: two same-day USD dividends; only one carries a usable USD prev_close. + let d = day(2024, 9, 2); + let fixtures = [ + div(d, 0.5, "USD", Some(80.0), Some("CAD")), + div(d, 0.5, "USD", Some(100.0), Some("USD")), + div(d, 0.5, "USD", None, None), + ]; + for order in [[0, 1, 2], [2, 1, 0], [1, 0, 2]] { + // Act + let built = build_adj_factors( + no_splits::(), + order.iter().map(|&i| (3, fixtures[i].clone())), + ) + .expect("valid build"); + + // Assert: factor uses the USD close and the summed cash; no fallback counted. + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].div_cash, 1.5); + assert_rel_eq(built.rows[0].cum_total_factor, 100.0 / 98.5, 1e-12); + assert_eq!(built.stats.dividends_currency_mismatch, 0); + assert_eq!(built.stats.dividends_missing_prev_close, 0); + } +} + +#[test] +fn zero_cash_dividends_are_dropped_even_with_empty_currency_or_negative_zero() { + let d1 = day(2024, 1, 2); + let d2 = day(2024, 2, 2); + let built = build_adj_factors( + [("Z".to_string(), split(d2, 2.0))], + [ + ("Z".to_string(), div(d1, 0.0, "", None, None)), + ( + "Z".to_string(), + div(d1, -0.0, "USD", Some(10.0), Some("USD")), + ), + ("Z".to_string(), div(d2, 0.0, " ", None, None)), + ], + ) + .expect("zero cash never errors"); + + assert_eq!(built.stats.dividend_events_in, 3); + assert_eq!(built.stats.dividend_zero_cash_dropped, 3); + assert_eq!( + built.rows.len(), + 1, + "zero-cash-only day must not emit a row" + ); + let row = &built.rows[0]; + assert_eq!((row.ex_date, row.split_factor), (d2, 2.0)); + assert_eq!(row.div_cash, 0.0); + assert_eq!(row.div_currency, None); + assert_eq!(row.cum_total_factor, 2.0); +} + +#[test] +fn split_only_ratio_one_and_cancelled_days_emit_nothing_and_count_no_keys() { + let d = day(2023, 5, 5); + let built = build_adj_factors( + [ + (1_i32, split(d, 1.0)), + (2_i32, split(d, 4.0)), + (2_i32, split(d, 0.25)), + ], + no_divs::(), + ) + .expect("valid build"); + + assert!(built.rows.is_empty()); + assert_eq!(built.stats.keys_out, 0); + assert_eq!(built.stats.rows_out, 0); + assert_eq!(built.stats.split_events_in, 3); + assert_eq!(built.stats.split_noops_dropped, 1); +} + +#[test] +fn invalid_event_after_many_valid_events_still_returns_typed_error() { + let base = day(2001, 1, 1); + let mut splits: Vec<(i32, SplitEvent)> = + (0..1_000).map(|i| (i % 10, split(base + i, 2.0))).collect(); + splits.push((3, split(base + 5_000, f64::NAN))); + let err = build_adj_factors(splits, no_divs::()).unwrap_err(); + assert!(matches!(err, AdjError::InvalidSplitRatio { ex_date, .. } if ex_date == base + 5_000)); + + let mut divs: Vec<(i32, DividendEvent)> = (0..1_000) + .map(|i| (i % 10, div(base + i, 0.1, "USD", Some(10.0), Some("USD")))) + .collect(); + divs.push((3, div(base + 6_000, -1e-9, "USD", Some(10.0), Some("USD")))); + let err = build_adj_factors(no_splits::(), divs).unwrap_err(); + assert!( + matches!(err, AdjError::InvalidDividendCash { ex_date, .. } if ex_date == base + 6_000) + ); +} + +#[test] +fn same_day_split_product_overflow_and_underflow_are_typed_errors() { + let d = day(2022, 2, 2); + for (a, b) in [(1e200, 1e200), (1e-200, 1e-200)] { + let err = build_adj_factors( + [(1_i32, split(d, a)), (1_i32, split(d, b))], + no_divs::(), + ) + .unwrap_err(); + assert!( + matches!(err, AdjError::FactorOverflow { ex_date, .. } if ex_date == d), + "{a}*{b}: {err:?}" + ); + } +} + +#[test] +fn compounding_dividend_factors_overflow_is_a_typed_error() { + // Each factor is ~1e7 (prev_close barely above cash); 60 rows exceed f64::MAX. + let base = day(2000, 1, 3); + let divs: Vec<(i32, DividendEvent)> = (0..60) + .map(|i| (9, div(base + i, 1.0, "USD", Some(1.000_000_1), Some("USD")))) + .collect(); + let err = build_adj_factors(no_splits::(), divs).unwrap_err(); + assert!(matches!(err, AdjError::FactorOverflow { .. }), "{err:?}"); +} + +#[test] +fn adj_factors_after_handles_boundaries_and_keys_absent_between_present_keys() { + let d1 = day(2020, 1, 10); + let d2 = day(2021, 1, 10); + let built = build_adj_factors( + [ + (10_i32, split(d1, 2.0)), + (10_i32, split(d2, 3.0)), + (30_i32, split(d1, 5.0)), + ], + no_divs::(), + ) + .expect("valid build"); + let rows = &built.rows; + + assert_eq!(adj_factors_after(rows, &10, d1 - 1).0, 6.0); + assert_eq!( + adj_factors_after(rows, &10, d1).0, + 3.0, + "bar on ex-date is post-split" + ); + assert_eq!(adj_factors_after(rows, &10, d2 - 1).0, 3.0); + assert_eq!(adj_factors_after(rows, &10, d2).0, 1.0); + assert_eq!(adj_factors_after(rows, &10, i32::MAX), (1.0, 1.0)); + assert_eq!(adj_factors_after(rows, &10, i32::MIN).0, 6.0); + // Key 20 sits between 10 and 30 and must not borrow key 30's row. + assert_eq!(adj_factors_after(rows, &20, d1 - 1), (1.0, 1.0)); + assert_eq!(adj_factors_after(rows, &0, d1 - 1), (1.0, 1.0)); + assert_eq!(adj_factors_after(rows, &30, d1 - 1).0, 5.0); + assert_eq!(adj_factors_after::(&[], &10, d1), (1.0, 1.0)); +} + +#[test] +fn default_bench_adj_checksum_matches_readme_recorded_bits() { + // README records rows_out=986702 and checksum 0x41710f4180ff5d60 for the default run. + let report = run_adj_benchmark(1_000_000).expect("bench builds"); + assert_eq!(report.rows_out, 986_702); + assert_eq!(report.keys_out, 20_000); + assert_eq!(report.split_events_in, 39_861); + assert_eq!(report.dividend_events_in, 960_139); + assert_eq!(report.checksum.to_bits(), 0x4171_0f41_80ff_5d60); +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +#[test] +fn bench_adj_binary_is_reproducible_and_rejects_invalid_args() { + let a = run_bin(&["bench-adj", "20000"]); + let b = run_bin(&["bench-adj", "20000"]); + assert!(a.status.success() && b.status.success()); + let checksum_of = |o: &Output| { + let text = String::from_utf8_lossy(&o.stdout).into_owned(); + assert!(text.contains("events/s"), "{text}"); + let start = text.find("checksum=").expect("checksum printed"); + text[start..].lines().next().unwrap_or_default().to_string() + }; + assert_eq!(checksum_of(&a), checksum_of(&b)); + assert!(checksum_of(&a).contains("(0x")); + + for args in [ + &["bench-adj", "0"][..], + &["bench-adj", "x"], + &["bench-adj", "10", "20"], + &["bench-adj", "-5"], + ] { + let out = run_bin(args); + assert!(!out.status.success(), "{args:?} should fail"); + let err = String::from_utf8_lossy(&out.stderr); + assert!( + err.contains("Usage:") && err.contains("bench-adj"), + "{args:?}: {err}" + ); + } +}