T-75: M1.2e — tools/curate-etl: pure fx_1d builder (merge CAD.FOREX daily + teMarketData.USDCAD into one USD/CAD series) with local benchmark (no new crates)
This commit is contained in:
parent
acbcb0ab7a
commit
a494defef5
8 changed files with 1541 additions and 7 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, and the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check.
|
||||
Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, and the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -74,6 +74,26 @@ Rules:
|
|||
- `volume_checked + volume_unchecked == rows_out` and `volume_within_tolerance + volume_mismatched == volume_checked`
|
||||
- `qm_rows_in == qm_unique_partners + qm_invalid_volume_dropped + qm_duplicate_collapsed + qm_duplicate_conflict_dropped`
|
||||
|
||||
## `fx_1d` Builder (`M1.2e`)
|
||||
|
||||
`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) 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:
|
||||
1. **Quote convention:** Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (`CADUSD.FOREX` inversion is out of scope).
|
||||
2. **Per-source filtering (strict priority, never panics or aborts):**
|
||||
- `dropped_invalid_ohlc`: any OHLC field non-finite or `<= 0.0`.
|
||||
- `dropped_inconsistent_ohlc`: `high < low`, or `open`/`close` outside `[low, high]`.
|
||||
3. **Per-source deduplication on `session_date`:** Bitwise-identical duplicates collapse to one (`duplicate_collapsed += n - 1`); conflicting duplicate groups drop entirely (`duplicate_conflict_dropped += n`).
|
||||
4. **Merge precedence:** `EodCadForex` wins on overlapping dates (`te_superseded_by_eod += 1`); `TeUsdCad` fills interior gaps and all dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting group).
|
||||
5. **Read-only overlap cross-check:** On every date where both sources survive, evaluates `|eod.close - te.close| / eod.close <= FX_OVERLAP_REL_TOLERANCE` (`0.01`, 1% inclusive), counts `overlap_checked`, `overlap_within_tolerance`, and `overlap_mismatched`, and tracks `max_overlap_rel` without modifying emitted rows.
|
||||
6. **No-look-ahead lookup (`fx_rate_on_or_before`):** Binary-searches sorted `Fx1dRow` slices for the latest row with `session_date <= date` and `date - session_date <= max_stale_days`. Carries forward across weekends/holidays within `max_stale_days`, returns `None` before the first row or when stale, and never returns a later date.
|
||||
7. **Determinism & accounting invariants:** Any permutation of `eod` or `te` yields bitwise-identical `rows` and `stats`, and:
|
||||
- Per source: `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped`
|
||||
- Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out`
|
||||
- Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod`
|
||||
|
||||
Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation (later writer task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends.
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
### `bench-split`
|
||||
|
|
@ -131,11 +151,27 @@ Command: `cargo run --release -p curate-etl --offline -- bench-bars`
|
|||
- Build: `rows_out=9488072`, `keys_out=20000`, `elapsed=842.38 ms`, `throughput=11871057 rows/s`, `latency=84.24 ns/row`, `checksum=0x25fae7ad0816891b` (identical across back-to-back runs)
|
||||
- Stats: `invalid_ohlc=20006`, `inconsistent_ohlc=19818`, `invalid_vol=19812`, `dup_collapsed=47627`, `dup_conflict=404665`, `checked=4721305`, `within_tol=4673885`, `mismatched=47420`, `unchecked=4766767`, `max_rel_diff=0.130435`, `samples=100`
|
||||
|
||||
## Deferred Follow-Ups (`M1.2e+` / `M2`)
|
||||
### `bench-fx`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over ~20,000 daily USD/CAD rows (~80% `CAD.FOREX`, ~20% `teMarketData.USDCAD` with an overlap window, interior gaps, post-EOD tail, injected bad/duplicate rows, and ~5% overlap mismatches), timing `build_fx_1d` plus `1,000,000` zero-allocation `fx_rate_on_or_before` lookups:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-fx [rows]
|
||||
```
|
||||
|
||||
Command: `cargo run --release -p curate-etl --offline -- bench-fx`
|
||||
|
||||
- Input: `rows=20000`, `eod_rows=16000`, `te_rows=4000`
|
||||
- Build: `rows_out=17172`, `eod_out=15336`, `te_out=1836`, `elapsed=0.745 ms`, `throughput=26834724 rows/s`, `latency=37.27 ns/row`
|
||||
- Lookup: `lookups=1000000`, `hits=999266`, `elapsed=26.76 ms`, `throughput=37370069 lookups/s`, `latency=26.76 ns/lookup`, `checksum=0xf41e7ae8ca6a26aa` (identical across back-to-back runs)
|
||||
- Stats: `eod_invalid=164`, `eod_inconsistent=170`, `eod_dup_collapsed=165`, `eod_dup_conflict=165`, `te_invalid=21`, `te_inconsistent=23`, `te_dup_collapsed=21`, `te_dup_conflict=34`, `te_superseded=2065`, `overlap_checked=2065`, `within_tol=1954`, `mismatched=111`, `max_overlap_rel=0.025000`
|
||||
|
||||
## Deferred Follow-Ups (`M1.2f+` / `M2`)
|
||||
|
||||
This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add:
|
||||
|
||||
- `bars_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
|
||||
- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
|
||||
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
|
||||
- `year=YYYY` partitioning, Zstd-compressed Parquet writer for curated daily/intraday datasets, and `qmPrices` OHLC cross-check
|
||||
- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`)
|
||||
- PostgreSQL `provider_mapping` preload keyed by `listing_id: i32` (supported via generic `SplitTable<K>`)
|
||||
|
|
|
|||
|
|
@ -9,12 +9,15 @@ use crate::corporate_actions::{
|
|||
build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent,
|
||||
DividendActionEvent, SplitActionEvent,
|
||||
};
|
||||
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar};
|
||||
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable};
|
||||
|
||||
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_FX_BENCH_ROWS: usize = 20_000;
|
||||
pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
|
||||
pub const BENCH_KEY_COUNT: usize = 20_000;
|
||||
pub const BENCH_EVENT_COUNT: usize = 19_000;
|
||||
|
||||
|
|
@ -22,6 +25,7 @@ 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 FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
|
||||
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
|
||||
|
||||
/// Deterministic SplitMix64 generator (zero external dependencies).
|
||||
|
|
@ -594,6 +598,337 @@ pub fn run_bars_benchmark(rows: usize) -> Result<BarsBenchReport, BarsError> {
|
|||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_fx_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct FxBenchReport {
|
||||
pub rows: usize,
|
||||
pub eod_rows_in: usize,
|
||||
pub te_rows_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub build_elapsed_ms: f64,
|
||||
pub build_rows_per_sec: f64,
|
||||
pub build_ns_per_row: f64,
|
||||
pub lookups: usize,
|
||||
pub lookup_hits: usize,
|
||||
pub lookup_elapsed_ms: f64,
|
||||
pub lookups_per_sec: f64,
|
||||
pub ns_per_lookup: f64,
|
||||
pub checksum: u64,
|
||||
pub stats: Fx1dStats,
|
||||
}
|
||||
|
||||
fn shuffle_slice<T>(items: &mut [T], rng: &mut SplitMix64) {
|
||||
for i in (1..items.len()).rev() {
|
||||
let j = (rng.next_u64() % (i as u64 + 1)) as usize;
|
||||
items.swap(i, j);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed `build_fx_1d` + [`fx_rate_on_or_before`] benchmark for `rows` total daily
|
||||
/// FX rows across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%).
|
||||
///
|
||||
/// Generates deterministic USD/CAD bars with an overlap window, interior EOD gaps, a post-EOD TE
|
||||
/// tail, small shares of invalid/inconsistent/identical-duplicate/conflicting-duplicate rows, and
|
||||
/// ~5% intentional overlap mismatches. Shuffles both inputs deterministically, times
|
||||
/// [`build_fx_1d`], then times [`DEFAULT_FX_BENCH_LOOKUPS`] (`1_000_000`, or `0` when `rows == 0`)
|
||||
/// zero-allocation [`fx_rate_on_or_before`] lookups.
|
||||
pub fn run_fx_benchmark(rows: usize) -> FxBenchReport {
|
||||
if rows == 0 {
|
||||
let built = build_fx_1d(&[], &[]);
|
||||
return FxBenchReport {
|
||||
rows: 0,
|
||||
eod_rows_in: 0,
|
||||
te_rows_in: 0,
|
||||
rows_out: 0,
|
||||
build_elapsed_ms: 0.0,
|
||||
build_rows_per_sec: 0.0,
|
||||
build_ns_per_row: 0.0,
|
||||
lookups: 0,
|
||||
lookup_hits: 0,
|
||||
lookup_elapsed_ms: 0.0,
|
||||
lookups_per_sec: 0.0,
|
||||
ns_per_lookup: 0.0,
|
||||
checksum: 0,
|
||||
stats: built.stats,
|
||||
};
|
||||
}
|
||||
|
||||
let base_date = ymd_to_epoch_days(1971, 1, 4).unwrap_or(368);
|
||||
let mut rng = SplitMix64::new(FX_BENCH_SEED);
|
||||
|
||||
let te_target = rows / 5;
|
||||
let eod_target = rows - te_target;
|
||||
|
||||
let mut eod: Vec<FxDailyBar> = Vec::with_capacity(eod_target);
|
||||
let mut eod_valid_history: Vec<FxDailyBar> = Vec::with_capacity(eod_target);
|
||||
let mut interior_gap_dates: Vec<i32> = Vec::new();
|
||||
let mut cur_date = base_date;
|
||||
let mut rate = 1.01_f64;
|
||||
|
||||
for _ in 0..eod_target {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 10 {
|
||||
if let Some(&prev) = eod_valid_history.last() {
|
||||
eod.push(prev);
|
||||
continue;
|
||||
}
|
||||
} else if roll < 15 {
|
||||
if let Some(&prev) = eod_valid_history.last() {
|
||||
let mut conflicting = prev;
|
||||
conflicting.close = (conflicting.close + 0.002).min(conflicting.high);
|
||||
if conflicting.close.to_bits() == prev.close.to_bits() {
|
||||
conflicting.high += 0.002;
|
||||
conflicting.close += 0.001;
|
||||
}
|
||||
eod.push(conflicting);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Advance calendar date, skipping weekends and occasional interior gaps.
|
||||
cur_date += 1;
|
||||
let dow = cur_date.rem_euclid(7); // 1970-01-01 was Thursday (0=Thu, 2=Sat, 3=Sun)
|
||||
if dow == 2 {
|
||||
cur_date += 2;
|
||||
} else if dow == 3 {
|
||||
cur_date += 1;
|
||||
}
|
||||
if rng.next_u64() % 20 == 0 {
|
||||
interior_gap_dates.push(cur_date);
|
||||
cur_date += 1;
|
||||
}
|
||||
|
||||
let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0001;
|
||||
rate = (rate + step).clamp(0.92, 1.60);
|
||||
let half_spread = ((rng.next_u64() % 80) + 10) as f64 * 0.0001;
|
||||
let low = (rate - half_spread).max(0.50);
|
||||
let high = rate + half_spread;
|
||||
let open = low + (high - low) * ((rng.next_u64() % 100) as f64 * 0.01);
|
||||
let close = rate;
|
||||
|
||||
let bar = match roll {
|
||||
15..=24 => FxDailyBar {
|
||||
session_date: cur_date,
|
||||
open: -1.0,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
},
|
||||
25..=34 => FxDailyBar {
|
||||
session_date: cur_date,
|
||||
open,
|
||||
high: low - 0.01,
|
||||
low,
|
||||
close,
|
||||
},
|
||||
_ => {
|
||||
let b = FxDailyBar {
|
||||
session_date: cur_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
};
|
||||
eod_valid_history.push(b);
|
||||
b
|
||||
}
|
||||
};
|
||||
eod.push(bar);
|
||||
}
|
||||
|
||||
let last_eod_date = cur_date;
|
||||
let mut te: Vec<FxDailyBar> = Vec::with_capacity(te_target);
|
||||
let mut te_last_valid: Option<FxDailyBar> = None;
|
||||
|
||||
// ~60% of TE rows overlap EOD's recent window + interior gaps; ~40% extend past EOD's tail.
|
||||
let te_overlap_target = (te_target * 3) / 5;
|
||||
let te_tail_target = te_target - te_overlap_target;
|
||||
let overlap_start = eod_valid_history.len().saturating_sub(te_overlap_target);
|
||||
|
||||
for idx in 0..te_overlap_target {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 10 {
|
||||
if let Some(prev) = te_last_valid {
|
||||
te.push(prev);
|
||||
continue;
|
||||
}
|
||||
} else if roll < 15 {
|
||||
if let Some(mut prev) = te_last_valid {
|
||||
prev.close = (prev.close + 0.002).min(prev.high);
|
||||
if prev.close.to_bits() == te_last_valid.map_or(0, |b| b.close.to_bits()) {
|
||||
prev.high += 0.002;
|
||||
prev.close += 0.001;
|
||||
}
|
||||
te.push(prev);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Fill some interior EOD gaps, otherwise overlap EOD dates.
|
||||
let (session_date, base_bar) = if idx % 10 == 0 && !interior_gap_dates.is_empty() {
|
||||
let gap_date = interior_gap_dates[(idx / 10) % interior_gap_dates.len()];
|
||||
let ref_bar = eod_valid_history
|
||||
.get(overlap_start + idx)
|
||||
.copied()
|
||||
.unwrap_or(FxDailyBar {
|
||||
session_date: gap_date,
|
||||
open: 1.35,
|
||||
high: 1.36,
|
||||
low: 1.34,
|
||||
close: 1.35,
|
||||
});
|
||||
(gap_date, ref_bar)
|
||||
} else if let Some(&ref_bar) = eod_valid_history.get(overlap_start + idx) {
|
||||
(ref_bar.session_date, ref_bar)
|
||||
} else {
|
||||
(
|
||||
last_eod_date + 1 + idx as i32,
|
||||
FxDailyBar {
|
||||
session_date: last_eod_date + 1 + idx as i32,
|
||||
open: 1.35,
|
||||
high: 1.36,
|
||||
low: 1.34,
|
||||
close: 1.35,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
// ~5% intentional overlap mismatches (+2.5%), ~95% within 1% (±0.30%).
|
||||
let factor = if rng.next_u64() % 20 == 0 {
|
||||
1.025
|
||||
} else {
|
||||
let jitter_bp = (rng.next_u64() % 61) as f64 - 30.0;
|
||||
1.0 + jitter_bp * 0.0001
|
||||
};
|
||||
let open = base_bar.open * factor;
|
||||
let high = base_bar.high * factor;
|
||||
let low = base_bar.low * factor;
|
||||
let close = base_bar.close * factor;
|
||||
|
||||
let bar = match roll {
|
||||
15..=24 => FxDailyBar {
|
||||
session_date,
|
||||
open: f64::NAN,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
},
|
||||
25..=34 => FxDailyBar {
|
||||
session_date,
|
||||
open,
|
||||
high: low - 0.01,
|
||||
low,
|
||||
close,
|
||||
},
|
||||
_ => {
|
||||
let b = FxDailyBar {
|
||||
session_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
};
|
||||
te_last_valid = Some(b);
|
||||
b
|
||||
}
|
||||
};
|
||||
te.push(bar);
|
||||
}
|
||||
|
||||
let mut tail_date = last_eod_date;
|
||||
let mut tail_rate = rate;
|
||||
for _ in 0..te_tail_target {
|
||||
tail_date += 1;
|
||||
let dow = tail_date.rem_euclid(7);
|
||||
if dow == 2 {
|
||||
tail_date += 2;
|
||||
} else if dow == 3 {
|
||||
tail_date += 1;
|
||||
}
|
||||
let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0001;
|
||||
tail_rate = (tail_rate + step).clamp(0.92, 1.60);
|
||||
let half_spread = ((rng.next_u64() % 80) + 10) as f64 * 0.0001;
|
||||
let low = (tail_rate - half_spread).max(0.50);
|
||||
let high = tail_rate + half_spread;
|
||||
let open = low + (high - low) * ((rng.next_u64() % 100) as f64 * 0.01);
|
||||
te.push(FxDailyBar {
|
||||
session_date: tail_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close: tail_rate,
|
||||
});
|
||||
}
|
||||
|
||||
shuffle_slice(&mut eod, &mut rng);
|
||||
shuffle_slice(&mut te, &mut rng);
|
||||
|
||||
let eod_rows_in = eod.len();
|
||||
let te_rows_in = te.len();
|
||||
|
||||
let build_start = Instant::now();
|
||||
let built = build_fx_1d(&eod, &te);
|
||||
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
|
||||
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
|
||||
let (build_rows_per_sec, build_ns_per_row) = compute_rates(rows, build_elapsed_secs);
|
||||
|
||||
let mut rows_hash = 0u64;
|
||||
for row in &built.rows {
|
||||
rows_hash = mix_u64(rows_hash, row.session_date as u64);
|
||||
rows_hash = mix_u64(rows_hash, row.open.to_bits());
|
||||
rows_hash = mix_u64(rows_hash, row.high.to_bits());
|
||||
rows_hash = mix_u64(rows_hash, row.low.to_bits());
|
||||
rows_hash = mix_u64(rows_hash, row.close.to_bits());
|
||||
rows_hash = mix_u64(rows_hash, row.source as u64);
|
||||
}
|
||||
|
||||
let lookups = DEFAULT_FX_BENCH_LOOKUPS;
|
||||
let (query_min, query_span) = match (built.rows.first(), built.rows.last()) {
|
||||
(Some(first), Some(last)) => {
|
||||
let min_q = first.session_date - 10;
|
||||
let max_q = last.session_date + 10;
|
||||
(min_q, (i64::from(max_q) - i64::from(min_q) + 1) as u64)
|
||||
}
|
||||
_ => (base_date, 100u64),
|
||||
};
|
||||
|
||||
let mut lookup_hash = 0u64;
|
||||
let mut lookup_hits = 0usize;
|
||||
let lookup_start = Instant::now();
|
||||
for _ in 0..lookups {
|
||||
let query_date = query_min + (rng.next_u64() % query_span) as i32;
|
||||
if let Some(row) = fx_rate_on_or_before(&built.rows, query_date, 4) {
|
||||
lookup_hits += 1;
|
||||
lookup_hash = mix_u64(lookup_hash, row.close.to_bits());
|
||||
} else {
|
||||
lookup_hash = mix_u64(lookup_hash, 0xDEAD_BEEF_u64);
|
||||
}
|
||||
}
|
||||
let lookup_hash = black_box(lookup_hash);
|
||||
let lookup_elapsed_secs = lookup_start.elapsed().as_secs_f64();
|
||||
let lookup_elapsed_ms = lookup_elapsed_secs * 1_000.0;
|
||||
let (lookups_per_sec, ns_per_lookup) = compute_rates(lookups, lookup_elapsed_secs);
|
||||
|
||||
let checksum = black_box(mix_u64(rows_hash, lookup_hash));
|
||||
|
||||
FxBenchReport {
|
||||
rows,
|
||||
eod_rows_in,
|
||||
te_rows_in,
|
||||
rows_out: built.stats.rows_out,
|
||||
build_elapsed_ms,
|
||||
build_rows_per_sec,
|
||||
build_ns_per_row,
|
||||
lookups,
|
||||
lookup_hits,
|
||||
lookup_elapsed_ms,
|
||||
lookups_per_sec,
|
||||
ns_per_lookup,
|
||||
checksum,
|
||||
stats: built.stats,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -752,4 +1087,49 @@ mod tests {
|
|||
assert_eq!(report.rows_per_sec, 0.0);
|
||||
assert_eq!(report.ns_per_row, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fx_benchmark_small_run_is_deterministic() {
|
||||
let a = run_fx_benchmark(2_000);
|
||||
let b = run_fx_benchmark(2_000);
|
||||
|
||||
assert_eq!(a.rows, 2_000);
|
||||
assert_eq!(a.eod_rows_in + a.te_rows_in, 2_000);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.lookups, DEFAULT_FX_BENCH_LOOKUPS);
|
||||
assert_eq!(a.lookup_hits, b.lookup_hits);
|
||||
assert!(a.lookup_hits > 0 && a.lookup_hits < a.lookups);
|
||||
assert_eq!(a.stats, b.stats);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
assert!(a.build_rows_per_sec.is_finite() && a.build_rows_per_sec >= 0.0);
|
||||
assert!(a.build_ns_per_row.is_finite() && a.build_ns_per_row >= 0.0);
|
||||
assert!(a.lookups_per_sec.is_finite() && a.lookups_per_sec >= 0.0);
|
||||
assert!(a.ns_per_lookup.is_finite() && a.ns_per_lookup >= 0.0);
|
||||
assert!(a.stats.eod.dropped_invalid_ohlc > 0);
|
||||
assert!(a.stats.eod.dropped_inconsistent_ohlc > 0);
|
||||
assert!(a.stats.eod.duplicate_collapsed > 0);
|
||||
assert!(a.stats.eod.duplicate_conflict_dropped > 0);
|
||||
assert!(a.stats.te_superseded_by_eod > 0);
|
||||
assert!(a.stats.overlap_within_tolerance > 0);
|
||||
assert!(a.stats.overlap_mismatched > 0);
|
||||
assert!(a.stats.te_rows_out > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fx_benchmark_zero_rows_handles_cleanly() {
|
||||
let report = run_fx_benchmark(0);
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.eod_rows_in, 0);
|
||||
assert_eq!(report.te_rows_in, 0);
|
||||
assert_eq!(report.rows_out, 0);
|
||||
assert_eq!(report.lookups, 0);
|
||||
assert_eq!(report.lookup_hits, 0);
|
||||
assert_eq!(report.stats, Fx1dStats::default());
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.build_rows_per_sec, 0.0);
|
||||
assert_eq!(report.build_ns_per_row, 0.0);
|
||||
assert_eq!(report.lookups_per_sec, 0.0);
|
||||
assert_eq!(report.ns_per_lookup, 0.0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_FX_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -17,6 +17,7 @@ pub enum CliAction {
|
|||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
BenchBars(usize),
|
||||
BenchFx(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -30,7 +31,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
|
||||
{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})"
|
||||
{name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -43,7 +45,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
{name} bench-bars [rows]"
|
||||
{name} bench-bars [rows]\n\
|
||||
{name} bench-fx [rows]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -92,6 +95,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-bars", _, ..] => Err("too many arguments for bench-bars".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)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-fx", _, ..] => Err("too many arguments for bench-fx".to_string()),
|
||||
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -193,6 +204,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-bars", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_fx_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-fx"])),
|
||||
Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-fx", "5000"])),
|
||||
Ok(CliAction::BenchFx(5_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-fx", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-fx", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-fx", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-fx", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -200,11 +227,13 @@ mod tests {
|
|||
assert!(full.contains("bench-adj"));
|
||||
assert!(full.contains("bench-corporate-actions"));
|
||||
assert!(full.contains("bench-bars"));
|
||||
assert!(full.contains("bench-fx"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
assert!(short.contains("bench-adj"));
|
||||
assert!(short.contains("bench-corporate-actions"));
|
||||
assert!(short.contains("bench-bars"));
|
||||
assert!(short.contains("bench-fx"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
604
tools/curate-etl/src/fx.rs
Normal file
604
tools/curate-etl/src/fx.rs
Normal file
|
|
@ -0,0 +1,604 @@
|
|||
//! 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;
|
||||
|
||||
/// 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 {
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ pub mod bars;
|
|||
pub mod bench;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod fx;
|
||||
pub mod split;
|
||||
|
||||
pub use adj::{
|
||||
|
|
@ -20,6 +21,10 @@ pub use corporate_actions::{
|
|||
CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent,
|
||||
KnownAtSource, SplitActionEvent,
|
||||
};
|
||||
pub use fx::{
|
||||
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
|
||||
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
|
||||
};
|
||||
pub use split::{
|
||||
unadjust_ohlcv, unadjust_price, unadjust_volume, ymd_to_epoch_days, OhlcvBar, SplitEntry,
|
||||
SplitError, SplitEvent, SplitTable,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ use std::env;
|
|||
use std::process::ExitCode;
|
||||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_split_benchmark,
|
||||
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_fx_benchmark,
|
||||
run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -160,6 +161,49 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchFx(rows)) => {
|
||||
let report = run_fx_benchmark(rows);
|
||||
println!("curate-etl bench-fx");
|
||||
println!(
|
||||
" input: rows={} eod_rows={} te_rows={}",
|
||||
report.rows, report.eod_rows_in, report.te_rows_in
|
||||
);
|
||||
println!(
|
||||
" build: rows_out={} eod_out={} te_out={} elapsed={:.3} ms throughput={:.0} rows/s latency={:.2} ns/row",
|
||||
report.rows_out,
|
||||
report.stats.eod_rows_out,
|
||||
report.stats.te_rows_out,
|
||||
report.build_elapsed_ms,
|
||||
report.build_rows_per_sec,
|
||||
report.build_ns_per_row
|
||||
);
|
||||
println!(
|
||||
" lookup: lookups={} hits={} elapsed={:.2} ms throughput={:.0} lookups/s latency={:.2} ns/lookup checksum=0x{:016x}",
|
||||
report.lookups,
|
||||
report.lookup_hits,
|
||||
report.lookup_elapsed_ms,
|
||||
report.lookups_per_sec,
|
||||
report.ns_per_lookup,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" stats: eod_invalid={} eod_inconsistent={} eod_dup_collapsed={} eod_dup_conflict={} te_invalid={} te_inconsistent={} te_dup_collapsed={} te_dup_conflict={} te_superseded={} overlap_checked={} within_tol={} mismatched={} max_overlap_rel={:.6}",
|
||||
report.stats.eod.dropped_invalid_ohlc,
|
||||
report.stats.eod.dropped_inconsistent_ohlc,
|
||||
report.stats.eod.duplicate_collapsed,
|
||||
report.stats.eod.duplicate_conflict_dropped,
|
||||
report.stats.te.dropped_invalid_ohlc,
|
||||
report.stats.te.dropped_inconsistent_ohlc,
|
||||
report.stats.te.duplicate_collapsed,
|
||||
report.stats.te.duplicate_conflict_dropped,
|
||||
report.stats.te_superseded_by_eod,
|
||||
report.stats.overlap_checked,
|
||||
report.stats.overlap_within_tolerance,
|
||||
report.stats.overlap_mismatched,
|
||||
report.stats.max_overlap_rel
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ fn no_args_and_help_print_usage_and_succeed() {
|
|||
assert!(text.contains("Usage:"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-split"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-fx"), "{args:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -54,6 +55,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() {
|
|||
&["bench-corporate-actions", "0"][..],
|
||||
&["bench-corporate-actions", "-5"][..],
|
||||
&["bench-corporate-actions", "10", "20"][..],
|
||||
&["bench-fx", "abc"][..],
|
||||
&["bench-fx", "0"][..],
|
||||
&["bench-fx", "-5"][..],
|
||||
&["bench-fx", "10", "20"][..],
|
||||
&["--unknown"][..],
|
||||
&["export"][..],
|
||||
] {
|
||||
|
|
@ -126,3 +131,35 @@ fn bench_corporate_actions_small_run_is_headless_deterministic_and_reports_rates
|
|||
assert_eq!(checksum_a, checksum_b);
|
||||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_fx_small_run_is_headless_deterministic_and_reports_rates() {
|
||||
let a = run(&["bench-fx", "1000"]);
|
||||
let b = run(&["bench-fx", "1000"]);
|
||||
assert!(a.status.success(), "{}", stderr(&a));
|
||||
assert!(b.status.success(), "{}", stderr(&b));
|
||||
assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a));
|
||||
assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b));
|
||||
|
||||
let text_a = stdout(&a);
|
||||
let text_b = stdout(&b);
|
||||
assert!(text_a.contains("curate-etl bench-fx"), "{text_a}");
|
||||
assert!(text_a.contains("rows=1000 "), "{text_a}");
|
||||
assert!(text_a.contains("rows_out="), "{text_a}");
|
||||
assert!(text_a.contains("rows/s"), "{text_a}");
|
||||
assert!(text_a.contains("lookups=1000000 "), "{text_a}");
|
||||
assert!(text_a.contains("lookups/s"), "{text_a}");
|
||||
assert!(text_a.contains("checksum=0x"), "{text_a}");
|
||||
assert!(text_a.contains("stats: eod_invalid="), "{text_a}");
|
||||
|
||||
let field = |s: &str, prefix: &str| {
|
||||
s.split_whitespace()
|
||||
.find(|t| t.starts_with(prefix))
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let checksum_a = field(&text_a, "checksum=");
|
||||
let checksum_b = field(&text_b, "checksum=");
|
||||
assert!(checksum_a.is_some(), "{text_a}");
|
||||
assert_eq!(checksum_a, checksum_b);
|
||||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
}
|
||||
|
|
|
|||
399
tools/curate-etl/tests/fx_contract.rs
Normal file
399
tools/curate-etl/tests/fx_contract.rs
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
//! Contract tests for the public `curate_etl` `fx_1d` builder API (T-75 / M1.2e).
|
||||
//!
|
||||
//! Uses only the crate's public surface, guarding the USD/CAD merge precedence, bad-row
|
||||
//! resilience, deduplication isolation, read-only 1% overlap audit, permutation invariance,
|
||||
//! accounting invariants, and no-look-ahead carry-forward lookup semantics.
|
||||
|
||||
use curate_etl::bench::{run_fx_benchmark, DEFAULT_FX_BENCH_LOOKUPS};
|
||||
use curate_etl::{
|
||||
build_fx_1d, fx_rate_on_or_before, ymd_to_epoch_days, Fx1dBuild, Fx1dRow, Fx1dStats,
|
||||
FxDailyBar, FxSource, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
|
||||
};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid fixture date")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&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 shuffle<T>(items: &mut [T], rng: &mut Rng) {
|
||||
for i in (1..items.len()).rev() {
|
||||
let j = (rng.next() % (i as u64 + 1)) as usize;
|
||||
items.swap(i, j);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_accounting_and_order(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 rows_out invariant failed: {s:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
s.rows_out,
|
||||
s.eod_rows_out + s.te_rows_out,
|
||||
"eod_rows_out + te_rows_out != rows_out: {s:?}"
|
||||
);
|
||||
assert_eq!(s.rows_out, build.rows.len());
|
||||
assert_eq!(
|
||||
s.overlap_within_tolerance + s.overlap_mismatched,
|
||||
s.overlap_checked,
|
||||
"overlap within + mismatched != checked: {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 must be strictly ascending and unique: {} >= {}",
|
||||
pair[0].session_date,
|
||||
pair[1].session_date
|
||||
);
|
||||
}
|
||||
for row in &build.rows {
|
||||
assert_eq!(row.pair, FX_PAIR_USDCAD);
|
||||
assert_eq!(row.pair, "USDCAD");
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_rows_bit_eq(a: &[Fx1dRow], b: &[Fx1dRow]) {
|
||||
assert_eq!(a.len(), b.len());
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
assert_eq!(x.pair, y.pair);
|
||||
assert_eq!(x.session_date, y.session_date);
|
||||
assert_eq!(x.open.to_bits(), y.open.to_bits());
|
||||
assert_eq!(x.high.to_bits(), y.high.to_bits());
|
||||
assert_eq!(x.low.to_bits(), y.low.to_bits());
|
||||
assert_eq!(x.close.to_bits(), y.close.to_bits());
|
||||
assert_eq!(x.source, y.source);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_stats_bit_eq(a: &Fx1dStats, b: &Fx1dStats) {
|
||||
assert_eq!(a.eod, b.eod);
|
||||
assert_eq!(a.te, b.te);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.eod_rows_out, b.eod_rows_out);
|
||||
assert_eq!(a.te_rows_out, b.te_rows_out);
|
||||
assert_eq!(a.te_superseded_by_eod, b.te_superseded_by_eod);
|
||||
assert_eq!(a.overlap_checked, b.overlap_checked);
|
||||
assert_eq!(a.overlap_within_tolerance, b.overlap_within_tolerance);
|
||||
assert_eq!(a.overlap_mismatched, b.overlap_mismatched);
|
||||
assert_eq!(a.max_overlap_rel.to_bits(), b.max_overlap_rel.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eod_precedence_te_gap_and_tail_fill_and_provenance_strings() {
|
||||
assert_eq!(FX_PAIR_USDCAD, "USDCAD");
|
||||
assert_eq!(FX_OVERLAP_REL_TOLERANCE, 0.01);
|
||||
assert_eq!(FxSource::EodCadForex.as_str(), "eod_cad_forex");
|
||||
assert_eq!(FxSource::TeUsdCad.as_str(), "te_usdcad");
|
||||
|
||||
let d1971 = day(1971, 1, 4);
|
||||
let d_gap = day(2024, 11, 12);
|
||||
let d_overlap = day(2025, 12, 31);
|
||||
let d_tail1 = day(2026, 1, 2);
|
||||
let d_tail2 = day(2026, 1, 5);
|
||||
|
||||
let eod = [
|
||||
bar(d_overlap, 1.435, 1.445, 1.430, 1.440),
|
||||
bar(d1971, 1.010, 1.015, 1.005, 1.012),
|
||||
];
|
||||
let te = [
|
||||
bar(d_tail2, 1.382, 1.390, 1.378, 1.385),
|
||||
bar(d_overlap, 1.436, 1.446, 1.431, 1.441),
|
||||
bar(d_gap, 1.395, 1.402, 1.390, 1.398),
|
||||
bar(d_tail1, 1.380, 1.388, 1.376, 1.384),
|
||||
];
|
||||
|
||||
let built = build_fx_1d(&eod, &te);
|
||||
assert_accounting_and_order(&built);
|
||||
assert_eq!(built.rows.len(), 5);
|
||||
assert_eq!(built.stats.eod_rows_out, 2);
|
||||
assert_eq!(built.stats.te_rows_out, 3);
|
||||
assert_eq!(built.stats.te_superseded_by_eod, 1);
|
||||
|
||||
let dates: Vec<i32> = built.rows.iter().map(|r| r.session_date).collect();
|
||||
assert_eq!(dates, vec![d1971, d_gap, d_overlap, d_tail1, d_tail2]);
|
||||
|
||||
assert_eq!(built.rows[0].source.as_str(), "eod_cad_forex");
|
||||
assert_eq!(built.rows[1].source.as_str(), "te_usdcad");
|
||||
assert_eq!(built.rows[2].source.as_str(), "eod_cad_forex");
|
||||
// Overlap date preserves EOD OHLC bit-for-bit.
|
||||
assert_eq!(built.rows[2].open.to_bits(), eod[0].open.to_bits());
|
||||
assert_eq!(built.rows[2].high.to_bits(), eod[0].high.to_bits());
|
||||
assert_eq!(built.rows[2].low.to_bits(), eod[0].low.to_bits());
|
||||
assert_eq!(built.rows[2].close.to_bits(), eod[0].close.to_bits());
|
||||
assert_eq!(built.rows[3].source.as_str(), "te_usdcad");
|
||||
assert_eq!(built.rows[4].source.as_str(), "te_usdcad");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_row_priority_and_duplicate_conflict_isolation_across_sources() {
|
||||
let base = day(2024, 1, 2);
|
||||
let eod = [
|
||||
// Invalid beats inconsistent when both apply
|
||||
bar(base, f64::NAN, 1.0, 2.0, 1.5),
|
||||
bar(base + 1, 0.0, 1.0, 2.0, 1.5),
|
||||
bar(base + 2, -1.0, 1.5, 1.0, 1.2),
|
||||
bar(base + 3, 1.2, f64::INFINITY, 1.1, 1.15),
|
||||
bar(base + 4, 1.2, 1.3, f64::NEG_INFINITY, 1.25),
|
||||
// Inconsistent OHLC
|
||||
bar(base + 5, 1.2, 1.1, 1.3, 1.2),
|
||||
bar(base + 6, 1.0, 1.3, 1.1, 1.2),
|
||||
bar(base + 7, 1.4, 1.3, 1.1, 1.2),
|
||||
bar(base + 8, 1.2, 1.3, 1.1, 1.0),
|
||||
bar(base + 9, 1.2, 1.3, 1.1, 1.4),
|
||||
// Identical duplicate collapses
|
||||
flat(base + 10, 1.35),
|
||||
flat(base + 10, 1.35),
|
||||
// Conflicting duplicate group drops entirely in EOD; TE fills base+11
|
||||
flat(base + 11, 1.36),
|
||||
flat(base + 11, 1.37),
|
||||
flat(base + 11, 1.36),
|
||||
];
|
||||
let te = [
|
||||
flat(base + 11, 1.365),
|
||||
// Conflicting TE group on base+10 drops cleanly without affecting EOD row
|
||||
flat(base + 10, 1.35),
|
||||
flat(base + 10, 1.40),
|
||||
// Invalid TE row on base+12 + valid TE row on base+12 -> valid survives
|
||||
bar(base + 12, -0.0, 1.4, 1.3, 1.35),
|
||||
flat(base + 12, 1.355),
|
||||
];
|
||||
|
||||
let built = build_fx_1d(&eod, &te);
|
||||
assert_accounting_and_order(&built);
|
||||
assert_eq!(built.stats.eod.dropped_invalid_ohlc, 5);
|
||||
assert_eq!(built.stats.eod.dropped_inconsistent_ohlc, 5);
|
||||
assert_eq!(built.stats.eod.duplicate_collapsed, 1);
|
||||
assert_eq!(built.stats.eod.duplicate_conflict_dropped, 3);
|
||||
assert_eq!(built.stats.eod.rows_kept, 1);
|
||||
|
||||
assert_eq!(built.stats.te.dropped_invalid_ohlc, 1);
|
||||
assert_eq!(built.stats.te.dropped_inconsistent_ohlc, 0);
|
||||
assert_eq!(built.stats.te.duplicate_collapsed, 0);
|
||||
assert_eq!(built.stats.te.duplicate_conflict_dropped, 2);
|
||||
assert_eq!(built.stats.te.rows_kept, 2);
|
||||
|
||||
assert_eq!(built.rows.len(), 3);
|
||||
assert_eq!(built.rows[0].session_date, base + 10);
|
||||
assert_eq!(built.rows[0].source, FxSource::EodCadForex);
|
||||
assert_eq!(built.rows[1].session_date, base + 11);
|
||||
assert_eq!(built.rows[1].source, FxSource::TeUsdCad);
|
||||
assert_eq!(built.rows[2].session_date, base + 12);
|
||||
assert_eq!(built.rows[2].source, FxSource::TeUsdCad);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_one_percent_boundary_is_inclusive_and_strictly_read_only() {
|
||||
let base = day(2025, 3, 1);
|
||||
let eod = [
|
||||
bar(base, 99.5, 101.0, 99.0, 100.0), // te = 101.0 -> exact +1% (within)
|
||||
bar(base + 1, 99.5, 101.0, 99.0, 100.0), // te = 99.0 -> exact -1% (within)
|
||||
bar(base + 2, 99.5, 101.0, 99.0, 100.0), // te = 101.01 -> +1.01% (mismatch)
|
||||
bar(base + 3, 99.5, 101.0, 99.0, 100.0), // te = 98.99 -> -1.01% (mismatch)
|
||||
bar(base + 4, 99.5, 101.0, 99.0, 100.0), // te = 200.0 -> +100% (mismatch)
|
||||
];
|
||||
let te = [
|
||||
flat(base, 101.0),
|
||||
flat(base + 1, 99.0),
|
||||
flat(base + 2, 101.01),
|
||||
flat(base + 3, 98.99),
|
||||
flat(base + 4, 200.0),
|
||||
];
|
||||
|
||||
let built = build_fx_1d(&eod, &te);
|
||||
assert_accounting_and_order(&built);
|
||||
assert_eq!(built.stats.overlap_checked, 5);
|
||||
assert_eq!(built.stats.overlap_within_tolerance, 2);
|
||||
assert_eq!(built.stats.overlap_mismatched, 3);
|
||||
assert_eq!(built.stats.max_overlap_rel, 1.0);
|
||||
|
||||
// Output rows must be bit-identical to EOD inputs.
|
||||
for (row, orig) in built.rows.iter().zip(&eod) {
|
||||
assert_eq!(row.source, FxSource::EodCadForex);
|
||||
assert_eq!(row.open.to_bits(), orig.open.to_bits());
|
||||
assert_eq!(row.high.to_bits(), orig.high.to_bits());
|
||||
assert_eq!(row.low.to_bits(), orig.low.to_bits());
|
||||
assert_eq!(row.close.to_bits(), orig.close.to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permutation_invariance_holds_across_multiple_fixed_seed_shuffles() {
|
||||
let base = day(2020, 1, 2);
|
||||
let mut eod = Vec::new();
|
||||
let mut te = Vec::new();
|
||||
|
||||
for i in 0..80_i32 {
|
||||
let d = base + i;
|
||||
let close = 1.30 + (i % 15) as f64 * 0.005;
|
||||
let b = bar(d, close - 0.002, close + 0.004, close - 0.004, close);
|
||||
if i % 7 != 0 {
|
||||
eod.push(b);
|
||||
if i % 11 == 0 {
|
||||
eod.push(b); // identical dup
|
||||
}
|
||||
if i % 19 == 0 {
|
||||
let mut c = b;
|
||||
c.close += 0.001;
|
||||
eod.push(c); // conflicting dup
|
||||
}
|
||||
}
|
||||
if i >= 40 {
|
||||
let factor = if i % 9 == 0 { 1.03 } else { 1.002 };
|
||||
let tb = bar(
|
||||
d,
|
||||
b.open * factor,
|
||||
b.high * factor,
|
||||
b.low * factor,
|
||||
b.close * factor,
|
||||
);
|
||||
te.push(tb);
|
||||
if i % 13 == 0 {
|
||||
te.push(tb); // identical dup
|
||||
}
|
||||
if i % 23 == 0 {
|
||||
let mut c = tb;
|
||||
c.close += 0.001;
|
||||
te.push(c); // conflicting dup
|
||||
}
|
||||
}
|
||||
}
|
||||
// Inject invalid and inconsistent rows into both sources.
|
||||
eod.push(bar(base + 200, f64::NAN, 1.3, 1.2, 1.25));
|
||||
eod.push(bar(base + 201, 1.25, 1.20, 1.30, 1.25));
|
||||
te.push(bar(base + 202, -1.0, 1.3, 1.2, 1.25));
|
||||
te.push(bar(base + 203, 1.50, 1.35, 1.25, 1.30));
|
||||
|
||||
let baseline = build_fx_1d(&eod, &te);
|
||||
assert_accounting_and_order(&baseline);
|
||||
assert!(baseline.stats.overlap_checked > 0);
|
||||
assert!(baseline.stats.overlap_within_tolerance > 0);
|
||||
assert!(baseline.stats.overlap_mismatched > 0);
|
||||
|
||||
let mut rng = Rng(0x570C_4B07_F81D_9999);
|
||||
for _ in 0..16 {
|
||||
let mut eod_perm = eod.clone();
|
||||
let mut te_perm = te.clone();
|
||||
shuffle(&mut eod_perm, &mut rng);
|
||||
shuffle(&mut te_perm, &mut rng);
|
||||
|
||||
let trial = build_fx_1d(&eod_perm, &te_perm);
|
||||
assert_accounting_and_order(&trial);
|
||||
assert_rows_bit_eq(&baseline.rows, &trial.rows);
|
||||
assert_stats_bit_eq(&baseline.stats, &trial.stats);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fx_rate_on_or_before_enforces_no_lookahead_and_staleness_bounds() {
|
||||
let fri = day(2025, 2, 14);
|
||||
let sat = day(2025, 2, 15);
|
||||
let sun = day(2025, 2, 16);
|
||||
let holiday_mon = day(2025, 2, 17); // Family Day / Presidents' Day
|
||||
let tue = day(2025, 2, 18);
|
||||
let later = day(2025, 3, 1);
|
||||
|
||||
let built = build_fx_1d(
|
||||
&[flat(fri, 1.420), flat(tue, 1.425)],
|
||||
&[flat(later, 1.440)],
|
||||
);
|
||||
let rows = &built.rows;
|
||||
|
||||
// Empty slice always None
|
||||
assert_eq!(fx_rate_on_or_before(&[], fri, 10), None);
|
||||
// Date before first row always None (never looks ahead)
|
||||
assert_eq!(fx_rate_on_or_before(rows, fri - 1, u32::MAX), None);
|
||||
// Exact hits with max_stale_days == 0
|
||||
assert_eq!(fx_rate_on_or_before(rows, fri, 0).map(|r| r.close), Some(1.420));
|
||||
assert_eq!(fx_rate_on_or_before(rows, tue, 0).map(|r| r.close), Some(1.425));
|
||||
assert_eq!(fx_rate_on_or_before(rows, later, 0).map(|r| r.close), Some(1.440));
|
||||
|
||||
// Long weekend carry-forward (Fri -> Sat, Sun, Mon)
|
||||
assert_eq!(fx_rate_on_or_before(rows, sat, 3).map(|r| r.session_date), Some(fri));
|
||||
assert_eq!(fx_rate_on_or_before(rows, sun, 3).map(|r| r.session_date), Some(fri));
|
||||
assert_eq!(fx_rate_on_or_before(rows, holiday_mon, 3).map(|r| r.session_date), Some(fri));
|
||||
// Staleness limit exceeded on holiday_mon (age = 3 > 2) -> None, never looks ahead to Tue
|
||||
assert_eq!(fx_rate_on_or_before(rows, holiday_mon, 2), None);
|
||||
|
||||
// Exhaustive no-look-ahead sweep across the full range
|
||||
for q in (fri - 5)..=(later + 5) {
|
||||
if let Some(found) = fx_rate_on_or_before(rows, q, 4) {
|
||||
assert!(found.session_date <= q, "look-ahead violation: {} > {}", found.session_date, q);
|
||||
assert!(i64::from(q) - i64::from(found.session_date) <= 4);
|
||||
}
|
||||
}
|
||||
|
||||
// Extreme i32 dates do not overflow
|
||||
let extreme = build_fx_1d(&[flat(i32::MIN, 1.0), flat(0, 1.1)], &[]);
|
||||
assert_eq!(
|
||||
fx_rate_on_or_before(&extreme.rows, i32::MIN, 0).map(|r| r.session_date),
|
||||
Some(i32::MIN)
|
||||
);
|
||||
assert_eq!(fx_rate_on_or_before(&extreme.rows, i32::MAX, 5), None);
|
||||
assert_eq!(
|
||||
fx_rate_on_or_before(&extreme.rows, i32::MAX, u32::MAX).map(|r| r.session_date),
|
||||
Some(0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_fx_benchmark_is_deterministic_across_runs() {
|
||||
let a = run_fx_benchmark(1_000);
|
||||
let b = run_fx_benchmark(1_000);
|
||||
assert_eq!(a.rows, 1_000);
|
||||
assert_eq!(a.lookups, DEFAULT_FX_BENCH_LOOKUPS);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.lookup_hits, b.lookup_hits);
|
||||
assert_eq!(a.stats, b.stats);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue