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

658 lines
24 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Pure, in-memory `fx_1d` USD/CAD builder (`CAD.FOREX` + `teMarketData.USDCAD`).
//!
//! Produces sorted, unique per-`session_date` USD/CAD rows (CAD per 1 USD) matching the
//! `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (excluding `ts`/`known_at`
//! timestamps, which belong to the later writer task).
//!
//! Rules:
//! - Both input streams are USD/CAD quotes (CAD per 1 USD); no inversion is performed here.
//! - Bad single rows never panic or abort the build; each source is filtered in strict priority
//! order (`dropped_invalid_ohlc`, then `dropped_inconsistent_ohlc`) and deduplicated on
//! `session_date` (bitwise-identical duplicates collapse; conflicting duplicate groups drop
//! entirely).
//! - Merge precedence: `EodCadForex` wins on overlapping dates (counting `te_superseded_by_eod`),
//! while `TeUsdCad` fills interior gaps and dates after EOD's last date.
//! - Overlap cross-check is strictly read-only: on every date where both sources survive, checks
//! `|eod.close - te.close| / eod.close <= FX_OVERLAP_REL_TOLERANCE` (1%) and tracks
//! `max_overlap_rel` without modifying emitted rows.
//! - [`fx_rate_on_or_before`] provides no-look-ahead binary-search lookup with bounded staleness.
use std::cmp::Ordering;
use std::fmt;
/// Canonical currency pair label emitted on every [`Fx1dRow`].
pub const FX_PAIR_USDCAD: &str = "USDCAD";
/// Relative close-price tolerance (1%) for the read-only EOD vs. TE overlap cross-check.
pub const FX_OVERLAP_REL_TOLERANCE: f64 = 0.01;
/// IEEE-754 rounding slack for the inclusive [`FX_OVERLAP_REL_TOLERANCE`] boundary so decimal
/// USD/CAD quotes that are mathematically exactly 1% apart (e.g. `1.4000` vs. `1.4140`, where
/// `(1.4140 - 1.4000) / 1.4000 = 0.010000000000000009`) are not falsely flagged as mismatches.
const FX_OVERLAP_REL_ROUNDING_EPS: f64 = 4.0 * f64::EPSILON;
/// Provenance source for a curated `fx_1d` USD/CAD row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FxSource {
/// EODHD `CAD.FOREX` daily history (1971–2025).
EodCadForex,
/// TradingEconomics `teMarketData.USDCAD` daily history (fills gaps and tail through 2026+).
TeUsdCad,
}
impl FxSource {
/// Canonical lowercase snake_case label written to the `source` column.
#[inline]
pub const fn as_str(self) -> &'static str {
match self {
Self::EodCadForex => "eod_cad_forex",
Self::TeUsdCad => "te_usdcad",
}
}
}
impl fmt::Display for FxSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// A single raw daily USD/CAD FX bar (CAD per 1 USD).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FxDailyBar {
/// Session date as days since `1970-01-01` (UTC Gregorian, matching [`crate::ymd_to_epoch_days`]).
pub session_date: i32,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
}
/// A single curated `fx_1d` row, sorted and unique by `session_date`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Fx1dRow {
pub pair: &'static str,
pub session_date: i32,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub source: FxSource,
}
/// Per-source filtering and deduplication counters.
///
/// Conservation invariant:
/// `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FxSourceStats {
pub rows_in: usize,
pub rows_kept: usize,
pub dropped_invalid_ohlc: usize,
pub dropped_inconsistent_ohlc: usize,
pub duplicate_collapsed: usize,
pub duplicate_conflict_dropped: usize,
}
/// Summary counters and read-only overlap audit metrics produced alongside [`Fx1dBuild::rows`].
///
/// Conservation invariants:
/// - Per source (`eod`, `te`):
/// `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped`
/// - Output merge:
/// `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod`
/// and `rows_out == eod_rows_out + te_rows_out`
/// - Overlap cross-check:
/// `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod`
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Fx1dStats {
pub eod: FxSourceStats,
pub te: FxSourceStats,
pub rows_out: usize,
pub eod_rows_out: usize,
pub te_rows_out: usize,
pub te_superseded_by_eod: usize,
pub overlap_checked: usize,
pub overlap_within_tolerance: usize,
pub overlap_mismatched: usize,
pub max_overlap_rel: f64,
}
/// Output of [`build_fx_1d`]: sorted, unique USD/CAD rows and exact accounting/overlap stats.
#[derive(Debug, Clone, PartialEq)]
pub struct Fx1dBuild {
pub rows: Vec<Fx1dRow>,
pub stats: Fx1dStats,
}
#[inline]
fn is_valid_rate(rate: f64) -> bool {
rate.is_finite() && rate > 0.0
}
#[inline]
fn bar_values_bit_eq(a: &FxDailyBar, b: &FxDailyBar) -> 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()
}
/// Filters, sorts, and deduplicates one FX source in strict priority order:
/// 1. Drop invalid OHLC (any field non-finite or `<= 0.0`).
/// 2. Drop inconsistent OHLC (`high < low`, or `open`/`close` outside `[low, high]`).
/// 3. Sort by `session_date` and compact in-place: bitwise-identical duplicates collapse to one;
/// conflicting duplicate groups drop entirely.
fn clean_source(input: &[FxDailyBar]) -> (Vec<FxDailyBar>, FxSourceStats) {
let mut stats = FxSourceStats {
rows_in: input.len(),
..FxSourceStats::default()
};
let mut valid = Vec::with_capacity(input.len());
for &bar in input {
if !is_valid_rate(bar.open)
|| !is_valid_rate(bar.high)
|| !is_valid_rate(bar.low)
|| !is_valid_rate(bar.close)
{
stats.dropped_invalid_ohlc += 1;
continue;
}
if bar.high < bar.low
|| bar.open < bar.low
|| bar.open > bar.high
|| bar.close < bar.low
|| bar.close > bar.high
{
stats.dropped_inconsistent_ohlc += 1;
continue;
}
valid.push(bar);
}
valid.sort_unstable_by_key(|b| b.session_date);
let len = valid.len();
let mut write_idx = 0usize;
let mut read_idx = 0usize;
while read_idx < len {
let session_date = valid[read_idx].session_date;
let mut group_end = read_idx + 1;
while group_end < len && valid[group_end].session_date == session_date {
group_end += 1;
}
let group_len = group_end - read_idx;
let first = valid[read_idx];
let all_identical = valid[read_idx + 1..group_end]
.iter()
.all(|other| bar_values_bit_eq(&first, other));
if all_identical {
stats.duplicate_collapsed += group_len - 1;
if write_idx != read_idx {
valid[write_idx] = first;
}
write_idx += 1;
} else {
stats.duplicate_conflict_dropped += group_len;
}
read_idx = group_end;
}
valid.truncate(write_idx);
stats.rows_kept = valid.len();
(valid, stats)
}
#[inline]
fn to_fx_row(bar: FxDailyBar, source: FxSource) -> Fx1dRow {
Fx1dRow {
pair: FX_PAIR_USDCAD,
session_date: bar.session_date,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
source,
}
}
/// Builds a sorted, unique `fx_1d` USD/CAD series by merging `CAD.FOREX` (`eod`) and
/// `teMarketData.USDCAD` (`te`).
///
/// - Never panics or aborts on single-row data errors.
/// - `EodCadForex` takes precedence on overlapping dates; `TeUsdCad` fills interior gaps and
/// dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting
/// group).
/// - On every overlapping date where both sources survive, performs a read-only relative close
/// cross-check against [`FX_OVERLAP_REL_TOLERANCE`] (1%) without mutating emitted rows.
/// - Any permutation of `eod` or `te` yields bitwise-identical `rows` and `stats`.
pub fn build_fx_1d(eod: &[FxDailyBar], te: &[FxDailyBar]) -> Fx1dBuild {
let (eod_clean, eod_stats) = clean_source(eod);
let (te_clean, te_stats) = clean_source(te);
let mut stats = Fx1dStats {
eod: eod_stats,
te: te_stats,
..Fx1dStats::default()
};
let mut rows = Vec::with_capacity(eod_clean.len() + te_clean.len());
let mut i = 0usize;
let mut j = 0usize;
while i < eod_clean.len() && j < te_clean.len() {
let e = eod_clean[i];
let t = te_clean[j];
match e.session_date.cmp(&t.session_date) {
Ordering::Less => {
rows.push(to_fx_row(e, FxSource::EodCadForex));
stats.eod_rows_out += 1;
i += 1;
}
Ordering::Greater => {
rows.push(to_fx_row(t, FxSource::TeUsdCad));
stats.te_rows_out += 1;
j += 1;
}
Ordering::Equal => {
rows.push(to_fx_row(e, FxSource::EodCadForex));
stats.eod_rows_out += 1;
stats.te_superseded_by_eod += 1;
stats.overlap_checked += 1;
let rel = (e.close - t.close).abs() / e.close;
if rel > stats.max_overlap_rel {
stats.max_overlap_rel = rel;
}
if rel <= FX_OVERLAP_REL_TOLERANCE + FX_OVERLAP_REL_ROUNDING_EPS {
stats.overlap_within_tolerance += 1;
} else {
stats.overlap_mismatched += 1;
}
i += 1;
j += 1;
}
}
}
while i < eod_clean.len() {
rows.push(to_fx_row(eod_clean[i], FxSource::EodCadForex));
stats.eod_rows_out += 1;
i += 1;
}
while j < te_clean.len() {
rows.push(to_fx_row(te_clean[j], FxSource::TeUsdCad));
stats.te_rows_out += 1;
j += 1;
}
stats.rows_out = rows.len();
Fx1dBuild { rows, stats }
}
/// Binary-search lookup of the latest [`Fx1dRow`] in `rows` (assumed sorted ascending by
/// `session_date`, as returned by [`build_fx_1d`]) with `session_date <= date` and
/// `date - session_date <= max_stale_days`.
///
/// Carries forward across weekends and holidays up to `max_stale_days`, never looks ahead to a
/// later date, and returns `None` if `rows` is empty, `date` precedes the first row, or the
/// latest prior row is older than `max_stale_days`.
#[inline]
pub fn fx_rate_on_or_before(
rows: &[Fx1dRow],
date: i32,
max_stale_days: u32,
) -> Option<&Fx1dRow> {
let idx = rows.partition_point(|r| r.session_date <= date);
if idx == 0 {
return None;
}
let candidate = &rows[idx - 1];
let age = i64::from(date) - i64::from(candidate.session_date);
if age <= i64::from(max_stale_days) {
Some(candidate)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::split::ymd_to_epoch_days;
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).unwrap()
}
fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar {
FxDailyBar {
session_date,
open,
high,
low,
close,
}
}
fn flat(session_date: i32, rate: f64) -> FxDailyBar {
bar(session_date, rate, rate, rate, rate)
}
fn assert_invariants(build: &Fx1dBuild) {
let s = &build.stats;
assert_eq!(
s.eod.rows_in,
s.eod.rows_kept
+ s.eod.dropped_invalid_ohlc
+ s.eod.dropped_inconsistent_ohlc
+ s.eod.duplicate_collapsed
+ s.eod.duplicate_conflict_dropped,
"eod accounting invariant failed: {s:?}"
);
assert_eq!(
s.te.rows_in,
s.te.rows_kept
+ s.te.dropped_invalid_ohlc
+ s.te.dropped_inconsistent_ohlc
+ s.te.duplicate_collapsed
+ s.te.duplicate_conflict_dropped,
"te accounting invariant failed: {s:?}"
);
assert_eq!(
s.rows_out,
s.eod.rows_kept + s.te.rows_kept - s.te_superseded_by_eod,
"merge accounting invariant failed: {s:?}"
);
assert_eq!(
s.rows_out,
s.eod_rows_out + s.te_rows_out,
"source split accounting invariant failed: {s:?}"
);
assert_eq!(s.rows_out, build.rows.len());
assert_eq!(
s.overlap_within_tolerance + s.overlap_mismatched,
s.overlap_checked,
"overlap tolerance accounting invariant failed: {s:?}"
);
assert_eq!(
s.overlap_checked, s.te_superseded_by_eod,
"overlap_checked != te_superseded_by_eod: {s:?}"
);
for pair in build.rows.windows(2) {
assert!(
pair[0].session_date < pair[1].session_date,
"rows not strictly ascending: {} >= {}",
pair[0].session_date,
pair[1].session_date
);
}
for row in &build.rows {
assert_eq!(row.pair, FX_PAIR_USDCAD);
}
}
#[test]
fn empty_inputs_return_empty_rows_and_zeroed_stats() {
let built = build_fx_1d(&[], &[]);
assert!(built.rows.is_empty());
assert_eq!(built.stats, Fx1dStats::default());
assert_invariants(&built);
}
#[test]
fn source_strings_and_display_match_contract() {
assert_eq!(FxSource::EodCadForex.as_str(), "eod_cad_forex");
assert_eq!(FxSource::TeUsdCad.as_str(), "te_usdcad");
assert_eq!(format!("{}", FxSource::EodCadForex), "eod_cad_forex");
assert_eq!(format!("{}", FxSource::TeUsdCad), "te_usdcad");
}
#[test]
fn eod_wins_on_overlap_and_te_fills_interior_gaps_and_tail() {
let d1 = day(2025, 1, 2);
let d2 = day(2025, 1, 3);
let d3 = day(2025, 1, 6);
let d4 = day(2026, 1, 2);
let eod = [
bar(d1, 1.430, 1.440, 1.425, 1.435),
// d2 missing in EOD -> TE should fill
bar(d3, 1.436, 1.442, 1.430, 1.438),
];
let te = [
bar(d1, 1.431, 1.441, 1.426, 1.436), // overlaps d1 -> EOD wins
bar(d2, 1.434, 1.439, 1.431, 1.437), // interior gap -> TE fills
bar(d4, 1.380, 1.390, 1.375, 1.385), // post-EOD tail -> TE fills
];
let built = build_fx_1d(&eod, &te);
assert_invariants(&built);
assert_eq!(built.rows.len(), 4);
assert_eq!(built.stats.eod_rows_out, 2);
assert_eq!(built.stats.te_rows_out, 2);
assert_eq!(built.stats.te_superseded_by_eod, 1);
assert_eq!(built.stats.overlap_checked, 1);
assert_eq!(built.stats.overlap_within_tolerance, 1);
assert_eq!(built.stats.overlap_mismatched, 0);
// d1: bitwise-preserved EOD OHLC
assert_eq!(built.rows[0].session_date, d1);
assert_eq!(built.rows[0].source, FxSource::EodCadForex);
assert_eq!(built.rows[0].open.to_bits(), eod[0].open.to_bits());
assert_eq!(built.rows[0].high.to_bits(), eod[0].high.to_bits());
assert_eq!(built.rows[0].low.to_bits(), eod[0].low.to_bits());
assert_eq!(built.rows[0].close.to_bits(), eod[0].close.to_bits());
// d2: TE interior gap fill
assert_eq!(built.rows[1].session_date, d2);
assert_eq!(built.rows[1].source, FxSource::TeUsdCad);
assert_eq!(built.rows[1].close.to_bits(), te[1].close.to_bits());
// d3: EOD only
assert_eq!(built.rows[2].session_date, d3);
assert_eq!(built.rows[2].source, FxSource::EodCadForex);
// d4: TE tail fill
assert_eq!(built.rows[3].session_date, d4);
assert_eq!(built.rows[3].source, FxSource::TeUsdCad);
}
#[test]
fn filters_bad_rows_in_strict_priority_order_without_panicking() {
let base = day(2024, 5, 1);
let eod = [
// Invalid OHLC (also inconsistent to prove strict priority)
bar(base, f64::NAN, 1.0, 2.0, 1.5),
bar(base + 1, 1.3, f64::INFINITY, 1.2, 1.25),
bar(base + 2, 1.3, 1.4, f64::NEG_INFINITY, 1.25),
bar(base + 3, 1.3, 1.4, 1.2, 0.0),
bar(base + 4, -0.0, 1.4, 1.2, 1.3),
bar(base + 5, 1.3, 1.4, 1.2, -1.2),
// Inconsistent OHLC
bar(base + 6, 1.3, 1.2, 1.4, 1.3), // high < low
bar(base + 7, 1.1, 1.4, 1.2, 1.3), // open < low
bar(base + 8, 1.5, 1.4, 1.2, 1.3), // open > high
bar(base + 9, 1.3, 1.4, 1.2, 1.1), // close < low
bar(base + 10, 1.3, 1.4, 1.2, 1.5), // close > high
// Valid row
bar(base + 11, 1.35, 1.38, 1.34, 1.36),
];
let built = build_fx_1d(&eod, &[]);
assert_invariants(&built);
assert_eq!(built.stats.eod.rows_in, 12);
assert_eq!(built.stats.eod.dropped_invalid_ohlc, 6);
assert_eq!(built.stats.eod.dropped_inconsistent_ohlc, 5);
assert_eq!(built.stats.eod.rows_kept, 1);
assert_eq!(built.rows.len(), 1);
assert_eq!(built.rows[0].session_date, base + 11);
}
#[test]
fn dedup_collapses_identical_drops_conflicting_and_allows_te_fallback() {
let d1 = day(2024, 6, 1);
let d2 = day(2024, 6, 2);
let d3 = day(2024, 6, 3);
let eod = [
// Identical triple -> collapses to 1
flat(d1, 1.35),
flat(d1, 1.35),
flat(d1, 1.35),
// Conflicting duplicate group in EOD -> dropped entirely; TE on d2 fills it
flat(d2, 1.36),
flat(d2, 1.37),
// Valid + invalid on same date -> invalid filtered early, valid survives
flat(d3, 1.38),
bar(d3, f64::NAN, 1.39, 1.37, 1.38),
];
let te = [
flat(d2, 1.365),
// Conflicting duplicate in TE on d1 -> dropped before merge, no overlap counted
flat(d1, 1.35),
flat(d1, 1.355),
];
let built = build_fx_1d(&eod, &te);
assert_invariants(&built);
assert_eq!(built.stats.eod.duplicate_collapsed, 2);
assert_eq!(built.stats.eod.duplicate_conflict_dropped, 2);
assert_eq!(built.stats.eod.dropped_invalid_ohlc, 1);
assert_eq!(built.stats.eod.rows_kept, 2);
assert_eq!(built.stats.te.duplicate_conflict_dropped, 2);
assert_eq!(built.stats.te.rows_kept, 1);
assert_eq!(built.stats.overlap_checked, 0);
assert_eq!(built.rows.len(), 3);
assert_eq!(built.rows[0].source, FxSource::EodCadForex);
assert_eq!(built.rows[1].session_date, d2);
assert_eq!(built.rows[1].source, FxSource::TeUsdCad);
assert_eq!(built.rows[1].close.to_bits(), 1.365_f64.to_bits());
assert_eq!(built.rows[2].source, FxSource::EodCadForex);
}
#[test]
fn overlap_crosscheck_exact_one_percent_boundary_and_read_only() {
let base = day(2024, 7, 1);
// Use exact integers so relative difference at 1% has zero binary rounding error.
let eod = [
flat(base, 100.0), // te = 101.0 -> rel = 0.01 (within)
flat(base + 1, 100.0), // te = 99.0 -> rel = 0.01 (within)
flat(base + 2, 100.0), // te = 101.01 -> rel = 0.0101 (mismatched)
flat(base + 3, 100.0), // te = 150.0 -> rel = 0.50 (mismatched, never mutates EOD)
];
let te = [
flat(base, 101.0),
flat(base + 1, 99.0),
flat(base + 2, 101.01),
flat(base + 3, 150.0),
];
let built = build_fx_1d(&eod, &te);
assert_invariants(&built);
assert_eq!(built.stats.overlap_checked, 4);
assert_eq!(built.stats.overlap_within_tolerance, 2);
assert_eq!(built.stats.overlap_mismatched, 2);
assert_eq!(built.stats.max_overlap_rel, 0.5);
for (row, orig) in built.rows.iter().zip(&eod) {
assert_eq!(row.source, FxSource::EodCadForex);
assert_eq!(row.close.to_bits(), orig.close.to_bits());
}
}
#[test]
fn overlap_crosscheck_decimal_usdcad_one_percent_boundary_is_rounding_aware() {
let base = day(2025, 4, 1);
// Decimal USD/CAD pairs at exact ±1% (including 1.4000 vs 1.4140 where raw f64 division
// produces 0.010000000000000009) and just outside ±1%.
let eod = [
flat(base, 1.4000), // te = 1.4140 (+1.0000%, within)
flat(base + 1, 1.4000), // te = 1.3860 (-1.0000%, within)
flat(base + 2, 1.3500), // te = 1.3635 (+1.0000%, within)
flat(base + 3, 1.3500), // te = 1.3365 (-1.0000%, within)
flat(base + 4, 1.3700), // te = 1.3837 (+1.0000%, within)
flat(base + 5, 1.3700), // te = 1.3563 (-1.0000%, within)
flat(base + 6, 1.4000), // te = 1.4141 (+1.0071%, mismatched)
flat(base + 7, 1.4000), // te = 1.3859 (-1.0071%, mismatched)
flat(base + 8, 1.4000), // te = 1.4140001 (+1.000007%, mismatched)
];
let te = [
flat(base, 1.4140),
flat(base + 1, 1.3860),
flat(base + 2, 1.3635),
flat(base + 3, 1.3365),
flat(base + 4, 1.3837),
flat(base + 5, 1.3563),
flat(base + 6, 1.4141),
flat(base + 7, 1.3859),
flat(base + 8, 1.4140001),
];
let built = build_fx_1d(&eod, &te);
assert_invariants(&built);
assert_eq!(built.stats.overlap_checked, 9);
assert_eq!(built.stats.overlap_within_tolerance, 6);
assert_eq!(built.stats.overlap_mismatched, 3);
// max_overlap_rel retains the raw calculated relative difference.
let expected_max = (1.4000_f64 - 1.4141_f64).abs() / 1.4000_f64;
assert_eq!(built.stats.max_overlap_rel.to_bits(), expected_max.to_bits());
// Exact 1.4000 vs 1.4140 alone still records its calculated rel in max_overlap_rel.
let single = build_fx_1d(&[flat(base, 1.4000)], &[flat(base, 1.4140)]);
assert_invariants(&single);
assert_eq!(single.stats.overlap_within_tolerance, 1);
assert_eq!(single.stats.overlap_mismatched, 0);
assert_eq!(
single.stats.max_overlap_rel.to_bits(),
((1.4000_f64 - 1.4140_f64).abs() / 1.4000_f64).to_bits()
);
}
#[test]
fn lookup_on_or_before_covers_exact_carry_forward_stale_and_no_lookahead() {
let fri = day(2025, 1, 3);
let sat = day(2025, 1, 4);
let sun = day(2025, 1, 5);
let mon = day(2025, 1, 6);
let next_mon = day(2025, 1, 13);
// Empty slice -> None
assert_eq!(fx_rate_on_or_before(&[], fri, 5), None);
let built = build_fx_1d(&[flat(fri, 1.44), flat(next_mon, 1.45)], &[]);
let rows = &built.rows;
// Before first row -> None (never looks ahead to Friday)
assert_eq!(fx_rate_on_or_before(rows, fri - 1, 30), None);
// Exact hit works even with max_stale_days == 0
assert_eq!(fx_rate_on_or_before(rows, fri, 0), Some(&rows[0]));
assert_eq!(fx_rate_on_or_before(rows, next_mon, 0), Some(&rows[1]));
// Weekend carry-forward
assert_eq!(fx_rate_on_or_before(rows, sat, 2), Some(&rows[0]));
assert_eq!(fx_rate_on_or_before(rows, sun, 2), Some(&rows[0]));
// Monday is 3 days after Friday: None when max_stale_days == 2, Some when == 3
assert_eq!(fx_rate_on_or_before(rows, mon, 2), None);
assert_eq!(fx_rate_on_or_before(rows, mon, 3), Some(&rows[0]));
// Stale gap between two rows returns None, never looks ahead to next_mon
assert_eq!(fx_rate_on_or_before(rows, next_mon - 1, 3), None);
// Pre-1970 negative dates and extreme i32 boundaries do not overflow
let pre = build_fx_1d(&[flat(i32::MIN, 1.05)], &[]);
assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MIN, 0), Some(&pre.rows[0]));
assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MAX, 10), None);
assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MIN + 5, 5), Some(&pre.rows[0]));
assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MIN + 6, 5), None);
}
}