diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs index b3dcd5a4..d4d603cd 100644 --- a/tools/curate-etl/src/bars_1m.rs +++ b/tools/curate-etl/src/bars_1m.rs @@ -18,8 +18,9 @@ //! - Bad single rows never panic or abort the build; each failure category is dropped and counted //! separately in [`Bars1mStats`]. +use std::borrow::Borrow; use std::cmp::Ordering; -use std::collections::BinaryHeap; +use std::collections::{BinaryHeap, HashMap}; use std::error::Error; use std::fmt; use std::hash::Hash; @@ -203,26 +204,132 @@ impl DailySessionClose { } } -impl From> for DailySessionClose { +/// Explicit in-memory session-close cutoff policy required when resolving raw [`Bar1dRow`] +/// references for [`check_session_closes_against_bars_1d`] or [`DailySessionClose::from_bar_1d`]. +/// +/// Lookup precedence for `(key, session_date)`: +/// 1. Per-listing, per-date override (`Some(cutoff_ts)` or `None` to explicitly use standard +/// `16:00:00 ET` even when a market-wide per-date cutoff is configured, e.g., a TSX listing on +/// a US early-close day). +/// 2. Per-date cutoff (e.g., `13:00:00 ET` on the Friday after US Thanksgiving). +/// 3. Standard `16:00:00 ET` RTH boundary (`None`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionCloseCutoffPolicy +where + K: Eq + Hash, +{ + per_date: HashMap, + per_listing_date: HashMap>>, +} + +impl SessionCloseCutoffPolicy { + /// Creates an explicit policy using the standard `16:00:00 ET` RTH boundary for all listings + /// and dates (no early-close overrides). + pub fn standard_rth() -> Self { + Self { + per_date: HashMap::new(), + per_listing_date: HashMap::new(), + } + } + + /// Sets an exclusive UTC microsecond session-close cutoff for all listings on `session_date` + /// (unless overridden by a listing-specific rule). + pub fn set_date_cutoff(&mut self, session_date: i32, cutoff_ts: i64) { + self.per_date.insert(session_date, cutoff_ts); + } + + /// Builder-style variant of [`Self::set_date_cutoff`]. + pub fn with_date_cutoff(mut self, session_date: i32, cutoff_ts: i64) -> Self { + self.set_date_cutoff(session_date, cutoff_ts); + self + } + + /// Builder-style helper to populate multiple `(session_date, cutoff_ts)` per-date cutoffs. + pub fn with_date_cutoffs(mut self, cutoffs: I) -> Self + where + I: IntoIterator, + { + for (session_date, cutoff_ts) in cutoffs { + self.set_date_cutoff(session_date, cutoff_ts); + } + self + } + + /// Sets a per-listing, per-date cutoff override. + /// + /// Pass `Some(cutoff_ts)` for a listing-specific early close, or `None` to explicitly select + /// the standard `16:00:00 ET` cutoff for `key` on `session_date` even if a per-date cutoff is + /// configured. + pub fn set_listing_date_cutoff(&mut self, key: K, session_date: i32, cutoff_ts: Option) { + self.per_listing_date + .entry(key) + .or_default() + .insert(session_date, cutoff_ts); + } + + /// Builder-style variant of [`Self::set_listing_date_cutoff`]. + pub fn with_listing_date_cutoff( + mut self, + key: K, + session_date: i32, + cutoff_ts: Option, + ) -> Self { + self.set_listing_date_cutoff(key, session_date, cutoff_ts); + self + } + + /// Builder-style helper to populate multiple `(key, session_date, cutoff_ts)` listing + /// overrides. + pub fn with_listing_date_cutoffs(mut self, cutoffs: I) -> Self + where + I: IntoIterator)>, + { + for (key, session_date, cutoff_ts) in cutoffs { + self.set_listing_date_cutoff(key, session_date, cutoff_ts); + } + self + } + + /// Resolves the exclusive UTC microsecond session-close cutoff for `(key, session_date)`, + /// returning `None` when the standard `16:00:00 ET` RTH boundary applies. #[inline] - fn from(row: Bar1dRow) -> Self { + pub fn cutoff_for(&self, key: &K, session_date: i32) -> Option { + if let Some(listing_cutoffs) = self.per_listing_date.get(key) { + if let Some(&override_cutoff) = listing_cutoffs.get(&session_date) { + return override_cutoff; + } + } + self.per_date.get(&session_date).copied() + } +} + +impl DailySessionClose { + /// Converts a raw [`Bar1dRow`] into a [`DailySessionClose`] using an explicit + /// [`SessionCloseCutoffPolicy`]. + #[inline] + pub fn from_bar_1d(row: Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self { + let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); Self { key: row.key, session_date: row.session_date, close: row.close, - session_close_ts: None, + session_close_ts, } } -} -impl From<&Bar1dRow> for DailySessionClose { + /// Converts a borrowed [`Bar1dRow`] into a [`DailySessionClose`] using an explicit + /// [`SessionCloseCutoffPolicy`]. #[inline] - fn from(row: &Bar1dRow) -> Self { + pub fn from_bar_1d_ref(row: &Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self + where + K: Clone, + { + let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); Self { key: row.key.clone(), session_date: row.session_date, close: row.close, - session_close_ts: None, + session_close_ts, } } } @@ -812,6 +919,33 @@ where }) } +/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per +/// `(key, session_date)` against raw [`Bar1dRow`] daily rows using an explicit +/// [`SessionCloseCutoffPolicy`]. +/// +/// Raw `Bar1dRow` values do not carry an exchange session-close cutoff, so callers must pass +/// `cutoff_policy` (for example, [`SessionCloseCutoffPolicy::standard_rth`] or a policy populated +/// with per-date / per-listing early-close cutoffs) rather than silently assuming `16:00:00 ET`. +pub fn check_session_closes_against_bars_1d( + rows_1m: &[Bar1mRow], + bars_1d: I, + cutoff_policy: &SessionCloseCutoffPolicy, + rel_tolerance: f64, +) -> Result, Bars1mError> +where + K: Ord + Eq + Hash + Clone, + R: Borrow>, + I: IntoIterator, +{ + check_session_closes( + rows_1m, + bars_1d + .into_iter() + .map(|row| DailySessionClose::from_bar_1d_ref(row.borrow(), cutoff_policy)), + rel_tolerance, + ) +} + #[cfg(test)] #[path = "bars_1m_tests.rs"] mod tests; diff --git a/tools/curate-etl/src/bars_1m_tests.rs b/tools/curate-etl/src/bars_1m_tests.rs index 81e4b66e..de8e7d68 100644 --- a/tools/curate-etl/src/bars_1m_tests.rs +++ b/tools/curate-etl/src/bars_1m_tests.rs @@ -196,7 +196,10 @@ fn nexm_reverse_split_1_for_20_unadjusts_pre_split_preserves_ex_date_and_matches daily_row("NEXM.V".to_string(), ex_date, 24.30), daily_row("NEXM.V".to_string(), post_day, 24.65), ]; - let check = check_session_closes(&built.rows, &daily_closes, 0.005).unwrap(); + let standard_policy = SessionCloseCutoffPolicy::standard_rth(); + let check = + check_session_closes_against_bars_1d(&built.rows, &daily_closes, &standard_policy, 0.005) + .unwrap(); assert_close_check_invariants(&check.stats); assert_eq!(check.stats.rth_sessions, 3); assert_eq!(check.stats.checked, 3); @@ -278,7 +281,10 @@ fn nvda_forward_split_10_for_1_unadjusts_pre_split_and_matches_bars_1d() { daily_row("NVDA.US".to_string(), ex_date, 121.79), daily_row("NVDA.US".to_string(), post_day, 120.91), ]; - let check = check_session_closes(&built.rows, daily_closes, 0.005).unwrap(); + let standard_policy = SessionCloseCutoffPolicy::standard_rth(); + let check = + check_session_closes_against_bars_1d(&built.rows, daily_closes, &standard_policy, 0.005) + .unwrap(); assert_close_check_invariants(&check.stats); assert_eq!(check.stats.checked, 3); assert_eq!(check.stats.within_tolerance, 3); @@ -321,7 +327,10 @@ fn negative_non_vacuity_still_adjusted_pre_split_bars_fail_session_close_check() daily_row("NEXM.V".to_string(), pre_day, 1.2145), daily_row("NEXM.V".to_string(), ex_date, 24.30), ]; - let check = check_session_closes(&built.rows, daily_closes, 0.005).unwrap(); + let standard_policy = SessionCloseCutoffPolicy::standard_rth(); + let check = + check_session_closes_against_bars_1d(&built.rows, daily_closes, &standard_policy, 0.005) + .unwrap(); assert_close_check_invariants(&check.stats); assert_eq!(check.stats.checked, 2); assert_eq!(check.stats.within_tolerance, 1); @@ -535,15 +544,24 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a assert!(err.to_string().contains("invalid relative tolerance")); } - // 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close): + // 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close) via raw Bar1dRow path: // - build_bars_1m preserves the fixed PRE/RTH/POST tags (13:00 and 13:15 still carry RTH). - // - check_session_closes applies the listing's 13:00 ET session_close_ts cutoff so 12:59 ET - // is selected and 13:00 / 13:15 / 16:15 prints do not displace the closing bar. + // - check_session_closes_against_bars_1d applies an explicit SessionCloseCutoffPolicy + // supporting per-date cutoffs and per-listing overrides: + // * listing 1 (US equity): inherits per-date 13:00 ET cutoff -> selects 12:59 ET, + // excluding 13:00 / 13:15 / 16:15 ET prints. + // * listing 2 (e.g. TSX equity on US Thanksgiving Friday): per-listing `None` override + // uses standard 16:00 ET close -> selects 15:59 ET. + // * listing 3: per-listing custom 14:00 ET cutoff -> selects 13:59 ET, excluding 14:15. let half_day = day(2024, 11, 29); // Friday after US Thanksgiving let post_only_day = day(2024, 12, 2); let ts_1259 = et_ts(2024, 11, 29, 12, 59); let ts_1300 = et_ts(2024, 11, 29, 13, 0); let ts_1315 = et_ts(2024, 11, 29, 13, 15); + let ts_1359 = et_ts(2024, 11, 29, 13, 59); + let ts_1400 = et_ts(2024, 11, 29, 14, 0); + let ts_1415 = et_ts(2024, 11, 29, 14, 15); + let ts_1559 = et_ts(2024, 11, 29, 15, 59); let splits: SplitTable = SplitTable::default(); let built = build_bars_1m( @@ -558,6 +576,12 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a // PRE/POST-only session must be excluded from rth_sessions. bar_1m(1, et_ts(2024, 12, 2, 8, 0), 102.0, 103.0, 101.5, 102.5, 50.0), bar_1m(1, et_ts(2024, 12, 2, 17, 0), 103.0, 104.0, 102.5, 103.5, 50.0), + // Listing 2 (standard 16:00 ET close override on half_day): 12:59 vs 15:59 (>5% apart). + bar_1m(2, ts_1259, 50.0, 50.5, 49.5, 50.0, 300.0), + bar_1m(2, ts_1559, 53.0, 53.5, 52.5, 53.25, 400.0), + // Listing 3 (listing-specific 14:00 ET cutoff override on half_day): 13:59 vs 14:15. + bar_1m(3, ts_1359, 20.0, 20.2, 19.8, 20.10, 250.0), + bar_1m(3, ts_1415, 21.5, 21.8, 21.2, 21.60, 100.0), ], &splits, ); @@ -572,25 +596,53 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a let mut reversed_rows = built.rows.clone(); reversed_rows.reverse(); - let daily = [ - DailySessionClose::with_close_cutoff(1, half_day, 101.25, ts_1300), - DailySessionClose::new(1, post_only_day, 103.5), + let cutoff_policy = SessionCloseCutoffPolicy::standard_rth() + .with_date_cutoff(half_day, ts_1300) + .with_listing_date_cutoff(2, half_day, None) + .with_listing_date_cutoff(3, half_day, Some(ts_1400)); + + let raw_daily_rows = [ + daily_row(1, half_day, 101.25), + daily_row(1, post_only_day, 103.5), + daily_row(2, half_day, 53.25), + daily_row(3, half_day, 20.10), ]; - let sorted_check = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); - let unsorted_check = check_session_closes(&reversed_rows, daily, 0.005).unwrap(); + + let sorted_check = + check_session_closes_against_bars_1d(&built.rows, &raw_daily_rows, &cutoff_policy, 0.005) + .unwrap(); + let unsorted_check = + check_session_closes_against_bars_1d(&reversed_rows, &raw_daily_rows, &cutoff_policy, 0.005) + .unwrap(); assert_eq!(sorted_check, unsorted_check); assert_close_check_invariants(&sorted_check.stats); - assert_eq!(sorted_check.stats.rth_sessions, 1); - assert_eq!(sorted_check.stats.checked, 1); - assert_eq!(sorted_check.stats.within_tolerance, 1); + assert_eq!(sorted_check.stats.rth_sessions, 3); + assert_eq!(sorted_check.stats.checked, 3); + assert_eq!(sorted_check.stats.within_tolerance, 3); assert_eq!(sorted_check.stats.mismatched, 0); assert_eq!(sorted_check.stats.max_rel_diff, 0.0); - // Prove 12:59 ET (101.25) was actually selected under the 13:00 ET cutoff: - // comparing against the 13:15 ET price (105.5) must report a mismatch at ts_1259. - let prove_1259 = check_session_closes( + // Verify DailySessionClose::from_bar_1d / from_bar_1d_ref parity with the cutoff policy. + let converted_owned: Vec> = raw_daily_rows + .iter() + .cloned() + .map(|row| DailySessionClose::from_bar_1d(row, &cutoff_policy)) + .collect(); + assert_eq!(converted_owned[0].session_close_ts, Some(ts_1300)); + assert_eq!(converted_owned[1].session_close_ts, None); + assert_eq!(converted_owned[2].session_close_ts, None); + assert_eq!(converted_owned[3].session_close_ts, Some(ts_1400)); + assert_eq!( + check_session_closes(&built.rows, converted_owned, 0.005).unwrap(), + sorted_check + ); + + // Prove 12:59 ET (101.25) was actually selected for listing 1 under the 13:00 ET cutoff: + // comparing its raw Bar1dRow against the 13:15 ET price (105.5) must mismatch at ts_1259. + let prove_1259 = check_session_closes_against_bars_1d( &built.rows, - [DailySessionClose::with_close_cutoff(1, half_day, 105.5, ts_1300)], + [daily_row(1, half_day, 105.5)], + &cutoff_policy, 0.005, ) .unwrap(); @@ -598,25 +650,27 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a assert_eq!(prove_1259.mismatch_samples[0].last_rth_ts, ts_1259); assert_eq!(prove_1259.mismatch_samples[0].close_1m, 101.25); - // Without the early-close cutoff, the fixed 16:00 ET window picks 13:15 ET (105.5) and mismatches. - let without_cutoff = check_session_closes( + // Under an explicit standard 16:00 ET policy, listing 1 picks 13:15 ET (105.5) and mismatches. + let standard_only = check_session_closes_against_bars_1d( &built.rows, - [DailySessionClose::new(1, half_day, 101.25)], + [daily_row(1, half_day, 101.25)], + &SessionCloseCutoffPolicy::standard_rth(), 0.005, ) .unwrap(); - assert_eq!(without_cutoff.stats.mismatched, 1); - assert_eq!(without_cutoff.mismatch_samples[0].last_rth_ts, ts_1315); - assert_eq!(without_cutoff.mismatch_samples[0].close_1m, 105.5); + assert_eq!(standard_only.stats.mismatched, 1); + assert_eq!(standard_only.mismatch_samples[0].last_rth_ts, ts_1315); + assert_eq!(standard_only.mismatch_samples[0].close_1m, 105.5); // A half-day session whose only RTH bars are at/after the cutoff has no eligible RTH bar. let post_cutoff_only = build_bars_1m( [bar_1m(9, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0)], &splits, ); - let post_cutoff_check = check_session_closes( + let post_cutoff_check = check_session_closes_against_bars_1d( &post_cutoff_only.rows, - [DailySessionClose::with_close_cutoff(9, half_day, 101.25, ts_1300)], + [daily_row(9, half_day, 101.25)], + &cutoff_policy, 0.005, ) .unwrap(); diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 5b9711a1..6fea2441 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -876,10 +876,45 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result, session_date: i32) -> BenchRthCandidate { + BenchRthCandidate { + key: bar.key, + session_date, + ts: bar.ts, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: if bar.volume == 0.0 { 0.0 } else { bar.volume }, + } + } + + #[inline] + fn bench_rth_values_bit_eq(a: &BenchRthCandidate, b: &BenchRthCandidate) -> 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.volume.to_bits() == b.volume.to_bits() + } + let mut bars: Vec> = Vec::with_capacity(rows); - // Track every valid RTH candidate `(key, session_date, ts, close)` (including exact/conflicting - // duplicates) so we can derive each session's exact expected last valid RTH bar before timing. - let mut valid_rth_candidates: Vec<(i32, i32, i64, f64)> = Vec::with_capacity(rows / 2 + 64); + // Track every valid RTH candidate with all five normalized OHLCV fields (including exact and + // conflicting duplicates) so we match `build_bars_1m`'s duplicate-conflict drop rule when + // deriving each session's expected last surviving valid RTH bar before timing. + let mut valid_rth_candidates: Vec = Vec::with_capacity(rows / 2 + 64); let mut last_valid: Option<(EodIntradayBar, i32, bool)> = None; for _ in 0..rows { @@ -887,7 +922,7 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result Result Result Result Result> = Vec::with_capacity(valid_rth_candidates.len() / 4 + 64); let mut idx = 0usize; while idx < valid_rth_candidates.len() { - let key = valid_rth_candidates[idx].0; - let session_date = valid_rth_candidates[idx].1; + let key = valid_rth_candidates[idx].key; + let session_date = valid_rth_candidates[idx].session_date; let mut session_end = idx + 1; while session_end < valid_rth_candidates.len() - && valid_rth_candidates[session_end].0 == key - && valid_rth_candidates[session_end].1 == session_date + && valid_rth_candidates[session_end].key == key + && valid_rth_candidates[session_end].session_date == session_date { session_end += 1; } @@ -1021,17 +1057,17 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result = None; let mut g = idx; while g < session_end { - let ts = valid_rth_candidates[g].2; + let ts = valid_rth_candidates[g].ts; let mut g_end = g + 1; - while g_end < session_end && valid_rth_candidates[g_end].2 == ts { + while g_end < session_end && valid_rth_candidates[g_end].ts == ts { g_end += 1; } - let first_bits = valid_rth_candidates[g].3.to_bits(); + let first = &valid_rth_candidates[g]; let all_same = valid_rth_candidates[g + 1..g_end] .iter() - .all(|c| c.3.to_bits() == first_bits); + .all(|c| bench_rth_values_bit_eq(first, c)); if all_same { - expected_last_close = Some(valid_rth_candidates[g].3); + expected_last_close = Some(first.close); } g = g_end; } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 0af02987..eaefb854 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -38,10 +38,10 @@ pub use bars::{ VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; pub use bars_1m::{ - build_bars_1m, check_session_closes, Bar1mRow, Bars1mBuild, Bars1mError, Bars1mStats, - DailySessionClose, EodIntradayBar, IntradaySession, SessionCloseCheck, - SessionCloseMismatchSample, SessionCloseStats, BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, - RTH_START_MINUTE_ET, + build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, Bar1mRow, + Bars1mBuild, Bars1mError, Bars1mStats, DailySessionClose, EodIntradayBar, IntradaySession, + SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, + BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, }; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc,