From ce4b8fa91c438728d137a6f0af8d9c3e6dae517f Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 15:34:09 -0500 Subject: [PATCH] =?UTF-8?q?T-47:=20M1.2a=20=E2=80=94=20Scaffold=20`tools/c?= =?UTF-8?q?urate-etl`=20Rust=20crate:=20split-factor=20table=20+=20un-adju?= =?UTF-8?q?stment=20core=20with=20local=20benchmark=20(no=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 4 + Cargo.toml | 3 +- package.json | 2 +- tools/curate-etl/Cargo.toml | 8 + tools/curate-etl/README.md | 46 +++ tools/curate-etl/src/bench.rs | 143 +++++++ tools/curate-etl/src/lib.rs | 9 + tools/curate-etl/src/main.rs | 86 +++++ tools/curate-etl/src/split.rs | 692 ++++++++++++++++++++++++++++++++++ 9 files changed, 991 insertions(+), 2 deletions(-) create mode 100644 tools/curate-etl/Cargo.toml create mode 100644 tools/curate-etl/README.md create mode 100644 tools/curate-etl/src/bench.rs create mode 100644 tools/curate-etl/src/lib.rs create mode 100644 tools/curate-etl/src/main.rs create mode 100644 tools/curate-etl/src/split.rs diff --git a/Cargo.lock b/Cargo.lock index cf928b60..4fc5e43f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -193,6 +193,10 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "curate-etl" +version = "0.1.0" + [[package]] name = "dashmap" version = "5.5.3" diff --git a/Cargo.toml b/Cargo.toml index 274a3d19..adb925b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ - "apps/stock/engine" + "apps/stock/engine", + "tools/curate-etl", ] resolver = "2" diff --git a/package.json b/package.json index 0b86adce..07b216ea 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "coverage:ci": "bun run tools/coverage-cli/src/index.ts --reporters markdown json --fail-under", "test:unit": "bun test test/unit", "test:integration": "bun test test/integration/", - "test:native": "cargo test -p engine --lib --offline", + "test:native": "cargo test -p engine -p curate-etl --lib --offline", "test:postgres": "bun run scripts/test-postgres.ts", "db:migrate": "bun run scripts/db-migrate.ts", "audit:secrets": "bun run scripts/audit-secrets.ts", diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml new file mode 100644 index 00000000..39a39fe6 --- /dev/null +++ b/tools/curate-etl/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "curate-etl" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true + +[dependencies] diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md new file mode 100644 index 00000000..a0edafc4 --- /dev/null +++ b/tools/curate-etl/README.md @@ -0,0 +1,46 @@ +# `curate-etl` + +Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table and bar un-adjustment core. + +## Scope & Sign Conventions + +Aligned with `design/DATA-CONTRACTS.md` (§1 `qmSplits`, `eodPrices`, `eodIntraday1M`): + +- **Split ratio**: `ratio = new_shares / old_shares`. + - Forward split `10:1` (e.g., NVDA on `2024-06-10`) → `ratio = 10.0`. + - Reverse split `1:20` (e.g., NEXM.V on `2025-06-18`) → `ratio = 0.05`. + - No-op rows (`ratio == 1.0`) are dropped during `SplitTable::from_events`. + - Duplicate events on the same `ex_date` are multiplied (and dropped if reciprocal pairs cancel to `1.0`). + - Non-finite or `<= 0.0` ratios and compounding overflow/underflow return a typed `SplitError` rather than panicking. +- **Ex-date boundary (strict `>`):** `cum_factor_after(key, bar_date)` returns the product of all split ratios with `ex_date > bar_date`. A bar dated on the ex-date itself is already post-split (`factor = 1.0`). Unknown keys and post-split dates return `1.0`. +- **`eodPrices` (daily bars):** OHLC is raw and only volume is retroactively split-adjusted: + - `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor` +- **`eodIntraday1M` (1m bars, reused in M2):** both OHLC and volume are retroactively split-adjusted: + - `raw_price = unadjust_price(adj_price, factor) = adj_price * factor` + - `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 + +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`): + +```bash +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`) + +This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (requiring crates.io access) will add: + +- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`) +- PostgreSQL `provider_mapping` preload keyed by `listing_id: i32` (supported via generic `SplitTable`) +- `rayon` parallel sharding across symbol/date partitions +- Zstd-compressed Parquet writer for curated daily/intraday datasets +- QuestDB ILP v2 writer for time-series ingestion diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs new file mode 100644 index 00000000..6e23be51 --- /dev/null +++ b/tools/curate-etl/src/bench.rs @@ -0,0 +1,143 @@ +//! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop. + +use std::hint::black_box; +use std::time::Instant; + +use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitEvent, SplitTable}; + +pub const DEFAULT_BENCH_ROWS: usize = 10_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 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). +#[derive(Debug, Clone, Copy)] +struct SplitMix64 { + state: u64, +} + +impl SplitMix64 { + #[inline] + fn new(seed: u64) -> Self { + Self { state: seed } + } + + #[inline] + fn next_u64(&mut self) -> u64 { + self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +/// Summary metrics produced by [`run_split_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BenchReport { + pub rows: usize, + pub key_count: usize, + pub table_keys_with_splits: usize, + pub table_event_count: usize, + pub build_elapsed_ms: f64, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub ns_per_row: f64, + pub checksum: f64, +} + +/// Runs the fixed-seed split lookup + `unadjust_volume` benchmark for `rows` bars. +/// +/// Builds a [`SplitTable`] with `20_000` symbol keys and `19_000` deterministic forward +/// and reverse splits spanning `1990-01-01..=2025-12-31`, then executes `rows` zero-allocation +/// lookups and volume un-adjustments. +pub fn run_split_benchmark(rows: usize) -> BenchReport { + 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 keys: Vec = (0..BENCH_KEY_COUNT) + .map(|i| format!("SYM{i:05}.US")) + .collect(); + + let mut rng = SplitMix64::new(BENCH_SEED); + let mut events = Vec::with_capacity(BENCH_EVENT_COUNT); + for _ in 0..BENCH_EVENT_COUNT { + let key_idx = (rng.next_u64() as usize) % keys.len(); + let ex_date = min_date + (rng.next_u64() % date_span) as i32; + let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]; + events.push((keys[key_idx].clone(), SplitEvent { ex_date, ratio })); + } + + let build_start = Instant::now(); + let table = SplitTable::from_events(events).unwrap_or_default(); + let build_elapsed_ms = build_start.elapsed().as_secs_f64() * 1_000.0; + + let key_count = keys.len(); + let mut acc = 0.0_f64; + + let loop_start = Instant::now(); + for _ in 0..rows { + let key_idx = (rng.next_u64() as usize) % key_count; + let bar_date = min_date + (rng.next_u64() % date_span) as i32; + let adj_volume = ((rng.next_u64() % 10_000_000) + 100) as f64; + + let factor = table.cum_factor_after(keys[key_idx].as_str(), bar_date); + let raw_volume = unadjust_volume(adj_volume, factor); + acc += raw_volume; + } + let checksum = black_box(acc); + let elapsed = loop_start.elapsed(); + let elapsed_secs = elapsed.as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + let (rows_per_sec, ns_per_row) = if rows == 0 || elapsed_secs == 0.0 { + (0.0, 0.0) + } else { + (rows as f64 / elapsed_secs, elapsed_secs * 1e9 / rows as f64) + }; + + BenchReport { + rows, + key_count, + table_keys_with_splits: table.len(), + table_event_count: table.event_count(), + build_elapsed_ms, + elapsed_ms, + rows_per_sec, + ns_per_row, + checksum, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn benchmark_small_run_is_deterministic() { + let a = run_split_benchmark(1_000); + let b = run_split_benchmark(1_000); + + assert_eq!(a.rows, 1_000); + assert_eq!(a.key_count, BENCH_KEY_COUNT); + assert_eq!(a.table_keys_with_splits, b.table_keys_with_splits); + assert_eq!(a.table_event_count, b.table_event_count); + assert_eq!(a.checksum.to_bits(), b.checksum.to_bits()); + assert!(a.checksum.is_finite() && a.checksum > 0.0); + assert!(a.rows_per_sec > 0.0); + assert!(a.ns_per_row > 0.0); + } + + #[test] + fn benchmark_zero_rows_handles_cleanly() { + let report = run_split_benchmark(0); + assert_eq!(report.rows, 0); + assert_eq!(report.checksum, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + assert!(report.table_keys_with_splits > 0); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs new file mode 100644 index 00000000..86295e40 --- /dev/null +++ b/tools/curate-etl/src/lib.rs @@ -0,0 +1,9 @@ +#![deny(clippy::all)] + +pub mod bench; +pub mod split; + +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 new file mode 100644 index 00000000..de1ed52a --- /dev/null +++ b/tools/curate-etl/src/main.rs @@ -0,0 +1,86 @@ +#![deny(clippy::all)] + +use std::env; +use std::process::ExitCode; + +use curate_etl::bench::{run_split_benchmark, DEFAULT_BENCH_ROWS}; + +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]" + ); +} + +fn main() -> ExitCode { + let args: Vec = env::args().skip(1).collect(); + + match args.first().map(String::as_str) { + None | Some("--help") | Some("-h") => { + print_usage(); + ExitCode::SUCCESS + } + Some("--version") | Some("-V") => { + println!("{NAME} {VERSION}"); + ExitCode::SUCCESS + } + Some("bench-split") => { + let rows = match args.get(1) { + None => DEFAULT_BENCH_ROWS, + Some(raw) if args.len() == 2 => match raw.parse::() { + Ok(n) if n > 0 => n, + _ => { + eprintln!("error: invalid row count '{raw}' (expected a positive integer)"); + print_usage_stderr(); + return ExitCode::FAILURE; + } + }, + Some(_) => { + eprintln!("error: too many arguments for bench-split"); + print_usage_stderr(); + return ExitCode::FAILURE; + } + }; + + let report = run_split_benchmark(rows); + println!("curate-etl bench-split"); + println!( + " table: keys={} keys_with_splits={} events={} build={:.2} ms", + report.key_count, + report.table_keys_with_splits, + report.table_event_count, + report.build_elapsed_ms + ); + println!( + " run: rows={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum={:.3}", + report.rows, + report.elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.checksum + ); + ExitCode::SUCCESS + } + Some(other) => { + eprintln!("error: unknown argument '{other}'"); + print_usage_stderr(); + ExitCode::FAILURE + } + } +} diff --git a/tools/curate-etl/src/split.rs b/tools/curate-etl/src/split.rs new file mode 100644 index 00000000..57aef753 --- /dev/null +++ b/tools/curate-etl/src/split.rs @@ -0,0 +1,692 @@ +//! In-memory split-factor lookup table and bar un-adjustment core. +//! +//! Sign conventions (aligned with `design/DATA-CONTRACTS.md`): +//! - `ratio = new_shares / old_shares` (e.g. `10.0` for a 10:1 forward split, `0.05` for a 1:20 +//! reverse split). +//! - `cum_factor_after(key, bar_date)` multiplies every split ratio with `ex_date > bar_date` +//! (strictly greater: a bar on the ex-date itself is already post-split). +//! - `eodPrices`: OHLC is raw and only volume is retroactively split-adjusted, so +//! `raw_volume = adj_volume / factor`. +//! - `eodIntraday1M`: both OHLC and volume are retroactively split-adjusted, so +//! `raw_price = adj_price * factor` and `raw_volume = adj_volume / factor` +//! (preserving dollar volume `raw_price * raw_volume == adj_price * adj_volume`). + +use std::borrow::Borrow; +use std::collections::HashMap; +use std::error::Error; +use std::fmt; +use std::hash::Hash; + +/// A single corporate split event. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SplitEvent { + /// Ex-dividend / ex-split date as days since 1970-01-01 (UTC Gregorian). + pub ex_date: i32, + /// Split ratio expressed as `new_shares / old_shares` (must be finite and `> 0.0`). + pub ratio: f64, +} + +/// A precomputed entry in [`SplitTable`], sorted ascending by `ex_date` per key. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SplitEntry { + /// Ex-split date as days since 1970-01-01. + pub ex_date: i32, + /// Cumulative product of split ratios for this `ex_date` and all subsequent `ex_date`s. + pub suffix_factor: f64, +} + +/// OHLCV bar used for intraday (1m) full-bar un-adjustment. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct OhlcvBar { + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, +} + +/// Typed errors returned while validating dates or building a [`SplitTable`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SplitError { + /// A split ratio was non-finite (`NaN`, `+/-inf`) or `<= 0.0`. + InvalidRatio { ex_date: i32, ratio: f64 }, + /// Multiplying duplicate-date or suffix split ratios overflowed to infinity or underflowed to 0. + FactorOverflow { ex_date: i32, factor: f64 }, + /// Calendar date components are outside valid Gregorian calendar bounds or `i32` epoch days. + InvalidDate { year: i32, month: u32, day: u32 }, +} + +impl fmt::Display for SplitError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::InvalidRatio { ex_date, ratio } => { + write!( + f, + "invalid split ratio {ratio} on epoch day {ex_date}: must be finite and > 0" + ) + } + Self::FactorOverflow { ex_date, factor } => { + write!( + f, + "split factor overflow/underflow ({factor}) at epoch day {ex_date}" + ) + } + Self::InvalidDate { year, month, day } => { + write!(f, "invalid Gregorian date {year:04}-{month:02}-{day:02}") + } + } + } +} + +impl Error for SplitError {} + +/// Converts a Gregorian `(year, month, day)` to signed days since `1970-01-01`. +/// +/// Validates calendar bounds including Gregorian leap years (Howard Hinnant's `days_from_civil`). +pub fn ymd_to_epoch_days(year: i32, month: u32, day: u32) -> Result { + if !(1..=12).contains(&month) { + return Err(SplitError::InvalidDate { year, month, day }); + } + let max_day = days_in_month(year, month); + if day < 1 || day > max_day { + return Err(SplitError::InvalidDate { year, month, day }); + } + + let y = i64::from(year) - i64::from(month <= 2); + let era = y.div_euclid(400); + let yoe = y - era * 400; // [0, 399] + let m = i64::from(month); + let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + i64::from(day) - 1; // [0, 365] + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] + let days = era * 146_097 + doe - 719_468; + + i32::try_from(days).map_err(|_| SplitError::InvalidDate { year, month, day }) +} + +#[inline] +fn is_leap_year(year: i32) -> bool { + (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) +} + +#[inline] +fn days_in_month(year: i32, month: u32) -> u32 { + match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 => { + if is_leap_year(year) { + 29 + } else { + 28 + } + } + _ => 0, + } +} + +/// Zero-allocation lookup table of precomputed suffix split factors keyed by `K`. +/// +/// Entries for all keys are packed into a single contiguous `Vec` arena so each +/// lookup is one hash probe plus a binary search over a small contiguous slice. +#[derive(Debug, Clone)] +pub struct SplitTable { + entries: Vec, + index: HashMap, +} + +impl Default for SplitTable +where + K: Eq + Hash, +{ + fn default() -> Self { + Self { + entries: Vec::new(), + index: HashMap::new(), + } + } +} + +impl SplitTable +where + K: Eq + Hash, +{ + /// Builds a [`SplitTable`] from an arbitrary (possibly unsorted) stream of `(key, SplitEvent)`. + /// + /// - Rejects any non-finite or `<= 0.0` ratio with [`SplitError::InvalidRatio`]. + /// - Drops `ratio == 1.0` no-op events. + /// - Sorts events per key by `ex_date` ascending and multiplies duplicate `ex_date` ratios. + /// - Precomputes right-to-left suffix cumulative products and rejects overflow/underflow with + /// [`SplitError::FactorOverflow`]. + /// - Omits keys that have zero effective split events remaining. + pub fn from_events(events: I) -> Result + where + I: IntoIterator, + { + let mut grouped: HashMap> = HashMap::new(); + let mut total_valid = 0usize; + + for (key, event) in events { + if !event.ratio.is_finite() || event.ratio <= 0.0 { + return Err(SplitError::InvalidRatio { + ex_date: event.ex_date, + ratio: event.ratio, + }); + } + if event.ratio == 1.0 { + continue; + } + grouped.entry(key).or_default().push(event); + total_valid += 1; + } + + let mut entries = Vec::with_capacity(total_valid); + let mut index = HashMap::with_capacity(grouped.len()); + let mut coalesced: Vec<(i32, f64)> = Vec::new(); + + for (key, mut key_events) in grouped { + key_events.sort_unstable_by_key(|ev| ev.ex_date); + coalesced.clear(); + + for ev in key_events { + if let Some(last) = coalesced.last_mut() { + if last.0 == ev.ex_date { + let combined = last.1 * ev.ratio; + if !combined.is_finite() || combined <= 0.0 { + return Err(SplitError::FactorOverflow { + ex_date: ev.ex_date, + factor: combined, + }); + } + last.1 = combined; + continue; + } + } + coalesced.push((ev.ex_date, ev.ratio)); + } + + // Drop duplicate-date pairs that cancelled back to 1.0 (e.g. 2.0 * 0.5). + coalesced.retain(|&(_, ratio)| ratio != 1.0); + if coalesced.is_empty() { + continue; + } + + let start = entries.len(); + let count = coalesced.len(); + entries.resize( + start + count, + SplitEntry { + ex_date: 0, + suffix_factor: 1.0, + }, + ); + + let mut running = 1.0_f64; + if let Some(dst_slice) = entries.get_mut(start..start + count) { + for (dst, &(ex_date, ratio)) in + dst_slice.iter_mut().rev().zip(coalesced.iter().rev()) + { + running *= ratio; + if !running.is_finite() || running <= 0.0 { + return Err(SplitError::FactorOverflow { + ex_date, + factor: running, + }); + } + *dst = SplitEntry { + ex_date, + suffix_factor: running, + }; + } + } + + index.insert(key, (start, count)); + } + + entries.shrink_to_fit(); + Ok(Self { entries, index }) + } + + /// Returns the cumulative product of all split ratios for `key` with `ex_date > bar_date`. + /// + /// Returns `1.0` when `key` is unknown or when no split occurred strictly after `bar_date`. + /// Performs zero heap allocations. + #[inline] + pub fn cum_factor_after(&self, key: &Q, bar_date: i32) -> f64 + where + K: Borrow, + Q: Hash + Eq + ?Sized, + { + let Some(&(start, len)) = self.index.get(key) else { + return 1.0; + }; + let Some(slice) = self.entries.get(start..start + len) else { + return 1.0; + }; + let idx = slice.partition_point(|entry| entry.ex_date <= bar_date); + slice.get(idx).map_or(1.0, |entry| entry.suffix_factor) + } + + /// Number of keys with at least one effective split event. + #[inline] + pub fn len(&self) -> usize { + self.index.len() + } + + /// Returns `true` if the table contains no split entries. + #[inline] + pub fn is_empty(&self) -> bool { + self.index.is_empty() + } + + /// Total number of coalesced split entries stored across all keys. + #[inline] + pub fn event_count(&self) -> usize { + self.entries.len() + } + + /// Returns the sorted precomputed split entries for `key` (empty slice if absent). + #[inline] + pub fn splits_for(&self, key: &Q) -> &[SplitEntry] + where + K: Borrow, + Q: Hash + Eq + ?Sized, + { + let Some(&(start, len)) = self.index.get(key) else { + return &[]; + }; + self.entries.get(start..start + len).unwrap_or(&[]) + } +} + +/// Un-adjusts a split-adjusted volume back to raw historical shares (`adj_volume / factor`). +/// +/// Used for `eodPrices` (where OHLC is raw and only volume is split-adjusted) and `eodIntraday1M`. +#[inline] +pub fn unadjust_volume(adj_volume: f64, factor: f64) -> f64 { + if factor == 1.0 { + adj_volume + } else { + adj_volume / factor + } +} + +/// Un-adjusts a split-adjusted price back to raw historical price (`adj_price * factor`). +/// +/// Used for `eodIntraday1M` (where OHLC and volume are both retroactively split-adjusted). +#[inline] +pub fn unadjust_price(adj_price: f64, factor: f64) -> f64 { + if factor == 1.0 { + adj_price + } else { + adj_price * factor + } +} + +/// Un-adjusts a full 1m OHLCV bar (`eodIntraday1M`), scaling prices by `* factor` and volume by +/// `/ factor` so dollar volume (`close * volume`) is invariant. +#[inline] +pub fn unadjust_ohlcv(bar: OhlcvBar, factor: f64) -> OhlcvBar { + if factor == 1.0 { + return bar; + } + OhlcvBar { + open: unadjust_price(bar.open, factor), + high: unadjust_price(bar.high, factor), + low: unadjust_price(bar.low, factor), + close: unadjust_price(bar.close, factor), + volume: unadjust_volume(bar.volume, factor), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + 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}" + ); + } + + #[test] + fn ymd_to_epoch_days_known_dates_and_leap_years() { + assert_eq!(ymd_to_epoch_days(1970, 1, 1), Ok(0)); + assert_eq!(ymd_to_epoch_days(1969, 12, 31), Ok(-1)); + assert_eq!(ymd_to_epoch_days(2024, 6, 10), Ok(19_884)); + assert_eq!(ymd_to_epoch_days(2024, 6, 7), Ok(19_881)); + assert_eq!(ymd_to_epoch_days(2025, 6, 18), Ok(20_257)); + assert!(ymd_to_epoch_days(2000, 2, 29).is_ok()); + assert!(ymd_to_epoch_days(2024, 2, 29).is_ok()); + assert_eq!( + ymd_to_epoch_days(1900, 2, 29), + Err(SplitError::InvalidDate { + year: 1900, + month: 2, + day: 29 + }) + ); + assert_eq!( + ymd_to_epoch_days(2023, 2, 29), + Err(SplitError::InvalidDate { + year: 2023, + month: 2, + day: 29 + }) + ); + assert!(matches!( + ymd_to_epoch_days(2024, 0, 10), + Err(SplitError::InvalidDate { .. }) + )); + assert!(matches!( + ymd_to_epoch_days(2024, 13, 10), + Err(SplitError::InvalidDate { .. }) + )); + assert!(matches!( + ymd_to_epoch_days(2024, 4, 31), + Err(SplitError::InvalidDate { .. }) + )); + } + + #[test] + fn nvda_10_for_1_forward_split_unadjusts_pre_split_volume_and_leaves_ex_date_unchanged() { + let ex_date = ymd_to_epoch_days(2024, 6, 10).unwrap(); + let pre_date = ymd_to_epoch_days(2024, 6, 7).unwrap(); + let post_date = ymd_to_epoch_days(2024, 6, 11).unwrap(); + + let table = SplitTable::from_events([( + "NVDA".to_string(), + SplitEvent { + ex_date, + ratio: 10.0, + }, + )]) + .unwrap(); + + let pre_factor = table.cum_factor_after("NVDA", pre_date); + assert_rel_eq(pre_factor, 10.0, 1e-12); + + let adj_volume = 412_390_000.0; + let raw_volume = unadjust_volume(adj_volume, pre_factor); + assert_rel_eq(raw_volume, 41_239_000.0, 1e-9); + + // Bar on the exact ex-date is already post-split -> factor 1.0, exact pass-through. + let ex_factor = table.cum_factor_after("NVDA", ex_date); + assert_eq!(ex_factor, 1.0); + assert_eq!(unadjust_volume(adj_volume, ex_factor), adj_volume); + + // Post-split bar is also unchanged. + let post_factor = table.cum_factor_after("NVDA", post_date); + assert_eq!(post_factor, 1.0); + assert_eq!(unadjust_volume(adj_volume, post_factor), adj_volume); + } + + #[test] + fn nexm_reverse_split_1_for_20_unadjusts_price_volume_and_preserves_dollar_volume() { + let ex_date = ymd_to_epoch_days(2025, 6, 18).unwrap(); + let pre_date = ymd_to_epoch_days(2025, 6, 17).unwrap(); + let post_date = ymd_to_epoch_days(2025, 6, 19).unwrap(); + + let table = SplitTable::from_events([( + "NEXM.V".to_string(), + SplitEvent { + ex_date, + ratio: 0.05, + }, + )]) + .unwrap(); + + let pre_factor = table.cum_factor_after("NEXM.V", pre_date); + assert_rel_eq(pre_factor, 0.05, 1e-12); + + let adj_bar = OhlcvBar { + open: 24.00, + high: 25.00, + low: 23.60, + close: 24.29, + volume: 100_000.0, + }; + let raw_bar = unadjust_ohlcv(adj_bar, pre_factor); + + assert_rel_eq(raw_bar.close, 1.2145, 1e-9); + assert_rel_eq(raw_bar.open, 1.20, 1e-9); + assert_rel_eq(raw_bar.high, 1.25, 1e-9); + assert_rel_eq(raw_bar.low, 1.18, 1e-9); + assert_rel_eq(raw_bar.volume, 100_000.0 / 0.05, 1e-9); + + // Dollar volume invariance: raw_close * raw_volume == adj_close * adj_volume. + assert_rel_eq( + raw_bar.close * raw_bar.volume, + adj_bar.close * adj_bar.volume, + 1e-9, + ); + + // Ex-date and post-split bars remain untouched. + assert_eq!(table.cum_factor_after("NEXM.V", ex_date), 1.0); + assert_eq!(unadjust_ohlcv(adj_bar, 1.0), adj_bar); + assert_eq!(table.cum_factor_after("NEXM.V", post_date), 1.0); + } + + #[test] + fn multiple_splits_compound_across_unsorted_inputs() { + let split1 = ymd_to_epoch_days(2021, 7, 20).unwrap(); // 4:1 + let split2 = ymd_to_epoch_days(2024, 6, 10).unwrap(); // 10:1 + + // Deliberately insert out of chronological order. + let table = SplitTable::from_events([ + ( + "NVDA".to_string(), + SplitEvent { + ex_date: split2, + ratio: 10.0, + }, + ), + ( + "NVDA".to_string(), + SplitEvent { + ex_date: split1, + ratio: 4.0, + }, + ), + ]) + .unwrap(); + + assert_rel_eq(table.cum_factor_after("NVDA", split1 - 1), 40.0, 1e-12); + assert_rel_eq(table.cum_factor_after("NVDA", split1), 10.0, 1e-12); + assert_rel_eq(table.cum_factor_after("NVDA", split2 - 1), 10.0, 1e-12); + assert_eq!(table.cum_factor_after("NVDA", split2), 1.0); + assert_eq!(table.cum_factor_after("NVDA", split2 + 10), 1.0); + } + + #[test] + fn drops_ratio_one_noops_and_coalesces_duplicate_ex_dates() { + let d1 = ymd_to_epoch_days(2020, 5, 1).unwrap(); + let d2 = ymd_to_epoch_days(2022, 5, 1).unwrap(); + let d3 = ymd_to_epoch_days(2023, 5, 1).unwrap(); + + let table = SplitTable::from_events([ + // Pure ratio == 1.0 key should be omitted completely. + ( + "NOOP".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1.0, + }, + ), + // Duplicate ex_date multiplied (2.0 * 3.0 = 6.0). + ( + "DUP".to_string(), + SplitEvent { + ex_date: d1, + ratio: 2.0, + }, + ), + ( + "DUP".to_string(), + SplitEvent { + ex_date: d1, + ratio: 3.0, + }, + ), + // Reciprocal pair on same date cancels to 1.0 and is dropped. + ( + "DUP".to_string(), + SplitEvent { + ex_date: d2, + ratio: 2.0, + }, + ), + ( + "DUP".to_string(), + SplitEvent { + ex_date: d2, + ratio: 0.5, + }, + ), + // Pure reciprocal key should also be omitted completely. + ( + "CANCEL".to_string(), + SplitEvent { + ex_date: d3, + ratio: 4.0, + }, + ), + ( + "CANCEL".to_string(), + SplitEvent { + ex_date: d3, + ratio: 0.25, + }, + ), + ]) + .unwrap(); + + assert_eq!(table.len(), 1); + assert_eq!(table.event_count(), 1); + assert!(table.splits_for("NOOP").is_empty()); + assert!(table.splits_for("CANCEL").is_empty()); + assert_eq!(table.cum_factor_after("NOOP", d1 - 1), 1.0); + assert_eq!(table.cum_factor_after("UNKNOWN", d1 - 1), 1.0); + assert_rel_eq(table.cum_factor_after("DUP", d1 - 1), 6.0, 1e-12); + assert_eq!(table.cum_factor_after("DUP", d1), 1.0); + } + + #[test] + fn generic_i32_listing_id_keys_and_date_boundaries() { + let table: SplitTable = SplitTable::from_events([ + ( + 42, + SplitEvent { + ex_date: i32::MIN + 1, + ratio: 2.0, + }, + ), + ( + 42, + SplitEvent { + ex_date: i32::MAX, + ratio: 5.0, + }, + ), + ]) + .unwrap(); + + assert_rel_eq(table.cum_factor_after(&42, i32::MIN), 10.0, 1e-12); + assert_rel_eq(table.cum_factor_after(&42, i32::MIN + 1), 5.0, 1e-12); + assert_rel_eq(table.cum_factor_after(&42, i32::MAX - 1), 5.0, 1e-12); + assert_eq!(table.cum_factor_after(&42, i32::MAX), 1.0); + assert_eq!(table.cum_factor_after(&999, 0), 1.0); + } + + #[test] + fn invalid_ratios_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(); + + for bad_ratio in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let err = SplitTable::from_events([( + "BAD".to_string(), + SplitEvent { + ex_date: d1, + ratio: bad_ratio, + }, + )]) + .unwrap_err(); + assert!( + matches!(err, SplitError::InvalidRatio { ex_date, .. } if ex_date == d1), + "expected InvalidRatio for {bad_ratio}, got {err:?}" + ); + } + + // Same-day overflow: 1e200 * 1e200 -> inf. + let dup_overflow = SplitTable::from_events([ + ( + "OVF".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e200, + }, + ), + ( + "OVF".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e200, + }, + ), + ]) + .unwrap_err(); + assert!(matches!( + dup_overflow, + SplitError::FactorOverflow { ex_date, .. } if ex_date == d1 + )); + + // Suffix compounding overflow across two dates. + let suffix_overflow = SplitTable::from_events([ + ( + "OVF2".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e200, + }, + ), + ( + "OVF2".to_string(), + SplitEvent { + ex_date: d2, + ratio: 1e200, + }, + ), + ]) + .unwrap_err(); + assert!(matches!( + suffix_overflow, + SplitError::FactorOverflow { ex_date, .. } if ex_date == d1 + )); + + // Suffix compounding underflow to 0.0. + let suffix_underflow = SplitTable::from_events([ + ( + "UDF".to_string(), + SplitEvent { + ex_date: d1, + ratio: 1e-200, + }, + ), + ( + "UDF".to_string(), + SplitEvent { + ex_date: d2, + ratio: 1e-200, + }, + ), + ]) + .unwrap_err(); + assert!(matches!( + suffix_underflow, + SplitError::FactorOverflow { ex_date, .. } if ex_date == d1 + )); + } +}