T-139: merge dev

This commit is contained in:
Studio 2026-12-01 20:58:33 -05:00
commit 5cd18dae2e
7 changed files with 2642 additions and 4 deletions

View file

@ -1574,6 +1574,40 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code
- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`.
- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar<K>`.
## 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. If a dated statutory-lag estimate for `(key, period_end, fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped (`observations_dropped_stale_estimate`) so an older vintage never rolls a newer filing backward.
- **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.
- Resolves standalone quarterly versions separately from `FY` rows (so an annual report sharing December 31 with standalone `Q4` never erases `Q4` from TTM) and 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 `0xd5f693a28da4d1f0` hashing all row fields, ordered snapshot slots, TTM flows, and provenance):
- **Run 1:** Stage 1 `47.63 ms`, Stage 2 `41.81 ms`, total `89.44 ms` (`1,118,108 rows/s`, `894.37 ns/row`)
- **Run 2:** Stage 1 `44.34 ms`, Stage 2 `39.73 ms`, total `84.07 ms` (`1,189,459 rows/s`, `840.72 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::ilp::{IlpShardedWriter, IlpWriterError, IlpWriterOptions};
use crate::parquet_adj::{
@ -79,6 +84,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;
@ -121,6 +127,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;
@ -11040,6 +11049,316 @@ 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 checksum = black_box(hash_fundamentals_outputs(&built.rows, &snapshots));
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,
})
}
#[inline]
fn mix_opt_f64(hash: u64, value: Option<f64>) -> u64 {
match value {
None => mix_u64(hash, 0),
Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()),
}
}
#[inline]
fn mix_str(mut hash: u64, value: &str) -> u64 {
hash = mix_u64(hash, value.len() as u64);
for byte in value.bytes() {
hash = mix_u64(hash, u64::from(byte));
}
hash
}
#[inline]
fn mix_fundamentals_fields(mut hash: u64, fields: &FundamentalsFields) -> u64 {
hash = mix_opt_f64(hash, fields.revenue);
hash = mix_opt_f64(hash, fields.net_income);
hash = mix_opt_f64(hash, fields.operating_cash_flow);
hash = mix_opt_f64(hash, fields.total_assets);
hash = mix_opt_f64(hash, fields.total_equity);
hash = mix_opt_f64(hash, fields.shares_outstanding);
hash
}
fn hash_fundamentals_outputs(
rows: &[crate::fundamentals::FundamentalsRow<i32>],
snapshots: &[crate::fundamentals::FundamentalsSnapshot<i32>],
) -> u64 {
let mut hash = 0u64;
for row in rows {
hash = mix_u64(hash, row.key as u64);
hash = mix_u64(hash, row.period_end as u64);
hash = mix_u64(hash, row.fiscal_period as u64);
hash = mix_str(hash, &row.currency);
hash = mix_u64(hash, row.known_at_utc_micros as u64);
hash = mix_str(hash, row.known_at_source);
hash = mix_fundamentals_fields(hash, &row.fields);
}
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_str(hash, snap.known_at_source);
hash = mix_u64(hash, u64::from(snap.has_estimated_lag));
hash = mix_u64(hash, snap.periods.len() as u64);
for slot in &snap.periods {
hash = mix_u64(hash, slot.period_end as u64);
hash = mix_u64(hash, slot.fiscal_period as u64);
hash = mix_str(hash, &slot.currency);
hash = mix_u64(hash, slot.known_at_utc_micros as u64);
hash = mix_str(hash, slot.known_at_source);
hash = mix_u64(hash, u64::from(slot.has_estimated_lag));
hash = mix_fundamentals_fields(hash, &slot.fields);
}
match &snap.ttm {
None => {
hash = mix_u64(hash, 0);
}
Some(ttm) => {
hash = mix_u64(hash, 1);
hash = mix_u64(hash, ttm.ending_period_end as u64);
hash = mix_str(hash, &ttm.currency);
hash = mix_u64(hash, u64::from(ttm.has_estimated_lag));
hash = mix_opt_f64(hash, ttm.flows.revenue);
hash = mix_opt_f64(hash, ttm.flows.net_income);
hash = mix_opt_f64(hash, ttm.flows.operating_cash_flow);
}
}
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
@ -13214,4 +13533,104 @@ mod tests {
assert_eq!(report.ns_per_row, 0.0);
assert_eq!(report.per_shard_rows, vec![0; ILP_BARS_1M_BENCH_SHARDS]);
}
#[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.observations_dropped_stale_estimate
+ a.stats.duplicate_collapsed
+ a.stats.duplicate_conflict_dropped
);
}
#[test]
fn fundamentals_checksum_distinguishes_none_zero_slots_and_non_revenue_ttm() {
use crate::fundamentals::{
FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, TtmFlowFields,
};
let base_slot = FundamentalsPeriodSlot {
period_end: 19_000,
fiscal_period: FiscalPeriod::Quarterly,
currency: "USD".to_string(),
known_at_utc_micros: 1_000,
known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP,
has_estimated_lag: false,
fields: FundamentalsFields {
revenue: Some(10.0),
net_income: None,
operating_cash_flow: Some(5.0),
total_assets: Some(100.0),
total_equity: Some(50.0),
shares_outstanding: Some(1_000.0),
},
};
let base_snap = FundamentalsSnapshot {
key: 1,
effective_known_at_utc_micros: 1_000,
known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP,
has_estimated_lag: false,
periods: vec![base_slot],
ttm: Some(FundamentalsTtm {
ending_period_end: 19_000,
currency: "USD".to_string(),
flows: TtmFlowFields {
revenue: Some(40.0),
net_income: None,
operating_cash_flow: Some(20.0),
},
has_estimated_lag: false,
}),
};
let h_base = hash_fundamentals_outputs(&[], &[base_snap.clone()]);
// None vs Some(0.0) in slot net_income
let mut s_zero = base_snap.clone();
s_zero.periods[0].fields.net_income = Some(0.0);
assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_zero]));
// Non-revenue TTM flow change (operating_cash_flow)
let mut s_ttm = base_snap.clone();
s_ttm.ttm.as_mut().unwrap().flows.operating_cash_flow = Some(21.0);
assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_ttm]));
// Carried-forward slot provenance change
let mut s_prov = base_snap;
s_prov.periods[0].has_estimated_lag = true;
assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_prov]));
}
#[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,8 +18,9 @@ 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_ILP_BARS_1M_BENCH_ROWS, DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS,
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
DEFAULT_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_ILP_BARS_1M_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,
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
@ -76,6 +77,7 @@ pub enum CliAction {
BenchFx(usize),
BenchShorts(usize),
BenchEvents(usize),
BenchFundamentals(usize),
BenchProviderMapping(usize),
BenchParquetBars(usize),
BenchParquetShorts(usize),
@ -136,6 +138,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\
@ -183,6 +186,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\
@ -1509,6 +1513,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,
)),
@ -3429,5 +3445,18 @@ mod tests {
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "-5"])).is_err());
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "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());
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -15,6 +15,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 ilp;
pub mod mongo_safety;
@ -107,6 +108,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,8 +11,8 @@ 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_ilp_bars_1m_benchmark, run_mongo_stream_benchmark,
run_parquet_adj_benchmark,
run_fundamentals_benchmark, run_fx_benchmark, run_ilp_bars_1m_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,
@ -510,6 +510,51 @@ 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={} obs_stale_est={} 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.observations_dropped_stale_estimate,
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,