T-130: M2.3a — tools/curate-etl: pure bars_1m builder (eodIntraday1M full-bar split un-adjustment + PRE/RTH/POST session tagging + session-close vs bars_1d cross-check) with tests and local benchmark (no new crates)
This commit is contained in:
parent
79b260aec5
commit
58658ff163
8 changed files with 2218 additions and 7 deletions
711
tools/curate-etl/src/bars_1m.rs
Normal file
711
tools/curate-etl/src/bars_1m.rs
Normal file
|
|
@ -0,0 +1,711 @@
|
|||
//! 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::cmp::Ordering;
|
||||
use std::collections::BinaryHeap;
|
||||
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";
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl<K> From<Bar1dRow<K>> for DailySessionClose<K> {
|
||||
#[inline]
|
||||
fn from(row: Bar1dRow<K>) -> Self {
|
||||
Self {
|
||||
key: row.key,
|
||||
session_date: row.session_date,
|
||||
close: row.close,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Clone> From<&Bar1dRow<K>> for DailySessionClose<K> {
|
||||
#[inline]
|
||||
fn from(row: &Bar1dRow<K>) -> Self {
|
||||
Self {
|
||||
key: row.key.clone(),
|
||||
session_date: row.session_date,
|
||||
close: row.close,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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,
|
||||
}
|
||||
|
||||
fn collect_last_rth_bars<K: Ord>(rows_1m: &[Bar1mRow<K>]) -> Vec<LastRthBar<'_, 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 {
|
||||
let mut last_rth: Vec<LastRthBar<'_, K>> = Vec::new();
|
||||
for row in rows_1m {
|
||||
if row.session != IntradaySession::Rth {
|
||||
continue;
|
||||
}
|
||||
if let Some(prev) = last_rth.last_mut() {
|
||||
if prev.key == &row.key && prev.session_date == row.session_date {
|
||||
prev.ts = row.ts;
|
||||
prev.close = row.close;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
last_rth.push(LastRthBar {
|
||||
key: &row.key,
|
||||
session_date: row.session_date,
|
||||
ts: row.ts,
|
||||
close: row.close,
|
||||
});
|
||||
}
|
||||
return last_rth;
|
||||
}
|
||||
|
||||
let mut rth_rows: Vec<LastRthBar<'_, K>> = rows_1m
|
||||
.iter()
|
||||
.filter(|row| row.session == IntradaySession::Rth)
|
||||
.map(|row| LastRthBar {
|
||||
key: &row.key,
|
||||
session_date: row.session_date,
|
||||
ts: row.ts,
|
||||
close: row.close,
|
||||
})
|
||||
.collect();
|
||||
|
||||
rth_rows.sort_by(|a, b| {
|
||||
a.key
|
||||
.cmp(b.key)
|
||||
.then_with(|| a.session_date.cmp(&b.session_date))
|
||||
.then_with(|| a.ts.cmp(&b.ts))
|
||||
});
|
||||
|
||||
let mut write_idx = 0usize;
|
||||
let mut read_idx = 0usize;
|
||||
while read_idx < rth_rows.len() {
|
||||
let mut group_end = read_idx + 1;
|
||||
while group_end < rth_rows.len()
|
||||
&& rth_rows[group_end].key == rth_rows[read_idx].key
|
||||
&& rth_rows[group_end].session_date == rth_rows[read_idx].session_date
|
||||
{
|
||||
group_end += 1;
|
||||
}
|
||||
let last_idx = group_end - 1;
|
||||
if write_idx != last_idx {
|
||||
rth_rows.swap(write_idx, last_idx);
|
||||
}
|
||||
write_idx += 1;
|
||||
read_idx = group_end;
|
||||
}
|
||||
rth_rows.truncate(write_idx);
|
||||
rth_rows
|
||||
}
|
||||
|
||||
/// 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)` (handling early-close half
|
||||
/// days cleanly while ignoring `PRE`/`POST` bars and excluding `PRE`/`POST`-only sessions).
|
||||
/// - 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.
|
||||
/// - 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 last_rth = collect_last_rth_bars(rows_1m);
|
||||
stats.rth_sessions = last_rth.len();
|
||||
|
||||
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 all_identical = valid_daily[read_idx + 1..group_end]
|
||||
.iter()
|
||||
.all(|other| other.close.to_bits() == first_bits);
|
||||
|
||||
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 mut daily_idx = 0usize;
|
||||
let mut heap: BinaryHeap<HeapSessionCloseMismatch<K>> =
|
||||
BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1);
|
||||
|
||||
for rth in &last_rth {
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bars_1m_tests.rs"]
|
||||
mod tests;
|
||||
687
tools/curate-etl/src/bars_1m_tests.rs
Normal file
687
tools/curate-etl/src/bars_1m_tests.rs
Normal file
|
|
@ -0,0 +1,687 @@
|
|||
use super::*;
|
||||
use crate::bars::Bar1dRow;
|
||||
use crate::session_close::{SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS};
|
||||
use crate::shorts::et_to_utc_micros;
|
||||
use crate::split::{ymd_to_epoch_days, SplitEvent};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 {
|
||||
et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp")
|
||||
}
|
||||
|
||||
fn utc_ts(y: i32, m: u32, d: u32, hour: i64, minute: i64) -> i64 {
|
||||
(i64::from(day(y, m, d)) * 86_400 + hour * 3_600 + minute * 60) * 1_000_000
|
||||
}
|
||||
|
||||
fn bar_1m<K>(
|
||||
key: K,
|
||||
ts: i64,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
) -> EodIntradayBar<K> {
|
||||
EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
}
|
||||
}
|
||||
|
||||
fn daily_row<K>(key: K, session_date: i32, close: f64) -> Bar1dRow<K> {
|
||||
Bar1dRow {
|
||||
key,
|
||||
session_date,
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 100_000.0,
|
||||
}
|
||||
}
|
||||
|
||||
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_bars_1m_invariants(stats: &Bars1mStats) {
|
||||
assert_eq!(
|
||||
stats.bars_in,
|
||||
stats.rows_out
|
||||
+ stats.dropped_invalid_ohlc
|
||||
+ stats.dropped_inconsistent_ohlc
|
||||
+ stats.dropped_invalid_volume
|
||||
+ stats.dropped_ts_out_of_range
|
||||
+ stats.duplicate_collapsed
|
||||
+ stats.duplicate_conflict_dropped,
|
||||
"bars_1m conservation invariant failed: {stats:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stats.rows_out,
|
||||
stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out,
|
||||
"session breakdown != rows_out: {stats:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_close_check_invariants(stats: &SessionCloseStats) {
|
||||
assert_eq!(
|
||||
stats.checked + stats.unchecked,
|
||||
stats.rth_sessions,
|
||||
"checked + unchecked != rth_sessions: {stats:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stats.within_tolerance + stats.mismatched,
|
||||
stats.checked,
|
||||
"within_tolerance + mismatched != checked: {stats:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stats.daily_rows_in,
|
||||
stats.daily_unique_partners
|
||||
+ stats.daily_invalid_close_dropped
|
||||
+ stats.daily_duplicate_collapsed
|
||||
+ stats.daily_duplicate_conflict_dropped,
|
||||
"daily partner conservation failed: {stats:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nexm_reverse_split_1_for_20_unadjusts_pre_split_preserves_ex_date_and_matches_bars_1d() {
|
||||
let pre_day = day(2025, 6, 17);
|
||||
let ex_date = day(2025, 6, 18);
|
||||
let post_day = day(2025, 6, 19);
|
||||
|
||||
let splits = SplitTable::from_events([(
|
||||
"NEXM.V".to_string(),
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: 0.05,
|
||||
},
|
||||
)])
|
||||
.unwrap();
|
||||
|
||||
// Adjusted 1m bars from eodIntraday1M:
|
||||
// Pre-split close = 24.29 -> un-adjusted = 24.29 * 0.05 = 1.2145, volume = 5000 / 0.05 = 100_000.
|
||||
let pre_open_bar = bar_1m(
|
||||
"NEXM.V".to_string(),
|
||||
et_ts(2025, 6, 17, 9, 30),
|
||||
24.00,
|
||||
24.60,
|
||||
23.80,
|
||||
24.20,
|
||||
2_000.0,
|
||||
);
|
||||
let pre_close_bar = bar_1m(
|
||||
"NEXM.V".to_string(),
|
||||
et_ts(2025, 6, 17, 15, 59),
|
||||
24.20,
|
||||
24.40,
|
||||
24.10,
|
||||
24.29,
|
||||
5_000.0,
|
||||
);
|
||||
let ex_bar = bar_1m(
|
||||
"NEXM.V".to_string(),
|
||||
et_ts(2025, 6, 18, 15, 59),
|
||||
24.10,
|
||||
24.50,
|
||||
23.90,
|
||||
24.30,
|
||||
12_500.0,
|
||||
);
|
||||
let post_bar = bar_1m(
|
||||
"NEXM.V".to_string(),
|
||||
et_ts(2025, 6, 19, 15, 59),
|
||||
24.30,
|
||||
24.80,
|
||||
24.00,
|
||||
24.65,
|
||||
9_800.0,
|
||||
);
|
||||
|
||||
let built = build_bars_1m(
|
||||
[
|
||||
pre_open_bar.clone(),
|
||||
pre_close_bar.clone(),
|
||||
ex_bar.clone(),
|
||||
post_bar.clone(),
|
||||
],
|
||||
&splits,
|
||||
);
|
||||
assert_bars_1m_invariants(&built.stats);
|
||||
assert_eq!(built.rows.len(), 4);
|
||||
assert_eq!(built.stats.keys_out, 1);
|
||||
assert_eq!(built.stats.rth_rows_out, 4);
|
||||
|
||||
// Pre-split close bar un-adjusted: price * 0.05, volume / 0.05, dollar volume invariant.
|
||||
let pre_close_out = &built.rows[1];
|
||||
assert_eq!(pre_close_out.session_date, pre_day);
|
||||
assert_eq!(pre_close_out.session, IntradaySession::Rth);
|
||||
assert_eq!(pre_close_out.source, BARS_1M_SOURCE_EOD);
|
||||
assert_rel_eq(pre_close_out.open, 1.21, 1e-12);
|
||||
assert_rel_eq(pre_close_out.high, 1.22, 1e-12);
|
||||
assert_rel_eq(pre_close_out.low, 1.205, 1e-12);
|
||||
assert_rel_eq(pre_close_out.close, 1.2145, 1e-12);
|
||||
assert_rel_eq(pre_close_out.volume, 100_000.0, 1e-12);
|
||||
assert_rel_eq(
|
||||
pre_close_out.close * pre_close_out.volume,
|
||||
pre_close_bar.close * pre_close_bar.volume,
|
||||
1e-12,
|
||||
);
|
||||
|
||||
// Ex-date and post-split bars must be bit-for-bit unchanged.
|
||||
for (actual, expected) in [(&built.rows[2], &ex_bar), (&built.rows[3], &post_bar)] {
|
||||
assert_eq!(actual.open.to_bits(), expected.open.to_bits());
|
||||
assert_eq!(actual.high.to_bits(), expected.high.to_bits());
|
||||
assert_eq!(actual.low.to_bits(), expected.low.to_bits());
|
||||
assert_eq!(actual.close.to_bits(), expected.close.to_bits());
|
||||
assert_eq!(actual.volume.to_bits(), expected.volume.to_bits());
|
||||
}
|
||||
|
||||
// Raw bars_1d closes match within 0.5% (0 mismatches).
|
||||
let daily_closes = [
|
||||
daily_row("NEXM.V".to_string(), pre_day, 1.215), // ~0.041% diff vs 1.2145
|
||||
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();
|
||||
assert_close_check_invariants(&check.stats);
|
||||
assert_eq!(check.stats.rth_sessions, 3);
|
||||
assert_eq!(check.stats.checked, 3);
|
||||
assert_eq!(check.stats.within_tolerance, 3);
|
||||
assert_eq!(check.stats.mismatched, 0);
|
||||
assert_eq!(check.stats.unchecked, 0);
|
||||
assert!(check.stats.max_rel_diff < 0.005);
|
||||
assert!(check.mismatch_samples.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nvda_forward_split_10_for_1_unadjusts_pre_split_and_matches_bars_1d() {
|
||||
let pre_day = day(2024, 6, 7);
|
||||
let ex_date = day(2024, 6, 10);
|
||||
let post_day = day(2024, 6, 11);
|
||||
|
||||
let splits = SplitTable::from_events([(
|
||||
"NVDA.US".to_string(),
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: 10.0,
|
||||
},
|
||||
)])
|
||||
.unwrap();
|
||||
|
||||
// Pre-split adjusted 1m close = 120.888 -> raw = 1208.88; volume = 412_390 -> raw = 41_239.
|
||||
let pre_bar = bar_1m(
|
||||
"NVDA.US".to_string(),
|
||||
et_ts(2024, 6, 7, 15, 59),
|
||||
120.50,
|
||||
121.00,
|
||||
120.40,
|
||||
120.888,
|
||||
412_390.0,
|
||||
);
|
||||
let ex_bar = bar_1m(
|
||||
"NVDA.US".to_string(),
|
||||
et_ts(2024, 6, 10, 15, 59),
|
||||
121.50,
|
||||
121.95,
|
||||
121.40,
|
||||
121.79,
|
||||
350_000.0,
|
||||
);
|
||||
let post_bar = bar_1m(
|
||||
"NVDA.US".to_string(),
|
||||
et_ts(2024, 6, 11, 15, 59),
|
||||
120.80,
|
||||
121.10,
|
||||
120.70,
|
||||
120.91,
|
||||
290_000.0,
|
||||
);
|
||||
|
||||
let built = build_bars_1m([pre_bar.clone(), ex_bar.clone(), post_bar.clone()], &splits);
|
||||
assert_bars_1m_invariants(&built.stats);
|
||||
assert_eq!(built.rows.len(), 3);
|
||||
|
||||
let pre_out = &built.rows[0];
|
||||
assert_rel_eq(pre_out.open, 1_205.0, 1e-12);
|
||||
assert_rel_eq(pre_out.high, 1_210.0, 1e-12);
|
||||
assert_rel_eq(pre_out.low, 1_204.0, 1e-12);
|
||||
assert_rel_eq(pre_out.close, 1_208.88, 1e-12);
|
||||
assert_rel_eq(pre_out.volume, 41_239.0, 1e-12);
|
||||
assert_rel_eq(
|
||||
pre_out.close * pre_out.volume,
|
||||
pre_bar.close * pre_bar.volume,
|
||||
1e-12,
|
||||
);
|
||||
|
||||
// Post-split unchanged bit-for-bit.
|
||||
assert_eq!(built.rows[1].close.to_bits(), ex_bar.close.to_bits());
|
||||
assert_eq!(built.rows[1].volume.to_bits(), ex_bar.volume.to_bits());
|
||||
assert_eq!(built.rows[2].close.to_bits(), post_bar.close.to_bits());
|
||||
assert_eq!(built.rows[2].volume.to_bits(), post_bar.volume.to_bits());
|
||||
|
||||
let daily_closes = [
|
||||
daily_row("NVDA.US".to_string(), pre_day, 1_208.88),
|
||||
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();
|
||||
assert_close_check_invariants(&check.stats);
|
||||
assert_eq!(check.stats.checked, 3);
|
||||
assert_eq!(check.stats.within_tolerance, 3);
|
||||
assert_eq!(check.stats.mismatched, 0);
|
||||
assert!(check.mismatch_samples.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_non_vacuity_still_adjusted_pre_split_bars_fail_session_close_check() {
|
||||
let pre_day = day(2025, 6, 17);
|
||||
let ex_date = day(2025, 6, 18);
|
||||
let empty_splits: SplitTable<String> = SplitTable::default();
|
||||
|
||||
// Build with an empty split table so pre-split bar stays retroactively adjusted (24.29).
|
||||
let built = build_bars_1m(
|
||||
[
|
||||
bar_1m(
|
||||
"NEXM.V".to_string(),
|
||||
et_ts(2025, 6, 17, 15, 59),
|
||||
24.20,
|
||||
24.40,
|
||||
24.10,
|
||||
24.29,
|
||||
5_000.0,
|
||||
),
|
||||
bar_1m(
|
||||
"NEXM.V".to_string(),
|
||||
et_ts(2025, 6, 18, 15, 59),
|
||||
24.10,
|
||||
24.50,
|
||||
23.90,
|
||||
24.30,
|
||||
12_500.0,
|
||||
),
|
||||
],
|
||||
&empty_splits,
|
||||
);
|
||||
|
||||
let daily_closes = [
|
||||
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();
|
||||
assert_close_check_invariants(&check.stats);
|
||||
assert_eq!(check.stats.checked, 2);
|
||||
assert_eq!(check.stats.within_tolerance, 1);
|
||||
assert_eq!(check.stats.mismatched, 1);
|
||||
assert!(
|
||||
check.stats.max_rel_diff > 0.005,
|
||||
"expected max_rel_diff > 0.005, got {}",
|
||||
check.stats.max_rel_diff
|
||||
);
|
||||
assert_eq!(check.mismatch_samples.len(), 1);
|
||||
assert_eq!(check.mismatch_samples[0].key, "NEXM.V");
|
||||
assert_eq!(check.mismatch_samples[0].session_date, pre_day);
|
||||
assert_rel_eq(check.mismatch_samples[0].rel, 19.0, 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_tagging_boundaries_in_est_and_edt_and_utc_date_rollover_split_lookup() {
|
||||
assert_eq!(IntradaySession::Pre.as_str(), "PRE");
|
||||
assert_eq!(IntradaySession::Rth.as_str(), "RTH");
|
||||
assert_eq!(IntradaySession::Post.as_str(), "POST");
|
||||
|
||||
// 1. EST (winter: 2025-01-15) and EDT (summer: 2024-06-10) session boundaries.
|
||||
let splits_empty: SplitTable<&'static str> = SplitTable::default();
|
||||
let boundary_bars = [
|
||||
// EST (UTC-5): 09:29 ET = 14:29 UTC, 09:30 = 14:30, 15:59 = 20:59, 16:00 = 21:00
|
||||
bar_1m("EST", utc_ts(2025, 1, 15, 14, 29), 10.0, 10.5, 9.5, 10.1, 100.0),
|
||||
bar_1m("EST", utc_ts(2025, 1, 15, 14, 30), 10.0, 10.5, 9.5, 10.2, 100.0),
|
||||
bar_1m("EST", utc_ts(2025, 1, 15, 20, 59), 10.0, 10.5, 9.5, 10.3, 100.0),
|
||||
bar_1m("EST", utc_ts(2025, 1, 15, 21, 0), 10.0, 10.5, 9.5, 10.4, 100.0),
|
||||
// EDT (UTC-4): 09:29 ET = 13:29 UTC, 09:30 = 13:30, 15:59 = 19:59, 16:00 = 20:00
|
||||
bar_1m("EDT", utc_ts(2024, 6, 10, 13, 29), 10.0, 10.5, 9.5, 10.1, 100.0),
|
||||
bar_1m("EDT", utc_ts(2024, 6, 10, 13, 30), 10.0, 10.5, 9.5, 10.2, 100.0),
|
||||
bar_1m("EDT", utc_ts(2024, 6, 10, 19, 59), 10.0, 10.5, 9.5, 10.3, 100.0),
|
||||
bar_1m("EDT", utc_ts(2024, 6, 10, 20, 0), 10.0, 10.5, 9.5, 10.4, 100.0),
|
||||
];
|
||||
let built = build_bars_1m(boundary_bars, &splits_empty);
|
||||
assert_bars_1m_invariants(&built.stats);
|
||||
assert_eq!(built.stats.pre_rows_out, 2);
|
||||
assert_eq!(built.stats.rth_rows_out, 4);
|
||||
assert_eq!(built.stats.post_rows_out, 2);
|
||||
|
||||
let expected_sessions = [
|
||||
IntradaySession::Pre,
|
||||
IntradaySession::Rth,
|
||||
IntradaySession::Rth,
|
||||
IntradaySession::Post,
|
||||
];
|
||||
for (idx, row) in built.rows.iter().enumerate() {
|
||||
assert_eq!(row.session, expected_sessions[idx % 4], "row {idx}");
|
||||
}
|
||||
|
||||
// 2. UTC date == ex_date while ET session_date == ex_date - 1 (both EDT and EST):
|
||||
// must use ET session_date so the pre-split factor IS applied.
|
||||
let edt_ex = day(2024, 6, 10);
|
||||
let est_ex = day(2025, 1, 16);
|
||||
let splits = SplitTable::from_events([
|
||||
(
|
||||
"EDT_ROLL".to_string(),
|
||||
SplitEvent {
|
||||
ex_date: edt_ex,
|
||||
ratio: 10.0,
|
||||
},
|
||||
),
|
||||
(
|
||||
"EST_ROLL".to_string(),
|
||||
SplitEvent {
|
||||
ex_date: est_ex,
|
||||
ratio: 2.0,
|
||||
},
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
// 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (POST, session_date = edt_ex - 1)
|
||||
let edt_evening_ts = utc_ts(2024, 6, 10, 0, 30);
|
||||
// 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST (POST, session_date = est_ex - 1)
|
||||
let est_evening_ts = utc_ts(2025, 1, 16, 0, 30);
|
||||
|
||||
let rollover = build_bars_1m(
|
||||
[
|
||||
bar_1m("EDT_ROLL".to_string(), edt_evening_ts, 12.0, 12.5, 11.5, 12.2, 1_000.0),
|
||||
bar_1m("EST_ROLL".to_string(), est_evening_ts, 50.0, 51.0, 49.0, 50.5, 400.0),
|
||||
],
|
||||
&splits,
|
||||
);
|
||||
assert_bars_1m_invariants(&rollover.stats);
|
||||
assert_eq!(rollover.rows.len(), 2);
|
||||
|
||||
assert_eq!(rollover.rows[0].key, "EDT_ROLL");
|
||||
assert_eq!(rollover.rows[0].session_date, edt_ex - 1);
|
||||
assert_eq!(rollover.rows[0].session, IntradaySession::Post);
|
||||
assert_rel_eq(rollover.rows[0].close, 122.0, 1e-12);
|
||||
assert_rel_eq(rollover.rows[0].volume, 100.0, 1e-12);
|
||||
|
||||
assert_eq!(rollover.rows[1].key, "EST_ROLL");
|
||||
assert_eq!(rollover.rows[1].session_date, est_ex - 1);
|
||||
assert_eq!(rollover.rows[1].session, IntradaySession::Post);
|
||||
assert_rel_eq(rollover.rows[1].close, 101.0, 1e-12);
|
||||
assert_rel_eq(rollover.rows[1].volume, 200.0, 1e-12);
|
||||
|
||||
// 3. Fall-back DST repeated 01:30 ET hour (EDT 05:30 UTC vs EST 06:30 UTC on 2024-11-03):
|
||||
// distinct UTC timestamps must NOT collide as duplicates.
|
||||
let fall_edt = utc_ts(2024, 11, 3, 5, 30);
|
||||
let fall_est = utc_ts(2024, 11, 3, 6, 30);
|
||||
let fall_built = build_bars_1m(
|
||||
[
|
||||
bar_1m("FALL", fall_est, 10.0, 10.2, 9.9, 10.1, 20.0),
|
||||
bar_1m("FALL", fall_edt, 10.0, 10.3, 9.8, 10.2, 10.0),
|
||||
],
|
||||
&splits_empty,
|
||||
);
|
||||
assert_bars_1m_invariants(&fall_built.stats);
|
||||
assert_eq!(fall_built.rows.len(), 2);
|
||||
assert_eq!(fall_built.rows[0].ts, fall_edt);
|
||||
assert_eq!(fall_built.rows[1].ts, fall_est);
|
||||
assert_eq!(fall_built.rows[0].session_date, day(2024, 11, 3));
|
||||
assert_eq!(fall_built.rows[1].session_date, day(2024, 11, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_duplicates() {
|
||||
let base_ts = et_ts(2024, 5, 1, 10, 0);
|
||||
let ex_date = day(2024, 6, 1);
|
||||
|
||||
let splits = SplitTable::from_events([
|
||||
(
|
||||
1_i32,
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: 1e-200,
|
||||
},
|
||||
),
|
||||
(
|
||||
2_i32,
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: 1e200,
|
||||
},
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let minute = 60_000_000_i64;
|
||||
let built = build_bars_1m(
|
||||
[
|
||||
// Priority 1: invalid OHLC (also inconsistent / bad vol / bad ts to verify priority)
|
||||
bar_1m(1, i64::MIN, f64::NAN, 10.0, 5.0, 8.0, -1.0),
|
||||
bar_1m(1, base_ts + minute, 10.0, f64::INFINITY, 5.0, 8.0, 10.0),
|
||||
bar_1m(1, base_ts + 2 * minute, 10.0, 12.0, 0.0, 8.0, 10.0),
|
||||
bar_1m(1, base_ts + 3 * minute, 10.0, 12.0, 5.0, -1.0, 10.0),
|
||||
// Priority 2: inconsistent OHLC (high < low, open/close out of [low, high])
|
||||
bar_1m(1, base_ts + 4 * minute, 10.0, 8.0, 9.0, 8.5, -5.0),
|
||||
bar_1m(1, base_ts + 5 * minute, 4.0, 10.0, 5.0, 8.0, 10.0),
|
||||
bar_1m(1, base_ts + 6 * minute, 11.0, 10.0, 5.0, 8.0, 10.0),
|
||||
bar_1m(1, base_ts + 7 * minute, 8.0, 10.0, 5.0, 4.0, 10.0),
|
||||
bar_1m(1, base_ts + 8 * minute, 8.0, 10.0, 5.0, 11.0, 10.0),
|
||||
// Priority 3: invalid volume (NaN, Inf, negative)
|
||||
bar_1m(1, base_ts + 9 * minute, 8.0, 10.0, 5.0, 8.0, f64::NAN),
|
||||
bar_1m(1, base_ts + 10 * minute, 8.0, 10.0, 5.0, 8.0, f64::INFINITY),
|
||||
bar_1m(1, base_ts + 11 * minute, 8.0, 10.0, 5.0, 8.0, -1.0),
|
||||
// Priority 4: out-of-range ts (pre-1976, post-2030, i64::MIN, i64::MAX)
|
||||
bar_1m(1, SESSION_MIN_SUPPORTED_UTC_MICROS - 1, 8.0, 10.0, 5.0, 8.0, 10.0),
|
||||
bar_1m(1, SESSION_MAX_SUPPORTED_UTC_MICROS + 1, 8.0, 10.0, 5.0, 8.0, 10.0),
|
||||
bar_1m(1, i64::MIN, 8.0, 10.0, 5.0, 8.0, 10.0),
|
||||
bar_1m(1, i64::MAX, 8.0, 10.0, 5.0, 8.0, 10.0),
|
||||
// Post-unadjust volume overflow (1e200 / 1e-200 -> Inf) -> dropped_invalid_volume
|
||||
bar_1m(1, base_ts + 12 * minute, 8.0, 10.0, 5.0, 8.0, 1e200),
|
||||
// Post-unadjust price underflow (1e-200 * 1e-200 -> 0.0) -> dropped_invalid_ohlc
|
||||
bar_1m(1, base_ts + 13 * minute, 1e-200, 1e-200, 1e-200, 1e-200, 10.0),
|
||||
// Post-unadjust price overflow (1e200 * 1e200 -> Inf) -> dropped_invalid_ohlc
|
||||
bar_1m(2, base_ts + 14 * minute, 1e200, 1e200, 1e200, 1e200, 10.0),
|
||||
// Exact duplicate triple (including -0.0 vs +0.0 volume) -> collapses to 1 row
|
||||
bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, 0.0),
|
||||
bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, -0.0),
|
||||
bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, 0.0),
|
||||
// Conflicting duplicate pair -> both dropped
|
||||
bar_1m(3, base_ts + minute, 10.0, 12.0, 9.0, 11.0, 50.0),
|
||||
bar_1m(3, base_ts + minute, 10.0, 12.0, 9.0, 11.01, 50.0),
|
||||
],
|
||||
&splits,
|
||||
);
|
||||
|
||||
assert_bars_1m_invariants(&built.stats);
|
||||
assert_eq!(built.stats.bars_in, 24);
|
||||
assert_eq!(built.stats.dropped_invalid_ohlc, 6); // 4 input + 1 underflow + 1 overflow
|
||||
assert_eq!(built.stats.dropped_inconsistent_ohlc, 5);
|
||||
assert_eq!(built.stats.dropped_invalid_volume, 4); // 3 input + 1 volume overflow
|
||||
assert_eq!(built.stats.dropped_ts_out_of_range, 4);
|
||||
assert_eq!(built.stats.duplicate_collapsed, 2);
|
||||
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
|
||||
assert_eq!(built.stats.rows_out, 1);
|
||||
assert_eq!(built.stats.keys_out, 1);
|
||||
assert_eq!(built.rows[0].key, 3);
|
||||
assert_eq!(built.rows[0].volume.to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_and_errors() {
|
||||
// 1. Invalid tolerances return Bars1mError::InvalidTolerance.
|
||||
for bad_tol in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.001] {
|
||||
let err = check_session_closes::<i32, DailySessionClose<i32>, _>(
|
||||
&[],
|
||||
std::iter::empty(),
|
||||
bad_tol,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, Bars1mError::InvalidTolerance { .. }));
|
||||
assert!(err.source().is_none());
|
||||
assert!(err.to_string().contains("invalid relative tolerance"));
|
||||
}
|
||||
|
||||
// 2. Half-day early close (last RTH bar 12:59 ET, later POST bar ignored) + PRE/POST-only session.
|
||||
let half_day = day(2024, 11, 29); // Day after US Thanksgiving
|
||||
let post_only_day = day(2024, 12, 2);
|
||||
let splits: SplitTable<i32> = SplitTable::default();
|
||||
|
||||
let built = build_bars_1m(
|
||||
[
|
||||
bar_1m(1, et_ts(2024, 11, 29, 9, 30), 100.0, 101.0, 99.5, 100.5, 500.0),
|
||||
bar_1m(1, et_ts(2024, 11, 29, 12, 59), 101.0, 101.5, 100.8, 101.25, 800.0),
|
||||
// Later POST bar with a very different close must NOT be selected as RTH close.
|
||||
bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.0, 106.0, 104.5, 105.5, 100.0),
|
||||
// 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),
|
||||
],
|
||||
&splits,
|
||||
);
|
||||
|
||||
// Reverse rows_1m to exercise the unsorted fallback path in check_session_closes.
|
||||
let mut reversed_rows = built.rows.clone();
|
||||
reversed_rows.reverse();
|
||||
|
||||
let daily = [
|
||||
DailySessionClose {
|
||||
key: 1,
|
||||
session_date: half_day,
|
||||
close: 101.25,
|
||||
},
|
||||
DailySessionClose {
|
||||
key: 1,
|
||||
session_date: post_only_day,
|
||||
close: 103.5,
|
||||
},
|
||||
];
|
||||
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();
|
||||
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.mismatched, 0);
|
||||
|
||||
// 3. Daily close hygiene (invalid, identical dup, conflicting dup) + >100 mismatch sample cap.
|
||||
let base_day = day(2024, 1, 2);
|
||||
let mut rows_1m_in = Vec::new();
|
||||
let mut daily_in = Vec::new();
|
||||
|
||||
// Session 0: exact match with identical daily duplicate -> collapses to 1
|
||||
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 2, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
|
||||
daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 });
|
||||
daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 });
|
||||
|
||||
// Session 1: conflicting daily duplicate -> dropped -> unchecked
|
||||
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 3, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
|
||||
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.0 });
|
||||
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.5 });
|
||||
|
||||
// Session 2: invalid daily closes (NaN, <=0) -> dropped -> unchecked
|
||||
rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 4, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0));
|
||||
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: f64::NAN });
|
||||
daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: 0.0 });
|
||||
|
||||
// 110 mismatches across distinct days on key=2 (plus a tie on key=3 to verify tie-break order).
|
||||
let start_day = day(2024, 2, 1);
|
||||
for i in 0..110_i32 {
|
||||
let d = start_day + i;
|
||||
let ts = et_to_utc_micros(d, 15, 59, 0).unwrap();
|
||||
let close_1m = 100.0 + (i + 2) as f64; // rel = (i + 2) / 100 >= 0.02 > 0.005
|
||||
rows_1m_in.push(bar_1m(2, ts, close_1m, close_1m, close_1m, close_1m, 100.0));
|
||||
daily_in.push(DailySessionClose {
|
||||
key: 2,
|
||||
session_date: d,
|
||||
close: 100.0,
|
||||
});
|
||||
}
|
||||
// Tie with highest rel (1.11) on key=3 vs key=2 -> key=2 must sort before key=3.
|
||||
let tie_d = start_day + 109;
|
||||
let tie_ts = et_to_utc_micros(tie_d, 15, 59, 0).unwrap();
|
||||
rows_1m_in.push(bar_1m(3, tie_ts, 211.0, 211.0, 211.0, 211.0, 100.0));
|
||||
daily_in.push(DailySessionClose {
|
||||
key: 3,
|
||||
session_date: tie_d,
|
||||
close: 100.0,
|
||||
});
|
||||
|
||||
let built_many = build_bars_1m(rows_1m_in, &splits);
|
||||
let check_many = check_session_closes(&built_many.rows, daily_in, 0.005).unwrap();
|
||||
assert_close_check_invariants(&check_many.stats);
|
||||
assert_eq!(check_many.stats.daily_invalid_close_dropped, 2);
|
||||
assert_eq!(check_many.stats.daily_duplicate_collapsed, 1);
|
||||
assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 2);
|
||||
assert_eq!(check_many.stats.unchecked, 2);
|
||||
assert_eq!(check_many.stats.mismatched, 111);
|
||||
assert_eq!(check_many.mismatch_samples.len(), MAX_MISMATCH_SAMPLES);
|
||||
|
||||
// Top two samples have rel == 1.11: key=2 before key=3.
|
||||
assert_rel_eq(check_many.mismatch_samples[0].rel, 1.11, 1e-12);
|
||||
assert_eq!(check_many.mismatch_samples[0].key, 2);
|
||||
assert_rel_eq(check_many.mismatch_samples[1].rel, 1.11, 1e-12);
|
||||
assert_eq!(check_many.mismatch_samples[1].key, 3);
|
||||
|
||||
// Entire mismatch_samples slice is strictly ordered by (rel DESC, key ASC, session_date ASC).
|
||||
for w in check_many.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]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_is_sorted_unique_and_deterministic_across_input_permutations() {
|
||||
let splits = SplitTable::from_events([
|
||||
(
|
||||
"B".to_string(),
|
||||
SplitEvent {
|
||||
ex_date: day(2024, 6, 10),
|
||||
ratio: 5.0,
|
||||
},
|
||||
),
|
||||
(
|
||||
"A".to_string(),
|
||||
SplitEvent {
|
||||
ex_date: day(2024, 6, 12),
|
||||
ratio: 0.25,
|
||||
},
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut bars = vec![
|
||||
bar_1m("B".to_string(), et_ts(2024, 6, 10, 15, 59), 20.0, 21.0, 19.5, 20.5, 300.0),
|
||||
bar_1m("A".to_string(), et_ts(2024, 6, 11, 9, 30), 40.0, 41.0, 39.0, 40.2, 100.0),
|
||||
bar_1m("B".to_string(), et_ts(2024, 6, 7, 15, 59), 19.0, 20.0, 18.5, 19.8, 500.0),
|
||||
bar_1m("A".to_string(), et_ts(2024, 6, 11, 9, 30), 40.0, 41.0, 39.0, 40.2, 100.0),
|
||||
bar_1m("A".to_string(), et_ts(2024, 6, 12, 16, 0), 10.0, 10.5, 9.8, 10.1, 200.0),
|
||||
];
|
||||
|
||||
let forward = build_bars_1m(bars.clone(), &splits);
|
||||
bars.reverse();
|
||||
let reversed = build_bars_1m(bars, &splits);
|
||||
|
||||
assert_eq!(forward, reversed);
|
||||
assert_bars_1m_invariants(&forward.stats);
|
||||
for w in forward.rows.windows(2) {
|
||||
let ord = w[0].key.cmp(&w[1].key).then_with(|| w[0].ts.cmp(&w[1].ts));
|
||||
assert_eq!(ord, Ordering::Less, "output not strictly sorted/unique");
|
||||
}
|
||||
}
|
||||
|
|
@ -16,6 +16,10 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
|
|||
|
||||
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
|
||||
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
|
||||
use crate::bars_1m::{
|
||||
build_bars_1m, check_session_closes, Bars1mError, Bars1mStats, DailySessionClose,
|
||||
EodIntradayBar, IntradaySession, SessionCloseStats,
|
||||
};
|
||||
use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats};
|
||||
use crate::bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats,
|
||||
|
|
@ -55,6 +59,7 @@ use crate::parquet_shorts::{
|
|||
write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions,
|
||||
};
|
||||
use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::session_close::{et_session_close_utc_micros, SESSION_MIN_SUPPORTED_UTC_MICROS};
|
||||
use crate::shorts::{
|
||||
add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, CeoShortReport,
|
||||
ShortsError, ShortsStats, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET,
|
||||
|
|
@ -66,6 +71,7 @@ pub const DEFAULT_BENCH_ROWS: usize = 10_000_000;
|
|||
pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000;
|
||||
pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000;
|
||||
pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000;
|
||||
pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000;
|
||||
pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000;
|
||||
pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
|
||||
pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000;
|
||||
|
|
@ -105,6 +111,9 @@ const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57;
|
|||
const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70;
|
||||
const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71;
|
||||
const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00;
|
||||
const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100;
|
||||
const BARS_1M_BENCH_KEY_COUNT: usize = 2_000;
|
||||
const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000;
|
||||
const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
|
||||
const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500;
|
||||
const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500;
|
||||
|
|
@ -689,6 +698,375 @@ pub fn run_bars_benchmark(rows: usize) -> Result<BarsBenchReport, BarsError> {
|
|||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_bars_1m_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Bars1mBenchReport {
|
||||
pub rows: usize,
|
||||
pub key_count: usize,
|
||||
pub split_event_count: usize,
|
||||
pub daily_rows_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub keys_out: usize,
|
||||
pub mismatch_samples_out: usize,
|
||||
pub build_elapsed_ms: f64,
|
||||
pub check_elapsed_ms: f64,
|
||||
pub total_elapsed_ms: f64,
|
||||
pub rows_per_sec: f64,
|
||||
pub ns_per_row: f64,
|
||||
pub checksum: u64,
|
||||
pub build_stats: Bars1mStats,
|
||||
pub close_stats: SessionCloseStats,
|
||||
}
|
||||
|
||||
fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> {
|
||||
let nexm_ex = ymd_to_epoch_days(2025, 6, 18).unwrap_or(20_257);
|
||||
let nvda_ex = ymd_to_epoch_days(2024, 6, 10).unwrap_or(19_884);
|
||||
let splits = SplitTable::from_events([
|
||||
(
|
||||
"NEXM.V",
|
||||
SplitEvent {
|
||||
ex_date: nexm_ex,
|
||||
ratio: 0.05,
|
||||
},
|
||||
),
|
||||
(
|
||||
"NVDA.US",
|
||||
SplitEvent {
|
||||
ex_date: nvda_ex,
|
||||
ratio: 10.0,
|
||||
},
|
||||
),
|
||||
])
|
||||
.expect("valid bench self-check splits");
|
||||
|
||||
let nexm_pre_ts = et_to_utc_micros(nexm_ex - 1, 15, 59, 0).expect("valid ET");
|
||||
let nexm_ex_ts = et_to_utc_micros(nexm_ex, 15, 59, 0).expect("valid ET");
|
||||
let nvda_pre_ts = et_to_utc_micros(nvda_ex - 3, 15, 59, 0).expect("valid ET");
|
||||
let nvda_ex_ts = et_to_utc_micros(nvda_ex, 15, 59, 0).expect("valid ET");
|
||||
let est_day = ymd_to_epoch_days(2025, 1, 15).expect("valid date");
|
||||
let est_pre_ts = et_to_utc_micros(est_day, 9, 29, 0).expect("valid ET");
|
||||
let est_rth_ts = et_to_utc_micros(est_day, 9, 30, 0).expect("valid ET");
|
||||
let est_post_ts = et_to_utc_micros(est_day, 16, 0, 0).expect("valid ET");
|
||||
|
||||
let built = build_bars_1m(
|
||||
[
|
||||
EodIntradayBar {
|
||||
key: "NEXM.V",
|
||||
ts: nexm_pre_ts,
|
||||
open: 24.0,
|
||||
high: 24.5,
|
||||
low: 23.9,
|
||||
close: 24.29,
|
||||
volume: 5_000.0,
|
||||
},
|
||||
EodIntradayBar {
|
||||
key: "NEXM.V",
|
||||
ts: nexm_ex_ts,
|
||||
open: 24.1,
|
||||
high: 24.4,
|
||||
low: 24.0,
|
||||
close: 24.30,
|
||||
volume: 10_000.0,
|
||||
},
|
||||
EodIntradayBar {
|
||||
key: "NVDA.US",
|
||||
ts: nvda_pre_ts,
|
||||
open: 120.5,
|
||||
high: 121.0,
|
||||
low: 120.4,
|
||||
close: 120.888,
|
||||
volume: 412_390.0,
|
||||
},
|
||||
EodIntradayBar {
|
||||
key: "NVDA.US",
|
||||
ts: nvda_ex_ts,
|
||||
open: 121.5,
|
||||
high: 121.9,
|
||||
low: 121.4,
|
||||
close: 121.79,
|
||||
volume: 300_000.0,
|
||||
},
|
||||
EodIntradayBar {
|
||||
key: "SESS",
|
||||
ts: est_pre_ts,
|
||||
open: 10.0,
|
||||
high: 10.1,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
volume: 100.0,
|
||||
},
|
||||
EodIntradayBar {
|
||||
key: "SESS",
|
||||
ts: est_rth_ts,
|
||||
open: 10.0,
|
||||
high: 10.1,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
volume: 100.0,
|
||||
},
|
||||
EodIntradayBar {
|
||||
key: "SESS",
|
||||
ts: est_post_ts,
|
||||
open: 10.0,
|
||||
high: 10.1,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
volume: 100.0,
|
||||
},
|
||||
],
|
||||
&splits,
|
||||
);
|
||||
|
||||
assert_eq!(built.rows.len(), 7, "self-check expected 7 bars");
|
||||
assert!(
|
||||
(built.rows[0].close - 1.2145).abs() < 1e-9,
|
||||
"NEXM.V pre-split self-check failed"
|
||||
);
|
||||
assert_eq!(built.rows[1].close.to_bits(), 24.30_f64.to_bits());
|
||||
assert!(
|
||||
(built.rows[2].close - 1_208.88).abs() < 1e-9,
|
||||
"NVDA.US pre-split close self-check failed"
|
||||
);
|
||||
assert!(
|
||||
(built.rows[2].volume - 41_239.0).abs() < 1e-9,
|
||||
"NVDA.US pre-split volume self-check failed"
|
||||
);
|
||||
assert_eq!(built.rows[3].close.to_bits(), 121.79_f64.to_bits());
|
||||
assert_eq!(built.rows[4].session, IntradaySession::Pre);
|
||||
assert_eq!(built.rows[5].session, IntradaySession::Rth);
|
||||
assert_eq!(built.rows[6].session, IntradaySession::Post);
|
||||
|
||||
let daily = [
|
||||
DailySessionClose {
|
||||
key: "NEXM.V",
|
||||
session_date: nexm_ex - 1,
|
||||
close: 1.2145,
|
||||
},
|
||||
DailySessionClose {
|
||||
key: "NEXM.V",
|
||||
session_date: nexm_ex,
|
||||
close: 24.30,
|
||||
},
|
||||
DailySessionClose {
|
||||
key: "NVDA.US",
|
||||
session_date: nvda_ex - 3,
|
||||
close: 1_208.88,
|
||||
},
|
||||
DailySessionClose {
|
||||
key: "NVDA.US",
|
||||
session_date: nvda_ex,
|
||||
close: 121.79,
|
||||
},
|
||||
];
|
||||
let check = check_session_closes(&built.rows, daily, 0.005)?;
|
||||
assert_eq!(check.stats.checked, 4, "self-check expected 4 checked sessions");
|
||||
assert_eq!(check.stats.mismatched, 0, "self-check expected 0 mismatches");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed `build_bars_1m` + `check_session_closes` benchmark for `rows` 1-minute bars.
|
||||
///
|
||||
/// Executes a pre-timing correctness self-check (NEXM.V 1:20 reverse split, NVDA.US 10:1 forward
|
||||
/// split, EST/EDT session tagging, and `check_session_closes`), then generates `rows` deterministic
|
||||
/// multi-session EST/EDT 1m bars across `2_000` `i32` keys with forward/reverse splits, a small
|
||||
/// share of invalid/inconsistent/out-of-range/duplicate bars, and daily close cross-check partners.
|
||||
/// Times [`build_bars_1m`] and [`check_session_closes`] and returns throughput plus a deterministic
|
||||
/// `u64` checksum.
|
||||
pub fn run_bars_1m_benchmark(rows: usize) -> Result<Bars1mBenchReport, Bars1mError> {
|
||||
verify_bars_1m_bench_self_check()?;
|
||||
|
||||
let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724);
|
||||
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 mut rng = SplitMix64::new(BARS_1M_BENCH_SEED);
|
||||
|
||||
let mut split_events = Vec::with_capacity(BARS_1M_BENCH_EVENT_COUNT);
|
||||
for _ in 0..BARS_1M_BENCH_EVENT_COUNT {
|
||||
let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1;
|
||||
let ex_date = min_date + (rng.next_u64() % date_span) as i32;
|
||||
let ratio = SAMPLE_RATIOS[(rng.next_u64() % (SAMPLE_RATIOS.len() as u64)) as usize];
|
||||
split_events.push((key, SplitEvent { ex_date, ratio }));
|
||||
}
|
||||
let splits = SplitTable::from_events(split_events).unwrap_or_default();
|
||||
let split_event_count = splits.event_count();
|
||||
|
||||
let mut bars: Vec<EodIntradayBar<i32>> = Vec::with_capacity(rows);
|
||||
let mut daily_closes: Vec<DailySessionClose<i32>> = Vec::with_capacity(rows / 20 + 64);
|
||||
|
||||
let mut last_valid: Option<EodIntradayBar<i32>> = None;
|
||||
for _ in 0..rows {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 5 {
|
||||
if let Some(prev) = last_valid.clone() {
|
||||
bars.push(prev);
|
||||
continue;
|
||||
}
|
||||
} else if roll < 7 {
|
||||
if let Some(mut prev) = last_valid.clone() {
|
||||
prev.close = (prev.close + 0.05).min(prev.high);
|
||||
if prev.close.to_bits() == last_valid.as_ref().map_or(0, |b| b.close.to_bits()) {
|
||||
prev.volume += 1.0;
|
||||
}
|
||||
bars.push(prev);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1;
|
||||
let session_date = min_date + (rng.next_u64() % date_span) as i32;
|
||||
// 08:00..=19:59 ET (minutes 480..1200) -> spans PRE, RTH, and POST on both EST and EDT.
|
||||
let et_minute = 480 + (rng.next_u64() % 720) as i64;
|
||||
let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0);
|
||||
let ts = close_1600_utc + (et_minute - 960) * 60_000_000;
|
||||
|
||||
let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01;
|
||||
let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01;
|
||||
let high = low + spread;
|
||||
let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
|
||||
let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
|
||||
let volume = ((rng.next_u64() % 500_000) + 10) as f64;
|
||||
|
||||
let bar = match roll {
|
||||
7..=8 => EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open: -1.0,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
},
|
||||
9..=10 => EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open,
|
||||
high: low - 0.5,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
},
|
||||
11..=12 => EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume: -10.0,
|
||||
},
|
||||
13..=14 => EodIntradayBar {
|
||||
key,
|
||||
ts: SESSION_MIN_SUPPORTED_UTC_MICROS - 60_000_000,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
},
|
||||
15..=17 => {
|
||||
let b = EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume: 0.0,
|
||||
};
|
||||
last_valid = Some(b.clone());
|
||||
b
|
||||
}
|
||||
_ => {
|
||||
let b = EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
};
|
||||
last_valid = Some(b.clone());
|
||||
if (570..960).contains(&et_minute) && (rng.next_u64() % 16) == 0 {
|
||||
let factor = splits.cum_factor_after(&key, session_date);
|
||||
let raw_close = close * factor;
|
||||
let mismatch_roll = rng.next_u64() % 100;
|
||||
let daily_close = if mismatch_roll == 0 {
|
||||
raw_close * 1.05
|
||||
} else {
|
||||
let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0; // -0.20%..+0.20%
|
||||
raw_close * (1.0 + jitter_bp * 0.0001)
|
||||
};
|
||||
daily_closes.push(DailySessionClose {
|
||||
key,
|
||||
session_date,
|
||||
close: daily_close,
|
||||
});
|
||||
}
|
||||
b
|
||||
}
|
||||
};
|
||||
bars.push(bar);
|
||||
}
|
||||
|
||||
let daily_rows_in = daily_closes.len();
|
||||
|
||||
let build_start = Instant::now();
|
||||
let built = build_bars_1m(bars, &splits);
|
||||
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
|
||||
|
||||
let check_start = Instant::now();
|
||||
let checked = check_session_closes(&built.rows, daily_closes, 0.005)?;
|
||||
let check_elapsed_secs = check_start.elapsed().as_secs_f64();
|
||||
|
||||
let total_elapsed_secs = build_elapsed_secs + check_elapsed_secs;
|
||||
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
|
||||
let check_elapsed_ms = check_elapsed_secs * 1_000.0;
|
||||
let total_elapsed_ms = total_elapsed_secs * 1_000.0;
|
||||
|
||||
let mut hash = 0u64;
|
||||
for row in &built.rows {
|
||||
hash = mix_u64(hash, row.key as u64);
|
||||
hash = mix_u64(hash, row.ts as u64);
|
||||
hash = mix_u64(hash, row.session_date as u64);
|
||||
hash = mix_u64(hash, row.session as u64);
|
||||
hash = mix_u64(hash, row.open.to_bits());
|
||||
hash = mix_u64(hash, row.high.to_bits());
|
||||
hash = mix_u64(hash, row.low.to_bits());
|
||||
hash = mix_u64(hash, row.close.to_bits());
|
||||
hash = mix_u64(hash, row.volume.to_bits());
|
||||
}
|
||||
for sample in &checked.mismatch_samples {
|
||||
hash = mix_u64(hash, sample.key as u64);
|
||||
hash = mix_u64(hash, sample.session_date as u64);
|
||||
hash = mix_u64(hash, sample.last_rth_ts as u64);
|
||||
hash = mix_u64(hash, sample.close_1m.to_bits());
|
||||
hash = mix_u64(hash, sample.close_1d.to_bits());
|
||||
hash = mix_u64(hash, sample.rel.to_bits());
|
||||
}
|
||||
let checksum = black_box(hash);
|
||||
let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs);
|
||||
|
||||
Ok(Bars1mBenchReport {
|
||||
rows,
|
||||
key_count: BARS_1M_BENCH_KEY_COUNT,
|
||||
split_event_count,
|
||||
daily_rows_in,
|
||||
rows_out: built.stats.rows_out,
|
||||
keys_out: built.stats.keys_out,
|
||||
mismatch_samples_out: checked.mismatch_samples.len(),
|
||||
build_elapsed_ms,
|
||||
check_elapsed_ms,
|
||||
total_elapsed_ms,
|
||||
rows_per_sec,
|
||||
ns_per_row,
|
||||
checksum,
|
||||
build_stats: built.stats,
|
||||
close_stats: checked.stats,
|
||||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_fx_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct FxBenchReport {
|
||||
|
|
@ -12539,4 +12917,63 @@ mod tests {
|
|||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() {
|
||||
let a = run_bars_1m_benchmark(5_000).unwrap();
|
||||
let b = run_bars_1m_benchmark(5_000).unwrap();
|
||||
|
||||
assert_eq!(a.rows, 5_000);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.build_stats, b.build_stats);
|
||||
assert_eq!(a.close_stats, b.close_stats);
|
||||
assert!(a.rows_out > 0);
|
||||
assert!(a.build_stats.pre_rows_out > 0);
|
||||
assert!(a.build_stats.rth_rows_out > 0);
|
||||
assert!(a.build_stats.post_rows_out > 0);
|
||||
assert!(a.build_stats.dropped_invalid_ohlc > 0);
|
||||
assert!(a.build_stats.dropped_inconsistent_ohlc > 0);
|
||||
assert!(a.build_stats.dropped_invalid_volume > 0);
|
||||
assert!(a.build_stats.dropped_ts_out_of_range > 0);
|
||||
assert!(a.close_stats.checked > 0);
|
||||
|
||||
// Conservation invariants
|
||||
assert_eq!(
|
||||
a.build_stats.bars_in,
|
||||
a.build_stats.rows_out
|
||||
+ a.build_stats.dropped_invalid_ohlc
|
||||
+ a.build_stats.dropped_inconsistent_ohlc
|
||||
+ a.build_stats.dropped_invalid_volume
|
||||
+ a.build_stats.dropped_ts_out_of_range
|
||||
+ a.build_stats.duplicate_collapsed
|
||||
+ a.build_stats.duplicate_conflict_dropped
|
||||
);
|
||||
assert_eq!(
|
||||
a.build_stats.rows_out,
|
||||
a.build_stats.pre_rows_out + a.build_stats.rth_rows_out + a.build_stats.post_rows_out
|
||||
);
|
||||
assert_eq!(
|
||||
a.close_stats.checked + a.close_stats.unchecked,
|
||||
a.close_stats.rth_sessions
|
||||
);
|
||||
assert_eq!(
|
||||
a.close_stats.within_tolerance + a.close_stats.mismatched,
|
||||
a.close_stats.checked
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bars_1m_benchmark_zero_rows_handles_cleanly() {
|
||||
let report = run_bars_1m_benchmark(0).unwrap();
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.rows_out, 0);
|
||||
assert_eq!(report.keys_out, 0);
|
||||
assert_eq!(report.daily_rows_in, 0);
|
||||
assert_eq!(report.mismatch_samples_out, 0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.rows_per_sec, 0.0);
|
||||
assert_eq!(report.ns_per_row, 0.0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ use std::io;
|
|||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_1M_BENCH_ROWS, DEFAULT_BARS_BENCH_ROWS,
|
||||
DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS,
|
||||
|
|
@ -70,6 +71,7 @@ pub enum CliAction {
|
|||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
BenchBars(usize),
|
||||
BenchBars1m(usize),
|
||||
BenchFx(usize),
|
||||
BenchShorts(usize),
|
||||
BenchEvents(usize),
|
||||
|
|
@ -128,6 +130,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
|
||||
{name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-bars-1m [rows] Run fixed-seed bars_1m build + session-close cross-check benchmark (default: {DEFAULT_BARS_1M_BENCH_ROWS})\n\
|
||||
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
|
||||
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\
|
||||
|
|
@ -173,6 +176,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
{name} bench-bars [rows]\n\
|
||||
{name} bench-bars-1m [rows]\n\
|
||||
{name} bench-fx [rows]\n\
|
||||
{name} bench-shorts [rows]\n\
|
||||
{name} bench-events [rows]\n\
|
||||
|
|
@ -1462,6 +1466,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-bars", _, ..] => Err("too many arguments for bench-bars".to_string()),
|
||||
["bench-bars-1m"] => Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS)),
|
||||
["bench-bars-1m", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBars1m(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()),
|
||||
["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)),
|
||||
["bench-fx", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)),
|
||||
|
|
@ -2088,6 +2100,7 @@ mod tests {
|
|||
assert!(full.contains("bench-adj"));
|
||||
assert!(full.contains("bench-corporate-actions"));
|
||||
assert!(full.contains("bench-bars"));
|
||||
assert!(full.contains("bench-bars-1m"));
|
||||
assert!(full.contains("bench-fx"));
|
||||
assert!(full.contains("bench-shorts"));
|
||||
assert!(full.contains("bench-events"));
|
||||
|
|
@ -2119,6 +2132,7 @@ mod tests {
|
|||
assert!(short.contains("bench-adj"));
|
||||
assert!(short.contains("bench-corporate-actions"));
|
||||
assert!(short.contains("bench-bars"));
|
||||
assert!(short.contains("bench-bars-1m"));
|
||||
assert!(short.contains("bench-fx"));
|
||||
assert!(short.contains("bench-shorts"));
|
||||
assert!(short.contains("bench-events"));
|
||||
|
|
@ -2146,6 +2160,22 @@ mod tests {
|
|||
assert!(short.contains("bench-curate-corporate-actions-cmd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bars_1m_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bars-1m"])),
|
||||
Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bars-1m", "1000000"])),
|
||||
Ok(CliAction::BenchBars1m(1_000_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bars-1m", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bars-1m", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bars-1m", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bars-1m", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_bars_args() {
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
pub mod adj;
|
||||
pub mod bars;
|
||||
pub mod bars_1m;
|
||||
pub mod bench;
|
||||
pub mod bson_ceo_shorts;
|
||||
pub mod bson_eod_prices;
|
||||
|
|
@ -36,6 +37,12 @@ pub use bars::{
|
|||
build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume,
|
||||
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,
|
||||
};
|
||||
pub use bson_ceo_shorts::{
|
||||
decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc,
|
||||
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
|
||||
|
|
@ -141,9 +148,10 @@ pub use provider_mapping::{
|
|||
ProviderMappingTable,
|
||||
};
|
||||
pub use session_close::{
|
||||
et_session_close_utc_micros, SessionCloseError, SESSION_CLOSE_MAX_SUPPORTED_DATE,
|
||||
SESSION_CLOSE_MAX_SUPPORTED_YEAR, SESSION_CLOSE_MIN_SUPPORTED_DATE,
|
||||
SESSION_CLOSE_MIN_SUPPORTED_YEAR,
|
||||
et_session_close_utc_micros, utc_micros_to_et_local, EtLocalDateTime, SessionCloseError,
|
||||
SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_YEAR,
|
||||
SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_YEAR,
|
||||
SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS,
|
||||
};
|
||||
pub use shorts::{
|
||||
add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ use std::env;
|
|||
use std::process::ExitCode;
|
||||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_adj_benchmark, run_bars_1m_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark,
|
||||
|
|
@ -333,6 +333,51 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBars1m(rows)) => {
|
||||
let report = match run_bars_1m_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: bars_1m benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-bars-1m");
|
||||
println!(
|
||||
" input: rows={} daily_closes={} splits={} keys={}",
|
||||
report.rows, report.daily_rows_in, report.split_event_count, report.key_count
|
||||
);
|
||||
println!(
|
||||
" build: rows_out={} keys_out={} (pre={} rth={} post={}) build={:.2} ms check={:.2} ms total={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
report.keys_out,
|
||||
report.build_stats.pre_rows_out,
|
||||
report.build_stats.rth_rows_out,
|
||||
report.build_stats.post_rows_out,
|
||||
report.build_elapsed_ms,
|
||||
report.check_elapsed_ms,
|
||||
report.total_elapsed_ms,
|
||||
report.rows_per_sec,
|
||||
report.ns_per_row,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" stats: invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_oor={} dup_collapsed={} dup_conflict={} rth_sessions={} checked={} within_tol={} mismatched={} unchecked={} max_rel_diff={:.6} samples={}",
|
||||
report.build_stats.dropped_invalid_ohlc,
|
||||
report.build_stats.dropped_inconsistent_ohlc,
|
||||
report.build_stats.dropped_invalid_volume,
|
||||
report.build_stats.dropped_ts_out_of_range,
|
||||
report.build_stats.duplicate_collapsed,
|
||||
report.build_stats.duplicate_conflict_dropped,
|
||||
report.close_stats.rth_sessions,
|
||||
report.close_stats.checked,
|
||||
report.close_stats.within_tolerance,
|
||||
report.close_stats.mismatched,
|
||||
report.close_stats.unchecked,
|
||||
report.close_stats.max_rel_diff,
|
||||
report.mismatch_samples_out
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchFx(rows)) => {
|
||||
let report = run_fx_benchmark(rows);
|
||||
println!("curate-etl bench-fx");
|
||||
|
|
|
|||
|
|
@ -42,10 +42,37 @@ pub const SESSION_CLOSE_MIN_SUPPORTED_DATE: i32 = 2_191;
|
|||
/// Epoch day for `2030-12-31` (inclusive upper bound of [`et_session_close_utc_micros`]).
|
||||
pub const SESSION_CLOSE_MAX_SUPPORTED_DATE: i32 = 22_279;
|
||||
|
||||
const MICROS_PER_SECOND: i64 = 1_000_000;
|
||||
const MICROS_PER_MINUTE: i64 = 60 * MICROS_PER_SECOND;
|
||||
const MICROS_PER_HOUR: i64 = 3_600 * MICROS_PER_SECOND;
|
||||
const MICROS_PER_DAY: i64 = 86_400 * MICROS_PER_SECOND;
|
||||
|
||||
/// Inclusive lower bound in UTC microseconds for [`utc_micros_to_et_local`]
|
||||
/// (`1976-01-01T00:00:00.000000 EST` = `1976-01-01T05:00:00.000000Z`).
|
||||
pub const SESSION_MIN_SUPPORTED_UTC_MICROS: i64 =
|
||||
SESSION_CLOSE_MIN_SUPPORTED_DATE as i64 * MICROS_PER_DAY + 5 * MICROS_PER_HOUR;
|
||||
|
||||
/// Inclusive upper bound in UTC microseconds for [`utc_micros_to_et_local`]
|
||||
/// (`2030-12-31T23:59:59.999999 EST` = `2031-01-01T04:59:59.999999Z`).
|
||||
pub const SESSION_MAX_SUPPORTED_UTC_MICROS: i64 =
|
||||
(SESSION_CLOSE_MAX_SUPPORTED_DATE as i64 + 1) * MICROS_PER_DAY + 5 * MICROS_PER_HOUR - 1;
|
||||
|
||||
const SUPPORTED_YEAR_COUNT: usize =
|
||||
(SESSION_CLOSE_MAX_SUPPORTED_YEAR - SESSION_CLOSE_MIN_SUPPORTED_YEAR + 1) as usize;
|
||||
|
||||
/// Typed error returned by [`et_session_close_utc_micros`].
|
||||
/// Eastern Time (`America/New_York` / `America/Toronto`) calendar date, minute-of-day, and DST
|
||||
/// state returned by [`utc_micros_to_et_local`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct EtLocalDateTime {
|
||||
/// Local Eastern calendar date as days since `1970-01-01`.
|
||||
pub session_date: i32,
|
||||
/// Local Eastern minute of day (`0..=1439`, i.e., `hour * 60 + minute`).
|
||||
pub minute_of_day: u16,
|
||||
/// `true` during EDT (`UTC-4`), `false` during EST (`UTC-5`).
|
||||
pub is_edt: bool,
|
||||
}
|
||||
|
||||
/// Typed error returned by [`et_session_close_utc_micros`] and [`utc_micros_to_et_local`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SessionCloseError {
|
||||
/// The requested epoch day fell outside `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`.
|
||||
|
|
@ -54,6 +81,12 @@ pub enum SessionCloseError {
|
|||
min_supported: i32,
|
||||
max_supported: i32,
|
||||
},
|
||||
/// The requested UTC timestamp fell outside `[SESSION_MIN_SUPPORTED_UTC_MICROS, SESSION_MAX_SUPPORTED_UTC_MICROS]`.
|
||||
TimestampOutOfRange {
|
||||
utc_micros: i64,
|
||||
min_supported: i64,
|
||||
max_supported: i64,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for SessionCloseError {
|
||||
|
|
@ -67,6 +100,14 @@ impl fmt::Display for SessionCloseError {
|
|||
f,
|
||||
"epoch day {epoch_day} is outside supported session-close range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01..={SESSION_CLOSE_MAX_SUPPORTED_YEAR}-12-31)"
|
||||
),
|
||||
Self::TimestampOutOfRange {
|
||||
utc_micros,
|
||||
min_supported,
|
||||
max_supported,
|
||||
} => write!(
|
||||
f,
|
||||
"UTC timestamp {utc_micros} us is outside supported Eastern Time range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z)"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -152,6 +193,52 @@ pub fn et_session_close_utc_micros(epoch_day: i32) -> Result<i64, SessionCloseEr
|
|||
Ok((i64::from(epoch_day) * 86_400 + utc_hour_secs) * 1_000_000)
|
||||
}
|
||||
|
||||
/// Converts a UTC timestamp (microseconds since the Unix epoch) into North American Eastern Time
|
||||
/// (`America/New_York` / `America/Toronto`) calendar date, minute-of-day (`0..=1439`), and DST
|
||||
/// state.
|
||||
///
|
||||
/// Reuses the crate's `1976..=2030` DST table across all three historical eras (`1976–1986`,
|
||||
/// `1987–2006`, `2007–2030`) with exact `02:00 EST` (`07:00 UTC`) spring-forward and `02:00 EDT`
|
||||
/// (`06:00 UTC`) fall-back transitions. Returns [`SessionCloseError::TimestampOutOfRange`] for any
|
||||
/// timestamp outside `[SESSION_MIN_SUPPORTED_UTC_MICROS, SESSION_MAX_SUPPORTED_UTC_MICROS]`.
|
||||
#[inline]
|
||||
pub fn utc_micros_to_et_local(utc_micros: i64) -> Result<EtLocalDateTime, SessionCloseError> {
|
||||
if !(SESSION_MIN_SUPPORTED_UTC_MICROS..=SESSION_MAX_SUPPORTED_UTC_MICROS).contains(&utc_micros) {
|
||||
return Err(SessionCloseError::TimestampOutOfRange {
|
||||
utc_micros,
|
||||
min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS,
|
||||
max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS,
|
||||
});
|
||||
}
|
||||
|
||||
// Bounds check above guarantees `est_micros >= 2191 * MICROS_PER_DAY > 0` without overflow.
|
||||
let est_micros = utc_micros - 5 * MICROS_PER_HOUR;
|
||||
let est_day = (est_micros / MICROS_PER_DAY) as i32;
|
||||
let (year, _, _) = epoch_days_to_ymd(est_day);
|
||||
let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize];
|
||||
|
||||
// Spring forward: 02:00:00 EST = 07:00:00 UTC on `dst_start`.
|
||||
// Fall back: 02:00:00 EDT = 06:00:00 UTC on `dst_end`.
|
||||
let dst_start_utc = i64::from(dst_start) * MICROS_PER_DAY + 7 * MICROS_PER_HOUR;
|
||||
let dst_end_utc = i64::from(dst_end) * MICROS_PER_DAY + 6 * MICROS_PER_HOUR;
|
||||
let is_edt = utc_micros >= dst_start_utc && utc_micros < dst_end_utc;
|
||||
|
||||
let local_micros = if is_edt {
|
||||
est_micros + MICROS_PER_HOUR
|
||||
} else {
|
||||
est_micros
|
||||
};
|
||||
let session_date = (local_micros / MICROS_PER_DAY) as i32;
|
||||
let rem_micros = local_micros - i64::from(session_date) * MICROS_PER_DAY;
|
||||
let minute_of_day = (rem_micros / MICROS_PER_MINUTE) as u16;
|
||||
|
||||
Ok(EtLocalDateTime {
|
||||
session_date,
|
||||
minute_of_day,
|
||||
is_edt,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -307,4 +394,207 @@ mod tests {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn utc_micros(y: i32, m: u32, d: u32, h: i64, min: i64, sec: i64, us: i64) -> i64 {
|
||||
let ep = day(y, m, d);
|
||||
((i64::from(ep) * 86_400 + h * 3_600 + min * 60 + sec) * 1_000_000) + us
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utc_micros_to_et_local_round_trips_et_session_close_across_all_supported_days() {
|
||||
for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE {
|
||||
let close_utc = et_session_close_utc_micros(d).expect("in-range date");
|
||||
let local = utc_micros_to_et_local(close_utc).expect("in-range timestamp");
|
||||
assert_eq!(local.session_date, d, "session_date mismatch on day={d}");
|
||||
assert_eq!(
|
||||
local.minute_of_day,
|
||||
16 * 60,
|
||||
"16:00 ET minute mismatch on day={d}"
|
||||
);
|
||||
let expected_edt =
|
||||
(close_utc - i64::from(d) * MICROS_PER_DAY) == 20 * MICROS_PER_HOUR;
|
||||
assert_eq!(local.is_edt, expected_edt, "DST flag mismatch on day={d}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utc_micros_to_et_local_handles_dst_transitions_across_all_three_eras() {
|
||||
// (year, spring_month, spring_day, fall_month, fall_day)
|
||||
let eras = [
|
||||
// Era 1 (1976..=1986): last Sun Apr -> last Sun Oct
|
||||
(1976, 4, 25, 10, 31),
|
||||
(1986, 4, 27, 10, 26),
|
||||
// Era 2 (1987..=2006): 1st Sun Apr -> last Sun Oct (including 2003)
|
||||
(1987, 4, 5, 10, 25),
|
||||
(2003, 4, 6, 10, 26),
|
||||
(2006, 4, 2, 10, 29),
|
||||
// Era 3 (2007..=2030): 2nd Sun Mar -> 1st Sun Nov
|
||||
(2007, 3, 11, 11, 4),
|
||||
(2024, 3, 10, 11, 3),
|
||||
(2030, 3, 10, 11, 3),
|
||||
];
|
||||
|
||||
for (y, sm, sd, fm, fd) in eras {
|
||||
let spring_day = day(y, sm, sd);
|
||||
// 06:59:59.999999 UTC -> 01:59:59.999999 EST
|
||||
let before_spring = utc_micros(y, sm, sd, 6, 59, 59, 999_999);
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(before_spring).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: spring_day,
|
||||
minute_of_day: 60 + 59,
|
||||
is_edt: false,
|
||||
},
|
||||
"before spring-forward in {y}"
|
||||
);
|
||||
// 07:00:00.000000 UTC -> 03:00:00.000000 EDT (skips 02:xx)
|
||||
let at_spring = utc_micros(y, sm, sd, 7, 0, 0, 0);
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(at_spring).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: spring_day,
|
||||
minute_of_day: 3 * 60,
|
||||
is_edt: true,
|
||||
},
|
||||
"at spring-forward in {y}"
|
||||
);
|
||||
|
||||
let fall_day = day(y, fm, fd);
|
||||
// 05:59:59.999999 UTC -> 01:59:59.999999 EDT (first 01:59)
|
||||
let before_fall = utc_micros(y, fm, fd, 5, 59, 59, 999_999);
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(before_fall).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: fall_day,
|
||||
minute_of_day: 60 + 59,
|
||||
is_edt: true,
|
||||
},
|
||||
"before fall-back in {y}"
|
||||
);
|
||||
// 06:00:00.000000 UTC -> 01:00:00.000000 EST (repeated 01:00)
|
||||
let at_fall = utc_micros(y, fm, fd, 6, 0, 0, 0);
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(at_fall).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: fall_day,
|
||||
minute_of_day: 60,
|
||||
is_edt: false,
|
||||
},
|
||||
"at fall-back in {y}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utc_micros_to_et_local_handles_utc_vs_et_midnight_crossovers() {
|
||||
// Summer (EDT, UTC-4): 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (previous calendar day)
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(utc_micros(2024, 6, 10, 0, 30, 0, 0)).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: day(2024, 6, 9),
|
||||
minute_of_day: 20 * 60 + 30,
|
||||
is_edt: true,
|
||||
}
|
||||
);
|
||||
// 2024-06-10 03:59:59.999999 UTC == 2024-06-09 23:59 EDT
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(utc_micros(2024, 6, 10, 3, 59, 59, 999_999)).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: day(2024, 6, 9),
|
||||
minute_of_day: 23 * 60 + 59,
|
||||
is_edt: true,
|
||||
}
|
||||
);
|
||||
// 2024-06-10 04:00:00.000000 UTC == 2024-06-10 00:00 EDT
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(utc_micros(2024, 6, 10, 4, 0, 0, 0)).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: day(2024, 6, 10),
|
||||
minute_of_day: 0,
|
||||
is_edt: true,
|
||||
}
|
||||
);
|
||||
|
||||
// Winter (EST, UTC-5): 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(utc_micros(2025, 1, 16, 0, 30, 0, 0)).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: day(2025, 1, 15),
|
||||
minute_of_day: 19 * 60 + 30,
|
||||
is_edt: false,
|
||||
}
|
||||
);
|
||||
// 2025-01-16 04:59:59.999999 UTC == 2025-01-15 23:59 EST
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(utc_micros(2025, 1, 16, 4, 59, 59, 999_999)).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: day(2025, 1, 15),
|
||||
minute_of_day: 23 * 60 + 59,
|
||||
is_edt: false,
|
||||
}
|
||||
);
|
||||
// 2025-01-16 05:00:00.000000 UTC == 2025-01-16 00:00 EST
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(utc_micros(2025, 1, 16, 5, 0, 0, 0)).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: day(2025, 1, 16),
|
||||
minute_of_day: 0,
|
||||
is_edt: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utc_micros_to_et_local_bounds_and_out_of_range_errors() {
|
||||
// Exact inclusive bounds
|
||||
assert_eq!(
|
||||
SESSION_MIN_SUPPORTED_UTC_MICROS,
|
||||
utc_micros(1976, 1, 1, 5, 0, 0, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
SESSION_MAX_SUPPORTED_UTC_MICROS,
|
||||
utc_micros(2031, 1, 1, 4, 59, 59, 999_999)
|
||||
);
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(SESSION_MIN_SUPPORTED_UTC_MICROS).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: SESSION_CLOSE_MIN_SUPPORTED_DATE,
|
||||
minute_of_day: 0,
|
||||
is_edt: false,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
utc_micros_to_et_local(SESSION_MAX_SUPPORTED_UTC_MICROS).unwrap(),
|
||||
EtLocalDateTime {
|
||||
session_date: SESSION_CLOSE_MAX_SUPPORTED_DATE,
|
||||
minute_of_day: 23 * 60 + 59,
|
||||
is_edt: false,
|
||||
}
|
||||
);
|
||||
|
||||
let bad_ts = [
|
||||
SESSION_MIN_SUPPORTED_UTC_MICROS - 1,
|
||||
SESSION_MAX_SUPPORTED_UTC_MICROS + 1,
|
||||
0,
|
||||
i64::MIN,
|
||||
i64::MAX,
|
||||
];
|
||||
for ts in bad_ts {
|
||||
let err = utc_micros_to_et_local(ts).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
SessionCloseError::TimestampOutOfRange {
|
||||
utc_micros: ts,
|
||||
min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS,
|
||||
max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS,
|
||||
}
|
||||
);
|
||||
assert!(err.source().is_none());
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
msg.contains(&ts.to_string()) && msg.contains("1976-01-01T05:00:00Z"),
|
||||
"unexpected Display message: {msg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -204,7 +204,10 @@ fn pre_1976_divergent_emergency_dst_years_and_post_2030_are_out_of_range() {
|
|||
epoch_day,
|
||||
min_supported,
|
||||
max_supported,
|
||||
} = err;
|
||||
} = err
|
||||
else {
|
||||
panic!("expected SessionCloseError::DateOutOfRange, got {err:?}");
|
||||
};
|
||||
assert_eq!(epoch_day, d);
|
||||
assert_eq!(min_supported, SESSION_CLOSE_MIN_SUPPORTED_DATE);
|
||||
assert_eq!(max_supported, SESSION_CLOSE_MAX_SUPPORTED_DATE);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue