mod baseline;
mod error;
mod ranges;
pub use baseline::NormalWeekBaseline;
pub use error::CalendarQueryError;
pub use ranges::{CompleteRanges, CoverageGaps};
use chrono::NaiveDate;
use super::exchange_calendar::CalendarSource;
use super::schedules::holidays::{self, HolidayCoverage, HolidayKind, HolidayTable, HolidayWindow};
use super::schedules::sourcing;
use super::schedules::timeline::effective_date;
pub const SUPPORT_FLOOR: NaiveDate = effective_date(2010, 1, 1);
const RESOLUTION_WALK_BOUND: u32 = 400;
const RESOLUTION_FAST_RADIUS: u32 = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DateRange {
first: NaiveDate,
last: NaiveDate,
}
impl DateRange {
#[must_use]
pub fn new(first: NaiveDate, last: NaiveDate) -> Option<Self> {
(first <= last).then_some(Self { first, last })
}
#[must_use]
pub const fn first(self) -> NaiveDate {
self.first
}
#[must_use]
pub const fn last(self) -> NaiveDate {
self.last
}
#[must_use]
pub fn contains(self, date: NaiveDate) -> bool {
self.first <= date && date <= self.last
}
#[must_use]
pub fn is_open_ended(self) -> bool {
self.last == NaiveDate::MAX
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DateCoverage {
Covered,
BeforeSupportFloor,
OutsideCoveredRange,
UnresolvedGap,
NormalWeekOnly,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CoverageGapReason {
NormalWeekCarried,
NoHolidayTable,
NoHolidayCoverage,
WithheldDate,
NormalWeekOnly,
HolidayWindowsBridged,
NormalWeekPhaseWithheld,
SpecialSessionUnrepresentable,
PostCloseQueueTradeDateLabel,
UnpublishedClosureDates,
ResolutionEdge,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PhaseGapShape {
EveryDay,
OrderEntryWindow {
open_ssm: Option<u32>,
close_ssm: u32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PhaseGap {
reason: CoverageGapReason,
closing_condition: &'static str,
since: Option<NaiveDate>,
until: Option<NaiveDate>,
shape: PhaseGapShape,
}
impl PhaseGap {
#[must_use]
pub const fn new(reason: CoverageGapReason, closing_condition: &'static str) -> Self {
Self {
reason,
closing_condition,
since: None,
until: None,
shape: PhaseGapShape::EveryDay,
}
}
#[must_use]
pub const fn since(self, since: NaiveDate) -> Self {
Self {
since: Some(since),
..self
}
}
#[must_use]
pub const fn until(self, until: NaiveDate) -> Self {
Self {
until: Some(until),
..self
}
}
#[must_use]
pub const fn with_shape(self, shape: PhaseGapShape) -> Self {
Self { shape, ..self }
}
#[must_use]
pub const fn reason(self) -> CoverageGapReason {
self.reason
}
#[must_use]
pub const fn closing_condition(self) -> &'static str {
self.closing_condition
}
#[must_use]
pub const fn applies_since(self) -> Option<NaiveDate> {
self.since
}
#[must_use]
pub const fn applies_until(self) -> Option<NaiveDate> {
self.until
}
#[must_use]
pub const fn shape(self) -> PhaseGapShape {
self.shape
}
#[must_use]
pub fn applies_on(self, date: NaiveDate) -> bool {
self.since.is_none_or(|since| date >= since) && self.until.is_none_or(|until| date < until)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CoverageGap {
range: DateRange,
reason: CoverageGapReason,
phase_gap: Option<PhaseGap>,
}
impl CoverageGap {
#[must_use]
pub const fn range(self) -> DateRange {
self.range
}
#[must_use]
pub const fn reason(self) -> CoverageGapReason {
self.reason
}
#[must_use]
pub const fn phase_gap(self) -> Option<PhaseGap> {
self.phase_gap
}
#[must_use]
pub const fn closing_condition(self) -> Option<&'static str> {
match self.phase_gap {
Some(phase_gap) => Some(phase_gap.closing_condition()),
None => None,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HolidayContract {
NoTable,
NoHolidays,
NormalWeekOnly,
Audited {
coverage: HolidayCoverage,
rows: usize,
},
}
impl HolidayContract {
#[must_use]
pub const fn coverage(self) -> Option<HolidayCoverage> {
match self {
Self::Audited { coverage, .. } => Some(coverage),
_ => None,
}
}
#[must_use]
pub const fn rows(self) -> Option<usize> {
match self {
Self::Audited { rows, .. } => Some(rows),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BridgeSpanKind {
TwoFlank,
OneFlankBelow,
}
#[derive(Clone, Copy)]
pub struct CalendarCoverage {
source: CalendarSource,
carried_below: Option<NaiveDate>,
phase_gaps: &'static [PhaseGap],
holidays: HolidayContract,
table: Option<&'static HolidayTable>,
shipped: Option<&'static HolidayTable>,
}
impl CalendarCoverage {
pub(crate) const fn new(source: CalendarSource, holidays_attached: bool) -> Self {
let declared = sourcing::declared(source);
let shipped = holidays::table_for(source);
let holidays = match shipped {
Some(table) if holidays_attached => HolidayContract::Audited {
coverage: table.coverage(),
rows: table.rows.len(),
},
Some(_) => HolidayContract::NormalWeekOnly,
None if declared.observes_no_holidays => HolidayContract::NoHolidays,
None => HolidayContract::NoTable,
};
Self {
source,
carried_below: declared.carried_below,
phase_gaps: declared.phase_gaps,
holidays,
table: if holidays_attached { shipped } else { None },
shipped,
}
}
#[must_use]
pub const fn identity(self) -> CalendarSource {
self.source
}
#[must_use]
pub const fn normal_week_sourced_from(self) -> Option<NaiveDate> {
self.carried_below
}
#[must_use]
pub fn sourced_normal_week(self) -> DateRange {
let first = match self.carried_below {
Some(carried_below) if carried_below > SUPPORT_FLOOR => carried_below,
_ => SUPPORT_FLOOR,
};
DateRange {
first,
last: NaiveDate::MAX,
}
}
#[must_use]
pub const fn holiday_contract(self) -> HolidayContract {
self.holidays
}
#[must_use]
pub const fn phase_gaps(self) -> &'static [PhaseGap] {
self.phase_gaps
}
#[must_use]
pub fn phase_gap_on(self, date: NaiveDate) -> Option<PhaseGap> {
if !self.identity_answers(date) {
return None;
}
self.phase_gaps
.iter()
.copied()
.find(|gap| gap.applies_on(date) && self.shape_resolves(*gap, date))
}
fn identity_answers(self, date: NaiveDate) -> bool {
if self.holidays != HolidayContract::NormalWeekOnly {
return self.date_level_gap_on(date).is_none();
}
if date < SUPPORT_FLOOR {
return true;
}
if self.carried_below.is_some_and(|carried| date < carried) {
return false;
}
match self.shipped {
None => false,
Some(table) => {
!Self::withholds_shipped(table, date) && table.coverage().contains(date)
|| Self::bridge_span_kind(self.windows(), self.carried_below, date).is_some()
}
}
}
fn withholds_shipped(table: &'static HolidayTable, date: NaiveDate) -> bool {
table
.holiday_on(date)
.is_some_and(|holiday| holiday.kind() == HolidayKind::Unsourced)
}
pub(in crate::calendar) fn has_unscoped_refusing_phase_gap_on(self, date: NaiveDate) -> bool {
self.phase_gaps.iter().copied().any(|gap| {
gap.applies_on(date)
&& gap.shape() == PhaseGapShape::EveryDay
&& !matches!(
gap.reason(),
CoverageGapReason::PostCloseQueueTradeDateLabel
| CoverageGapReason::UnpublishedClosureDates
)
})
}
fn shape_resolves(self, gap: PhaseGap, date: NaiveDate) -> bool {
match gap.shape() {
PhaseGapShape::EveryDay => true,
PhaseGapShape::OrderEntryWindow {
open_ssm,
close_ssm,
} => crate::calendar::query::schedule::builtin_resolves_order_entry(
self.source,
date,
open_ssm,
close_ssm,
),
}
}
pub(super) fn has_date_scoped_shapes_between(self, first: NaiveDate, last: NaiveDate) -> bool {
let Some(table) = self.shipped else {
return false;
};
if last == NaiveDate::MAX {
return false;
}
let answered_through = table.windows.iter().map(|window| window.last()).max();
let Some(answered_through) = answered_through else {
return false;
};
last <= answered_through
&& self.phase_gaps.iter().any(|gap| {
matches!(gap.shape, PhaseGapShape::OrderEntryWindow { .. })
&& gap.applies_on(first)
&& gap.applies_on(last)
})
}
#[must_use]
pub fn coverage_on(self, date: NaiveDate) -> DateCoverage {
if date < SUPPORT_FLOOR {
return DateCoverage::BeforeSupportFloor;
}
match self.gap_reason_on(date) {
None => DateCoverage::Covered,
Some(CoverageGapReason::WithheldDate) => DateCoverage::UnresolvedGap,
Some(CoverageGapReason::NormalWeekOnly) => DateCoverage::NormalWeekOnly,
Some(
CoverageGapReason::NormalWeekCarried
| CoverageGapReason::NoHolidayTable
| CoverageGapReason::NoHolidayCoverage
| CoverageGapReason::HolidayWindowsBridged
| CoverageGapReason::NormalWeekPhaseWithheld
| CoverageGapReason::SpecialSessionUnrepresentable
| CoverageGapReason::PostCloseQueueTradeDateLabel
| CoverageGapReason::UnpublishedClosureDates
| CoverageGapReason::ResolutionEdge,
) => DateCoverage::OutsideCoveredRange,
}
}
#[must_use]
pub fn is_complete_on(self, date: NaiveDate) -> bool {
self.coverage_on(date) == DateCoverage::Covered
}
#[must_use]
pub fn complete_ranges(self) -> CompleteRanges {
CompleteRanges::new(self)
}
#[must_use]
pub fn gaps(self) -> CoverageGaps {
CoverageGaps::new(self)
}
pub(super) fn gap_reason_on(self, date: NaiveDate) -> Option<CoverageGapReason> {
if date < SUPPORT_FLOOR {
return None;
}
if let Some(phase_gap) = self.phase_gap_on(date) {
return Some(phase_gap.reason());
}
if let Some(reason) = self.date_level_gap_on(date) {
return Some(reason);
}
if Self::bridge_span_kind(self.windows(), self.carried_below, date).is_some() {
return Some(CoverageGapReason::HolidayWindowsBridged);
}
if !self.resolution_reach_answerable(date) {
return Some(CoverageGapReason::ResolutionEdge);
}
None
}
fn surviving_session_day(self, day: NaiveDate) -> bool {
if !crate::calendar::query::schedule::builtin_has_tradeable_rule(self.source, day) {
return false;
}
match self.shipped.and_then(|table| table.holiday_on(day)) {
Some(holiday) => !matches!(
holiday.kind(),
HolidayKind::Closed | HolidayKind::ReplacementBlocks(_)
),
None => true,
}
}
fn resolution_reach_answerable(self, date: NaiveDate) -> bool {
if !self.unanswerable_within(date, Some(RESOLUTION_FAST_RADIUS)) {
return true;
}
let mut day = date;
let mut steps: u32 = 0;
loop {
if self.surviving_session_day(day) {
match day.pred_opt() {
Some(prev) if self.identity_answers(prev) => break,
Some(_) => return false,
None => break,
}
}
match day.pred_opt() {
Some(prev) if self.identity_answers(prev) => day = prev,
Some(_) => return false,
None => break,
}
steps += 1;
if steps > RESOLUTION_WALK_BOUND {
return false;
}
}
let mut day = date;
let mut steps: u32 = 0;
loop {
if self.surviving_session_day(day) {
match day.succ_opt() {
Some(next) if self.identity_answers(next) => break,
Some(_) => return false,
None => break,
}
}
match day.succ_opt() {
Some(next) if self.identity_answers(next) => day = next,
Some(_) => return false,
None => break,
}
steps += 1;
if steps > RESOLUTION_WALK_BOUND {
return false;
}
}
true
}
fn unanswerable_within(self, date: NaiveDate, bound: Option<u32>) -> bool {
let within = |candidate: Option<NaiveDate>| {
candidate.is_some_and(|candidate| {
bound.is_none_or(|bound| {
candidate.signed_duration_since(date).num_days().abs() <= i64::from(bound)
})
})
};
if within(self.carried_below) {
return true;
}
for window in self.windows() {
if within(window.first().pred_opt()) {
return true;
}
if within(window.last().succ_opt()) {
return true;
}
}
if let Some(table) = self.table {
let index = table.rows.partition_point(|row| row.trade_date < date);
let mut back = index;
while back > 0 {
let row = &table.rows[back - 1];
let days = date.signed_duration_since(row.trade_date).num_days();
if days > i64::from(RESOLUTION_FAST_RADIUS) {
break;
}
if row.kind == HolidayKind::Unsourced {
return true;
}
back -= 1;
}
for row in &table.rows[index..] {
let days = row.trade_date.signed_duration_since(date).num_days();
if days > i64::from(RESOLUTION_FAST_RADIUS) {
break;
}
if row.kind == HolidayKind::Unsourced {
return true;
}
}
}
false
}
pub(super) fn date_level_gap_on(self, date: NaiveDate) -> Option<CoverageGapReason> {
if date < SUPPORT_FLOOR {
return None;
}
if let Some(carried_below) = self.carried_below
&& date < carried_below
{
return Some(CoverageGapReason::NormalWeekCarried);
}
match self.holidays {
HolidayContract::NormalWeekOnly => Some(CoverageGapReason::NormalWeekOnly),
HolidayContract::NoHolidays => None,
HolidayContract::NoTable => Some(CoverageGapReason::NoHolidayTable),
HolidayContract::Audited { coverage, .. } => {
if self.withholds(date) {
Some(CoverageGapReason::WithheldDate)
} else if coverage.contains(date) {
None
} else if Self::bridge_span_kind(self.windows(), self.carried_below, date).is_some()
{
None
} else {
Some(CoverageGapReason::NoHolidayCoverage)
}
}
}
}
fn withholds(self, date: NaiveDate) -> bool {
self.table.is_some_and(|table| {
table
.holiday_on(date)
.is_some_and(|holiday| holiday.kind() == HolidayKind::Unsourced)
})
}
fn bridge_span_kind(
windows: &'static [HolidayWindow],
carried_below: Option<NaiveDate>,
date: NaiveDate,
) -> Option<BridgeSpanKind> {
let mut lower_last: Option<NaiveDate> = None;
let mut upper_first: Option<NaiveDate> = None;
for window in windows {
if window.contains(date) {
return None;
}
if window.last() < date {
lower_last = Some(match lower_last {
Some(current) if current > window.last() => current,
_ => window.last(),
});
}
if window.first() > date {
upper_first = Some(match upper_first {
Some(current) if current < window.first() => current,
_ => window.first(),
});
}
}
let kind = match (lower_last, upper_first) {
(Some(_), Some(_)) => BridgeSpanKind::TwoFlank,
(None, Some(_)) => BridgeSpanKind::OneFlankBelow,
(_, None) => return None,
};
carried_below
.is_none_or(|carried| date >= carried)
.then_some(kind)
}
pub(in crate::calendar) fn holiday_classification_refused_on(self, date: NaiveDate) -> bool {
date >= SUPPORT_FLOOR
&& matches!(self.holidays, HolidayContract::Audited { .. })
&& Self::bridge_span_kind(self.windows(), self.carried_below, date)
== Some(BridgeSpanKind::OneFlankBelow)
}
fn next_boundary_after(self, date: NaiveDate) -> Option<NaiveDate> {
let mut best: Option<NaiveDate> = None;
let mut consider = |candidate: Option<NaiveDate>| {
best = [best, candidate].into_iter().flatten().min();
};
consider((SUPPORT_FLOOR > date).then_some(SUPPORT_FLOOR));
consider(self.carried_below.filter(|boundary| *boundary > date));
for gap in self.phase_gaps {
for bound in [gap.applies_since(), gap.applies_until()] {
consider(bound.filter(|bound| *bound > date));
consider(
bound
.and_then(|bound| bound.pred_opt())
.filter(|last| *last > date),
);
}
}
for window in self.windows() {
consider(Some(window.first()).filter(|first| *first > date));
consider(window.last().succ_opt().filter(|after| *after > date));
}
if let Some(table) = self.table {
for row in table.rows {
if row.kind == HolidayKind::Unsourced && row.trade_date >= SUPPORT_FLOOR {
consider(Some(row.trade_date).filter(|withheld| *withheld > date));
consider(row.trade_date.succ_opt().filter(|after| *after > date));
}
}
}
if self.holidays == HolidayContract::NormalWeekOnly {
return best;
}
if let Some(carried_below) = self.carried_below
&& let Some(before) = carried_below.pred_opt()
{
for edge in self.resolution_zone_edges(before) {
consider(edge.filter(|edge| *edge > date));
}
}
for window in self.windows() {
if let Some(before) = window.first().pred_opt() {
for edge in self.resolution_zone_edges(before) {
consider(edge.filter(|edge| *edge > date));
}
}
if let Some(after) = window.last().succ_opt() {
for edge in self.resolution_zone_edges(after) {
consider(edge.filter(|edge| *edge > date));
}
}
}
if let Some(table) = self.table {
let first_relevant = table.rows.partition_point(|row| {
row.trade_date
.checked_add_signed(chrono::Duration::days(
i64::from(RESOLUTION_WALK_BOUND) + 2,
))
.is_some_and(|limit| limit <= date)
});
for row in &table.rows[first_relevant..] {
if row.kind == HolidayKind::Unsourced {
for edge in self.resolution_zone_edges(row.trade_date) {
consider(edge.filter(|edge| *edge > date));
}
}
}
}
best
}
fn resolution_zone_edges(self, x: NaiveDate) -> [Option<NaiveDate>; 2] {
let mut below = x.pred_opt().and_then(|first| first.pred_opt());
if let Some(start) = below {
let mut day = start;
let mut steps = 0;
loop {
if !self.identity_answers(day) || self.surviving_session_day(day) {
break;
}
match day.pred_opt() {
Some(prev) => day = prev,
None => break,
}
steps += 1;
if steps > RESOLUTION_WALK_BOUND {
break;
}
}
below = day.succ_opt();
}
let below = below.filter(|edge| self.identity_answers(*edge));
let mut above = None;
if let Some(start) = x.succ_opt().and_then(|first| first.succ_opt()) {
let mut day = start;
let mut steps = 0;
loop {
if !self.identity_answers(day) || self.surviving_session_day(day) {
break;
}
match day.succ_opt() {
Some(next) => day = next,
None => return [below, None],
}
steps += 1;
if steps > RESOLUTION_WALK_BOUND {
return [below, None];
}
}
above = Some(day);
}
let above = above.filter(|edge| self.identity_answers(*edge));
[below, above]
}
fn windows(self) -> &'static [HolidayWindow] {
self.shipped.map_or(&[], |table| table.windows)
}
pub(super) fn run_end(self, first: NaiveDate) -> NaiveDate {
match self
.next_boundary_after(first)
.and_then(|boundary| boundary.pred_opt())
{
Some(last) => last,
None => NaiveDate::MAX,
}
}
}
impl core::fmt::Debug for CalendarCoverage {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CalendarCoverage")
.field("identity", &self.source)
.field("support_floor", &SUPPORT_FLOOR)
.field("normal_week_sourced_from", &self.carried_below)
.field("phase_gaps", &self.phase_gaps)
.field("holidays", &self.holidays)
.finish_non_exhaustive()
}
}
impl PartialEq for CalendarCoverage {
fn eq(&self, other: &Self) -> bool {
self.source == other.source
&& self.carried_below == other.carried_below
&& self.phase_gaps == other.phase_gaps
&& self.holidays == other.holidays
}
}
impl Eq for CalendarCoverage {}
const fn gap_of(range: DateRange, reason: CoverageGapReason) -> CoverageGap {
CoverageGap {
range,
reason,
phase_gap: None,
}
}