399 lines
15 KiB
Rust
399 lines
15 KiB
Rust
//! Pure, in-memory `bars_1d` curation stage joining [`crate::bars::build_bars_1d`],
|
||
//! [`crate::provider_mapping::ProviderMappingTable`], listing currency metadata, and
|
||
//! [`crate::parquet_bars::write_bars_1d_dataset`] into contract [`Bars1dParquetRow`]s.
|
||
//!
|
||
//! # Contract & Point-in-Time Rules
|
||
//! - Calls [`build_bars_1d`] unchanged to validate OHLCV, un-adjust `eodPrices` share volume via
|
||
//! `SplitTable`, and cross-check against optional `qmPrices.sharevolume` observations.
|
||
//! - Resolves each output row's `(mapping_source, source_id, session_date)` to a permanent
|
||
//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`]
|
||
//! (one cursor per contiguous `key` run, since `build_bars_1d` emits rows sorted by
|
||
//! `(key, session_date)`).
|
||
//! - Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to
|
||
//! UTC microseconds via [`crate::session_close::et_session_close_utc_micros`]
|
||
//! (`design/PLATFORM-PLAN.md`: "`known_at` = session close").
|
||
//! - **Early-close half days** (e.g., `13:00 ET` on Christmas Eve or the day after US
|
||
//! Thanksgiving) still use `16:00 ET`, which is strictly later than the real close and
|
||
//! therefore never introduces look-ahead bias.
|
||
//! - **North American DST eras (`America/New_York` == `America/Toronto` over `1976..=2030`):**
|
||
//! `et_session_close_utc_micros` applies the three identical US/Canada DST eras (`1976..=1986`
|
||
//! last Sun Apr → last Sun Oct; `1987..=2006` first Sun Apr → last Sun Oct; `2007..=2030`
|
||
//! second Sun Mar → first Sun Nov; EDT `UTC-4` = `20:00 UTC`, EST `UTC-5` = `21:00 UTC`).
|
||
//! - **Calendar window:** covers `1976-01-01..=2030-12-31`
|
||
//! ([`crate::session_close::SESSION_CLOSE_MIN_SUPPORTED_DATE`]..=[`crate::session_close::SESSION_CLOSE_MAX_SUPPORTED_DATE`]).
|
||
//! The lower bound is `1976-01-01` because US emergency DST in `1974–1975` diverged from
|
||
//! Toronto; pre-1976 or post-2030 dates are dropped into
|
||
//! [`CurateBars1dStats::dropped_ts_out_of_range`] rather than panicking or guessing.
|
||
//! - Sets `vwap = None` and `source = Cow::Borrowed(BARS_1D_SOURCE_EOD)` (`"eod_unadj"`).
|
||
//! - Re-sorts mapped rows in place by `(listing_id, session_date)` and compacts cross-`source_id`
|
||
//! collisions on the same `(listing_id, session_date)`: bitwise-identical OHLCV collapses to one
|
||
//! row (`listing_collision_collapsed`), while any OHLCV conflict drops the entire group
|
||
//! (`listing_collision_dropped`), mirroring `build_bars_1d`'s duplicate policy.
|
||
|
||
use std::borrow::Cow;
|
||
use std::collections::HashMap;
|
||
use std::error::Error;
|
||
use std::fmt;
|
||
use std::hash::Hash;
|
||
use std::path::Path;
|
||
|
||
use crate::bars::{
|
||
build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample,
|
||
};
|
||
use crate::parquet_bars::{
|
||
write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError,
|
||
};
|
||
use crate::provider_mapping::ProviderMappingTable;
|
||
use crate::session_close::et_session_close_utc_micros;
|
||
use crate::split::SplitTable;
|
||
|
||
/// Canonical contract `source` provenance label for un-adjusted `eodPrices` daily bars.
|
||
pub const BARS_1D_SOURCE_EOD: &str = "eod_unadj";
|
||
|
||
/// Regular North American equity session close hour in Eastern Time (`16:00 ET`).
|
||
pub const BARS_1D_SESSION_CLOSE_HOUR_ET: u8 = 16;
|
||
|
||
/// Regular North American equity session close minute in Eastern Time (`16:00 ET`).
|
||
pub const BARS_1D_SESSION_CLOSE_MINUTE_ET: u8 = 0;
|
||
|
||
/// Regular North American equity session close second in Eastern Time (`16:00 ET`).
|
||
pub const BARS_1D_SESSION_CLOSE_SECOND_ET: u8 = 0;
|
||
|
||
/// Accounting summary produced alongside [`CurateBars1dOutput::rows`].
|
||
///
|
||
/// Conservation invariants:
|
||
/// - `rows_in == builder.rows_out`
|
||
/// - `rows_in == rows_out + dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped`
|
||
/// - `builder` independently satisfies all [`Bars1dStats`] conservation invariants.
|
||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||
pub struct CurateBars1dStats {
|
||
pub builder: Bars1dStats,
|
||
pub rows_in: usize,
|
||
pub rows_out: usize,
|
||
pub listings_out: usize,
|
||
pub dropped_unmapped: usize,
|
||
pub dropped_missing_currency: usize,
|
||
pub dropped_ts_out_of_range: usize,
|
||
pub listing_collision_collapsed: usize,
|
||
pub listing_collision_dropped: usize,
|
||
}
|
||
|
||
/// Output of [`curate_bars_1d`]: contract Parquet rows sorted and unique by
|
||
/// `(listing_id, session_date)`, full stage + builder stats, and untouched mismatch samples.
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct CurateBars1dOutput<K = String> {
|
||
pub rows: Vec<Bars1dParquetRow>,
|
||
pub stats: CurateBars1dStats,
|
||
pub mismatch_samples: Vec<VolumeMismatchSample<K>>,
|
||
}
|
||
|
||
/// Typed caller errors returned by [`curate_bars_1d`].
|
||
///
|
||
/// Bad single rows (unmapped dates, missing currencies, out-of-range timestamps, and
|
||
/// cross-`source_id` collisions) are dropped and counted in [`CurateBars1dStats`] rather than
|
||
/// aborting the stage.
|
||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||
pub enum CurateBarsError {
|
||
/// Error propagated from [`build_bars_1d`] (e.g., invalid `rel_tolerance`).
|
||
Bars(BarsError),
|
||
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
|
||
EmptyMappingSource,
|
||
}
|
||
|
||
impl fmt::Display for CurateBarsError {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
match *self {
|
||
Self::Bars(err) => write!(f, "{err}"),
|
||
Self::EmptyMappingSource => {
|
||
write!(f, "mapping_source must not be empty or blank")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Error for CurateBarsError {
|
||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||
match self {
|
||
Self::Bars(err) => Some(err),
|
||
Self::EmptyMappingSource => None,
|
||
}
|
||
}
|
||
}
|
||
|
||
impl From<BarsError> for CurateBarsError {
|
||
fn from(err: BarsError) -> Self {
|
||
Self::Bars(err)
|
||
}
|
||
}
|
||
|
||
/// Combined stats and mismatch samples returned by [`curate_and_write_bars_1d`].
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
pub struct CurateBars1dWriteReport<K = String> {
|
||
pub curate_stats: CurateBars1dStats,
|
||
pub write_stats: Bars1dWriteStats,
|
||
pub mismatch_samples: Vec<VolumeMismatchSample<K>>,
|
||
}
|
||
|
||
/// Typed error returned by [`curate_and_write_bars_1d`].
|
||
#[derive(Debug)]
|
||
pub enum CurateBarsWriteError {
|
||
Curate(CurateBarsError),
|
||
Parquet(ParquetBarsError),
|
||
}
|
||
|
||
impl fmt::Display for CurateBarsWriteError {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
match self {
|
||
Self::Curate(err) => write!(f, "bars_1d curation failed: {err}"),
|
||
Self::Parquet(err) => write!(f, "bars_1d Parquet write failed: {err}"),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Error for CurateBarsWriteError {
|
||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||
match self {
|
||
Self::Curate(err) => Some(err),
|
||
Self::Parquet(err) => Some(err),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl From<CurateBarsError> for CurateBarsWriteError {
|
||
fn from(err: CurateBarsError) -> Self {
|
||
Self::Curate(err)
|
||
}
|
||
}
|
||
|
||
impl From<ParquetBarsError> for CurateBarsWriteError {
|
||
fn from(err: ParquetBarsError) -> Self {
|
||
Self::Parquet(err)
|
||
}
|
||
}
|
||
|
||
#[inline]
|
||
fn parquet_row_ohlcv_bit_eq(a: &Bars1dParquetRow, b: &Bars1dParquetRow) -> bool {
|
||
a.open.to_bits() == b.open.to_bits()
|
||
&& a.high.to_bits() == b.high.to_bits()
|
||
&& a.low.to_bits() == b.low.to_bits()
|
||
&& a.close.to_bits() == b.close.to_bits()
|
||
&& a.volume.to_bits() == b.volume.to_bits()
|
||
}
|
||
|
||
/// Pure `bars_1d` curation stage: un-adjusts and cross-checks source-keyed `eodPrices` bars via
|
||
/// [`build_bars_1d`], resolves `(mapping_source, source_id, session_date) -> listing_id` through
|
||
/// `provider_mapping`, attaches listing currency and `16:00 ET` session-close UTC timestamps, and
|
||
/// emits contract [`Bars1dParquetRow`]s sorted and unique by `(listing_id, session_date)`.
|
||
///
|
||
/// Drop priority per built row:
|
||
/// 1. No mapping range covers `(mapping_source, source_id, session_date)` → `dropped_unmapped`.
|
||
/// 2. Resolved `listing_id` is absent from `listing_currencies` or maps to a blank string →
|
||
/// `dropped_missing_currency`.
|
||
/// 3. `et_session_close_utc_micros(session_date)` fails (date outside `1976-01-01..=2030-12-31`) →
|
||
/// `dropped_ts_out_of_range`.
|
||
///
|
||
/// After re-sorting in place by `(listing_id, session_date)`, cross-`source_id` collisions on the
|
||
/// same `(listing_id, session_date)` collapse to one row when OHLCV is bitwise identical
|
||
/// (`listing_collision_collapsed += g - 1`) and drop the entire group when any OHLCV field differs
|
||
/// (`listing_collision_dropped += g`).
|
||
pub fn curate_bars_1d<K, B, Q>(
|
||
bars: B,
|
||
splits: &SplitTable<K>,
|
||
qm_volumes: Q,
|
||
rel_tolerance: f64,
|
||
provider_mapping: &ProviderMappingTable,
|
||
mapping_source: &str,
|
||
listing_currencies: &HashMap<i32, Cow<'static, str>>,
|
||
) -> Result<CurateBars1dOutput<K>, CurateBarsError>
|
||
where
|
||
K: Ord + Eq + Hash + Clone + AsRef<str>,
|
||
B: IntoIterator<Item = EodDailyBar<K>>,
|
||
Q: IntoIterator<Item = QmRawVolume<K>>,
|
||
{
|
||
if !rel_tolerance.is_finite() || rel_tolerance < 0.0 {
|
||
return Err(BarsError::InvalidTolerance { rel_tolerance }.into());
|
||
}
|
||
if mapping_source.trim().is_empty() {
|
||
return Err(CurateBarsError::EmptyMappingSource);
|
||
}
|
||
|
||
let built = build_bars_1d(bars, splits, qm_volumes, rel_tolerance)?;
|
||
|
||
let mut stats = CurateBars1dStats {
|
||
builder: built.stats,
|
||
rows_in: built.rows.len(),
|
||
..CurateBars1dStats::default()
|
||
};
|
||
|
||
let mut rows: Vec<Bars1dParquetRow> = Vec::with_capacity(built.rows.len());
|
||
let total_built = built.rows.len();
|
||
let mut idx = 0usize;
|
||
|
||
while idx < total_built {
|
||
let run_start = idx;
|
||
let run_key = &built.rows[run_start].key;
|
||
idx += 1;
|
||
while idx < total_built && built.rows[idx].key == *run_key {
|
||
idx += 1;
|
||
}
|
||
let run_end = idx;
|
||
|
||
let mut cursor = provider_mapping.cursor_for(mapping_source, run_key.as_ref());
|
||
if cursor.ranges().is_empty() {
|
||
stats.dropped_unmapped += run_end - run_start;
|
||
continue;
|
||
}
|
||
|
||
let mut cached_currency: Option<(i32, Option<&Cow<'static, str>>)> = None;
|
||
|
||
for bar in &built.rows[run_start..run_end] {
|
||
let Some(listing_id) = cursor.resolve(bar.session_date) else {
|
||
stats.dropped_unmapped += 1;
|
||
continue;
|
||
};
|
||
|
||
let currency = match cached_currency {
|
||
Some((cached_id, cached)) if cached_id == listing_id => cached,
|
||
_ => {
|
||
let looked_up = listing_currencies
|
||
.get(&listing_id)
|
||
.filter(|c| !c.trim().is_empty());
|
||
cached_currency = Some((listing_id, looked_up));
|
||
looked_up
|
||
}
|
||
};
|
||
let Some(currency) = currency else {
|
||
stats.dropped_missing_currency += 1;
|
||
continue;
|
||
};
|
||
|
||
let Ok(ts_micros) = et_session_close_utc_micros(bar.session_date) else {
|
||
stats.dropped_ts_out_of_range += 1;
|
||
continue;
|
||
};
|
||
|
||
rows.push(Bars1dParquetRow {
|
||
listing_id,
|
||
ts_micros,
|
||
session_date: bar.session_date,
|
||
open: bar.open,
|
||
high: bar.high,
|
||
low: bar.low,
|
||
close: bar.close,
|
||
volume: bar.volume,
|
||
vwap: None,
|
||
currency: currency.clone(),
|
||
source: Cow::Borrowed(BARS_1D_SOURCE_EOD),
|
||
known_at_micros: ts_micros,
|
||
});
|
||
}
|
||
}
|
||
|
||
// Free builder rows before sorting/compacting mapped contract rows to cut peak RAM.
|
||
drop(built.rows);
|
||
|
||
rows.sort_unstable_by(|a, b| {
|
||
a.listing_id
|
||
.cmp(&b.listing_id)
|
||
.then_with(|| a.session_date.cmp(&b.session_date))
|
||
});
|
||
|
||
let mut write_idx = 0usize;
|
||
let mut read_idx = 0usize;
|
||
let total_mapped = rows.len();
|
||
let mut last_listing_id: Option<i32> = None;
|
||
|
||
while read_idx < total_mapped {
|
||
let listing_id = rows[read_idx].listing_id;
|
||
let session_date = rows[read_idx].session_date;
|
||
let mut group_end = read_idx + 1;
|
||
while group_end < total_mapped
|
||
&& rows[group_end].listing_id == listing_id
|
||
&& rows[group_end].session_date == session_date
|
||
{
|
||
group_end += 1;
|
||
}
|
||
let group_len = group_end - read_idx;
|
||
|
||
if group_len == 1 {
|
||
if write_idx != read_idx {
|
||
rows.swap(write_idx, read_idx);
|
||
}
|
||
if last_listing_id != Some(listing_id) {
|
||
stats.listings_out += 1;
|
||
last_listing_id = Some(listing_id);
|
||
}
|
||
write_idx += 1;
|
||
} else {
|
||
let first = &rows[read_idx];
|
||
let all_identical = rows[read_idx + 1..group_end]
|
||
.iter()
|
||
.all(|other| parquet_row_ohlcv_bit_eq(first, other));
|
||
|
||
if all_identical {
|
||
stats.listing_collision_collapsed += group_len - 1;
|
||
if write_idx != read_idx {
|
||
rows.swap(write_idx, read_idx);
|
||
}
|
||
if last_listing_id != Some(listing_id) {
|
||
stats.listings_out += 1;
|
||
last_listing_id = Some(listing_id);
|
||
}
|
||
write_idx += 1;
|
||
} else {
|
||
stats.listing_collision_dropped += group_len;
|
||
}
|
||
}
|
||
|
||
read_idx = group_end;
|
||
}
|
||
rows.truncate(write_idx);
|
||
stats.rows_out = rows.len();
|
||
|
||
Ok(CurateBars1dOutput {
|
||
rows,
|
||
stats,
|
||
mismatch_samples: built.mismatch_samples,
|
||
})
|
||
}
|
||
|
||
/// Thin end-to-end wrapper running [`curate_bars_1d`] and publishing the resulting contract rows
|
||
/// via [`write_bars_1d_dataset`] to `<out_dir>/bars_1d/year=YYYY/part.parquet`.
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub fn curate_and_write_bars_1d<P, K, B, Q>(
|
||
out_dir: P,
|
||
bars: B,
|
||
splits: &SplitTable<K>,
|
||
qm_volumes: Q,
|
||
rel_tolerance: f64,
|
||
provider_mapping: &ProviderMappingTable,
|
||
mapping_source: &str,
|
||
listing_currencies: &HashMap<i32, Cow<'static, str>>,
|
||
options: Bars1dWriteOptions,
|
||
) -> Result<CurateBars1dWriteReport<K>, CurateBarsWriteError>
|
||
where
|
||
P: AsRef<Path>,
|
||
K: Ord + Eq + Hash + Clone + AsRef<str>,
|
||
B: IntoIterator<Item = EodDailyBar<K>>,
|
||
Q: IntoIterator<Item = QmRawVolume<K>>,
|
||
{
|
||
let curated = curate_bars_1d(
|
||
bars,
|
||
splits,
|
||
qm_volumes,
|
||
rel_tolerance,
|
||
provider_mapping,
|
||
mapping_source,
|
||
listing_currencies,
|
||
)?;
|
||
let write_stats = write_bars_1d_dataset(out_dir, &curated.rows, options)?;
|
||
Ok(CurateBars1dWriteReport {
|
||
curate_stats: curated.stats,
|
||
write_stats,
|
||
mismatch_samples: curated.mismatch_samples,
|
||
})
|
||
}
|
||
|
||
#[cfg(test)]
|
||
#[path = "curate_bars_tests.rs"]
|
||
mod tests;
|