T-169: M2.2l — tools/curate-etl: pure fundamentals_pit curation stage (FinancialObservation<K> + QmFiling<K> → provider_mapping → build_fundamentals_rows → build_fundamentals_snapshots → fundamentals_pit Zstd Parquet) in curate_fundamentals.rs with tests (no new crates, no CLI/bench/stream changes, no live Mongo)
This commit is contained in:
parent
f221a95a5b
commit
1332d2c9b0
3 changed files with 1458 additions and 0 deletions
282
tools/curate-etl/src/curate_fundamentals.rs
Normal file
282
tools/curate-etl/src/curate_fundamentals.rs
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
//! Pure, in-memory `fundamentals_pit` curation stage joining
|
||||
//! [`crate::provider_mapping::ProviderMappingTable`],
|
||||
//! [`crate::fundamentals::build_fundamentals_rows`],
|
||||
//! [`crate::fundamentals::build_fundamentals_snapshots`], and
|
||||
//! [`crate::parquet_fundamentals::write_fundamentals_pit_dataset`] into contract
|
||||
//! [`FundamentalsPitParquetRow`]s.
|
||||
//!
|
||||
//! # Contract & Point-in-Time Rules
|
||||
//! - Resolves provider source keys to permanent `listing_id: i32` **before** building
|
||||
//! bitemporal rows and snapshots so ticker reuse never mixes issuers or spans TTM windows
|
||||
//! across distinct listings:
|
||||
//! - **Observations:** resolved on `(mapping_source, obs.key, obs.period_end)` (the fiscal
|
||||
//! period end date, not `report_date`).
|
||||
//! - **Filings:** `filing.timefiled` is parsed first via [`parse_filing_timefiled`]; parse
|
||||
//! failures are dropped and counted in
|
||||
//! [`CurateFundamentalsStats::filings_dropped_invalid_timestamp`] (never fabricating a
|
||||
//! placeholder `listing_id`). Valid filings are resolved on
|
||||
//! `(mapping_source, filing.key, parsed.et_date)` (Eastern local calendar date, never UTC
|
||||
//! date).
|
||||
//! - Unmapped observations and filings are dropped and counted in
|
||||
//! [`CurateFundamentalsStats::observations_dropped_unmapped`] and
|
||||
//! [`CurateFundamentalsStats::filings_dropped_unmapped`].
|
||||
//! - Feeds mapped inputs into [`build_fundamentals_rows`] with `K = i32` and the caller's
|
||||
//! `venues` map, then [`build_fundamentals_snapshots`] with `k`, then converts each snapshot via
|
||||
//! [`FundamentalsPitParquetRow::from`]. Output rows preserve the builder's strictly ascending
|
||||
//! `(listing_id, effective_known_at_micros)` order and are independent of input order.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::events::{parse_filing_timefiled, QmFiling};
|
||||
use crate::fundamentals::{
|
||||
build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FundamentalsError,
|
||||
FundamentalsStats, StatutoryLagVenue,
|
||||
};
|
||||
use crate::parquet_fundamentals::{
|
||||
write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions,
|
||||
FundamentalsPitWriteStats, ParquetFundamentalsError,
|
||||
};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
|
||||
/// Accounting summary produced alongside [`CurateFundamentalsOutput::rows`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `observations_in == observations_dropped_unmapped + build.observations_in`
|
||||
/// - `filings_in == filings_dropped_unmapped + filings_dropped_invalid_timestamp + build.filings_in`
|
||||
/// - `build` independently satisfies all [`FundamentalsStats`] conservation invariants (with
|
||||
/// `build.filings_dropped_invalid_timestamp == 0` because malformed filings are filtered at the
|
||||
/// stage before mapping lookup).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct CurateFundamentalsStats {
|
||||
pub build: FundamentalsStats,
|
||||
pub observations_in: usize,
|
||||
pub observations_dropped_unmapped: usize,
|
||||
pub filings_in: usize,
|
||||
pub filings_dropped_unmapped: usize,
|
||||
pub filings_dropped_invalid_timestamp: usize,
|
||||
pub rows_out: usize,
|
||||
pub listings_out: usize,
|
||||
}
|
||||
|
||||
/// Output of [`curate_fundamentals`]: contract Parquet rows strictly ascending by
|
||||
/// `(listing_id, effective_known_at_micros)` and full stage + builder stats.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateFundamentalsOutput {
|
||||
pub rows: Vec<FundamentalsPitParquetRow>,
|
||||
pub stats: CurateFundamentalsStats,
|
||||
}
|
||||
|
||||
/// Typed caller errors returned by [`curate_fundamentals`].
|
||||
///
|
||||
/// Unmapped inputs and malformed filing timestamps are dropped and counted in
|
||||
/// [`CurateFundamentalsStats`] rather than aborting the stage.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CurateFundamentalsError {
|
||||
/// Error propagated from [`build_fundamentals_snapshots`] (e.g., `k == 0`).
|
||||
Fundamentals(FundamentalsError),
|
||||
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateFundamentalsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
Self::Fundamentals(err) => write!(f, "{err}"),
|
||||
Self::EmptyMappingSource => {
|
||||
write!(f, "mapping_source must not be empty or blank")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateFundamentalsError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Fundamentals(err) => Some(err),
|
||||
Self::EmptyMappingSource => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FundamentalsError> for CurateFundamentalsError {
|
||||
fn from(err: FundamentalsError) -> Self {
|
||||
Self::Fundamentals(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Combined stats returned by [`curate_and_write_fundamentals`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateFundamentalsWriteReport {
|
||||
pub curate_stats: CurateFundamentalsStats,
|
||||
pub write_stats: FundamentalsPitWriteStats,
|
||||
}
|
||||
|
||||
/// Typed error returned by [`curate_and_write_fundamentals`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateFundamentalsWriteError {
|
||||
Curate(CurateFundamentalsError),
|
||||
Parquet(ParquetFundamentalsError),
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateFundamentalsWriteError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Curate(err) => write!(f, "fundamentals curation failed: {err}"),
|
||||
Self::Parquet(err) => write!(f, "fundamentals Parquet write failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateFundamentalsWriteError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Curate(err) => Some(err),
|
||||
Self::Parquet(err) => Some(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurateFundamentalsError> for CurateFundamentalsWriteError {
|
||||
fn from(err: CurateFundamentalsError) -> Self {
|
||||
Self::Curate(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParquetFundamentalsError> for CurateFundamentalsWriteError {
|
||||
fn from(err: ParquetFundamentalsError) -> Self {
|
||||
Self::Parquet(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure `fundamentals_pit` curation stage: resolves provider source keys to permanent
|
||||
/// `listing_id`s via `provider_mapping` (observations on `period_end`, filings on Eastern local
|
||||
/// date `ParsedFilingTime::et_date`), builds bitemporal rows and 2D point-in-time snapshots via
|
||||
/// [`build_fundamentals_rows`] and [`build_fundamentals_snapshots`], and emits contract
|
||||
/// [`FundamentalsPitParquetRow`]s strictly ascending by `(listing_id, effective_known_at_micros)`.
|
||||
///
|
||||
/// Rejects blank `mapping_source` with [`CurateFundamentalsError::EmptyMappingSource`] and `k == 0`
|
||||
/// with [`CurateFundamentalsError::Fundamentals`] (`FundamentalsError::InvalidPeriodLimit`) before
|
||||
/// consuming input iterators.
|
||||
pub fn curate_fundamentals<K, IO, IF>(
|
||||
observations: IO,
|
||||
filings: IF,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
venues: &BTreeMap<i32, StatutoryLagVenue>,
|
||||
k: usize,
|
||||
) -> Result<CurateFundamentalsOutput, CurateFundamentalsError>
|
||||
where
|
||||
K: AsRef<str>,
|
||||
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||
IF: IntoIterator<Item = QmFiling<K>>,
|
||||
{
|
||||
if mapping_source.trim().is_empty() {
|
||||
return Err(CurateFundamentalsError::EmptyMappingSource);
|
||||
}
|
||||
if k == 0 {
|
||||
return Err(FundamentalsError::InvalidPeriodLimit { k }.into());
|
||||
}
|
||||
|
||||
let obs_iter = observations.into_iter();
|
||||
let filings_iter = filings.into_iter();
|
||||
|
||||
let mut stats = CurateFundamentalsStats::default();
|
||||
let mut mapped_observations: Vec<FinancialObservation<i32>> =
|
||||
Vec::with_capacity(obs_iter.size_hint().0);
|
||||
let mut mapped_filings: Vec<QmFiling<i32>> = Vec::with_capacity(filings_iter.size_hint().0);
|
||||
|
||||
for obs in obs_iter {
|
||||
stats.observations_in += 1;
|
||||
let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end)
|
||||
else {
|
||||
stats.observations_dropped_unmapped += 1;
|
||||
continue;
|
||||
};
|
||||
mapped_observations.push(FinancialObservation {
|
||||
key: listing_id,
|
||||
period_end: obs.period_end,
|
||||
fiscal_period: obs.fiscal_period,
|
||||
currency: obs.currency,
|
||||
report_date: obs.report_date,
|
||||
fields: obs.fields,
|
||||
});
|
||||
}
|
||||
|
||||
for filing in filings_iter {
|
||||
stats.filings_in += 1;
|
||||
let Ok(parsed_time) = parse_filing_timefiled(&filing.timefiled) else {
|
||||
stats.filings_dropped_invalid_timestamp += 1;
|
||||
continue;
|
||||
};
|
||||
let Some(listing_id) =
|
||||
mapping.resolve(mapping_source, filing.key.as_ref(), parsed_time.et_date)
|
||||
else {
|
||||
stats.filings_dropped_unmapped += 1;
|
||||
continue;
|
||||
};
|
||||
mapped_filings.push(QmFiling {
|
||||
key: listing_id,
|
||||
timefiled: filing.timefiled,
|
||||
form_type: filing.form_type,
|
||||
filing_id: filing.filing_id,
|
||||
url: filing.url,
|
||||
});
|
||||
}
|
||||
|
||||
let built = build_fundamentals_rows(mapped_observations, mapped_filings, venues);
|
||||
stats.build = built.stats;
|
||||
|
||||
let snapshots = build_fundamentals_snapshots(&built.rows, k)?;
|
||||
let rows: Vec<FundamentalsPitParquetRow> = snapshots
|
||||
.into_iter()
|
||||
.map(FundamentalsPitParquetRow::from)
|
||||
.collect();
|
||||
|
||||
let mut last_listing_id: Option<i32> = None;
|
||||
for row in &rows {
|
||||
if last_listing_id != Some(row.listing_id) {
|
||||
stats.listings_out += 1;
|
||||
last_listing_id = Some(row.listing_id);
|
||||
}
|
||||
}
|
||||
stats.rows_out = rows.len();
|
||||
|
||||
Ok(CurateFundamentalsOutput { rows, stats })
|
||||
}
|
||||
|
||||
/// Thin end-to-end wrapper running [`curate_fundamentals`] and publishing the resulting contract
|
||||
/// rows via [`write_fundamentals_pit_dataset`] to `<out_dir>/fundamentals_pit/year=YYYY/part.parquet`.
|
||||
///
|
||||
/// Any [`CurateFundamentalsError`] returns before [`write_fundamentals_pit_dataset`] is invoked,
|
||||
/// leaving `out_dir` untouched.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn curate_and_write_fundamentals<P, K, IO, IF>(
|
||||
out_dir: P,
|
||||
observations: IO,
|
||||
filings: IF,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
venues: &BTreeMap<i32, StatutoryLagVenue>,
|
||||
k: usize,
|
||||
options: FundamentalsPitWriteOptions,
|
||||
) -> Result<CurateFundamentalsWriteReport, CurateFundamentalsWriteError>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
K: AsRef<str>,
|
||||
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||
IF: IntoIterator<Item = QmFiling<K>>,
|
||||
{
|
||||
let curated = curate_fundamentals(observations, filings, mapping_source, mapping, venues, k)?;
|
||||
let write_stats = write_fundamentals_pit_dataset(out_dir, &curated.rows, options)?;
|
||||
Ok(CurateFundamentalsWriteReport {
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "curate_fundamentals_tests.rs"]
|
||||
mod tests;
|
||||
1169
tools/curate-etl/src/curate_fundamentals_tests.rs
Normal file
1169
tools/curate-etl/src/curate_fundamentals_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -245,6 +245,13 @@ pub use curate_posts::{
|
|||
CuratePostsWriteError, CuratePostsWriteReport,
|
||||
};
|
||||
|
||||
pub mod curate_fundamentals;
|
||||
pub use curate_fundamentals::{
|
||||
curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError,
|
||||
CurateFundamentalsOutput, CurateFundamentalsStats, CurateFundamentalsWriteError,
|
||||
CurateFundamentalsWriteReport,
|
||||
};
|
||||
|
||||
pub mod curate_fx;
|
||||
pub use curate_fx::{
|
||||
curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue