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

310 lines
13 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 `std`-only North American Eastern Time (`16:00:00 ET`) session-close timestamp converter
//! covering `1976-01-01..=2030-12-31`.
//!
//! # DST Schedule (`America/New_York` == `America/Toronto` over `1976..=2030`)
//! Across the entire `1976..=2030` window, `America/New_York` and `America/Toronto` observed
//! identical Daylight Saving Time rules across three eras:
//! - **`1976..=1986`**: last Sunday of April → last Sunday of October.
//! - **`1987..=2006`**: first Sunday of April → last Sunday of October.
//! - **`2007..=2030`**: second Sunday of March → first Sunday of November (Energy Policy Act of
//! 2005 / matching Canadian provincial adoption).
//!
//! During EDT (`UTC-4`), `16:00:00 ET` is `20:00:00 UTC`. During EST (`UTC-5`), `16:00:00 ET` is
//! `21:00:00 UTC`. Because `16:00` is strictly after the `02:00` wall-clock transition, the spring
//! transition Sunday is already EDT (`20:00 UTC`) and the fall transition Sunday is already EST
//! (`21:00 UTC`).
//!
//! # Conservative Early-Close & Lower-Bound Policy
//! - **Early-close half days** (e.g., `13:00 ET` on Christmas Eve or the day after US
//! Thanksgiving) still map to `16:00:00 ET`, which is strictly later than the actual close and
//! therefore never introduces look-ahead bias for daily bar `known_at`.
//! - **Why the lower bound is `1976-01-01`**: in `1974–1975` the US Emergency Daylight Saving Time
//! Energy Conservation Act moved US clocks onto winter DST while Ontario/Toronto stayed on
//! standard rules, so `America/New_York` and `America/Toronto` diverged. Earlier dates return
//! [`SessionCloseError::DateOutOfRange`] rather than guessing exchange-specific historical rules.
use std::error::Error;
use std::fmt;
use std::sync::OnceLock;
use crate::shorts::epoch_days_to_ymd;
use crate::split::ymd_to_epoch_days;
/// First Gregorian year covered by [`et_session_close_utc_micros`] (`1976-01-01`).
pub const SESSION_CLOSE_MIN_SUPPORTED_YEAR: i32 = 1976;
/// Last Gregorian year covered by [`et_session_close_utc_micros`] (`2030-12-31`).
pub const SESSION_CLOSE_MAX_SUPPORTED_YEAR: i32 = 2030;
/// Epoch day for `1976-01-01` (inclusive lower bound of [`et_session_close_utc_micros`]).
pub const SESSION_CLOSE_MIN_SUPPORTED_DATE: i32 = 2_191;
/// Epoch day for `2030-12-31` (inclusive upper bound of [`et_session_close_utc_micros`]).
pub const SESSION_CLOSE_MAX_SUPPORTED_DATE: i32 = 22_279;
const SUPPORTED_YEAR_COUNT: usize =
(SESSION_CLOSE_MAX_SUPPORTED_YEAR - SESSION_CLOSE_MIN_SUPPORTED_YEAR + 1) as usize;
/// Typed error returned by [`et_session_close_utc_micros`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionCloseError {
/// The requested epoch day fell outside `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`.
DateOutOfRange {
epoch_day: i32,
min_supported: i32,
max_supported: i32,
},
}
impl fmt::Display for SessionCloseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::DateOutOfRange {
epoch_day,
min_supported,
max_supported,
} => write!(
f,
"epoch day {epoch_day} is outside supported session-close range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01..={SESSION_CLOSE_MAX_SUPPORTED_YEAR}-12-31)"
),
}
}
}
impl Error for SessionCloseError {}
/// ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `6 = Saturday`, `7 = Sunday`.
#[inline]
fn iso_weekday(epoch_day: i32) -> u8 {
// 1970-01-01 (epoch_day == 0) was Thursday (ISO 4).
((i64::from(epoch_day) + 3).rem_euclid(7) + 1) as u8
}
/// Returns the epoch day of the `nth` Sunday (`1`-indexed) in `(year, month)`.
fn nth_sunday_of_month(year: i32, month: u32, nth: u32) -> i32 {
let first = ymd_to_epoch_days(year, month, 1).expect("valid first of month");
let first_wd = iso_weekday(first);
let delta = (7 - i32::from(first_wd)).rem_euclid(7);
first + delta + (nth as i32 - 1) * 7
}
/// Returns the epoch day of the last Sunday in `(year, month)`.
fn last_sunday_of_month(year: i32, month: u32) -> i32 {
let (next_year, next_month) = if month == 12 {
(year + 1, 1)
} else {
(year, month + 1)
};
let last = ymd_to_epoch_days(next_year, next_month, 1).expect("valid first of next month") - 1;
let last_wd = iso_weekday(last);
last - (i32::from(last_wd) % 7)
}
fn build_dst_bounds() -> [(i32, i32); SUPPORTED_YEAR_COUNT] {
let mut table = [(0i32, 0i32); SUPPORTED_YEAR_COUNT];
for year in SESSION_CLOSE_MIN_SUPPORTED_YEAR..=SESSION_CLOSE_MAX_SUPPORTED_YEAR {
let (dst_start, dst_end) = match year {
1976..=1986 => (
last_sunday_of_month(year, 4),
last_sunday_of_month(year, 10),
),
1987..=2006 => (
nth_sunday_of_month(year, 4, 1),
last_sunday_of_month(year, 10),
),
2007..=2030 => (
nth_sunday_of_month(year, 3, 2),
nth_sunday_of_month(year, 11, 1),
),
_ => unreachable!("year is bounded by supported range"),
};
table[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize] = (dst_start, dst_end);
}
table
}
#[inline]
fn dst_bounds() -> &'static [(i32, i32); SUPPORTED_YEAR_COUNT] {
static TABLE: OnceLock<[(i32, i32); SUPPORTED_YEAR_COUNT]> = OnceLock::new();
TABLE.get_or_init(build_dst_bounds)
}
/// Converts `epoch_day` at `16:00:00` Eastern wall-clock (`America/New_York` / `America/Toronto`)
/// to UTC microseconds since the Unix epoch.
///
/// Covers `1976-01-01..=2030-12-31` across all three North American DST eras (`1976–1986`,
/// `1987–2006`, `2007–2030`). Returns [`SessionCloseError::DateOutOfRange`] for any date outside
/// `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`.
#[inline]
pub fn et_session_close_utc_micros(epoch_day: i32) -> Result<i64, SessionCloseError> {
if !(SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE).contains(&epoch_day) {
return Err(SessionCloseError::DateOutOfRange {
epoch_day,
min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE,
max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE,
});
}
let (year, _, _) = epoch_days_to_ymd(epoch_day);
let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize];
let is_edt = epoch_day >= dst_start && epoch_day < dst_end;
let utc_hour_secs: i64 = if is_edt { 20 * 3_600 } else { 21 * 3_600 };
Ok((i64::from(epoch_day) * 86_400 + utc_hour_secs) * 1_000_000)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE};
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn expected_utc_micros(epoch_day: i32, utc_hour: i64) -> i64 {
(i64::from(epoch_day) * 86_400 + utc_hour * 3_600) * 1_000_000
}
#[test]
fn supported_date_constants_match_ymd_to_epoch_days() {
assert_eq!(SESSION_CLOSE_MIN_SUPPORTED_DATE, day(1976, 1, 1));
assert_eq!(SESSION_CLOSE_MAX_SUPPORTED_DATE, day(2030, 12, 31));
assert_eq!(SUPPORTED_YEAR_COUNT, 55);
}
#[test]
fn known_vectors_cover_all_three_dst_eras_and_transitions() {
let cases = [
// Era 1 (1976..=1986): last Sunday of April -> last Sunday of October
(1976, 4, 24, 21), // Saturday before spring-forward (EST)
(1976, 4, 25, 20), // Last Sunday of April (EDT)
(1976, 10, 30, 20), // Saturday before fall-back (EDT)
(1976, 10, 31, 21), // Last Sunday of October (EST)
(1980, 1, 15, 21), // Era 1 mid-winter (EST)
(1980, 7, 15, 20), // Era 1 mid-summer (EDT)
(1986, 4, 26, 21), // Saturday before spring-forward (EST)
(1986, 4, 27, 20), // Last Sunday of April (EDT)
// Era 2 (1987..=2006): first Sunday of April -> last Sunday of October
(1987, 4, 4, 21), // Saturday before spring-forward (EST)
(1987, 4, 5, 20), // First Sunday of April (EDT)
(1987, 10, 24, 20), // Saturday before fall-back (EDT)
(1987, 10, 25, 21), // Last Sunday of October (EST)
(1999, 1, 15, 21), // Era 2 mid-winter (EST)
(1999, 7, 15, 20), // Era 2 mid-summer (EDT)
(2006, 4, 1, 21), // Saturday before spring-forward (EST)
(2006, 4, 2, 20), // First Sunday of April (EDT)
(2006, 10, 28, 20), // Saturday before fall-back (EDT)
(2006, 10, 29, 21), // Last Sunday of October (EST)
// Era 3 (2007..=2030): second Sunday of March -> first Sunday of November
(2007, 3, 10, 21), // Saturday before spring-forward (EST)
(2007, 3, 11, 20), // Second Sunday of March (EDT)
(2007, 11, 3, 20), // Saturday before fall-back (EDT)
(2007, 11, 4, 21), // First Sunday of November (EST)
(2024, 1, 15, 21), // Era 3 mid-winter (EST)
(2024, 7, 15, 20), // Era 3 mid-summer (EDT)
];
for (y, m, d, expected_hour) in cases {
let epoch_day = day(y, m, d);
let actual = et_session_close_utc_micros(epoch_day).expect("in-range date");
let expected = expected_utc_micros(epoch_day, expected_hour);
assert_eq!(
actual, expected,
"micros mismatch on {y:04}-{m:02}-{d:02} (expected {expected_hour}:00 UTC)"
);
let hour_of_day = (actual / 1_000_000 - i64::from(epoch_day) * 86_400) / 3_600;
assert_eq!(
hour_of_day, expected_hour,
"UTC hour mismatch on {y:04}-{m:02}-{d:02}"
);
}
}
#[test]
fn bit_exact_parity_with_shorts_et_to_utc_micros_for_2008_to_2030() {
for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE {
let expected = et_to_utc_micros(d, 16, 0, 0).expect("shorts 2008..=2030 date");
let actual = et_session_close_utc_micros(d).expect("session_close 2008..=2030 date");
assert_eq!(
actual, expected,
"parity mismatch against shorts::et_to_utc_micros on epoch_day={d}"
);
}
}
#[test]
fn full_window_sweep_has_only_20_or_21_utc_and_two_sunday_flips_per_year() {
let mut spring_flips_by_year = [0u32; SUPPORTED_YEAR_COUNT];
let mut fall_flips_by_year = [0u32; SUPPORTED_YEAR_COUNT];
let mut prev_hour: Option<i64> = None;
for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE {
let micros = et_session_close_utc_micros(d).expect("in-range date");
let offset_micros = micros - i64::from(d) * 86_400 * 1_000_000;
let utc_hour = match offset_micros {
72_000_000_000 => 20, // 20 * 3600 * 1e6
75_600_000_000 => 21, // 21 * 3600 * 1e6
other => panic!(
"unexpected UTC offset micros {other} on epoch_day={d} (expected 20h or 21h)"
),
};
if let Some(prev) = prev_hour {
if prev != utc_hour {
assert_eq!(
iso_weekday(d),
7,
"DST flip on epoch_day={d} must occur on a Sunday"
);
let (year, _, _) = epoch_days_to_ymd(d);
let idx = (year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize;
match (prev, utc_hour) {
(21, 20) => spring_flips_by_year[idx] += 1,
(20, 21) => fall_flips_by_year[idx] += 1,
_ => unreachable!(),
}
}
}
prev_hour = Some(utc_hour);
}
for year in SESSION_CLOSE_MIN_SUPPORTED_YEAR..=SESSION_CLOSE_MAX_SUPPORTED_YEAR {
let idx = (year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize;
assert_eq!(
spring_flips_by_year[idx], 1,
"year {year} must have exactly one EST->EDT flip"
);
assert_eq!(
fall_flips_by_year[idx], 1,
"year {year} must have exactly one EDT->EST flip"
);
}
}
#[test]
fn out_of_range_dates_return_typed_error_without_panicking() {
let bad_days = [
day(1975, 12, 31),
day(2031, 1, 1),
i32::MIN,
i32::MAX,
];
for bad_day in bad_days {
let err = et_session_close_utc_micros(bad_day).unwrap_err();
assert_eq!(
err,
SessionCloseError::DateOutOfRange {
epoch_day: bad_day,
min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE,
max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE,
}
);
assert!(err.source().is_none());
let msg = err.to_string();
assert!(
msg.contains(&bad_day.to_string()) && msg.contains("1976-01-01..=2030-12-31"),
"unexpected Display message: {msg}"
);
}
}
}