T-77: M1.2g — tools/curate-etl: pure events builder (qmFilings timefiled → UTC + form groups; qmEarnings linked to same-day filing or lagged to 16:05 ET) with local benchmark (no new crates)

This commit is contained in:
Studio 2026-11-27 22:45:41 -05:00
parent 3100ec65b1
commit 88a7e32db7
4 changed files with 189 additions and 19 deletions

View file

@ -142,14 +142,14 @@ Rules:
- Malformed strings (`filings_skipped_malformed_timestamp`), missing/unknown zones such as `PST`/`UTC`/`Z` (`filings_skipped_unknown_zone`), and invalid calendar dates or wall-clock times (`filings_skipped_invalid_date_time`) are skipped and counted without panicking.
- *Provenance caveat:* EDGAR filings accepted after `17:30 ET` are converted directly to UTC without next-business-day shifting (per the M1.2g contract); downstream intraday studies should apply exchange-session routing and post-`17:30 ET` visibility rules on top of `known_at_micros`.
2. **Table-driven form groups & periodic-report predicate (`classify_form_type`, `is_periodic_financial_report`):**
- Exact EDGAR codes (checked after stripping optional `/A` amendment suffix so `"4"` never matches `"40-F"`, `"424B5"`, or `"45-106F1"`): `10-K` (`"10-k"`), `10-Q` (`"10-q"`), `8-K` (`"8-k"`), `4` (`"4"`), `144` (`"144"`), `40-F` (`"40-f"`).
- Exact EDGAR codes (checked after stripping optional `/A` and standalone `Amended` markers such as `10-K (Amended)` so `"4"` never matches `"40-F"`, `"424B5"`, or `"45-106F1"`): `10-K` (`"10-k"`), `10-Q` (`"10-q"`), `8-K` (`"8-k"`), `4` (`"4"`), `144` (`"144"`), `40-F` (`"40-f"`).
- SEDAR+ substring rules in fixed priority order: `Interim financial statements/report` (`"interim_financial_statements"`), `Annual financial statements` (`"annual_financial_statements"`), `MD&A` (`"mda"`), `52-109` (`"52-109"`), `NI 43-101` (`"ni_43_101"`), `45-106F1` (`"45-106f1"`), `News release` (`"news_release"`). Everything else maps to `"other"`.
- Amendments (`/A` or `"amended"`) map to the same group with `is_amendment: true` and the raw `form_type` preserved in `payload_json`.
- Amendments (`/A` or standalone `"amended"`) map to the same group with `is_amendment: true` and the raw `form_type` preserved in `payload_json`.
- `is_periodic_financial_report` is `true` only for `10-K`, `10-Q`, `40-F`, `Interim financial statements`, and `Annual financial statements` (for the M2 `fundamentals_pit` filing join).
3. **Earnings linking & conservative `16:05 ET` lag (`kind = "earnings"`):**
- Precedence:
1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments) whose local ET calendar date matches `report_date` (including late-evening ET filings whose UTC date is the next day), `known_at_micros` = earliest such filing's UTC timestamp (`known_at_source = "filing_timestamp"`, deterministic tie-break on `(filing_id, form_type, url)`).
2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via `shorts::et_to_utc_micros` (`known_at_source = "statutory_lag_estimate"`, conservative T+1 open). This applies to `N/A`, `BTO`, and `AMC` alike whenever no linked filing provides a real timestamp—unlinked `BTO`/`AMC` rows are never stamped earlier than `16:05 ET`.
2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via `shorts::et_to_utc_micros` (`known_at_source = "statutory_lag_estimate"`). This fallback is intended for T+1 open use (not same-day intraday cutoffs, since a later same-date `8-K` or `News release` filing supersedes the fallback with its actual filing timestamp). It applies to `N/A`, `BTO`, and `AMC` alike whenever no linked filing provides a real timestamp—unlinked `BTO`/`AMC` rows are never stamped earlier than `16:05 ET`.
3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`) are skipped and counted in `earnings_skipped_out_of_range` (pre-2008 dates with a linked same-day filing still succeed).
- `ts_micros = known_at_micros`; `subtype` = normalized announce time (`"bto"` / `"amc"` / `"unknown"`).
- Post-hoc overwritten `consensusEps` is deliberately omitted from `QmEarning` and `payload_json` per `design/DATA-CONTRACTS.md` §1.

View file

@ -19,10 +19,12 @@
//! whose local ET calendar date matches `report_date`, `known_at_micros` is the earliest such
//! filing's UTC timestamp (`known_at_source = "filing_timestamp"`).
//! 2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via
//! [`crate::shorts::et_to_utc_micros`] (`known_at_source = "statutory_lag_estimate"`,
//! tradable T+1 open). This conservative fallback applies to `N/A`, `BTO`, and `AMC` rows
//! alike whenever no linked filing provides a verified timestamp—unlinked `BTO`/`AMC` rows
//! are never stamped earlier than `16:05 ET`.
//! [`crate::shorts::et_to_utc_micros`] (`known_at_source = "statutory_lag_estimate"`).
//! This conservative fallback is intended for T+1 open use (not same-day intraday cutoffs,
//! since a later same-date `8-K` / `News release` filing supersedes the fallback with its
//! actual filing timestamp). It applies to `N/A`, `BTO`, and `AMC` rows alike whenever no
//! linked filing provides a verified timestamp—unlinked `BTO`/`AMC` rows are never stamped
//! earlier than `16:05 ET`.
//! 3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`
//! (`2008-01-01..=2030-12-31`) are skipped and counted (`earnings_skipped_out_of_range`).
//! 4. Post-hoc overwritten `consensusEps` is deliberately omitted from [`QmEarning`] and
@ -256,11 +258,90 @@ const SEDAR_SUBSTRING_RULES: &[(&str, FilingFormGroup)] = &[
("NEWS RELEASE", FilingFormGroup::NewsRelease),
];
/// Returns `true` iff `upper` contains `"AMENDED"` as a standalone ASCII token (not embedded in a
/// longer word such as `"UNAMENDED"`).
fn contains_standalone_amended(upper: &str) -> bool {
let bytes = upper.as_bytes();
let needle = "AMENDED";
let mut offset = 0;
while let Some(rel) = upper[offset..].find(needle) {
let start = offset + rel;
let end = start + needle.len();
let left_ok = start == 0 || !bytes[start - 1].is_ascii_alphanumeric();
let right_ok = end == bytes.len() || !bytes[end].is_ascii_alphanumeric();
if left_ok && right_ok {
return true;
}
offset = start + 1;
}
false
}
/// Strips leading/trailing amendment markers (`/A`, `(AMENDED)`, or standalone `AMENDED` with
/// adjacent whitespace/punctuation separators) from an uppercased form label so exact EDGAR codes
/// such as `"10-K (Amended)"` or `"Amended 10-Q"` retain their underlying form group.
fn strip_amendment_markers(mut s: &str) -> (&str, bool) {
let mut stripped_any = false;
loop {
let trimmed = s.trim();
let next = if let Some(prefix) = trimmed.strip_suffix("/A") {
Some(prefix.trim_end())
} else if let Some(prefix) = trimmed.strip_suffix("(AMENDED)") {
Some(prefix.trim_end_matches(|c: char| {
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
}))
} else if let Some(suffix) = trimmed.strip_prefix("(AMENDED)") {
Some(suffix.trim_start_matches(|c: char| {
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
}))
} else if let Some(prefix) = trimmed.strip_suffix("AMENDED") {
if prefix
.as_bytes()
.last()
.is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'-' | b',' | b':'))
{
Some(prefix.trim_end_matches(|c: char| {
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
}))
} else {
None
}
} else if let Some(suffix) = trimmed.strip_prefix("AMENDED") {
if suffix
.as_bytes()
.first()
.is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'-' | b',' | b':'))
{
Some(suffix.trim_start_matches(|c: char| {
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
}))
} else {
None
}
} else {
None
};
match next {
Some(rest) => {
stripped_any = true;
s = rest;
}
None => {
s = trimmed;
break;
}
}
}
(s, stripped_any)
}
/// Classifies a raw `qmFilings.form_type` into `(FilingFormGroup, is_amendment)`.
///
/// - Trims ASCII whitespace and compares case-insensitively.
/// - Detects `/A` suffixes (e.g. `10-K/A`, `8-K/A`, `40-F/A`) and `"amended"` markers while
/// mapping amendments to the same underlying [`FilingFormGroup`].
/// - Detects and strips `/A` suffixes (e.g. `10-K/A`, `8-K/A`, `40-F/A`) and standalone
/// `"amended"` markers (e.g. `10-K (Amended)`, `10-Q - Amended`, `Amended 40-F`) before exact
/// EDGAR matching so amendments retain their underlying [`FilingFormGroup`].
/// - Checks exact EDGAR codes first, then SEDAR+ substring rules in fixed priority order,
/// defaulting to [`FilingFormGroup::Other`].
pub fn classify_form_type(form_type: &str) -> (FilingFormGroup, bool) {
@ -270,11 +351,8 @@ pub fn classify_form_type(form_type: &str) -> (FilingFormGroup, bool) {
}
let upper = trimmed.to_ascii_uppercase();
let (base, has_slash_a) = match upper.strip_suffix("/A") {
Some(prefix) => (prefix.trim_end(), true),
None => (upper.as_str(), false),
};
let is_amendment = has_slash_a || upper.contains("AMENDED");
let (base, stripped_amendment) = strip_amendment_markers(&upper);
let is_amendment = stripped_amendment || contains_standalone_amended(base);
for &(code, group) in EXACT_EDGAR_FORM_RULES {
if base == code {
@ -728,7 +806,9 @@ where
.then_with(|| a.report_date.cmp(&b.report_date))
});
rows.reserve(norm_earnings.len());
// Reserve only the exact upper bound for earnings rows so appending a small earnings batch
// onto a multi-million-row filings vector does not double the vector's capacity.
rows.reserve_exact(norm_earnings.len());
let len = norm_earnings.len();
let mut read_idx = 0usize;
while read_idx < len {
@ -953,15 +1033,21 @@ mod tests {
let cases = [
("10-K", FilingFormGroup::Form10K, false, true, false),
("10-K/A", FilingFormGroup::Form10K, true, true, false),
("10-K (Amended)", FilingFormGroup::Form10K, true, true, false),
("10-K/A (Amended)", FilingFormGroup::Form10K, true, true, false),
(" 10-q ", FilingFormGroup::Form10Q, false, true, false),
("10-Q/A", FilingFormGroup::Form10Q, true, true, false),
("10-Q - Amended", FilingFormGroup::Form10Q, true, true, false),
("8-K", FilingFormGroup::Form8K, false, false, true),
("8-K/A", FilingFormGroup::Form8K, true, false, true),
("8-K (Amended)", FilingFormGroup::Form8K, true, false, true),
("4", FilingFormGroup::Form4, false, false, false),
("4/A", FilingFormGroup::Form4, true, false, false),
("144", FilingFormGroup::Form144, false, false, false),
("40-F", FilingFormGroup::Form40F, false, true, false),
("40-F/A", FilingFormGroup::Form40F, true, true, false),
("Amended 40-F", FilingFormGroup::Form40F, true, true, false),
("UNAMENDED", FilingFormGroup::Other, false, false, false),
(
"Interim financial statements/report",
FilingFormGroup::InterimFinancials,

View file

@ -368,13 +368,17 @@ fn form_groups_and_periodic_predicate_cover_all_contract_forms() {
let cases = [
("10-K", FilingFormGroup::Form10K, "10-k", false, true),
("10-K/A", FilingFormGroup::Form10K, "10-k", true, true),
("10-K (Amended)", FilingFormGroup::Form10K, "10-k", true, true),
("10-Q", FilingFormGroup::Form10Q, "10-q", false, true),
("10-Q/A", FilingFormGroup::Form10Q, "10-q", true, true),
("10-Q - Amended", FilingFormGroup::Form10Q, "10-q", true, true),
("8-K", FilingFormGroup::Form8K, "8-k", false, false),
("8-K/A", FilingFormGroup::Form8K, "8-k", true, false),
("8-K (Amended)", FilingFormGroup::Form8K, "8-k", true, false),
("4", FilingFormGroup::Form4, "4", false, false),
("144", FilingFormGroup::Form144, "144", false, false),
("40-F", FilingFormGroup::Form40F, "40-f", false, true),
("Amended 40-F", FilingFormGroup::Form40F, "40-f", true, true),
(
"Interim financial statements/report",
FilingFormGroup::InterimFinancials,
@ -430,6 +434,37 @@ fn form_groups_and_periodic_predicate_cover_all_contract_forms() {
assert_eq!(normalize_announce_time(" amc "), "amc");
assert_eq!(normalize_announce_time("N/A"), "unknown");
assert_eq!(normalize_announce_time(""), "unknown");
// Regression: `10-K (Amended)` retains subtype `"10-k"` while preserving the raw label in JSON.
let amended_build = build_events(
vec![QmFiling {
key: 7_i32,
timefiled: "2025-03-03T16:15:00 EST".to_string(),
form_type: "10-K (Amended)".to_string(),
filing_id: Some("f-10k-amended".to_string()),
url: None,
}],
Vec::<QmEarning<i32>>::new(),
);
assert_accounting_and_order(&amended_build);
assert_eq!(amended_build.rows.len(), 1);
assert_eq!(amended_build.rows[0].subtype, "10-k");
let fields = parse_json_object(&amended_build.rows[0].payload_json);
assert_eq!(
fields,
vec![
(
"filing_id".to_string(),
JsonVal::Str("f-10k-amended".to_string())
),
(
"form_type".to_string(),
JsonVal::Str("10-K (Amended)".to_string())
),
("is_amendment".to_string(), JsonVal::Bool(true)),
("url".to_string(), JsonVal::Null),
]
);
}
#[test]

View file

@ -5,13 +5,15 @@
//! year-end cross-midnight filings,
//! - Cross-midnight ET calendar-date linking (`2024-12-31T21:30:00 EST` links to `2024-12-31`
//! while partitioning into UTC `year=2025`),
//! - Future poison-row no-look-ahead invariance (appending future filings, earnings, bad rows,
//! and conflicting duplicates never alters any earlier emitted row).
//! - Future-date poison-row stability (appending filings and earnings on later dates never alters
//! emitted rows from earlier dates), plus an explicit fixture showing that a same-date evening
//! filing replaces the `16:05 ET` fallback (which is intended for T+1 open use, not same-day
//! intraday cutoffs).
use curate_etl::bench::{run_events_benchmark, DEFAULT_EVENTS_BENCH_ROWS};
use curate_etl::{
build_events, parse_filing_timefiled, partition_year_utc, ymd_to_epoch_days, QmEarning,
QmFiling, EVENT_KIND_EARNINGS, KNOWN_AT_SOURCE_FILING_TIMESTAMP,
QmFiling, EVENT_KIND_EARNINGS, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG,
};
const MICROS_PER_SEC: i64 = 1_000_000;
@ -106,7 +108,7 @@ fn year_end_late_et_filing_links_by_et_date_and_partitions_by_utc_year() {
}
#[test]
fn appending_future_poison_filings_and_earnings_never_alters_earlier_rows() {
fn appending_future_date_poison_filings_and_earnings_never_alters_prior_dates() {
let cutoff_utc = oracle_utc_micros(2025, 3, 1, 0, 0, 0, 0);
let base_filings = vec![
@ -206,6 +208,53 @@ fn appending_future_poison_filings_and_earnings_never_alters_earlier_rows() {
assert_eq!(earlier, before.rows);
}
#[test]
fn same_date_late_filing_replaces_1605_fallback_across_intraday_cutoff() {
// The 16:05 ET fallback (`statutory_lag_estimate`) is intended for T+1 open use, not same-day
// intraday cutoffs: if a same-date qualifying filing arrives at 21:30 ET, link precedence
// moves the earnings timestamp from 16:05 ET (before a 17:00 ET intraday cutoff) to 21:30 ET
// (after that cutoff).
let report_date = day(2025, 2, 10);
let intraday_cutoff_utc = oracle_utc_micros(2025, 2, 10, 17, 0, 0, 5); // 17:00 EST = 22:00Z
let fallback_1605_utc = oracle_utc_micros(2025, 2, 10, 16, 5, 0, 5); // 16:05 EST = 21:05Z
let late_filing_utc = oracle_utc_micros(2025, 2, 10, 21, 30, 0, 5); // 21:30 EST = 02:30Z Feb 11
let earning = QmEarning {
key: 2_i32,
report_date,
announce_time: "AMC".to_string(),
fiscal_period_end: Some(day(2024, 12, 31)),
actual_eps: Some(2.2),
revenue: Some(80_000.0),
};
let without_filing = build_events(Vec::<QmFiling<i32>>::new(), vec![earning.clone()]);
assert_eq!(without_filing.rows.len(), 1);
let fallback_row = &without_filing.rows[0];
assert_eq!(fallback_row.known_at_micros, fallback_1605_utc);
assert_eq!(fallback_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert!(fallback_row.known_at_micros < intraday_cutoff_utc);
let with_late_filing = build_events(
vec![QmFiling {
key: 2_i32,
timefiled: "2025-02-10T21:30:00 EST".to_string(),
form_type: "8-K".to_string(),
filing_id: Some("f-late-8k".to_string()),
url: None,
}],
vec![earning],
);
let linked_row = with_late_filing
.rows
.iter()
.find(|r| r.kind == EVENT_KIND_EARNINGS)
.expect("earnings row present");
assert_eq!(linked_row.known_at_micros, late_filing_utc);
assert_eq!(linked_row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert!(linked_row.known_at_micros > intraday_cutoff_utc);
}
#[test]
fn default_bench_events_matches_readme_recorded_output() {
// README records rows_out=491190, filings_out=484531, earnings_out=6659, keys_out=20000,