diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 9bed4735..15034a84 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1564,14 +1564,14 @@ Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals. - Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`. - **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation` against periodic `events::QmFiling` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap` (`UsTsx` vs `TsxvCse`). - `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked. - - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. + - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. If a dated statutory-lag estimate for `(key, period_end, fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped (`observations_dropped_stale_estimate`) so an older vintage never rolls a newer filing backward. - **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field). - **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`. - **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`. - **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):** - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order. - Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate. - - Computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency. + - Resolves standalone quarterly versions separately from `FY` rows (so an annual report sharing December 31 with standalone `Q4` never erases `Q4` from TTM) and computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency. - `as_of(snapshots, key, as_of_micros)` performs an inclusive `O(log N)` binary search on `(key, effective_known_at_utc_micros)`. ### `bench-fundamentals` @@ -1582,11 +1582,10 @@ Fixed-seed (`SplitMix64`), offline benchmark exercising both venue classes, link cargo run -p curate-etl --release --offline -- bench-fundamentals [rows] ``` -Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0x078d99c42d5f200b`): +Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0xd5f693a28da4d1f0` hashing all row fields, ordered snapshot slots, TTM flows, and provenance): -- **Run 1:** Stage 1 `47.19 ms`, Stage 2 `35.75 ms`, total `82.94 ms` (`1,205,683 rows/s`, `829.41 ns/row`) -- **Run 2:** Stage 1 `43.89 ms`, Stage 2 `37.88 ms`, total `81.78 ms` (`1,222,862 rows/s`, `817.75 ns/row`) -- **500k scale check (`rows = 500000`, `filings = 395406`, `keys = 12500`, `rows_out = 485524`, `snapshots_out = 485518`, checksum `0x44fda3cd5f82ce5e`):** Stage 1 `277.89 ms`, Stage 2 `212.92 ms`, total `490.81 ms` (`1,018,714 rows/s`, `981.63 ns/row`) +- **Run 1:** Stage 1 `47.63 ms`, Stage 2 `41.81 ms`, total `89.44 ms` (`1,118,108 rows/s`, `894.37 ns/row`) +- **Run 2:** Stage 1 `44.34 ms`, Stage 2 `39.73 ms`, total `84.07 ms` (`1,189,459 rows/s`, `840.72 ns/row`) ## Exporting Input Files (`data-pipeline`) diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 89369cbb..aab8346a 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -11159,27 +11159,7 @@ pub fn run_fundamentals_benchmark( let total_elapsed_secs = rows_elapsed_secs + snaps_elapsed_secs; let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); - let mut hash = 0u64; - for row in &built.rows { - hash = mix_u64(hash, row.key as u64); - hash = mix_u64(hash, row.period_end as u64); - hash = mix_u64(hash, row.known_at_utc_micros as u64); - hash = mix_u64(hash, row.fiscal_period as u64); - hash = mix_u64(hash, row.fields.revenue.map_or(0, f64::to_bits)); - hash = mix_u64(hash, row.fields.total_assets.map_or(0, f64::to_bits)); - } - for snap in &snapshots { - hash = mix_u64(hash, snap.key as u64); - hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); - hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); - hash = mix_u64(hash, snap.periods.len() as u64); - if let Some(ttm) = &snap.ttm { - hash = mix_u64(hash, ttm.ending_period_end as u64); - hash = mix_u64(hash, ttm.flows.revenue.map_or(0, f64::to_bits)); - hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); - } - } - let checksum = black_box(hash); + let checksum = black_box(hash_fundamentals_outputs(&built.rows, &snapshots)); Ok(FundamentalsBenchReport { rows, @@ -11198,6 +11178,81 @@ pub fn run_fundamentals_benchmark( }) } +#[inline] +fn mix_opt_f64(hash: u64, value: Option) -> u64 { + match value { + None => mix_u64(hash, 0), + Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), + } +} + +#[inline] +fn mix_str(mut hash: u64, value: &str) -> u64 { + hash = mix_u64(hash, value.len() as u64); + for byte in value.bytes() { + hash = mix_u64(hash, u64::from(byte)); + } + hash +} + +#[inline] +fn mix_fundamentals_fields(mut hash: u64, fields: &FundamentalsFields) -> u64 { + hash = mix_opt_f64(hash, fields.revenue); + hash = mix_opt_f64(hash, fields.net_income); + hash = mix_opt_f64(hash, fields.operating_cash_flow); + hash = mix_opt_f64(hash, fields.total_assets); + hash = mix_opt_f64(hash, fields.total_equity); + hash = mix_opt_f64(hash, fields.shares_outstanding); + hash +} + +fn hash_fundamentals_outputs( + rows: &[crate::fundamentals::FundamentalsRow], + snapshots: &[crate::fundamentals::FundamentalsSnapshot], +) -> u64 { + let mut hash = 0u64; + for row in rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.period_end as u64); + hash = mix_u64(hash, row.fiscal_period as u64); + hash = mix_str(hash, &row.currency); + hash = mix_u64(hash, row.known_at_utc_micros as u64); + hash = mix_str(hash, row.known_at_source); + hash = mix_fundamentals_fields(hash, &row.fields); + } + for snap in snapshots { + hash = mix_u64(hash, snap.key as u64); + hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); + hash = mix_str(hash, snap.known_at_source); + hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); + hash = mix_u64(hash, snap.periods.len() as u64); + for slot in &snap.periods { + hash = mix_u64(hash, slot.period_end as u64); + hash = mix_u64(hash, slot.fiscal_period as u64); + hash = mix_str(hash, &slot.currency); + hash = mix_u64(hash, slot.known_at_utc_micros as u64); + hash = mix_str(hash, slot.known_at_source); + hash = mix_u64(hash, u64::from(slot.has_estimated_lag)); + hash = mix_fundamentals_fields(hash, &slot.fields); + } + match &snap.ttm { + None => { + hash = mix_u64(hash, 0); + } + Some(ttm) => { + hash = mix_u64(hash, 1); + hash = mix_u64(hash, ttm.ending_period_end as u64); + hash = mix_str(hash, &ttm.currency); + hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); + hash = mix_opt_f64(hash, ttm.flows.revenue); + hash = mix_opt_f64(hash, ttm.flows.net_income); + hash = mix_opt_f64(hash, ttm.flows.operating_cash_flow); + } + } + } + hash +} + #[cfg(test)] mod tests { use super::*; @@ -13366,11 +13421,70 @@ mod tests { + a.stats.observations_dropped_date_out_of_range + a.stats.observations_dropped_report_date_not_after_period_end + a.stats.observations_dropped_unanchored_vintage + + a.stats.observations_dropped_stale_estimate + a.stats.duplicate_collapsed + a.stats.duplicate_conflict_dropped ); } + #[test] + fn fundamentals_checksum_distinguishes_none_zero_slots_and_non_revenue_ttm() { + use crate::fundamentals::{ + FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, TtmFlowFields, + }; + + let base_slot = FundamentalsPeriodSlot { + period_end: 19_000, + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + known_at_utc_micros: 1_000, + known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + fields: FundamentalsFields { + revenue: Some(10.0), + net_income: None, + operating_cash_flow: Some(5.0), + total_assets: Some(100.0), + total_equity: Some(50.0), + shares_outstanding: Some(1_000.0), + }, + }; + let base_snap = FundamentalsSnapshot { + key: 1, + effective_known_at_utc_micros: 1_000, + known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + periods: vec![base_slot], + ttm: Some(FundamentalsTtm { + ending_period_end: 19_000, + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(40.0), + net_income: None, + operating_cash_flow: Some(20.0), + }, + has_estimated_lag: false, + }), + }; + + let h_base = hash_fundamentals_outputs(&[], &[base_snap.clone()]); + + // None vs Some(0.0) in slot net_income + let mut s_zero = base_snap.clone(); + s_zero.periods[0].fields.net_income = Some(0.0); + assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_zero])); + + // Non-revenue TTM flow change (operating_cash_flow) + let mut s_ttm = base_snap.clone(); + s_ttm.ttm.as_mut().unwrap().flows.operating_cash_flow = Some(21.0); + assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_ttm])); + + // Carried-forward slot provenance change + let mut s_prov = base_snap; + s_prov.periods[0].has_estimated_lag = true; + assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_prov])); + } + #[test] fn fundamentals_benchmark_zero_rows_handles_cleanly() { let report = run_fundamentals_benchmark(0).unwrap(); diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs index 44c72169..3c4cf629 100644 --- a/tools/curate-etl/src/fundamentals.rs +++ b/tools/curate-etl/src/fundamentals.rs @@ -32,6 +32,11 @@ //! `rd > lag_date`, it is dropped and counted as an unanchored vintage //! (`observations_dropped_unanchored_vintage`) rather than backdating `known_at` before its //! observed `report_date`. +//! - If a dated statutory-lag estimate (`report_date: Some(rd_a)`) for `(key, period_end, +//! fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, +//! `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped and counted +//! in `observations_dropped_stale_estimate` so an older vintage never rolls a newer filing +//! backward. //! - Otherwise `known_at_utc_micros` is `lag_date` at `16:05:00 America/Toronto` //! ([`FUNDAMENTALS_FALLBACK_HOUR_ET`]:[`FUNDAMENTALS_FALLBACK_MINUTE_ET`]) via //! [`crate::shorts::et_to_utc_micros`], tagged `known_at_source = "statutory_lag_estimate"`. @@ -56,7 +61,9 @@ //! with per-field provenance. //! - Emits the latest `k` visible periods in descending `period_end` order (annual rows may occupy //! slots; stock fields remain reported period values). -//! - Independently of `k`, computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, +//! - Independently of `k` and of annual (`FY`) rows sharing a `period_end` (such as a calendar +//! year-end `10-K` sharing December 31 with standalone `Q4`), resolves standalone quarterly +//! versions separately and computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, //! `operating_cash_flow`) from the 4 latest visible standalone quarterly periods when adjacent //! `period_end` spacing is within [`TTM_CONSECUTIVE_QUARTER_MIN_DAYS`]..=[`TTM_CONSECUTIVE_QUARTER_MAX_DAYS`] //! (`77..=105` calendar days, a heuristic given the input lacks a fiscal-quarter ordinal) and @@ -303,7 +310,7 @@ pub struct FundamentalsSnapshot { /// /// Conservation invariants: /// - Observations: -/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + duplicate_collapsed + duplicate_conflict_dropped` +/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + observations_dropped_stale_estimate + duplicate_collapsed + duplicate_conflict_dropped` /// - Output provenance: /// `rows_out == rows_linked_to_filing + rows_statutory_lag_estimate` /// - Filings: @@ -320,6 +327,7 @@ pub struct FundamentalsStats { pub observations_dropped_date_out_of_range: usize, pub observations_dropped_report_date_not_after_period_end: usize, pub observations_dropped_unanchored_vintage: usize, + pub observations_dropped_stale_estimate: usize, pub duplicate_collapsed: usize, pub duplicate_conflict_dropped: usize, pub filings_in: usize, @@ -417,6 +425,11 @@ struct ParsedPeriodicFiling { is_amendment: bool, } +struct CandidateRow { + row: FundamentalsRow, + report_date: Option, +} + /// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic /// filings, and per-listing statutory-lag venue classes. /// @@ -543,7 +556,7 @@ where }); } - let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); + let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); for obs in eligible_obs { let linked_micros = filing_index @@ -601,63 +614,111 @@ where (micros, KNOWN_AT_SOURCE_STATUTORY_LAG) }; - candidates.push(FundamentalsRow { - key: obs.key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - known_at_utc_micros, - known_at_source, - fields: obs.fields, + candidates.push(CandidateRow { + row: FundamentalsRow { + key: obs.key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + known_at_utc_micros, + known_at_source, + fields: obs.fields, + }, + report_date: obs.report_date, }); } candidates.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.period_end.cmp(&b.period_end)) - .then_with(|| a.known_at_utc_micros.cmp(&b.known_at_utc_micros)) + a.row + .key + .cmp(&b.row.key) + .then_with(|| a.row.period_end.cmp(&b.row.period_end)) + .then_with(|| a.row.known_at_utc_micros.cmp(&b.row.known_at_utc_micros)) }); let mut rows: Vec> = Vec::with_capacity(candidates.len()); + let mut surviving_indices: Vec = Vec::new(); let total = candidates.len(); - let mut idx = 0usize; + let mut pe_start = 0usize; - while idx < total { - let mut group_end = idx + 1; - while group_end < total - && candidates[group_end].key == candidates[idx].key - && candidates[group_end].period_end == candidates[idx].period_end - && candidates[group_end].known_at_utc_micros == candidates[idx].known_at_utc_micros + while pe_start < total { + let mut pe_end = pe_start + 1; + while pe_end < total + && candidates[pe_end].row.key == candidates[pe_start].row.key + && candidates[pe_end].row.period_end == candidates[pe_start].row.period_end { - group_end += 1; + pe_end += 1; } - let group_len = group_end - idx; - let first = &candidates[idx]; - let all_identical = candidates[idx + 1..group_end].iter().all(|other| { - first.fiscal_period == other.fiscal_period - && first.currency == other.currency - && first.known_at_source == other.known_at_source - && first.fields.bit_eq(&other.fields) - }); + // Drop dated statutory-lag estimates superseded by a newer dated version of the same + // `(key, period_end, fiscal_period)` that becomes visible at or before the fallback time. + let slice = &candidates[pe_start..pe_end]; + let has_dated_estimate = slice.len() > 1 + && slice.iter().any(|c| { + c.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG && c.report_date.is_some() + }); - if all_identical { - stats.duplicate_collapsed += group_len - 1; - if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { - stats.rows_linked_to_filing += 1; - } else { - stats.rows_statutory_lag_estimate += 1; + surviving_indices.clear(); + if has_dated_estimate { + for (rel_idx, cand) in slice.iter().enumerate() { + let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand.report_date.is_some_and(|rd_a| { + slice.iter().any(|other| { + other.row.fiscal_period == cand.row.fiscal_period + && other.report_date.is_some_and(|rd_b| rd_b > rd_a) + && other.row.known_at_utc_micros <= cand.row.known_at_utc_micros + }) + }); + if is_stale_estimate { + stats.observations_dropped_stale_estimate += 1; + } else { + surviving_indices.push(pe_start + rel_idx); + } } - if rows.last().is_none_or(|prev| prev.key != first.key) { - stats.keys_out += 1; - } - rows.push(first.clone()); } else { - stats.duplicate_conflict_dropped += group_len; + surviving_indices.extend(pe_start..pe_end); } - idx = group_end; + let mut g_start = 0usize; + while g_start < surviving_indices.len() { + let first_idx = surviving_indices[g_start]; + let first = &candidates[first_idx].row; + let mut g_end = g_start + 1; + while g_end < surviving_indices.len() + && candidates[surviving_indices[g_end]].row.known_at_utc_micros + == first.known_at_utc_micros + { + g_end += 1; + } + + let group_len = g_end - g_start; + let all_identical = surviving_indices[g_start + 1..g_end].iter().all(|&other_idx| { + let other = &candidates[other_idx].row; + first.fiscal_period == other.fiscal_period + && first.currency == other.currency + && first.known_at_source == other.known_at_source + && first.fields.bit_eq(&other.fields) + }); + + if all_identical { + stats.duplicate_collapsed += group_len - 1; + if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { + stats.rows_linked_to_filing += 1; + } else { + stats.rows_statutory_lag_estimate += 1; + } + if rows.last().is_none_or(|prev| prev.key != first.key) { + stats.keys_out += 1; + } + rows.push(first.clone()); + } else { + stats.duplicate_conflict_dropped += group_len; + } + + g_start = g_end; + } + + pe_start = pe_end; } stats.rows_out = rows.len(); @@ -770,12 +831,9 @@ fn sum_4_flows(values: [Option; 4]) -> Option { } } -fn compute_ttm(visible_periods: &BTreeMap) -> Option { +fn compute_ttm(visible_quarters: &BTreeMap) -> Option { let quarters: [&ResolvedPeriod; TTM_QUARTER_COUNT] = { - let mut iter = visible_periods - .values() - .rev() - .filter(|p| p.fiscal_period == FiscalPeriod::Quarterly); + let mut iter = visible_quarters.values().rev(); let q0 = iter.next()?; let q1 = iter.next()?; let q2 = iter.next()?; @@ -853,6 +911,7 @@ where .cmp(&rows[b].key) .then_with(|| rows[a].known_at_utc_micros.cmp(&rows[b].known_at_utc_micros)) .then_with(|| rows[a].period_end.cmp(&rows[b].period_end)) + .then_with(|| rows[a].fiscal_period.cmp(&rows[b].fiscal_period)) }); let mut snapshots: Vec> = Vec::new(); @@ -862,6 +921,7 @@ where while idx < total { let key = &rows[order[idx]].key; let mut visible_periods: BTreeMap = BTreeMap::new(); + let mut visible_quarters: BTreeMap = BTreeMap::new(); while idx < total && &rows[order[idx]].key == key { let effective_ts = rows[order[idx]].known_at_utc_micros; @@ -871,10 +931,25 @@ where && rows[order[idx]].known_at_utc_micros == effective_ts { let row = &rows[order[idx]]; - match visible_periods.get_mut(&row.period_end) { - Some(existing) => existing.apply_update(row), - None => { - visible_periods.insert(row.period_end, ResolvedPeriod::from_row(row)); + if row.fiscal_period == FiscalPeriod::Quarterly { + let resolved = match visible_quarters.get_mut(&row.period_end) { + Some(existing) => { + existing.apply_update(row); + existing.clone() + } + None => { + let created = ResolvedPeriod::from_row(row); + visible_quarters.insert(row.period_end, created.clone()); + created + } + }; + visible_periods.insert(row.period_end, resolved); + } else { + match visible_periods.get_mut(&row.period_end) { + Some(existing) => existing.apply_update(row), + None => { + visible_periods.insert(row.period_end, ResolvedPeriod::from_row(row)); + } } } idx += 1; @@ -886,7 +961,7 @@ where .take(k) .map(ResolvedPeriod::to_slot) .collect(); - let ttm = compute_ttm(&visible_periods); + let ttm = compute_ttm(&visible_quarters); let has_estimated_lag = periods.iter().any(|p| p.has_estimated_lag) || ttm.as_ref().is_some_and(|t| t.has_estimated_lag); let known_at_source = if has_estimated_lag { diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs index 1d9e0b9d..4afa3272 100644 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -76,6 +76,7 @@ fn assert_reconciliation(build: &FundamentalsBuild) { + s.observations_dropped_date_out_of_range + s.observations_dropped_report_date_not_after_period_end + s.observations_dropped_unanchored_vintage + + s.observations_dropped_stale_estimate + s.duplicate_collapsed + s.duplicate_conflict_dropped, "observation reconciliation failed: {s:?}" @@ -737,3 +738,171 @@ fn robustness_bad_rows_dedup_conflicts_and_input_order_determinism() { let snaps_b = build_fundamentals_snapshots(&built_rev.rows, 4).unwrap(); assert_eq!(snaps_a, snaps_b); } + +#[test] +fn stale_statutory_lag_estimate_does_not_overwrite_newer_filed_version() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + + // Apr 30 observation has no same-day periodic filing -> would fall back to May 15 16:05 ET. + // May 10 observation links to a 10-Q -> visible May 10 16:15 ET. + // Because Apr 30 is an older report vintage than May 10, the stale estimate must be dropped + // so revenue stays 110 at and after May 15 instead of reverting to 100. + let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; + let observations = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 4, 30)), + fields_rev(100.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(110.0), + ), + ]; + + let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 1); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + assert_eq!(built.stats.observations_dropped_stale_estimate, 1); + + // Input-order determinism with stale estimate present + let mut obs_rev = observations; + obs_rev.reverse(); + assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + assert_eq!(snaps.len(), 1); + + let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); + let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); + + for probe in [ts_may_10, ts_may_15_fallback, ts_may_15_fallback + 1_000_000] { + let snap = as_of(&snaps, "ACME", probe).expect("snapshot visible"); + assert_eq!(snap.effective_known_at_utc_micros, ts_may_10); + assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!snap.has_estimated_lag); + assert_eq!(snap.periods[0].period_end, q1_end); + assert_eq!(snap.periods[0].fields.revenue, Some(110.0)); + } + + // Edge cases: + // (a) An earlier estimate (Apr 30 -> May 15) followed by a LATER filing (Jun 1) is NOT stale. + // (b) A linked FY filing sharing Dec 31 does NOT suppress a standalone Q4 estimate. + let edge_filings = vec![ + filing("ACME", "2024-06-01T17:00:00 EDT", "10-Q/A"), + filing("ACME", "2024-02-12T16:15:00 EST", "10-K"), + ]; + let dec_31 = day(2023, 12, 31); + let edge_obs = vec![ + obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 4, 30)), fields_rev(100.0)), + obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 1)), fields_rev(115.0)), + obs("ACME", dec_31, FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 10)), fields_rev(40.0)), + obs("ACME", dec_31, FiscalPeriod::Annual, "USD", Some(day(2024, 2, 12)), fields_rev(160.0)), + ]; + let edge_built = build_fundamentals_rows(edge_obs, edge_filings, &venues); + assert_reconciliation(&edge_built); + assert_eq!(edge_built.stats.observations_dropped_stale_estimate, 0); + assert_eq!(edge_built.stats.rows_out, 4); +} + +#[test] +fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { + let make_row = |pe: i32, kind: FiscalPeriod, ts: i64, src: &'static str, fields: FundamentalsFields| { + FundamentalsRow { + key: "CAL".to_string(), + period_end: pe, + fiscal_period: kind, + currency: "USD".to_string(), + known_at_utc_micros: ts, + known_at_source: src, + fields, + } + }; + + let q1 = day(2023, 3, 31); + let q2 = day(2023, 6, 30); + let q3 = day(2023, 9, 30); + let q4_fy = day(2023, 12, 31); + + let rows = vec![ + make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), + // Later FY report sharing December 31 period_end + make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), + // Even later Q4 restatement omitting operating_cash_flow -> should inherit original Q4's OCF + make_row( + q4_fy, + FiscalPeriod::Quarterly, + 600, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + FundamentalsFields { + revenue: Some(45.0), + net_income: Some(4.5), + operating_cash_flow: None, + total_assets: Some(210.0), + total_equity: Some(85.0), + shares_outstanding: Some(1_000.0), + }, + ), + ]; + + let snaps = build_fundamentals_snapshots(&rows, 4).unwrap(); + assert_eq!(snaps.len(), 6); + + // At t=400 (Q4 visible): TTM ends 2023-12-31 with revenue 100 + let s4 = as_of(&snaps, "CAL", 400).unwrap(); + assert_eq!(s4.periods[0].period_end, q4_fy); + assert_eq!(s4.periods[0].fiscal_period, FiscalPeriod::Quarterly); + assert_eq!(s4.ttm.as_ref().unwrap().ending_period_end, q4_fy); + assert_eq!(s4.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); + + // At t=500 (FY shares 2023-12-31): latest slot is FY, while TTM still uses all 4 standalone quarters + let s5 = as_of(&snaps, "CAL", 500).unwrap(); + assert_eq!(s5.periods[0].period_end, q4_fy); + assert_eq!(s5.periods[0].fiscal_period, FiscalPeriod::Annual); + assert_eq!(s5.periods[0].fields.revenue, Some(100.0)); + let ttm5 = s5.ttm.as_ref().expect("TTM must survive FY sharing Dec 31"); + assert_eq!(ttm5.ending_period_end, q4_fy); + assert_eq!(ttm5.flows.revenue, Some(100.0)); + assert_eq!(ttm5.flows.net_income, Some(10.0)); + assert_eq!(ttm5.flows.operating_cash_flow, Some(15.0)); + + // At t=600 (Q4 restatement after FY): inherits original Q4's operating_cash_flow (6.0), TTM updates to 105 + let s6 = as_of(&snaps, "CAL", 600).unwrap(); + assert_eq!(s6.periods[0].period_end, q4_fy); + assert_eq!(s6.periods[0].fiscal_period, FiscalPeriod::Quarterly); + assert_eq!(s6.periods[0].fields.revenue, Some(45.0)); + assert_eq!(s6.periods[0].fields.operating_cash_flow, Some(6.0)); + let ttm6 = s6.ttm.as_ref().expect("TTM after Q4 restatement"); + assert_eq!(ttm6.ending_period_end, q4_fy); + assert_eq!(ttm6.flows.revenue, Some(105.0)); + assert_eq!(ttm6.flows.operating_cash_flow, Some(15.0)); + + // Provenance check: if Q4 was statutory_lag_estimate and later FY (filing_timestamp) occupies + // periods[0] on Dec 31, TTM still uses estimated Q4 so snapshot stays flagged estimated. + let rows_est_q4 = vec![ + make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(40.0)), + make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), + ]; + let snaps_est = build_fundamentals_snapshots(&rows_est_q4, 4).unwrap(); + let fy_snap = as_of(&snaps_est, "CAL", 500).unwrap(); + assert!(!fy_snap.periods[0].has_estimated_lag); + assert!(fy_snap.ttm.as_ref().unwrap().has_estimated_lag); + assert!(fy_snap.has_estimated_lag); + assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); +} diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 04d3c213..b211d86c 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -508,7 +508,7 @@ fn main() -> ExitCode { report.checksum ); println!( - " stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}", + " stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} obs_stale_est={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}", report.stats.rows_linked_to_filing, report.stats.rows_statutory_lag_estimate, report.stats.duplicate_collapsed, @@ -518,6 +518,7 @@ fn main() -> ExitCode { report.stats.observations_dropped_date_out_of_range, report.stats.observations_dropped_report_date_not_after_period_end, report.stats.observations_dropped_unanchored_vintage, + report.stats.observations_dropped_stale_estimate, report.stats.filings_eligible, report.stats.filings_ignored_non_periodic, report.stats.filings_dropped_invalid_timestamp,