stock-bot/tools/curate-etl/src/bars_1m.rs

954 lines
33 KiB
Rust

//! Pure, in-memory `bars_1m` intraday 1-minute bar builder (`eodIntraday1M` + `SplitTable`)
//! and `bars_1d` session-close cross-check.
//!
//! Produces sorted, unique per-`(key, ts)` rows with full OHLCV un-adjusted via
//! [`crate::split::unadjust_ohlcv`] using the cumulative split factor for each bar's **Eastern
//! Time session date** (strict `ex_date > session_date` boundary, matching
//! [`SplitTable::cum_factor_after`] bitwise), plus `PRE`/`RTH`/`POST` session tagging.
//!
//! Aligned with `design/DATA-CONTRACTS.md` (§1 `eodIntraday1M` and §B `bars_1m`):
//! - `eodIntraday1M` has both OHLC and volume retroactively split-adjusted, so
//! `raw_price = adj_price * factor` and `raw_volume = adj_volume / factor` (preserving dollar
//! volume `close * volume`).
//! - Session classification uses Eastern Time (`America/New_York` / `America/Toronto`) derived
//! from UTC microseconds via [`crate::session_close::utc_micros_to_et_local`]:
//! `PRE` (`< 09:30 ET`), `RTH` (`09:30..=15:59 ET`), `POST` (`>= 16:00 ET`).
//! - `vwap` and `known_at` are intentionally left to the downstream writer stage (ILP v2 /
//! QuestDB writer), keeping this module pure and I/O-free.
//! - 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, HashMap};
use std::error::Error;
use std::fmt;
use std::hash::Hash;
use crate::bars::{Bar1dRow, MAX_MISMATCH_SAMPLES};
use crate::session_close::utc_micros_to_et_local;
use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable};
/// Canonical provenance label written to [`Bar1mRow::source`] for un-adjusted `eodIntraday1M` bars.
pub const BARS_1M_SOURCE_EOD: &str = "eod_unadj";
/// Canonical provenance label written to [`Bar1mRow::source`] for raw `qmIntraday` bars.
pub const BARS_1M_SOURCE_QM: &str = "qm_raw";
/// Regular Trading Hours start minute in Eastern Time (`09:30 ET` = `570`).
pub const RTH_START_MINUTE_ET: u16 = 9 * 60 + 30;
/// Regular Trading Hours exclusive end minute in Eastern Time (`16:00 ET` = `960`).
pub const RTH_END_MINUTE_ET: u16 = 16 * 60;
/// Intraday market session classification in Eastern Time (`America/New_York` / `America/Toronto`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IntradaySession {
/// Pre-market (`00:00..09:30 ET`, i.e., `minute_of_day < 570`).
Pre,
/// Regular trading hours (`09:30..16:00 ET`, i.e., `570 <= minute_of_day < 960`).
Rth,
/// Post-market / after-hours (`16:00..24:00 ET`, i.e., `minute_of_day >= 960`).
Post,
}
impl IntradaySession {
/// Returns the canonical `bars_1m.session` string tag (`"PRE"`, `"RTH"`, or `"POST"`).
#[inline]
pub const fn as_str(self) -> &'static str {
match self {
Self::Pre => "PRE",
Self::Rth => "RTH",
Self::Post => "POST",
}
}
/// Classifies an Eastern Time minute-of-day (`0..=1439`) into [`IntradaySession`].
#[inline]
pub const fn from_et_minute(minute_of_day: u16) -> Self {
if minute_of_day < RTH_START_MINUTE_ET {
Self::Pre
} else if minute_of_day < RTH_END_MINUTE_ET {
Self::Rth
} else {
Self::Post
}
}
}
/// A single raw `eodIntraday1M` 1-minute bar input.
///
/// Per `design/DATA-CONTRACTS.md` §1, both OHLC and `volume` are retroactively split-adjusted.
#[derive(Debug, Clone, PartialEq)]
pub struct EodIntradayBar<K = String> {
pub key: K,
/// Bar start timestamp in UTC microseconds since the Unix epoch.
pub ts: i64,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
}
/// A single curated `bars_1m` row, sorted and unique by `(key, ts)`.
///
/// Carries the `bars_1m` contract columns from `design/DATA-CONTRACTS.md` §B (`key`, `ts`,
/// raw un-adjusted OHLCV, `session`, `source`) plus the derived Eastern Time `session_date`.
/// Downstream writer columns (`vwap`, `known_at`) are intentionally left to the writer stage.
#[derive(Debug, Clone, PartialEq)]
pub struct Bar1mRow<K = String> {
pub key: K,
/// Bar start timestamp in UTC microseconds since the Unix epoch.
pub ts: i64,
/// Local Eastern Time calendar date as days since `1970-01-01`.
pub session_date: i32,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
pub session: IntradaySession,
pub source: &'static str,
}
/// Summary counters produced alongside [`Bars1mBuild::rows`].
///
/// Conservation invariants:
/// - `bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + dropped_ts_out_of_range + duplicate_collapsed + duplicate_conflict_dropped`
/// - `pre_rows_out + rth_rows_out + post_rows_out == rows_out`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Bars1mStats {
pub bars_in: usize,
pub rows_out: usize,
pub keys_out: usize,
pub pre_rows_out: usize,
pub rth_rows_out: usize,
pub post_rows_out: usize,
pub dropped_invalid_ohlc: usize,
pub dropped_inconsistent_ohlc: usize,
pub dropped_invalid_volume: usize,
pub dropped_ts_out_of_range: usize,
pub duplicate_collapsed: usize,
pub duplicate_conflict_dropped: usize,
}
/// Output of [`build_bars_1m`]: sorted, unique 1m rows and build statistics.
#[derive(Debug, Clone, PartialEq)]
pub struct Bars1mBuild<K = String> {
pub rows: Vec<Bar1mRow<K>>,
pub stats: Bars1mStats,
}
/// Typed caller errors returned by [`check_session_closes`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Bars1mError {
/// Caller-supplied `rel_tolerance` was non-finite (`NaN`, `+/-inf`) or `< 0.0`.
InvalidTolerance { rel_tolerance: f64 },
}
impl fmt::Display for Bars1mError {
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 Bars1mError {}
/// Daily raw close reference used by [`check_session_closes`].
#[derive(Debug, Clone, PartialEq)]
pub struct DailySessionClose<K = String> {
pub key: K,
/// Session date as days since `1970-01-01` (Eastern / trading calendar date).
pub session_date: i32,
pub close: f64,
/// Optional exclusive Eastern Time session-close cutoff in UTC microseconds.
///
/// When `Some(cutoff_ts)`, only [`IntradaySession::Rth`] bars with `ts < cutoff_ts` are
/// eligible as the session's closing bar (for example, `13:00:00 ET` on an early-close half
/// day so post-close prints between `13:00` and `15:59 ET` do not displace the `12:59 ET`
/// closing bar while [`Bar1mRow::session`] retains the fixed `PRE`/`RTH`/`POST` tags).
/// When `None`, defaults to the standard `16:00:00 ET` RTH boundary.
pub session_close_ts: Option<i64>,
}
impl<K> DailySessionClose<K> {
/// Creates a daily close reference using the standard `16:00:00 ET` RTH cutoff.
#[inline]
pub const fn new(key: K, session_date: i32, close: f64) -> Self {
Self {
key,
session_date,
close,
session_close_ts: None,
}
}
/// Creates a daily close reference with an explicit exclusive UTC microsecond session-close
/// cutoff (for example, `13:00:00 ET` on a half-day early close).
#[inline]
pub const fn with_close_cutoff(
key: K,
session_date: i32,
close: f64,
session_close_ts: i64,
) -> Self {
Self {
key,
session_date,
close,
session_close_ts: Some(session_close_ts),
}
}
}
/// 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<K = String>
where
K: Eq + Hash,
{
per_date: HashMap<i32, i64>,
per_listing_date: HashMap<K, HashMap<i32, Option<i64>>>,
}
impl<K: Eq + Hash> SessionCloseCutoffPolicy<K> {
/// 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<I>(mut self, cutoffs: I) -> Self
where
I: IntoIterator<Item = (i32, i64)>,
{
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<i64>) {
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<i64>,
) -> 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<I>(mut self, cutoffs: I) -> Self
where
I: IntoIterator<Item = (K, i32, Option<i64>)>,
{
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]
pub fn cutoff_for(&self, key: &K, session_date: i32) -> Option<i64> {
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<K: Eq + Hash> DailySessionClose<K> {
/// Converts a raw [`Bar1dRow`] into a [`DailySessionClose`] using an explicit
/// [`SessionCloseCutoffPolicy`].
#[inline]
pub fn from_bar_1d(row: Bar1dRow<K>, cutoff_policy: &SessionCloseCutoffPolicy<K>) -> 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,
}
}
/// Converts a borrowed [`Bar1dRow`] into a [`DailySessionClose`] using an explicit
/// [`SessionCloseCutoffPolicy`].
#[inline]
pub fn from_bar_1d_ref(row: &Bar1dRow<K>, cutoff_policy: &SessionCloseCutoffPolicy<K>) -> 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,
}
}
}
/// A single session-close cross-check mismatch sample retained for downstream reporting.
#[derive(Debug, Clone, PartialEq)]
pub struct SessionCloseMismatchSample<K = String> {
pub key: K,
pub session_date: i32,
pub last_rth_ts: i64,
pub close_1m: f64,
pub close_1d: f64,
pub rel: f64,
}
/// Summary counters and mismatch metrics produced by [`check_session_closes`].
///
/// Conservation invariants:
/// - `checked + unchecked == rth_sessions`
/// - `within_tolerance + mismatched == checked`
/// - `daily_rows_in == daily_unique_partners + daily_invalid_close_dropped + daily_duplicate_collapsed + daily_duplicate_conflict_dropped`
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct SessionCloseStats {
pub rth_sessions: usize,
pub checked: usize,
pub within_tolerance: usize,
pub mismatched: usize,
pub unchecked: usize,
pub max_rel_diff: f64,
pub daily_rows_in: usize,
pub daily_unique_partners: usize,
pub daily_invalid_close_dropped: usize,
pub daily_duplicate_collapsed: usize,
pub daily_duplicate_conflict_dropped: usize,
}
/// Output of [`check_session_closes`]: summary statistics and capped worst mismatch samples.
#[derive(Debug, Clone, PartialEq)]
pub struct SessionCloseCheck<K = String> {
pub stats: SessionCloseStats,
pub mismatch_samples: Vec<SessionCloseMismatchSample<K>>,
}
#[inline]
fn is_valid_price(price: f64) -> bool {
price.is_finite() && price > 0.0
}
#[inline]
fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool {
high >= low && open >= low && open <= high && close >= low && close <= high
}
struct ValidatedIntradayBar<K> {
key: K,
ts: i64,
session_date: i32,
session: IntradaySession,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
}
#[inline]
fn validated_bar_values_bit_eq<K>(
a: &ValidatedIntradayBar<K>,
b: &ValidatedIntradayBar<K>,
) -> 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()
}
/// Builds sorted, unique `bars_1m` rows from split-adjusted `eodIntraday1M` bars.
///
/// - Validates each input bar without panicking in strict priority order:
/// `dropped_invalid_ohlc` -> `dropped_inconsistent_ohlc` -> `dropped_invalid_volume` ->
/// `dropped_ts_out_of_range`.
/// - Normalizes `-0.0` volume to `+0.0`, sorts surviving bars by `(key, ts)`, collapses
/// bitwise-identical `(key, ts)` duplicates (`duplicate_collapsed`), and drops conflicting
/// duplicate groups (`duplicate_conflict_dropped`).
/// - Looks up the cumulative split factor on the strict `ex_date > session_date` boundary using
/// each bar's **Eastern Time** `session_date`, un-adjusts full OHLCV via [`unadjust_ohlcv`],
/// and re-validates post-unadjust values against floating-point overflow/underflow.
/// - Tags each emitted row with [`IntradaySession`] (`PRE`/`RTH`/`POST`) and
/// [`BARS_1M_SOURCE_EOD`].
pub fn build_bars_1m<K, B>(bars: B, splits: &SplitTable<K>) -> Bars1mBuild<K>
where
K: Ord + Eq + Hash + Clone,
B: IntoIterator<Item = EodIntradayBar<K>>,
{
let bars_iter = bars.into_iter();
let mut valid_bars: Vec<ValidatedIntradayBar<K>> = Vec::with_capacity(bars_iter.size_hint().0);
let mut stats = Bars1mStats::default();
for 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 !is_consistent_ohlc(bar.open, bar.high, bar.low, bar.close) {
stats.dropped_inconsistent_ohlc += 1;
continue;
}
if !bar.volume.is_finite() || bar.volume < 0.0 {
stats.dropped_invalid_volume += 1;
continue;
}
let Ok(et_local) = utc_micros_to_et_local(bar.ts) else {
stats.dropped_ts_out_of_range += 1;
continue;
};
let volume = if bar.volume == 0.0 { 0.0 } else { bar.volume };
valid_bars.push(ValidatedIntradayBar {
key: bar.key,
ts: bar.ts,
session_date: et_local.session_date,
session: IntradaySession::from_et_minute(et_local.minute_of_day),
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume,
});
}
valid_bars.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.ts.cmp(&b.ts)));
let mut rows: Vec<Bar1mRow<K>> = 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 bar_idx = key_start;
while bar_idx < key_end {
let ts = valid_bars[bar_idx].ts;
let group_start = bar_idx;
while bar_idx < key_end && valid_bars[bar_idx].ts == ts {
bar_idx += 1;
}
let group_end = bar_idx;
let group_len = group_end - group_start;
let first = &valid_bars[group_start];
let all_identical = valid_bars[group_start + 1..group_end]
.iter()
.all(|other| validated_bar_values_bit_eq(first, other));
if !all_identical {
stats.duplicate_conflict_dropped += group_len;
continue;
}
stats.duplicate_collapsed += group_len - 1;
// `session_date` is monotonically non-decreasing with UTC `ts` (DST transitions
// happen at 02:00 local, never crossing midnight), so this two-pointer scan matches
// `SplitTable::cum_factor_after(&key, first.session_date)` bitwise.
while split_idx < key_splits.len()
&& key_splits[split_idx].ex_date <= first.session_date
{
split_idx += 1;
}
let factor = key_splits.get(split_idx).map_or(1.0, |e| e.suffix_factor);
let mut unadj = unadjust_ohlcv(
OhlcvBar {
open: first.open,
high: first.high,
low: first.low,
close: first.close,
volume: first.volume,
},
factor,
);
if !is_valid_price(unadj.open)
|| !is_valid_price(unadj.high)
|| !is_valid_price(unadj.low)
|| !is_valid_price(unadj.close)
{
stats.dropped_invalid_ohlc += 1;
continue;
}
if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) {
stats.dropped_inconsistent_ohlc += 1;
continue;
}
if !unadj.volume.is_finite()
|| unadj.volume < 0.0
|| (first.volume > 0.0 && unadj.volume == 0.0)
{
stats.dropped_invalid_volume += 1;
continue;
}
if unadj.volume == 0.0 {
unadj.volume = 0.0;
}
match first.session {
IntradaySession::Pre => stats.pre_rows_out += 1,
IntradaySession::Rth => stats.rth_rows_out += 1,
IntradaySession::Post => stats.post_rows_out += 1,
}
rows.push(Bar1mRow {
key: key.clone(),
ts,
session_date: first.session_date,
open: unadj.open,
high: unadj.high,
low: unadj.low,
close: unadj.close,
volume: unadj.volume,
session: first.session,
source: BARS_1M_SOURCE_EOD,
});
}
if rows.len() > key_rows_start {
stats.keys_out += 1;
}
}
stats.rows_out = rows.len();
Bars1mBuild { rows, stats }
}
/// Wrapper ordering [`SessionCloseMismatchSample`] 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 HeapSessionCloseMismatch<K>(SessionCloseMismatchSample<K>);
impl<K: Ord> Ord for HeapSessionCloseMismatch<K> {
#[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<K: Ord> PartialOrd for HeapSessionCloseMismatch<K> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<K: Ord> PartialEq for HeapSessionCloseMismatch<K> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl<K: Ord> Eq for HeapSessionCloseMismatch<K> {}
struct LastRthBar<'a, K> {
key: &'a K,
session_date: i32,
ts: i64,
close: f64,
/// `true` when multiple eligible `Rth` bars shared the maximum `ts` with differing closes.
conflicting_last_ts: bool,
}
fn select_last_rth_bars<'a, K, I>(
rth_sorted: I,
valid_daily: &[DailySessionClose<K>],
) -> Vec<LastRthBar<'a, K>>
where
K: Ord + 'a,
I: IntoIterator<Item = (&'a K, i32, i64, f64)>,
{
let mut result: Vec<LastRthBar<'a, K>> = Vec::new();
let mut daily_idx = 0usize;
let mut cur_group: Option<(&'a K, i32, Option<i64>)> = None;
let mut cur_best: Option<LastRthBar<'a, K>> = None;
for (key, session_date, ts, close) in rth_sorted {
let cutoff = match cur_group {
Some((gk, gd, cutoff)) if gk == key && gd == session_date => cutoff,
_ => {
if let Some(best) = cur_best.take() {
result.push(best);
}
while daily_idx < valid_daily.len() {
match valid_daily[daily_idx]
.key
.cmp(key)
.then_with(|| valid_daily[daily_idx].session_date.cmp(&session_date))
{
Ordering::Less => daily_idx += 1,
Ordering::Equal | Ordering::Greater => break,
}
}
let cutoff = if daily_idx < valid_daily.len()
&& &valid_daily[daily_idx].key == key
&& valid_daily[daily_idx].session_date == session_date
{
valid_daily[daily_idx].session_close_ts
} else {
None
};
cur_group = Some((key, session_date, cutoff));
cutoff
}
};
if let Some(cutoff_ts) = cutoff {
if ts >= cutoff_ts {
continue;
}
}
match &mut cur_best {
Some(best) => match ts.cmp(&best.ts) {
Ordering::Greater => {
best.ts = ts;
best.close = close;
best.conflicting_last_ts = false;
}
Ordering::Equal => {
if close.to_bits() != best.close.to_bits() {
best.conflicting_last_ts = true;
}
}
Ordering::Less => {}
},
None => {
cur_best = Some(LastRthBar {
key,
session_date,
ts,
close,
conflicting_last_ts: false,
});
}
}
}
if let Some(best) = cur_best {
result.push(best);
}
result
}
fn collect_last_rth_bars<'a, K: Ord>(
rows_1m: &'a [Bar1mRow<K>],
valid_daily: &[DailySessionClose<K>],
) -> Vec<LastRthBar<'a, K>> {
let is_sorted = rows_1m.windows(2).all(|w| {
w[0].key
.cmp(&w[1].key)
.then_with(|| w[0].session_date.cmp(&w[1].session_date))
.then_with(|| w[0].ts.cmp(&w[1].ts))
!= Ordering::Greater
});
if is_sorted {
return select_last_rth_bars(
rows_1m
.iter()
.filter(|row| row.session == IntradaySession::Rth)
.map(|row| (&row.key, row.session_date, row.ts, row.close)),
valid_daily,
);
}
let mut rth_rows: Vec<(&'a K, i32, i64, f64)> = rows_1m
.iter()
.filter(|row| row.session == IntradaySession::Rth)
.map(|row| (&row.key, row.session_date, row.ts, row.close))
.collect();
rth_rows.sort_unstable_by(|a, b| {
a.0.cmp(b.0)
.then_with(|| a.1.cmp(&b.1))
.then_with(|| a.2.cmp(&b.2))
});
select_last_rth_bars(rth_rows, valid_daily)
}
/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per
/// `(key, session_date)` against raw daily `bars_1d` closes.
///
/// - Returns [`Bars1mError::InvalidTolerance`] if `rel_tolerance` is non-finite or `< 0.0`.
/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` strictly before the
/// partner's optional [`DailySessionClose::session_close_ts`] cutoff (defaulting to the
/// standard `16:00:00 ET` boundary when `None`), ignoring `PRE`/`POST` bars and excluding
/// sessions with no eligible `RTH` bar before their cutoff.
/// - If a caller supplies multiple eligible `RTH` bars sharing the session's maximum `ts` with
/// differing `close` values, the session is deterministically counted as `unchecked` regardless
/// of input order.
/// - Uses an `O(N)` single-pass scan when `rows_1m` is already sorted by `(key, session_date, ts)`
/// and falls back to a deterministic sort otherwise.
/// - Filters invalid (`<= 0`, non-finite), collapses bitwise-identical duplicate, and drops
/// conflicting duplicate `bars_1d_closes` partners (comparing both `close` and
/// `session_close_ts`).
/// - Retains up to [`MAX_MISMATCH_SAMPLES`] worst mismatches ordered by
/// `(rel DESC, key ASC, session_date ASC)`.
pub fn check_session_closes<K, D, I>(
rows_1m: &[Bar1mRow<K>],
bars_1d_closes: I,
rel_tolerance: f64,
) -> Result<SessionCloseCheck<K>, Bars1mError>
where
K: Ord + Clone,
D: Into<DailySessionClose<K>>,
I: IntoIterator<Item = D>,
{
if !rel_tolerance.is_finite() || rel_tolerance < 0.0 {
return Err(Bars1mError::InvalidTolerance { rel_tolerance });
}
let mut stats = SessionCloseStats::default();
let daily_iter = bars_1d_closes.into_iter();
let mut valid_daily: Vec<DailySessionClose<K>> = Vec::with_capacity(daily_iter.size_hint().0);
for item in daily_iter {
let daily: DailySessionClose<K> = item.into();
stats.daily_rows_in += 1;
if !is_valid_price(daily.close) {
stats.daily_invalid_close_dropped += 1;
continue;
}
valid_daily.push(daily);
}
valid_daily.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 daily_valid_len = valid_daily.len();
while read_idx < daily_valid_len {
let mut group_end = read_idx + 1;
while group_end < daily_valid_len
&& valid_daily[group_end].key == valid_daily[read_idx].key
&& valid_daily[group_end].session_date == valid_daily[read_idx].session_date
{
group_end += 1;
}
let group_len = group_end - read_idx;
let first_bits = valid_daily[read_idx].close.to_bits();
let first_cutoff = valid_daily[read_idx].session_close_ts;
let all_identical = valid_daily[read_idx + 1..group_end].iter().all(|other| {
other.close.to_bits() == first_bits && other.session_close_ts == first_cutoff
});
if all_identical {
stats.daily_duplicate_collapsed += group_len - 1;
if write_idx != read_idx {
valid_daily.swap(write_idx, read_idx);
}
write_idx += 1;
} else {
stats.daily_duplicate_conflict_dropped += group_len;
}
read_idx = group_end;
}
valid_daily.truncate(write_idx);
stats.daily_unique_partners = valid_daily.len();
let last_rth = collect_last_rth_bars(rows_1m, &valid_daily);
stats.rth_sessions = last_rth.len();
let mut daily_idx = 0usize;
let mut heap: BinaryHeap<HeapSessionCloseMismatch<K>> =
BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1);
for rth in &last_rth {
if rth.conflicting_last_ts {
stats.unchecked += 1;
continue;
}
while daily_idx < valid_daily.len() {
match valid_daily[daily_idx]
.key
.cmp(rth.key)
.then_with(|| valid_daily[daily_idx].session_date.cmp(&rth.session_date))
{
Ordering::Less => daily_idx += 1,
Ordering::Equal | Ordering::Greater => break,
}
}
if daily_idx < valid_daily.len()
&& &valid_daily[daily_idx].key == rth.key
&& valid_daily[daily_idx].session_date == rth.session_date
{
let close_1d = valid_daily[daily_idx].close;
daily_idx += 1;
stats.checked += 1;
let rel = if is_valid_price(rth.close) {
(rth.close - close_1d).abs() / close_1d
} else {
f64::INFINITY
};
let within = rel.is_finite() && rel <= rel_tolerance;
if rel > stats.max_rel_diff {
stats.max_rel_diff = rel;
}
if within {
stats.within_tolerance += 1;
} else {
stats.mismatched += 1;
let should_insert = if heap.len() < MAX_MISMATCH_SAMPLES {
true
} else if let Some(worst_kept) = heap.peek() {
worst_kept
.0
.rel
.total_cmp(&rel)
.then_with(|| rth.key.cmp(&worst_kept.0.key))
.then_with(|| rth.session_date.cmp(&worst_kept.0.session_date))
== Ordering::Less
} else {
false
};
if should_insert {
heap.push(HeapSessionCloseMismatch(SessionCloseMismatchSample {
key: rth.key.clone(),
session_date: rth.session_date,
last_rth_ts: rth.ts,
close_1m: rth.close,
close_1d,
rel,
}));
if heap.len() > MAX_MISMATCH_SAMPLES {
heap.pop();
}
}
}
} else {
stats.unchecked += 1;
}
}
let mismatch_samples: Vec<SessionCloseMismatchSample<K>> =
heap.into_sorted_vec().into_iter().map(|w| w.0).collect();
Ok(SessionCloseCheck {
stats,
mismatch_samples,
})
}
/// 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<K, R, I>(
rows_1m: &[Bar1mRow<K>],
bars_1d: I,
cutoff_policy: &SessionCloseCutoffPolicy<K>,
rel_tolerance: f64,
) -> Result<SessionCloseCheck<K>, Bars1mError>
where
K: Ord + Eq + Hash + Clone,
R: Borrow<Bar1dRow<K>>,
I: IntoIterator<Item = R>,
{
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;