stock-bot/tools/curate-etl/tests/bars_1m_qa_contract.rs
2026-11-30 23:51:10 -05:00

584 lines
19 KiB
Rust

//! QA contract tests for `bars_1m::build_bars_1m` / `check_session_closes` (T-130 / M2.3a).
//!
//! Uses only the public crate API. Expected Eastern session dates and minutes come from how the
//! fixtures are generated (`et_to_utc_micros(date, hh, mm)`), not from `utc_micros_to_et_local`,
//! and expected split factors come from `SplitTable::cum_factor_after`, so the builder's
//! two-pointer split cursor and ET conversion are checked against independent oracles.
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use curate_etl::{
build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, et_to_utc_micros,
unadjust_ohlcv, ymd_to_epoch_days, Bar1dRow, Bar1mRow, Bars1mStats, DailySessionClose,
EodIntradayBar, IntradaySession, OhlcvBar, SessionCloseCutoffPolicy, SessionCloseStats,
SplitEvent, SplitTable, BARS_1M_SOURCE_EOD, MAX_MISMATCH_SAMPLES,
};
/// Deterministic SplitMix64 so every run sees identical fixtures.
struct Rng(u64);
impl Rng {
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, n: u64) -> u64 {
self.next_u64() % n
}
}
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn et(date: i32, hour: u8, minute: u8) -> i64 {
et_to_utc_micros(date, hour, minute, 0).expect("valid ET timestamp")
}
fn bar(key: &str, ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64) -> EodIntradayBar {
EodIntradayBar {
key: key.to_string(),
ts,
open: o,
high: h,
low: l,
close: c,
volume: v,
}
}
fn flat(key: &str, ts: i64, price: f64, volume: f64) -> EodIntradayBar {
bar(key, ts, price, price, price, price, volume)
}
fn expected_session(minute_of_day: u16) -> IntradaySession {
if minute_of_day < 570 {
IntradaySession::Pre
} else if minute_of_day < 960 {
IntradaySession::Rth
} else {
IntradaySession::Post
}
}
fn assert_conservation(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,
"conservation invariant failed: {stats:?}"
);
assert_eq!(
stats.rows_out,
stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out
);
}
fn assert_close_invariants(stats: &SessionCloseStats) {
assert_eq!(
stats.checked + stats.unchecked,
stats.rth_sessions,
"{stats:?}"
);
assert_eq!(
stats.within_tolerance + stats.mismatched,
stats.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,
"{stats:?}"
);
}
fn assert_strictly_sorted<K: Ord + std::fmt::Debug>(rows: &[Bar1mRow<K>]) {
for w in 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,
"rows not strictly sorted: {:?} / {:?}",
w[0],
w[1]
);
}
}
#[test]
fn seeded_clean_bars_match_independent_et_and_cum_factor_oracle_bitwise() {
// Arrange: 40 keys, 0-3 splits each (forward/reverse, some on weekends), bars spread across
// 2023-2025 at arbitrary ET minutes (including 00:00 and 23:59) so EST, EDT and DST-transition
// days are all exercised.
let mut rng = Rng(0x0B45_1A11_7E57_0001);
let ratios = [0.05, 0.1, 0.25, 0.5, 2.0, 3.0, 4.0, 10.0, 1.5];
let min_date = day(2023, 1, 1);
let span = (day(2025, 12, 31) - min_date + 1) as u64;
let mut events = Vec::new();
for k in 0..40 {
for _ in 0..rng.below(4) {
events.push((
format!("K{k:02}"),
SplitEvent {
ex_date: min_date + rng.below(span) as i32,
ratio: ratios[rng.below(ratios.len() as u64) as usize],
},
));
}
}
let splits = SplitTable::from_events(events).expect("valid splits");
let mut inputs = Vec::new();
let mut expected: HashMap<(String, i64), (i32, u16, EodIntradayBar)> = HashMap::new();
while inputs.len() < 5_000 {
let key = format!("K{:02}", rng.below(40));
let date = min_date + rng.below(span) as i32;
let minute = rng.below(1_440) as u16;
let (hh, mm) = ((minute / 60) as u8, (minute % 60) as u8);
// Skip wall-clock times that do not exist on spring-forward day.
let Ok(ts) = et_to_utc_micros(date, hh, mm, 0) else {
continue;
};
if expected.contains_key(&(key.clone(), ts)) {
continue;
}
let low = 1.0 + rng.below(10_000) as f64 / 100.0;
let high = low * (1.0 + rng.below(500) as f64 / 10_000.0);
let open = low + (high - low) * 0.25;
let close = low + (high - low) * 0.75;
let volume = rng.below(1_000_000) as f64;
let b = bar(&key, ts, open, high, low, close, volume);
// Fall-back day repeats 01:xx; keep only the first occurrence's ET minute oracle.
expected.insert((key, ts), (date, minute, b.clone()));
inputs.push(b);
}
// Act
let built = build_bars_1m(inputs.clone(), &splits);
// Assert
assert_conservation(&built.stats);
assert_eq!(built.stats.rows_out, inputs.len());
assert_strictly_sorted(&built.rows);
let mut applied_non_unit = 0usize;
for row in &built.rows {
let (date, minute, ref input) = expected[&(row.key.clone(), row.ts)];
assert_eq!(row.session_date, date, "ET session_date for {row:?}");
assert_eq!(row.session, expected_session(minute), "session for {row:?}");
assert_eq!(row.source, BARS_1M_SOURCE_EOD);
let factor = splits.cum_factor_after(row.key.as_str(), date);
if factor != 1.0 {
applied_non_unit += 1;
}
let want = unadjust_ohlcv(
OhlcvBar {
open: input.open,
high: input.high,
low: input.low,
close: input.close,
volume: input.volume,
},
factor,
);
assert_eq!(row.open.to_bits(), want.open.to_bits(), "{row:?}");
assert_eq!(row.high.to_bits(), want.high.to_bits(), "{row:?}");
assert_eq!(row.low.to_bits(), want.low.to_bits(), "{row:?}");
assert_eq!(row.close.to_bits(), want.close.to_bits(), "{row:?}");
assert_eq!(row.volume.to_bits(), want.volume.to_bits(), "{row:?}");
}
assert!(
applied_non_unit > 500,
"fixture must exercise splits: {applied_non_unit}"
);
}
#[test]
fn et_midnight_is_the_split_boundary_not_utc_midnight_in_est_and_edt() {
// Arrange: 2:1 splits; ex-dates in EDT (2024-06-10) and EST (2025-01-16).
for ex in [day(2024, 6, 10), day(2025, 1, 16)] {
let splits = SplitTable::from_events([(
"S".to_string(),
SplitEvent {
ex_date: ex,
ratio: 2.0,
},
)])
.unwrap();
let last_pre_minute = et(ex - 1, 23, 59);
let first_ex_minute = et(ex, 0, 0);
// Act
let built = build_bars_1m(
[
flat("S", first_ex_minute, 10.0, 100.0),
flat("S", last_pre_minute, 10.0, 100.0),
],
&splits,
);
// Assert: 23:59 ET (already the next UTC day) still gets the pre-split factor.
assert_conservation(&built.stats);
assert_eq!(built.rows.len(), 2);
assert_eq!(built.rows[0].session_date, ex - 1);
assert_eq!(built.rows[0].session, IntradaySession::Post);
assert_eq!(built.rows[0].close, 20.0);
assert_eq!(built.rows[0].volume, 50.0);
assert_eq!(built.rows[1].session_date, ex);
assert_eq!(built.rows[1].session, IntradaySession::Pre);
assert_eq!(built.rows[1].close.to_bits(), 10.0_f64.to_bits());
assert_eq!(built.rows[1].volume.to_bits(), 100.0_f64.to_bits());
}
}
#[test]
fn cumulative_factor_spans_multiple_splits_and_weekend_ex_dates() {
// Arrange: 2:1 ex Saturday 2024-03-02, then 1:4 reverse ex Monday 2024-03-11.
let splits = SplitTable::from_events([
(
"M".to_string(),
SplitEvent {
ex_date: day(2024, 3, 2),
ratio: 2.0,
},
),
(
"M".to_string(),
SplitEvent {
ex_date: day(2024, 3, 11),
ratio: 0.25,
},
),
])
.unwrap();
// Act
let built = build_bars_1m(
[
flat("M", et(day(2024, 3, 1), 15, 59), 8.0, 1_000.0), // Fri: both splits ahead
flat("M", et(day(2024, 3, 4), 15, 59), 8.0, 1_000.0), // Mon: only reverse ahead
flat("M", et(day(2024, 3, 11), 15, 59), 8.0, 1_000.0), // ex-date of reverse
],
&splits,
);
// Assert: factor 2*0.25 = 0.5, then 0.25, then 1.
assert_conservation(&built.stats);
let closes: Vec<f64> = built.rows.iter().map(|r| r.close).collect();
let volumes: Vec<f64> = built.rows.iter().map(|r| r.volume).collect();
assert_eq!(closes, vec![4.0, 2.0, 8.0]);
assert_eq!(volumes, vec![2_000.0, 4_000.0, 1_000.0]);
}
#[test]
fn rth_boundaries_hold_on_dst_transition_sundays() {
// Arrange: spring-forward 2024-03-10 and fall-back 2024-11-03 (EDT->EST).
let splits: SplitTable<String> = SplitTable::default();
let mut inputs = Vec::new();
for d in [day(2024, 3, 10), day(2024, 11, 3)] {
for (h, m) in [(9, 29), (9, 30), (15, 59), (16, 0)] {
inputs.push(flat("D", et(d, h, m), 10.0, 1.0));
}
}
// Act
let built = build_bars_1m(inputs, &splits);
// Assert
let sessions: Vec<&str> = built.rows.iter().map(|r| r.session.as_str()).collect();
assert_eq!(
sessions,
vec!["PRE", "RTH", "RTH", "POST", "PRE", "RTH", "RTH", "POST"]
);
}
#[test]
fn seeded_dirty_input_conserves_counts_and_is_permutation_invariant() {
// Arrange: mix of valid bars, every bad-row category, exact and conflicting duplicates.
let mut rng = Rng(0x0B45_1A11_D127_0002);
let splits = SplitTable::from_events([
(
"A".to_string(),
SplitEvent {
ex_date: day(2024, 6, 10),
ratio: 10.0,
},
),
(
"B".to_string(),
SplitEvent {
ex_date: day(2024, 6, 12),
ratio: 0.05,
},
),
])
.unwrap();
let keys = ["A", "B", "C"];
let base = et(day(2024, 6, 7), 4, 0);
let mut inputs = Vec::new();
for _ in 0..3_000 {
let key = keys[rng.below(3) as usize];
let ts = base + rng.below(8 * 1_440) as i64 * 60_000_000;
let p = 10.0 + rng.below(100) as f64 / 10.0;
let b = match rng.below(12) {
0 => bar(key, ts, f64::NAN, p, p, p, 1.0),
1 => bar(key, ts, p, p, p, -p, 1.0),
2 => bar(key, ts, p, p - 1.0, p, p, 1.0),
3 => bar(key, ts, p, p, p, p, f64::NEG_INFINITY),
4 => bar(key, i64::MAX - rng.below(10) as i64, p, p, p, p, 1.0),
5 => bar(key, ts, p, p, p, p, -0.0),
_ => bar(key, ts, p, p + 0.5, p - 0.5, p, rng.below(1_000) as f64),
};
inputs.push(b.clone());
// ~10% exact duplicates, ~5% conflicting duplicates.
match rng.below(20) {
0 | 1 => inputs.push(b),
2 => {
let mut c = b;
c.volume += 1.0;
inputs.push(c);
}
_ => {}
}
}
// Act
let forward = build_bars_1m(inputs.clone(), &splits);
let mut shuffled = inputs.clone();
for i in (1..shuffled.len()).rev() {
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
}
let permuted = build_bars_1m(shuffled, &splits);
// Assert
assert_conservation(&forward.stats);
assert_eq!(forward, permuted, "output must not depend on input order");
assert_strictly_sorted(&forward.rows);
for counter in [
forward.stats.dropped_invalid_ohlc,
forward.stats.dropped_inconsistent_ohlc,
forward.stats.dropped_invalid_volume,
forward.stats.dropped_ts_out_of_range,
forward.stats.duplicate_collapsed,
forward.stats.duplicate_conflict_dropped,
] {
assert!(
counter > 0,
"every category must be exercised: {:?}",
forward.stats
);
}
let unique: HashSet<(String, i64)> =
forward.rows.iter().map(|r| (r.key.clone(), r.ts)).collect();
assert_eq!(unique.len(), forward.rows.len());
assert!(forward
.rows
.iter()
.all(|r| r.volume.to_bits() != (-0.0_f64).to_bits()));
}
#[test]
fn keys_out_ignores_keys_whose_every_bar_is_dropped() {
let splits: SplitTable<String> = SplitTable::default();
let ts = et(day(2024, 6, 10), 10, 0);
let built = build_bars_1m(
[
flat("GONE", ts, 10.0, 1.0),
flat("GONE", ts, 10.5, 1.0), // conflict drops the whole group
flat("NAN", ts, f64::NAN, 1.0),
flat("KEEP", ts, 10.0, 1.0),
],
&splits,
);
assert_conservation(&built.stats);
assert_eq!(built.stats.keys_out, 1);
assert_eq!(built.rows.len(), 1);
assert_eq!(built.rows[0].key, "KEEP");
}
#[test]
fn session_close_tolerance_is_inclusive_and_zero_tolerance_is_accepted() {
let d = day(2024, 6, 10);
let splits: SplitTable<String> = SplitTable::default();
let built = build_bars_1m([flat("T", et(d, 15, 59), 100.5, 1.0)], &splits);
let daily = [DailySessionClose::new("T".to_string(), d, 100.0)];
// rel == 0.5 / 100 == 0.005 exactly -> within tolerance.
let at_edge = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap();
assert_close_invariants(&at_edge.stats);
assert_eq!(at_edge.stats.within_tolerance, 1);
assert_eq!(at_edge.stats.mismatched, 0);
let zero = check_session_closes(&built.rows, daily.clone(), 0.0).unwrap();
assert_eq!(zero.stats.mismatched, 1);
let neg_zero = check_session_closes(&built.rows, daily, -0.0).unwrap();
assert_eq!(neg_zero.stats.mismatched, 1);
}
#[test]
fn daily_partner_without_intraday_rows_and_post_only_sessions_are_not_rth_sessions() {
let d1 = day(2024, 6, 10);
let d2 = day(2024, 6, 11);
let splits: SplitTable<String> = SplitTable::default();
let built = build_bars_1m(
[
flat("X", et(d1, 15, 59), 50.0, 1.0),
flat("X", et(d2, 16, 30), 99.0, 1.0), // POST only
],
&splits,
);
let rows_1d = [
Bar1dRow {
key: "X".to_string(),
session_date: d1,
open: 50.0,
high: 50.0,
low: 50.0,
close: 50.0,
volume: 1.0,
},
Bar1dRow {
key: "X".to_string(),
session_date: d2,
open: 50.0,
high: 50.0,
low: 50.0,
close: 50.0,
volume: 1.0,
},
Bar1dRow {
key: "Y".to_string(),
session_date: d1,
open: 7.0,
high: 7.0,
low: 7.0,
close: 7.0,
volume: 1.0,
},
];
let check = check_session_closes_against_bars_1d(
&built.rows,
&rows_1d,
&SessionCloseCutoffPolicy::standard_rth(),
0.005,
)
.unwrap();
assert_close_invariants(&check.stats);
assert_eq!(check.stats.rth_sessions, 1);
assert_eq!(check.stats.checked, 1);
assert_eq!(check.stats.within_tolerance, 1);
assert_eq!(check.stats.daily_unique_partners, 3);
}
#[test]
fn early_close_date_cutoff_applies_to_listings_without_override() {
// Arrange: Friday after US Thanksgiving 2024 (13:00 ET close); policy sets only a date cutoff.
let d = day(2024, 11, 29);
let splits: SplitTable<String> = SplitTable::default();
let built = build_bars_1m(
[
flat("U", et(d, 12, 59), 40.0, 1.0),
flat("U", et(d, 13, 15), 44.0, 1.0),
flat("V", et(d, 12, 59), 70.0, 1.0),
flat("V", et(d, 15, 59), 77.0, 1.0),
],
&splits,
);
let policy = SessionCloseCutoffPolicy::standard_rth().with_date_cutoff(d, et(d, 13, 0));
let rows_1d = [
Bar1dRow {
key: "U".to_string(),
session_date: d,
open: 40.0,
high: 40.0,
low: 40.0,
close: 40.0,
volume: 1.0,
},
Bar1dRow {
key: "V".to_string(),
session_date: d,
open: 70.0,
high: 70.0,
low: 70.0,
close: 70.0,
volume: 1.0,
},
];
// Act
let check = check_session_closes_against_bars_1d(&built.rows, rows_1d, &policy, 0.005).unwrap();
// Assert: both listings resolve to their 12:59 ET bar.
assert_close_invariants(&check.stats);
assert_eq!(check.stats.checked, 2);
assert_eq!(check.stats.mismatched, 0);
assert_eq!(check.stats.max_rel_diff, 0.0);
}
#[test]
fn split_fixture_cross_check_is_order_independent_and_samples_are_capped() {
// Arrange: 150 sessions on one 1:20 reverse-split key; feed adjusted (empty split table) and
// un-adjusted builds against the same raw daily closes.
let ex = day(2025, 6, 18);
let splits = SplitTable::from_events([(
"NEXM.V".to_string(),
SplitEvent {
ex_date: ex,
ratio: 0.05,
},
)])
.unwrap();
let empty: SplitTable<String> = SplitTable::default();
let mut bars = Vec::new();
let mut daily = Vec::new();
for i in 0..150 {
let d = ex - 150 + i;
let adj_close = 20.0 + f64::from(i) * 0.01;
bars.push(flat("NEXM.V", et(d, 15, 59), adj_close, 1_000.0));
bars.push(flat("NEXM.V", et(d, 16, 5), adj_close * 1.1, 10.0)); // POST noise
daily.push(DailySessionClose::new(
"NEXM.V".to_string(),
d,
adj_close * 0.05,
));
}
// Act
let unadj = build_bars_1m(bars.clone(), &splits);
let still_adj = build_bars_1m(bars, &empty);
let good = check_session_closes(&unadj.rows, daily.clone(), 0.005).unwrap();
let bad = check_session_closes(&still_adj.rows, daily.clone(), 0.005).unwrap();
let mut reversed = still_adj.rows.clone();
reversed.reverse();
let bad_reversed = check_session_closes(&reversed, daily, 0.005).unwrap();
// Assert
assert_close_invariants(&good.stats);
assert_eq!(good.stats.checked, 150);
assert_eq!(good.stats.mismatched, 0);
assert!(good.stats.max_rel_diff < 1e-12);
assert_close_invariants(&bad.stats);
assert_eq!(bad.stats.mismatched, 150);
assert!(bad.stats.max_rel_diff > 0.005);
assert_eq!(bad.mismatch_samples.len(), MAX_MISMATCH_SAMPLES);
assert_eq!(bad, bad_reversed);
for s in &bad.mismatch_samples {
assert!((s.rel - 19.0).abs() < 1e-9, "rel {s:?}");
assert_eq!(s.last_rth_ts, et(s.session_date, 15, 59));
}
}