//! 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(|a, b| { a.ex_date .cmp(&b.ex_date) .then_with(|| a.ratio.total_cmp(&b.ratio)) }); 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 same_date_events_produce_bitwise_identical_factors_across_permutations() { let d1 = ymd_to_epoch_days(2023, 3, 15).unwrap(); let permutations = [[10.0, 0.1, 0.1], [0.1, 10.0, 0.1], [0.1, 0.1, 10.0]]; let mut baseline_bits: Option = None; for ratios in permutations { let table = SplitTable::from_events( ratios .into_iter() .map(|ratio| ("PERM".to_string(), SplitEvent { ex_date: d1, ratio })), ) .unwrap(); let factor = table.cum_factor_after("PERM", d1 - 1); assert_rel_eq(factor, 0.1, 1e-12); match baseline_bits { None => baseline_bits = Some(factor.to_bits()), Some(expected) => assert_eq!( factor.to_bits(), expected, "same-date ratio permutation changed factor bits" ), } } } #[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 )); } }