T-132: M2.2a — tools/curate-etl: pure point-in-time fundamentals builder (qmFinancials × qmFilings known_at link + statutory-lag fallback → bitemporal rows → 2D PIT snapshots + TTM) with restatement fixture test and local benchmark (no new crates)

This commit is contained in:
Studio 2026-12-01 00:43:53 -05:00
parent bf65712a38
commit be5bd1c38a
2 changed files with 173 additions and 75 deletions

View file

@ -33,10 +33,10 @@
//! (`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.
//! fiscal_period)` would become visible at or after an accepted 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"`.
@ -637,7 +637,6 @@ where
});
let mut rows: Vec<FundamentalsRow<K>> = Vec::with_capacity(candidates.len());
let mut surviving_indices: Vec<usize> = Vec::new();
let total = candidates.len();
let mut pe_start = 0usize;
@ -650,71 +649,82 @@ where
pe_end += 1;
}
// 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()
});
// Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for
// each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag
// estimate.
let mut max_accepted_rd_q: Option<i32> = None;
let mut max_accepted_rd_fy: Option<i32> = None;
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);
}
}
} else {
surviving_indices.extend(pe_start..pe_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_start = pe_start;
while g_start < pe_end {
let first = &candidates[g_start].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
while g_end < pe_end
&& candidates[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;
let all_identical = candidates[g_start + 1..g_end].iter().all(|other_cand| {
let other = &other_cand.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 {
if !all_identical {
stats.duplicate_conflict_dropped += group_len;
g_start = g_end;
continue;
}
let mut group_max_rd: Option<i32> = None;
let mut all_dated = true;
for cand in &candidates[g_start..g_end] {
match cand.report_date {
Some(rd) => {
group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd)));
}
None => all_dated = false,
}
}
let prior_max_rd = match first.fiscal_period {
FiscalPeriod::Quarterly => max_accepted_rd_q,
FiscalPeriod::Annual => max_accepted_rd_fy,
};
let is_stale_estimate = first.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG
&& all_dated
&& group_max_rd
.is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a));
if is_stale_estimate {
stats.observations_dropped_stale_estimate += group_len;
g_start = g_end;
continue;
}
if let Some(rd) = group_max_rd {
let slot = match first.fiscal_period {
FiscalPeriod::Quarterly => &mut max_accepted_rd_q,
FiscalPeriod::Annual => &mut max_accepted_rd_fy,
};
*slot = Some(slot.map_or(rd, |m| m.max(rd)));
}
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());
g_start = g_end;
}
@ -922,6 +932,7 @@ where
let key = &rows[order[idx]].key;
let mut visible_periods: BTreeMap<i32, ResolvedPeriod> = BTreeMap::new();
let mut visible_quarters: BTreeMap<i32, ResolvedPeriod> = BTreeMap::new();
let mut visible_annuals: BTreeMap<i32, ResolvedPeriod> = BTreeMap::new();
while idx < total && &rows[order[idx]].key == key {
let effective_ts = rows[order[idx]].known_at_utc_micros;
@ -931,27 +942,22 @@ where
&& rows[order[idx]].known_at_utc_micros == effective_ts
{
let row = &rows[order[idx]];
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));
}
let by_kind = match row.fiscal_period {
FiscalPeriod::Quarterly => &mut visible_quarters,
FiscalPeriod::Annual => &mut visible_annuals,
};
let resolved = match by_kind.get_mut(&row.period_end) {
Some(existing) => {
existing.apply_update(row);
existing.clone()
}
}
None => {
let created = ResolvedPeriod::from_row(row);
by_kind.insert(row.period_end, created.clone());
created
}
};
visible_periods.insert(row.period_end, resolved);
idx += 1;
}

View file

@ -815,6 +815,71 @@ fn stale_statutory_lag_estimate_does_not_overwrite_newer_filed_version() {
assert_eq!(edge_built.stats.rows_out, 4);
}
#[test]
fn conflicting_newer_filing_does_not_suppress_eligible_statutory_lag_estimate() {
let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]);
let q1_end = day(2024, 3, 31);
// Apr 30 observation (rev 100) has no same-day filing -> May 15 16:05 ET fallback.
// Two May 10 observations link to the same 10-Q with conflicting revenues (110 vs 112).
// Because the May 10 group is rejected as a duplicate conflict, it must NOT suppress the
// eligible Apr 30 statutory-lag estimate.
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),
),
obs(
"ACME",
q1_end,
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 5, 10)),
fields_rev(112.0),
),
];
let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues);
assert_reconciliation(&built);
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
assert_eq!(built.stats.observations_dropped_stale_estimate, 0);
assert_eq!(built.stats.rows_out, 1);
assert_eq!(built.stats.rows_linked_to_filing, 0);
assert_eq!(built.stats.rows_statutory_lag_estimate, 1);
// Input-order determinism
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();
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();
assert!(as_of(&snaps, "ACME", ts_may_10).is_none());
assert!(as_of(&snaps, "ACME", ts_may_15_fallback - 1).is_none());
let snap = as_of(&snaps, "ACME", ts_may_15_fallback).expect("fallback estimate must be visible");
assert_eq!(snap.effective_known_at_utc_micros, ts_may_15_fallback);
assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert!(snap.has_estimated_lag);
assert_eq!(snap.periods[0].period_end, q1_end);
assert_eq!(snap.periods[0].fields.revenue, Some(100.0));
}
#[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| {
@ -856,10 +921,25 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() {
shares_outstanding: Some(1_000.0),
},
),
// Partial FY amendment after the Q4 amendment -> should inherit original FY's OCF (15.0)
make_row(
q4_fy,
FiscalPeriod::Annual,
700,
KNOWN_AT_SOURCE_FILING_TIMESTAMP,
FundamentalsFields {
revenue: Some(102.0),
net_income: Some(10.2),
operating_cash_flow: None,
total_assets: Some(220.0),
total_equity: Some(90.0),
shares_outstanding: Some(1_000.0),
},
),
];
let snaps = build_fundamentals_snapshots(&rows, 4).unwrap();
assert_eq!(snaps.len(), 6);
assert_eq!(snaps.len(), 7);
// At t=400 (Q4 visible): TTM ends 2023-12-31 with revenue 100
let s4 = as_of(&snaps, "CAL", 400).unwrap();
@ -890,6 +970,18 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() {
assert_eq!(ttm6.flows.revenue, Some(105.0));
assert_eq!(ttm6.flows.operating_cash_flow, Some(15.0));
// At t=700 (partial FY amendment after Q4 amendment): inherits original FY's OCF (15.0) while
// TTM remains backed by the 4 standalone quarters (rev 105, OCF 15).
let s7 = as_of(&snaps, "CAL", 700).unwrap();
assert_eq!(s7.periods[0].period_end, q4_fy);
assert_eq!(s7.periods[0].fiscal_period, FiscalPeriod::Annual);
assert_eq!(s7.periods[0].fields.revenue, Some(102.0));
assert_eq!(s7.periods[0].fields.operating_cash_flow, Some(15.0));
let ttm7 = s7.ttm.as_ref().expect("TTM after partial FY amendment");
assert_eq!(ttm7.ending_period_end, q4_fy);
assert_eq!(ttm7.flows.revenue, Some(105.0));
assert_eq!(ttm7.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![