1719 lines
56 KiB
Rust
1719 lines
56 KiB
Rust
//! 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<i32>,
|
|
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<String> {
|
|
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<i32>,
|
|
fields: FundamentalsFields,
|
|
) -> FinancialObservation<String> {
|
|
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<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
|
|
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<f64>,
|
|
net_income: Option<f64>,
|
|
operating_cash_flow: Option<f64>,
|
|
total_assets: Option<f64>,
|
|
total_equity: Option<f64>,
|
|
shares_outstanding: Option<f64>,
|
|
ttm_period_end: Option<i32>,
|
|
ttm_currency: Option<String>,
|
|
ttm_revenue: Option<f64>,
|
|
ttm_net_income: Option<f64>,
|
|
ttm_operating_cash_flow: Option<f64>,
|
|
ttm_has_estimated_lag: Option<bool>,
|
|
}
|
|
|
|
/// 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<DecodedParquetRow> {
|
|
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<i32> {
|
|
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<Option<i32>> {
|
|
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<i64> {
|
|
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<bool> {
|
|
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<Option<bool>> {
|
|
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<Option<f64>> {
|
|
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<String> {
|
|
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<Option<String>> {
|
|
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::<QmFiling<String>>::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::<QmFiling<String>>::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::<QmFiling<String>>::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::<QmFiling<String>>::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::<QmFiling<String>>::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::<FinancialObservation<String>>::new(),
|
|
Vec::<QmFiling<String>>::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::<FinancialObservation<String>>::new(),
|
|
Vec::<QmFiling<String>>::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::<FinancialObservation<String>>::new(),
|
|
Vec::<QmFiling<String>>::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::<FinancialObservation<String>>::new(),
|
|
Vec::<QmFiling<String>>::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<DecodedParquetRow> = curated.rows.iter().map(decoded_from_curated).collect();
|
|
assert_eq!(read_back, expected);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// QA additions (T-169): amendment TTM propagation, UTC-year partitioning, Eastern-date filing
|
|
// resolution, builder venue misses, cutoff-truncation PIT replay, and empty input.
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
fn grow_four_quarters() -> (Vec<FinancialObservation<String>>, Vec<QmFiling<String>>) {
|
|
let observations = vec![
|
|
obs(
|
|
"GROW",
|
|
day(2023, 3, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2023, 5, 1)),
|
|
sample_fields(100.0, 10.0, 15.0, 500.0, 200.0, 10.0),
|
|
),
|
|
obs(
|
|
"GROW",
|
|
day(2023, 6, 30),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2023, 8, 1)),
|
|
sample_fields(110.0, 12.0, 18.0, 520.0, 212.0, 10.0),
|
|
),
|
|
obs(
|
|
"GROW",
|
|
day(2023, 9, 30),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2023, 11, 1)),
|
|
sample_fields(125.0, 14.0, 20.0, 545.0, 226.0, 10.0),
|
|
),
|
|
obs(
|
|
"GROW",
|
|
day(2023, 12, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2024, 2, 15)),
|
|
sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0),
|
|
),
|
|
];
|
|
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"),
|
|
];
|
|
(observations, filings)
|
|
}
|
|
|
|
fn grow_mapping() -> (ProviderMappingTable, BTreeMap<i32, StatutoryLagVenue>) {
|
|
let mapping =
|
|
ProviderMappingTable::from_rows([mapping_row("qm", "GROW", day(2023, 1, 1), None, 777)])
|
|
.expect("valid mapping");
|
|
(mapping, BTreeMap::from([(777, StatutoryLagVenue::UsTsx)]))
|
|
}
|
|
|
|
#[test]
|
|
fn q1_amendment_after_q4_first_changes_ttm_at_its_filing_instant_and_keeps_q4_latest() {
|
|
let (mapping, venues) = grow_mapping();
|
|
let (observations, filings) = grow_four_quarters();
|
|
|
|
let baseline = curate_fundamentals(
|
|
observations.clone(),
|
|
filings.clone(),
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
)
|
|
.expect("baseline");
|
|
assert_eq!(baseline.rows.len(), 4);
|
|
let baseline_ttm = baseline.rows[3].ttm.clone().expect("baseline ttm");
|
|
assert_eq!(baseline_ttm.flows.revenue, Some(475.0));
|
|
|
|
let mut revised_obs = observations;
|
|
revised_obs.push(obs(
|
|
"GROW",
|
|
day(2023, 3, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2024, 3, 20)),
|
|
sample_fields(80.0, 4.0, 9.0, 480.0, 190.0, 10.0),
|
|
));
|
|
let mut revised_filings = filings;
|
|
revised_filings.push(filing("GROW", "2024-03-20T17:45:00 EDT", "10-Q/A"));
|
|
|
|
let revised = curate_fundamentals(revised_obs, revised_filings, "qm", &mapping, &venues, 4)
|
|
.expect("revised");
|
|
assert_stage_conservation(&revised.stats);
|
|
assert_eq!(revised.rows.len(), 5);
|
|
|
|
// Every pre-amendment snapshot is unchanged (no look-back leak of the restated Q1).
|
|
assert_eq!(&revised.rows[..4], &baseline.rows[..]);
|
|
|
|
let amend_at = utc_micros(2024, 3, 20, 21, 45, 0);
|
|
let amended = &revised.rows[4];
|
|
assert_eq!(amended.effective_known_at_micros, amend_at);
|
|
assert_eq!(
|
|
amended.known_at_source.as_ref(),
|
|
KNOWN_AT_SOURCE_FILING_TIMESTAMP
|
|
);
|
|
|
|
// Latest period stays Q4 with Q4's fields and Q4's original availability.
|
|
let latest = amended.latest_period().expect("latest");
|
|
assert_eq!(latest.period_end, day(2023, 12, 31));
|
|
assert_eq!(
|
|
latest.fields,
|
|
sample_fields(140.0, 16.0, 22.0, 575.0, 242.0, 10.0)
|
|
);
|
|
assert_eq!(
|
|
latest.period_known_at_micros,
|
|
utc_micros(2024, 2, 15, 21, 10, 0)
|
|
);
|
|
|
|
// The TTM total first reflects the restated Q1 at the amendment instant.
|
|
let ttm = amended.ttm.as_ref().expect("amended ttm");
|
|
assert_eq!(ttm.ending_period_end, day(2023, 12, 31));
|
|
assert_eq!(ttm.flows.revenue, Some(80.0 + 110.0 + 125.0 + 140.0));
|
|
assert_eq!(ttm.flows.net_income, Some(4.0 + 12.0 + 14.0 + 16.0));
|
|
assert_eq!(
|
|
ttm.flows.operating_cash_flow,
|
|
Some(9.0 + 18.0 + 20.0 + 22.0)
|
|
);
|
|
assert_ne!(ttm.flows, baseline_ttm.flows);
|
|
}
|
|
|
|
#[test]
|
|
fn late_december_eastern_filing_partitions_into_next_utc_year() {
|
|
// Listing 900 is valid through 2023-12-31 ET only; a 21:00 EST filing on Dec 31 is
|
|
// 2024-01-01T02:00Z, so it must resolve on the Eastern date but partition by UTC year.
|
|
let mapping = ProviderMappingTable::from_rows([mapping_row(
|
|
"qm",
|
|
"NYE",
|
|
day(2023, 1, 1),
|
|
Some(day(2023, 12, 31)),
|
|
900,
|
|
)])
|
|
.expect("valid mapping");
|
|
let venues = BTreeMap::from([(900, StatutoryLagVenue::UsTsx)]);
|
|
|
|
let observations = vec![
|
|
obs(
|
|
"NYE",
|
|
day(2023, 8, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2023, 10, 10)),
|
|
sample_fields(5.0, 1.0, 1.0, 20.0, 10.0, 1.0),
|
|
),
|
|
obs(
|
|
"NYE",
|
|
day(2023, 11, 30),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2023, 12, 31)),
|
|
sample_fields(6.0, 1.5, 1.2, 22.0, 11.0, 1.0),
|
|
),
|
|
];
|
|
let filings = vec![
|
|
filing("NYE", "2023-10-10T16:00:00 EDT", "10-Q"),
|
|
filing("NYE", "2023-12-31T21:00:00 EST", "10-Q"),
|
|
];
|
|
|
|
let tmp = TempDirGuard::new("nye");
|
|
let report = curate_and_write_fundamentals(
|
|
tmp.path(),
|
|
observations.clone(),
|
|
filings.clone(),
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
FundamentalsPitWriteOptions::default(),
|
|
)
|
|
.expect("curate and write");
|
|
assert_stage_conservation(&report.curate_stats);
|
|
assert_eq!(report.curate_stats.filings_dropped_unmapped, 0);
|
|
assert_eq!(report.curate_stats.build.rows_linked_to_filing, 2);
|
|
assert_eq!(
|
|
report.write_stats.rows_by_year,
|
|
BTreeMap::from([(2023, 1), (2024, 1)])
|
|
);
|
|
|
|
let curated =
|
|
curate_fundamentals(observations, filings, "qm", &mapping, &venues, 4).expect("curate");
|
|
let nye_row = &curated.rows[1];
|
|
assert_eq!(
|
|
nye_row.effective_known_at_micros,
|
|
utc_micros(2024, 1, 1, 2, 0, 0)
|
|
);
|
|
|
|
let y2024 = read_parquet_rows_by_name(
|
|
&tmp.path()
|
|
.join("fundamentals_pit")
|
|
.join("year=2024")
|
|
.join("part.parquet"),
|
|
);
|
|
assert_eq!(y2024, vec![decoded_from_curated(nye_row)]);
|
|
let y2023 = read_parquet_rows_by_name(
|
|
&tmp.path()
|
|
.join("fundamentals_pit")
|
|
.join("year=2023")
|
|
.join("part.parquet"),
|
|
);
|
|
assert_eq!(y2023, vec![decoded_from_curated(&curated.rows[0])]);
|
|
}
|
|
|
|
#[test]
|
|
fn filing_matching_mapping_only_by_utc_date_is_dropped_unmapped() {
|
|
// Mapping starts 2024-05-02 ET. The filing is 2024-05-01T21:00 EDT (= 2024-05-02T01:00Z):
|
|
// mapped on its UTC date it would link; on its Eastern date it must not.
|
|
let mapping =
|
|
ProviderMappingTable::from_rows([mapping_row("qm", "EDGE", day(2024, 5, 2), None, 42)])
|
|
.expect("valid mapping");
|
|
let venues = BTreeMap::from([(42, StatutoryLagVenue::UsTsx)]);
|
|
|
|
let out = curate_fundamentals(
|
|
[obs(
|
|
"EDGE",
|
|
day(2024, 6, 30),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
None,
|
|
sample_fields(1.0, 1.0, 1.0, 1.0, 1.0, 1.0),
|
|
)],
|
|
[filing("EDGE", "2024-05-01T21:00:00 EDT", "10-Q")],
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
)
|
|
.expect("curate");
|
|
assert_stage_conservation(&out.stats);
|
|
assert_eq!(out.stats.filings_in, 1);
|
|
assert_eq!(out.stats.filings_dropped_unmapped, 1);
|
|
assert_eq!(out.stats.build.filings_in, 0);
|
|
assert_eq!(out.stats.observations_dropped_unmapped, 0);
|
|
assert_eq!(out.rows.len(), 1);
|
|
assert_eq!(out.rows[0].listing_id, 42);
|
|
}
|
|
|
|
#[test]
|
|
fn wrong_mapping_source_drops_everything_and_mapped_listing_without_venue_is_counted_by_builder() {
|
|
let mapping = ProviderMappingTable::from_rows([
|
|
mapping_row("qm", "NOVENUE", day(2024, 1, 1), None, 7),
|
|
mapping_row("qm", "OK", day(2024, 1, 1), None, 8),
|
|
])
|
|
.expect("valid mapping");
|
|
let venues = BTreeMap::from([(8, StatutoryLagVenue::TsxvCse)]);
|
|
let f = sample_fields(3.0, 1.0, 1.0, 9.0, 4.0, 1.0);
|
|
let observations = vec![
|
|
obs(
|
|
"NOVENUE",
|
|
day(2024, 3, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"CAD",
|
|
Some(day(2024, 5, 20)),
|
|
f,
|
|
),
|
|
obs(
|
|
"OK",
|
|
day(2024, 3, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"CAD",
|
|
Some(day(2024, 5, 21)),
|
|
f,
|
|
),
|
|
];
|
|
let filings = vec![
|
|
filing(
|
|
"NOVENUE",
|
|
"2024-05-20T16:00:00 EDT",
|
|
"Interim financial statements",
|
|
),
|
|
filing(
|
|
"OK",
|
|
"2024-05-21T16:00:00 EDT",
|
|
"Interim financial statements",
|
|
),
|
|
];
|
|
|
|
let out = curate_fundamentals(
|
|
observations.clone(),
|
|
filings.clone(),
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
)
|
|
.expect("curate");
|
|
assert_stage_conservation(&out.stats);
|
|
assert_eq!(out.stats.observations_dropped_unmapped, 0);
|
|
assert_eq!(out.stats.build.observations_dropped_unknown_key, 1);
|
|
assert_eq!(out.stats.build.filings_dropped_unknown_key, 1);
|
|
assert_eq!(out.stats.listings_out, 1);
|
|
assert_eq!(out.stats.rows_out, 1);
|
|
assert_eq!(out.rows[0].listing_id, 8);
|
|
|
|
let other = curate_fundamentals(observations, filings, "eodhd", &mapping, &venues, 4)
|
|
.expect("other source");
|
|
assert_stage_conservation(&other.stats);
|
|
assert_eq!(other.stats.observations_dropped_unmapped, 2);
|
|
assert_eq!(other.stats.filings_dropped_unmapped, 2);
|
|
assert!(other.rows.is_empty());
|
|
assert_eq!(other.stats.listings_out, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn rebuilding_from_inputs_available_by_each_cutoff_reproduces_the_published_prefix() {
|
|
// PIT audit: for each published instant t, rebuild from only the (observation, filing)
|
|
// pairs available at or before t; the result must equal the full run's rows with
|
|
// effective_known_at <= t. Then append an extreme far-future revision and require every
|
|
// earlier row to stay byte-identical.
|
|
let mapping = ProviderMappingTable::from_rows([
|
|
mapping_row("qm", "GROW", day(2023, 1, 1), None, 777),
|
|
mapping_row("qm", "SMALL", day(2023, 1, 1), None, 555),
|
|
])
|
|
.expect("valid mapping");
|
|
let venues = BTreeMap::from([
|
|
(777, StatutoryLagVenue::UsTsx),
|
|
(555, StatutoryLagVenue::TsxvCse),
|
|
]);
|
|
let (mut observations, mut filings) = grow_four_quarters();
|
|
observations.push(obs(
|
|
"SMALL",
|
|
day(2023, 6, 30),
|
|
FiscalPeriod::Quarterly,
|
|
"CAD",
|
|
Some(day(2023, 8, 1)),
|
|
sample_fields(2.0, 0.5, 0.4, 8.0, 3.0, 50.0),
|
|
));
|
|
filings.push(filing(
|
|
"SMALL",
|
|
"2023-08-01T16:10:00 EDT",
|
|
"Interim financial statements",
|
|
));
|
|
observations.push(obs(
|
|
"SMALL",
|
|
day(2023, 9, 30),
|
|
FiscalPeriod::Quarterly,
|
|
"CAD",
|
|
Some(day(2023, 11, 20)),
|
|
sample_fields(2.5, 0.6, 0.5, 9.0, 3.4, 50.0),
|
|
));
|
|
filings.push(filing(
|
|
"SMALL",
|
|
"2023-11-20T09:00:00 EST",
|
|
"Interim financial statements",
|
|
));
|
|
|
|
let full = curate_fundamentals(
|
|
observations.clone(),
|
|
filings.clone(),
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
)
|
|
.expect("full");
|
|
assert_eq!(full.rows.len(), 6);
|
|
|
|
let pair_known_at: Vec<i64> = filings
|
|
.iter()
|
|
.map(|f| parse_filing_timefiled(&f.timefiled).expect("ts").utc_micros)
|
|
.collect();
|
|
for cutoff in full.rows.iter().map(|r| r.effective_known_at_micros) {
|
|
let keep: Vec<usize> = (0..filings.len())
|
|
.filter(|&i| pair_known_at[i] <= cutoff)
|
|
.collect();
|
|
let truncated = curate_fundamentals(
|
|
keep.iter().map(|&i| observations[i].clone()),
|
|
keep.iter().map(|&i| filings[i].clone()),
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
)
|
|
.expect("truncated");
|
|
let mut expected: Vec<FundamentalsPitParquetRow> = full
|
|
.rows
|
|
.iter()
|
|
.filter(|r| r.effective_known_at_micros <= cutoff)
|
|
.cloned()
|
|
.collect();
|
|
expected.sort_by_key(|r| (r.listing_id, r.effective_known_at_micros));
|
|
assert_eq!(truncated.rows, expected, "cutoff {cutoff}");
|
|
}
|
|
|
|
let mut future_obs = observations.clone();
|
|
future_obs.push(obs(
|
|
"GROW",
|
|
day(2023, 3, 31),
|
|
FiscalPeriod::Quarterly,
|
|
"USD",
|
|
Some(day(2030, 1, 2)),
|
|
sample_fields(1.0e12, -1.0e12, 1.0e12, 1.0e13, -1.0e12, 1.0),
|
|
));
|
|
let mut future_filings = filings.clone();
|
|
future_filings.push(filing("GROW", "2030-01-02T16:00:00 EST", "10-Q/A"));
|
|
let with_future = curate_fundamentals(future_obs, future_filings, "qm", &mapping, &venues, 4)
|
|
.expect("with future revision");
|
|
assert_stage_conservation(&with_future.stats);
|
|
let future_at = utc_micros(2030, 1, 2, 21, 0, 0);
|
|
let before: Vec<_> = with_future
|
|
.rows
|
|
.iter()
|
|
.filter(|r| r.effective_known_at_micros < future_at)
|
|
.cloned()
|
|
.collect();
|
|
assert_eq!(before, full.rows);
|
|
assert_eq!(with_future.rows.len(), full.rows.len() + 1);
|
|
}
|
|
|
|
#[test]
|
|
fn empty_inputs_yield_no_rows_and_zero_stats() {
|
|
let (mapping, venues) = grow_mapping();
|
|
let out = curate_fundamentals(
|
|
Vec::<FinancialObservation<String>>::new(),
|
|
Vec::<QmFiling<String>>::new(),
|
|
"qm",
|
|
&mapping,
|
|
&venues,
|
|
4,
|
|
)
|
|
.expect("empty");
|
|
assert!(out.rows.is_empty());
|
|
assert_eq!(out.stats, CurateFundamentalsStats::default());
|
|
}
|