1246 lines
45 KiB
Rust
1246 lines
45 KiB
Rust
//! Pure, in-memory `events` builder (`qmFilings` `timefiled` → UTC + form groups; `qmEarnings`
|
|
//! linked to same-day `8-K` / `News release` filing or conservatively lagged to `16:05 ET`).
|
|
//!
|
|
//! Produces deterministically sorted [`EventRow`] records matching `events/year=YYYY/part.parquet`
|
|
//! in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype,
|
|
//! payload_json`), plus [`partition_year_utc`] / [`EventRow::partition_year`] for `year=YYYY`
|
|
//! partitioning.
|
|
//!
|
|
//! ## Point-in-time & Provenance Rules
|
|
//! - **Filings (`kind = "filing"`):** `timefiled` is parsed strictly as `YYYY-MM-DDTHH:MM:SS EST`
|
|
//! (`UTC-5`) or `YYYY-MM-DDTHH:MM:SS EDT` (`UTC-4`). Using the explicit zone abbreviation's
|
|
//! fixed offset avoids DST calendar range limits so pre-2008 filings convert cleanly.
|
|
//! `ts_micros = known_at_micros = UTC(timefiled)` with `known_at_source = "filing_timestamp"`.
|
|
//! *Caveat:* EDGAR filings accepted after `17:30 ET` are not shifted to the next business day
|
|
//! here (per the M1.2g contract); downstream intraday studies should apply exchange-session
|
|
//! routing / post-`17:30 ET` visibility rules on top of `known_at_micros`.
|
|
//! - **Earnings (`kind = "earnings"`):**
|
|
//! 1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments)
|
|
//! whose local ET calendar date matches `report_date`, `known_at_micros` is the earliest such
|
|
//! filing's UTC timestamp (`known_at_source = "filing_timestamp"`).
|
|
//! 2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via
|
|
//! [`crate::shorts::et_to_utc_micros`] (`known_at_source = "statutory_lag_estimate"`).
|
|
//! This conservative fallback is intended for T+1 open use (not same-day intraday cutoffs,
|
|
//! since a later same-date `8-K` / `News release` filing supersedes the fallback with its
|
|
//! actual filing timestamp). It applies to `N/A`, `BTO`, and `AMC` rows alike whenever no
|
|
//! linked filing provides a verified timestamp—unlinked `BTO`/`AMC` rows are never stamped
|
|
//! earlier than `16:05 ET`.
|
|
//! 3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`
|
|
//! (`2008-01-01..=2030-12-31`) are skipped and counted (`earnings_skipped_out_of_range`).
|
|
//! 4. Post-hoc overwritten `consensusEps` is deliberately omitted from [`QmEarning`] and
|
|
//! earnings `payload_json` per `design/DATA-CONTRACTS.md` §1.
|
|
|
|
use std::error::Error;
|
|
use std::fmt::{self, Write as _};
|
|
|
|
use crate::shorts::{epoch_days_to_ymd, et_to_utc_micros};
|
|
use crate::split::ymd_to_epoch_days;
|
|
|
|
/// Canonical `kind` label for `qmFilings` rows.
|
|
pub const EVENT_KIND_FILING: &str = "filing";
|
|
|
|
/// Canonical `kind` label for `qmEarnings` rows.
|
|
pub const EVENT_KIND_EARNINGS: &str = "earnings";
|
|
|
|
/// Provenance label when `known_at_micros` comes directly from a parsed `qmFilings.timefiled`.
|
|
pub const KNOWN_AT_SOURCE_FILING_TIMESTAMP: &str = "filing_timestamp";
|
|
|
|
/// Provenance label when an unlinked earnings row falls back to `report_date 16:05 ET`.
|
|
pub const KNOWN_AT_SOURCE_STATUTORY_LAG: &str = "statutory_lag_estimate";
|
|
|
|
/// Conservative fallback hour (`16:05 America/Toronto`) for unlinked earnings rows.
|
|
pub const EARNINGS_FALLBACK_HOUR_ET: u8 = 16;
|
|
|
|
/// Conservative fallback minute (`16:05 America/Toronto`) for unlinked earnings rows.
|
|
pub const EARNINGS_FALLBACK_MINUTE_ET: u8 = 5;
|
|
|
|
const MICROS_PER_DAY: i64 = 86_400_000_000;
|
|
|
|
/// Returns the UTC Gregorian calendar year for `ts_micros` (microseconds since
|
|
/// `1970-01-01T00:00:00Z`), used for `events/year=YYYY/part.parquet` partitioning.
|
|
#[inline]
|
|
pub fn partition_year_utc(ts_micros: i64) -> i32 {
|
|
let epoch_day = ts_micros.div_euclid(MICROS_PER_DAY) as i32;
|
|
epoch_days_to_ymd(epoch_day).0
|
|
}
|
|
|
|
/// Typed parse errors returned by [`parse_filing_timefiled`].
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum FilingTimeError {
|
|
/// Input did not match the exact 19-byte ASCII `YYYY-MM-DDTHH:MM:SS` prefix structure.
|
|
MalformedFormat,
|
|
/// Input had a valid timestamp prefix but was missing a zone or used a zone other than
|
|
/// `" EST"` or `" EDT"`.
|
|
UnknownZone,
|
|
/// Calendar date components were not a valid Gregorian date (e.g., `2025-02-30`).
|
|
InvalidDate,
|
|
/// Clock components were outside `00:00:00..=23:59:59`.
|
|
InvalidTime,
|
|
}
|
|
|
|
impl fmt::Display for FilingTimeError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match *self {
|
|
Self::MalformedFormat => {
|
|
write!(f, "malformed filing timestamp (expected YYYY-MM-DDTHH:MM:SS EST|EDT)")
|
|
}
|
|
Self::UnknownZone => {
|
|
write!(f, "missing or unsupported filing time zone (expected ' EST' or ' EDT')")
|
|
}
|
|
Self::InvalidDate => write!(f, "invalid Gregorian calendar date in filing timestamp"),
|
|
Self::InvalidTime => {
|
|
write!(f, "invalid wall-clock time in filing timestamp (expected 00:00:00..=23:59:59)")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for FilingTimeError {}
|
|
|
|
/// Parsed `qmFilings.timefiled` carrying both the UTC instant and the local ET calendar date.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct ParsedFilingTime {
|
|
/// UTC timestamp in microseconds since `1970-01-01T00:00:00Z`.
|
|
pub utc_micros: i64,
|
|
/// Local Eastern Time calendar date as days since `1970-01-01` (used for same-day earnings
|
|
/// linking even when late-evening ET crosses into the next UTC calendar day).
|
|
pub et_date: i32,
|
|
}
|
|
|
|
#[inline]
|
|
fn parse_2_digits(bytes: &[u8], offset: usize) -> Option<u32> {
|
|
let a = bytes[offset];
|
|
let b = bytes[offset + 1];
|
|
if a.is_ascii_digit() && b.is_ascii_digit() {
|
|
Some(u32::from(a - b'0') * 10 + u32::from(b - b'0'))
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn parse_4_digits(bytes: &[u8], offset: usize) -> Option<i32> {
|
|
let hi = parse_2_digits(bytes, offset)?;
|
|
let lo = parse_2_digits(bytes, offset + 2)?;
|
|
Some((hi * 100 + lo) as i32)
|
|
}
|
|
|
|
/// Strictly parses a `qmFilings.timefiled` string of the form `YYYY-MM-DDTHH:MM:SS EST` or
|
|
/// `YYYY-MM-DDTHH:MM:SS EDT`.
|
|
///
|
|
/// Uses the explicit zone abbreviation's fixed offset (`EST = UTC-5`, `EDT = UTC-4`) so historical
|
|
/// pre-2008 filings convert without DST table range restrictions. Never panics and never guesses
|
|
/// on malformed strings, unknown zones, or invalid calendar dates/times.
|
|
pub fn parse_filing_timefiled(raw: &str) -> Result<ParsedFilingTime, FilingTimeError> {
|
|
let bytes = raw.as_bytes();
|
|
if bytes.len() < 19
|
|
|| bytes[4] != b'-'
|
|
|| bytes[7] != b'-'
|
|
|| bytes[10] != b'T'
|
|
|| bytes[13] != b':'
|
|
|| bytes[16] != b':'
|
|
{
|
|
return Err(FilingTimeError::MalformedFormat);
|
|
}
|
|
|
|
let year = parse_4_digits(bytes, 0).ok_or(FilingTimeError::MalformedFormat)?;
|
|
let month = parse_2_digits(bytes, 5).ok_or(FilingTimeError::MalformedFormat)?;
|
|
let day = parse_2_digits(bytes, 8).ok_or(FilingTimeError::MalformedFormat)?;
|
|
let hour = parse_2_digits(bytes, 11).ok_or(FilingTimeError::MalformedFormat)?;
|
|
let minute = parse_2_digits(bytes, 14).ok_or(FilingTimeError::MalformedFormat)?;
|
|
let second = parse_2_digits(bytes, 17).ok_or(FilingTimeError::MalformedFormat)?;
|
|
|
|
let offset_hours: i64 = match &bytes[19..] {
|
|
b" EST" => 5,
|
|
b" EDT" => 4,
|
|
_ => return Err(FilingTimeError::UnknownZone),
|
|
};
|
|
|
|
let et_date = ymd_to_epoch_days(year, month, day).map_err(|_| FilingTimeError::InvalidDate)?;
|
|
if hour > 23 || minute > 59 || second > 59 {
|
|
return Err(FilingTimeError::InvalidTime);
|
|
}
|
|
|
|
let local_secs = i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second);
|
|
let utc_secs = i64::from(et_date) * 86_400 + local_secs + offset_hours * 3_600;
|
|
Ok(ParsedFilingTime {
|
|
utc_micros: utc_secs * 1_000_000,
|
|
et_date,
|
|
})
|
|
}
|
|
|
|
/// Canonical form-group classification for US EDGAR and Canadian SEDAR+ filings.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum FilingFormGroup {
|
|
Form10K,
|
|
Form10Q,
|
|
Form8K,
|
|
Form4,
|
|
Form144,
|
|
Form40F,
|
|
InterimFinancials,
|
|
AnnualFinancials,
|
|
Mda,
|
|
Form52109,
|
|
Ni43101,
|
|
Form45106F1,
|
|
NewsRelease,
|
|
Other,
|
|
}
|
|
|
|
impl FilingFormGroup {
|
|
/// Canonical lowercase `subtype` string written to [`EventRow::subtype`].
|
|
#[inline]
|
|
pub const fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::Form10K => "10-k",
|
|
Self::Form10Q => "10-q",
|
|
Self::Form8K => "8-k",
|
|
Self::Form4 => "4",
|
|
Self::Form144 => "144",
|
|
Self::Form40F => "40-f",
|
|
Self::InterimFinancials => "interim_financial_statements",
|
|
Self::AnnualFinancials => "annual_financial_statements",
|
|
Self::Mda => "mda",
|
|
Self::Form52109 => "52-109",
|
|
Self::Ni43101 => "ni_43_101",
|
|
Self::Form45106F1 => "45-106f1",
|
|
Self::NewsRelease => "news_release",
|
|
Self::Other => "other",
|
|
}
|
|
}
|
|
|
|
/// Returns `true` iff this form group is a periodic financial report eligible for the M2
|
|
/// `fundamentals_pit` filing join (`10-K`, `10-Q`, `40-F`, `Interim financial statements`,
|
|
/// `Annual financial statements`).
|
|
#[inline]
|
|
pub const fn is_periodic_financial_report(self) -> bool {
|
|
matches!(
|
|
self,
|
|
Self::Form10K
|
|
| Self::Form10Q
|
|
| Self::Form40F
|
|
| Self::InterimFinancials
|
|
| Self::AnnualFinancials
|
|
)
|
|
}
|
|
|
|
/// Returns `true` iff this form group may anchor a same-day `qmEarnings` announcement time
|
|
/// (`8-K` or `News release`).
|
|
#[inline]
|
|
pub const fn is_earnings_link_candidate(self) -> bool {
|
|
matches!(self, Self::Form8K | Self::NewsRelease)
|
|
}
|
|
}
|
|
|
|
/// Exact-match EDGAR form table (checked after stripping optional `/A` amendment suffix).
|
|
/// Keeping EDGAR codes exact prevents `"4"` from falsely matching `"40-F"`, `"424B5"`, or
|
|
/// `"45-106F1"`.
|
|
const EXACT_EDGAR_FORM_RULES: &[(&str, FilingFormGroup)] = &[
|
|
("10-K", FilingFormGroup::Form10K),
|
|
("10-Q", FilingFormGroup::Form10Q),
|
|
("8-K", FilingFormGroup::Form8K),
|
|
("4", FilingFormGroup::Form4),
|
|
("144", FilingFormGroup::Form144),
|
|
("40-F", FilingFormGroup::Form40F),
|
|
];
|
|
|
|
/// Fixed-priority substring rules for Canadian SEDAR+ filing descriptions.
|
|
const SEDAR_SUBSTRING_RULES: &[(&str, FilingFormGroup)] = &[
|
|
("INTERIM FINANCIAL STATEMENTS", FilingFormGroup::InterimFinancials),
|
|
("INTERIM FINANCIAL REPORT", FilingFormGroup::InterimFinancials),
|
|
("ANNUAL FINANCIAL STATEMENTS", FilingFormGroup::AnnualFinancials),
|
|
("MD&A", FilingFormGroup::Mda),
|
|
("MANAGEMENT'S DISCUSSION AND ANALYSIS", FilingFormGroup::Mda),
|
|
("52-109", FilingFormGroup::Form52109),
|
|
("43-101", FilingFormGroup::Ni43101),
|
|
("45-106F1", FilingFormGroup::Form45106F1),
|
|
("NEWS RELEASE", FilingFormGroup::NewsRelease),
|
|
];
|
|
|
|
/// Returns `true` iff `upper` contains `"AMENDED"` as a standalone ASCII token (not embedded in a
|
|
/// longer word such as `"UNAMENDED"`).
|
|
fn contains_standalone_amended(upper: &str) -> bool {
|
|
let bytes = upper.as_bytes();
|
|
let needle = "AMENDED";
|
|
let mut offset = 0;
|
|
while let Some(rel) = upper[offset..].find(needle) {
|
|
let start = offset + rel;
|
|
let end = start + needle.len();
|
|
let left_ok = start == 0 || !bytes[start - 1].is_ascii_alphanumeric();
|
|
let right_ok = end == bytes.len() || !bytes[end].is_ascii_alphanumeric();
|
|
if left_ok && right_ok {
|
|
return true;
|
|
}
|
|
offset = start + 1;
|
|
}
|
|
false
|
|
}
|
|
|
|
/// Strips leading/trailing amendment markers (`/A`, `(AMENDED)`, or standalone `AMENDED` with
|
|
/// adjacent whitespace/punctuation separators) from an uppercased form label so exact EDGAR codes
|
|
/// such as `"10-K (Amended)"` or `"Amended 10-Q"` retain their underlying form group.
|
|
fn strip_amendment_markers(mut s: &str) -> (&str, bool) {
|
|
let mut stripped_any = false;
|
|
loop {
|
|
let trimmed = s.trim();
|
|
let next = if let Some(prefix) = trimmed.strip_suffix("/A") {
|
|
Some(prefix.trim_end())
|
|
} else if let Some(prefix) = trimmed.strip_suffix("(AMENDED)") {
|
|
Some(prefix.trim_end_matches(|c: char| {
|
|
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
|
|
}))
|
|
} else if let Some(suffix) = trimmed.strip_prefix("(AMENDED)") {
|
|
Some(suffix.trim_start_matches(|c: char| {
|
|
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
|
|
}))
|
|
} else if let Some(prefix) = trimmed.strip_suffix("AMENDED") {
|
|
if prefix
|
|
.as_bytes()
|
|
.last()
|
|
.is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'-' | b',' | b':'))
|
|
{
|
|
Some(prefix.trim_end_matches(|c: char| {
|
|
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
|
|
}))
|
|
} else {
|
|
None
|
|
}
|
|
} else if let Some(suffix) = trimmed.strip_prefix("AMENDED") {
|
|
if suffix
|
|
.as_bytes()
|
|
.first()
|
|
.is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'-' | b',' | b':'))
|
|
{
|
|
Some(suffix.trim_start_matches(|c: char| {
|
|
c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':')
|
|
}))
|
|
} else {
|
|
None
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
|
|
match next {
|
|
Some(rest) => {
|
|
stripped_any = true;
|
|
s = rest;
|
|
}
|
|
None => {
|
|
s = trimmed;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
(s, stripped_any)
|
|
}
|
|
|
|
/// Classifies a raw `qmFilings.form_type` into `(FilingFormGroup, is_amendment)`.
|
|
///
|
|
/// - Trims ASCII whitespace and compares case-insensitively.
|
|
/// - Detects and strips `/A` suffixes (e.g. `10-K/A`, `8-K/A`, `40-F/A`) and standalone
|
|
/// `"amended"` markers (e.g. `10-K (Amended)`, `10-Q - Amended`, `Amended 40-F`) before exact
|
|
/// EDGAR matching so amendments retain their underlying [`FilingFormGroup`].
|
|
/// - Checks exact EDGAR codes first, then SEDAR+ substring rules in fixed priority order,
|
|
/// defaulting to [`FilingFormGroup::Other`].
|
|
pub fn classify_form_type(form_type: &str) -> (FilingFormGroup, bool) {
|
|
let trimmed = form_type.trim();
|
|
if trimmed.is_empty() {
|
|
return (FilingFormGroup::Other, false);
|
|
}
|
|
|
|
let upper = trimmed.to_ascii_uppercase();
|
|
let (base, stripped_amendment) = strip_amendment_markers(&upper);
|
|
let is_amendment = stripped_amendment || contains_standalone_amended(base);
|
|
|
|
for &(code, group) in EXACT_EDGAR_FORM_RULES {
|
|
if base == code {
|
|
return (group, is_amendment);
|
|
}
|
|
}
|
|
|
|
for &(needle, group) in SEDAR_SUBSTRING_RULES {
|
|
if base.contains(needle) {
|
|
return (group, is_amendment);
|
|
}
|
|
}
|
|
|
|
(FilingFormGroup::Other, is_amendment)
|
|
}
|
|
|
|
/// Convenience predicate returning `true` iff `form_type` classifies as a periodic financial
|
|
/// report (`10-K`, `10-Q`, `40-F`, `Interim financial statements`, `Annual financial statements`,
|
|
/// including amendments).
|
|
#[inline]
|
|
pub fn is_periodic_financial_report(form_type: &str) -> bool {
|
|
classify_form_type(form_type)
|
|
.0
|
|
.is_periodic_financial_report()
|
|
}
|
|
|
|
/// Normalizes `qmEarnings.announceTime` into `"bto"`, `"amc"`, or `"unknown"`.
|
|
#[inline]
|
|
pub fn normalize_announce_time(raw: &str) -> &'static str {
|
|
let trimmed = raw.trim();
|
|
if trimmed.eq_ignore_ascii_case("bto") {
|
|
"bto"
|
|
} else if trimmed.eq_ignore_ascii_case("amc") {
|
|
"amc"
|
|
} else {
|
|
"unknown"
|
|
}
|
|
}
|
|
|
|
/// A single raw `qmFilings` input record.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct QmFiling<K = String> {
|
|
pub key: K,
|
|
/// Raw Eastern timestamp string, e.g. `"2025-01-31T06:01:27 EST"`.
|
|
pub timefiled: String,
|
|
/// Raw EDGAR or SEDAR+ form type string, e.g. `"10-K/A"` or `"News release"`.
|
|
pub form_type: String,
|
|
/// Optional provider filing / accession identifier included in `payload_json`.
|
|
pub filing_id: Option<String>,
|
|
/// Optional filing document URL included in `payload_json`.
|
|
pub url: Option<String>,
|
|
}
|
|
|
|
/// A single raw `qmEarnings` input record.
|
|
///
|
|
/// Deliberately omits `consensusEps`, which is overwritten post-hoc in `qmEarnings` per
|
|
/// `design/DATA-CONTRACTS.md` §1 and is not point-in-time safe.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct QmEarning<K = String> {
|
|
pub key: K,
|
|
/// Earnings report calendar date (ET) as days since `1970-01-01` (UTC Gregorian).
|
|
pub report_date: i32,
|
|
/// Raw provider announce-time code (`"BTO"`, `"AMC"`, `"N/A"`, etc.).
|
|
pub announce_time: String,
|
|
/// Optional fiscal period end date as days since `1970-01-01`.
|
|
pub fiscal_period_end: Option<i32>,
|
|
/// Optional reported actual EPS (non-finite values emit as `null` in `payload_json`).
|
|
pub actual_eps: Option<f64>,
|
|
/// Optional reported revenue (non-finite values emit as `null` in `payload_json`).
|
|
pub revenue: Option<f64>,
|
|
}
|
|
|
|
/// A single curated `events` row matching `events/year=YYYY/part.parquet`.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct EventRow<K = String> {
|
|
pub key: K,
|
|
/// Event timestamp in UTC microseconds since `1970-01-01T00:00:00Z`.
|
|
pub ts_micros: i64,
|
|
/// Point-in-time availability timestamp in UTC microseconds since `1970-01-01T00:00:00Z`.
|
|
pub known_at_micros: i64,
|
|
/// Provenance of `known_at_micros` (`"filing_timestamp"` or `"statutory_lag_estimate"`).
|
|
pub known_at_source: &'static str,
|
|
/// Event category (`"filing"` or `"earnings"`).
|
|
pub kind: &'static str,
|
|
/// Normalized form group (filings) or announce time (`"bto"` / `"amc"` / `"unknown"`, earnings).
|
|
pub subtype: String,
|
|
/// Compact RFC 8259 JSON object with stable key ordering.
|
|
pub payload_json: String,
|
|
}
|
|
|
|
impl<K> EventRow<K> {
|
|
/// Returns the UTC Gregorian partition year of [`Self::ts_micros`] (`year=YYYY`).
|
|
#[inline]
|
|
pub fn partition_year(&self) -> i32 {
|
|
partition_year_utc(self.ts_micros)
|
|
}
|
|
}
|
|
|
|
/// Exact per-kind accounting counters produced alongside [`EventsBuild::rows`].
|
|
///
|
|
/// Conservation invariants:
|
|
/// - `filings_in == filings_out + filings_skipped_malformed_timestamp + filings_skipped_unknown_zone + filings_skipped_invalid_date_time + filings_duplicate_collapsed`
|
|
/// - `earnings_in == earnings_out + earnings_skipped_out_of_range + earnings_duplicate_collapsed + earnings_duplicate_conflict_dropped`
|
|
/// - `earnings_out == earnings_linked_to_filing + earnings_lagged_1605`
|
|
/// - `rows_out == filings_out + earnings_out`
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct EventsStats {
|
|
pub filings_in: usize,
|
|
pub filings_out: usize,
|
|
pub filings_skipped_malformed_timestamp: usize,
|
|
pub filings_skipped_unknown_zone: usize,
|
|
pub filings_skipped_invalid_date_time: usize,
|
|
pub filings_duplicate_collapsed: usize,
|
|
pub earnings_in: usize,
|
|
pub earnings_out: usize,
|
|
pub earnings_linked_to_filing: usize,
|
|
pub earnings_lagged_1605: usize,
|
|
pub earnings_skipped_out_of_range: usize,
|
|
pub earnings_duplicate_collapsed: usize,
|
|
pub earnings_duplicate_conflict_dropped: usize,
|
|
pub rows_out: usize,
|
|
pub keys_out: usize,
|
|
}
|
|
|
|
/// Output of [`build_events`]: deterministically sorted `events` rows and reconciling stats.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct EventsBuild<K = String> {
|
|
pub rows: Vec<EventRow<K>>,
|
|
pub stats: EventsStats,
|
|
}
|
|
|
|
#[inline]
|
|
fn sanitize_opt_f64(value: Option<f64>) -> Option<f64> {
|
|
match value {
|
|
Some(v) if v.is_finite() => Some(if v == 0.0 { 0.0 } else { v }),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
const HEX_LOWER: &[u8; 16] = b"0123456789abcdef";
|
|
|
|
pub(crate) fn push_json_str(out: &mut String, s: &str) {
|
|
out.push('"');
|
|
let bytes = s.as_bytes();
|
|
let mut start = 0usize;
|
|
for (idx, &b) in bytes.iter().enumerate() {
|
|
let escaped = match b {
|
|
b'"' => Some("\\\""),
|
|
b'\\' => Some("\\\\"),
|
|
0x08 => Some("\\b"),
|
|
0x0C => Some("\\f"),
|
|
b'\n' => Some("\\n"),
|
|
b'\r' => Some("\\r"),
|
|
b'\t' => Some("\\t"),
|
|
0x00..=0x1F => {
|
|
if start < idx {
|
|
out.push_str(&s[start..idx]);
|
|
}
|
|
out.push_str("\\u00");
|
|
out.push(HEX_LOWER[(b >> 4) as usize] as char);
|
|
out.push(HEX_LOWER[(b & 0x0F) as usize] as char);
|
|
start = idx + 1;
|
|
continue;
|
|
}
|
|
_ => None,
|
|
};
|
|
if let Some(esc) = escaped {
|
|
if start < idx {
|
|
out.push_str(&s[start..idx]);
|
|
}
|
|
out.push_str(esc);
|
|
start = idx + 1;
|
|
}
|
|
}
|
|
if start < bytes.len() {
|
|
out.push_str(&s[start..]);
|
|
}
|
|
out.push('"');
|
|
}
|
|
|
|
#[inline]
|
|
pub(crate) fn push_json_opt_str(out: &mut String, s: Option<&str>) {
|
|
match s {
|
|
Some(v) => push_json_str(out, v),
|
|
None => out.push_str("null"),
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn push_json_opt_f64(out: &mut String, v: Option<f64>) {
|
|
match sanitize_opt_f64(v) {
|
|
Some(x) => {
|
|
let _ = write!(out, "{x}");
|
|
}
|
|
None => out.push_str("null"),
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn push_json_date(out: &mut String, epoch_day: i32) {
|
|
let (y, m, d) = epoch_days_to_ymd(epoch_day);
|
|
let _ = write!(out, "\"{y:04}-{m:02}-{d:02}\"");
|
|
}
|
|
|
|
#[inline]
|
|
fn push_json_opt_date(out: &mut String, epoch_day: Option<i32>) {
|
|
match epoch_day {
|
|
Some(d) => push_json_date(out, d),
|
|
None => out.push_str("null"),
|
|
}
|
|
}
|
|
|
|
/// Encodes a filing event's `payload_json` as a compact RFC 8259 JSON object with stable key
|
|
/// ordering: `{"filing_id":...,"form_type":...,"is_amendment":...,"url":...}`.
|
|
pub fn encode_filing_payload_json(
|
|
filing_id: Option<&str>,
|
|
form_type: &str,
|
|
is_amendment: bool,
|
|
url: Option<&str>,
|
|
) -> String {
|
|
let cap = 56
|
|
+ filing_id.map_or(4, str::len)
|
|
+ form_type.len()
|
|
+ url.map_or(4, str::len);
|
|
let mut out = String::with_capacity(cap);
|
|
out.push_str("{\"filing_id\":");
|
|
push_json_opt_str(&mut out, filing_id);
|
|
out.push_str(",\"form_type\":");
|
|
push_json_str(&mut out, form_type);
|
|
out.push_str(",\"is_amendment\":");
|
|
out.push_str(if is_amendment { "true" } else { "false" });
|
|
out.push_str(",\"url\":");
|
|
push_json_opt_str(&mut out, url);
|
|
out.push('}');
|
|
out
|
|
}
|
|
|
|
/// Encodes an earnings event's `payload_json` as a compact RFC 8259 JSON object with stable key
|
|
/// ordering:
|
|
/// `{"actual_eps":...,"announce_time":...,"fiscal_period_end":...,"linked_filing_id":...,"report_date":"YYYY-MM-DD","revenue":...}`.
|
|
///
|
|
/// Non-finite numeric values emit as `null`, `-0.0` normalizes to `0.0`, and `consensusEps` is
|
|
/// deliberately omitted.
|
|
pub fn encode_earnings_payload_json(
|
|
actual_eps: Option<f64>,
|
|
announce_time: &str,
|
|
fiscal_period_end: Option<i32>,
|
|
linked_filing_id: Option<&str>,
|
|
report_date: i32,
|
|
revenue: Option<f64>,
|
|
) -> String {
|
|
let cap = 112 + announce_time.len() + linked_filing_id.map_or(4, str::len);
|
|
let mut out = String::with_capacity(cap);
|
|
out.push_str("{\"actual_eps\":");
|
|
push_json_opt_f64(&mut out, actual_eps);
|
|
out.push_str(",\"announce_time\":");
|
|
push_json_str(&mut out, announce_time);
|
|
out.push_str(",\"fiscal_period_end\":");
|
|
push_json_opt_date(&mut out, fiscal_period_end);
|
|
out.push_str(",\"linked_filing_id\":");
|
|
push_json_opt_str(&mut out, linked_filing_id);
|
|
out.push_str(",\"report_date\":");
|
|
push_json_date(&mut out, report_date);
|
|
out.push_str(",\"revenue\":");
|
|
push_json_opt_f64(&mut out, revenue);
|
|
out.push('}');
|
|
out
|
|
}
|
|
|
|
struct QualifyingLink<K> {
|
|
key: K,
|
|
et_date: i32,
|
|
utc_micros: i64,
|
|
filing_id: Option<String>,
|
|
form_type: String,
|
|
url: Option<String>,
|
|
}
|
|
|
|
struct NormalizedEarning<K> {
|
|
key: K,
|
|
report_date: i32,
|
|
ts_micros: i64,
|
|
known_at_source: &'static str,
|
|
is_linked: bool,
|
|
link_idx: Option<usize>,
|
|
subtype: &'static str,
|
|
fiscal_period_end: Option<i32>,
|
|
actual_eps: Option<f64>,
|
|
revenue: Option<f64>,
|
|
}
|
|
|
|
impl<K> NormalizedEarning<K> {
|
|
#[inline]
|
|
fn values_bit_eq(&self, other: &Self) -> bool {
|
|
self.subtype == other.subtype
|
|
&& self.fiscal_period_end == other.fiscal_period_end
|
|
&& self.actual_eps.map(f64::to_bits) == other.actual_eps.map(f64::to_bits)
|
|
&& self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits)
|
|
}
|
|
}
|
|
|
|
/// Crate-internal [`EventRow`] paired with its exact Eastern local calendar date (`et_date` for
|
|
/// filings, `report_date` for earnings) for point-in-time `provider_mapping` resolution across all
|
|
/// supported years (including pre-2008 filings and late-evening ET rollovers).
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub(crate) struct EventRowWithDate<K> {
|
|
pub(crate) row: EventRow<K>,
|
|
pub(crate) event_date: i32,
|
|
}
|
|
|
|
trait EventRecord<K>: Sized {
|
|
fn from_parts(row: EventRow<K>, event_date: i32) -> Self;
|
|
fn event_row(&self) -> &EventRow<K>;
|
|
fn event_date_tiebreak(&self) -> i32;
|
|
}
|
|
|
|
impl<K> EventRecord<K> for EventRow<K> {
|
|
#[inline]
|
|
fn from_parts(row: EventRow<K>, _event_date: i32) -> Self {
|
|
row
|
|
}
|
|
|
|
#[inline]
|
|
fn event_row(&self) -> &EventRow<K> {
|
|
self
|
|
}
|
|
|
|
#[inline]
|
|
fn event_date_tiebreak(&self) -> i32 {
|
|
0
|
|
}
|
|
}
|
|
|
|
impl<K> EventRecord<K> for EventRowWithDate<K> {
|
|
#[inline]
|
|
fn from_parts(row: EventRow<K>, event_date: i32) -> Self {
|
|
Self { row, event_date }
|
|
}
|
|
|
|
#[inline]
|
|
fn event_row(&self) -> &EventRow<K> {
|
|
&self.row
|
|
}
|
|
|
|
#[inline]
|
|
fn event_date_tiebreak(&self) -> i32 {
|
|
self.event_date
|
|
}
|
|
}
|
|
|
|
fn build_events_impl<K, R, IF, IE>(filings: IF, earnings: IE) -> (Vec<R>, EventsStats)
|
|
where
|
|
K: Ord + Clone,
|
|
R: EventRecord<K>,
|
|
IF: IntoIterator<Item = QmFiling<K>>,
|
|
IE: IntoIterator<Item = QmEarning<K>>,
|
|
{
|
|
let filings_iter = filings.into_iter();
|
|
let (filings_lower, _) = filings_iter.size_hint();
|
|
let mut stats = EventsStats::default();
|
|
let mut rows: Vec<R> = Vec::with_capacity(filings_lower);
|
|
let mut links: Vec<QualifyingLink<K>> = Vec::new();
|
|
|
|
for filing in filings_iter {
|
|
stats.filings_in += 1;
|
|
|
|
let parsed = match parse_filing_timefiled(&filing.timefiled) {
|
|
Ok(p) => p,
|
|
Err(FilingTimeError::MalformedFormat) => {
|
|
stats.filings_skipped_malformed_timestamp += 1;
|
|
continue;
|
|
}
|
|
Err(FilingTimeError::UnknownZone) => {
|
|
stats.filings_skipped_unknown_zone += 1;
|
|
continue;
|
|
}
|
|
Err(FilingTimeError::InvalidDate | FilingTimeError::InvalidTime) => {
|
|
stats.filings_skipped_invalid_date_time += 1;
|
|
continue;
|
|
}
|
|
};
|
|
|
|
let (group, is_amendment) = classify_form_type(&filing.form_type);
|
|
let payload_json = encode_filing_payload_json(
|
|
filing.filing_id.as_deref(),
|
|
&filing.form_type,
|
|
is_amendment,
|
|
filing.url.as_deref(),
|
|
);
|
|
|
|
if group.is_earnings_link_candidate() {
|
|
links.push(QualifyingLink {
|
|
key: filing.key.clone(),
|
|
et_date: parsed.et_date,
|
|
utc_micros: parsed.utc_micros,
|
|
filing_id: filing.filing_id,
|
|
form_type: filing.form_type,
|
|
url: filing.url,
|
|
});
|
|
}
|
|
|
|
rows.push(R::from_parts(
|
|
EventRow {
|
|
key: filing.key,
|
|
ts_micros: parsed.utc_micros,
|
|
known_at_micros: parsed.utc_micros,
|
|
known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP,
|
|
kind: EVENT_KIND_FILING,
|
|
subtype: group.as_str().to_string(),
|
|
payload_json,
|
|
},
|
|
parsed.et_date,
|
|
));
|
|
}
|
|
|
|
// Retain the strictly earliest deterministic qualifying filing per (key, et_date).
|
|
links.sort_unstable_by(|a, b| {
|
|
a.key
|
|
.cmp(&b.key)
|
|
.then_with(|| a.et_date.cmp(&b.et_date))
|
|
.then_with(|| a.utc_micros.cmp(&b.utc_micros))
|
|
.then_with(|| a.filing_id.cmp(&b.filing_id))
|
|
.then_with(|| a.form_type.cmp(&b.form_type))
|
|
.then_with(|| a.url.cmp(&b.url))
|
|
});
|
|
links.dedup_by(|later, earlier| earlier.key == later.key && earlier.et_date == later.et_date);
|
|
|
|
// Collapse exact duplicate filing rows.
|
|
rows.sort_unstable_by(|a, b| {
|
|
let ra = a.event_row();
|
|
let rb = b.event_row();
|
|
ra.key
|
|
.cmp(&rb.key)
|
|
.then_with(|| ra.ts_micros.cmp(&rb.ts_micros))
|
|
.then_with(|| ra.subtype.cmp(&rb.subtype))
|
|
.then_with(|| ra.payload_json.cmp(&rb.payload_json))
|
|
.then_with(|| a.event_date_tiebreak().cmp(&b.event_date_tiebreak()))
|
|
});
|
|
let filings_before_dedup = rows.len();
|
|
rows.dedup_by(|b, a| {
|
|
let ra = a.event_row();
|
|
let rb = b.event_row();
|
|
ra.key == rb.key
|
|
&& ra.ts_micros == rb.ts_micros
|
|
&& ra.subtype == rb.subtype
|
|
&& ra.payload_json == rb.payload_json
|
|
});
|
|
stats.filings_duplicate_collapsed = filings_before_dedup - rows.len();
|
|
stats.filings_out = rows.len();
|
|
|
|
// Scan and resolve earnings rows against qualifying links or 16:05 ET fallback.
|
|
let earnings_iter = earnings.into_iter();
|
|
let (earnings_lower, _) = earnings_iter.size_hint();
|
|
let mut norm_earnings: Vec<NormalizedEarning<K>> = Vec::with_capacity(earnings_lower);
|
|
|
|
for earning in earnings_iter {
|
|
stats.earnings_in += 1;
|
|
|
|
let link_lookup = links.binary_search_by(|l| {
|
|
l.key
|
|
.cmp(&earning.key)
|
|
.then_with(|| l.et_date.cmp(&earning.report_date))
|
|
});
|
|
|
|
let (ts_micros, known_at_source, is_linked, link_idx) = match link_lookup {
|
|
Ok(idx) => (
|
|
links[idx].utc_micros,
|
|
KNOWN_AT_SOURCE_FILING_TIMESTAMP,
|
|
true,
|
|
Some(idx),
|
|
),
|
|
Err(_) => match et_to_utc_micros(
|
|
earning.report_date,
|
|
EARNINGS_FALLBACK_HOUR_ET,
|
|
EARNINGS_FALLBACK_MINUTE_ET,
|
|
0,
|
|
) {
|
|
Ok(utc) => (utc, KNOWN_AT_SOURCE_STATUTORY_LAG, false, None),
|
|
Err(_) => {
|
|
stats.earnings_skipped_out_of_range += 1;
|
|
continue;
|
|
}
|
|
},
|
|
};
|
|
|
|
norm_earnings.push(NormalizedEarning {
|
|
key: earning.key,
|
|
report_date: earning.report_date,
|
|
ts_micros,
|
|
known_at_source,
|
|
is_linked,
|
|
link_idx,
|
|
subtype: normalize_announce_time(&earning.announce_time),
|
|
fiscal_period_end: earning.fiscal_period_end,
|
|
actual_eps: sanitize_opt_f64(earning.actual_eps),
|
|
revenue: sanitize_opt_f64(earning.revenue),
|
|
});
|
|
}
|
|
|
|
norm_earnings.sort_unstable_by(|a, b| {
|
|
a.key
|
|
.cmp(&b.key)
|
|
.then_with(|| a.report_date.cmp(&b.report_date))
|
|
});
|
|
|
|
// Reserve only the exact upper bound for earnings rows so appending a small earnings batch
|
|
// onto a multi-million-row filings vector does not double the vector's capacity.
|
|
rows.reserve_exact(norm_earnings.len());
|
|
let len = norm_earnings.len();
|
|
let mut read_idx = 0usize;
|
|
while read_idx < len {
|
|
let mut group_end = read_idx + 1;
|
|
while group_end < len
|
|
&& norm_earnings[group_end].key == norm_earnings[read_idx].key
|
|
&& norm_earnings[group_end].report_date == norm_earnings[read_idx].report_date
|
|
{
|
|
group_end += 1;
|
|
}
|
|
|
|
let group_len = group_end - read_idx;
|
|
let first = &norm_earnings[read_idx];
|
|
let all_identical = norm_earnings[read_idx + 1..group_end]
|
|
.iter()
|
|
.all(|other| first.values_bit_eq(other));
|
|
|
|
if all_identical {
|
|
stats.earnings_duplicate_collapsed += group_len - 1;
|
|
if first.is_linked {
|
|
stats.earnings_linked_to_filing += 1;
|
|
} else {
|
|
stats.earnings_lagged_1605 += 1;
|
|
}
|
|
|
|
let linked_filing_id = first
|
|
.link_idx
|
|
.and_then(|idx| links[idx].filing_id.as_deref());
|
|
let payload_json = encode_earnings_payload_json(
|
|
first.actual_eps,
|
|
first.subtype,
|
|
first.fiscal_period_end,
|
|
linked_filing_id,
|
|
first.report_date,
|
|
first.revenue,
|
|
);
|
|
rows.push(R::from_parts(
|
|
EventRow {
|
|
key: first.key.clone(),
|
|
ts_micros: first.ts_micros,
|
|
known_at_micros: first.ts_micros,
|
|
known_at_source: first.known_at_source,
|
|
kind: EVENT_KIND_EARNINGS,
|
|
subtype: first.subtype.to_string(),
|
|
payload_json,
|
|
},
|
|
first.report_date,
|
|
));
|
|
} else {
|
|
stats.earnings_duplicate_conflict_dropped += group_len;
|
|
}
|
|
|
|
read_idx = group_end;
|
|
}
|
|
|
|
stats.earnings_out = stats.earnings_linked_to_filing + stats.earnings_lagged_1605;
|
|
|
|
rows.sort_unstable_by(|a, b| {
|
|
let ra = a.event_row();
|
|
let rb = b.event_row();
|
|
ra.key
|
|
.cmp(&rb.key)
|
|
.then_with(|| ra.ts_micros.cmp(&rb.ts_micros))
|
|
.then_with(|| ra.kind.cmp(rb.kind))
|
|
.then_with(|| ra.subtype.cmp(&rb.subtype))
|
|
.then_with(|| ra.payload_json.cmp(&rb.payload_json))
|
|
.then_with(|| ra.known_at_micros.cmp(&rb.known_at_micros))
|
|
.then_with(|| ra.known_at_source.cmp(rb.known_at_source))
|
|
.then_with(|| a.event_date_tiebreak().cmp(&b.event_date_tiebreak()))
|
|
});
|
|
|
|
stats.rows_out = rows.len();
|
|
let mut keys_out = 0usize;
|
|
let mut prev_key: Option<&K> = None;
|
|
for item in &rows {
|
|
let row = item.event_row();
|
|
if prev_key != Some(&row.key) {
|
|
keys_out += 1;
|
|
prev_key = Some(&row.key);
|
|
}
|
|
}
|
|
stats.keys_out = keys_out;
|
|
|
|
(rows, stats)
|
|
}
|
|
|
|
/// Crate-internal entry point returning each [`EventRow`] alongside its exact Eastern local
|
|
/// calendar date (`ParsedFilingTime::et_date` for filings, `QmEarning::report_date` for earnings).
|
|
pub(crate) fn build_events_with_dates<K, IF, IE>(
|
|
filings: IF,
|
|
earnings: IE,
|
|
) -> (Vec<EventRowWithDate<K>>, EventsStats)
|
|
where
|
|
K: Ord + Clone,
|
|
IF: IntoIterator<Item = QmFiling<K>>,
|
|
IE: IntoIterator<Item = QmEarning<K>>,
|
|
{
|
|
build_events_impl(filings, earnings)
|
|
}
|
|
|
|
/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and
|
|
/// `qmEarnings` streams.
|
|
///
|
|
/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range
|
|
/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking.
|
|
/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`.
|
|
pub fn build_events<K, IF, IE>(filings: IF, earnings: IE) -> EventsBuild<K>
|
|
where
|
|
K: Ord + Clone,
|
|
IF: IntoIterator<Item = QmFiling<K>>,
|
|
IE: IntoIterator<Item = QmEarning<K>>,
|
|
{
|
|
let (rows, stats) = build_events_impl(filings, earnings);
|
|
EventsBuild { rows, 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 assert_invariants<K: Ord>(build: &EventsBuild<K>) {
|
|
let s = &build.stats;
|
|
assert_eq!(
|
|
s.filings_in,
|
|
s.filings_out
|
|
+ s.filings_skipped_malformed_timestamp
|
|
+ s.filings_skipped_unknown_zone
|
|
+ s.filings_skipped_invalid_date_time
|
|
+ s.filings_duplicate_collapsed,
|
|
"filing accounting mismatch: {s:?}"
|
|
);
|
|
assert_eq!(
|
|
s.earnings_in,
|
|
s.earnings_out
|
|
+ s.earnings_skipped_out_of_range
|
|
+ s.earnings_duplicate_collapsed
|
|
+ s.earnings_duplicate_conflict_dropped,
|
|
"earnings accounting mismatch: {s:?}"
|
|
);
|
|
assert_eq!(
|
|
s.earnings_out,
|
|
s.earnings_linked_to_filing + s.earnings_lagged_1605
|
|
);
|
|
assert_eq!(s.rows_out, s.filings_out + s.earnings_out);
|
|
assert_eq!(s.rows_out, build.rows.len());
|
|
|
|
for pair in build.rows.windows(2) {
|
|
assert!(
|
|
(
|
|
&pair[0].key,
|
|
pair[0].ts_micros,
|
|
pair[0].kind,
|
|
&pair[0].subtype,
|
|
&pair[0].payload_json
|
|
) <= (
|
|
&pair[1].key,
|
|
pair[1].ts_micros,
|
|
pair[1].kind,
|
|
&pair[1].subtype,
|
|
&pair[1].payload_json
|
|
),
|
|
"rows must be deterministically sorted"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_filing_timefiled_converts_est_edt_leap_and_pre_2008_exact_to_microsecond() {
|
|
let est = parse_filing_timefiled("2025-01-31T06:01:27 EST").unwrap();
|
|
assert_eq!(est.utc_micros, utc_micros(2025, 1, 31, 11, 1, 27));
|
|
assert_eq!(est.et_date, day(2025, 1, 31));
|
|
|
|
let edt = parse_filing_timefiled("2025-07-15T16:30:45 EDT").unwrap();
|
|
assert_eq!(edt.utc_micros, utc_micros(2025, 7, 15, 20, 30, 45));
|
|
assert_eq!(edt.et_date, day(2025, 7, 15));
|
|
|
|
let pre_2008 = parse_filing_timefiled("2003-07-15T14:30:00 EDT").unwrap();
|
|
assert_eq!(pre_2008.utc_micros, utc_micros(2003, 7, 15, 18, 30, 0));
|
|
assert_eq!(pre_2008.et_date, day(2003, 7, 15));
|
|
|
|
let leap = parse_filing_timefiled("2024-02-29T23:45:10 EST").unwrap();
|
|
assert_eq!(leap.utc_micros, utc_micros(2024, 3, 1, 4, 45, 10));
|
|
assert_eq!(leap.et_date, day(2024, 2, 29));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_filing_timefiled_rejects_malformed_unknown_zone_and_invalid_dates_times() {
|
|
for bad in [
|
|
"",
|
|
"2025-01-31 06:01:27 EST",
|
|
"2025/01/31T06:01:27 EST",
|
|
"2025-1-31T06:01:27 EST",
|
|
"not-a-timestamp",
|
|
] {
|
|
assert_eq!(
|
|
parse_filing_timefiled(bad),
|
|
Err(FilingTimeError::MalformedFormat),
|
|
"expected MalformedFormat for {bad:?}"
|
|
);
|
|
}
|
|
|
|
for bad_zone in [
|
|
"2025-01-31T06:01:27",
|
|
"2025-01-31T06:01:27 PST",
|
|
"2025-01-31T06:01:27 UTC",
|
|
"2025-01-31T06:01:27Z",
|
|
"2025-01-31T06:01:27 est",
|
|
"2025-01-31T06:01:27 EST ",
|
|
] {
|
|
assert_eq!(
|
|
parse_filing_timefiled(bad_zone),
|
|
Err(FilingTimeError::UnknownZone),
|
|
"expected UnknownZone for {bad_zone:?}"
|
|
);
|
|
}
|
|
|
|
for bad_date in [
|
|
"2025-02-30T06:01:27 EST",
|
|
"2025-02-29T06:01:27 EST",
|
|
"2025-13-01T06:01:27 EST",
|
|
"2025-00-10T06:01:27 EST",
|
|
] {
|
|
assert_eq!(
|
|
parse_filing_timefiled(bad_date),
|
|
Err(FilingTimeError::InvalidDate),
|
|
"expected InvalidDate for {bad_date:?}"
|
|
);
|
|
}
|
|
|
|
for bad_time in [
|
|
"2025-01-31T24:00:00 EST",
|
|
"2025-01-31T25:00:00 EST",
|
|
"2025-01-31T12:60:00 EST",
|
|
"2025-01-31T12:00:60 EST",
|
|
] {
|
|
assert_eq!(
|
|
parse_filing_timefiled(bad_time),
|
|
Err(FilingTimeError::InvalidTime),
|
|
"expected InvalidTime for {bad_time:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn classify_form_type_covers_all_edgar_sedar_amendments_and_negative_cases() {
|
|
let cases = [
|
|
("10-K", FilingFormGroup::Form10K, false, true, false),
|
|
("10-K/A", FilingFormGroup::Form10K, true, true, false),
|
|
("10-K (Amended)", FilingFormGroup::Form10K, true, true, false),
|
|
("10-K/A (Amended)", FilingFormGroup::Form10K, true, true, false),
|
|
(" 10-q ", FilingFormGroup::Form10Q, false, true, false),
|
|
("10-Q/A", FilingFormGroup::Form10Q, true, true, false),
|
|
("10-Q - Amended", FilingFormGroup::Form10Q, true, true, false),
|
|
("8-K", FilingFormGroup::Form8K, false, false, true),
|
|
("8-K/A", FilingFormGroup::Form8K, true, false, true),
|
|
("8-K (Amended)", FilingFormGroup::Form8K, true, false, true),
|
|
("4", FilingFormGroup::Form4, false, false, false),
|
|
("4/A", FilingFormGroup::Form4, true, false, false),
|
|
("144", FilingFormGroup::Form144, false, false, false),
|
|
("40-F", FilingFormGroup::Form40F, false, true, false),
|
|
("40-F/A", FilingFormGroup::Form40F, true, true, false),
|
|
("Amended 40-F", FilingFormGroup::Form40F, true, true, false),
|
|
("UNAMENDED", FilingFormGroup::Other, false, false, false),
|
|
(
|
|
"Interim financial statements/report",
|
|
FilingFormGroup::InterimFinancials,
|
|
false,
|
|
true,
|
|
false,
|
|
),
|
|
(
|
|
"Amended interim financial statements/report",
|
|
FilingFormGroup::InterimFinancials,
|
|
true,
|
|
true,
|
|
false,
|
|
),
|
|
(
|
|
"Annual financial statements",
|
|
FilingFormGroup::AnnualFinancials,
|
|
false,
|
|
true,
|
|
false,
|
|
),
|
|
("MD&A", FilingFormGroup::Mda, false, false, false),
|
|
("52-109", FilingFormGroup::Form52109, false, false, false),
|
|
("NI 43-101", FilingFormGroup::Ni43101, false, false, false),
|
|
("45-106F1", FilingFormGroup::Form45106F1, false, false, false),
|
|
(
|
|
"News release",
|
|
FilingFormGroup::NewsRelease,
|
|
false,
|
|
false,
|
|
true,
|
|
),
|
|
("424B5", FilingFormGroup::Other, false, false, false),
|
|
("S-3", FilingFormGroup::Other, false, false, false),
|
|
("DEF 14A", FilingFormGroup::Other, false, false, false),
|
|
("", FilingFormGroup::Other, false, false, false),
|
|
];
|
|
|
|
for (raw, expected_group, expected_amend, expected_periodic, expected_link) in cases {
|
|
let (group, is_amend) = classify_form_type(raw);
|
|
assert_eq!(group, expected_group, "group mismatch for {raw:?}");
|
|
assert_eq!(is_amend, expected_amend, "amendment mismatch for {raw:?}");
|
|
assert_eq!(
|
|
group.is_periodic_financial_report(),
|
|
expected_periodic,
|
|
"periodic mismatch for {raw:?}"
|
|
);
|
|
assert_eq!(
|
|
is_periodic_financial_report(raw),
|
|
expected_periodic,
|
|
"free predicate mismatch for {raw:?}"
|
|
);
|
|
assert_eq!(
|
|
group.is_earnings_link_candidate(),
|
|
expected_link,
|
|
"link candidate mismatch for {raw:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn json_encoding_escapes_special_chars_and_handles_non_finite_numbers() {
|
|
let filing_json = encode_filing_payload_json(
|
|
Some("acc-\"1\"\\x\n\t\x00\x1f"),
|
|
"10-K/A",
|
|
true,
|
|
Some("https://example.com/café"),
|
|
);
|
|
assert_eq!(
|
|
filing_json,
|
|
"{\"filing_id\":\"acc-\\\"1\\\"\\\\x\\n\\t\\u0000\\u001f\",\"form_type\":\"10-K/A\",\"is_amendment\":true,\"url\":\"https://example.com/café\"}"
|
|
);
|
|
|
|
let earnings_json = encode_earnings_payload_json(
|
|
Some(f64::NAN),
|
|
"unknown",
|
|
Some(day(2024, 12, 31)),
|
|
None,
|
|
day(2025, 1, 31),
|
|
Some(-0.0),
|
|
);
|
|
assert_eq!(
|
|
earnings_json,
|
|
"{\"actual_eps\":null,\"announce_time\":\"unknown\",\"fiscal_period_end\":\"2024-12-31\",\"linked_filing_id\":null,\"report_date\":\"2025-01-31\",\"revenue\":0}"
|
|
);
|
|
assert!(!earnings_json.contains("consensusEps"));
|
|
assert!(!earnings_json.contains("consensus_eps"));
|
|
}
|
|
|
|
#[test]
|
|
fn partition_year_utc_tracks_utc_year_across_year_end_et_rollover() {
|
|
let late_dec31 = parse_filing_timefiled("2024-12-31T21:30:00 EST").unwrap();
|
|
assert_eq!(late_dec31.et_date, day(2024, 12, 31));
|
|
assert_eq!(partition_year_utc(late_dec31.utc_micros), 2025);
|
|
|
|
let mid_dec31 = parse_filing_timefiled("2024-12-31T16:00:00 EST").unwrap();
|
|
assert_eq!(partition_year_utc(mid_dec31.utc_micros), 2024);
|
|
}
|
|
|
|
#[test]
|
|
fn build_events_empty_and_basic_reconciliation() {
|
|
let empty = build_events::<i32, _, _>(Vec::new(), Vec::new());
|
|
assert!(empty.rows.is_empty());
|
|
assert_eq!(empty.stats, EventsStats::default());
|
|
assert_invariants(&empty);
|
|
}
|
|
}
|