T-132: M2.2a — tools/curate-etl: pure point-in-time fundamentals builder (qmFinancials × qmFilings known_at link + statutory-lag fallback → bitemporal rows → 2D PIT snapshots + TTM) with restatement fixture test and local benchmark (no new crates)

This commit is contained in:
Studio 2026-12-01 00:16:33 -05:00
parent f0f55acef2
commit 7f2d5c46d7
7 changed files with 2110 additions and 2 deletions

View file

@ -1553,6 +1553,41 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks).
## Point-in-Time Fundamentals Core (`M2.2a`)
Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks.
### Public API & Field Set
- **Single field definition (`FundamentalsFields`):**
- Flow fields (4-quarter TTM-eligible): `revenue`, `net_income`, `operating_cash_flow`.
- Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`.
- **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation<K>` against periodic `events::QmFiling<K>` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap<K, StatutoryLagVenue>` (`UsTsx` vs `TsxvCse`).
- `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked.
- **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated.
- **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field).
- **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`.
- **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`.
- **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):**
- Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot<K>` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order.
- Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate.
- Computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency.
- `as_of(snapshots, key, as_of_micros)` performs an inclusive `O(log N)` binary search on `(key, effective_known_at_utc_micros)`.
### `bench-fundamentals`
Fixed-seed (`SplitMix64`), offline benchmark exercising both venue classes, linked periodic filings, statutory-lag fallback, exact duplicates, complete 4-quarter TTM histories, and late Q1 amendments across both stages (`k = 4`):
```bash
cargo run -p curate-etl --release --offline -- bench-fundamentals [rows]
```
Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0x078d99c42d5f200b`):
- **Run 1:** Stage 1 `47.19 ms`, Stage 2 `35.75 ms`, total `82.94 ms` (`1,205,683 rows/s`, `829.41 ns/row`)
- **Run 2:** Stage 1 `43.89 ms`, Stage 2 `37.88 ms`, total `81.78 ms` (`1,222,862 rows/s`, `817.75 ns/row`)
- **500k scale check (`rows = 500000`, `filings = 395406`, `keys = 12500`, `rows_out = 485524`, `snapshots_out = 485518`, checksum `0x44fda3cd5f82ce5e`):** Stage 1 `277.89 ms`, Stage 2 `212.92 ms`, total `490.81 ms` (`1,018,714 rows/s`, `981.63 ns/row`)
## Exporting Input Files (`data-pipeline`)
All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`:

View file

@ -1,6 +1,7 @@
//! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop.
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::hint::black_box;
use std::io;
@ -38,6 +39,10 @@ use crate::events::{
EventsStats, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING,
KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG,
};
use crate::fundamentals::{
build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod,
FundamentalsError, FundamentalsFields, FundamentalsStats, StatutoryLagVenue,
};
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD};
use crate::parquet_adj::{
write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError,
@ -76,6 +81,7 @@ pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000;
pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000;
pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000;
pub const DEFAULT_FUNDAMENTALS_BENCH_ROWS: usize = 100_000;
pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000;
pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000;
pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84;
@ -117,6 +123,9 @@ const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000;
const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500;
const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500;
const FUNDAMENTALS_BENCH_SEED: u64 = 0x570C_4B07_F04D_A001;
const FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY: usize = 40;
const FUNDAMENTALS_BENCH_SNAPSHOT_K: usize = 4;
const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00;
const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45;
const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404;
@ -10934,6 +10943,261 @@ pub fn run_curate_events_cmd_benchmark(
Ok(report)
}
/// Summary metrics produced by [`run_fundamentals_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FundamentalsBenchReport {
pub rows: usize,
pub filings_in: usize,
pub key_count: usize,
pub rows_out: usize,
pub keys_out: usize,
pub snapshots_out: usize,
pub rows_elapsed_ms: f64,
pub snapshots_elapsed_ms: f64,
pub total_elapsed_ms: f64,
pub rows_per_sec: f64,
pub ns_per_row: f64,
pub checksum: u64,
pub stats: FundamentalsStats,
}
fn format_bench_filing_timefiled(epoch_day: i32, hour: u8, minute: u8, second: u8) -> String {
let (y, m, d) = epoch_days_to_ymd(epoch_day);
let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" };
format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}")
}
/// Runs the fixed-seed two-stage `fundamentals` benchmark (`build_fundamentals_rows` +
/// `build_fundamentals_snapshots`) for `rows` synthetic statement observations.
///
/// Generates filings and observations before timing, exercising both `UsTsx` and `TsxvCse` venue
/// classes, linked periodic filings (10-Q/10-K/40-F/SEDAR), statutory-lag fallback, exact
/// duplicates, complete 4-quarter histories for TTM, and late Q1-style amendments.
pub fn run_fundamentals_benchmark(
rows: usize,
) -> Result<FundamentalsBenchReport, FundamentalsError> {
if rows == 0 {
return Ok(FundamentalsBenchReport {
rows: 0,
filings_in: 0,
key_count: 0,
rows_out: 0,
keys_out: 0,
snapshots_out: 0,
rows_elapsed_ms: 0.0,
snapshots_elapsed_ms: 0.0,
total_elapsed_ms: 0.0,
rows_per_sec: 0.0,
ns_per_row: 0.0,
checksum: 0,
stats: FundamentalsStats::default(),
});
}
let key_count = (rows / FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY).max(1);
let mut venues: BTreeMap<i32, StatutoryLagVenue> = BTreeMap::new();
for k in 1..=(key_count as i32) {
let venue = if k % 10 < 7 {
StatutoryLagVenue::UsTsx
} else {
StatutoryLagVenue::TsxvCse
};
venues.insert(k, venue);
}
let base_start = ymd_to_epoch_days(2015, 3, 31).unwrap_or(16_525);
let mut rng = SplitMix64::new(FUNDAMENTALS_BENCH_SEED);
let mut observations: Vec<FinancialObservation<i32>> = Vec::with_capacity(rows);
let mut filings: Vec<QmFiling<i32>> = Vec::with_capacity(rows);
let mut period_step: i32 = 0;
while observations.len() < rows {
for key in 1..=(key_count as i32) {
if observations.len() >= rows {
break;
}
let venue = venues[&key];
let currency = match venue {
StatutoryLagVenue::UsTsx => {
if key % 5 == 0 {
"CAD"
} else {
"USD"
}
}
StatutoryLagVenue::TsxvCse => "CAD",
};
let is_annual = period_step % 5 == 4;
let quarter_index = period_step - (period_step / 5);
let period_end = if is_annual {
base_start + (quarter_index - 1) * 91 + 1
} else {
base_start + quarter_index * 91
};
let fiscal_period = if is_annual {
FiscalPeriod::Annual
} else {
FiscalPeriod::Quarterly
};
let rev = ((rng.next_u64() % 50_000) + 1_000) as f64;
let fields = FundamentalsFields {
revenue: Some(rev),
net_income: Some(rev * 0.12),
operating_cash_flow: Some(rev * 0.18),
total_assets: Some(rev * 4.5),
total_equity: Some(rev * 2.1),
shares_outstanding: Some(1_000_000.0 + (key as f64) * 100.0),
};
let roll = rng.next_u64() % 100;
let report_date = if roll < 75 {
let lag = 25 + (rng.next_u64() % 30) as i32;
let file_day = period_end + lag;
let form_type = match (venue, fiscal_period) {
(StatutoryLagVenue::UsTsx, FiscalPeriod::Quarterly) => "10-Q",
(StatutoryLagVenue::UsTsx, FiscalPeriod::Annual) => {
if key % 5 == 0 {
"40-F"
} else {
"10-K"
}
}
(StatutoryLagVenue::TsxvCse, FiscalPeriod::Quarterly) => {
"Interim financial statements/report - English"
}
(StatutoryLagVenue::TsxvCse, FiscalPeriod::Annual) => {
"Annual financial statements - English"
}
};
let hour = 8 + (rng.next_u64() % 10) as u8;
let minute = (rng.next_u64() % 60) as u8;
filings.push(QmFiling {
key,
timefiled: format_bench_filing_timefiled(file_day, hour, minute, 0),
form_type: form_type.to_string(),
filing_id: None,
url: None,
});
if roll < 50 {
Some(file_day)
} else {
None
}
} else {
None
};
if roll % 19 == 0 {
filings.push(QmFiling {
key,
timefiled: format_bench_filing_timefiled(period_end + 10, 16, 15, 0),
form_type: "8-K".to_string(),
filing_id: None,
url: None,
});
}
let obs = FinancialObservation {
key,
period_end,
fiscal_period,
currency: currency.to_string(),
report_date,
fields,
};
observations.push(obs.clone());
// ~3% exact duplicate
if observations.len() < rows && roll < 3 {
observations.push(obs);
}
// ~2% late amendment of prior quarter (after current quarter's filing)
if observations.len() < rows && !is_annual && quarter_index >= 1 && (3..5).contains(&roll)
{
let prior_pe = period_end - 91;
let amend_day = period_end + 60;
filings.push(QmFiling {
key,
timefiled: format_bench_filing_timefiled(amend_day, 17, 0, 0),
form_type: "10-Q/A".to_string(),
filing_id: None,
url: None,
});
observations.push(FinancialObservation {
key,
period_end: prior_pe,
fiscal_period: FiscalPeriod::Quarterly,
currency: currency.to_string(),
report_date: Some(amend_day),
fields: FundamentalsFields {
revenue: Some(rev * 1.03),
net_income: Some(rev * 0.13),
operating_cash_flow: None,
total_assets: None,
total_equity: Some(rev * 2.15),
shares_outstanding: None,
},
});
}
}
period_step += 1;
}
let filings_in = filings.len();
let rows_start = Instant::now();
let built = build_fundamentals_rows(observations, filings, &venues);
let rows_elapsed_secs = rows_start.elapsed().as_secs_f64();
let snaps_start = Instant::now();
let snapshots = build_fundamentals_snapshots(&built.rows, FUNDAMENTALS_BENCH_SNAPSHOT_K)?;
let snaps_elapsed_secs = snaps_start.elapsed().as_secs_f64();
let total_elapsed_secs = rows_elapsed_secs + snaps_elapsed_secs;
let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs);
let mut hash = 0u64;
for row in &built.rows {
hash = mix_u64(hash, row.key as u64);
hash = mix_u64(hash, row.period_end as u64);
hash = mix_u64(hash, row.known_at_utc_micros as u64);
hash = mix_u64(hash, row.fiscal_period as u64);
hash = mix_u64(hash, row.fields.revenue.map_or(0, f64::to_bits));
hash = mix_u64(hash, row.fields.total_assets.map_or(0, f64::to_bits));
}
for snap in &snapshots {
hash = mix_u64(hash, snap.key as u64);
hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64);
hash = mix_u64(hash, u64::from(snap.has_estimated_lag));
hash = mix_u64(hash, snap.periods.len() as u64);
if let Some(ttm) = &snap.ttm {
hash = mix_u64(hash, ttm.ending_period_end as u64);
hash = mix_u64(hash, ttm.flows.revenue.map_or(0, f64::to_bits));
hash = mix_u64(hash, u64::from(ttm.has_estimated_lag));
}
}
let checksum = black_box(hash);
Ok(FundamentalsBenchReport {
rows,
filings_in,
key_count,
rows_out: built.stats.rows_out,
keys_out: built.stats.keys_out,
snapshots_out: snapshots.len(),
rows_elapsed_ms: rows_elapsed_secs * 1_000.0,
snapshots_elapsed_ms: snaps_elapsed_secs * 1_000.0,
total_elapsed_ms: total_elapsed_secs * 1_000.0,
rows_per_sec,
ns_per_row,
checksum,
stats: built.stats,
})
}
#[cfg(test)]
mod tests {
use super::*;
@ -13077,4 +13341,45 @@ mod tests {
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
#[test]
fn fundamentals_benchmark_small_run_is_deterministic_and_conserves_counts() {
let a = run_fundamentals_benchmark(1_000).unwrap();
let b = run_fundamentals_benchmark(1_000).unwrap();
assert_eq!(a.rows, 1_000);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert_eq!(a.rows_out, b.rows_out);
assert_eq!(a.snapshots_out, b.snapshots_out);
assert_eq!(a.stats, b.stats);
assert!(a.rows_out > 0);
assert!(a.snapshots_out > 0);
assert!(a.stats.rows_linked_to_filing > 0);
assert!(a.stats.rows_statutory_lag_estimate > 0);
assert!(a.stats.duplicate_collapsed > 0);
assert_eq!(
a.stats.observations_in,
a.stats.rows_out
+ a.stats.observations_dropped_unknown_key
+ a.stats.observations_dropped_non_finite
+ a.stats.observations_dropped_date_out_of_range
+ a.stats.observations_dropped_report_date_not_after_period_end
+ a.stats.observations_dropped_unanchored_vintage
+ a.stats.duplicate_collapsed
+ a.stats.duplicate_conflict_dropped
);
}
#[test]
fn fundamentals_benchmark_zero_rows_handles_cleanly() {
let report = run_fundamentals_benchmark(0).unwrap();
assert_eq!(report.rows, 0);
assert_eq!(report.filings_in, 0);
assert_eq!(report.rows_out, 0);
assert_eq!(report.snapshots_out, 0);
assert_eq!(report.checksum, 0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
}

View file

@ -18,7 +18,8 @@ use crate::bench::{
DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS,
DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS,
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
DEFAULT_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS,
DEFAULT_PARQUET_BARS_BENCH_ROWS,
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
@ -75,6 +76,7 @@ pub enum CliAction {
BenchFx(usize),
BenchShorts(usize),
BenchEvents(usize),
BenchFundamentals(usize),
BenchProviderMapping(usize),
BenchParquetBars(usize),
BenchParquetShorts(usize),
@ -134,6 +136,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\
{name} bench-fundamentals [rows] Run fixed-seed fundamentals bitemporal + PIT snapshot benchmark (default: {DEFAULT_FUNDAMENTALS_BENCH_ROWS})\n\
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\
{name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})\n\
{name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\
@ -180,6 +183,7 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-fx [rows]\n\
{name} bench-shorts [rows]\n\
{name} bench-events [rows]\n\
{name} bench-fundamentals [rows]\n\
{name} bench-provider-mapping [lookups]\n\
{name} bench-parquet-bars [rows]\n\
{name} bench-parquet-shorts [rows]\n\
@ -1498,6 +1502,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
)),
},
["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()),
["bench-fundamentals"] => Ok(CliAction::BenchFundamentals(
DEFAULT_FUNDAMENTALS_BENCH_ROWS,
)),
["bench-fundamentals", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchFundamentals(n)),
_ => Err(format!(
"invalid row count '{raw}' (expected a positive integer)"
)),
},
["bench-fundamentals", _, ..] => {
Err("too many arguments for bench-fundamentals".to_string())
}
["bench-provider-mapping"] => Ok(CliAction::BenchProviderMapping(
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS,
)),
@ -3404,5 +3420,18 @@ mod tests {
assert!(parse_args(&to_args(&["bench-curate-events-cmd", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err());
// bench-fundamentals
assert_eq!(
parse_args(&to_args(&["bench-fundamentals"])),
Ok(CliAction::BenchFundamentals(DEFAULT_FUNDAMENTALS_BENCH_ROWS))
);
assert_eq!(
parse_args(&to_args(&["bench-fundamentals", "2500"])),
Ok(CliAction::BenchFundamentals(2_500))
);
assert!(parse_args(&to_args(&["bench-fundamentals", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err());
}
}

View file

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

View file

@ -0,0 +1,739 @@
use super::*;
use crate::split::ymd_to_epoch_days;
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 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 fields_rev(rev: f64) -> FundamentalsFields {
FundamentalsFields {
revenue: Some(rev),
net_income: Some(rev * 0.1),
operating_cash_flow: Some(rev * 0.15),
total_assets: Some(rev * 5.0),
total_equity: Some(rev * 2.0),
shares_outstanding: Some(1_000.0),
}
}
fn venues_map(entries: &[(&str, StatutoryLagVenue)]) -> BTreeMap<String, StatutoryLagVenue> {
entries
.iter()
.map(|&(k, v)| (k.to_string(), v))
.collect()
}
fn assert_reconciliation<K: Ord>(build: &FundamentalsBuild<K>) {
let s = &build.stats;
assert_eq!(s.rows_out, build.rows.len());
assert_eq!(
s.rows_out,
s.rows_linked_to_filing + s.rows_statutory_lag_estimate,
"output provenance mismatch: {s:?}"
);
assert_eq!(
s.observations_in,
s.rows_out
+ s.observations_dropped_unknown_key
+ s.observations_dropped_non_finite
+ s.observations_dropped_date_out_of_range
+ s.observations_dropped_report_date_not_after_period_end
+ s.observations_dropped_unanchored_vintage
+ s.duplicate_collapsed
+ s.duplicate_conflict_dropped,
"observation reconciliation failed: {s:?}"
);
assert_eq!(
s.filings_in,
s.filings_eligible
+ s.filings_dropped_unknown_key
+ s.filings_ignored_non_periodic
+ s.filings_dropped_invalid_timestamp
+ s.filings_dropped_date_out_of_range
+ s.filings_dropped_before_period_end,
"filing reconciliation failed: {s:?}"
);
for pair in build.rows.windows(2) {
assert!(
(&pair[0].key, pair[0].period_end, pair[0].known_at_utc_micros)
< (&pair[1].key, pair[1].period_end, pair[1].known_at_utc_micros),
"rows must be strictly sorted and unique by (key, period_end, known_at_utc_micros)"
);
}
}
#[test]
fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2() {
let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]);
let p_2023_q3 = day(2023, 9, 30);
let p_2023_q4 = day(2023, 12, 31);
let p_2024_q1 = day(2024, 3, 31);
let p_2024_q2 = day(2024, 6, 30);
let initial_filings = vec![
filing("ACME", "2023-11-01T16:15:00 EDT", "10-Q"),
filing("ACME", "2024-02-01T16:15:00 EST", "10-Q"),
filing("ACME", "2024-05-01T16:15:00 EDT", "10-Q"),
filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"),
];
let amendment_filing = filing("ACME", "2024-09-15T17:00:00 EDT", "10-Q/A");
let initial_obs = vec![
obs(
"ACME",
p_2023_q3,
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 11, 1)),
FundamentalsFields {
revenue: Some(70.0),
net_income: Some(7.0),
operating_cash_flow: Some(10.0),
total_assets: Some(500.0),
total_equity: Some(200.0),
shares_outstanding: Some(100.0),
},
),
obs(
"ACME",
p_2023_q4,
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 2, 1)),
FundamentalsFields {
revenue: Some(80.0),
net_income: Some(8.0),
operating_cash_flow: Some(12.0),
total_assets: Some(520.0),
total_equity: Some(210.0),
shares_outstanding: Some(100.0),
},
),
obs(
"ACME",
p_2024_q1,
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 5, 1)),
FundamentalsFields {
revenue: Some(100.0),
net_income: Some(10.0),
operating_cash_flow: Some(15.0),
total_assets: Some(540.0),
total_equity: Some(220.0),
shares_outstanding: Some(100.0),
},
),
obs(
"ACME",
p_2024_q2,
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 8, 1)),
FundamentalsFields {
revenue: Some(120.0),
net_income: Some(12.0),
operating_cash_flow: Some(18.0),
total_assets: Some(560.0),
total_equity: Some(230.0),
shares_outstanding: Some(100.0),
},
),
];
// Q1 amendment filed on 2024-09-15 (168 days after Q1 period end, beyond 75d window)
// Restates revenue from 100 -> 110 and omits operating_cash_flow & total_assets (None).
let q1_amendment = obs(
"ACME",
p_2024_q1,
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 9, 15)),
FundamentalsFields {
revenue: Some(110.0),
net_income: Some(11.0),
operating_cash_flow: None,
total_assets: None,
total_equity: Some(225.0),
shares_outstanding: None,
},
);
let mut full_obs = initial_obs.clone();
full_obs.push(q1_amendment);
let mut full_filings = initial_filings.clone();
full_filings.push(amendment_filing);
let full_build = build_fundamentals_rows(full_obs, full_filings, &venues);
assert_reconciliation(&full_build);
assert_eq!(full_build.stats.rows_out, 5);
assert_eq!(full_build.stats.rows_linked_to_filing, 5);
assert_eq!(full_build.stats.rows_statutory_lag_estimate, 0);
let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).unwrap();
assert_eq!(full_snaps.len(), 5);
let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0);
let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0);
// As-of strictly between Q2 filing and Q1 restatement (also check exact Q2 timestamp).
for probe in [ts_q2, ts_amend - 1] {
let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible after Q2");
assert_eq!(snap.effective_known_at_utc_micros, ts_q2);
assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert!(!snap.has_estimated_lag);
assert_eq!(snap.periods[0].period_end, p_2024_q2);
assert_eq!(snap.periods[0].fields.revenue, Some(120.0));
assert_eq!(snap.periods[1].period_end, p_2024_q1);
assert_eq!(snap.periods[1].fields.revenue, Some(100.0));
assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0));
let ttm = snap.ttm.as_ref().expect("4 consecutive quarters");
assert_eq!(ttm.ending_period_end, p_2024_q2);
assert_eq!(ttm.flows.revenue, Some(370.0));
assert_eq!(ttm.flows.net_income, Some(37.0));
assert_eq!(ttm.flows.operating_cash_flow, Some(55.0));
}
// As-of at and after the Q1 restatement: Q2 stays latest and unchanged, Q1 updated + inherited, TTM updated.
for probe in [ts_amend, ts_amend + 1_000_000] {
let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible at/after amendment");
assert_eq!(snap.effective_known_at_utc_micros, ts_amend);
assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert!(!snap.has_estimated_lag);
assert_eq!(snap.periods[0].period_end, p_2024_q2);
assert_eq!(snap.periods[0].fields.revenue, Some(120.0));
assert_eq!(snap.periods[0].fields.total_assets, Some(560.0));
assert_eq!(snap.periods[1].period_end, p_2024_q1);
assert_eq!(snap.periods[1].known_at_utc_micros, ts_amend);
assert_eq!(snap.periods[1].fields.revenue, Some(110.0));
assert_eq!(snap.periods[1].fields.net_income, Some(11.0));
// Omitted fields inherited from original Q1
assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0));
assert_eq!(snap.periods[1].fields.total_assets, Some(540.0));
assert_eq!(snap.periods[1].fields.shares_outstanding, Some(100.0));
assert_eq!(snap.periods[1].fields.total_equity, Some(225.0));
let ttm = snap.ttm.as_ref().expect("4 consecutive quarters");
assert_eq!(ttm.ending_period_end, p_2024_q2);
assert_eq!(ttm.flows.revenue, Some(380.0));
assert_eq!(ttm.flows.net_income, Some(38.0));
assert_eq!(ttm.flows.operating_cash_flow, Some(55.0));
}
// Truncation test: rebuild without future amendment and its filing; all earlier snapshots identical.
let trunc_build = build_fundamentals_rows(initial_obs, initial_filings, &venues);
assert_reconciliation(&trunc_build);
let trunc_snaps = build_fundamentals_snapshots(&trunc_build.rows, 4).unwrap();
assert_eq!(trunc_snaps.len(), 4);
assert_eq!(&full_snaps[..4], &trunc_snaps[..]);
}
#[test]
fn known_at_filing_linking_covers_all_periodic_forms_zones_windows_and_exclusions() {
let venues = venues_map(&[
("US_Q", StatutoryLagVenue::UsTsx),
("US_A", StatutoryLagVenue::UsTsx),
("CA_40F", StatutoryLagVenue::UsTsx),
("SEDAR_Q", StatutoryLagVenue::TsxvCse),
("SEDAR_A", StatutoryLagVenue::TsxvCse),
("WIN_Q", StatutoryLagVenue::UsTsx),
("WIN_A", StatutoryLagVenue::UsTsx),
("NOISE", StatutoryLagVenue::UsTsx),
]);
let filings = vec![
// Late-evening EDT filing whose UTC date is the next day (2024-05-11T01:30:00Z)
filing("US_Q", "2024-05-10T21:30:00 EDT", "10-Q"),
// EST annual 10-K
filing("US_A", "2024-03-01T08:15:30 EST", "10-K"),
// 40-F annual
filing("CA_40F", "2024-03-15T14:00:00 EDT", "40-F"),
// SEDAR interim & annual
filing("SEDAR_Q", "2024-05-20T18:00:00 EDT", "Interim financial statements/report - English"),
filing("SEDAR_A", "2024-04-20T12:30:00 EDT", "Annual financial statements - English"),
// Window boundary filings for undated quarterly (period_end = 2024-03-31 -> +75d = 2024-06-14, +76d = 2024-06-15)
// Also add an earlier 10-Q/A on 2024-05-01 which undated observation must ignore!
filing("WIN_Q", "2024-05-01T10:00:00 EDT", "10-Q/A"),
filing("WIN_Q", "2024-06-14T11:00:00 EDT", "10-Q"),
// Window boundary for undated annual (period_end = 2023-12-31 -> +150d = 2024-05-29, +151d = 2024-05-30)
filing("WIN_A", "2024-05-29T15:00:00 EDT", "10-K"),
// Non-periodic 8-K, wrong kind (10-K for quarterly), and wrong listing
filing("NOISE", "2024-05-05T09:00:00 EDT", "8-K"),
filing("NOISE", "2024-05-05T09:30:00 EDT", "News release"),
filing("NOISE", "2024-05-05T10:00:00 EDT", "10-K"),
];
let observations = vec![
// Same-day match across UTC midnight rollover (ET date = 2024-05-10)
obs("US_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 10)), fields_rev(10.0)),
obs("US_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)),
obs("CA_40F", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(30.0)),
obs("SEDAR_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(40.0)),
obs("SEDAR_A", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(50.0)),
// Exact +75d inclusive boundary -> links to 2024-06-14 10-Q (skipping 2024-05-01 10-Q/A)
obs("WIN_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(60.0)),
// Exact +76d (period_end = 2024-03-30 -> 2024-06-14 is +76d) -> outside window, falls back!
obs("WIN_Q", day(2024, 3, 30), FiscalPeriod::Quarterly, "USD", None, fields_rev(61.0)),
// Exact +150d inclusive boundary -> links to 2024-05-29 10-K
obs("WIN_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(70.0)),
// Exact +151d (period_end = 2023-12-30 -> 2024-05-29 is +151d) -> outside window, falls back!
obs("WIN_A", day(2023, 12, 30), FiscalPeriod::Annual, "USD", None, fields_rev(71.0)),
// NOISE quarterly: 8-K, News release, and 10-K must NOT link -> statutory lag fallback
obs("NOISE", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(80.0)),
];
let built = build_fundamentals_rows(observations, filings, &venues);
assert_reconciliation(&built);
assert_eq!(built.stats.filings_ignored_non_periodic, 2);
assert_eq!(built.stats.rows_linked_to_filing, 7);
assert_eq!(built.stats.rows_statutory_lag_estimate, 3);
let find = |k: &str, pe: i32| {
built
.rows
.iter()
.find(|r| r.key == k && r.period_end == pe)
.expect("row present")
};
assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 11, 1, 30, 0));
assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert_eq!(find("US_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 1, 13, 15, 30));
assert_eq!(find("CA_40F", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 15, 18, 0, 0));
assert_eq!(find("SEDAR_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 20, 22, 0, 0));
assert_eq!(find("SEDAR_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 20, 16, 30, 0));
// Window boundaries
assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 6, 14, 15, 0, 0));
assert_eq!(find("WIN_Q", day(2024, 3, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
assert_eq!(find("WIN_A", day(2023, 12, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert_eq!(find("WIN_A", day(2023, 12, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
// 8-K and wrong-kind 10-K did not link
assert_eq!(find("NOISE", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
}
#[test]
fn statutory_lag_fallback_exact_offsets_dst_boundary_and_unanchored_vintage() {
let venues = venues_map(&[
("US", StatutoryLagVenue::UsTsx),
("VN", StatutoryLagVenue::TsxvCse),
]);
// Spring DST 2024 is Sunday 2024-03-10:
// - 2024-01-24 + 45d = 2024-03-09 (EST, UTC-5) -> 16:05 ET == 21:05 UTC
// - 2024-01-25 + 45d = 2024-03-10 (EDT, UTC-4) -> 16:05 ET == 20:05 UTC
let observations = vec![
// US/TSX Quarterly (+45d) before DST
obs("US", day(2024, 1, 24), FiscalPeriod::Quarterly, "USD", None, fields_rev(10.0)),
// US/TSX Quarterly (+45d) on spring DST Sunday
obs("US", day(2024, 1, 25), FiscalPeriod::Quarterly, "USD", None, fields_rev(11.0)),
// US/TSX Annual (+90d): 2023-12-31 + 90d = 2024-03-30 (EDT, 2024 is leap year)
obs("US", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)),
// TSXV/CSE Quarterly (+60d): 2024-03-31 + 60d = 2024-05-30 (EDT)
obs("VN", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(30.0)),
// TSXV/CSE Annual (+120d): 2023-12-31 + 120d = 2024-04-29 (EDT)
obs("VN", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(40.0)),
// Dated record with no same-day filing and report_date == lag_date -> allowed fallback
obs(
"US",
day(2024, 6, 30),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 6, 30) + 45),
fields_rev(50.0),
),
// Dated record with no same-day filing and report_date > lag_date -> dropped as unanchored vintage!
obs(
"US",
day(2024, 9, 30),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 9, 30) + 46),
fields_rev(60.0),
),
];
let built = build_fundamentals_rows(observations, Vec::<QmFiling<String>>::new(), &venues);
assert_reconciliation(&built);
assert_eq!(built.stats.rows_out, 6);
assert_eq!(built.stats.rows_statutory_lag_estimate, 6);
assert_eq!(built.stats.observations_dropped_unanchored_vintage, 1);
let find = |k: &str, pe: i32| {
built
.rows
.iter()
.find(|r| r.key == k && r.period_end == pe)
.expect("row present")
};
assert_eq!(find("US", day(2024, 1, 24)).known_at_utc_micros, utc_micros(2024, 3, 9, 21, 5, 0));
assert_eq!(find("US", day(2024, 1, 25)).known_at_utc_micros, utc_micros(2024, 3, 10, 20, 5, 0));
assert_eq!(find("US", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 30, 20, 5, 0));
assert_eq!(find("VN", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 30, 20, 5, 0));
assert_eq!(find("VN", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 29, 20, 5, 0));
assert_eq!(
find("US", day(2024, 6, 30)).known_at_utc_micros,
et_to_utc_micros(day(2024, 6, 30) + 45, 16, 5, 0).unwrap()
);
}
#[test]
fn ttm_handles_gaps_fy_rows_currency_missing_overflow_carry_forward_and_provenance() {
// 1. Quarter spacing boundaries (76 rejected, 77 accepted, 105 accepted, 106 rejected)
let make_row = |key: &str, pe: i32, kind: FiscalPeriod, curr: &str, ts: i64, src: &'static str, fields: FundamentalsFields| {
FundamentalsRow {
key: key.to_string(),
period_end: pe,
fiscal_period: kind,
currency: curr.to_string(),
known_at_utc_micros: ts,
known_at_source: src,
fields,
}
};
let base = day(2023, 1, 1);
// Exact 77-day spacing -> TTM computed
let rows_77 = vec![
make_row("G77", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)),
make_row("G77", base + 77, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)),
make_row("G77", base + 154, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)),
make_row("G77", base + 231, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)),
];
let snaps_77 = build_fundamentals_snapshots(&rows_77, 2).unwrap();
assert!(snaps_77[2].ttm.is_none()); // only 3 quarters
let ttm_77 = snaps_77[3].ttm.as_ref().expect("77d spacing is consecutive");
assert_eq!(ttm_77.flows.revenue, Some(100.0));
assert_eq!(ttm_77.ending_period_end, base + 231);
// Stock fields remain period values (not summed)
assert_eq!(snaps_77[3].periods[0].fields.total_assets, Some(200.0));
assert_eq!(snaps_77[3].periods[0].fields.shares_outstanding, Some(1_000.0));
// 76-day gap -> None
let mut rows_76 = rows_77.clone();
rows_76[3].period_end = base + 154 + 76;
assert!(build_fundamentals_snapshots(&rows_76, 4).unwrap()[3].ttm.is_none());
// 105-day spacing -> Some, 106-day gap -> None
let rows_105 = vec![
make_row("G105", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)),
make_row("G105", base + 105, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)),
make_row("G105", base + 210, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)),
make_row("G105", base + 315, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)),
];
assert!(build_fundamentals_snapshots(&rows_105, 4).unwrap()[3].ttm.is_some());
let mut rows_106 = rows_105.clone();
rows_106[3].period_end = base + 210 + 106;
assert!(build_fundamentals_snapshots(&rows_106, 4).unwrap()[3].ttm.is_none());
// 2. Intervening FY row occupies a snapshot slot while TTM still uses the 4 standalone quarters
let rows_fy = vec![
make_row("FY", day(2023, 3, 31), FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)),
make_row("FY", day(2023, 6, 30), FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)),
make_row("FY", day(2023, 9, 30), FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)),
make_row("FY", day(2023, 12, 31), FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)),
make_row("FY", day(2024, 1, 1), FiscalPeriod::Annual, "USD", 5, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)),
];
let snaps_fy = build_fundamentals_snapshots(&rows_fy, 2).unwrap();
let last_fy = snaps_fy.last().unwrap();
assert_eq!(last_fy.periods[0].fiscal_period, FiscalPeriod::Annual);
assert_eq!(last_fy.ttm.as_ref().unwrap().flows.revenue, Some(100.0));
// 3. Currency mismatch across 4 quarters -> TTM is None
let mut rows_curr = rows_77.clone();
rows_curr[2].currency = "CAD".to_string();
assert!(build_fundamentals_snapshots(&rows_curr, 4).unwrap()[3].ttm.is_none());
// 4. Missing flow input & overflow -> per-field None while other flow fields still sum
let mut rows_edge = rows_77.clone();
rows_edge[1].fields.net_income = None;
rows_edge[0].fields.operating_cash_flow = Some(f64::MAX);
rows_edge[1].fields.operating_cash_flow = Some(f64::MAX);
let ttm_edge = build_fundamentals_snapshots(&rows_edge, 4).unwrap()[3]
.ttm
.clone()
.expect("ttm present");
assert_eq!(ttm_edge.flows.revenue, Some(100.0));
assert_eq!(ttm_edge.flows.net_income, None);
assert_eq!(ttm_edge.flows.operating_cash_flow, None);
// 5. Carry-forward stays within same (period_end, kind, currency) and retains estimated provenance
let rows_cf = vec![
// Initial Q1 with statutory_lag_estimate
make_row(
"CF",
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"USD",
10,
KNOWN_AT_SOURCE_STATUTORY_LAG,
FundamentalsFields {
revenue: Some(100.0),
net_income: Some(10.0),
operating_cash_flow: None,
total_assets: Some(500.0),
total_equity: None,
shares_outstanding: None,
},
),
// Filing restatement leaves net_income=None -> inherits net_income from estimated version -> still estimated!
make_row(
"CF",
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"USD",
20,
KNOWN_AT_SOURCE_FILING_TIMESTAMP,
FundamentalsFields {
revenue: Some(105.0),
net_income: None,
operating_cash_flow: Some(15.0),
total_assets: Some(505.0),
total_equity: None,
shares_outstanding: None,
},
),
// Currency change to CAD at t=30 -> does NOT carry forward USD fields; now purely filing_timestamp!
make_row(
"CF",
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"CAD",
30,
KNOWN_AT_SOURCE_FILING_TIMESTAMP,
FundamentalsFields {
revenue: Some(140.0),
net_income: None,
operating_cash_flow: None,
total_assets: None,
total_equity: None,
shares_outstanding: None,
},
),
];
let snaps_cf = build_fundamentals_snapshots(&rows_cf, 2).unwrap();
assert!(snaps_cf[0].has_estimated_lag);
assert_eq!(snaps_cf[1].periods[0].fields.net_income, Some(10.0));
assert!(snaps_cf[1].periods[0].has_estimated_lag);
assert!(snaps_cf[1].has_estimated_lag);
assert_eq!(snaps_cf[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
// After currency change, no carry-forward from USD estimated row
assert_eq!(snaps_cf[2].periods[0].fields.net_income, None);
assert!(!snaps_cf[2].periods[0].has_estimated_lag);
assert!(!snaps_cf[2].has_estimated_lag);
assert_eq!(snaps_cf[2].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
// 6. Estimated TTM contributor outside displayed k=2 slots flags the snapshot as estimated
let rows_ttm_est = vec![
make_row("EST", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(10.0)),
make_row("EST", base + 90, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)),
make_row("EST", base + 180, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)),
make_row("EST", base + 270, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)),
];
let snaps_est = build_fundamentals_snapshots(&rows_ttm_est, 2).unwrap();
let s4 = &snaps_est[3];
assert_eq!(s4.periods.len(), 2);
assert!(s4.periods.iter().all(|p| !p.has_estimated_lag));
assert!(s4.ttm.as_ref().unwrap().has_estimated_lag);
assert!(s4.has_estimated_lag);
assert_eq!(s4.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
// 7. Multiple updates at the same timestamp produce one combined snapshot + as_of edge cases
let rows_same_ts = vec![
make_row("M", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)),
make_row("M", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)),
];
let snaps_same = build_fundamentals_snapshots(&rows_same_ts, 4).unwrap();
assert_eq!(snaps_same.len(), 1);
assert_eq!(snaps_same[0].periods.len(), 2);
assert!(as_of(&snaps_same, "M", 99).is_none());
assert_eq!(as_of(&snaps_same, "M", 100), Some(&snaps_same[0]));
assert!(as_of(&snaps_same, "UNKNOWN", 100).is_none());
// 8. k == 0 rejected with typed error
assert_eq!(
build_fundamentals_snapshots(&rows_same_ts, 0),
Err(FundamentalsError::InvalidPeriodLimit { k: 0 })
);
}
#[test]
fn robustness_bad_rows_dedup_conflicts_and_input_order_determinism() {
let venues = venues_map(&[
("A", StatutoryLagVenue::UsTsx),
("B", StatutoryLagVenue::TsxvCse),
]);
let observations = vec![
// Valid linked observation (with -0.0 normalized to 0.0) + exact duplicate
obs(
"A",
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 5, 1)),
FundamentalsFields {
revenue: Some(-0.0),
net_income: Some(5.0),
operating_cash_flow: Some(6.0),
total_assets: Some(100.0),
total_equity: Some(50.0),
shares_outstanding: Some(10.0),
},
),
obs(
"A",
day(2024, 3, 31),
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 5, 1)),
FundamentalsFields {
revenue: Some(0.0),
net_income: Some(5.0),
operating_cash_flow: Some(6.0),
total_assets: Some(100.0),
total_equity: Some(50.0),
shares_outstanding: Some(10.0),
},
),
// Conflicting duplicate pair on B (same period_end & known_at, differing revenue)
obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(10.0)),
obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(11.0)),
// Unknown key
obs("UNKNOWN", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)),
// Non-finite values (NaN, +inf, -inf)
obs(
"A",
day(2024, 6, 30),
FiscalPeriod::Quarterly,
"USD",
None,
FundamentalsFields {
revenue: Some(f64::NAN),
..Default::default()
},
),
obs(
"A",
day(2024, 6, 30),
FiscalPeriod::Quarterly,
"USD",
None,
FundamentalsFields {
total_assets: Some(f64::INFINITY),
..Default::default()
},
),
// Out-of-range period_end, report_date, and lag_date
obs("A", day(2007, 12, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)),
obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2031, 1, 1)), fields_rev(1.0)),
obs("A", day(2030, 12, 1), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)),
// Explicit report_date <= period_end
obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 30)), fields_rev(1.0)),
// Valid second period for A to verify early filing anchored earlier period, not dropped
obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 1)), fields_rev(25.0)),
];
let filings = vec![
// Legitimate filings for A Q1 and Q2 (Q1 filing predates Q2 period_end, must NOT be dropped!)
filing("A", "2024-05-01T16:10:00 EDT", "10-Q"),
filing("A", "2024-08-01T16:10:00 EDT", "10-Q"),
// Early filing on or before A's earliest quarterly period_end (2024-03-31) -> dropped
filing("A", "2024-03-31T16:00:00 EDT", "10-Q"),
// Unknown key
filing("UNKNOWN", "2024-05-01T16:10:00 EDT", "10-Q"),
// Non-periodic
filing("A", "2024-05-02T16:10:00 EDT", "8-K"),
// Invalid timestamps (malformed, unknown zone, invalid date)
filing("A", "not-a-date", "10-Q"),
filing("A", "2024-05-01T16:10:00 UTC", "10-Q"),
filing("A", "2024-02-30T16:10:00 EST", "10-Q"),
// Out-of-range Eastern filing date
filing("A", "2007-12-31T16:10:00 EST", "10-Q"),
];
let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues);
assert_reconciliation(&built);
assert_eq!(built.stats.observations_in, 12);
assert_eq!(built.stats.rows_out, 2);
assert_eq!(built.stats.keys_out, 1);
assert_eq!(built.stats.rows_linked_to_filing, 2);
assert_eq!(built.stats.rows_statutory_lag_estimate, 0);
assert_eq!(built.stats.observations_dropped_unknown_key, 1);
assert_eq!(built.stats.observations_dropped_non_finite, 2);
assert_eq!(built.stats.observations_dropped_date_out_of_range, 3);
assert_eq!(built.stats.observations_dropped_report_date_not_after_period_end, 1);
assert_eq!(built.stats.duplicate_collapsed, 1);
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
assert_eq!(built.stats.filings_in, 9);
assert_eq!(built.stats.filings_eligible, 2);
assert_eq!(built.stats.filings_dropped_unknown_key, 1);
assert_eq!(built.stats.filings_ignored_non_periodic, 1);
assert_eq!(built.stats.filings_dropped_invalid_timestamp, 3);
assert_eq!(built.stats.filings_dropped_date_out_of_range, 1);
assert_eq!(built.stats.filings_dropped_before_period_end, 1);
// -0.0 normalized to +0.0
assert_eq!(built.rows[0].fields.revenue.unwrap().to_bits(), 0.0_f64.to_bits());
// Input-order determinism: reversed and rotated inputs yield identical rows, snapshots, and stats
let mut obs_rev = observations.clone();
obs_rev.reverse();
let mut fil_rev = filings.clone();
fil_rev.reverse();
let built_rev = build_fundamentals_rows(obs_rev, fil_rev, &venues);
assert_eq!(built, built_rev);
let mut obs_rot = observations;
obs_rot.rotate_left(5);
let mut fil_rot = filings;
fil_rot.rotate_left(4);
let built_rot = build_fundamentals_rows(obs_rot, fil_rot, &venues);
assert_eq!(built, built_rot);
let snaps_a = build_fundamentals_snapshots(&built.rows, 4).unwrap();
let snaps_b = build_fundamentals_snapshots(&built_rev.rows, 4).unwrap();
assert_eq!(snaps_a, snaps_b);
}

View file

@ -14,6 +14,7 @@ pub mod bson_te_market_data;
pub mod cli;
pub mod corporate_actions;
pub mod events;
pub mod fundamentals;
pub mod fx;
pub mod mongo_safety;
pub mod mongo_stream;
@ -100,6 +101,17 @@ pub use events::{
EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP,
KNOWN_AT_SOURCE_STATUTORY_LAG,
};
pub use fundamentals::{
as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_snapshots,
FinancialObservation, FiscalPeriod, FundamentalsBuild, FundamentalsError, FundamentalsFields,
FundamentalsPeriodSlot, FundamentalsRow, FundamentalsSnapshot, FundamentalsStats,
FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, ANNUAL_FILING_LINK_WINDOW_DAYS,
FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET,
QUARTERLY_FILING_LINK_WINDOW_DAYS, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS,
STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS,
STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, TTM_CONSECUTIVE_QUARTER_MAX_DAYS,
TTM_CONSECUTIVE_QUARTER_MIN_DAYS, TTM_QUARTER_COUNT,
};
pub use fx::{
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,

View file

@ -11,7 +11,7 @@ use curate_etl::bench::{
run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark,
run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark,
run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark,
run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark,
run_fundamentals_benchmark, run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark,
run_parquet_bars_benchmark,
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
@ -482,6 +482,50 @@ fn main() -> ExitCode {
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchFundamentals(rows)) => {
let report = match run_fundamentals_benchmark(rows) {
Ok(report) => report,
Err(err) => {
eprintln!("error: fundamentals benchmark failed: {err}");
return ExitCode::FAILURE;
}
};
println!("curate-etl bench-fundamentals");
println!(
" input: rows={} filings={} keys={}",
report.rows, report.filings_in, report.key_count
);
println!(
" build: rows_out={} keys_out={} snapshots_out={} rows={:.2} ms snapshots={:.2} ms total={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}",
report.rows_out,
report.keys_out,
report.snapshots_out,
report.rows_elapsed_ms,
report.snapshots_elapsed_ms,
report.total_elapsed_ms,
report.rows_per_sec,
report.ns_per_row,
report.checksum
);
println!(
" stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}",
report.stats.rows_linked_to_filing,
report.stats.rows_statutory_lag_estimate,
report.stats.duplicate_collapsed,
report.stats.duplicate_conflict_dropped,
report.stats.observations_dropped_unknown_key,
report.stats.observations_dropped_non_finite,
report.stats.observations_dropped_date_out_of_range,
report.stats.observations_dropped_report_date_not_after_period_end,
report.stats.observations_dropped_unanchored_vintage,
report.stats.filings_eligible,
report.stats.filings_ignored_non_periodic,
report.stats.filings_dropped_invalid_timestamp,
report.stats.filings_dropped_date_out_of_range,
report.stats.filings_dropped_before_period_end
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchProviderMapping(lookups)) => {
let report = match run_provider_mapping_benchmark(lookups) {
Ok(report) => report,