diff --git a/tools/curate-etl/src/curate_fundamentals.rs b/tools/curate-etl/src/curate_fundamentals.rs new file mode 100644 index 00000000..02092a68 --- /dev/null +++ b/tools/curate-etl/src/curate_fundamentals.rs @@ -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, + 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 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 for CurateFundamentalsWriteError { + fn from(err: CurateFundamentalsError) -> Self { + Self::Curate(err) + } +} + +impl From 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( + observations: IO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, +) -> Result +where + K: AsRef, + IO: IntoIterator>, + IF: IntoIterator>, +{ + 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> = + Vec::with_capacity(obs_iter.size_hint().0); + let mut mapped_filings: Vec> = 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 = snapshots + .into_iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + + let mut last_listing_id: Option = 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 `/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( + out_dir: P, + observations: IO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + K: AsRef, + IO: IntoIterator>, + IF: IntoIterator>, +{ + 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; diff --git a/tools/curate-etl/src/curate_fundamentals_tests.rs b/tools/curate-etl/src/curate_fundamentals_tests.rs new file mode 100644 index 00000000..c0b9a0c0 --- /dev/null +++ b/tools/curate-etl/src/curate_fundamentals_tests.rs @@ -0,0 +1,1169 @@ +//! Unit, replay, PIT-leakage, mapping, determinism, error, and Parquet round-trip tests for +//! `curate_fundamentals`. + +use std::collections::{BTreeMap, HashMap}; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError, + CurateFundamentalsStats, CurateFundamentalsWriteError, +}; +use crate::events::{ + parse_filing_timefiled, partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + FinancialObservation, FiscalPeriod, FundamentalsError, FundamentalsFields, FundamentalsTtm, + StatutoryLagVenue, TtmFlowFields, +}; +use crate::parquet_fundamentals::{FundamentalsPitParquetRow, FundamentalsPitWriteOptions}; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-fundamentals-test-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(y, m, d); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 +} + +fn mapping_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn filing(key: &str, timefiled: &str, form_type: &str) -> QmFiling { + QmFiling { + key: key.to_string(), + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: None, + url: None, + } +} + +fn obs( + key: &str, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: &str, + report_date: Option, + fields: FundamentalsFields, +) -> FinancialObservation { + FinancialObservation { + key: key.to_string(), + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + } +} + +fn sample_fields(rev: f64, ni: f64, ocf: f64, assets: f64, equity: f64, shares: f64) -> FundamentalsFields { + FundamentalsFields { + revenue: Some(rev), + net_income: Some(ni), + operating_cash_flow: Some(ocf), + total_assets: Some(assets), + total_equity: Some(equity), + shares_outstanding: Some(shares), + } +} + +fn assert_stage_conservation(stats: &CurateFundamentalsStats) { + assert_eq!( + stats.observations_in, + stats.observations_dropped_unmapped + stats.build.observations_in, + "observation stage conservation failed: {stats:?}" + ); + assert_eq!( + stats.filings_in, + stats.filings_dropped_unmapped + + stats.filings_dropped_invalid_timestamp + + stats.build.filings_in, + "filing stage conservation failed: {stats:?}" + ); + assert_eq!( + stats.build.filings_dropped_invalid_timestamp, 0, + "malformed filings must be dropped at the stage before build_fundamentals_rows" + ); + assert_eq!( + stats.build.observations_in, + stats.build.rows_out + + stats.build.observations_dropped_unknown_key + + stats.build.observations_dropped_non_finite + + stats.build.observations_dropped_date_out_of_range + + stats.build.observations_dropped_report_date_not_after_period_end + + stats.build.observations_dropped_unanchored_vintage + + stats.build.observations_dropped_stale_estimate + + stats.build.duplicate_collapsed + + stats.build.duplicate_conflict_dropped, + "builder observation conservation failed: {stats:?}" + ); + assert_eq!( + stats.build.filings_in, + stats.build.filings_eligible + + stats.build.filings_dropped_unknown_key + + stats.build.filings_ignored_non_periodic + + stats.build.filings_dropped_invalid_timestamp + + stats.build.filings_dropped_date_out_of_range + + stats.build.filings_dropped_before_period_end, + "builder filing conservation failed: {stats:?}" + ); +} + +fn permutations(items: &[T]) -> Vec> { + if items.is_empty() { + return vec![Vec::new()]; + } + let mut out = Vec::new(); + for i in 0..items.len() { + let mut rest = items.to_vec(); + let head = rest.remove(i); + for mut tail in permutations(&rest) { + let mut perm = Vec::with_capacity(items.len()); + perm.push(head.clone()); + perm.append(&mut tail); + out.push(perm); + } + } + out +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedParquetRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_has_estimated_lag: Option, +} + +/// Reads a `fundamentals_pit` Parquet file resolving every column strictly by schema column name +/// (never by positional index). +fn read_parquet_rows_by_name(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let schema_descr = meta.file_metadata().schema_descr(); + + let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); + for (idx, col) in schema_descr.columns().iter().enumerate() { + col_idx_by_name.insert(col.name(), idx); + } + + let col_idx = |name: &str| -> usize { + *col_idx_by_name + .get(name) + .unwrap_or_else(|| panic!("missing expected Parquet column '{name}'")) + }; + + let mut out = Vec::new(); + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + for c in 0..rg_meta.num_columns() { + assert_eq!( + rg_meta.column(c).compression(), + Compression::ZSTD(Default::default()), + "expected Zstd compression on column {c}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_req_i32 = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for column '{name}'"), + } + vals + }; + + let read_opt_i32 = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_i64 = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req i64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 for column '{name}'"), + } + vals + }; + + let read_req_bool = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for column '{name}'"), + } + vals + }; + + let read_opt_bool = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_opt_f64 = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt f64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_str = |name: &str| -> Vec { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for column '{name}'"), + } + vals.into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) + .collect() + }; + + let read_opt_str = |name: &str| -> Vec> { + let idx = col_idx(name); + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for column '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = String::from_utf8(vals[vi].data().to_vec()).expect("utf8"); + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let listing_id = read_req_i32("listing_id"); + let effective_known_at = read_req_i64("effective_known_at"); + let known_at_source = read_req_str("known_at_source"); + let has_estimated_lag = read_req_bool("has_estimated_lag"); + let period_end = read_req_i32("period_end"); + let fiscal_period = read_req_str("fiscal_period"); + let currency = read_req_str("currency"); + let period_known_at = read_req_i64("period_known_at"); + let revenue = read_opt_f64("revenue"); + let net_income = read_opt_f64("net_income"); + let operating_cash_flow = read_opt_f64("operating_cash_flow"); + let total_assets = read_opt_f64("total_assets"); + let total_equity = read_opt_f64("total_equity"); + let shares_outstanding = read_opt_f64("shares_outstanding"); + let ttm_period_end = read_opt_i32("ttm_period_end"); + let ttm_currency = read_opt_str("ttm_currency"); + let ttm_revenue = read_opt_f64("ttm_revenue"); + let ttm_net_income = read_opt_f64("ttm_net_income"); + let ttm_operating_cash_flow = read_opt_f64("ttm_operating_cash_flow"); + let ttm_has_estimated_lag = read_opt_bool("ttm_has_estimated_lag"); + + for i in 0..rg_rows { + out.push(DecodedParquetRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + out +} + +fn decoded_from_curated(row: &FundamentalsPitParquetRow) -> DecodedParquetRow { + let latest = row.latest_period().expect("curated row must have latest_period"); + DecodedParquetRow { + listing_id: row.listing_id, + effective_known_at: row.effective_known_at_micros, + known_at_source: row.known_at_source.to_string(), + has_estimated_lag: row.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: latest.fiscal_period.to_string(), + currency: latest.currency.clone(), + period_known_at: latest.period_known_at_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_period_end: row.ttm.as_ref().map(|t| t.ending_period_end), + ttm_currency: row.ttm.as_ref().map(|t| t.currency.clone()), + ttm_revenue: row.ttm.as_ref().and_then(|t| t.flows.revenue), + ttm_net_income: row.ttm.as_ref().and_then(|t| t.flows.net_income), + ttm_operating_cash_flow: row.ttm.as_ref().and_then(|t| t.flows.operating_cash_flow), + ttm_has_estimated_lag: row.ttm.as_ref().map(|t| t.has_estimated_lag), + } +} + +#[test] +fn restatement_after_q2_preserves_prior_snapshots_and_never_displaces_q2() { + let mapping = ProviderMappingTable::from_rows([mapping_row( + "qm", + "ACME", + day(2024, 1, 1), + None, + 1001, + )]) + .expect("valid mapping"); + let venues = BTreeMap::from([(1001, StatutoryLagVenue::UsTsx)]); + + let q1_end = day(2024, 3, 31); + let q2_end = day(2024, 6, 30); + let q1_fields = sample_fields(100.0, 12.0, 15.0, 500.0, 250.0, 10.0); + let q2_fields = sample_fields(130.0, 18.0, 21.0, 540.0, 270.0, 10.0); + let q1_restated_fields = sample_fields(92.0, 9.0, 11.0, 490.0, 245.0, 10.0); + + let base_observations = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + q1_fields, + ), + obs( + "ACME", + q2_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 1)), + q2_fields, + ), + ]; + let base_filings = vec![ + filing("ACME", "2024-05-01T16:10:00 EDT", "10-Q"), + filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"), + ]; + + let baseline = curate_fundamentals( + base_observations.clone(), + base_filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("baseline curate"); + assert_stage_conservation(&baseline.stats); + assert_eq!(baseline.rows.len(), 2); + + let mut revised_observations = base_observations; + revised_observations.push(obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 15)), + q1_restated_fields, + )); + let mut revised_filings = base_filings; + revised_filings.push(filing("ACME", "2024-09-15T16:30:00 EDT", "10-Q/A")); + + let revised = curate_fundamentals( + revised_observations, + revised_filings, + "qm", + &mapping, + &venues, + 4, + ) + .expect("revised curate"); + assert_stage_conservation(&revised.stats); + assert_eq!(revised.rows.len(), 3); + + let q2_known_at = parse_filing_timefiled("2024-08-01T16:15:00 EDT") + .expect("q2 ts") + .utc_micros; + let amend_known_at = parse_filing_timefiled("2024-09-15T16:30:00 EDT") + .expect("amend ts") + .utc_micros; + + // Snapshots before the amendment must be bit-for-bit identical to the baseline replay. + assert_eq!(&revised.rows[..2], &baseline.rows[..]); + + // The amendment produces a new snapshot at the amendment timestamp, while Q2 remains latest. + assert_eq!(revised.rows[2].effective_known_at_micros, amend_known_at); + for row in revised + .rows + .iter() + .filter(|r| r.effective_known_at_micros >= q2_known_at) + { + let latest = row.latest_period().expect("latest period"); + assert_eq!(latest.period_end, q2_end); + assert_eq!(latest.fields, q2_fields); + assert_eq!(latest.period_known_at_micros, q2_known_at); + assert_ne!(latest.period_end, q1_end); + } +} + +#[test] +fn statutory_lag_deadlines_and_filing_timestamp_provenance() { + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "US_CO", day(2024, 1, 1), None, 10), + mapping_row("qm", "TSXV_CO", day(2024, 1, 1), None, 20), + mapping_row("qm", "LINKED_CO", day(2024, 1, 1), None, 30), + ]) + .expect("valid mapping"); + let venues = BTreeMap::from([ + (10, StatutoryLagVenue::UsTsx), + (20, StatutoryLagVenue::TsxvCse), + (30, StatutoryLagVenue::UsTsx), + ]); + + let q_end = day(2024, 3, 31); + let fy_end = day(2024, 12, 31); + let fields = sample_fields(50.0, 5.0, 6.0, 200.0, 120.0, 8.0); + + // 1. UsTsx quarterly (+45d -> 2024-05-15 16:05 EDT = 20:05 UTC) + let us_q = curate_fundamentals( + [obs("US_CO", q_end, FiscalPeriod::Quarterly, "USD", None, fields)], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("us quarterly"); + assert_eq!(us_q.rows.len(), 1); + let expected_us_q = et_to_utc_micros(q_end + 45, 16, 5, 0).expect("us q et"); + assert_eq!(expected_us_q, utc_micros(2024, 5, 15, 20, 5, 0)); + assert_eq!(us_q.rows[0].effective_known_at_micros, expected_us_q); + assert_eq!(us_q.rows[0].known_at_source.as_ref(), KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(us_q.rows[0].has_estimated_lag); + + // 2. UsTsx annual (+90d -> 2025-03-31 16:05 EDT = 20:05 UTC) + let us_fy = curate_fundamentals( + [obs("US_CO", fy_end, FiscalPeriod::Annual, "USD", None, fields)], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("us annual"); + assert_eq!(us_fy.rows.len(), 1); + let expected_us_fy = et_to_utc_micros(fy_end + 90, 16, 5, 0).expect("us fy et"); + assert_eq!(expected_us_fy, utc_micros(2025, 3, 31, 20, 5, 0)); + assert_eq!(us_fy.rows[0].effective_known_at_micros, expected_us_fy); + assert_eq!(us_fy.rows[0].known_at_source.as_ref(), KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(us_fy.rows[0].has_estimated_lag); + + // 3. TsxvCse quarterly (+60d -> 2024-05-30 16:05 EDT = 20:05 UTC) + let tsxv_q = curate_fundamentals( + [obs("TSXV_CO", q_end, FiscalPeriod::Quarterly, "CAD", None, fields)], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("tsxv quarterly"); + assert_eq!(tsxv_q.rows.len(), 1); + let expected_tsxv_q = et_to_utc_micros(q_end + 60, 16, 5, 0).expect("tsxv q et"); + assert_eq!(expected_tsxv_q, utc_micros(2024, 5, 30, 20, 5, 0)); + assert_eq!(tsxv_q.rows[0].effective_known_at_micros, expected_tsxv_q); + assert_eq!( + tsxv_q.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(tsxv_q.rows[0].has_estimated_lag); + + // 4. TsxvCse annual (+120d -> 2025-04-30 16:05 EDT = 20:05 UTC) + let tsxv_fy = curate_fundamentals( + [obs("TSXV_CO", fy_end, FiscalPeriod::Annual, "CAD", None, fields)], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("tsxv annual"); + assert_eq!(tsxv_fy.rows.len(), 1); + let expected_tsxv_fy = et_to_utc_micros(fy_end + 120, 16, 5, 0).expect("tsxv fy et"); + assert_eq!(expected_tsxv_fy, utc_micros(2025, 4, 30, 20, 5, 0)); + assert_eq!(tsxv_fy.rows[0].effective_known_at_micros, expected_tsxv_fy); + assert_eq!( + tsxv_fy.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(tsxv_fy.rows[0].has_estimated_lag); + + // 5. Filing-linked observation uses exact parsed filing timestamp and filing_timestamp source. + let linked = curate_fundamentals( + [obs( + "LINKED_CO", + q_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields, + )], + [filing("LINKED_CO", "2024-05-02T08:30:15 EDT", "10-Q")], + "qm", + &mapping, + &venues, + 4, + ) + .expect("linked quarterly"); + assert_eq!(linked.rows.len(), 1); + let expected_linked = utc_micros(2024, 5, 2, 12, 30, 15); + assert_eq!(linked.rows[0].effective_known_at_micros, expected_linked); + assert_eq!( + linked.rows[0].known_at_source.as_ref(), + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + assert!(!linked.rows[0].has_estimated_lag); +} + +#[test] +fn ticker_remap_across_utc_midnight_separates_listings_and_prevents_cross_listing_ttm() { + // Source key "REUSED" belongs to listing 101 through 2023-08-05 ET, then listing 202 starting + // 2023-08-06 ET. + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "REUSED", day(2023, 1, 1), Some(day(2023, 8, 5)), 101), + mapping_row("qm", "REUSED", day(2023, 8, 6), None, 202), + ]) + .expect("valid remap"); + let venues = BTreeMap::from([ + (101, StatutoryLagVenue::UsTsx), + (202, StatutoryLagVenue::UsTsx), + ]); + + let f = sample_fields(10.0, 1.0, 2.0, 50.0, 25.0, 5.0); + + // Listing 101 gets Q1 (2023-03-31) and Q2 (2023-06-30). + // Q2's filing is at 2023-08-05T21:00:00 EDT (2023-08-06T01:00:00 UTC): Eastern date is + // 2023-08-05 (listing 101), whereas UTC date is 2023-08-06 (listing 202). + // Listing 202 gets Q3 (2023-09-30) and Q4 (2023-12-31). + let observations = vec![ + obs("REUSED", day(2023, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2023, 5, 10)), f), + obs("REUSED", day(2023, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2023, 8, 5)), f), + obs("REUSED", day(2023, 9, 30), FiscalPeriod::Quarterly, "USD", Some(day(2023, 11, 8)), f), + obs("REUSED", day(2023, 12, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 12)), f), + ]; + let filings = vec![ + filing("REUSED", "2023-05-10T16:00:00 EDT", "10-Q"), + filing("REUSED", "2023-08-05T21:00:00 EDT", "10-Q"), + filing("REUSED", "2023-11-08T16:00:00 EST", "10-Q"), + filing("REUSED", "2024-02-12T16:00:00 EST", "10-Q"), + ]; + + let out = curate_fundamentals(observations, filings, "qm", &mapping, &venues, 4) + .expect("remap curate"); + assert_stage_conservation(&out.stats); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.rows.len(), 4); + + let l101: Vec<&FundamentalsPitParquetRow> = + out.rows.iter().filter(|r| r.listing_id == 101).collect(); + let l202: Vec<&FundamentalsPitParquetRow> = + out.rows.iter().filter(|r| r.listing_id == 202).collect(); + assert_eq!(l101.len(), 2); + assert_eq!(l202.len(), 2); + + // Late-evening EDT filing must link to listing 101's Q2 (not listing 202). + assert_eq!( + l101[1].effective_known_at_micros, + utc_micros(2023, 8, 6, 1, 0, 0) + ); + assert_eq!( + l101[1].known_at_source.as_ref(), + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + assert!(!l101[1].has_estimated_lag); + + // Neither listing has 4 quarters, so TTM must never span across the ticker remap. + assert!(out.rows.iter().all(|r| r.ttm.is_none())); + + // Also verify observation resolution uses period_end even when report_date falls after remap. + let after_remap_report = curate_fundamentals( + [obs( + "REUSED", + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 10)), // after 2023-08-05 remap, <= statutory lag 2023-08-14 + f, + )], + Vec::>::new(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("period_end resolution"); + assert_eq!(after_remap_report.rows.len(), 1); + assert_eq!(after_remap_report.rows[0].listing_id, 101); +} + +#[test] +fn unmapped_and_malformed_inputs_are_counted_and_conserved() { + let mapping = ProviderMappingTable::from_rows([mapping_row( + "qm", + "KNOWN", + day(2024, 1, 1), + Some(day(2024, 12, 31)), + 501, + )]) + .expect("valid mapping"); + let venues = BTreeMap::from([(501, StatutoryLagVenue::UsTsx)]); + let f = sample_fields(25.0, 3.0, 4.0, 100.0, 60.0, 2.0); + + let valid_obs = obs( + "KNOWN", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + f, + ); + let valid_filing = filing("KNOWN", "2024-05-01T17:00:00 EDT", "10-Q"); + + let clean = curate_fundamentals( + [valid_obs.clone()], + [valid_filing.clone()], + "qm", + &mapping, + &venues, + 4, + ) + .expect("clean curate"); + + let with_noise = curate_fundamentals( + [ + valid_obs, + // Unmapped observation (unknown key) + obs( + "UNKNOWN", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + None, + f, + ), + // Unmapped observation (known key, period_end outside range) + obs( + "KNOWN", + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + None, + f, + ), + ], + [ + valid_filing, + // Parseable unmapped filing + filing("UNKNOWN", "2024-05-01T10:00:00 EDT", "10-Q"), + // Malformed filing timestamp for mapped key + filing("KNOWN", "2024-05-01 09:00:00 UTC", "10-Q"), + ], + "qm", + &mapping, + &venues, + 4, + ) + .expect("noisy curate"); + + assert_stage_conservation(&with_noise.stats); + assert_eq!(with_noise.stats.observations_in, 3); + assert_eq!(with_noise.stats.observations_dropped_unmapped, 2); + assert_eq!(with_noise.stats.build.observations_in, 1); + + assert_eq!(with_noise.stats.filings_in, 3); + assert_eq!(with_noise.stats.filings_dropped_unmapped, 1); + assert_eq!(with_noise.stats.filings_dropped_invalid_timestamp, 1); + assert_eq!(with_noise.stats.build.filings_in, 1); + assert_eq!(with_noise.stats.build.filings_eligible, 1); + + // Malformed and unmapped inputs must have zero effect on availability or emitted rows. + assert_eq!(with_noise.rows, clean.rows); +} + +#[test] +fn permutation_invariance_and_strict_ascending_order() { + let mapping = ProviderMappingTable::from_rows([ + mapping_row("qm", "ALPHA", day(2024, 1, 1), None, 200), + mapping_row("qm", "BETA", day(2024, 1, 1), None, 100), + ]) + .expect("valid mapping"); + let venues = BTreeMap::from([ + (100, StatutoryLagVenue::UsTsx), + (200, StatutoryLagVenue::TsxvCse), + ]); + + let f1 = sample_fields(10.0, 1.0, 2.0, 40.0, 20.0, 4.0); + let f2 = sample_fields(15.0, 2.0, 3.0, 45.0, 22.0, 4.0); + let f3 = sample_fields(20.0, 3.0, 4.0, 60.0, 30.0, 6.0); + + let base_obs = vec![ + obs("ALPHA", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", Some(day(2024, 5, 1)), f1), + obs("ALPHA", day(2024, 6, 30), FiscalPeriod::Quarterly, "CAD", Some(day(2024, 8, 1)), f2), + obs("BETA", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 1)), f3), + ]; + let base_filings = vec![ + filing("ALPHA", "2024-05-01T16:00:00 EDT", "Interim financial statements"), + filing("ALPHA", "2024-08-01T16:00:00 EDT", "Interim financial statements"), + // Same-instant filing for BETA + filing("BETA", "2024-05-01T16:00:00 EDT", "10-Q"), + ]; + + let reference = curate_fundamentals( + base_obs.clone(), + base_filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("reference run"); + assert_stage_conservation(&reference.stats); + assert_eq!(reference.rows.len(), 3); + + for pair in reference.rows.windows(2) { + let a = (pair[0].listing_id, pair[0].effective_known_at_micros); + let b = (pair[1].listing_id, pair[1].effective_known_at_micros); + assert!(a < b, "rows not strictly ascending: {a:?} >= {b:?}"); + } + + let obs_perms = permutations(&base_obs); + let filing_perms = permutations(&base_filings); + assert_eq!(obs_perms.len(), 6); + assert_eq!(filing_perms.len(), 6); + + for op in &obs_perms { + for fp in &filing_perms { + let out = curate_fundamentals( + op.iter().cloned(), + fp.iter().cloned(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("permuted run"); + assert_eq!(out.rows, reference.rows); + assert_eq!(out.stats, reference.stats); + } + } +} + +#[test] +fn typed_errors_and_untouched_out_dir_on_curation_failure() { + let mapping = ProviderMappingTable::from_rows([mapping_row( + "qm", + "ACME", + day(2024, 1, 1), + None, + 10, + )]) + .expect("valid mapping"); + let venues = BTreeMap::from([(10, StatutoryLagVenue::UsTsx)]); + let invalid_writer_opts = FundamentalsPitWriteOptions { + row_group_rows: 0, + ..FundamentalsPitWriteOptions::default() + }; + + for blank_source in ["", " \t\n "] { + let err = curate_fundamentals( + Vec::>::new(), + Vec::>::new(), + blank_source, + &mapping, + &venues, + 4, + ) + .expect_err("blank mapping_source must fail"); + assert_eq!(err, CurateFundamentalsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + + let tmp = TempDirGuard::new("empty-source"); + let write_err = curate_and_write_fundamentals( + tmp.path(), + Vec::>::new(), + Vec::>::new(), + blank_source, + &mapping, + &venues, + 4, + invalid_writer_opts, + ) + .expect_err("curation error must take precedence over invalid writer options"); + assert!(matches!( + write_err, + CurateFundamentalsWriteError::Curate(CurateFundamentalsError::EmptyMappingSource) + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("fundamentals curation failed")); + assert!( + !tmp.path().join("fundamentals_pit").exists(), + "out_dir must remain untouched on curation failure" + ); + } + + let k_err = curate_fundamentals( + Vec::>::new(), + Vec::>::new(), + "qm", + &mapping, + &venues, + 0, + ) + .expect_err("k == 0 must fail"); + assert_eq!( + k_err, + CurateFundamentalsError::Fundamentals(FundamentalsError::InvalidPeriodLimit { k: 0 }) + ); + assert!(k_err.source().is_some()); + + let tmp_k = TempDirGuard::new("k-zero"); + let write_k_err = curate_and_write_fundamentals( + tmp_k.path(), + Vec::>::new(), + Vec::>::new(), + "qm", + &mapping, + &venues, + 0, + invalid_writer_opts, + ) + .expect_err("k == 0 must fail before writer"); + assert!(matches!( + write_k_err, + CurateFundamentalsWriteError::Curate(CurateFundamentalsError::Fundamentals( + FundamentalsError::InvalidPeriodLimit { k: 0 } + )) + )); + assert!( + !tmp_k.path().join("fundamentals_pit").exists(), + "out_dir must remain untouched on k == 0 failure" + ); +} + +#[test] +fn curate_and_write_fundamentals_round_trips_four_quarters_and_ttm_by_column_name() { + let mapping = ProviderMappingTable::from_rows([mapping_row( + "qm", + "GROW", + day(2023, 1, 1), + None, + 777, + )]) + .expect("valid mapping"); + let venues = BTreeMap::from([(777, StatutoryLagVenue::UsTsx)]); + + let q1_f = sample_fields(100.0, 10.0, 15.0, 500.0, 200.0, 10.0); + let q2_f = sample_fields(110.0, 12.0, 18.0, 520.0, 212.0, 10.0); + let q3_f = sample_fields(125.0, 14.0, 20.0, 545.0, 226.0, 10.0); + let q4_f = sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0); + + let observations = vec![ + obs("GROW", day(2023, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2023, 5, 1)), q1_f), + obs("GROW", day(2023, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2023, 8, 1)), q2_f), + obs("GROW", day(2023, 9, 30), FiscalPeriod::Quarterly, "USD", Some(day(2023, 11, 1)), q3_f), + obs("GROW", day(2023, 12, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 15)), q4_f), + ]; + let filings = vec![ + filing("GROW", "2023-05-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2023-08-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2023-11-01T16:10:00 EDT", "10-Q"), + filing("GROW", "2024-02-15T16:10:00 EST", "10-Q"), + ]; + + let curated = curate_fundamentals( + observations.clone(), + filings.clone(), + "qm", + &mapping, + &venues, + 4, + ) + .expect("curate four quarters"); + assert_stage_conservation(&curated.stats); + assert_eq!(curated.rows.len(), 4); + assert!(curated.rows[0].ttm.is_none()); + assert!(curated.rows[1].ttm.is_none()); + assert!(curated.rows[2].ttm.is_none()); + assert_eq!( + curated.rows[3].ttm, + Some(FundamentalsTtm { + ending_period_end: day(2023, 12, 31), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(100.0 + 110.0 + 125.0 + 140.0), + net_income: Some(10.0 + 12.0 + 14.0 + 16.0), + operating_cash_flow: Some(15.0 + 18.0 + 20.0 + 22.0), + }, + has_estimated_lag: false, + }) + ); + + let tmp = TempDirGuard::new("round-trip"); + let report = curate_and_write_fundamentals( + tmp.path(), + observations, + filings, + "qm", + &mapping, + &venues, + 4, + FundamentalsPitWriteOptions::default(), + ) + .expect("curate and write"); + + assert_eq!(report.curate_stats, curated.stats); + assert_eq!(report.write_stats.files_written, 2); + assert_eq!(report.write_stats.rows_written, 4); + assert_eq!( + report.write_stats.rows_by_year, + BTreeMap::from([(2023, 3), (2024, 1)]) + ); + + let mut read_back = Vec::new(); + for year in [2023, 2024] { + let part_path = tmp + .path() + .join("fundamentals_pit") + .join(format!("year={year}")) + .join("part.parquet"); + assert!(part_path.exists(), "missing partition {}", part_path.display()); + let part_rows = read_parquet_rows_by_name(&part_path); + for row in &part_rows { + assert_eq!(partition_year_utc(row.effective_known_at), year); + } + read_back.extend(part_rows); + } + + let expected: Vec = curated.rows.iter().map(decoded_from_curated).collect(); + assert_eq!(read_back, expected); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 7402899c..a7b49d35 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -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,