stock-bot/tools/curate-etl/src/curate_fx.rs

195 lines
7.6 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Pure, in-memory `fx_1d` curation stage joining [`crate::fx::build_fx_1d`] and
//! [`crate::parquet_fx::write_fx_1d_dataset`] into contract [`Fx1dParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - Calls [`build_fx_1d`] unchanged: EODHD `CAD.FOREX` takes precedence on overlapping dates,
//! TradingEconomics `teMarketData.USDCAD` fills interior gaps and the post-EOD tail, the
//! read-only 1% overlap cross-check runs untouched, and all [`Fx1dStats`] counters are carried
//! through unchanged.
//! - Maps every [`crate::fx::Fx1dRow`] to [`Fx1dParquetRow`] via [`Fx1dParquetRow::from_fx_row`]
//! with zero per-row heap allocation (`pair` and `source` stay `Cow::Borrowed`), preserving the
//! strictly ascending, unique `session_date` order emitted by [`build_fx_1d`].
//! - **Conservative no-look-ahead timestamp rule:** stamps every row with
//! `ts_micros = known_at_micros = (session_date + 1) * FX_1D_MICROS_PER_DAY - 1`
//! (i.e. `23:59:59.999999 UTC` of `session_date`, offset
//! [`FX_1D_TS_OFFSET_MICROS_FROM_DAY_START`] from UTC midnight). Neither `CAD.FOREX` nor
//! `teMarketData.USDCAD` documents its daily FX cutoff, so the last microsecond of the UTC day
//! is the conservative no-look-ahead boundary:
//! - Same-day `16:00 ET` equity close signals resolve to the prior UTC day's FX bar rather than
//! peeking at an undocumented same-day cutoff.
//! - Every timestamp lies strictly inside the UTC day `[day_start, day_end)` and has
//! `known_at >= ts`, satisfying `parquet_fx`'s `TsOutsideSessionDate` and `KnownAtBeforeTs`
//! invariants.
//! - Requires no DST table for `1971–1975` (which lies outside `session_close.rs`'s
//! `1976–2030` range).
//! - Uses checked `i64` arithmetic via [`fx_1d_utc_day_end_micros`]; any `session_date` whose
//! UTC day-end microsecond timestamp overflows `i64` returns
//! [`CurateFxError::SessionDateOutOfRange`] without panicking or wrapping.
//! - Accounting invariant on [`CurateFx1dStats`]: `rows_in == builder.rows_out == rows_out`.
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::fx::{build_fx_1d, Fx1dStats, FxDailyBar};
use crate::parquet_fx::{
write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError,
};
/// Number of microseconds in one UTC calendar day (`86_400 * 1_000_000`).
pub const FX_1D_MICROS_PER_DAY: i64 = 86_400_000_000;
/// Offset in microseconds from `00:00:00.000000 UTC` to `23:59:59.999999 UTC`
/// (`FX_1D_MICROS_PER_DAY - 1`), used as both `ts` and `known_at` for curated `fx_1d` rows.
pub const FX_1D_TS_OFFSET_MICROS_FROM_DAY_START: i64 = FX_1D_MICROS_PER_DAY - 1;
/// Accounting summary produced alongside [`CurateFx1dOutput::rows`].
///
/// Conservation invariant:
/// - `rows_in == builder.rows_out == rows_out`
/// - `builder` independently satisfies all [`Fx1dStats`] conservation invariants.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct CurateFx1dStats {
pub builder: Fx1dStats,
pub rows_in: usize,
pub rows_out: usize,
}
/// Output of [`curate_fx_1d`]: contract Parquet rows sorted and unique by `session_date`
/// and full stage + builder stats.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateFx1dOutput {
pub rows: Vec<Fx1dParquetRow>,
pub stats: CurateFx1dStats,
}
/// Typed errors returned by [`curate_fx_1d`] and [`fx_1d_utc_day_end_micros`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CurateFxError {
/// `session_date` cannot be represented as a UTC day-end `i64` microsecond timestamp
/// (`(session_date + 1) * 86_400_000_000 - 1` overflows `i64`).
SessionDateOutOfRange { session_date: i32 },
}
impl fmt::Display for CurateFxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::SessionDateOutOfRange { session_date } => write!(
f,
"fx_1d session_date {session_date} overflows i64 UTC microsecond timestamp"
),
}
}
}
impl Error for CurateFxError {}
/// Combined stats returned by [`curate_and_write_fx_1d`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CurateFx1dWriteReport {
pub curate_stats: CurateFx1dStats,
pub write_stats: Fx1dWriteStats,
}
/// Typed error returned by [`curate_and_write_fx_1d`].
#[derive(Debug)]
pub enum CurateFxWriteError {
Curate(CurateFxError),
Parquet(ParquetFxError),
}
impl fmt::Display for CurateFxWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "fx_1d curation failed: {err}"),
Self::Parquet(err) => write!(f, "fx_1d Parquet write failed: {err}"),
}
}
}
impl Error for CurateFxWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateFxError> for CurateFxWriteError {
fn from(err: CurateFxError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetFxError> for CurateFxWriteError {
fn from(err: ParquetFxError) -> Self {
Self::Parquet(err)
}
}
/// Computes `23:59:59.999999 UTC` of `session_date` (days since `1970-01-01`) in UTC microseconds
/// using checked `i64` arithmetic.
///
/// Formula: `(session_date + 1) * FX_1D_MICROS_PER_DAY - (FX_1D_MICROS_PER_DAY - FX_1D_TS_OFFSET_MICROS_FROM_DAY_START)`.
#[inline]
pub fn fx_1d_utc_day_end_micros(session_date: i32) -> Result<i64, CurateFxError> {
let sub_from_next_day = FX_1D_MICROS_PER_DAY - FX_1D_TS_OFFSET_MICROS_FROM_DAY_START;
i64::from(session_date)
.checked_add(1)
.and_then(|next_day| next_day.checked_mul(FX_1D_MICROS_PER_DAY))
.and_then(|next_day_start| next_day_start.checked_sub(sub_from_next_day))
.ok_or(CurateFxError::SessionDateOutOfRange { session_date })
}
/// Pure `fx_1d` curation stage: merges `CAD.FOREX` (`eod`) and `teMarketData.USDCAD` (`te`) via
/// [`build_fx_1d`] and stamps each row with conservative `23:59:59.999999 UTC` `ts`/`known_at`
/// timestamps via [`fx_1d_utc_day_end_micros`] into contract [`Fx1dParquetRow`]s.
///
/// Output rows preserve the strictly ascending, unique `session_date` order emitted by
/// [`build_fx_1d`], with `pair` and `source` kept as `Cow::Borrowed` (zero per-row heap
/// allocation).
pub fn curate_fx_1d(
eod: &[FxDailyBar],
te: &[FxDailyBar],
) -> Result<CurateFx1dOutput, CurateFxError> {
let built = build_fx_1d(eod, te);
let rows_in = built.rows.len();
let mut rows = Vec::with_capacity(rows_in);
for row in &built.rows {
let ts_micros = fx_1d_utc_day_end_micros(row.session_date)?;
rows.push(Fx1dParquetRow::from_fx_row(row, ts_micros, ts_micros));
}
let stats = CurateFx1dStats {
builder: built.stats,
rows_in,
rows_out: rows.len(),
};
Ok(CurateFx1dOutput { rows, stats })
}
/// Thin end-to-end wrapper running [`curate_fx_1d`] and publishing the resulting contract rows
/// via [`write_fx_1d_dataset`] to `<out_dir>/fx_1d/part.parquet`.
///
/// Any [`CurateFxError`] returns before [`write_fx_1d_dataset`] is invoked, leaving `out_dir`
/// untouched.
pub fn curate_and_write_fx_1d<P: AsRef<Path>>(
out_dir: P,
eod: &[FxDailyBar],
te: &[FxDailyBar],
options: Fx1dWriteOptions,
) -> Result<CurateFx1dWriteReport, CurateFxWriteError> {
let curated = curate_fx_1d(eod, te)?;
let write_stats = write_fx_1d_dataset(out_dir, &curated.rows, options)?;
Ok(CurateFx1dWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_fx_tests.rs"]
mod tests;