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

987 lines
35 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 `shorts` builder (`ceoShorts` → `+4` Canadian TSX business-day `17:00 ET`
//! `known_at`).
//!
//! Produces sorted, unique per-`(key, report_date)` rows matching `shorts/part.parquet` in
//! `design/DATA-CONTRACTS.md` (`listing_id, report_date, known_at, shares_short, net_change,
//! pct_float, source`).
//!
//! Also exposes reusable `std`-only Canadian TSX business-day calendar (`2008–2030`) and
//! `America/Toronto` ET→UTC DST conversion helpers ([`is_canadian_business_day`],
//! [`add_canadian_business_days`], [`et_to_utc_micros`], [`epoch_days_to_ymd`]) for downstream
//! builders (e.g., `events` with `16:05 ET` lag).
use std::error::Error;
use std::fmt;
use std::sync::OnceLock;
use crate::split::ymd_to_epoch_days;
/// Canonical provenance label written to [`ShortRow::source`].
pub const SHORTS_SOURCE_CEO: &str = "ceo_shorts";
/// Locked CIRO dissemination lag in Canadian TSX business days (`design/DATA-CONTRACTS.md` §1).
pub const SHORTS_LAG_BUSINESS_DAYS: u32 = 4;
/// Locked CIRO dissemination wall-clock hour in `America/Toronto` (`17:00 ET`).
pub const SHORTS_DISSEMINATION_HOUR_ET: u8 = 17;
/// Locked CIRO dissemination wall-clock minute in `America/Toronto` (`17:00 ET`).
pub const SHORTS_DISSEMINATION_MINUTE_ET: u8 = 0;
/// First Gregorian year covered by the built-in TSX holiday & DST calendar (Family Day joined TSX
/// in 2008; North American 2nd-Sun-Mar / 1st-Sun-Nov DST rules took effect in 2007).
pub const MIN_SUPPORTED_YEAR: i32 = 2008;
/// Last Gregorian year covered by the built-in TSX holiday & DST calendar (strictly covers
/// `2017-01-01..=2027-12-31` plus year-end `+4` business-day rollovers).
pub const MAX_SUPPORTED_YEAR: i32 = 2030;
/// Epoch day for `2008-01-01` (inclusive lower bound of the supported calendar range).
pub const MIN_SUPPORTED_DATE: i32 = 13_879;
/// Epoch day for `2030-12-31` (inclusive upper bound of the supported calendar range).
pub const MAX_SUPPORTED_DATE: i32 = 22_279;
const SUPPORTED_DAY_COUNT: usize = (MAX_SUPPORTED_DATE - MIN_SUPPORTED_DATE + 1) as usize;
const SUPPORTED_YEAR_COUNT: usize = (MAX_SUPPORTED_YEAR - MIN_SUPPORTED_YEAR + 1) as usize;
/// Typed errors returned by the Canadian calendar, ET→UTC converter, and [`build_shorts`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShortsError {
/// A date (or a stepped business day) fell outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`.
DateOutOfRange {
epoch_day: i32,
min_supported: i32,
max_supported: i32,
},
/// Wall-clock `(hour, minute, second)` components were out of range (`0..=23`, `0..=59`, `0..=59`).
InvalidLocalTime { hour: u8, minute: u8, second: u8 },
/// Local wall-clock time fell in the spring-forward DST gap (`02:00:00..=02:59:59` ET on the
/// 2nd Sunday of March).
NonexistentLocalTime {
epoch_day: i32,
hour: u8,
minute: u8,
second: u8,
},
/// Local wall-clock time fell in the fall-back DST overlap (`01:00:00..=01:59:59` ET on the
/// 1st Sunday of November).
AmbiguousLocalTime {
epoch_day: i32,
hour: u8,
minute: u8,
second: u8,
},
}
impl fmt::Display for ShortsError {
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 calendar range [{min_supported}, {max_supported}] ({MIN_SUPPORTED_YEAR}-01-01..={MAX_SUPPORTED_YEAR}-12-31)"
),
Self::InvalidLocalTime {
hour,
minute,
second,
} => write!(
f,
"invalid local time {hour:02}:{minute:02}:{second:02} (expected 00:00:00..=23:59:59)"
),
Self::NonexistentLocalTime {
epoch_day,
hour,
minute,
second,
} => {
let (y, m, d) = epoch_days_to_ymd(epoch_day);
write!(
f,
"nonexistent America/Toronto local time {y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02} (spring-forward DST gap)"
)
}
Self::AmbiguousLocalTime {
epoch_day,
hour,
minute,
second,
} => {
let (y, m, d) = epoch_days_to_ymd(epoch_day);
write!(
f,
"ambiguous America/Toronto local time {y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02} (fall-back DST overlap)"
)
}
}
}
}
impl Error for ShortsError {}
/// Converts signed days since `1970-01-01` (UTC Gregorian) back to `(year, month, day)`.
///
/// Exact inverse of [`crate::ymd_to_epoch_days`] (Howard Hinnant's `civil_from_days`).
#[inline]
pub fn epoch_days_to_ymd(epoch_day: i32) -> (i32, u32, u32) {
let z = i64::from(epoch_day) + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097; // [0, 146096]
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
let mp = (5 * doy + 2) / 153; // [0, 11]
let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
let year = y + i64::from(m <= 2);
(year as i32, m as u32, d as u32)
}
/// 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
}
/// Computes the epoch day of the `nth` occurrence (`1`-indexed) of `target_iso_weekday`
/// (`1 = Mon ..= 7 = Sun`) in `(year, month)`.
fn nth_weekday_of_month(year: i32, month: u32, target_iso_weekday: u8, 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 = (i32::from(target_iso_weekday) - i32::from(first_wd)).rem_euclid(7);
first + delta + (nth as i32 - 1) * 7
}
/// Anonymous Gregorian algorithm (Meeus/Jones/Butcher) for Easter Sunday.
fn easter_sunday_epoch_day(year: i32) -> i32 {
let a = year % 19;
let b = year / 100;
let c = year % 100;
let d = b / 4;
let e = b % 4;
let f = (b + 8) / 25;
let g = (b - f + 1) / 3;
let h = (19 * a + b - d - g + 15) % 30;
let i = c / 4;
let k = c % 4;
let l = (32 + 2 * e + 2 * i - h - k) % 7;
let m = (a + 11 * h + 22 * l) / 451;
let month = (h + l - 7 * m + 114) / 31;
let day = ((h + l - 7 * m + 114) % 31) + 1;
ymd_to_epoch_days(year, month as u32, day as u32).expect("valid Easter Sunday")
}
/// Observes a fixed-date TSX holiday (New Year's Day / Canada Day): Saturday → Monday (`+2`),
/// Sunday → Monday (`+1`), weekday → same day.
fn observed_fixed_holiday(epoch_day: i32) -> i32 {
match iso_weekday(epoch_day) {
6 => epoch_day + 2,
7 => epoch_day + 1,
_ => epoch_day,
}
}
struct CalendarTable {
/// `true` iff `MIN_SUPPORTED_DATE + idx` is a Canadian TSX business day.
is_business: Vec<bool>,
/// Per-year `(dst_start_epoch_day, dst_end_epoch_day)` for `MIN_SUPPORTED_YEAR..=MAX_SUPPORTED_YEAR`.
dst_bounds: [(i32, i32); SUPPORTED_YEAR_COUNT],
}
impl CalendarTable {
fn build() -> Self {
let mut is_business = vec![true; SUPPORTED_DAY_COUNT];
for (idx, flag) in is_business.iter_mut().enumerate() {
let day = MIN_SUPPORTED_DATE + idx as i32;
if iso_weekday(day) >= 6 {
*flag = false;
}
}
let mut dst_bounds = [(0i32, 0i32); SUPPORTED_YEAR_COUNT];
for year in MIN_SUPPORTED_YEAR..=MAX_SUPPORTED_YEAR {
let mut mark_holiday = |day: i32| {
if (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&day) {
is_business[(day - MIN_SUPPORTED_DATE) as usize] = false;
}
};
// 1. New Year's Day (Jan 1; Sat -> Mon Jan 3, Sun -> Mon Jan 2).
let jan1 = ymd_to_epoch_days(year, 1, 1).expect("valid Jan 1");
mark_holiday(observed_fixed_holiday(jan1));
// 2. Family Day (3rd Monday of February, observed by TSX since 2008).
mark_holiday(nth_weekday_of_month(year, 2, 1, 3));
// 3. Good Friday (Easter Sunday - 2 days).
mark_holiday(easter_sunday_epoch_day(year) - 2);
// 4. Victoria Day (Monday strictly before May 25).
let may24 = ymd_to_epoch_days(year, 5, 24).expect("valid May 24");
let victoria = may24 - i32::from(iso_weekday(may24) - 1);
mark_holiday(victoria);
// 5. Canada Day (Jul 1; Sat -> Mon Jul 3, Sun -> Mon Jul 2).
let jul1 = ymd_to_epoch_days(year, 7, 1).expect("valid Jul 1");
mark_holiday(observed_fixed_holiday(jul1));
// 6. Civic Holiday (1st Monday of August).
mark_holiday(nth_weekday_of_month(year, 8, 1, 1));
// 7. Labour Day (1st Monday of September).
mark_holiday(nth_weekday_of_month(year, 9, 1, 1));
// 8. Thanksgiving (2nd Monday of October).
mark_holiday(nth_weekday_of_month(year, 10, 1, 2));
// 9. Christmas Day & Boxing Day pair (Dec 25/26 with TSX weekend observance):
// Mon–Thu -> Dec 25 & Dec 26
// Fri -> Dec 25 (Fri) & Dec 28 (Mon)
// Sat -> Dec 27 (Mon) & Dec 28 (Tue)
// Sun -> Dec 26 (Mon) & Dec 27 (Tue)
let dec25 = ymd_to_epoch_days(year, 12, 25).expect("valid Dec 25");
let (xmas_obs, boxing_obs) = match iso_weekday(dec25) {
1..=4 => (dec25, dec25 + 1),
5 => (dec25, dec25 + 3),
6 => (dec25 + 2, dec25 + 3),
7 => (dec25 + 1, dec25 + 2),
_ => unreachable!("iso_weekday is always in 1..=7"),
};
mark_holiday(xmas_obs);
mark_holiday(boxing_obs);
// America/Toronto DST: 2nd Sunday of March -> 1st Sunday of November.
let dst_start = nth_weekday_of_month(year, 3, 7, 2);
let dst_end = nth_weekday_of_month(year, 11, 7, 1);
dst_bounds[(year - MIN_SUPPORTED_YEAR) as usize] = (dst_start, dst_end);
}
Self {
is_business,
dst_bounds,
}
}
}
fn calendar_table() -> &'static CalendarTable {
static TABLE: OnceLock<CalendarTable> = OnceLock::new();
TABLE.get_or_init(CalendarTable::build)
}
#[inline]
fn check_supported_date(epoch_day: i32) -> Result<(), ShortsError> {
if (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) {
Ok(())
} else {
Err(ShortsError::DateOutOfRange {
epoch_day,
min_supported: MIN_SUPPORTED_DATE,
max_supported: MAX_SUPPORTED_DATE,
})
}
}
/// Returns `Ok(true)` iff `epoch_day` is a Canadian TSX business day (weekday and not a TSX
/// holiday) within `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`).
///
/// Dates outside the supported range return [`ShortsError::DateOutOfRange`].
#[inline]
pub fn is_canadian_business_day(epoch_day: i32) -> Result<bool, ShortsError> {
check_supported_date(epoch_day)?;
let table = calendar_table();
Ok(table.is_business[(epoch_day - MIN_SUPPORTED_DATE) as usize])
}
/// Advances `epoch_day` strictly forward by `n` Canadian TSX business days.
///
/// - When `n == 0`, returns `Ok(epoch_day)` if `epoch_day` is within the supported range.
/// - When `epoch_day` is itself a weekend or holiday, counts strictly forward from `epoch_day` so
/// the returned date is the `n`-th business day strictly after `epoch_day`.
/// - Returns [`ShortsError::DateOutOfRange`] if `epoch_day` or any stepped day leaves
/// `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`.
#[inline]
pub fn add_canadian_business_days(epoch_day: i32, n: u32) -> Result<i32, ShortsError> {
check_supported_date(epoch_day)?;
if n == 0 {
return Ok(epoch_day);
}
let table = calendar_table();
let mut cur = epoch_day;
let mut remaining = n;
while remaining > 0 {
if cur >= MAX_SUPPORTED_DATE {
return Err(ShortsError::DateOutOfRange {
epoch_day: cur.saturating_add(1),
min_supported: MIN_SUPPORTED_DATE,
max_supported: MAX_SUPPORTED_DATE,
});
}
cur += 1;
if table.is_business[(cur - MIN_SUPPORTED_DATE) as usize] {
remaining -= 1;
}
}
Ok(cur)
}
/// Converts an `America/Toronto` local date and wall-clock time `(hour, minute, second)` to UTC
/// microseconds since `1970-01-01T00:00:00Z`.
///
/// Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November
/// 02:00 = EDT `UTC-4`, otherwise EST `UTC-5`) over `2008-01-01..=2030-12-31`.
///
/// Rejects:
/// - out-of-range dates ([`ShortsError::DateOutOfRange`]),
/// - invalid clock components ([`ShortsError::InvalidLocalTime`]),
/// - spring-forward nonexistent times `02:00:00..=02:59:59` ([`ShortsError::NonexistentLocalTime`]),
/// - fall-back ambiguous times `01:00:00..=01:59:59` ([`ShortsError::AmbiguousLocalTime`]).
#[inline]
pub fn et_to_utc_micros(
epoch_day: i32,
hour: u8,
minute: u8,
second: u8,
) -> Result<i64, ShortsError> {
if hour > 23 || minute > 59 || second > 59 {
return Err(ShortsError::InvalidLocalTime {
hour,
minute,
second,
});
}
check_supported_date(epoch_day)?;
let (year, _, _) = epoch_days_to_ymd(epoch_day);
let (dst_start, dst_end) = calendar_table().dst_bounds[(year - MIN_SUPPORTED_YEAR) as usize];
let is_edt = if epoch_day == dst_start {
if hour == 2 {
return Err(ShortsError::NonexistentLocalTime {
epoch_day,
hour,
minute,
second,
});
}
hour >= 3
} else if epoch_day == dst_end {
if hour == 1 {
return Err(ShortsError::AmbiguousLocalTime {
epoch_day,
hour,
minute,
second,
});
}
hour == 0
} else {
epoch_day > dst_start && epoch_day < dst_end
};
let offset_hours: i64 = if is_edt { 4 } else { 5 };
let local_secs = i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second);
let utc_secs = i64::from(epoch_day) * 86_400 + local_secs + offset_hours * 3_600;
Ok(utc_secs * 1_000_000)
}
/// A single raw `ceoShorts` short-interest report row.
#[derive(Debug, Clone, PartialEq)]
pub struct CeoShortReport<K = String> {
pub key: K,
/// Report period date (15th or month-end) as days since `1970-01-01` (UTC Gregorian).
pub report_date: i32,
/// Reported short share count (must be finite and `>= 0.0`).
pub shares_short: f64,
/// Optional net change vs. prior report (non-finite values are sanitized to `None`).
pub net_change: Option<f64>,
/// Optional percent of float short passed through from caller (non-finite → `None`).
pub pct_float: Option<f64>,
}
/// A single curated `shorts` row, sorted and unique by `(key, report_date)`.
#[derive(Debug, Clone, PartialEq)]
pub struct ShortRow<K = String> {
pub key: K,
pub report_date: i32,
/// Point-in-time dissemination date (`report_date + 4` Canadian TSX business days).
pub known_at_date: i32,
/// Point-in-time UTC microseconds (`17:00:00 America/Toronto` on `known_at_date`).
pub known_at_utc_micros: i64,
pub shares_short: f64,
pub net_change: Option<f64>,
pub pct_float: Option<f64>,
pub source: &'static str,
}
/// Summary accounting counters produced alongside [`ShortsBuild::rows`].
///
/// Conservation invariant:
/// `rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ShortsStats {
pub rows_in: usize,
pub rows_out: usize,
pub keys_out: usize,
pub dropped_invalid_shares_short: usize,
pub nulled_invalid_net_change: usize,
pub nulled_invalid_pct_float: usize,
pub duplicate_collapsed: usize,
pub duplicate_conflict_dropped: usize,
}
/// Output of [`build_shorts`]: sorted, unique point-in-time `shorts` rows and exact stats.
#[derive(Debug, Clone, PartialEq)]
pub struct ShortsBuild<K = String> {
pub rows: Vec<ShortRow<K>>,
pub stats: ShortsStats,
}
#[inline]
fn normalize_zero(v: f64) -> f64 {
if v == 0.0 {
0.0
} else {
v
}
}
struct NormalizedShort<K> {
key: K,
report_date: i32,
known_at_date: i32,
shares_short: f64,
net_change: Option<f64>,
pct_float: Option<f64>,
}
impl<K> NormalizedShort<K> {
#[inline]
fn values_bit_eq(&self, other: &Self) -> bool {
self.shares_short.to_bits() == other.shares_short.to_bits()
&& self.net_change.map(f64::to_bits) == other.net_change.map(f64::to_bits)
&& self.pct_float.map(f64::to_bits) == other.pct_float.map(f64::to_bits)
}
}
/// Builds sorted, unique point-in-time `shorts` rows from raw `ceoShorts` report rows.
///
/// - Validates `report_date + 4` Canadian TSX business days on every input row first so any
/// out-of-range date returns [`ShortsError::DateOutOfRange`] deterministically regardless of row
/// order or bad numeric fields.
/// - Drops non-finite or negative `shares_short` (`dropped_invalid_shares_short`) without aborting
/// and without incrementing optional-field null counters.
/// - Sanitizes non-finite `net_change` / `pct_float` to `None` (`nulled_invalid_net_change` /
/// `nulled_invalid_pct_float`) and normalizes `-0.0` to `0.0` before deduplication.
/// - Collapses bitwise-identical duplicates on `(key, report_date)` (`duplicate_collapsed`) and
/// drops conflicting duplicate groups entirely (`duplicate_conflict_dropped`).
/// - Stamps `known_at_utc_micros = 17:00 America/Toronto` on `known_at_date` and
/// `source = "ceo_shorts"`.
/// - Any permutation of `rows` yields bitwise-identical `rows` and `stats`.
pub fn build_shorts<K, I>(rows: I) -> Result<ShortsBuild<K>, ShortsError>
where
K: Ord + Clone,
I: IntoIterator<Item = CeoShortReport<K>>,
{
let iter = rows.into_iter();
let (lower, _) = iter.size_hint();
let mut stats = ShortsStats::default();
let mut valid: Vec<NormalizedShort<K>> = Vec::with_capacity(lower);
for row in iter {
stats.rows_in += 1;
let known_at_date = add_canadian_business_days(row.report_date, SHORTS_LAG_BUSINESS_DAYS)?;
if !row.shares_short.is_finite() || row.shares_short < 0.0 {
stats.dropped_invalid_shares_short += 1;
continue;
}
let shares_short = normalize_zero(row.shares_short);
let net_change = match row.net_change {
Some(v) if v.is_finite() => Some(normalize_zero(v)),
Some(_) => {
stats.nulled_invalid_net_change += 1;
None
}
None => None,
};
let pct_float = match row.pct_float {
Some(v) if v.is_finite() => Some(normalize_zero(v)),
Some(_) => {
stats.nulled_invalid_pct_float += 1;
None
}
None => None,
};
valid.push(NormalizedShort {
key: row.key,
report_date: row.report_date,
known_at_date,
shares_short,
net_change,
pct_float,
});
}
valid.sort_unstable_by(|a, b| {
a.key
.cmp(&b.key)
.then_with(|| a.report_date.cmp(&b.report_date))
});
let mut out: Vec<ShortRow<K>> = Vec::with_capacity(valid.len());
let len = valid.len();
let mut read_idx = 0usize;
while read_idx < len {
let mut group_end = read_idx + 1;
while group_end < len
&& valid[group_end].key == valid[read_idx].key
&& valid[group_end].report_date == valid[read_idx].report_date
{
group_end += 1;
}
let group_len = group_end - read_idx;
let first = &valid[read_idx];
let all_identical = valid[read_idx + 1..group_end]
.iter()
.all(|other| first.values_bit_eq(other));
if all_identical {
stats.duplicate_collapsed += group_len - 1;
let known_at_utc_micros = et_to_utc_micros(
first.known_at_date,
SHORTS_DISSEMINATION_HOUR_ET,
SHORTS_DISSEMINATION_MINUTE_ET,
0,
)?;
if out.last().is_none_or(|prev| prev.key != first.key) {
stats.keys_out += 1;
}
out.push(ShortRow {
key: first.key.clone(),
report_date: first.report_date,
known_at_date: first.known_at_date,
known_at_utc_micros,
shares_short: first.shares_short,
net_change: first.net_change,
pct_float: first.pct_float,
source: SHORTS_SOURCE_CEO,
});
} else {
stats.duplicate_conflict_dropped += group_len;
}
read_idx = group_end;
}
stats.rows_out = out.len();
Ok(ShortsBuild { rows: out, stats })
}
#[cfg(test)]
mod tests {
use super::*;
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 report(
key: &str,
report_date: i32,
shares_short: f64,
net_change: Option<f64>,
pct_float: Option<f64>,
) -> CeoShortReport<String> {
CeoShortReport {
key: key.to_string(),
report_date,
shares_short,
net_change,
pct_float,
}
}
fn assert_invariants<K: Ord>(build: &ShortsBuild<K>) {
let s = &build.stats;
assert_eq!(
s.rows_in,
s.rows_out
+ s.dropped_invalid_shares_short
+ s.duplicate_collapsed
+ s.duplicate_conflict_dropped,
"accounting invariant failed: {s:?}"
);
assert_eq!(s.rows_out, build.rows.len());
for pair in build.rows.windows(2) {
assert!(
(&pair[0].key, pair[0].report_date) < (&pair[1].key, pair[1].report_date),
"rows must be strictly sorted by (key, report_date)"
);
}
for row in &build.rows {
assert!(
row.known_at_date > row.report_date,
"look-ahead violation: known_at_date {} <= report_date {}",
row.known_at_date,
row.report_date
);
assert_eq!(row.source, SHORTS_SOURCE_CEO);
}
}
#[test]
fn supported_date_bounds_match_calendar_constants() {
assert_eq!(day(MIN_SUPPORTED_YEAR, 1, 1), MIN_SUPPORTED_DATE);
assert_eq!(day(MAX_SUPPORTED_YEAR, 12, 31), MAX_SUPPORTED_DATE);
assert_eq!(epoch_days_to_ymd(MIN_SUPPORTED_DATE), (2008, 1, 1));
assert_eq!(epoch_days_to_ymd(MAX_SUPPORTED_DATE), (2030, 12, 31));
assert_eq!(epoch_days_to_ymd(0), (1970, 1, 1));
assert_eq!(epoch_days_to_ymd(-1), (1969, 12, 31));
}
#[test]
fn epoch_days_to_ymd_round_trips_every_supported_day() {
for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE {
let (y, m, dom) = epoch_days_to_ymd(d);
assert_eq!(ymd_to_epoch_days(y, m, dom).unwrap(), d);
}
}
#[test]
fn pinned_tsx_holidays_and_observances_are_non_business_days() {
let holidays = [
// Pinned acceptance criteria dates
(2024, 3, 29), // Good Friday
(2023, 7, 3), // Canada Day observed (Jul 1 Sat)
(2022, 12, 26), // Christmas observed (Dec 25 Sun)
(2022, 12, 27), // Boxing Day observed (Dec 25 Sun)
(2021, 2, 15), // Family Day
(2024, 5, 20), // Victoria Day
(2024, 8, 5), // Civic Holiday
(2024, 10, 14), // Thanksgiving
// New Year's Day weekday + Sat/Sun observances
(2024, 1, 1), // Mon
(2022, 1, 3), // Jan 1 Sat -> Mon Jan 3
(2023, 1, 2), // Jan 1 Sun -> Mon Jan 2
// Christmas/Boxing Day Fri and Sat cases
(2020, 12, 25), // Fri
(2020, 12, 28), // Dec 26 Sat -> Mon Dec 28
(2021, 12, 27), // Dec 25 Sat -> Mon Dec 27
(2021, 12, 28), // Dec 26 Sun -> Tue Dec 28
// Canada Day Sun observance
(2018, 7, 2), // Jul 1 Sun -> Mon Jul 2
// Labour Day
(2024, 9, 2), // 1st Mon of Sep
// Weekend
(2024, 6, 15), // Saturday
(2024, 6, 16), // Sunday
];
for (y, m, d) in holidays {
assert_eq!(
is_canadian_business_day(day(y, m, d)),
Ok(false),
"expected {y:04}-{m:02}-{d:02} to be a non-business day"
);
}
// Ordinary weekdays + federal holidays where TSX remains open
let business_days = [
(2024, 6, 12), // Ordinary Wednesday
(2023, 10, 2), // National Day for Truth & Reconciliation observed (TSX open)
(2024, 9, 30), // National Day for Truth & Reconciliation (TSX open)
(2024, 11, 11), // Remembrance Day (TSX open)
(2021, 12, 24), // Christmas Eve (Fri before Sat Christmas -> TSX open)
(2021, 12, 31), // New Year's Eve (Fri before Sat New Year's -> TSX open)
];
for (y, m, d) in business_days {
assert_eq!(
is_canadian_business_day(day(y, m, d)),
Ok(true),
"expected {y:04}-{m:02}-{d:02} to be a TSX business day"
);
}
}
#[test]
fn add_canadian_business_days_matches_pinned_plus_four_fixtures() {
assert_eq!(
add_canadian_business_days(day(2024, 3, 15), 4),
Ok(day(2024, 3, 21))
);
assert_eq!(
add_canadian_business_days(day(2024, 3, 28), 4),
Ok(day(2024, 4, 4))
);
assert_eq!(
add_canadian_business_days(day(2023, 12, 29), 4),
Ok(day(2024, 1, 5))
);
assert_eq!(
add_canadian_business_days(day(2023, 9, 30), 4),
Ok(day(2023, 10, 5))
);
// n == 0 returns input unchanged when in range (even on a weekend)
assert_eq!(
add_canadian_business_days(day(2023, 9, 30), 0),
Ok(day(2023, 9, 30))
);
// Year-end 2027 rollover into Jan 2028 works cleanly
assert_eq!(
add_canadian_business_days(day(2027, 12, 31), 4),
Ok(day(2028, 1, 7))
);
}
#[test]
fn out_of_range_dates_return_typed_error_without_panicking() {
for bad in [
MIN_SUPPORTED_DATE - 1,
MAX_SUPPORTED_DATE + 1,
day(2007, 12, 31),
day(2031, 1, 1),
i32::MIN,
i32::MAX,
] {
assert!(matches!(
is_canadian_business_day(bad),
Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad
));
assert!(matches!(
add_canadian_business_days(bad, 4),
Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad
));
assert!(matches!(
et_to_utc_micros(bad, 17, 0, 0),
Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad
));
}
// Stepping past MAX_SUPPORTED_DATE returns DateOutOfRange
assert!(matches!(
add_canadian_business_days(day(2030, 12, 30), 4),
Err(ShortsError::DateOutOfRange { .. })
));
}
#[test]
fn et_to_utc_micros_handles_edt_est_dst_boundaries_and_errors() {
// Summer (EDT UTC-4) -> 17:00 ET == 21:00 UTC
assert_eq!(
et_to_utc_micros(day(2024, 7, 15), 17, 0, 0),
Ok(utc_micros(2024, 7, 15, 21, 0, 0))
);
// Winter (EST UTC-5) -> 17:00 ET == 22:00 UTC
assert_eq!(
et_to_utc_micros(day(2024, 1, 15), 17, 0, 0),
Ok(utc_micros(2024, 1, 15, 22, 0, 0))
);
// Both sides of March 2024 spring-forward (2nd Sun = Mar 10)
assert_eq!(
et_to_utc_micros(day(2024, 3, 9), 17, 0, 0),
Ok(utc_micros(2024, 3, 9, 22, 0, 0))
);
assert_eq!(
et_to_utc_micros(day(2024, 3, 10), 1, 59, 59),
Ok(utc_micros(2024, 3, 10, 6, 59, 59))
);
assert_eq!(
et_to_utc_micros(day(2024, 3, 10), 3, 0, 0),
Ok(utc_micros(2024, 3, 10, 7, 0, 0))
);
assert_eq!(
et_to_utc_micros(day(2024, 3, 10), 17, 0, 0),
Ok(utc_micros(2024, 3, 10, 21, 0, 0))
);
// Both sides of November 2024 fall-back (1st Sun = Nov 3)
assert_eq!(
et_to_utc_micros(day(2024, 11, 2), 17, 0, 0),
Ok(utc_micros(2024, 11, 2, 21, 0, 0))
);
assert_eq!(
et_to_utc_micros(day(2024, 11, 3), 0, 30, 0),
Ok(utc_micros(2024, 11, 3, 4, 30, 0))
);
assert_eq!(
et_to_utc_micros(day(2024, 11, 3), 2, 0, 0),
Ok(utc_micros(2024, 11, 3, 7, 0, 0))
);
assert_eq!(
et_to_utc_micros(day(2024, 11, 3), 17, 0, 0),
Ok(utc_micros(2024, 11, 3, 22, 0, 0))
);
// Reuse check for events 16:05 ET lag
assert_eq!(
et_to_utc_micros(day(2024, 7, 15), 16, 5, 0),
Ok(utc_micros(2024, 7, 15, 20, 5, 0))
);
assert_eq!(
et_to_utc_micros(day(2024, 1, 15), 16, 5, 0),
Ok(utc_micros(2024, 1, 15, 21, 5, 0))
);
// Spring-forward nonexistent local time (2026-03-08 02:30)
assert_eq!(
et_to_utc_micros(day(2026, 3, 8), 2, 30, 0),
Err(ShortsError::NonexistentLocalTime {
epoch_day: day(2026, 3, 8),
hour: 2,
minute: 30,
second: 0,
})
);
// Fall-back ambiguous local time (2026-11-01 01:30)
assert_eq!(
et_to_utc_micros(day(2026, 11, 1), 1, 30, 0),
Err(ShortsError::AmbiguousLocalTime {
epoch_day: day(2026, 11, 1),
hour: 1,
minute: 30,
second: 0,
})
);
// Invalid clock components
assert_eq!(
et_to_utc_micros(day(2024, 6, 12), 24, 0, 0),
Err(ShortsError::InvalidLocalTime {
hour: 24,
minute: 0,
second: 0,
})
);
assert_eq!(
et_to_utc_micros(day(2024, 6, 12), 12, 60, 0),
Err(ShortsError::InvalidLocalTime {
hour: 12,
minute: 60,
second: 0,
})
);
assert_eq!(
et_to_utc_micros(day(2024, 6, 12), 12, 0, 60),
Err(ShortsError::InvalidLocalTime {
hour: 12,
minute: 0,
second: 60,
})
);
}
#[test]
fn build_shorts_handles_empty_input() {
let built = build_shorts::<String, _>(Vec::new()).unwrap();
assert!(built.rows.is_empty());
assert_eq!(built.stats, ShortsStats::default());
assert_invariants(&built);
}
#[test]
fn build_shorts_filters_sanitizes_dedups_and_preserves_accounting() {
let d1 = day(2024, 3, 15);
let d2 = day(2024, 3, 28);
let d3 = day(2023, 12, 29);
let input = vec![
// Valid row + bitwise-identical duplicate with -0.0 normalization
report("AAA.TO", d1, -0.0, Some(-0.0), Some(-0.0)),
report("AAA.TO", d1, 0.0, Some(0.0), Some(0.0)),
// Invalid shares_short with NaN optional fields: dropped before optional-field nulling
report("AAA.TO", d2, -10.0, Some(f64::NAN), Some(f64::INFINITY)),
report("AAA.TO", d2, f64::NAN, Some(1.0), None),
report("AAA.TO", d2, f64::INFINITY, None, Some(f64::NEG_INFINITY)),
// Valid row with non-finite optional fields -> nulled and counted
report(
"BBB.TO",
d2,
125_000.0,
Some(f64::NAN),
Some(f64::INFINITY),
),
// Conflicting duplicate group -> dropped entirely
report("CCC.TO", d3, 50_000.0, Some(1_000.0), Some(1.5)),
report("CCC.TO", d3, 50_001.0, Some(1_000.0), Some(1.5)),
];
let built = build_shorts(input).unwrap();
assert_invariants(&built);
assert_eq!(built.stats.rows_in, 8);
assert_eq!(built.stats.rows_out, 2);
assert_eq!(built.stats.keys_out, 2);
assert_eq!(built.stats.dropped_invalid_shares_short, 3);
assert_eq!(built.stats.nulled_invalid_net_change, 1);
assert_eq!(built.stats.nulled_invalid_pct_float, 1);
assert_eq!(built.stats.duplicate_collapsed, 1);
assert_eq!(built.stats.duplicate_conflict_dropped, 2);
assert_eq!(built.rows[0].key, "AAA.TO");
assert_eq!(built.rows[0].report_date, d1);
assert_eq!(built.rows[0].known_at_date, day(2024, 3, 21));
assert_eq!(
built.rows[0].known_at_utc_micros,
utc_micros(2024, 3, 21, 21, 0, 0)
);
assert_eq!(built.rows[0].shares_short.to_bits(), 0.0_f64.to_bits());
assert_eq!(
built.rows[0].net_change.map(f64::to_bits),
Some(0.0_f64.to_bits())
);
assert_eq!(
built.rows[0].pct_float.map(f64::to_bits),
Some(0.0_f64.to_bits())
);
assert_eq!(built.rows[1].key, "BBB.TO");
assert_eq!(built.rows[1].report_date, d2);
assert_eq!(built.rows[1].known_at_date, day(2024, 4, 4));
assert_eq!(
built.rows[1].known_at_utc_micros,
utc_micros(2024, 4, 4, 21, 0, 0)
);
assert_eq!(built.rows[1].shares_short, 125_000.0);
assert_eq!(built.rows[1].net_change, None);
assert_eq!(built.rows[1].pct_float, None);
}
#[test]
fn build_shorts_rejects_out_of_range_date_even_on_invalid_shares_row() {
let err = build_shorts(vec![report(
"AAA.TO",
day(2007, 12, 31),
-5.0,
None,
None,
)])
.unwrap_err();
assert!(matches!(err, ShortsError::DateOutOfRange { .. }));
}
}