stock-bot/tools/curate-etl/src/fundamentals.rs

1030 lines
40 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Pure, in-memory point-in-time `fundamentals` builder (`qmFinancials` × `qmFilings` →
//! `fundamentals_bitemporal` rows → 2D `fundamentals_pit` snapshots + 4-quarter TTM).
//!
//! Aligned with `design/DATA-CONTRACTS.md` (§1 `qmFinancials`/`qmFilings` and §3A
//! `fundamentals_bitemporal` / `fundamentals_pit`):
//!
//! ## Stage 1 — Bitemporal Rows (`build_fundamentals_rows`)
//! - **Filing classification & timestamp parsing:** reuses [`crate::events::classify_form_type`],
//! [`FilingFormGroup::is_periodic_financial_report`], and
//! [`crate::events::parse_filing_timefiled`]. `10-Q` and SEDAR `Interim financial statements`
//! map to [`FiscalPeriod::Quarterly`]; `10-K`, `40-F`, and SEDAR `Annual financial statements`
//! map to [`FiscalPeriod::Annual`]. Non-periodic forms (such as `8-K`, `4`, `144`, `MD&A`,
//! `News release`) are never linked.
//! - **Heuristic filing-link rules (sampled `qmFilings` carries no statement-period field):**
//! - **Dated observation (`report_date: Some(rd)`):** `report_date` is assumed to identify the
//! observation's Eastern Time filing/vintage date. Links to the earliest matching periodic
//! filing (amended or unamended) for the same `(key, fiscal_period)` with `et_date == rd`
//! (strictly after `period_end`, because `rd <= period_end` is rejected). A same-day match can
//! anchor a late restatement/amendment beyond the inference windows below.
//! - **Undated observation (`report_date: None`):** links to the earliest matching
//! **non-amended** periodic filing for the same `(key, fiscal_period)` strictly after
//! `period_end` and within an inclusive calendar-day window of
//! [`QUARTERLY_FILING_LINK_WINDOW_DAYS`] (`75` days) for quarterly reports or
//! [`ANNUAL_FILING_LINK_WINDOW_DAYS`] (`150` days) for annual reports.
//! - Linked rows carry `known_at_utc_micros = parsed.utc_micros` and
//! `known_at_source = "filing_timestamp"`.
//! - **Statutory-lag fallback (unlinked observations):**
//! - `lag_date = period_end + venue.lag_days(fiscal_period)`:
//! - US & TSX ([`StatutoryLagVenue::UsTsx`]): `+45` calendar days (Q) / `+90` calendar days (FY).
//! - TSXV & CSE ([`StatutoryLagVenue::TsxvCse`]): `+60` calendar days (Q) / `+120` calendar days (FY).
//! - If a dated observation (`report_date: Some(rd)`) has no same-day filing link and
//! `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 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"`.
//! - **Calendar bounds & bad-row resilience:** statement `period_end`, optional `report_date`,
//! periodic filing Eastern days, and computed `lag_date` are validated against
//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`). Periodic filings
//! with `et_date <= earliest_period_end` for that `(key, fiscal_period)` are excluded and counted
//! in `filings_dropped_before_period_end`. Bad rows never panic; each category is counted in
//! [`FundamentalsStats`].
//! - **Normalization, deduplication & sort:** `-0.0` normalizes to `0.0`. Rows are sorted by
//! `(key, period_end, known_at_utc_micros)`. Bitwise-identical duplicates at the same
//! `(key, period_end, known_at_utc_micros)` collapse (`duplicate_collapsed`); conflicting groups
//! (differing values, currency, fiscal period, or provenance) are discarded entirely
//! (`duplicate_conflict_dropped`). Distinct `known_at_utc_micros` versions for the same
//! `(key, period_end)` are preserved as separate restatement versions.
//!
//! ## Stage 2 — 2D PIT Snapshots & TTM (`build_fundamentals_snapshots`, `as_of`)
//! - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates sharing
//! `(key, effective_known_at_utc_micros)` before emitting one [`FundamentalsSnapshot`].
//! - Maintains the latest visible version per `period_end`, carrying `None` fields forward from
//! the previous visible version of the **same** `(period_end, fiscal_period, currency)` along
//! 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` 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
//! all 4 share one currency. Missing flow inputs or non-finite sums produce `None` for that
//! field.
//! - Flags `has_estimated_lag = true` (and `known_at_source = "statutory_lag_estimate"`) if any
//! visible period slot or any quarter contributing to `ttm` used `statutory_lag_estimate`
//! (directly or via an inherited field).
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use crate::events::{
classify_form_type, parse_filing_timefiled, FilingFormGroup, QmFiling,
KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG,
};
use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE};
/// Statutory quarterly reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1).
pub const STATUTORY_LAG_US_TSX_QUARTERLY_DAYS: i32 = 45;
/// Statutory annual reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1).
pub const STATUTORY_LAG_US_TSX_ANNUAL_DAYS: i32 = 90;
/// Statutory quarterly reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1).
pub const STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS: i32 = 60;
/// Statutory annual reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1).
pub const STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS: i32 = 120;
/// Conservative fallback hour (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps.
pub const FUNDAMENTALS_FALLBACK_HOUR_ET: u8 = 16;
/// Conservative fallback minute (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps.
pub const FUNDAMENTALS_FALLBACK_MINUTE_ET: u8 = 5;
/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated
/// quarterly observations when `qmFilings` carries no statement-period field.
pub const QUARTERLY_FILING_LINK_WINDOW_DAYS: i32 = 75;
/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated
/// annual observations when `qmFilings` carries no statement-period field.
pub const ANNUAL_FILING_LINK_WINDOW_DAYS: i32 = 150;
/// Minimum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated
/// as consecutive for 4-quarter TTM summation.
pub const TTM_CONSECUTIVE_QUARTER_MIN_DAYS: i32 = 77;
/// Maximum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated
/// as consecutive for 4-quarter TTM summation.
pub const TTM_CONSECUTIVE_QUARTER_MAX_DAYS: i32 = 105;
/// Number of consecutive standalone quarters required to compute TTM flow sums.
pub const TTM_QUARTER_COUNT: usize = 4;
/// Fiscal statement period kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FiscalPeriod {
Quarterly,
Annual,
}
impl FiscalPeriod {
/// Canonical contract label (`"Q"` or `"FY"`).
#[inline]
pub const fn as_str(self) -> &'static str {
match self {
Self::Quarterly => "Q",
Self::Annual => "FY",
}
}
/// Inclusive heuristic link window in calendar days for undated observations.
#[inline]
pub const fn undated_link_window_days(self) -> i32 {
match self {
Self::Quarterly => QUARTERLY_FILING_LINK_WINDOW_DAYS,
Self::Annual => ANNUAL_FILING_LINK_WINDOW_DAYS,
}
}
}
/// Per-listing venue class governing statutory deadline lag fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StatutoryLagVenue {
/// US exchanges and Toronto Stock Exchange (`+45d` Q / `+90d` FY).
UsTsx,
/// TSX Venture Exchange and Canadian Securities Exchange (`+60d` Q / `+120d` FY).
TsxvCse,
}
impl StatutoryLagVenue {
/// Exact calendar-day statutory deadline lag for `(self, fiscal_period)`.
#[inline]
pub const fn lag_days(self, fiscal_period: FiscalPeriod) -> i32 {
match (self, fiscal_period) {
(Self::UsTsx, FiscalPeriod::Quarterly) => STATUTORY_LAG_US_TSX_QUARTERLY_DAYS,
(Self::UsTsx, FiscalPeriod::Annual) => STATUTORY_LAG_US_TSX_ANNUAL_DAYS,
(Self::TsxvCse, FiscalPeriod::Quarterly) => STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS,
(Self::TsxvCse, FiscalPeriod::Annual) => STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS,
}
}
}
/// Standardized numeric statement fields (single source of truth for Stage 1 and Stage 2).
///
/// Flow fields (`revenue`, `net_income`, `operating_cash_flow`) are summed across 4 consecutive
/// standalone quarters for TTM. Stock fields (`total_assets`, `total_equity`, `shares_outstanding`)
/// are point-in-time balance/count values and are never summed for TTM.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct FundamentalsFields {
// Flow fields (TTM-eligible)
pub revenue: Option<f64>,
pub net_income: Option<f64>,
pub operating_cash_flow: Option<f64>,
// Stock fields (never TTM-summed)
pub total_assets: Option<f64>,
pub total_equity: Option<f64>,
pub shares_outstanding: Option<f64>,
}
impl FundamentalsFields {
#[inline]
fn all_finite(&self) -> bool {
opt_is_finite(self.revenue)
&& opt_is_finite(self.net_income)
&& opt_is_finite(self.operating_cash_flow)
&& opt_is_finite(self.total_assets)
&& opt_is_finite(self.total_equity)
&& opt_is_finite(self.shares_outstanding)
}
#[inline]
fn normalize_zeros(self) -> Self {
Self {
revenue: self.revenue.map(normalize_zero),
net_income: self.net_income.map(normalize_zero),
operating_cash_flow: self.operating_cash_flow.map(normalize_zero),
total_assets: self.total_assets.map(normalize_zero),
total_equity: self.total_equity.map(normalize_zero),
shares_outstanding: self.shares_outstanding.map(normalize_zero),
}
}
#[inline]
fn bit_eq(&self, other: &Self) -> bool {
self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits)
&& self.net_income.map(f64::to_bits) == other.net_income.map(f64::to_bits)
&& self.operating_cash_flow.map(f64::to_bits)
== other.operating_cash_flow.map(f64::to_bits)
&& self.total_assets.map(f64::to_bits) == other.total_assets.map(f64::to_bits)
&& self.total_equity.map(f64::to_bits) == other.total_equity.map(f64::to_bits)
&& self.shares_outstanding.map(f64::to_bits)
== other.shares_outstanding.map(f64::to_bits)
}
}
/// 4-quarter trailing twelve months (TTM) sums for flow fields.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct TtmFlowFields {
pub revenue: Option<f64>,
pub net_income: Option<f64>,
pub operating_cash_flow: Option<f64>,
}
/// Precomputed 4-quarter TTM summary attached to a [`FundamentalsSnapshot`].
#[derive(Debug, Clone, PartialEq)]
pub struct FundamentalsTtm {
/// `period_end` epoch day of the latest (4th) quarter in the TTM window.
pub ending_period_end: i32,
/// Shared currency across all 4 contributing quarters.
pub currency: String,
/// Trailing 4-quarter sums for each flow field (`None` if any quarter lacks the field or if
/// the sum overflows to non-finite).
pub flows: TtmFlowFields,
/// `true` if any of the 4 contributing quarters used `statutory_lag_estimate` (directly or via
/// an inherited field).
pub has_estimated_lag: bool,
}
/// A single raw financial-statement observation input (`qmFinancials`-shaped, BSON-free).
#[derive(Debug, Clone, PartialEq)]
pub struct FinancialObservation<K = String> {
pub key: K,
/// Fiscal period end date as days since `1970-01-01` (UTC Gregorian).
pub period_end: i32,
pub fiscal_period: FiscalPeriod,
/// ISO currency code (e.g. `"USD"`, `"CAD"`).
pub currency: String,
/// Optional Eastern Time report/vintage date as days since `1970-01-01`.
pub report_date: Option<i32>,
pub fields: FundamentalsFields,
}
/// A single curated bitemporal fundamentals row matching `fundamentals_bitemporal` in
/// `design/DATA-CONTRACTS.md` §3A, sorted and unique by `(key, period_end, known_at_utc_micros)`.
#[derive(Debug, Clone, PartialEq)]
pub struct FundamentalsRow<K = String> {
pub key: K,
pub period_end: i32,
pub fiscal_period: FiscalPeriod,
pub currency: String,
pub known_at_utc_micros: i64,
pub known_at_source: &'static str,
pub fields: FundamentalsFields,
}
/// A single resolved period entry inside a [`FundamentalsSnapshot`].
#[derive(Debug, Clone, PartialEq)]
pub struct FundamentalsPeriodSlot {
pub period_end: i32,
pub fiscal_period: FiscalPeriod,
pub currency: String,
pub known_at_utc_micros: i64,
pub known_at_source: &'static str,
/// `true` if this period's latest version used `statutory_lag_estimate` or any field was
/// carried forward from an earlier `statutory_lag_estimate` version.
pub has_estimated_lag: bool,
pub fields: FundamentalsFields,
}
/// A single 2D point-in-time snapshot matching `fundamentals_pit` in `design/DATA-CONTRACTS.md`
/// §3A, keyed by `(key, effective_known_at_utc_micros)`.
#[derive(Debug, Clone, PartialEq)]
pub struct FundamentalsSnapshot<K = String> {
pub key: K,
pub effective_known_at_utc_micros: i64,
/// `"statutory_lag_estimate"` if [`Self::has_estimated_lag`] is `true`, otherwise
/// `"filing_timestamp"`.
pub known_at_source: &'static str,
/// `true` if any visible period slot or any quarter contributing to [`Self::ttm`] used
/// `statutory_lag_estimate` (directly or via an inherited field).
pub has_estimated_lag: bool,
/// Latest `k` visible periods ordered by `period_end` descending (`periods[0]` is latest).
pub periods: Vec<FundamentalsPeriodSlot>,
/// Precomputed 4-quarter TTM flow sums, computed independently of `k`.
pub ttm: Option<FundamentalsTtm>,
}
/// Summary accounting counters produced alongside [`FundamentalsBuild::rows`].
///
/// 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 + observations_dropped_stale_estimate + duplicate_collapsed + duplicate_conflict_dropped`
/// - Output provenance:
/// `rows_out == rows_linked_to_filing + rows_statutory_lag_estimate`
/// - Filings:
/// `filings_in == filings_eligible + filings_dropped_unknown_key + filings_ignored_non_periodic + filings_dropped_invalid_timestamp + filings_dropped_date_out_of_range + filings_dropped_before_period_end`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FundamentalsStats {
pub observations_in: usize,
pub rows_out: usize,
pub keys_out: usize,
pub rows_linked_to_filing: usize,
pub rows_statutory_lag_estimate: usize,
pub observations_dropped_unknown_key: usize,
pub observations_dropped_non_finite: usize,
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,
pub filings_eligible: usize,
pub filings_dropped_unknown_key: usize,
pub filings_ignored_non_periodic: usize,
pub filings_dropped_invalid_timestamp: usize,
pub filings_dropped_date_out_of_range: usize,
pub filings_dropped_before_period_end: usize,
}
/// Output of [`build_fundamentals_rows`]: sorted, unique bitemporal rows and reconciling stats.
#[derive(Debug, Clone, PartialEq)]
pub struct FundamentalsBuild<K = String> {
pub rows: Vec<FundamentalsRow<K>>,
pub stats: FundamentalsStats,
}
/// Typed caller errors returned by [`build_fundamentals_snapshots`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FundamentalsError {
/// Caller-supplied `k` (maximum periods retained per snapshot) was zero.
InvalidPeriodLimit { k: usize },
}
impl fmt::Display for FundamentalsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::InvalidPeriodLimit { k } => {
write!(f, "invalid snapshot period limit k={k}: must be >= 1")
}
}
}
}
impl Error for FundamentalsError {}
#[inline]
fn opt_is_finite(v: Option<f64>) -> bool {
v.is_none_or(f64::is_finite)
}
#[inline]
fn normalize_zero(v: f64) -> f64 {
if v == 0.0 {
0.0
} else {
v
}
}
#[inline]
fn is_supported_date(epoch_day: i32) -> bool {
(MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day)
}
#[inline]
fn periodic_group_to_fiscal_period(group: FilingFormGroup) -> Option<FiscalPeriod> {
if !group.is_periodic_financial_report() {
return None;
}
match group {
FilingFormGroup::Form10Q | FilingFormGroup::InterimFinancials => {
Some(FiscalPeriod::Quarterly)
}
FilingFormGroup::Form10K
| FilingFormGroup::Form40F
| FilingFormGroup::AnnualFinancials => Some(FiscalPeriod::Annual),
_ => None,
}
}
struct EligibleObservation<K> {
key: K,
period_end: i32,
fiscal_period: FiscalPeriod,
currency: String,
report_date: Option<i32>,
venue: StatutoryLagVenue,
fields: FundamentalsFields,
}
#[derive(Debug, Clone, Copy)]
struct IndexedFiling {
et_date: i32,
utc_micros: i64,
is_amendment: bool,
}
struct ParsedPeriodicFiling<K> {
key: K,
fiscal_period: FiscalPeriod,
et_date: i32,
utc_micros: i64,
is_amendment: bool,
}
struct CandidateRow<K> {
row: FundamentalsRow<K>,
report_date: Option<i32>,
}
/// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic
/// filings, and per-listing statutory-lag venue classes.
///
/// Any permutation of `observations` or `filings` yields bitwise-identical `rows` and `stats`.
pub fn build_fundamentals_rows<K, IO, IF>(
observations: IO,
filings: IF,
venues: &BTreeMap<K, StatutoryLagVenue>,
) -> FundamentalsBuild<K>
where
K: Ord + Clone,
IO: IntoIterator<Item = FinancialObservation<K>>,
IF: IntoIterator<Item = QmFiling<K>>,
{
let obs_iter = observations.into_iter();
let mut stats = FundamentalsStats::default();
let mut eligible_obs: Vec<EligibleObservation<K>> = Vec::with_capacity(obs_iter.size_hint().0);
let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new();
for obs in obs_iter {
stats.observations_in += 1;
let Some(&venue) = venues.get(&obs.key) else {
stats.observations_dropped_unknown_key += 1;
continue;
};
if !obs.fields.all_finite() {
stats.observations_dropped_non_finite += 1;
continue;
}
if !is_supported_date(obs.period_end)
|| obs.report_date.is_some_and(|rd| !is_supported_date(rd))
{
stats.observations_dropped_date_out_of_range += 1;
continue;
}
if obs.report_date.is_some_and(|rd| rd <= obs.period_end) {
stats.observations_dropped_report_date_not_after_period_end += 1;
continue;
}
earliest_period_by_key_kind
.entry((obs.key.clone(), obs.fiscal_period))
.and_modify(|min_pe| {
if obs.period_end < *min_pe {
*min_pe = obs.period_end;
}
})
.or_insert(obs.period_end);
eligible_obs.push(EligibleObservation {
key: obs.key,
period_end: obs.period_end,
fiscal_period: obs.fiscal_period,
currency: obs.currency,
report_date: obs.report_date,
venue,
fields: obs.fields.normalize_zeros(),
});
}
let filings_iter = filings.into_iter();
let mut parsed_filings: Vec<ParsedPeriodicFiling<K>> = Vec::new();
for filing in filings_iter {
stats.filings_in += 1;
if !venues.contains_key(&filing.key) {
stats.filings_dropped_unknown_key += 1;
continue;
}
let (group, is_amendment) = classify_form_type(&filing.form_type);
let Some(fiscal_period) = periodic_group_to_fiscal_period(group) else {
stats.filings_ignored_non_periodic += 1;
continue;
};
let Ok(parsed) = parse_filing_timefiled(&filing.timefiled) else {
stats.filings_dropped_invalid_timestamp += 1;
continue;
};
if !is_supported_date(parsed.et_date) {
stats.filings_dropped_date_out_of_range += 1;
continue;
}
parsed_filings.push(ParsedPeriodicFiling {
key: filing.key,
fiscal_period,
et_date: parsed.et_date,
utc_micros: parsed.utc_micros,
is_amendment,
});
}
let mut filing_index: BTreeMap<(K, FiscalPeriod), Vec<IndexedFiling>> = BTreeMap::new();
for pf in parsed_filings {
let key_kind = (pf.key, pf.fiscal_period);
if let Some(&min_pe) = earliest_period_by_key_kind.get(&key_kind) {
if pf.et_date <= min_pe {
stats.filings_dropped_before_period_end += 1;
continue;
}
}
stats.filings_eligible += 1;
filing_index.entry(key_kind).or_default().push(IndexedFiling {
et_date: pf.et_date,
utc_micros: pf.utc_micros,
is_amendment: pf.is_amendment,
});
}
for bucket in filing_index.values_mut() {
bucket.sort_unstable_by(|a, b| {
a.et_date
.cmp(&b.et_date)
.then_with(|| a.utc_micros.cmp(&b.utc_micros))
.then_with(|| a.is_amendment.cmp(&b.is_amendment))
});
}
let mut candidates: Vec<CandidateRow<K>> = Vec::with_capacity(eligible_obs.len());
for obs in eligible_obs {
let linked_micros = filing_index
.get(&(obs.key.clone(), obs.fiscal_period))
.and_then(|bucket| match obs.report_date {
Some(rd) => {
// Earliest matching periodic filing (amended or unamended) on Eastern day `rd`.
// `rd > obs.period_end` is guaranteed by validation above.
let pos = bucket.partition_point(|f| f.et_date < rd);
bucket
.get(pos)
.filter(|f| f.et_date == rd)
.map(|f| f.utc_micros)
}
None => {
// Earliest matching non-amended periodic filing strictly after `period_end`
// and within the inclusive calendar-day inference window.
let window_end = i64::from(obs.period_end)
+ i64::from(obs.fiscal_period.undated_link_window_days());
let pos = bucket.partition_point(|f| f.et_date <= obs.period_end);
bucket[pos..]
.iter()
.take_while(|f| i64::from(f.et_date) <= window_end)
.find(|f| !f.is_amendment)
.map(|f| f.utc_micros)
}
});
let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros {
(micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP)
} else {
let lag_days = obs.venue.lag_days(obs.fiscal_period);
let lag_date_i64 = i64::from(obs.period_end) + i64::from(lag_days);
if let Some(rd) = obs.report_date {
if i64::from(rd) > lag_date_i64 {
stats.observations_dropped_unanchored_vintage += 1;
continue;
}
}
let Ok(lag_date) = i32::try_from(lag_date_i64) else {
stats.observations_dropped_date_out_of_range += 1;
continue;
};
let Ok(micros) = et_to_utc_micros(
lag_date,
FUNDAMENTALS_FALLBACK_HOUR_ET,
FUNDAMENTALS_FALLBACK_MINUTE_ET,
0,
) else {
stats.observations_dropped_date_out_of_range += 1;
continue;
};
(micros, KNOWN_AT_SOURCE_STATUTORY_LAG)
};
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.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<FundamentalsRow<K>> = Vec::with_capacity(candidates.len());
let mut survivors: Vec<usize> = Vec::new();
let total = candidates.len();
let mut pe_start = 0usize;
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
{
pe_end += 1;
}
// 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;
let mut g_start = pe_start;
while g_start < pe_end {
let group_ts = candidates[g_start].row.known_at_utc_micros;
let mut g_end = g_start + 1;
while g_end < pe_end && candidates[g_end].row.known_at_utc_micros == group_ts {
g_end += 1;
}
// Filter out stale dated statutory-lag candidates before duplicate/conflict checks
// so a superseded estimate cannot cause an eligible estimate at the same fallback
// timestamp to be rejected as conflicting.
survivors.clear();
for idx in g_start..g_end {
let cand = &candidates[idx];
let prior_max_rd = match cand.row.fiscal_period {
FiscalPeriod::Quarterly => max_accepted_rd_q,
FiscalPeriod::Annual => max_accepted_rd_fy,
};
let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG
&& cand
.report_date
.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 += 1;
} else {
survivors.push(idx);
}
}
if survivors.is_empty() {
g_start = g_end;
continue;
}
let first = &candidates[survivors[0]].row;
let all_identical = survivors[1..].iter().all(|&idx| {
let other = &candidates[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_conflict_dropped += survivors.len();
g_start = g_end;
continue;
}
let mut group_max_rd: Option<i32> = None;
for &idx in &survivors {
if let Some(rd) = candidates[idx].report_date {
group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd)));
}
}
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 += survivors.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;
}
pe_start = pe_end;
}
stats.rows_out = rows.len();
FundamentalsBuild { rows, stats }
}
#[derive(Clone)]
struct ResolvedPeriod {
period_end: i32,
fiscal_period: FiscalPeriod,
currency: String,
known_at_utc_micros: i64,
known_at_source: &'static str,
fields: FundamentalsFields,
/// Per-field flag: `true` iff that `Some` field originated from a `statutory_lag_estimate` row.
field_estimated: [bool; 6],
}
impl ResolvedPeriod {
#[inline]
fn from_row<K>(row: &FundamentalsRow<K>) -> Self {
let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG;
let fields = row.fields.normalize_zeros();
let field_estimated = [
est && fields.revenue.is_some(),
est && fields.net_income.is_some(),
est && fields.operating_cash_flow.is_some(),
est && fields.total_assets.is_some(),
est && fields.total_equity.is_some(),
est && fields.shares_outstanding.is_some(),
];
Self {
period_end: row.period_end,
fiscal_period: row.fiscal_period,
currency: row.currency.clone(),
known_at_utc_micros: row.known_at_utc_micros,
known_at_source: row.known_at_source,
fields,
field_estimated,
}
}
#[inline]
fn apply_update<K>(&mut self, row: &FundamentalsRow<K>) {
if self.fiscal_period != row.fiscal_period || self.currency != row.currency {
*self = Self::from_row(row);
return;
}
let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG;
let incoming = row.fields.normalize_zeros();
if let Some(v) = incoming.revenue {
self.fields.revenue = Some(v);
self.field_estimated[0] = est;
}
if let Some(v) = incoming.net_income {
self.fields.net_income = Some(v);
self.field_estimated[1] = est;
}
if let Some(v) = incoming.operating_cash_flow {
self.fields.operating_cash_flow = Some(v);
self.field_estimated[2] = est;
}
if let Some(v) = incoming.total_assets {
self.fields.total_assets = Some(v);
self.field_estimated[3] = est;
}
if let Some(v) = incoming.total_equity {
self.fields.total_equity = Some(v);
self.field_estimated[4] = est;
}
if let Some(v) = incoming.shares_outstanding {
self.fields.shares_outstanding = Some(v);
self.field_estimated[5] = est;
}
self.known_at_utc_micros = row.known_at_utc_micros;
self.known_at_source = row.known_at_source;
}
#[inline]
fn has_estimated_lag(&self) -> bool {
self.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG
|| self.field_estimated.iter().any(|&e| e)
}
#[inline]
fn to_slot(&self) -> FundamentalsPeriodSlot {
FundamentalsPeriodSlot {
period_end: self.period_end,
fiscal_period: self.fiscal_period,
currency: self.currency.clone(),
known_at_utc_micros: self.known_at_utc_micros,
known_at_source: self.known_at_source,
has_estimated_lag: self.has_estimated_lag(),
fields: self.fields,
}
}
}
#[inline]
fn sum_4_flows(values: [Option<f64>; 4]) -> Option<f64> {
let [v0, v1, v2, v3] = values;
let sum = v3? + v2? + v1? + v0?;
if sum.is_finite() {
Some(normalize_zero(sum))
} else {
None
}
}
fn compute_ttm(visible_quarters: &BTreeMap<i32, ResolvedPeriod>) -> Option<FundamentalsTtm> {
let quarters: [&ResolvedPeriod; TTM_QUARTER_COUNT] = {
let mut iter = visible_quarters.values().rev();
let q0 = iter.next()?;
let q1 = iter.next()?;
let q2 = iter.next()?;
let q3 = iter.next()?;
[q0, q1, q2, q3]
};
let min_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MIN_DAYS);
let max_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MAX_DAYS);
for pair in quarters.windows(2) {
let gap = i64::from(pair[0].period_end) - i64::from(pair[1].period_end);
if gap < min_gap || gap > max_gap {
return None;
}
}
let currency = &quarters[0].currency;
if !quarters[1..].iter().all(|q| &q.currency == currency) {
return None;
}
let flows = TtmFlowFields {
revenue: sum_4_flows([
quarters[0].fields.revenue,
quarters[1].fields.revenue,
quarters[2].fields.revenue,
quarters[3].fields.revenue,
]),
net_income: sum_4_flows([
quarters[0].fields.net_income,
quarters[1].fields.net_income,
quarters[2].fields.net_income,
quarters[3].fields.net_income,
]),
operating_cash_flow: sum_4_flows([
quarters[0].fields.operating_cash_flow,
quarters[1].fields.operating_cash_flow,
quarters[2].fields.operating_cash_flow,
quarters[3].fields.operating_cash_flow,
]),
};
let has_estimated_lag = quarters.iter().any(|q| q.has_estimated_lag());
Some(FundamentalsTtm {
ending_period_end: quarters[0].period_end,
currency: currency.clone(),
flows,
has_estimated_lag,
})
}
/// Builds 2D point-in-time [`FundamentalsSnapshot`] records sorted by
/// `(key, effective_known_at_utc_micros)` from bitemporal [`FundamentalsRow`] inputs.
///
/// Returns [`FundamentalsError::InvalidPeriodLimit`] if `k == 0`.
pub fn build_fundamentals_snapshots<K>(
rows: &[FundamentalsRow<K>],
k: usize,
) -> Result<Vec<FundamentalsSnapshot<K>>, FundamentalsError>
where
K: Ord + Clone,
{
if k == 0 {
return Err(FundamentalsError::InvalidPeriodLimit { k });
}
if rows.is_empty() {
return Ok(Vec::new());
}
let mut order: Vec<usize> = (0..rows.len()).collect();
order.sort_unstable_by(|&a, &b| {
rows[a]
.key
.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<FundamentalsSnapshot<K>> = Vec::new();
let total = order.len();
let mut idx = 0usize;
while idx < total {
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;
while idx < total
&& &rows[order[idx]].key == key
&& rows[order[idx]].known_at_utc_micros == effective_ts
{
let row = &rows[order[idx]];
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;
}
let periods: Vec<FundamentalsPeriodSlot> = visible_periods
.values()
.rev()
.take(k)
.map(ResolvedPeriod::to_slot)
.collect();
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 {
KNOWN_AT_SOURCE_STATUTORY_LAG
} else {
KNOWN_AT_SOURCE_FILING_TIMESTAMP
};
snapshots.push(FundamentalsSnapshot {
key: key.clone(),
effective_known_at_utc_micros: effective_ts,
known_at_source,
has_estimated_lag,
periods,
ttm,
});
}
}
Ok(snapshots)
}
/// Returns the latest [`FundamentalsSnapshot`] for `key` with
/// `effective_known_at_utc_micros <= as_of_micros` (inclusive).
///
/// Requires `snapshots` to be sorted by `(key, effective_known_at_utc_micros)` (as returned by
/// [`build_fundamentals_snapshots`]).
pub fn as_of<'a, K, Q>(
snapshots: &'a [FundamentalsSnapshot<K>],
key: &Q,
as_of_micros: i64,
) -> Option<&'a FundamentalsSnapshot<K>>
where
K: Borrow<Q> + Ord,
Q: Ord + ?Sized,
{
let pos = snapshots.partition_point(|s| match s.key.borrow().cmp(key) {
Ordering::Less => true,
Ordering::Equal => s.effective_known_at_utc_micros <= as_of_micros,
Ordering::Greater => false,
});
if pos == 0 {
return None;
}
let candidate = &snapshots[pos - 1];
if candidate.key.borrow() == key {
Some(candidate)
} else {
None
}
}
#[cfg(test)]
#[path = "fundamentals_tests.rs"]
mod tests;