diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 8f6b360c..7ac91470 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -811,12 +811,12 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows] 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 `split`, `dividend`, and terminal `delisting` rows. - - For `otc_delist_transfer` rows, Pass 6 anchors `ex_date` (and `known_at`) to `effectiveDate` (the successor's first OTC trading date), which normally falls after the outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` starts `2023-03-28`). The outgoing `listing_id` therefore resolves to the latest `provider_mapping` range for `(mapping_source, key)` with `valid_from <= ex_date`, while `successor_key` is resolved strictly on `ex_date` to `successor_listing_id`. Never emits an `otc_delist_transfer` with `successor_listing_id = None` or `successor_listing_id == listing_id`. + - For `otc_delist_transfer` rows, Pass 6 anchors `ex_date` (and `known_at`) to `effectiveDate` (the successor's first OTC trading date), which normally falls after the outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` starts `2023-03-28`) and may coincide with ticker reuse. Callers pass Pass 6's outgoing listing identity via `CurateDelistingInput::from_listing_id`: when `Some(expected_id)`, curation selects only a `provider_mapping` range for `(mapping_source, key)` with `valid_from <= ex_date` and `listing_id == expected_id` (never attaching to an unrelated ticker occupant); when `None`, lookup falls back to strict point-in-time `ex_date` resolution (never guessing an ended range). `successor_key` is always resolved strictly on `ex_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 covering `provider_mapping` range for `(mapping_source, key, ex_date)` (or, for `otc_delist_transfer`, no range with `valid_from <= ex_date`). + 1. `dropped_unmapped`: no covering `provider_mapping` range for `(mapping_source, key, ex_date)` (or, for `otc_delist_transfer` with `from_listing_id = Some(id)`, no range with `valid_from <= ex_date` matching `id`; or, for terminal `delisting` with `from_listing_id = Some(id)`, active occupant does not match `id`). 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. @@ -839,12 +839,12 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1 - 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=12886`, `unmapped_succ=511`, `self_succ=531`, `known_at_oor=2526`, `coll_collapsed=1398`, `coll_dropped=1854` +- 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=256.41 ms`, `throughput=2027993 events/s`, `latency=493.10 ns/event`, `checksum=0x0c22a1a1ab7caad4` - - Parquet write: `elapsed=127.16 ms`, `throughput=3888979 rows/s` - - Combined (stage → Parquet): `elapsed=383.57 ms`, `throughput=1355685 events/s` + - Stage (in-memory): `elapsed=287.50 ms`, `throughput=1808724 events/s`, `latency=552.88 ns/event`, `checksum=0x0c22a1a1ab7caad4` + - Parquet write: `elapsed=85.31 ms`, `throughput=5797014 rows/s` + - Combined (stage → Parquet): `elapsed=372.80 ms`, `throughput=1394845 events/s` - Run 2: - - Stage (in-memory): `elapsed=259.24 ms`, `throughput=2005895 events/s`, `latency=498.53 ns/event`, `checksum=0x0c22a1a1ab7caad4` - - Parquet write: `elapsed=126.13 ms`, `throughput=3920583 rows/s` - - Combined (stage → Parquet): `elapsed=385.37 ms`, `throughput=1349354 events/s` + - Stage (in-memory): `elapsed=281.40 ms`, `throughput=1847913 events/s`, `latency=541.15 ns/event`, `checksum=0x0c22a1a1ab7caad4` + - Parquet write: `elapsed=87.82 ms`, `throughput=5630801 rows/s` + - Combined (stage → Parquet): `elapsed=369.22 ms`, `throughput=1408366 events/s` diff --git a/tools/curate-etl/src/curate_corporate_actions.rs b/tools/curate-etl/src/curate_corporate_actions.rs index df89549c..c71c1b12 100644 --- a/tools/curate-etl/src/curate_corporate_actions.rs +++ b/tools/curate-etl/src/curate_corporate_actions.rs @@ -16,12 +16,16 @@ //! - For [`CorporateActionKind::OtcDelistTransfer`] rows, Pass 6 anchors `ex_date` (and `known_at`) //! to `effectiveDate` (the successor's first OTC trading date), which normally falls after the //! outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` -//! starts `2023-03-28`). The outgoing `listing_id` therefore resolves to the latest range for -//! `(mapping_source, key)` with `valid_from <= ex_date`, while `successor_key` is resolved -//! strictly on `ex_date` to `successor_listing_id`. Unmapped outgoing keys (`dropped_unmapped`), -//! 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. +//! starts `2023-03-28`) and may coincide with ticker reuse. Callers pass Pass 6's outgoing +//! listing identity via [`CurateDelistingInput::from_listing_id`]: when `Some(expected_id)`, +//! curation selects the `(mapping_source, key)` range with `valid_from <= ex_date` whose +//! `listing_id == expected_id` (so an unrelated occupant of `key` is never linked to the OTC +//! successor); when `None`, lookup falls back to strict point-in-time `ex_date` resolution +//! (never guessing an ended range). `successor_key` is always resolved strictly on `ex_date` to +//! `successor_listing_id`. Unmapped outgoing keys (`dropped_unmapped`), 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 @@ -163,10 +167,86 @@ impl From for CurateCorporateActionsWriteError { } } +/// Input delisting item for [`curate_corporate_actions`], pairing a source key and +/// [`DelistingOutcomeEvent`] with Pass 6's optional outgoing `listing_id` (`from_listing_id` in +/// `corporate_action_continuity`). +/// +/// Implements `From<(K, DelistingOutcomeEvent)>` (with `from_listing_id = None`) so existing +/// tuple iterators continue to work ergonomics-first while Pass 6 callers supply +/// `from_listing_id = Some(id)` to select/validate ended or reused outgoing ticker mappings. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateDelistingInput { + pub key: K, + pub event: DelistingOutcomeEvent, + pub from_listing_id: Option, +} + +impl CurateDelistingInput { + /// Creates a delisting input without an explicit Pass 6 outgoing `listing_id`. + #[inline] + pub fn new(key: K, event: DelistingOutcomeEvent) -> Self { + Self { + key, + event, + from_listing_id: None, + } + } + + /// Creates a delisting input carrying Pass 6's outgoing `from_listing_id`. + #[inline] + pub fn with_from_listing_id( + key: K, + from_listing_id: i32, + event: DelistingOutcomeEvent, + ) -> Self { + Self { + key, + event, + from_listing_id: Some(from_listing_id), + } + } +} + +impl From<(K, DelistingOutcomeEvent)> for CurateDelistingInput { + #[inline] + fn from((key, event): (K, DelistingOutcomeEvent)) -> Self { + Self::new(key, event) + } +} + +#[derive(Debug, Clone)] +struct DelistingIdentity { + key: K, + ex_date: i32, + kind: CorporateActionKind, + successor_key: Option, + terminal_return_bits: Option, + from_listing_id: Option, +} + #[inline] -fn resolve_on_or_before(ranges: &[MappingRange], date: i32) -> Option { - let idx = ranges.partition_point(|r| r.valid_from <= date); - idx.checked_sub(1).map(|i| ranges[i].listing_id) +fn cmp_delisting_identity(a: &DelistingIdentity, b: &DelistingIdentity) -> Ordering { + a.key + .cmp(&b.key) + .then_with(|| a.ex_date.cmp(&b.ex_date)) + .then_with(|| a.kind.cmp(&b.kind)) + .then_with(|| a.successor_key.cmp(&b.successor_key)) + .then_with(|| a.terminal_return_bits.cmp(&b.terminal_return_bits)) + .then_with(|| a.from_listing_id.cmp(&b.from_listing_id)) +} + +#[inline] +fn resolve_for_listing_on_or_before( + ranges: &[MappingRange], + date: i32, + expected_listing_id: i32, +) -> Option { + let end = ranges.partition_point(|r| r.valid_from <= date); + ranges[..end] + .iter() + .rev() + .find(|r| r.listing_id == expected_listing_id) + .map(|r| r.listing_id) } #[inline] @@ -205,7 +285,7 @@ fn cmp_parquet_row(a: &CorporateActionsParquetRow, b: &CorporateActionsParquetRo /// `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( +pub fn curate_corporate_actions( splits: S, dividends: D, delistings: L, @@ -216,13 +296,51 @@ where K: Ord + Clone + AsRef, S: IntoIterator, D: IntoIterator, - L: IntoIterator)>, + L: IntoIterator, + I: Into>, { if mapping_source.trim().is_empty() { return Err(CurateCorporateActionsError::EmptyMappingSource); } - let built = build_corporate_actions(splits, dividends, delistings)?; + let delistings_iter = delistings.into_iter(); + let delistings_hint = delistings_iter.size_hint().0; + let mut delistings_for_builder: Vec<(K, DelistingOutcomeEvent)> = + Vec::with_capacity(delistings_hint); + let mut delisting_identities: Vec> = Vec::with_capacity(delistings_hint); + + for raw in delistings_iter { + let item = raw.into(); + match (&item.event.successor_key, item.event.terminal_return) { + (Some(succ), None) => { + delisting_identities.push(DelistingIdentity { + key: item.key.clone(), + ex_date: item.event.delist_date, + kind: CorporateActionKind::OtcDelistTransfer, + successor_key: Some(succ.clone()), + terminal_return_bits: None, + from_listing_id: item.from_listing_id, + }); + } + (None, Some(raw_return)) => { + let norm = if raw_return == 0.0 { 0.0 } else { raw_return }; + delisting_identities.push(DelistingIdentity { + key: item.key.clone(), + ex_date: item.event.delist_date, + kind: CorporateActionKind::Delisting, + successor_key: None, + terminal_return_bits: Some(norm.to_bits()), + from_listing_id: item.from_listing_id, + }); + } + _ => {} + } + delistings_for_builder.push((item.key, item.event)); + } + + let built = build_corporate_actions(splits, dividends, delistings_for_builder)?; + delisting_identities.sort_unstable_by(cmp_delisting_identity); + let mut delisting_id_idx = 0usize; let mut stats = CurateCorporateActionsStats { builder: built.stats, @@ -237,6 +355,20 @@ where let mut cursor = mapping.cursor_for(mapping_source, ""); for row in built.rows { + let from_listing_id = match row.kind { + CorporateActionKind::OtcDelistTransfer | CorporateActionKind::Delisting => { + let ident = &delisting_identities[delisting_id_idx]; + debug_assert!(ident.key == row.key); + debug_assert_eq!(ident.ex_date, row.ex_date); + debug_assert_eq!(ident.kind, row.kind); + debug_assert!(ident.successor_key == row.successor_key); + debug_assert_eq!(ident.terminal_return_bits, opt_f64_bits(row.terminal_return)); + delisting_id_idx += 1; + ident.from_listing_id + } + CorporateActionKind::Split | CorporateActionKind::Dividend => None, + }; + let key_changed = match ¤t_key { Some(prev) => *prev != row.key, None => true, @@ -253,16 +385,22 @@ where // 1. Primary listing lookup -> dropped_unmapped. // For `OtcDelistTransfer`, Pass 6 anchors `ex_date` to the successor's first OTC // trading date (`effectiveDate`), after the outgoing listing's primary-venue mapping - // has typically ended (e.g. SIVB.US ends 2023-03-10, SIVBQ.US starts 2023-03-28), so - // resolve the outgoing listing as the latest range with `valid_from <= ex_date`. + // has typically ended (e.g. SIVB.US ends 2023-03-10, SIVBQ.US starts 2023-03-28) and + // possibly after ticker reuse. When Pass 6's `from_listing_id` is supplied, select + // only a range with `valid_from <= ex_date` matching `from_listing_id`; otherwise + // require an active range on `ex_date` (never guessing an ended occupant). if cursor.ranges().is_empty() { stats.dropped_unmapped += 1; continue; } - let primary_listing_id = if row.kind == CorporateActionKind::OtcDelistTransfer { - resolve_on_or_before(cursor.ranges(), row.ex_date) - } else { - cursor.resolve(row.ex_date) + let primary_listing_id = match (row.kind, from_listing_id) { + (CorporateActionKind::OtcDelistTransfer, Some(expected_id)) => { + resolve_for_listing_on_or_before(cursor.ranges(), row.ex_date, expected_id) + } + (CorporateActionKind::Delisting, Some(expected_id)) => { + cursor.resolve(row.ex_date).filter(|&id| id == expected_id) + } + _ => cursor.resolve(row.ex_date), }; let Some(listing_id) = primary_listing_id else { stats.dropped_unmapped += 1; @@ -429,7 +567,7 @@ where /// /// Any [`CurateCorporateActionsError`] returns before [`write_corporate_actions_dataset`] is /// invoked, leaving `out_dir` untouched. -pub fn curate_and_write_corporate_actions( +pub fn curate_and_write_corporate_actions( out_dir: P, splits: S, dividends: D, @@ -443,7 +581,8 @@ where K: Ord + Clone + AsRef, S: IntoIterator, D: IntoIterator, - L: IntoIterator)>, + L: IntoIterator, + I: Into>, { let curated = curate_corporate_actions(splits, dividends, delistings, mapping_source, mapping)?; let write_stats = write_corporate_actions_dataset(out_dir, &curated.rows, options)?; diff --git a/tools/curate-etl/src/curate_corporate_actions_tests.rs b/tools/curate-etl/src/curate_corporate_actions_tests.rs index 426707cc..1e3c4c85 100644 --- a/tools/curate-etl/src/curate_corporate_actions_tests.rs +++ b/tools/curate-etl/src/curate_corporate_actions_tests.rs @@ -93,8 +93,8 @@ fn div_ev( ) } -fn otc_ev(key: &str, delist_date: i32, successor_key: &str) -> (String, DelistingOutcomeEvent) { - ( +fn otc_ev(key: &str, delist_date: i32, successor_key: &str) -> CurateDelistingInput { + CurateDelistingInput::new( key.to_string(), DelistingOutcomeEvent { delist_date, @@ -104,8 +104,25 @@ fn otc_ev(key: &str, delist_date: i32, successor_key: &str) -> (String, Delistin ) } -fn term_ev(key: &str, delist_date: i32, terminal_return: f64) -> (String, DelistingOutcomeEvent) { - ( +fn otc_ev_from( + key: &str, + from_listing_id: i32, + delist_date: i32, + successor_key: &str, +) -> CurateDelistingInput { + CurateDelistingInput::with_from_listing_id( + key.to_string(), + from_listing_id, + DelistingOutcomeEvent { + delist_date, + successor_key: Some(successor_key.to_string()), + terminal_return: None, + }, + ) +} + +fn term_ev(key: &str, delist_date: i32, terminal_return: f64) -> CurateDelistingInput { + CurateDelistingInput::new( key.to_string(), DelistingOutcomeEvent { delist_date, @@ -115,8 +132,25 @@ fn term_ev(key: &str, delist_date: i32, terminal_return: f64) -> (String, Delist ) } -fn no_outcome_ev(key: &str, delist_date: i32) -> (String, DelistingOutcomeEvent) { - ( +fn term_ev_from( + key: &str, + from_listing_id: i32, + delist_date: i32, + terminal_return: f64, +) -> CurateDelistingInput { + CurateDelistingInput::with_from_listing_id( + key.to_string(), + from_listing_id, + DelistingOutcomeEvent { + delist_date, + successor_key: None, + terminal_return: Some(terminal_return), + }, + ) +} + +fn no_outcome_ev(key: &str, delist_date: i32) -> CurateDelistingInput { + CurateDelistingInput::new( key.to_string(), DelistingOutcomeEvent { delist_date, @@ -320,8 +354,8 @@ fn happy_path_all_kinds_est_edt_known_at_and_sources() { div_ev("RY.TO", d_edt_ex, 0.0, "CAD", None), ]; let delistings = vec![ - // SIVB -> SIVBQ OTC delist transfer on EDT date -> DelistDate - otc_ev("SIVB", d_sivb_otc, "SIVBQ"), + // SIVB (listing_id=30, ended Mar 10) -> SIVBQ (31) OTC delist transfer on EDT date -> DelistDate + otc_ev_from("SIVB", 30, d_sivb_otc, "SIVBQ"), // Terminal delisting -0.3 on EST date -> DelistDate term_ev("FAIL1", d_term_est, -0.3), // Terminal delisting -1.0 on EDT date -> DelistDate @@ -679,8 +713,9 @@ fn permutation_invariance_shuffled_and_reversed_inputs_match_bit_for_bit() { map_row("qm", "Z_KEY", day(2020, 1, 1), None, 10), map_row("qm", "A_KEY", day(2020, 1, 1), None, 20), map_row("qm", "A_ALIAS", day(2020, 1, 1), None, 20), - map_row("qm", "M_KEY", day(2020, 1, 1), None, 30), - map_row("qm", "M_SUCC", day(2020, 1, 1), None, 31), + map_row("qm", "M_KEY", day(2020, 1, 1), Some(d4 - 18), 30), + map_row("qm", "M_KEY", d4 - 5, None, 39), + map_row("qm", "M_SUCC", d4, None, 31), ]) .unwrap(); @@ -700,7 +735,8 @@ fn permutation_invariance_shuffled_and_reversed_inputs_match_bit_for_bit() { div_ev("M_KEY", d3, 0.75, "EUR", None), ]; let mut delistings = vec![ - otc_ev("M_KEY", d4, "M_SUCC"), + otc_ev_from("M_KEY", 30, d4, "M_SUCC"), + otc_ev_from("M_KEY", 999, d4, "M_SUCC"), term_ev("Z_KEY", d4, -0.30), otc_ev("A_KEY", d4, "A_ALIAS"), ]; @@ -914,7 +950,7 @@ fn parquet_round_trip_byte_identical_double_write_and_empty_input() { div_ev("RY.TO", d1, 1.42, "CAD", Some(d1 + 3)), ]; let delistings = vec![ - otc_ev("SIVB", d3, "SIVBQ"), + otc_ev_from("SIVB", 30, d3, "SIVBQ"), term_ev("FAIL", d4, -0.30), ]; @@ -1024,22 +1060,24 @@ fn otc_delist_transfer_resolves_ended_outgoing_listing_sivb_to_sivbq() { div_ev("SIVB.US", d_sivbq_start, 0.25, "USD", None), ]; let delistings = vec![ - // Real SIVB.US -> SIVBQ.US transfer: outgoing ended Mar 10, successor starts Mar 28. + // Real SIVB.US (listing_id=30, ended Mar 10) -> SIVBQ.US (31, starts Mar 28) transfer. + otc_ev_from("SIVB.US", 30, d_sivbq_start, "SIVBQ.US"), + // Same transfer without Pass 6 from_listing_id must not guess an ended range -> dropped_unmapped. otc_ev("SIVB.US", d_sivbq_start, "SIVBQ.US"), // Transfer before outgoing valid_from (1987-10-26) -> dropped_unmapped. - otc_ev("SIVB.US", d_sivb_start - 1, "SIVBQ.US"), + otc_ev_from("SIVB.US", 30, d_sivb_start - 1, "SIVBQ.US"), // Successor lookup remains strictly anchored to effectiveDate (Mar 28) -> dropped_unmapped_successor. - otc_ev("SIVB.US", d_sivbq_start, "SIVBQ_LATE.US"), + otc_ev_from("SIVB.US", 30, d_sivbq_start, "SIVBQ_LATE.US"), ]; let out = curate_corporate_actions(empty_splits(), dividends, delistings, "eod", &mapping) .unwrap(); assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 4); + assert_eq!(out.stats.rows_in, 5); assert_eq!(out.stats.rows_out, 1); assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.dropped_unmapped, 2); + assert_eq!(out.stats.dropped_unmapped, 3); assert_eq!(out.stats.dropped_unmapped_successor, 1); assert_eq!(out.stats.dropped_self_successor, 0); assert_eq!(out.stats.dropped_known_at_out_of_range, 0); @@ -1058,3 +1096,73 @@ fn otc_delist_transfer_resolves_ended_outgoing_listing_sivb_to_sivbq() { ); assert_eq!(row.known_at_source, KnownAtSource::DelistDate); } + +#[test] +fn otc_delist_transfer_never_attaches_to_unrelated_ticker_occupant() { + let d_halt = day(2023, 3, 10); + let d_reuse_early = day(2023, 3, 20); // Unrelated issuer takes over ticker before OTC date + let d_otc = day(2023, 3, 28); // Pass 6 effectiveDate (18 days after halt) + + let mapping = ProviderMappingTable::from_rows([ + // Case 1: Outgoing listing 30 ended Mar 10, unrelated listing 99 reused REUSE.US on Mar 20. + map_row("eod", "REUSE.US", day(2015, 1, 1), Some(d_halt), 30), + map_row("eod", "REUSE.US", d_reuse_early, None, 99), + map_row("eod", "REUSEQ.US", d_otc, None, 31), + // Case 2: Outgoing listing 40 is missing from provider_mapping; only an older unrelated + // occupant (listing 12, ended 2018) exists for OLD_ONLY.US. + map_row("eod", "OLD_ONLY.US", day(2010, 1, 1), Some(day(2018, 12, 31)), 12), + map_row("eod", "OLD_ONLYQ.US", d_otc, None, 41), + // Case 3: Outgoing listing 50 is missing from provider_mapping; only a newer unrelated + // occupant (listing 88, active on d_otc) exists for NEW_ONLY.US. + map_row("eod", "NEW_ONLY.US", d_reuse_early, None, 88), + map_row("eod", "NEW_ONLYQ.US", d_otc, None, 51), + ]) + .unwrap(); + + let delistings = vec![ + // Case 1: Must select outgoing listing 30 (NOT unrelated new occupant 99). + otc_ev_from("REUSE.US", 30, d_otc, "REUSEQ.US"), + // Case 2a: Outgoing listing 40 missing -> must drop, NOT attach to older occupant 12. + otc_ev_from("OLD_ONLY.US", 40, d_otc, "OLD_ONLYQ.US"), + // Case 2b: Same ticker without from_listing_id -> must drop, NOT guess older occupant 12. + otc_ev("OLD_ONLY.US", d_otc, "OLD_ONLYQ.US"), + // Case 3: Outgoing listing 50 missing -> must drop, NOT attach to active new occupant 88. + otc_ev_from("NEW_ONLY.US", 50, d_otc, "NEW_ONLYQ.US"), + // Case 4: Terminal delisting carrying wrong from_listing_id -> must drop, NOT attach to 88. + term_ev_from("NEW_ONLY.US", 50, d_otc, -1.0), + ]; + + let out = curate_corporate_actions( + empty_splits(), + empty_divs(), + delistings, + "eod", + &mapping, + ) + .unwrap(); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.rows_in, 5); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.stats.listings_out, 1); + assert_eq!(out.stats.dropped_unmapped, 4); + assert_eq!(out.stats.dropped_unmapped_successor, 0); + assert_eq!(out.stats.dropped_self_successor, 0); + + // Only the true outgoing listing 30 -> 31 transfer is emitted; no row for 12, 88, or 99. + assert_eq!(out.rows.len(), 1); + let row = &out.rows[0]; + assert_eq!(row.listing_id, 30); + assert_eq!(row.successor_listing_id, Some(31)); + assert_eq!(row.kind, CorporateActionKind::OtcDelistTransfer); + assert_eq!(row.ex_date, d_otc); + assert_eq!( + row.known_at_micros, + et_session_close_utc_micros(d_otc).unwrap() + ); + assert_eq!(row.known_at_source, KnownAtSource::DelistDate); + assert!(out + .rows + .iter() + .all(|r| r.listing_id != 12 && r.listing_id != 88 && r.listing_id != 99)); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index f26e4422..b4968493 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -120,5 +120,5 @@ pub mod curate_corporate_actions; pub use curate_corporate_actions::{ curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError, CurateCorporateActionsOutput, CurateCorporateActionsStats, CurateCorporateActionsWriteError, - CurateCorporateActionsWriteReport, + CurateCorporateActionsWriteReport, CurateDelistingInput, };