//! Pure, in-memory `bars_1d` daily bar builder (`eodPrices` + `SplitTable` + `qmPrices.sharevolume`). //! //! Produces sorted, unique per-`(key, session_date)` rows with raw OHLC passed through bit-for-bit //! and volume un-adjusted via [`SplitTable::splits_for`] (matching [`SplitTable::cum_factor_after`] //! bitwise under the strict `ex_date > session_date` boundary). //! //! Aligned with `design/DATA-CONTRACTS.md` (§1 `eodPrices`, `qmPrices`, `qmSplits`): //! - `eodPrices` OHLC is already raw; only `adj_volume` is retroactively split-adjusted, so //! `volume = unadjust_volume(adj_volume, factor) = adj_volume / factor`. //! - Bad single rows never panic or abort the build; each failure category is dropped and counted //! separately in [`Bars1dStats`]. //! - `qmPrices.sharevolume` is an optional read-only cross-check stream that never mutates output //! rows; invalid, duplicate, and conflicting QM rows are filtered/compacted deterministically //! and counted in [`Bars1dStats`]. //! - Caller-supplied `rel_tolerance` errors return a typed [`BarsError`]. use std::cmp::Ordering; use std::collections::BinaryHeap; use std::error::Error; use std::fmt; use std::hash::Hash; use crate::split::{unadjust_volume, SplitTable}; /// Maximum number of worst-case volume mismatch samples retained in [`Bars1dBuild::mismatch_samples`]. pub const MAX_MISMATCH_SAMPLES: usize = 100; /// A single raw `eodPrices` daily bar input. /// /// Per `design/DATA-CONTRACTS.md` §1, OHLC is already raw and only `adj_volume` is retroactively /// split-adjusted. #[derive(Debug, Clone, PartialEq)] pub struct EodDailyBar { pub key: K, /// Session date as days since `1970-01-01` (UTC Gregorian). pub session_date: i32, pub open: f64, pub high: f64, pub low: f64, pub close: f64, pub adj_volume: f64, } /// A single `qmPrices.sharevolume` cross-check observation (genuinely raw share volume). #[derive(Debug, Clone, PartialEq)] pub struct QmRawVolume { pub key: K, /// Session date as days since `1970-01-01` (UTC Gregorian). pub session_date: i32, pub share_volume: f64, } /// A single curated `bars_1d` row, sorted and unique by `(key, session_date)`. #[derive(Debug, Clone, PartialEq)] pub struct Bar1dRow { pub key: K, pub session_date: i32, pub open: f64, pub high: f64, pub low: f64, pub close: f64, pub volume: f64, } /// A single cross-check volume mismatch sample retained for downstream match reporting. #[derive(Debug, Clone, PartialEq)] pub struct VolumeMismatchSample { pub key: K, pub session_date: i32, pub volume: f64, pub share_volume: f64, pub rel: f64, } /// Summary counters and cross-check metrics produced alongside [`Bars1dBuild::rows`]. /// /// Conservation invariants: /// - `bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + duplicate_collapsed + duplicate_conflict_dropped` /// - `volume_checked + volume_unchecked == rows_out` /// - `volume_within_tolerance + volume_mismatched == volume_checked` /// - `qm_rows_in == qm_unique_partners + qm_invalid_volume_dropped + qm_duplicate_collapsed + qm_duplicate_conflict_dropped` #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Bars1dStats { pub bars_in: usize, pub rows_out: usize, pub keys_out: usize, pub dropped_invalid_ohlc: usize, pub dropped_inconsistent_ohlc: usize, pub dropped_invalid_volume: usize, pub duplicate_collapsed: usize, pub duplicate_conflict_dropped: usize, pub qm_rows_in: usize, pub qm_invalid_volume_dropped: usize, pub qm_duplicate_collapsed: usize, pub qm_duplicate_conflict_dropped: usize, pub qm_unique_partners: usize, pub volume_checked: usize, pub volume_within_tolerance: usize, pub volume_mismatched: usize, pub volume_unchecked: usize, pub max_rel_diff: f64, } /// Output of [`build_bars_1d`]: sorted rows, build/cross-check statistics, and worst mismatch samples. #[derive(Debug, Clone, PartialEq)] pub struct Bars1dBuild { pub rows: Vec>, pub stats: Bars1dStats, pub mismatch_samples: Vec>, } /// Typed caller errors returned by [`build_bars_1d`]. /// /// Single-row data errors in `bars` or `qm_volumes` are dropped and counted in [`Bars1dStats`] /// rather than aborting the build. #[derive(Debug, Clone, Copy, PartialEq)] pub enum BarsError { /// Caller-supplied `rel_tolerance` was non-finite (`NaN`, `+/-inf`) or `< 0.0`. InvalidTolerance { rel_tolerance: f64 }, } impl fmt::Display for BarsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::InvalidTolerance { rel_tolerance } => { write!( f, "invalid relative tolerance {rel_tolerance}: must be finite and >= 0" ) } } } } impl Error for BarsError {} #[inline] fn is_valid_price(price: f64) -> bool { price.is_finite() && price > 0.0 } #[inline] fn bar_values_bit_eq(a: &EodDailyBar, b: &EodDailyBar) -> bool { a.open.to_bits() == b.open.to_bits() && a.high.to_bits() == b.high.to_bits() && a.low.to_bits() == b.low.to_bits() && a.close.to_bits() == b.close.to_bits() && a.adj_volume.to_bits() == b.adj_volume.to_bits() } /// Wrapper ordering [`VolumeMismatchSample`] by desired output order: /// `(rel DESC, key ASC, session_date ASC)`. /// /// In a max-heap ([`BinaryHeap`]), the *largest* element (smallest `rel`, or latest `(key, date)` /// tie) sits at the top and is evicted when the heap exceeds [`MAX_MISMATCH_SAMPLES`]. Calling /// [`BinaryHeap::into_sorted_vec`] then returns samples in ascending `Ord` order (worst mismatch /// first). struct HeapMismatchSample(VolumeMismatchSample); impl Ord for HeapMismatchSample { #[inline] fn cmp(&self, other: &Self) -> Ordering { other .0 .rel .total_cmp(&self.0.rel) .then_with(|| self.0.key.cmp(&other.0.key)) .then_with(|| self.0.session_date.cmp(&other.0.session_date)) } } impl PartialOrd for HeapMismatchSample { #[inline] fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for HeapMismatchSample { #[inline] fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for HeapMismatchSample {} /// Builds sorted, unique `bars_1d` rows from `eodPrices` daily bars, un-adjusting share volume /// via `splits` and cross-checking against optional `qmPrices.sharevolume` observations. /// /// - Returns [`BarsError::InvalidTolerance`] if `rel_tolerance` is non-finite or `< 0.0`. /// - Drops invalid/inconsistent single bars without aborting the build (priority: invalid OHLC, /// inconsistent OHLC range, invalid volume). /// - Collapses bitwise-identical duplicate `(key, session_date)` bars and drops entire conflicting /// duplicate groups. /// - Passes raw OHLC through bit-for-bit and un-adjusts volume via `unadjust_volume(adj_volume, factor)` /// where `factor = splits.cum_factor_after(&key, session_date)`. /// - Cross-checks output rows against compacted unique `qm_volumes` partners without modifying any /// output row, retaining up to [`MAX_MISMATCH_SAMPLES`] worst mismatches ordered by /// `(rel DESC, key ASC, session_date ASC)`. pub fn build_bars_1d( bars: B, splits: &SplitTable, qm_volumes: Q, rel_tolerance: f64, ) -> Result, BarsError> where K: Ord + Eq + Hash + Clone, B: IntoIterator>, Q: IntoIterator>, { if !rel_tolerance.is_finite() || rel_tolerance < 0.0 { return Err(BarsError::InvalidTolerance { rel_tolerance }); } let bars_iter = bars.into_iter(); let mut valid_bars: Vec> = Vec::with_capacity(bars_iter.size_hint().0); let mut stats = Bars1dStats::default(); for mut bar in bars_iter { stats.bars_in += 1; if !is_valid_price(bar.open) || !is_valid_price(bar.high) || !is_valid_price(bar.low) || !is_valid_price(bar.close) { stats.dropped_invalid_ohlc += 1; continue; } if bar.high < bar.low || bar.open < bar.low || bar.open > bar.high || bar.close < bar.low || bar.close > bar.high { stats.dropped_inconsistent_ohlc += 1; continue; } if !bar.adj_volume.is_finite() || bar.adj_volume < 0.0 { stats.dropped_invalid_volume += 1; continue; } if bar.adj_volume == 0.0 { bar.adj_volume = 0.0; } valid_bars.push(bar); } valid_bars.sort_unstable_by(|a, b| { a.key .cmp(&b.key) .then_with(|| a.session_date.cmp(&b.session_date)) }); let mut rows: Vec> = Vec::with_capacity(valid_bars.len()); let total_valid = valid_bars.len(); let mut idx = 0usize; while idx < total_valid { let key_start = idx; let key = valid_bars[key_start].key.clone(); while idx < total_valid && valid_bars[idx].key == key { idx += 1; } let key_end = idx; let key_splits = splits.splits_for(&key); let mut split_idx = 0usize; let key_rows_start = rows.len(); let mut day_idx = key_start; while day_idx < key_end { let session_date = valid_bars[day_idx].session_date; let day_start = day_idx; while day_idx < key_end && valid_bars[day_idx].session_date == session_date { day_idx += 1; } let day_end = day_idx; let group_len = day_end - day_start; while split_idx < key_splits.len() && key_splits[split_idx].ex_date <= session_date { split_idx += 1; } let first = &valid_bars[day_start]; let all_identical = valid_bars[day_start + 1..day_end] .iter() .all(|other| bar_values_bit_eq(first, other)); if !all_identical { stats.duplicate_conflict_dropped += group_len; continue; } stats.duplicate_collapsed += group_len - 1; let factor = key_splits.get(split_idx).map_or(1.0, |e| e.suffix_factor); let mut volume = unadjust_volume(first.adj_volume, factor); if !volume.is_finite() || volume < 0.0 { stats.dropped_invalid_volume += 1; continue; } if volume == 0.0 { volume = 0.0; } rows.push(Bar1dRow { key: key.clone(), session_date, open: first.open, high: first.high, low: first.low, close: first.close, volume, }); } if rows.len() > key_rows_start { stats.keys_out += 1; } } stats.rows_out = rows.len(); // Free the validated EOD buffer before allocating/sorting QM partners to cut peak RAM. drop(valid_bars); // Filter, sort, and compact QM raw-volume partners. let qm_iter = qm_volumes.into_iter(); let mut valid_qm: Vec> = Vec::with_capacity(qm_iter.size_hint().0); for mut qm in qm_iter { stats.qm_rows_in += 1; if !qm.share_volume.is_finite() || qm.share_volume < 0.0 { stats.qm_invalid_volume_dropped += 1; continue; } if qm.share_volume == 0.0 { qm.share_volume = 0.0; } valid_qm.push(qm); } valid_qm.sort_unstable_by(|a, b| { a.key .cmp(&b.key) .then_with(|| a.session_date.cmp(&b.session_date)) }); let mut write_idx = 0usize; let mut read_idx = 0usize; let qm_valid_len = valid_qm.len(); while read_idx < qm_valid_len { let mut group_end = read_idx + 1; while group_end < qm_valid_len && valid_qm[group_end].key == valid_qm[read_idx].key && valid_qm[group_end].session_date == valid_qm[read_idx].session_date { group_end += 1; } let group_len = group_end - read_idx; let first_bits = valid_qm[read_idx].share_volume.to_bits(); let all_identical = valid_qm[read_idx + 1..group_end] .iter() .all(|other| other.share_volume.to_bits() == first_bits); if all_identical { stats.qm_duplicate_collapsed += group_len - 1; if write_idx != read_idx { valid_qm.swap(write_idx, read_idx); } write_idx += 1; } else { stats.qm_duplicate_conflict_dropped += group_len; } read_idx = group_end; } valid_qm.truncate(write_idx); stats.qm_unique_partners = valid_qm.len(); // Linear two-pointer merge cross-check over sorted rows and sorted unique QM partners. let mut qm_idx = 0usize; let mut heap: BinaryHeap> = BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1); for row in &rows { while qm_idx < valid_qm.len() { match valid_qm[qm_idx] .key .cmp(&row.key) .then_with(|| valid_qm[qm_idx].session_date.cmp(&row.session_date)) { Ordering::Less => qm_idx += 1, Ordering::Equal | Ordering::Greater => break, } } if qm_idx < valid_qm.len() && valid_qm[qm_idx].key == row.key && valid_qm[qm_idx].session_date == row.session_date { let share_volume = valid_qm[qm_idx].share_volume; qm_idx += 1; stats.volume_checked += 1; let (rel, within) = if row.volume == 0.0 && share_volume == 0.0 { (0.0, true) } else if share_volume == 0.0 { (f64::INFINITY, false) } else { let r = (row.volume - share_volume).abs() / share_volume; (r, r <= rel_tolerance) }; if rel > stats.max_rel_diff { stats.max_rel_diff = rel; } if within { stats.volume_within_tolerance += 1; } else { stats.volume_mismatched += 1; let should_insert = if heap.len() < MAX_MISMATCH_SAMPLES { true } else if let Some(worst_kept) = heap.peek() { // Candidate is better (comes earlier in output) iff it is < worst_kept. worst_kept .0 .rel .total_cmp(&rel) .then_with(|| row.key.cmp(&worst_kept.0.key)) .then_with(|| row.session_date.cmp(&worst_kept.0.session_date)) == Ordering::Less } else { false }; if should_insert { heap.push(HeapMismatchSample(VolumeMismatchSample { key: row.key.clone(), session_date: row.session_date, volume: row.volume, share_volume, rel, })); if heap.len() > MAX_MISMATCH_SAMPLES { heap.pop(); } } } } else { stats.volume_unchecked += 1; } } let mismatch_samples: Vec> = heap.into_sorted_vec().into_iter().map(|w| w.0).collect(); Ok(Bars1dBuild { rows, stats, mismatch_samples, }) } #[cfg(test)] mod tests { use super::*; use crate::split::{ymd_to_epoch_days, SplitEvent}; fn day(y: i32, m: u32, d: u32) -> i32 { ymd_to_epoch_days(y, m, d).unwrap() } fn bar( key: K, session_date: i32, open: f64, high: f64, low: f64, close: f64, adj_volume: f64, ) -> EodDailyBar { EodDailyBar { key, session_date, open, high, low, close, adj_volume, } } fn qm(key: K, session_date: i32, share_volume: f64) -> QmRawVolume { QmRawVolume { key, session_date, share_volume, } } 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 assert_accounting_invariants(stats: &Bars1dStats) { assert_eq!( stats.bars_in, stats.rows_out + stats.dropped_invalid_ohlc + stats.dropped_inconsistent_ohlc + stats.dropped_invalid_volume + stats.duplicate_collapsed + stats.duplicate_conflict_dropped, "bars accounting mismatch: {stats:?}" ); assert_eq!( stats.volume_checked + stats.volume_unchecked, stats.rows_out, "checked + unchecked != rows_out: {stats:?}" ); assert_eq!( stats.volume_within_tolerance + stats.volume_mismatched, stats.volume_checked, "within + mismatched != checked: {stats:?}" ); assert_eq!( stats.qm_rows_in, stats.qm_unique_partners + stats.qm_invalid_volume_dropped + stats.qm_duplicate_collapsed + stats.qm_duplicate_conflict_dropped, "qm accounting mismatch: {stats:?}" ); } #[test] fn nvda_synthetic_4_for_1_and_10_for_1_unadjusts_volume_and_matches_qm_within_1_percent() { // Synthetic NVDA-style fixture: 4:1 on 2021-07-20 and 10:1 on 2024-06-10. let split1 = day(2021, 7, 20); let split2 = day(2024, 6, 10); let pre_both = day(2021, 7, 19); let on_split1 = split1; let between = day(2024, 6, 7); let on_split2 = split2; let post_both = day(2024, 6, 11); let splits = SplitTable::from_events([ ( "NVDA".to_string(), SplitEvent { ex_date: split2, ratio: 10.0, }, ), ( "NVDA".to_string(), SplitEvent { ex_date: split1, ratio: 4.0, }, ), ]) .unwrap(); let input_bars = vec![ // Pre both splits: factor = 40 -> volume / 40 bar("NVDA".to_string(), pre_both, 730.0, 755.5, 725.25, 751.19, 400_000_000.0), // Exact split1 ex-date: excludes 4:1, includes 10:1 -> factor = 10 bar("NVDA".to_string(), on_split1, 187.3, 190.0, 181.64, 186.12, 434_680_000.0), // Between splits: factor = 10 -> volume / 10 bar("NVDA".to_string(), between, 1197.7, 1216.92, 1180.22, 1208.88, 412_390_000.0), // Exact split2 ex-date: factor = 1 bar("NVDA".to_string(), on_split2, 120.37, 123.1, 117.01, 121.79, 314_162_700.0), // Post both splits: factor = 1 bar("NVDA".to_string(), post_both, 121.77, 122.87, 118.74, 120.91, 222_551_200.0), ]; // Synthetic qmPrices.sharevolume partners within 1% of true raw volume. let qm_partners = vec![ qm("NVDA".to_string(), pre_both, 10_040_000.0), // raw = 10,000,000 (~0.40% diff) qm("NVDA".to_string(), on_split1, 43_468_000.0), // exact match qm("NVDA".to_string(), between, 41_300_000.0), // raw = 41,239,000 (~0.15% diff) qm("NVDA".to_string(), on_split2, 314_162_700.0), qm("NVDA".to_string(), post_both, 222_551_200.0), ]; let built = build_bars_1d(input_bars.clone(), &splits, qm_partners.clone(), 0.01).unwrap(); assert_accounting_invariants(&built.stats); assert_eq!(built.rows.len(), 5); assert_eq!(built.stats.keys_out, 1); assert_eq!(built.stats.volume_checked, 5); assert_eq!(built.stats.volume_within_tolerance, 5); assert_eq!(built.stats.volume_mismatched, 0); assert_eq!(built.stats.volume_unchecked, 0); assert!(built.mismatch_samples.is_empty()); let expected_vols = [ 10_000_000.0, 43_468_000.0, 41_239_000.0, 314_162_700.0, 222_551_200.0, ]; for ((row, orig), (&exp_vol, qm_row)) in built .rows .iter() .zip(&input_bars) .zip(expected_vols.iter().zip(&qm_partners)) { // OHLC passed through bit-for-bit. assert_eq!(row.open.to_bits(), orig.open.to_bits()); assert_eq!(row.high.to_bits(), orig.high.to_bits()); assert_eq!(row.low.to_bits(), orig.low.to_bits()); assert_eq!(row.close.to_bits(), orig.close.to_bits()); assert_rel_eq(row.volume, exp_vol, 1e-12); // Dollar volume (close * raw_volume) within 1% of close * share_volume. let eod_dv = row.close * row.volume; let qm_dv = row.close * qm_row.share_volume; assert!((eod_dv - qm_dv).abs() / qm_dv <= 0.01); } } #[test] fn reverse_split_unknown_key_and_ex_date_boundary() { let ex_date = day(2025, 6, 18); let splits = SplitTable::from_events([( "NEXM.V".to_string(), SplitEvent { ex_date, ratio: 0.05, }, )]) .unwrap(); let built = build_bars_1d( [ // Pre-reverse-split: volume / 0.05 = volume * 20 bar("NEXM.V".to_string(), ex_date - 1, 1.2, 1.3, 1.1, 1.21, 100_000.0), // Exact ex-date: not un-adjusted -> factor 1.0 bar("NEXM.V".to_string(), ex_date, 24.0, 25.0, 23.5, 24.2, 50_000.0), // Unknown key: factor 1.0, volume unchanged bar("UNKNOWN".to_string(), ex_date - 5, 10.0, 11.0, 9.5, 10.5, 123_456.0), ], &splits, std::iter::empty::>(), 0.01, ) .unwrap(); assert_accounting_invariants(&built.stats); assert_eq!(built.rows.len(), 3); assert_eq!(built.stats.keys_out, 2); assert_rel_eq(built.rows[0].volume, 2_000_000.0, 1e-12); assert_eq!(built.rows[1].volume.to_bits(), 50_000.0_f64.to_bits()); assert_eq!(built.rows[2].volume.to_bits(), 123_456.0_f64.to_bits()); } #[test] fn drops_bad_rows_by_priority_and_keeps_zero_volume() { let d = day(2024, 1, 2); let ex = day(2024, 6, 1); let splits = SplitTable::from_events([( 1_i32, SplitEvent { ex_date: ex, ratio: 1e-200, }, )]) .unwrap(); let built = build_bars_1d( [ // Invalid OHLC (NaN, Inf, <=0 on each field) - also inconsistent/bad vol to test priority bar(1, d, f64::NAN, 10.0, 5.0, 8.0, -1.0), bar(1, d + 1, 10.0, f64::INFINITY, 5.0, 8.0, 100.0), bar(1, d + 2, 10.0, 12.0, 0.0, 8.0, 100.0), bar(1, d + 3, 10.0, 12.0, 5.0, -1.0, 100.0), // Inconsistent OHLC (high < low, open < low, open > high, close < low, close > high) bar(1, d + 4, 10.0, 8.0, 9.0, 8.5, -5.0), bar(1, d + 5, 4.0, 10.0, 5.0, 8.0, 100.0), bar(1, d + 6, 11.0, 10.0, 5.0, 8.0, 100.0), bar(1, d + 7, 8.0, 10.0, 5.0, 4.0, 100.0), bar(1, d + 8, 8.0, 10.0, 5.0, 11.0, 100.0), // Invalid adj_volume (NaN, Inf, < 0) bar(1, d + 9, 8.0, 10.0, 5.0, 8.0, f64::NAN), bar(1, d + 10, 8.0, 10.0, 5.0, 8.0, f64::INFINITY), bar(1, d + 11, 8.0, 10.0, 5.0, 8.0, -1.0), // Reverse-split unadjust overflow: 1e200 / 1e-200 -> Inf -> dropped_invalid_volume bar(1, d + 12, 8.0, 10.0, 5.0, 8.0, 1e200), // Zero volume (both +0.0 and -0.0) kept and normalized to +0.0 bar(2, d, 8.0, 10.0, 5.0, 8.0, 0.0), bar(2, d + 1, 8.0, 10.0, 5.0, 8.0, -0.0), ], &splits, std::iter::empty::>(), 0.01, ) .unwrap(); assert_accounting_invariants(&built.stats); assert_eq!(built.stats.dropped_invalid_ohlc, 4); assert_eq!(built.stats.dropped_inconsistent_ohlc, 5); assert_eq!(built.stats.dropped_invalid_volume, 4); assert_eq!(built.stats.rows_out, 2); assert_eq!(built.stats.keys_out, 1); assert_eq!(built.rows[0].volume.to_bits(), 0.0_f64.to_bits()); assert_eq!(built.rows[1].volume.to_bits(), 0.0_f64.to_bits()); } #[test] fn identical_duplicates_collapse_conflicting_drop_and_valid_coexists_with_invalid() { let d1 = day(2024, 3, 1); let d2 = day(2024, 3, 2); let d3 = day(2024, 3, 3); let splits: SplitTable = SplitTable::default(); let built = build_bars_1d( [ // Identical triple (with -0.0 normalized to +0.0) -> collapses to 1 bar(1, d1, 10.0, 12.0, 9.0, 11.0, 0.0), bar(1, d1, 10.0, 12.0, 9.0, 11.0, -0.0), bar(1, d1, 10.0, 12.0, 9.0, 11.0, 0.0), // Conflicting triple -> all 3 dropped bar(1, d2, 10.0, 12.0, 9.0, 11.0, 500.0), bar(1, d2, 10.0, 12.0, 9.0, 11.0, 500.0), bar(1, d2, 10.0, 12.0, 9.0, 11.01, 500.0), // Valid + invalid on same (key, session_date) -> invalid dropped early, valid kept bar(1, d3, 10.0, 12.0, 9.0, 11.0, 750.0), bar(1, d3, -1.0, 12.0, 9.0, 11.0, 750.0), ], &splits, std::iter::empty::>(), 0.01, ) .unwrap(); assert_accounting_invariants(&built.stats); assert_eq!(built.stats.bars_in, 8); assert_eq!(built.stats.dropped_invalid_ohlc, 1); assert_eq!(built.stats.duplicate_collapsed, 2); assert_eq!(built.stats.duplicate_conflict_dropped, 3); assert_eq!(built.stats.rows_out, 2); assert_eq!(built.rows[0].session_date, d1); assert_eq!(built.rows[0].volume, 0.0); assert_eq!(built.rows[1].session_date, d3); assert_eq!(built.rows[1].volume, 750.0); } #[test] fn cross_check_outcomes_boundaries_zeros_qm_hygiene_and_sample_cap() { let base = day(2024, 1, 1); let splits: SplitTable = SplitTable::default(); // Build 110 mismatches + edge cases. let mut bars = vec![ // Exact tolerance boundary: |101 - 100| / 100 = 0.01 <= 0.01 -> within bar(1, base, 10.0, 11.0, 9.0, 10.0, 101.0), // Both zero -> match (rel = 0.0) bar(1, base + 1, 10.0, 11.0, 9.0, 10.0, 0.0), // share_volume == 0, volume > 0 -> mismatch (rel = INFINITY) bar(1, base + 2, 10.0, 11.0, 9.0, 10.0, 50.0), // volume == 0, share_volume > 0 -> rel = 1.0 -> mismatch bar(1, base + 3, 10.0, 11.0, 9.0, 10.0, 0.0), // No partner -> unchecked bar(1, base + 4, 10.0, 11.0, 9.0, 10.0, 200.0), // Partner has conflicting QM duplicates -> QM group dropped -> unchecked bar(1, base + 5, 10.0, 11.0, 9.0, 10.0, 200.0), ]; let mut qms = vec![ // Identical QM duplicate collapses to 1 qm(1, base, 100.0), qm(1, base, 100.0), qm(1, base + 1, -0.0), qm(1, base + 2, 0.0), qm(1, base + 3, 100.0), // Invalid QM rows dropped qm(1, base + 4, f64::NAN), qm(1, base + 4, -5.0), // Conflicting QM rows dropped qm(1, base + 5, 200.0), qm(1, base + 5, 201.0), // Orphan QM row (no EOD bar) must not emit any bar qm(999, base, 500.0), ]; // Add 105 distinct mismatches with known rel values plus ties to test cap & ordering. for i in 0..105_i32 { let d = base + 10 + i; // rel = (i + 2) / 100.0 -> strictly > 0.01 let vol = 100.0 + (i + 2) as f64; bars.push(bar(2, d, 10.0, 11.0, 9.0, 10.0, vol)); qms.push(qm(2, d, 100.0)); } // Tie on rel = 1.0 across two keys/dates: (1, base+3) vs (3, base+1) vs (3, base+2). bars.push(bar(3, base + 2, 10.0, 11.0, 9.0, 10.0, 200.0)); qms.push(qm(3, base + 2, 100.0)); bars.push(bar(3, base + 1, 10.0, 11.0, 9.0, 10.0, 200.0)); qms.push(qm(3, base + 1, 100.0)); let built = build_bars_1d(bars, &splits, qms, 0.01).unwrap(); assert_accounting_invariants(&built.stats); assert_eq!(built.stats.volume_within_tolerance, 2); assert_eq!(built.stats.volume_mismatched, 2 + 105 + 2); assert_eq!(built.stats.volume_unchecked, 2); assert_eq!(built.stats.qm_invalid_volume_dropped, 2); assert_eq!(built.stats.qm_duplicate_collapsed, 1); assert_eq!(built.stats.qm_duplicate_conflict_dropped, 2); assert!(built.stats.max_rel_diff.is_infinite() && built.stats.max_rel_diff.is_sign_positive()); // Capped at MAX_MISMATCH_SAMPLES (100), sorted by (rel DESC, key ASC, session_date ASC). assert_eq!(built.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); assert_eq!(built.mismatch_samples[0].key, 1); assert_eq!(built.mismatch_samples[0].session_date, base + 2); assert!(built.mismatch_samples[0].rel.is_infinite()); // Verify strict ordering of all 100 samples. for w in built.mismatch_samples.windows(2) { let ord = w[1] .rel .total_cmp(&w[0].rel) .then_with(|| w[0].key.cmp(&w[1].key)) .then_with(|| w[0].session_date.cmp(&w[1].session_date)); assert_eq!(ord, Ordering::Less, "samples out of order: {:?} vs {:?}", w[0], w[1]); } // Verify tie ordering for rel == 1.0: (1, base+3) < (2, base+108) < (3, base+1) < (3, base+2). let rel_one: Vec<(i32, i32)> = built .mismatch_samples .iter() .filter(|s| (s.rel - 1.0).abs() < 1e-12) .map(|s| (s.key, s.session_date)) .collect(); assert_eq!( rel_one, vec![(1, base + 3), (2, base + 108), (3, base + 1), (3, base + 2)] ); } #[test] fn invalid_tolerance_returns_typed_error_and_zero_tolerance_is_allowed() { let splits: SplitTable = SplitTable::default(); for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1e-9, -0.01] { let err = build_bars_1d( std::iter::empty::>(), &splits, std::iter::empty::>(), bad, ) .unwrap_err(); assert!(matches!(err, BarsError::InvalidTolerance { .. }), "{bad}: {err:?}"); assert!(!err.to_string().is_empty()); } let d = day(2024, 5, 1); let built = build_bars_1d( [ bar(1, d, 10.0, 11.0, 9.0, 10.0, 100.0), bar(1, d + 1, 10.0, 11.0, 9.0, 10.0, 100.000_001), ], &splits, [qm(1, d, 100.0), qm(1, d + 1, 100.0)], 0.0, ) .unwrap(); assert_eq!(built.stats.volume_within_tolerance, 1); assert_eq!(built.stats.volume_mismatched, 1); } #[test] fn permutation_determinism_across_both_input_streams() { let base = day(2020, 1, 1); let splits = SplitTable::from_events([ (1_i32, SplitEvent { ex_date: base + 10, ratio: 4.0 }), (2_i32, SplitEvent { ex_date: base + 15, ratio: 0.05 }), ]) .unwrap(); let mut bars = vec![ bar(1, base + 5, 10.0, 12.0, 9.0, 11.0, 400.0), bar(1, base + 5, 10.0, 12.0, 9.0, 11.0, 400.0), bar(1, base + 10, 10.0, 12.0, 9.0, 11.0, 100.0), bar(1, base + 12, 10.0, 12.0, 9.0, 11.0, 100.0), bar(1, base + 12, 10.0, 12.0, 9.0, 11.5, 100.0), bar(2, base + 14, 1.0, 1.2, 0.9, 1.1, 50.0), bar(2, base + 15, 20.0, 22.0, 19.0, 21.0, 0.0), bar(3, base + 1, 5.0, 6.0, 4.0, 5.5, 300.0), bar(3, base + 2, -1.0, 6.0, 4.0, 5.5, 300.0), ]; let mut qms = vec![ qm(1, base + 5, 100.0), qm(1, base + 5, 100.0), qm(1, base + 10, 120.0), qm(2, base + 14, 900.0), qm(2, base + 15, 0.0), qm(3, base + 1, 250.0), qm(3, base + 1, 260.0), qm(3, base + 2, -10.0), ]; let baseline = build_bars_1d(bars.clone(), &splits, qms.clone(), 0.01).unwrap(); assert_accounting_invariants(&baseline.stats); let mut state = 0xCAFE_BABE_1234_5678_u64; 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) }; for _ in 0..8 { for i in (1..bars.len()).rev() { let j = (next_u64() % (i as u64 + 1)) as usize; bars.swap(i, j); } for i in (1..qms.len()).rev() { let j = (next_u64() % (i as u64 + 1)) as usize; qms.swap(i, j); } let again = build_bars_1d(bars.clone(), &splits, qms.clone(), 0.01).unwrap(); 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.session_date), (b.key, b.session_date)); assert_eq!(a.open.to_bits(), b.open.to_bits()); assert_eq!(a.high.to_bits(), b.high.to_bits()); assert_eq!(a.low.to_bits(), b.low.to_bits()); assert_eq!(a.close.to_bits(), b.close.to_bits()); assert_eq!(a.volume.to_bits(), b.volume.to_bits()); } assert_eq!(again.mismatch_samples.len(), baseline.mismatch_samples.len()); for (a, b) in again .mismatch_samples .iter() .zip(&baseline.mismatch_samples) { assert_eq!((a.key, a.session_date), (b.key, b.session_date)); assert_eq!(a.volume.to_bits(), b.volume.to_bits()); assert_eq!(a.share_volume.to_bits(), b.share_volume.to_bits()); assert_eq!(a.rel.to_bits(), b.rel.to_bits()); } } } }