T-103: M1.2u — tools/curate-etl: pure corporate_actions curation stage (source-keyed qmSplits + qmDividends + Pass 6 delisting outcomes → provider_mapping → CorporateActionsParquetRows → Zstd Parquet) with tests and local benchmark (no new crates)
This commit is contained in:
parent
48bbf01eef
commit
6ce22a1643
7 changed files with 2346 additions and 13 deletions
|
|
@ -803,3 +803,48 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows]
|
|||
- Parquet write: `files=1`, `row_groups=1`, `bytes=27440094`, `read_back_rows=859916`, `elapsed=215.804 ms`, `throughput=3984706 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s`
|
||||
- Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000`
|
||||
|
||||
## `corporate_actions` Curation Stage (`M1.2u`)
|
||||
|
||||
`curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`.
|
||||
|
||||
1. **Field & timestamp rules:**
|
||||
- Calls `build_corporate_actions` unchanged (`1:1` split no-ops, `0.0` cash dividends, and delistings without an outcome drop inside the builder; same-key multi-dividends stay separate; late declarations clamp to `ex_date` with `KnownAtSource::ExDateFallback`; local `currency` is preserved).
|
||||
- Resolves `(mapping_source, key, ex_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run).
|
||||
- For `otc_delist_transfer` rows, resolves `successor_key` at the same `ex_date` (Pass 6 `effectiveDate`, the successor's first OTC trading date) to `successor_listing_id`. Never emits an `otc_delist_transfer` with `successor_listing_id = None` or `successor_listing_id == listing_id`.
|
||||
- Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source corporate-action records carry no intraday announcement time) and carries `known_at_source` through unchanged.
|
||||
- Carries `ex_date`, `declared_date`, `kind`, `ratio`, `cash_amount`, `currency`, and `terminal_return` through bit-exactly (`"USD"`/`"CAD"` interned as `Cow::Borrowed`).
|
||||
2. **Drop & collision policy (never panics or aborts on bad rows):**
|
||||
- Strict drop priority per built row:
|
||||
1. `dropped_unmapped`: no `provider_mapping` range covers `(mapping_source, key, ex_date)`.
|
||||
2. `dropped_unmapped_successor`: `otc_delist_transfer` whose `successor_key` has no covering range on `ex_date`.
|
||||
3. `dropped_self_successor`: `otc_delist_transfer` whose `successor_key` resolves to the row's own `listing_id`.
|
||||
4. `dropped_known_at_out_of_range`: `known_at_date` falls outside `et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window.
|
||||
- After re-sorting deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`):
|
||||
- Cross-key conflicting `split` ratios on the same `(listing_id, ex_date)` (`> 1` source key and `> 1` distinct `ratio` bit pattern) drop the entire group (`listing_collision_dropped`).
|
||||
- Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount same-day regular + special dividends) while collapsing cross-key aliases.
|
||||
- Exact conservation invariant in `CurateCorporateActionsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`.
|
||||
- Typed caller errors: `CurateCorporateActionsError` (`CorporateAction(CorporateActionError)`, `EmptyMappingSource`) and `CurateCorporateActionsWriteError` (`Curate(CurateCorporateActionsError)`, `Parquet(ParquetCorporateActionsError)`). A curate error in `curate_and_write_corporate_actions` returns before invoking `write_corporate_actions_dataset`, leaving `out_dir` untouched.
|
||||
|
||||
### `bench-curate-corporate-actions`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `520,000` source-keyed corporate-action events (~3.6% splits ≈20.3k incl. `1:1` no-ops and alias collisions, ~95.4% USD/CAD dividends ≈494.6k incl. `0.0` drops and same-day multi-dividends, ~1.0% delisting outcomes ≈5.1k incl. OTC transfers and `-0.3`/`-1.0`/no-outcome) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps, aliases, unmapped/self successors, and pre-1976 dates, separately timing in-memory `curate_corporate_actions` and Zstd Parquet `write_corporate_actions_dataset` into a temp directory with footer row-count verification and cleanup:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions [events]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1ab7caad4`): `cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions`
|
||||
|
||||
- Input: `events=520000`, `splits=20262`, `dividends=494624`, `delistings=5114`, `keys=20000`
|
||||
- Builder: `rows_out=514224`, `splits_out=19938`, `split_noops=324`, `divs_out=489671`, `zero_div=4953`, `otc_out=2856`, `delist_out=1759`, `delist_no_outcome=499`
|
||||
- Output: `rows_out=494518` (`95.10%` retained), `listings_out=19996`, `files=1`, `row_groups=1`, `bytes=3802001`, `read_back_rows=494518`
|
||||
- Curation stats: `unmapped=12887`, `unmapped_succ=510`, `self_succ=531`, `known_at_oor=2526`, `coll_collapsed=1398`, `coll_dropped=1854`
|
||||
- Run 1:
|
||||
- Stage (in-memory): `elapsed=243.00 ms`, `throughput=2139948 events/s`, `latency=467.30 ns/event`, `checksum=0x0c22a1a1ab7caad4`
|
||||
- Parquet write: `elapsed=118.61 ms`, `throughput=4169410 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=361.60 ms`, `throughput=1438042 events/s`
|
||||
- Run 2:
|
||||
- Stage (in-memory): `elapsed=244.15 ms`, `throughput=2129829 events/s`, `latency=469.52 ns/event`, `checksum=0x0c22a1a1ab7caad4`
|
||||
- Parquet write: `elapsed=155.57 ms`, `throughput=3178815 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=399.72 ms`, `throughput=1300918 events/s`
|
||||
|
|
|
|||
|
|
@ -5004,6 +5004,454 @@ pub fn run_curate_fx_benchmark(
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 520_000;
|
||||
const CURATE_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C04A_AC72;
|
||||
const CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT: usize = 20_000;
|
||||
|
||||
/// Summary metrics produced by [`run_curate_corporate_actions_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CurateCorporateActionsBenchReport {
|
||||
pub events: usize,
|
||||
pub splits_in: usize,
|
||||
pub dividends_in: usize,
|
||||
pub delistings_in: usize,
|
||||
pub key_count: usize,
|
||||
pub rows_out: usize,
|
||||
pub listings_out: usize,
|
||||
pub stage_elapsed_ms: f64,
|
||||
pub stage_events_per_sec: f64,
|
||||
pub stage_ns_per_event: f64,
|
||||
pub parquet_elapsed_ms: f64,
|
||||
pub parquet_rows_per_sec: f64,
|
||||
pub total_elapsed_ms: f64,
|
||||
pub total_events_per_sec: f64,
|
||||
pub files_written: usize,
|
||||
pub row_groups_written: usize,
|
||||
pub bytes_written: u64,
|
||||
pub read_back_rows: usize,
|
||||
pub checksum: u64,
|
||||
pub stats: crate::curate_corporate_actions::CurateCorporateActionsStats,
|
||||
}
|
||||
|
||||
struct CurateCorporateActionsBenchFixture {
|
||||
splits: Vec<(String, SplitActionEvent)>,
|
||||
dividends: Vec<(String, DividendActionEvent)>,
|
||||
delistings: Vec<(String, DelistingOutcomeEvent<String>)>,
|
||||
provider_mapping: ProviderMappingTable,
|
||||
key_count: usize,
|
||||
}
|
||||
|
||||
fn build_curate_corporate_actions_bench_fixture(
|
||||
events: usize,
|
||||
) -> CurateCorporateActionsBenchFixture {
|
||||
const KEY_COUNT: usize = CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT;
|
||||
const SINGLE_RANGE_END: usize = 18_000;
|
||||
const REUSE_END: usize = 19_000;
|
||||
const ALIAS_END: usize = 19_500;
|
||||
const ALIAS_COUNT: usize = ALIAS_END - REUSE_END;
|
||||
const OTC_SUCC_COUNT: usize = 500;
|
||||
|
||||
let valid_from_start = ymd_to_epoch_days(1970, 1, 1).expect("valid start");
|
||||
let reuse_end = ymd_to_epoch_days(2015, 6, 30).expect("valid reuse end");
|
||||
let reuse_resume = ymd_to_epoch_days(2016, 1, 1).expect("valid reuse resume");
|
||||
let in_range_start = ymd_to_epoch_days(1977, 1, 3).expect("valid in-range start");
|
||||
let in_range_end = ymd_to_epoch_days(2025, 12, 31).expect("valid in-range end");
|
||||
let in_range_span = (in_range_end - in_range_start + 1) as u64;
|
||||
let pre_1976_day = ymd_to_epoch_days(1975, 6, 15).expect("valid pre-1976 day");
|
||||
|
||||
let keys: Vec<String> = (0..KEY_COUNT).map(|i| format!("CA{i:05}")).collect();
|
||||
let otc_keys: Vec<String> = (0..OTC_SUCC_COUNT).map(|i| format!("OTC{i:05}")).collect();
|
||||
|
||||
let mut mapping_rows: Vec<ProviderMappingRow> =
|
||||
Vec::with_capacity(KEY_COUNT + (REUSE_END - SINGLE_RANGE_END) + OTC_SUCC_COUNT);
|
||||
for (i, key) in keys.iter().enumerate() {
|
||||
if i < SINGLE_RANGE_END {
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: None,
|
||||
listing_id: (i + 1) as i32,
|
||||
});
|
||||
} else if i < REUSE_END {
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: Some(reuse_end),
|
||||
listing_id: (i + 1) as i32,
|
||||
});
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: reuse_resume,
|
||||
valid_to: None,
|
||||
listing_id: (i + 100_001) as i32,
|
||||
});
|
||||
} else if i < ALIAS_END {
|
||||
let alias_lid = (i - REUSE_END + 1) as i32;
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: None,
|
||||
listing_id: alias_lid,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (i, otc_key) in otc_keys.iter().enumerate() {
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: otc_key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: None,
|
||||
listing_id: (500_001 + i) as i32,
|
||||
});
|
||||
}
|
||||
|
||||
let provider_mapping =
|
||||
ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping");
|
||||
|
||||
let mut rng = SplitMix64::new(CURATE_CORPORATE_ACTIONS_BENCH_SEED);
|
||||
let mut splits: Vec<(String, SplitActionEvent)> = Vec::with_capacity(events / 25 + 64);
|
||||
let mut dividends: Vec<(String, DividendActionEvent)> = Vec::with_capacity(events);
|
||||
let mut delistings: Vec<(String, DelistingOutcomeEvent<String>)> =
|
||||
Vec::with_capacity(events / 90 + 32);
|
||||
|
||||
let mut generated = 0usize;
|
||||
while generated < events {
|
||||
let r1 = rng.next_u64();
|
||||
let r2 = rng.next_u64();
|
||||
let kind_roll = r1 % 1_000;
|
||||
let is_pre_1976 = ((r1 >> 10) % 200) == 0;
|
||||
let ex_date = if is_pre_1976 {
|
||||
pre_1976_day
|
||||
} else {
|
||||
in_range_start + ((r2 % in_range_span) as i32)
|
||||
};
|
||||
|
||||
if kind_roll < 36 {
|
||||
// ~3.6% splits (~18.7k at 520k), including 1:1 no-ops and alias collisions.
|
||||
let is_alias_target = !is_pre_1976 && ((r1 >> 18) % 10) == 0;
|
||||
let key_idx = if is_alias_target {
|
||||
((r2 >> 24) as usize) % ALIAS_COUNT
|
||||
} else {
|
||||
((r2 >> 24) as usize) % KEY_COUNT
|
||||
};
|
||||
let is_noop = ((r1 >> 22) % 50) == 0;
|
||||
let ratio = if is_noop {
|
||||
1.0
|
||||
} else {
|
||||
SAMPLE_RATIOS[((r1 >> 28) as usize) % SAMPLE_RATIOS.len()]
|
||||
};
|
||||
let decl_roll = (r1 >> 36) % 100;
|
||||
let declared_date = if decl_roll < 80 {
|
||||
Some(ex_date - 21)
|
||||
} else if decl_roll < 98 {
|
||||
None
|
||||
} else {
|
||||
Some(ex_date + 3)
|
||||
};
|
||||
|
||||
let ev = SplitActionEvent {
|
||||
ex_date,
|
||||
ratio,
|
||||
declared_date,
|
||||
};
|
||||
splits.push((keys[key_idx].clone(), ev));
|
||||
generated += 1;
|
||||
|
||||
if is_alias_target && !is_noop && generated < events {
|
||||
let alias_key = keys[REUSE_END + key_idx].clone();
|
||||
let alias_ratio = if ((r1 >> 44) & 1) == 0 {
|
||||
ratio
|
||||
} else {
|
||||
ratio * 1.5
|
||||
};
|
||||
splits.push((
|
||||
alias_key,
|
||||
SplitActionEvent {
|
||||
ex_date,
|
||||
ratio: alias_ratio,
|
||||
declared_date,
|
||||
},
|
||||
));
|
||||
generated += 1;
|
||||
}
|
||||
} else if kind_roll < 990 {
|
||||
// ~95.4% dividends (~496k at 520k), USD/CAD, 0.0 drops, multi-dividends, alias dups.
|
||||
let key_idx = ((r2 >> 24) as usize) % KEY_COUNT;
|
||||
let is_zero = ((r1 >> 18) % 100) == 0;
|
||||
let cash = if is_zero {
|
||||
0.0
|
||||
} else {
|
||||
(((r1 >> 26) % 250) + 1) as f64 * 0.01
|
||||
};
|
||||
let currency = if ((r1 >> 34) & 3) == 0 { "CAD" } else { "USD" };
|
||||
let decl_roll = (r1 >> 38) % 100;
|
||||
let declared_date = if decl_roll < 80 {
|
||||
Some(ex_date - 21)
|
||||
} else if decl_roll < 98 {
|
||||
None
|
||||
} else {
|
||||
Some(ex_date + 3)
|
||||
};
|
||||
|
||||
dividends.push((
|
||||
keys[key_idx].clone(),
|
||||
DividendActionEvent {
|
||||
ex_date,
|
||||
cash,
|
||||
currency: currency.to_string(),
|
||||
declared_date,
|
||||
},
|
||||
));
|
||||
generated += 1;
|
||||
|
||||
if !is_zero && !is_pre_1976 && generated < events {
|
||||
if ((r1 >> 46) % 100) == 0 {
|
||||
// Same-key same-day special dividend.
|
||||
dividends.push((
|
||||
keys[key_idx].clone(),
|
||||
DividendActionEvent {
|
||||
ex_date,
|
||||
cash: cash * 2.0,
|
||||
currency: currency.to_string(),
|
||||
declared_date,
|
||||
},
|
||||
));
|
||||
generated += 1;
|
||||
} else if key_idx < ALIAS_COUNT && ((r1 >> 52) % 25) == 0 {
|
||||
// Identical cross-key alias dividend.
|
||||
dividends.push((
|
||||
keys[REUSE_END + key_idx].clone(),
|
||||
DividendActionEvent {
|
||||
ex_date,
|
||||
cash,
|
||||
currency: currency.to_string(),
|
||||
declared_date,
|
||||
},
|
||||
));
|
||||
generated += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// ~1.0% delistings (~5.2k at 520k): OTC transfers (valid/unmapped/self), -0.3, -1.0, none.
|
||||
let key_idx = ((r2 >> 24) as usize) % KEY_COUNT;
|
||||
let outcome_roll = (r1 >> 18) % 100;
|
||||
let ev = if outcome_roll < 35 {
|
||||
let succ_idx = ((r2 >> 40) as usize) % OTC_SUCC_COUNT;
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: ex_date,
|
||||
successor_key: Some(otc_keys[succ_idx].clone()),
|
||||
terminal_return: None,
|
||||
}
|
||||
} else if outcome_roll < 45 {
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: ex_date,
|
||||
successor_key: Some("OTC_UNMAPPED".to_string()),
|
||||
terminal_return: None,
|
||||
}
|
||||
} else if outcome_roll < 55 {
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: ex_date,
|
||||
successor_key: Some(keys[key_idx].clone()),
|
||||
terminal_return: None,
|
||||
}
|
||||
} else if outcome_roll < 75 {
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: ex_date,
|
||||
successor_key: None,
|
||||
terminal_return: Some(-0.3),
|
||||
}
|
||||
} else if outcome_roll < 90 {
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: ex_date,
|
||||
successor_key: None,
|
||||
terminal_return: Some(-1.0),
|
||||
}
|
||||
} else {
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: ex_date,
|
||||
successor_key: None,
|
||||
terminal_return: None,
|
||||
}
|
||||
};
|
||||
delistings.push((keys[key_idx].clone(), ev));
|
||||
generated += 1;
|
||||
}
|
||||
}
|
||||
|
||||
CurateCorporateActionsBenchFixture {
|
||||
splits,
|
||||
dividends,
|
||||
delistings,
|
||||
provider_mapping,
|
||||
key_count: KEY_COUNT,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_curate_corporate_actions_benchmark_tracked(
|
||||
events: usize,
|
||||
) -> Result<
|
||||
(CurateCorporateActionsBenchReport, PathBuf),
|
||||
crate::curate_corporate_actions::CurateCorporateActionsWriteError,
|
||||
> {
|
||||
use crate::curate_corporate_actions::{
|
||||
curate_corporate_actions, CurateCorporateActionsStats, CurateCorporateActionsWriteError,
|
||||
};
|
||||
|
||||
let temp = BenchTempDir::new_in_with_prefix(
|
||||
&std::env::temp_dir(),
|
||||
"curate-etl-bench-curate-corp-actions",
|
||||
)
|
||||
.map_err(|(path, source)| {
|
||||
CurateCorporateActionsWriteError::Parquet(ParquetCorporateActionsError::Io { path, source })
|
||||
})?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
if events == 0 {
|
||||
let mapping = ProviderMappingTable::default();
|
||||
let curated = curate_corporate_actions(
|
||||
std::iter::empty::<(String, SplitActionEvent)>(),
|
||||
std::iter::empty::<(String, DividendActionEvent)>(),
|
||||
std::iter::empty::<(String, DelistingOutcomeEvent<String>)>(),
|
||||
"qm",
|
||||
&mapping,
|
||||
)?;
|
||||
let write_stats = write_corporate_actions_dataset(
|
||||
&temp.path,
|
||||
&curated.rows,
|
||||
CorporateActionsWriteOptions::default(),
|
||||
)?;
|
||||
let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, 0)?;
|
||||
drop(temp);
|
||||
return Ok((
|
||||
CurateCorporateActionsBenchReport {
|
||||
events: 0,
|
||||
splits_in: 0,
|
||||
dividends_in: 0,
|
||||
delistings_in: 0,
|
||||
key_count: CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT,
|
||||
rows_out: 0,
|
||||
listings_out: 0,
|
||||
stage_elapsed_ms: 0.0,
|
||||
stage_events_per_sec: 0.0,
|
||||
stage_ns_per_event: 0.0,
|
||||
parquet_elapsed_ms: 0.0,
|
||||
parquet_rows_per_sec: 0.0,
|
||||
total_elapsed_ms: 0.0,
|
||||
total_events_per_sec: 0.0,
|
||||
files_written: write_stats.files_written,
|
||||
row_groups_written: write_stats.row_groups_written,
|
||||
bytes_written: write_stats.bytes_written,
|
||||
read_back_rows,
|
||||
checksum: 0,
|
||||
stats: CurateCorporateActionsStats::default(),
|
||||
},
|
||||
temp_path,
|
||||
));
|
||||
}
|
||||
|
||||
let fixture = build_curate_corporate_actions_bench_fixture(events);
|
||||
let splits_in = fixture.splits.len();
|
||||
let dividends_in = fixture.dividends.len();
|
||||
let delistings_in = fixture.delistings.len();
|
||||
let key_count = fixture.key_count;
|
||||
|
||||
// 1. Time pure in-memory curation stage.
|
||||
let stage_start = Instant::now();
|
||||
let curated = curate_corporate_actions(
|
||||
fixture.splits,
|
||||
fixture.dividends,
|
||||
fixture.delistings,
|
||||
"qm",
|
||||
&fixture.provider_mapping,
|
||||
)?;
|
||||
let stage_elapsed_secs = stage_start.elapsed().as_secs_f64();
|
||||
let stage_elapsed_ms = stage_elapsed_secs * 1_000.0;
|
||||
|
||||
let mut hash = 0u64;
|
||||
for row in &curated.rows {
|
||||
hash = mix_u64(hash, row.listing_id as u64);
|
||||
hash = mix_u64(hash, row.ex_date as u64);
|
||||
hash = mix_u64(hash, row.declared_date.map_or(u64::MAX, |d| d as u64));
|
||||
hash = mix_u64(hash, row.kind as u64);
|
||||
hash = mix_u64(hash, row.ratio.map_or(0, f64::to_bits));
|
||||
hash = mix_u64(hash, row.cash_amount.map_or(0, f64::to_bits));
|
||||
if let Some(curr) = row.currency.as_deref() {
|
||||
hash = mix_str_u64(hash, curr);
|
||||
}
|
||||
hash = mix_u64(
|
||||
hash,
|
||||
row.successor_listing_id.map_or(u64::MAX, |id| id as u64),
|
||||
);
|
||||
hash = mix_u64(hash, row.terminal_return.map_or(0, f64::to_bits));
|
||||
hash = mix_u64(hash, row.known_at_micros as u64);
|
||||
hash = mix_u64(hash, row.known_at_source as u64);
|
||||
}
|
||||
let checksum = black_box(hash);
|
||||
|
||||
// 2. Separately time Parquet write to temp dir.
|
||||
let parquet_start = Instant::now();
|
||||
let write_stats = write_corporate_actions_dataset(
|
||||
&temp.path,
|
||||
&curated.rows,
|
||||
CorporateActionsWriteOptions::default(),
|
||||
)?;
|
||||
let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64();
|
||||
let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0;
|
||||
|
||||
let read_back_rows =
|
||||
verify_parquet_corporate_actions_row_count(&temp.path, curated.rows.len())?;
|
||||
|
||||
let (stage_events_per_sec, stage_ns_per_event) = compute_rates(events, stage_elapsed_secs);
|
||||
let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs);
|
||||
let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs;
|
||||
let total_elapsed_ms = total_elapsed_secs * 1_000.0;
|
||||
let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs);
|
||||
|
||||
let report = CurateCorporateActionsBenchReport {
|
||||
events,
|
||||
splits_in,
|
||||
dividends_in,
|
||||
delistings_in,
|
||||
key_count,
|
||||
rows_out: curated.stats.rows_out,
|
||||
listings_out: curated.stats.listings_out,
|
||||
stage_elapsed_ms,
|
||||
stage_events_per_sec,
|
||||
stage_ns_per_event,
|
||||
parquet_elapsed_ms,
|
||||
parquet_rows_per_sec,
|
||||
total_elapsed_ms,
|
||||
total_events_per_sec,
|
||||
files_written: write_stats.files_written,
|
||||
row_groups_written: write_stats.row_groups_written,
|
||||
bytes_written: write_stats.bytes_written,
|
||||
read_back_rows,
|
||||
checksum,
|
||||
stats: curated.stats,
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
Ok((report, temp_path))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed `corporate_actions` curation stage + Zstd Parquet write benchmark for
|
||||
/// `events` source-keyed splits (~3.6%), USD/CAD dividends (~95.4%), and delisting outcomes
|
||||
/// (~1.0%) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps,
|
||||
/// aliases, unmapped/self successors, and pre-1976 dates.
|
||||
pub fn run_curate_corporate_actions_benchmark(
|
||||
events: usize,
|
||||
) -> Result<
|
||||
CurateCorporateActionsBenchReport,
|
||||
crate::curate_corporate_actions::CurateCorporateActionsWriteError,
|
||||
> {
|
||||
let (report, _) = run_curate_corporate_actions_benchmark_tracked(events)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -6274,4 +6722,96 @@ mod tests {
|
|||
assert_eq!(report.total_rows_per_sec, 0.0);
|
||||
assert_eq!(report.stats, crate::curate_fx::CurateFx1dStats::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() {
|
||||
let (a, dir_a) = run_curate_corporate_actions_benchmark_tracked(20_000).unwrap();
|
||||
let (b, dir_b) = run_curate_corporate_actions_benchmark_tracked(20_000).unwrap();
|
||||
|
||||
assert!(
|
||||
!dir_a.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_a.display()
|
||||
);
|
||||
assert!(
|
||||
!dir_b.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_b.display()
|
||||
);
|
||||
assert_eq!(a.events, 20_000);
|
||||
assert_eq!(a.splits_in + a.dividends_in + a.delistings_in, 20_000);
|
||||
assert_eq!(a.stats.builder.splits_in, a.splits_in);
|
||||
assert_eq!(a.stats.builder.dividends_in, a.dividends_in);
|
||||
assert_eq!(a.stats.builder.delistings_in, a.delistings_in);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.read_back_rows, a.rows_out);
|
||||
assert_eq!(a.listings_out, b.listings_out);
|
||||
assert_eq!(a.files_written, 1);
|
||||
assert_eq!(a.row_groups_written, b.row_groups_written);
|
||||
assert_eq!(a.bytes_written, b.bytes_written);
|
||||
assert!(a.bytes_written > 0);
|
||||
assert_eq!(a.stats, b.stats);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
assert!(a.stage_events_per_sec.is_finite() && a.stage_events_per_sec >= 0.0);
|
||||
assert!(a.stage_ns_per_event.is_finite() && a.stage_ns_per_event >= 0.0);
|
||||
assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0);
|
||||
assert!(a.total_events_per_sec.is_finite() && a.total_events_per_sec >= 0.0);
|
||||
|
||||
// Conservation invariants
|
||||
assert_eq!(a.stats.rows_in, a.stats.builder.rows_out);
|
||||
assert_eq!(
|
||||
a.stats.rows_in,
|
||||
a.stats.rows_out
|
||||
+ a.stats.dropped_unmapped
|
||||
+ a.stats.dropped_unmapped_successor
|
||||
+ a.stats.dropped_self_successor
|
||||
+ a.stats.dropped_known_at_out_of_range
|
||||
+ a.stats.listing_collision_collapsed
|
||||
+ a.stats.listing_collision_dropped
|
||||
);
|
||||
|
||||
// All major builder and curation counters exercised
|
||||
assert!(a.stats.builder.splits_out > 0);
|
||||
assert!(a.stats.builder.split_noops_dropped > 0);
|
||||
assert!(a.stats.builder.dividends_out > 0);
|
||||
assert!(a.stats.builder.dividend_zero_cash_dropped > 0);
|
||||
assert!(a.stats.builder.otc_delist_transfers_out > 0);
|
||||
assert!(a.stats.builder.delistings_out > 0);
|
||||
assert!(a.stats.builder.delist_without_outcome > 0);
|
||||
assert!(a.stats.dropped_unmapped > 0);
|
||||
assert!(a.stats.dropped_unmapped_successor > 0);
|
||||
assert!(a.stats.dropped_self_successor > 0);
|
||||
assert!(a.stats.dropped_known_at_out_of_range > 0);
|
||||
assert!(a.stats.listing_collision_collapsed > 0);
|
||||
assert!(a.stats.listing_collision_dropped > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_corporate_actions_benchmark_zero_events_handles_cleanly() {
|
||||
let (report, dir) = run_curate_corporate_actions_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.events, 0);
|
||||
assert_eq!(report.splits_in, 0);
|
||||
assert_eq!(report.dividends_in, 0);
|
||||
assert_eq!(report.delistings_in, 0);
|
||||
assert_eq!(report.rows_out, 0);
|
||||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.listings_out, 0);
|
||||
assert_eq!(report.files_written, 0);
|
||||
assert_eq!(report.row_groups_written, 0);
|
||||
assert_eq!(report.bytes_written, 0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.stage_elapsed_ms, 0.0);
|
||||
assert_eq!(report.stage_events_per_sec, 0.0);
|
||||
assert_eq!(report.stage_ns_per_event, 0.0);
|
||||
assert_eq!(report.parquet_elapsed_ms, 0.0);
|
||||
assert_eq!(report.parquet_rows_per_sec, 0.0);
|
||||
assert_eq!(report.total_elapsed_ms, 0.0);
|
||||
assert_eq!(report.total_events_per_sec, 0.0);
|
||||
assert_eq!(
|
||||
report.stats,
|
||||
crate::curate_corporate_actions::CurateCorporateActionsStats::default()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,12 +6,12 @@
|
|||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS,
|
||||
DEFAULT_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -37,6 +37,7 @@ pub enum CliAction {
|
|||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
BenchCurateFx(usize),
|
||||
BenchCurateCorporateActions(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -64,7 +65,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})"
|
||||
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
|
||||
{name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -91,7 +93,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]\n\
|
||||
{name} bench-curate-fx [rows]"
|
||||
{name} bench-curate-fx [rows]\n\
|
||||
{name} bench-curate-corporate-actions [events]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -286,6 +289,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()),
|
||||
["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions(
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
)),
|
||||
["bench-curate-corporate-actions", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateCorporateActions(n)),
|
||||
_ => Err(format!(
|
||||
"invalid event count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-corporate-actions", _, ..] => {
|
||||
Err("too many arguments for bench-curate-corporate-actions".to_string())
|
||||
}
|
||||
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -594,6 +609,7 @@ mod tests {
|
|||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
assert!(full.contains("bench-curate-fx"));
|
||||
assert!(full.contains("bench-curate-corporate-actions"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
|
|
@ -614,6 +630,7 @@ mod tests {
|
|||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
assert!(short.contains("bench-curate-fx"));
|
||||
assert!(short.contains("bench-curate-corporate-actions"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -665,4 +682,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-curate-fx", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_corporate_actions_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-corporate-actions"])),
|
||||
Ok(CliAction::BenchCurateCorporateActions(
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-corporate-actions", "20000"])),
|
||||
Ok(CliAction::BenchCurateCorporateActions(20_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "10", "20"])).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
439
tools/curate-etl/src/curate_corporate_actions.rs
Normal file
439
tools/curate-etl/src/curate_corporate_actions.rs
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
//! Pure, in-memory `corporate_actions` curation stage joining
|
||||
//! [`crate::corporate_actions::build_corporate_actions`],
|
||||
//! [`crate::provider_mapping::ProviderMappingTable`],
|
||||
//! [`crate::session_close::et_session_close_utc_micros`], and
|
||||
//! [`crate::parquet_corporate_actions::write_corporate_actions_dataset`] into contract
|
||||
//! [`CorporateActionsParquetRow`]s.
|
||||
//!
|
||||
//! # Contract & Point-in-Time Rules
|
||||
//! - Calls [`build_corporate_actions`] unchanged (drops `ratio == 1.0` split no-ops, `cash == 0.0`
|
||||
//! dividends, and delistings without an outcome; keeps same-key multi-dividends separate; clamps
|
||||
//! late declarations to `ex_date` with `KnownAtSource::ExDateFallback`).
|
||||
//! - Resolves each built row's `(mapping_source, key, ex_date) -> listing_id` via
|
||||
//! [`ProviderMappingTable::cursor_for`] / [`crate::provider_mapping::ProviderMappingCursor::resolve`]
|
||||
//! (one cursor per contiguous `key` run, since `build_corporate_actions` emits rows sorted by
|
||||
//! `key` then `ex_date`).
|
||||
//! - For [`CorporateActionKind::OtcDelistTransfer`] rows, resolves `successor_key` at the same
|
||||
//! `ex_date` (Pass 6 `effectiveDate`, the successor's first OTC trading date) to
|
||||
//! `successor_listing_id`. Unmapped successors (`dropped_unmapped_successor`) and successors that
|
||||
//! alias to the row's own `listing_id` (`dropped_self_successor`) are dropped—never emitted with
|
||||
//! `successor_listing_id = None` or a self-link.
|
||||
//! - Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of
|
||||
//! `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source
|
||||
//! corporate-action records carry no intraday announcement time). Dates outside
|
||||
//! `1976-01-01..=2030-12-31` drop into `dropped_known_at_out_of_range` without panicking.
|
||||
//! - Re-sorts mapped rows deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`)
|
||||
//! and resolves cross-`key` collisions:
|
||||
//! - `Split` groups on the same `(listing_id, ex_date)` with `> 1` distinct source key and `> 1`
|
||||
//! distinct `ratio` bit pattern drop the entire group (`listing_collision_dropped`).
|
||||
//! - Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies
|
||||
//! (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount
|
||||
//! same-day regular + special dividends) while deduplicating cross-key aliases.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cmp::Ordering;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
|
||||
DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent,
|
||||
};
|
||||
use crate::parquet_corporate_actions::{
|
||||
write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions,
|
||||
CorporateActionsWriteStats, ParquetCorporateActionsError,
|
||||
};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::session_close::et_session_close_utc_micros;
|
||||
|
||||
/// Accounting summary produced alongside [`CurateCorporateActionsOutput::rows`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `rows_in == builder.rows_out`
|
||||
/// - `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor
|
||||
/// + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`
|
||||
/// - `builder` independently satisfies all [`CorporateActionsStats`] conservation invariants.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct CurateCorporateActionsStats {
|
||||
pub builder: CorporateActionsStats,
|
||||
pub rows_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub listings_out: usize,
|
||||
pub dropped_unmapped: usize,
|
||||
pub dropped_unmapped_successor: usize,
|
||||
pub dropped_self_successor: usize,
|
||||
pub dropped_known_at_out_of_range: usize,
|
||||
pub listing_collision_collapsed: usize,
|
||||
pub listing_collision_dropped: usize,
|
||||
}
|
||||
|
||||
/// Output of [`curate_corporate_actions`]: contract Parquet rows sorted deterministically with
|
||||
/// non-decreasing `(listing_id, ex_date, kind)` plus full stage and builder stats.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateCorporateActionsOutput {
|
||||
pub rows: Vec<CorporateActionsParquetRow>,
|
||||
pub stats: CurateCorporateActionsStats,
|
||||
}
|
||||
|
||||
/// Typed caller errors returned by [`curate_corporate_actions`].
|
||||
///
|
||||
/// Bad single rows (unmapped keys/successors, self-successors, out-of-range `known_at_date`, and
|
||||
/// cross-key collisions) are dropped and counted in [`CurateCorporateActionsStats`] rather than
|
||||
/// aborting the stage.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum CurateCorporateActionsError {
|
||||
/// Error propagated from [`build_corporate_actions`] (e.g. non-positive split ratio).
|
||||
CorporateAction(CorporateActionError),
|
||||
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateCorporateActionsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::CorporateAction(err) => write!(f, "{err}"),
|
||||
Self::EmptyMappingSource => {
|
||||
write!(f, "mapping_source must not be empty or blank")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateCorporateActionsError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::CorporateAction(err) => Some(err),
|
||||
Self::EmptyMappingSource => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CorporateActionError> for CurateCorporateActionsError {
|
||||
fn from(err: CorporateActionError) -> Self {
|
||||
Self::CorporateAction(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Combined stats returned by [`curate_and_write_corporate_actions`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CurateCorporateActionsWriteReport {
|
||||
pub curate_stats: CurateCorporateActionsStats,
|
||||
pub write_stats: CorporateActionsWriteStats,
|
||||
}
|
||||
|
||||
/// Typed error returned by [`curate_and_write_corporate_actions`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateCorporateActionsWriteError {
|
||||
Curate(CurateCorporateActionsError),
|
||||
Parquet(ParquetCorporateActionsError),
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateCorporateActionsWriteError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Curate(err) => write!(f, "corporate_actions curation failed: {err}"),
|
||||
Self::Parquet(err) => write!(f, "corporate_actions Parquet write failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateCorporateActionsWriteError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Curate(err) => Some(err),
|
||||
Self::Parquet(err) => Some(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurateCorporateActionsError> for CurateCorporateActionsWriteError {
|
||||
fn from(err: CurateCorporateActionsError) -> Self {
|
||||
Self::Curate(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParquetCorporateActionsError> for CurateCorporateActionsWriteError {
|
||||
fn from(err: ParquetCorporateActionsError) -> Self {
|
||||
Self::Parquet(err)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn opt_f64_bits(value: Option<f64>) -> Option<u64> {
|
||||
value.map(f64::to_bits)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn intern_currency(currency: Option<String>) -> Option<Cow<'static, str>> {
|
||||
currency.map(|c| match c.as_str() {
|
||||
"USD" => Cow::Borrowed("USD"),
|
||||
"CAD" => Cow::Borrowed("CAD"),
|
||||
_ => Cow::Owned(c),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn cmp_parquet_row(a: &CorporateActionsParquetRow, b: &CorporateActionsParquetRow) -> Ordering {
|
||||
a.listing_id
|
||||
.cmp(&b.listing_id)
|
||||
.then_with(|| a.ex_date.cmp(&b.ex_date))
|
||||
.then_with(|| a.kind.cmp(&b.kind))
|
||||
.then_with(|| a.declared_date.cmp(&b.declared_date))
|
||||
.then_with(|| opt_f64_bits(a.ratio).cmp(&opt_f64_bits(b.ratio)))
|
||||
.then_with(|| opt_f64_bits(a.cash_amount).cmp(&opt_f64_bits(b.cash_amount)))
|
||||
.then_with(|| a.currency.as_deref().cmp(&b.currency.as_deref()))
|
||||
.then_with(|| a.successor_listing_id.cmp(&b.successor_listing_id))
|
||||
.then_with(|| opt_f64_bits(a.terminal_return).cmp(&opt_f64_bits(b.terminal_return)))
|
||||
.then_with(|| a.known_at_micros.cmp(&b.known_at_micros))
|
||||
.then_with(|| a.known_at_source.cmp(&b.known_at_source))
|
||||
}
|
||||
|
||||
/// Pure `corporate_actions` curation stage: validates and builds source-keyed splits, dividends,
|
||||
/// and delisting outcomes via [`build_corporate_actions`], resolves `(mapping_source, key,
|
||||
/// ex_date) -> listing_id` (and OTC transfer `successor_key` on `ex_date`) through
|
||||
/// `provider_mapping`, stamps `known_at_micros = et_session_close_utc_micros(known_at_date)`,
|
||||
/// compacts cross-key collisions, and emits contract [`CorporateActionsParquetRow`]s sorted
|
||||
/// deterministically with non-decreasing `(listing_id, ex_date, kind)`.
|
||||
pub fn curate_corporate_actions<K, S, D, L>(
|
||||
splits: S,
|
||||
dividends: D,
|
||||
delistings: L,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
) -> Result<CurateCorporateActionsOutput, CurateCorporateActionsError>
|
||||
where
|
||||
K: Ord + Clone + AsRef<str>,
|
||||
S: IntoIterator<Item = (K, SplitActionEvent)>,
|
||||
D: IntoIterator<Item = (K, DividendActionEvent)>,
|
||||
L: IntoIterator<Item = (K, DelistingOutcomeEvent<K>)>,
|
||||
{
|
||||
if mapping_source.trim().is_empty() {
|
||||
return Err(CurateCorporateActionsError::EmptyMappingSource);
|
||||
}
|
||||
|
||||
let built = build_corporate_actions(splits, dividends, delistings)?;
|
||||
|
||||
let mut stats = CurateCorporateActionsStats {
|
||||
builder: built.stats,
|
||||
rows_in: built.rows.len(),
|
||||
..CurateCorporateActionsStats::default()
|
||||
};
|
||||
|
||||
let mut tagged: Vec<(CorporateActionsParquetRow, usize)> = Vec::with_capacity(built.rows.len());
|
||||
|
||||
let mut current_key: Option<K> = None;
|
||||
let mut key_run_id: usize = 0;
|
||||
let mut cursor = mapping.cursor_for(mapping_source, "");
|
||||
|
||||
for row in built.rows {
|
||||
let key_changed = match ¤t_key {
|
||||
Some(prev) => *prev != row.key,
|
||||
None => true,
|
||||
};
|
||||
if key_changed {
|
||||
if current_key.is_some() {
|
||||
key_run_id += 1;
|
||||
}
|
||||
cursor = mapping.cursor_for(mapping_source, row.key.as_ref());
|
||||
current_key = Some(row.key);
|
||||
}
|
||||
|
||||
// Strict drop priority:
|
||||
// 1. Primary (mapping_source, key, ex_date) unmapped -> dropped_unmapped
|
||||
if cursor.ranges().is_empty() {
|
||||
stats.dropped_unmapped += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(listing_id) = cursor.resolve(row.ex_date) else {
|
||||
stats.dropped_unmapped += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
// 2. For otc_delist_transfer, resolve successor_key on ex_date (Pass 6 effectiveDate)
|
||||
let successor_listing_id = if row.kind == CorporateActionKind::OtcDelistTransfer {
|
||||
let Some(ref succ_key) = row.successor_key else {
|
||||
stats.dropped_unmapped_successor += 1;
|
||||
continue;
|
||||
};
|
||||
let Some(succ_id) = mapping.resolve(mapping_source, succ_key.as_ref(), row.ex_date)
|
||||
else {
|
||||
stats.dropped_unmapped_successor += 1;
|
||||
continue;
|
||||
};
|
||||
if succ_id == listing_id {
|
||||
stats.dropped_self_successor += 1;
|
||||
continue;
|
||||
}
|
||||
Some(succ_id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 3. Convert known_at_date to 16:00:00 ET UTC microseconds
|
||||
let Ok(known_at_micros) = et_session_close_utc_micros(row.known_at_date) else {
|
||||
stats.dropped_known_at_out_of_range += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
tagged.push((
|
||||
CorporateActionsParquetRow {
|
||||
listing_id,
|
||||
ex_date: row.ex_date,
|
||||
declared_date: row.declared_date,
|
||||
kind: row.kind,
|
||||
ratio: row.ratio,
|
||||
cash_amount: row.cash_amount,
|
||||
currency: intern_currency(row.currency),
|
||||
successor_listing_id,
|
||||
terminal_return: row.terminal_return,
|
||||
known_at_micros,
|
||||
known_at_source: row.known_at_source,
|
||||
},
|
||||
key_run_id,
|
||||
));
|
||||
}
|
||||
|
||||
tagged.sort_unstable_by(|a, b| cmp_parquet_row(&a.0, &b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
|
||||
let mut write_idx = 0usize;
|
||||
let mut read_idx = 0usize;
|
||||
let total_mapped = tagged.len();
|
||||
let mut last_listing_id: Option<i32> = None;
|
||||
|
||||
while read_idx < total_mapped {
|
||||
let listing_id = tagged[read_idx].0.listing_id;
|
||||
let ex_date = tagged[read_idx].0.ex_date;
|
||||
let kind = tagged[read_idx].0.kind;
|
||||
|
||||
let mut group_end = read_idx + 1;
|
||||
while group_end < total_mapped
|
||||
&& tagged[group_end].0.listing_id == listing_id
|
||||
&& tagged[group_end].0.ex_date == ex_date
|
||||
&& tagged[group_end].0.kind == kind
|
||||
{
|
||||
group_end += 1;
|
||||
}
|
||||
let group_len = group_end - read_idx;
|
||||
|
||||
// Cross-key conflicting split ratios on the same (listing_id, ex_date) drop the whole group.
|
||||
if kind == CorporateActionKind::Split && group_len > 1 {
|
||||
let first_key = tagged[read_idx].1;
|
||||
let first_ratio = opt_f64_bits(tagged[read_idx].0.ratio);
|
||||
let mut has_multi_key = false;
|
||||
let mut has_multi_ratio = false;
|
||||
for item in &tagged[read_idx + 1..group_end] {
|
||||
if item.1 != first_key {
|
||||
has_multi_key = true;
|
||||
}
|
||||
if opt_f64_bits(item.0.ratio) != first_ratio {
|
||||
has_multi_ratio = true;
|
||||
}
|
||||
if has_multi_key && has_multi_ratio {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if has_multi_key && has_multi_ratio {
|
||||
stats.listing_collision_dropped += group_len;
|
||||
read_idx = group_end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Compact contiguous runs of bitwise-identical rows: keep `max_per_key` copies so
|
||||
// same-key multi-dividends (including equal-amount regular + special) stay separate while
|
||||
// cross-key alias duplicates collapse cleanly.
|
||||
let mut run_start = read_idx;
|
||||
while run_start < group_end {
|
||||
let mut run_end = run_start + 1;
|
||||
while run_end < group_end
|
||||
&& cmp_parquet_row(&tagged[run_start].0, &tagged[run_end].0) == Ordering::Equal
|
||||
{
|
||||
run_end += 1;
|
||||
}
|
||||
let run_len = run_end - run_start;
|
||||
|
||||
let keep_count = if run_len == 1 {
|
||||
1
|
||||
} else {
|
||||
let mut max_per_key = 0usize;
|
||||
let mut cur_key = tagged[run_start].1;
|
||||
let mut cur_count = 1usize;
|
||||
for item in &tagged[run_start + 1..run_end] {
|
||||
if item.1 == cur_key {
|
||||
cur_count += 1;
|
||||
} else {
|
||||
if cur_count > max_per_key {
|
||||
max_per_key = cur_count;
|
||||
}
|
||||
cur_key = item.1;
|
||||
cur_count = 1;
|
||||
}
|
||||
}
|
||||
if cur_count > max_per_key {
|
||||
max_per_key = cur_count;
|
||||
}
|
||||
max_per_key
|
||||
};
|
||||
|
||||
stats.listing_collision_collapsed += run_len - keep_count;
|
||||
|
||||
for offset in 0..keep_count {
|
||||
let src_idx = run_start + offset;
|
||||
if write_idx != src_idx {
|
||||
tagged.swap(write_idx, src_idx);
|
||||
}
|
||||
write_idx += 1;
|
||||
}
|
||||
|
||||
if last_listing_id != Some(listing_id) {
|
||||
stats.listings_out += 1;
|
||||
last_listing_id = Some(listing_id);
|
||||
}
|
||||
|
||||
run_start = run_end;
|
||||
}
|
||||
|
||||
read_idx = group_end;
|
||||
}
|
||||
|
||||
tagged.truncate(write_idx);
|
||||
let rows: Vec<CorporateActionsParquetRow> = tagged.into_iter().map(|(row, _)| row).collect();
|
||||
stats.rows_out = rows.len();
|
||||
|
||||
Ok(CurateCorporateActionsOutput { rows, stats })
|
||||
}
|
||||
|
||||
/// Thin end-to-end wrapper running [`curate_corporate_actions`] and publishing the resulting
|
||||
/// contract rows via [`write_corporate_actions_dataset`] to
|
||||
/// `<out_dir>/corporate_actions/part.parquet`.
|
||||
///
|
||||
/// Any [`CurateCorporateActionsError`] returns before [`write_corporate_actions_dataset`] is
|
||||
/// invoked, leaving `out_dir` untouched.
|
||||
pub fn curate_and_write_corporate_actions<P, K, S, D, L>(
|
||||
out_dir: P,
|
||||
splits: S,
|
||||
dividends: D,
|
||||
delistings: L,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
options: CorporateActionsWriteOptions,
|
||||
) -> Result<CurateCorporateActionsWriteReport, CurateCorporateActionsWriteError>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
K: Ord + Clone + AsRef<str>,
|
||||
S: IntoIterator<Item = (K, SplitActionEvent)>,
|
||||
D: IntoIterator<Item = (K, DividendActionEvent)>,
|
||||
L: IntoIterator<Item = (K, DelistingOutcomeEvent<K>)>,
|
||||
{
|
||||
let curated = curate_corporate_actions(splits, dividends, delistings, mapping_source, mapping)?;
|
||||
let write_stats = write_corporate_actions_dataset(out_dir, &curated.rows, options)?;
|
||||
Ok(CurateCorporateActionsWriteReport {
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "curate_corporate_actions_tests.rs"]
|
||||
mod tests;
|
||||
1199
tools/curate-etl/src/curate_corporate_actions_tests.rs
Normal file
1199
tools/curate-etl/src/curate_corporate_actions_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -115,3 +115,10 @@ pub use curate_fx::{
|
|||
CurateFx1dStats, CurateFx1dWriteReport, CurateFxError, CurateFxWriteError,
|
||||
FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START,
|
||||
};
|
||||
|
||||
pub mod curate_corporate_actions;
|
||||
pub use curate_corporate_actions::{
|
||||
curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError,
|
||||
CurateCorporateActionsOutput, CurateCorporateActionsStats, CurateCorporateActionsWriteError,
|
||||
CurateCorporateActionsWriteReport,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_fx_benchmark,
|
||||
run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark,
|
||||
run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark,
|
||||
run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark,
|
||||
run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_corporate_actions_benchmark, run_curate_fx_benchmark, run_curate_shorts_benchmark,
|
||||
run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -694,6 +695,73 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateCorporateActions(events)) => {
|
||||
let report = match run_curate_corporate_actions_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-corporate-actions benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-corporate-actions");
|
||||
println!(
|
||||
" input: events={} splits={} dividends={} delistings={} keys={}",
|
||||
report.events,
|
||||
report.splits_in,
|
||||
report.dividends_in,
|
||||
report.delistings_in,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" builder: rows_out={} splits_out={} split_noops={} divs_out={} zero_div={} otc_out={} delist_out={} delist_no_outcome={}",
|
||||
report.stats.builder.rows_out,
|
||||
report.stats.builder.splits_out,
|
||||
report.stats.builder.split_noops_dropped,
|
||||
report.stats.builder.dividends_out,
|
||||
report.stats.builder.dividend_zero_cash_dropped,
|
||||
report.stats.builder.otc_delist_transfers_out,
|
||||
report.stats.builder.delistings_out,
|
||||
report.stats.builder.delist_without_outcome
|
||||
);
|
||||
println!(
|
||||
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.stage_elapsed_ms,
|
||||
report.stage_events_per_sec,
|
||||
report.stage_ns_per_event,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows,
|
||||
report.parquet_elapsed_ms,
|
||||
report.parquet_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s",
|
||||
report.total_elapsed_ms, report.total_events_per_sec
|
||||
);
|
||||
println!(
|
||||
" curate: unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={}",
|
||||
report.stats.dropped_unmapped,
|
||||
report.stats.dropped_unmapped_successor,
|
||||
report.stats.dropped_self_successor,
|
||||
report.stats.dropped_known_at_out_of_range,
|
||||
report.stats.listing_collision_collapsed,
|
||||
report.stats.listing_collision_dropped
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue