T-47: M1.2a — Scaffold tools/curate-etl Rust crate: split-factor table + un-adjustment core with local benchmark (no new crates)
This commit is contained in:
parent
ce4b8fa91c
commit
4c8a621e48
4 changed files with 161 additions and 41 deletions
|
|
@ -12,7 +12,7 @@ Aligned with `design/DATA-CONTRACTS.md` (§1 `qmSplits`, `eodPrices`, `eodIntrad
|
||||||
- No-op rows (`ratio == 1.0`) are dropped during `SplitTable::from_events`.
|
- No-op rows (`ratio == 1.0`) are dropped during `SplitTable::from_events`.
|
||||||
- Duplicate events on the same `ex_date` are multiplied (and dropped if reciprocal pairs cancel to `1.0`).
|
- Duplicate events on the same `ex_date` are multiplied (and dropped if reciprocal pairs cancel to `1.0`).
|
||||||
- Non-finite or `<= 0.0` ratios and compounding overflow/underflow return a typed `SplitError` rather than panicking.
|
- Non-finite or `<= 0.0` ratios and compounding overflow/underflow return a typed `SplitError` rather than panicking.
|
||||||
- **Ex-date boundary (strict `>`):** `cum_factor_after(key, bar_date)` returns the product of all split ratios with `ex_date > bar_date`. A bar dated on the ex-date itself is already post-split (`factor = 1.0`). Unknown keys and post-split dates return `1.0`.
|
- **Ex-date boundary (strict `>`):** `cum_factor_after(key, bar_date)` returns the product of all split ratios with `ex_date > bar_date`. A bar dated on an ex-date excludes that day's split (it is already post-split for that event) while still including any later splits (for example, NVDA on its `2021-07-20` 4:1 ex-date still has `factor = 10.0` from the later `2024-06-10` 10:1 split). Unknown keys and dates with no later splits return `1.0`.
|
||||||
- **`eodPrices` (daily bars):** OHLC is raw and only volume is retroactively split-adjusted:
|
- **`eodPrices` (daily bars):** OHLC is raw and only volume is retroactively split-adjusted:
|
||||||
- `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor`
|
- `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor`
|
||||||
- **`eodIntraday1M` (1m bars, reused in M2):** both OHLC and volume are retroactively split-adjusted:
|
- **`eodIntraday1M` (1m bars, reused in M2):** both OHLC and volume are retroactively split-adjusted:
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
use std::hint::black_box;
|
use std::hint::black_box;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitEvent, SplitTable};
|
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable};
|
||||||
|
|
||||||
pub const DEFAULT_BENCH_ROWS: usize = 10_000_000;
|
pub const DEFAULT_BENCH_ROWS: usize = 10_000_000;
|
||||||
pub const BENCH_KEY_COUNT: usize = 20_000;
|
pub const BENCH_KEY_COUNT: usize = 20_000;
|
||||||
|
|
@ -48,14 +48,23 @@ pub struct BenchReport {
|
||||||
pub checksum: f64,
|
pub checksum: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn compute_rates(rows: usize, elapsed_secs: f64) -> (f64, f64) {
|
||||||
|
if rows == 0 || elapsed_secs <= 0.0 || !elapsed_secs.is_finite() {
|
||||||
|
(0.0, 0.0)
|
||||||
|
} else {
|
||||||
|
(rows as f64 / elapsed_secs, elapsed_secs * 1e9 / rows as f64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Runs the fixed-seed split lookup + `unadjust_volume` benchmark for `rows` bars.
|
/// Runs the fixed-seed split lookup + `unadjust_volume` benchmark for `rows` bars.
|
||||||
///
|
///
|
||||||
/// Builds a [`SplitTable<String>`] with `20_000` symbol keys and `19_000` deterministic forward
|
/// Builds a [`SplitTable<String>`] with `20_000` symbol keys and `19_000` deterministic forward
|
||||||
/// and reverse splits spanning `1990-01-01..=2025-12-31`, then executes `rows` zero-allocation
|
/// and reverse splits spanning `1990-01-01..=2025-12-31`, then executes `rows` zero-allocation
|
||||||
/// lookups and volume un-adjustments.
|
/// lookups and volume un-adjustments.
|
||||||
pub fn run_split_benchmark(rows: usize) -> BenchReport {
|
pub fn run_split_benchmark(rows: usize) -> Result<BenchReport, SplitError> {
|
||||||
let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305);
|
let min_date = ymd_to_epoch_days(1990, 1, 1)?;
|
||||||
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
|
let max_date = ymd_to_epoch_days(2025, 12, 31)?;
|
||||||
let date_span = (max_date - min_date + 1) as u64;
|
let date_span = (max_date - min_date + 1) as u64;
|
||||||
|
|
||||||
let keys: Vec<String> = (0..BENCH_KEY_COUNT)
|
let keys: Vec<String> = (0..BENCH_KEY_COUNT)
|
||||||
|
|
@ -72,7 +81,7 @@ pub fn run_split_benchmark(rows: usize) -> BenchReport {
|
||||||
}
|
}
|
||||||
|
|
||||||
let build_start = Instant::now();
|
let build_start = Instant::now();
|
||||||
let table = SplitTable::from_events(events).unwrap_or_default();
|
let table = SplitTable::from_events(events)?;
|
||||||
let build_elapsed_ms = build_start.elapsed().as_secs_f64() * 1_000.0;
|
let build_elapsed_ms = build_start.elapsed().as_secs_f64() * 1_000.0;
|
||||||
|
|
||||||
let key_count = keys.len();
|
let key_count = keys.len();
|
||||||
|
|
@ -93,13 +102,9 @@ pub fn run_split_benchmark(rows: usize) -> BenchReport {
|
||||||
let elapsed_secs = elapsed.as_secs_f64();
|
let elapsed_secs = elapsed.as_secs_f64();
|
||||||
let elapsed_ms = elapsed_secs * 1_000.0;
|
let elapsed_ms = elapsed_secs * 1_000.0;
|
||||||
|
|
||||||
let (rows_per_sec, ns_per_row) = if rows == 0 || elapsed_secs == 0.0 {
|
let (rows_per_sec, ns_per_row) = compute_rates(rows, elapsed_secs);
|
||||||
(0.0, 0.0)
|
|
||||||
} else {
|
|
||||||
(rows as f64 / elapsed_secs, elapsed_secs * 1e9 / rows as f64)
|
|
||||||
};
|
|
||||||
|
|
||||||
BenchReport {
|
Ok(BenchReport {
|
||||||
rows,
|
rows,
|
||||||
key_count,
|
key_count,
|
||||||
table_keys_with_splits: table.len(),
|
table_keys_with_splits: table.len(),
|
||||||
|
|
@ -109,35 +114,53 @@ pub fn run_split_benchmark(rows: usize) -> BenchReport {
|
||||||
rows_per_sec,
|
rows_per_sec,
|
||||||
ns_per_row,
|
ns_per_row,
|
||||||
checksum,
|
checksum,
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
const EXPECTED_KEYS_WITH_SPLITS: usize = 12_153;
|
||||||
|
const EXPECTED_EVENT_COUNT: usize = 18_999;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn benchmark_small_run_is_deterministic() {
|
fn benchmark_small_run_is_deterministic() {
|
||||||
let a = run_split_benchmark(1_000);
|
let a = run_split_benchmark(1_000).unwrap();
|
||||||
let b = run_split_benchmark(1_000);
|
let b = run_split_benchmark(1_000).unwrap();
|
||||||
|
|
||||||
assert_eq!(a.rows, 1_000);
|
assert_eq!(a.rows, 1_000);
|
||||||
assert_eq!(a.key_count, BENCH_KEY_COUNT);
|
assert_eq!(a.key_count, BENCH_KEY_COUNT);
|
||||||
|
assert_eq!(a.table_keys_with_splits, EXPECTED_KEYS_WITH_SPLITS);
|
||||||
|
assert_eq!(a.table_event_count, EXPECTED_EVENT_COUNT);
|
||||||
assert_eq!(a.table_keys_with_splits, b.table_keys_with_splits);
|
assert_eq!(a.table_keys_with_splits, b.table_keys_with_splits);
|
||||||
assert_eq!(a.table_event_count, b.table_event_count);
|
assert_eq!(a.table_event_count, b.table_event_count);
|
||||||
assert_eq!(a.checksum.to_bits(), b.checksum.to_bits());
|
assert_eq!(a.checksum.to_bits(), b.checksum.to_bits());
|
||||||
assert!(a.checksum.is_finite() && a.checksum > 0.0);
|
assert!(a.checksum.is_finite() && a.checksum > 0.0);
|
||||||
assert!(a.rows_per_sec > 0.0);
|
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
|
||||||
assert!(a.ns_per_row > 0.0);
|
assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compute_rates_uses_fixed_duration() {
|
||||||
|
let (rows_per_sec, ns_per_row) = compute_rates(1_000, 0.5);
|
||||||
|
assert_eq!(rows_per_sec, 2_000.0);
|
||||||
|
assert_eq!(ns_per_row, 500_000.0);
|
||||||
|
|
||||||
|
assert_eq!(compute_rates(0, 0.5), (0.0, 0.0));
|
||||||
|
assert_eq!(compute_rates(1_000, 0.0), (0.0, 0.0));
|
||||||
|
assert_eq!(compute_rates(1_000, -1.0), (0.0, 0.0));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn benchmark_zero_rows_handles_cleanly() {
|
fn benchmark_zero_rows_handles_cleanly() {
|
||||||
let report = run_split_benchmark(0);
|
let report = run_split_benchmark(0).unwrap();
|
||||||
assert_eq!(report.rows, 0);
|
assert_eq!(report.rows, 0);
|
||||||
|
assert_eq!(report.key_count, BENCH_KEY_COUNT);
|
||||||
|
assert_eq!(report.table_keys_with_splits, EXPECTED_KEYS_WITH_SPLITS);
|
||||||
|
assert_eq!(report.table_event_count, EXPECTED_EVENT_COUNT);
|
||||||
assert_eq!(report.checksum, 0.0);
|
assert_eq!(report.checksum, 0.0);
|
||||||
assert_eq!(report.rows_per_sec, 0.0);
|
assert_eq!(report.rows_per_sec, 0.0);
|
||||||
assert_eq!(report.ns_per_row, 0.0);
|
assert_eq!(report.ns_per_row, 0.0);
|
||||||
assert!(report.table_keys_with_splits > 0);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,37 +28,53 @@ fn print_usage_stderr() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum CliAction {
|
||||||
|
Help,
|
||||||
|
Version,
|
||||||
|
BenchSplit(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||||
|
let slices: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||||
|
match slices.as_slice() {
|
||||||
|
[] | ["--help"] | ["-h"] => Ok(CliAction::Help),
|
||||||
|
["--version"] | ["-V"] => Ok(CliAction::Version),
|
||||||
|
[flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => {
|
||||||
|
Err(format!("unexpected argument '{extra}' after '{flag}'"))
|
||||||
|
}
|
||||||
|
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||||
|
["bench-split", raw] => match raw.parse::<usize>() {
|
||||||
|
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),
|
||||||
|
_ => Err(format!(
|
||||||
|
"invalid row count '{raw}' (expected a positive integer)"
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
["bench-split", _, ..] => Err("too many arguments for bench-split".to_string()),
|
||||||
|
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn main() -> ExitCode {
|
fn main() -> ExitCode {
|
||||||
let args: Vec<String> = env::args().skip(1).collect();
|
let args: Vec<String> = env::args().skip(1).collect();
|
||||||
|
|
||||||
match args.first().map(String::as_str) {
|
match parse_args(&args) {
|
||||||
None | Some("--help") | Some("-h") => {
|
Ok(CliAction::Help) => {
|
||||||
print_usage();
|
print_usage();
|
||||||
ExitCode::SUCCESS
|
ExitCode::SUCCESS
|
||||||
}
|
}
|
||||||
Some("--version") | Some("-V") => {
|
Ok(CliAction::Version) => {
|
||||||
println!("{NAME} {VERSION}");
|
println!("{NAME} {VERSION}");
|
||||||
ExitCode::SUCCESS
|
ExitCode::SUCCESS
|
||||||
}
|
}
|
||||||
Some("bench-split") => {
|
Ok(CliAction::BenchSplit(rows)) => {
|
||||||
let rows = match args.get(1) {
|
let report = match run_split_benchmark(rows) {
|
||||||
None => DEFAULT_BENCH_ROWS,
|
Ok(report) => report,
|
||||||
Some(raw) if args.len() == 2 => match raw.parse::<usize>() {
|
Err(err) => {
|
||||||
Ok(n) if n > 0 => n,
|
eprintln!("error: benchmark fixture failed: {err}");
|
||||||
_ => {
|
|
||||||
eprintln!("error: invalid row count '{raw}' (expected a positive integer)");
|
|
||||||
print_usage_stderr();
|
|
||||||
return ExitCode::FAILURE;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Some(_) => {
|
|
||||||
eprintln!("error: too many arguments for bench-split");
|
|
||||||
print_usage_stderr();
|
|
||||||
return ExitCode::FAILURE;
|
return ExitCode::FAILURE;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let report = run_split_benchmark(rows);
|
|
||||||
println!("curate-etl bench-split");
|
println!("curate-etl bench-split");
|
||||||
println!(
|
println!(
|
||||||
" table: keys={} keys_with_splits={} events={} build={:.2} ms",
|
" table: keys={} keys_with_splits={} events={} build={:.2} ms",
|
||||||
|
|
@ -77,10 +93,60 @@ fn main() -> ExitCode {
|
||||||
);
|
);
|
||||||
ExitCode::SUCCESS
|
ExitCode::SUCCESS
|
||||||
}
|
}
|
||||||
Some(other) => {
|
Err(msg) => {
|
||||||
eprintln!("error: unknown argument '{other}'");
|
eprintln!("error: {msg}");
|
||||||
print_usage_stderr();
|
print_usage_stderr();
|
||||||
ExitCode::FAILURE
|
ExitCode::FAILURE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn to_args(items: &[&str]) -> Vec<String> {
|
||||||
|
items.iter().map(|s| (*s).to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_standalone_help_and_version_flags() {
|
||||||
|
assert_eq!(parse_args(&to_args(&[])), Ok(CliAction::Help));
|
||||||
|
assert_eq!(parse_args(&to_args(&["--help"])), Ok(CliAction::Help));
|
||||||
|
assert_eq!(parse_args(&to_args(&["-h"])), Ok(CliAction::Help));
|
||||||
|
assert_eq!(parse_args(&to_args(&["--version"])), Ok(CliAction::Version));
|
||||||
|
assert_eq!(parse_args(&to_args(&["-V"])), Ok(CliAction::Version));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_trailing_arguments_after_help_or_version() {
|
||||||
|
for invalid in [
|
||||||
|
&["--help", "--unknown"][..],
|
||||||
|
&["-h", "extra"][..],
|
||||||
|
&["--version", "--offine"][..],
|
||||||
|
&["-V", "bench-split"][..],
|
||||||
|
] {
|
||||||
|
let err = parse_args(&to_args(invalid)).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.contains("unexpected argument"),
|
||||||
|
"expected unexpected argument error for {invalid:?}, got: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_and_validates_bench_split_and_unknown_args() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&to_args(&["bench-split"])),
|
||||||
|
Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&to_args(&["bench-split", "100000"])),
|
||||||
|
Ok(CliAction::BenchSplit(100_000))
|
||||||
|
);
|
||||||
|
assert!(parse_args(&to_args(&["bench-split", "0"])).is_err());
|
||||||
|
assert!(parse_args(&to_args(&["bench-split", "abc"])).is_err());
|
||||||
|
assert!(parse_args(&to_args(&["bench-split", "10", "20"])).is_err());
|
||||||
|
assert!(parse_args(&to_args(&["--unknown"])).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -184,7 +184,11 @@ where
|
||||||
let mut coalesced: Vec<(i32, f64)> = Vec::new();
|
let mut coalesced: Vec<(i32, f64)> = Vec::new();
|
||||||
|
|
||||||
for (key, mut key_events) in grouped {
|
for (key, mut key_events) in grouped {
|
||||||
key_events.sort_unstable_by_key(|ev| ev.ex_date);
|
key_events.sort_unstable_by(|a, b| {
|
||||||
|
a.ex_date
|
||||||
|
.cmp(&b.ex_date)
|
||||||
|
.then_with(|| a.ratio.total_cmp(&b.ratio))
|
||||||
|
});
|
||||||
coalesced.clear();
|
coalesced.clear();
|
||||||
|
|
||||||
for ev in key_events {
|
for ev in key_events {
|
||||||
|
|
@ -573,6 +577,33 @@ mod tests {
|
||||||
assert_eq!(table.cum_factor_after("DUP", d1), 1.0);
|
assert_eq!(table.cum_factor_after("DUP", d1), 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn same_date_events_produce_bitwise_identical_factors_across_permutations() {
|
||||||
|
let d1 = ymd_to_epoch_days(2023, 3, 15).unwrap();
|
||||||
|
let permutations = [[10.0, 0.1, 0.1], [0.1, 10.0, 0.1], [0.1, 0.1, 10.0]];
|
||||||
|
|
||||||
|
let mut baseline_bits: Option<u64> = None;
|
||||||
|
for ratios in permutations {
|
||||||
|
let table = SplitTable::from_events(
|
||||||
|
ratios
|
||||||
|
.into_iter()
|
||||||
|
.map(|ratio| ("PERM".to_string(), SplitEvent { ex_date: d1, ratio })),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let factor = table.cum_factor_after("PERM", d1 - 1);
|
||||||
|
assert_rel_eq(factor, 0.1, 1e-12);
|
||||||
|
match baseline_bits {
|
||||||
|
None => baseline_bits = Some(factor.to_bits()),
|
||||||
|
Some(expected) => assert_eq!(
|
||||||
|
factor.to_bits(),
|
||||||
|
expected,
|
||||||
|
"same-date ratio permutation changed factor bits"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn generic_i32_listing_id_keys_and_date_boundaries() {
|
fn generic_i32_listing_id_keys_and_date_boundaries() {
|
||||||
let table: SplitTable<i32> = SplitTable::from_events([
|
let table: SplitTable<i32> = SplitTable::from_events([
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue