1099 lines
39 KiB
Rust
1099 lines
39 KiB
Rust
//! Pure, in-memory `adj_factors` builder (`qmSplits` + `qmDividends` -> per-ex-date factors).
|
|
//!
|
|
//! Produces sorted per-`(key, ex_date)` rows matching the `adj_factors/part.parquet` schema
|
|
//! columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, split_factor, div_cash,
|
|
//! div_currency, cum_split_factor, cum_total_factor`):
|
|
//! - Splits use the same sign convention as [`crate::split`]: `ratio = new_shares / old_shares`
|
|
//! (`10.0` for a 10:1 forward split, `0.05` for a 1:20 reverse split).
|
|
//! - `cum_split_factor` is the cumulative product of `split_factor` over this row and all later
|
|
//! rows of the same key (inclusive of the row's own `ex_date`), so for any bar dated `d`, the
|
|
//! first row with `ex_date > d` equals [`crate::split::SplitTable::cum_factor_after`].
|
|
//! - Per-row dividend factor is `prev_close / (prev_close - div_cash)` when `prev_close` is
|
|
//! present, finite, `> div_cash > 0.0`, and matches `div_currency`; otherwise `1.0` with the
|
|
//! fallback reason counted in [`AdjBuildStats`].
|
|
//! - `cum_total_factor = cum_split_factor * suffix_product(div_factor)`.
|
|
|
|
use std::cmp::Ordering;
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
|
|
use crate::split::SplitEvent;
|
|
|
|
/// A single cash dividend event.
|
|
///
|
|
/// Deliberately omits `usdFxRate` (contract: ignore `qmDividends.usdFxRate`).
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct DividendEvent {
|
|
/// Ex-dividend date as days since 1970-01-01 (UTC Gregorian).
|
|
pub ex_date: i32,
|
|
/// Cash dividend amount per share (must be finite and `>= 0.0`).
|
|
pub cash: f64,
|
|
/// Dividend currency code (e.g. `"USD"`, `"CAD"`). Must be non-empty when `cash > 0.0`.
|
|
pub currency: String,
|
|
/// Raw (un-adjusted) close of the last session strictly before `ex_date`, if known.
|
|
pub prev_close: Option<f64>,
|
|
/// Currency of `prev_close`, if known.
|
|
pub prev_close_currency: Option<String>,
|
|
}
|
|
|
|
/// A single curated `adj_factors` row, unique per `(key, ex_date)`.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct AdjFactorRow<K = String> {
|
|
pub key: K,
|
|
pub ex_date: i32,
|
|
pub split_factor: f64,
|
|
pub div_cash: f64,
|
|
pub div_currency: Option<String>,
|
|
pub cum_split_factor: f64,
|
|
pub cum_total_factor: f64,
|
|
}
|
|
|
|
/// Summary counters produced alongside the built [`AdjFactorRow`] vector.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct AdjBuildStats {
|
|
pub split_events_in: usize,
|
|
pub split_noops_dropped: usize,
|
|
pub dividend_events_in: usize,
|
|
pub dividend_zero_cash_dropped: usize,
|
|
pub rows_out: usize,
|
|
pub keys_out: usize,
|
|
pub dividends_missing_prev_close: usize,
|
|
pub dividends_currency_mismatch: usize,
|
|
pub dividends_not_below_prev_close: usize,
|
|
}
|
|
|
|
/// Output of [`build_adj_factors`]: sorted rows plus build statistics.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct AdjFactorBuild<K = String> {
|
|
pub rows: Vec<AdjFactorRow<K>>,
|
|
pub stats: AdjBuildStats,
|
|
}
|
|
|
|
/// Typed errors returned while validating inputs or computing cumulative factors.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum AdjError {
|
|
/// A split ratio was non-finite (`NaN`, `+/-inf`) or `<= 0.0`.
|
|
InvalidSplitRatio { ex_date: i32, ratio: f64 },
|
|
/// A dividend cash amount was non-finite (`NaN`, `+/-inf`) or `< 0.0`.
|
|
InvalidDividendCash { ex_date: i32, cash: f64 },
|
|
/// A positive cash dividend had an empty or whitespace-only currency.
|
|
EmptyDividendCurrency { ex_date: i32 },
|
|
/// Two dividends on the same `(key, ex_date)` carried different currencies.
|
|
ConflictingDividendCurrency {
|
|
ex_date: i32,
|
|
first: String,
|
|
second: String,
|
|
},
|
|
/// Combining or compounding split/dividend factors overflowed to infinity or underflowed to 0.
|
|
FactorOverflow { ex_date: i32, factor: f64 },
|
|
}
|
|
|
|
impl fmt::Display for AdjError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::InvalidSplitRatio { ex_date, ratio } => {
|
|
write!(
|
|
f,
|
|
"invalid split ratio {ratio} on epoch day {ex_date}: must be finite and > 0"
|
|
)
|
|
}
|
|
Self::InvalidDividendCash { ex_date, cash } => {
|
|
write!(
|
|
f,
|
|
"invalid dividend cash {cash} on epoch day {ex_date}: must be finite and >= 0"
|
|
)
|
|
}
|
|
Self::EmptyDividendCurrency { ex_date } => {
|
|
write!(
|
|
f,
|
|
"empty dividend currency on epoch day {ex_date} for positive cash dividend"
|
|
)
|
|
}
|
|
Self::ConflictingDividendCurrency {
|
|
ex_date,
|
|
first,
|
|
second,
|
|
} => {
|
|
write!(
|
|
f,
|
|
"conflicting dividend currencies '{first}' and '{second}' on epoch day {ex_date}"
|
|
)
|
|
}
|
|
Self::FactorOverflow { ex_date, factor } => {
|
|
write!(
|
|
f,
|
|
"adjustment factor overflow/underflow ({factor}) at epoch day {ex_date}"
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for AdjError {}
|
|
|
|
enum RawEvent {
|
|
Split(f64),
|
|
Dividend {
|
|
cash: f64,
|
|
currency: String,
|
|
prev_close: Option<f64>,
|
|
prev_close_currency: Option<String>,
|
|
},
|
|
}
|
|
|
|
/// Deterministic preference rank for selecting a `prev_close` candidate when multiple dividend
|
|
/// records share the same `(key, ex_date)`.
|
|
#[inline]
|
|
fn prev_close_rank(
|
|
prev_close: Option<f64>,
|
|
prev_close_currency: Option<&str>,
|
|
div_currency: &str,
|
|
) -> u8 {
|
|
match prev_close {
|
|
Some(pc) if pc.is_finite() => {
|
|
if prev_close_currency == Some(div_currency) {
|
|
3
|
|
} else {
|
|
2
|
|
}
|
|
}
|
|
Some(_) => 1,
|
|
None => u8::from(prev_close_currency.is_some()),
|
|
}
|
|
}
|
|
|
|
/// Deterministic comparison between two `prev_close` candidates so output is invariant to
|
|
/// input permutation of same-day dividends.
|
|
#[inline]
|
|
fn is_better_prev_close(
|
|
cand_close: Option<f64>,
|
|
cand_currency: Option<&str>,
|
|
best_close: Option<f64>,
|
|
best_currency: Option<&str>,
|
|
div_currency: &str,
|
|
) -> bool {
|
|
let cand_rank = prev_close_rank(cand_close, cand_currency, div_currency);
|
|
let best_rank = prev_close_rank(best_close, best_currency, div_currency);
|
|
if cand_rank != best_rank {
|
|
return cand_rank > best_rank;
|
|
}
|
|
let close_ord = match (cand_close, best_close) {
|
|
(Some(a), Some(b)) => a.total_cmp(&b),
|
|
(Some(_), None) => Ordering::Greater,
|
|
(None, Some(_)) => Ordering::Less,
|
|
(None, None) => Ordering::Equal,
|
|
};
|
|
match close_ord {
|
|
Ordering::Greater => true,
|
|
Ordering::Less => false,
|
|
Ordering::Equal => cand_currency > best_currency,
|
|
}
|
|
}
|
|
|
|
/// Builds sorted, per-`(key, ex_date)` adjustment factor rows from split and cash-dividend streams.
|
|
///
|
|
/// - Rejects non-finite or `<= 0.0` split ratios with [`AdjError::InvalidSplitRatio`].
|
|
/// - Drops `ratio == 1.0` split no-ops and counts them in `stats.split_noops_dropped`.
|
|
/// - Rejects non-finite or `< 0.0` dividend cash with [`AdjError::InvalidDividendCash`].
|
|
/// - Drops `cash == 0.0` dividends and counts them in `stats.dividend_zero_cash_dropped`.
|
|
/// - Rejects empty/whitespace currency on positive dividends with [`AdjError::EmptyDividendCurrency`].
|
|
/// - Coalesces same-day splits (multiplying in `f64::total_cmp` order) and same-day dividends
|
|
/// (summing in `f64::total_cmp` order; rejecting currency conflicts with
|
|
/// [`AdjError::ConflictingDividendCurrency`]).
|
|
/// - Computes right-to-left cumulative suffix factors per key, rejecting overflow or underflow
|
|
/// with [`AdjError::FactorOverflow`].
|
|
pub fn build_adj_factors<K, S, D>(splits: S, dividends: D) -> Result<AdjFactorBuild<K>, AdjError>
|
|
where
|
|
K: Ord + Clone,
|
|
S: IntoIterator<Item = (K, SplitEvent)>,
|
|
D: IntoIterator<Item = (K, DividendEvent)>,
|
|
{
|
|
let splits_iter = splits.into_iter();
|
|
let divs_iter = dividends.into_iter();
|
|
let cap = splits_iter
|
|
.size_hint()
|
|
.0
|
|
.saturating_add(divs_iter.size_hint().0);
|
|
|
|
let mut raw: Vec<(K, i32, RawEvent)> = Vec::with_capacity(cap);
|
|
let mut stats = AdjBuildStats::default();
|
|
|
|
for (key, event) in splits_iter {
|
|
stats.split_events_in += 1;
|
|
if !event.ratio.is_finite() || event.ratio <= 0.0 {
|
|
return Err(AdjError::InvalidSplitRatio {
|
|
ex_date: event.ex_date,
|
|
ratio: event.ratio,
|
|
});
|
|
}
|
|
if event.ratio == 1.0 {
|
|
stats.split_noops_dropped += 1;
|
|
continue;
|
|
}
|
|
raw.push((key, event.ex_date, RawEvent::Split(event.ratio)));
|
|
}
|
|
|
|
for (key, event) in divs_iter {
|
|
stats.dividend_events_in += 1;
|
|
if !event.cash.is_finite() || event.cash < 0.0 {
|
|
return Err(AdjError::InvalidDividendCash {
|
|
ex_date: event.ex_date,
|
|
cash: event.cash,
|
|
});
|
|
}
|
|
if event.cash == 0.0 {
|
|
stats.dividend_zero_cash_dropped += 1;
|
|
continue;
|
|
}
|
|
if event.currency.trim().is_empty() {
|
|
return Err(AdjError::EmptyDividendCurrency {
|
|
ex_date: event.ex_date,
|
|
});
|
|
}
|
|
raw.push((
|
|
key,
|
|
event.ex_date,
|
|
RawEvent::Dividend {
|
|
cash: event.cash,
|
|
currency: event.currency,
|
|
prev_close: event.prev_close,
|
|
prev_close_currency: event.prev_close_currency,
|
|
},
|
|
));
|
|
}
|
|
|
|
if raw.is_empty() {
|
|
return Ok(AdjFactorBuild {
|
|
rows: Vec::new(),
|
|
stats,
|
|
});
|
|
}
|
|
|
|
raw.sort_unstable_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
|
|
|
let mut rows: Vec<AdjFactorRow<K>> = Vec::with_capacity(raw.len());
|
|
let mut same_day_splits: Vec<f64> = Vec::new();
|
|
let mut same_day_div_cash: Vec<f64> = Vec::new();
|
|
let mut key_div_factors: Vec<f64> = Vec::new();
|
|
|
|
let total_raw = raw.len();
|
|
let mut idx = 0usize;
|
|
|
|
while idx < total_raw {
|
|
let key_start = idx;
|
|
let key = raw[key_start].0.clone();
|
|
while idx < total_raw && raw[idx].0 == key {
|
|
idx += 1;
|
|
}
|
|
let key_end = idx;
|
|
|
|
let key_rows_start = rows.len();
|
|
key_div_factors.clear();
|
|
|
|
let mut day_idx = key_start;
|
|
while day_idx < key_end {
|
|
let ex_date = raw[day_idx].1;
|
|
let day_start = day_idx;
|
|
while day_idx < key_end && raw[day_idx].1 == ex_date {
|
|
day_idx += 1;
|
|
}
|
|
let day_end = day_idx;
|
|
|
|
same_day_splits.clear();
|
|
same_day_div_cash.clear();
|
|
|
|
let mut div_currency: Option<String> = None;
|
|
let mut has_prev_candidate = false;
|
|
let mut best_prev_close: Option<f64> = None;
|
|
let mut best_prev_close_currency: Option<String> = None;
|
|
|
|
for (_, _, ev) in &raw[day_start..day_end] {
|
|
match ev {
|
|
RawEvent::Split(ratio) => same_day_splits.push(*ratio),
|
|
RawEvent::Dividend {
|
|
cash,
|
|
currency,
|
|
prev_close,
|
|
prev_close_currency,
|
|
} => {
|
|
match &div_currency {
|
|
None => div_currency = Some(currency.clone()),
|
|
Some(first) if first != currency => {
|
|
return Err(AdjError::ConflictingDividendCurrency {
|
|
ex_date,
|
|
first: first.clone(),
|
|
second: currency.clone(),
|
|
});
|
|
}
|
|
Some(_) => {}
|
|
}
|
|
same_day_div_cash.push(*cash);
|
|
|
|
if !has_prev_candidate
|
|
|| is_better_prev_close(
|
|
*prev_close,
|
|
prev_close_currency.as_deref(),
|
|
best_prev_close,
|
|
best_prev_close_currency.as_deref(),
|
|
currency.as_str(),
|
|
)
|
|
{
|
|
has_prev_candidate = true;
|
|
best_prev_close = *prev_close;
|
|
best_prev_close_currency = prev_close_currency.clone();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut split_factor = 1.0_f64;
|
|
if !same_day_splits.is_empty() {
|
|
same_day_splits.sort_unstable_by(f64::total_cmp);
|
|
let mut combined = same_day_splits[0];
|
|
for &ratio in &same_day_splits[1..] {
|
|
combined *= ratio;
|
|
if !combined.is_finite() || combined <= 0.0 {
|
|
return Err(AdjError::FactorOverflow {
|
|
ex_date,
|
|
factor: combined,
|
|
});
|
|
}
|
|
}
|
|
split_factor = combined;
|
|
}
|
|
let has_effective_split = split_factor != 1.0;
|
|
|
|
let mut div_cash = 0.0_f64;
|
|
if !same_day_div_cash.is_empty() {
|
|
same_day_div_cash.sort_unstable_by(f64::total_cmp);
|
|
for &cash in &same_day_div_cash {
|
|
div_cash += cash;
|
|
if !div_cash.is_finite() {
|
|
return Err(AdjError::FactorOverflow {
|
|
ex_date,
|
|
factor: div_cash,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
let has_dividend = !same_day_div_cash.is_empty();
|
|
|
|
if !has_effective_split && !has_dividend {
|
|
continue;
|
|
}
|
|
|
|
let div_factor = if let Some(ref curr) = div_currency {
|
|
match best_prev_close {
|
|
Some(pc) if pc.is_finite() => {
|
|
if best_prev_close_currency.as_deref() != Some(curr.as_str()) {
|
|
stats.dividends_currency_mismatch += 1;
|
|
1.0
|
|
} else if pc <= div_cash {
|
|
stats.dividends_not_below_prev_close += 1;
|
|
1.0
|
|
} else {
|
|
let denom = pc - div_cash;
|
|
let factor = pc / denom;
|
|
if !factor.is_finite() || factor <= 0.0 {
|
|
return Err(AdjError::FactorOverflow { ex_date, factor });
|
|
}
|
|
factor
|
|
}
|
|
}
|
|
_ => {
|
|
stats.dividends_missing_prev_close += 1;
|
|
1.0
|
|
}
|
|
}
|
|
} else {
|
|
1.0
|
|
};
|
|
|
|
rows.push(AdjFactorRow {
|
|
key: key.clone(),
|
|
ex_date,
|
|
split_factor,
|
|
div_cash,
|
|
div_currency,
|
|
cum_split_factor: 1.0,
|
|
cum_total_factor: 1.0,
|
|
});
|
|
key_div_factors.push(div_factor);
|
|
}
|
|
|
|
if rows.len() > key_rows_start {
|
|
stats.keys_out += 1;
|
|
let mut running_split = 1.0_f64;
|
|
let mut running_div = 1.0_f64;
|
|
|
|
if let Some(key_slice) = rows.get_mut(key_rows_start..) {
|
|
for (row, &div_factor) in
|
|
key_slice.iter_mut().rev().zip(key_div_factors.iter().rev())
|
|
{
|
|
if row.split_factor != 1.0 {
|
|
running_split *= row.split_factor;
|
|
if !running_split.is_finite() || running_split <= 0.0 {
|
|
return Err(AdjError::FactorOverflow {
|
|
ex_date: row.ex_date,
|
|
factor: running_split,
|
|
});
|
|
}
|
|
}
|
|
if div_factor != 1.0 {
|
|
running_div *= div_factor;
|
|
if !running_div.is_finite() || running_div <= 0.0 {
|
|
return Err(AdjError::FactorOverflow {
|
|
ex_date: row.ex_date,
|
|
factor: running_div,
|
|
});
|
|
}
|
|
}
|
|
let cum_total = if running_div == 1.0 {
|
|
running_split
|
|
} else {
|
|
let prod = running_split * running_div;
|
|
if !prod.is_finite() || prod <= 0.0 {
|
|
return Err(AdjError::FactorOverflow {
|
|
ex_date: row.ex_date,
|
|
factor: prod,
|
|
});
|
|
}
|
|
prod
|
|
};
|
|
row.cum_split_factor = running_split;
|
|
row.cum_total_factor = cum_total;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
stats.rows_out = rows.len();
|
|
Ok(AdjFactorBuild { rows, stats })
|
|
}
|
|
|
|
/// Zero-allocation binary-search helper returning `(cum_split_factor, cum_total_factor)` of the
|
|
/// first row for `key` with `ex_date > bar_date`, or `(1.0, 1.0)` if no such row exists.
|
|
///
|
|
/// Assumes `rows` is sorted ascending by `(key, ex_date)` (as returned by [`build_adj_factors`]).
|
|
#[inline]
|
|
pub fn adj_factors_after<K: Ord>(rows: &[AdjFactorRow<K>], key: &K, bar_date: i32) -> (f64, f64) {
|
|
let idx = rows.partition_point(|row| match row.key.cmp(key) {
|
|
Ordering::Less => true,
|
|
Ordering::Equal => row.ex_date <= bar_date,
|
|
Ordering::Greater => false,
|
|
});
|
|
match rows.get(idx) {
|
|
Some(row) if &row.key == key => (row.cum_split_factor, row.cum_total_factor),
|
|
_ => (1.0, 1.0),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::split::{ymd_to_epoch_days, SplitTable};
|
|
|
|
fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) {
|
|
let diff = (actual - expected).abs();
|
|
let scale = expected.abs().max(1.0);
|
|
assert!(
|
|
diff <= rel_tol * scale,
|
|
"actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}"
|
|
);
|
|
}
|
|
|
|
fn div(
|
|
ex_date: i32,
|
|
cash: f64,
|
|
currency: &str,
|
|
prev_close: Option<f64>,
|
|
prev_close_currency: Option<&str>,
|
|
) -> DividendEvent {
|
|
DividendEvent {
|
|
ex_date,
|
|
cash,
|
|
currency: currency.to_string(),
|
|
prev_close,
|
|
prev_close_currency: prev_close_currency.map(str::to_string),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn nvda_splits_4_for_1_and_10_for_1_without_dividends() {
|
|
let d1 = ymd_to_epoch_days(2021, 7, 20).unwrap();
|
|
let d2 = ymd_to_epoch_days(2024, 6, 10).unwrap();
|
|
|
|
let built = build_adj_factors(
|
|
[
|
|
(
|
|
"NVDA".to_string(),
|
|
SplitEvent {
|
|
ex_date: d2,
|
|
ratio: 10.0,
|
|
},
|
|
),
|
|
(
|
|
"NVDA".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 4.0,
|
|
},
|
|
),
|
|
],
|
|
std::iter::empty::<(String, DividendEvent)>(),
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(built.rows.len(), 2);
|
|
assert_eq!(built.stats.rows_out, 2);
|
|
assert_eq!(built.stats.keys_out, 1);
|
|
assert_eq!(built.stats.split_events_in, 2);
|
|
assert_eq!(built.stats.dividend_events_in, 0);
|
|
|
|
let r0 = &built.rows[0];
|
|
assert_eq!(r0.key, "NVDA");
|
|
assert_eq!(r0.ex_date, d1);
|
|
assert_eq!(r0.split_factor, 4.0);
|
|
assert_eq!(r0.div_cash, 0.0);
|
|
assert_eq!(r0.div_currency, None);
|
|
assert_eq!(r0.cum_split_factor, 40.0);
|
|
assert_eq!(r0.cum_total_factor, r0.cum_split_factor);
|
|
|
|
let r1 = &built.rows[1];
|
|
assert_eq!(r1.key, "NVDA");
|
|
assert_eq!(r1.ex_date, d2);
|
|
assert_eq!(r1.split_factor, 10.0);
|
|
assert_eq!(r1.div_cash, 0.0);
|
|
assert_eq!(r1.div_currency, None);
|
|
assert_eq!(r1.cum_split_factor, 10.0);
|
|
assert_eq!(r1.cum_total_factor, r1.cum_split_factor);
|
|
}
|
|
|
|
#[test]
|
|
fn cum_split_factor_matches_split_table_across_mixed_keys_and_exact_ex_dates() {
|
|
let mut state: u64 = 0x1234_5678_9ABC_DEF0;
|
|
let mut next_u64 = || {
|
|
state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
|
let mut z = state;
|
|
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
|
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
|
z ^ (z >> 31)
|
|
};
|
|
|
|
let min_date = ymd_to_epoch_days(2005, 1, 1).unwrap();
|
|
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap();
|
|
let span = (max_date - min_date + 1) as u64;
|
|
let ratios = [2.0, 3.0, 4.0, 0.5, 0.25, 0.05, 1.0];
|
|
|
|
let mut splits: Vec<(i32, SplitEvent)> = Vec::new();
|
|
let mut dividends: Vec<(i32, DividendEvent)> = Vec::new();
|
|
let mut interesting_dates: Vec<(i32, i32)> = Vec::new();
|
|
|
|
for _ in 0..400 {
|
|
let key = (next_u64() % 40) as i32;
|
|
let ex_date = min_date + (next_u64() % span) as i32;
|
|
let ratio = ratios[(next_u64() as usize) % ratios.len()];
|
|
splits.push((key, SplitEvent { ex_date, ratio }));
|
|
interesting_dates.push((key, ex_date - 1));
|
|
interesting_dates.push((key, ex_date));
|
|
interesting_dates.push((key, ex_date + 1));
|
|
}
|
|
|
|
for _ in 0..800 {
|
|
let key = (next_u64() % 50) as i32;
|
|
let ex_date = min_date + (next_u64() % span) as i32;
|
|
let cash = ((next_u64() % 200) + 1) as f64 * 0.01;
|
|
dividends.push((key, div(ex_date, cash, "USD", Some(100.0), Some("USD"))));
|
|
interesting_dates.push((key, ex_date - 1));
|
|
interesting_dates.push((key, ex_date));
|
|
interesting_dates.push((key, ex_date + 1));
|
|
}
|
|
|
|
let table = SplitTable::from_events(splits.clone()).unwrap();
|
|
let built = build_adj_factors(splits, dividends).unwrap();
|
|
|
|
for (key, bar_date) in interesting_dates {
|
|
let expected = table.cum_factor_after(&key, bar_date);
|
|
let (actual, _) = adj_factors_after(&built.rows, &key, bar_date);
|
|
assert_eq!(
|
|
actual.to_bits(),
|
|
expected.to_bits(),
|
|
"mismatch for key={key} bar_date={bar_date}: adj={actual} split_table={expected}"
|
|
);
|
|
}
|
|
|
|
// Unknown key returns (1.0, 1.0) matching SplitTable.
|
|
assert_eq!(adj_factors_after(&built.rows, &999, min_date), (1.0, 1.0));
|
|
assert_eq!(table.cum_factor_after(&999, min_date), 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn reverse_split_noop_and_same_day_reciprocal_cancellation() {
|
|
let d1 = ymd_to_epoch_days(2025, 6, 18).unwrap();
|
|
let d2 = ymd_to_epoch_days(2025, 7, 1).unwrap();
|
|
let d3 = ymd_to_epoch_days(2025, 8, 1).unwrap();
|
|
|
|
let built = build_adj_factors(
|
|
[
|
|
// NEXM.V-style 1:20 reverse split
|
|
(
|
|
"NEXM.V".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 0.05,
|
|
},
|
|
),
|
|
// ratio == 1.0 no-op -> dropped
|
|
(
|
|
"NOOP".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 1.0,
|
|
},
|
|
),
|
|
// Same-day reciprocal splits alone -> cancelled, no row
|
|
(
|
|
"CANCEL_ONLY".to_string(),
|
|
SplitEvent {
|
|
ex_date: d2,
|
|
ratio: 2.0,
|
|
},
|
|
),
|
|
(
|
|
"CANCEL_ONLY".to_string(),
|
|
SplitEvent {
|
|
ex_date: d2,
|
|
ratio: 0.5,
|
|
},
|
|
),
|
|
// Same-day reciprocal splits paired with a dividend -> row kept with split_factor == 1.0
|
|
(
|
|
"CANCEL_WITH_DIV".to_string(),
|
|
SplitEvent {
|
|
ex_date: d3,
|
|
ratio: 2.0,
|
|
},
|
|
),
|
|
(
|
|
"CANCEL_WITH_DIV".to_string(),
|
|
SplitEvent {
|
|
ex_date: d3,
|
|
ratio: 0.5,
|
|
},
|
|
),
|
|
],
|
|
[(
|
|
"CANCEL_WITH_DIV".to_string(),
|
|
div(d3, 1.0, "USD", Some(50.0), Some("USD")),
|
|
)],
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(built.stats.split_events_in, 6);
|
|
assert_eq!(built.stats.split_noops_dropped, 1);
|
|
assert_eq!(built.stats.rows_out, 2);
|
|
assert_eq!(built.stats.keys_out, 2);
|
|
|
|
// Keys sorted ascending: "CANCEL_WITH_DIV" < "NEXM.V"
|
|
assert_eq!(built.rows[0].key, "CANCEL_WITH_DIV");
|
|
assert_eq!(built.rows[0].ex_date, d3);
|
|
assert_eq!(built.rows[0].split_factor, 1.0);
|
|
assert_eq!(built.rows[0].div_cash, 1.0);
|
|
assert_eq!(built.rows[0].div_currency.as_deref(), Some("USD"));
|
|
assert_eq!(built.rows[0].cum_split_factor, 1.0);
|
|
assert_rel_eq(built.rows[0].cum_total_factor, 50.0 / 49.0, 1e-12);
|
|
|
|
assert_eq!(built.rows[1].key, "NEXM.V");
|
|
assert_eq!(built.rows[1].ex_date, d1);
|
|
assert_eq!(built.rows[1].split_factor, 0.05);
|
|
assert_eq!(built.rows[1].cum_split_factor, 0.05);
|
|
assert_eq!(built.rows[1].cum_total_factor, 0.05);
|
|
}
|
|
|
|
#[test]
|
|
fn dividend_factor_compounds_into_earlier_split_cum_total_but_not_cum_split() {
|
|
let split_date = ymd_to_epoch_days(2023, 1, 10).unwrap();
|
|
let div_date = ymd_to_epoch_days(2024, 3, 15).unwrap();
|
|
|
|
let built = build_adj_factors(
|
|
[(
|
|
"AAPL".to_string(),
|
|
SplitEvent {
|
|
ex_date: split_date,
|
|
ratio: 4.0,
|
|
},
|
|
)],
|
|
[(
|
|
"AAPL".to_string(),
|
|
div(div_date, 2.0, "USD", Some(100.0), Some("USD")),
|
|
)],
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(built.rows.len(), 2);
|
|
let expected_div_factor = 100.0 / 98.0;
|
|
|
|
// Earlier split row: cum_split excludes dividend, cum_total includes it.
|
|
let r0 = &built.rows[0];
|
|
assert_eq!(r0.ex_date, split_date);
|
|
assert_eq!(r0.split_factor, 4.0);
|
|
assert_eq!(r0.div_cash, 0.0);
|
|
assert_eq!(r0.div_currency, None);
|
|
assert_eq!(r0.cum_split_factor, 4.0);
|
|
assert_rel_eq(r0.cum_total_factor, 4.0 * expected_div_factor, 1e-12);
|
|
|
|
// Later dividend row: split_factor == 1.0, cum_split == 1.0, cum_total == 100/98.
|
|
let r1 = &built.rows[1];
|
|
assert_eq!(r1.ex_date, div_date);
|
|
assert_eq!(r1.split_factor, 1.0);
|
|
assert_eq!(r1.div_cash, 2.0);
|
|
assert_eq!(r1.div_currency.as_deref(), Some("USD"));
|
|
assert_eq!(r1.cum_split_factor, 1.0);
|
|
assert_rel_eq(r1.cum_total_factor, expected_div_factor, 1e-12);
|
|
}
|
|
|
|
#[test]
|
|
fn same_day_split_and_multiple_dividends_merge_deterministically() {
|
|
let d = ymd_to_epoch_days(2024, 5, 1).unwrap();
|
|
let d_zero = ymd_to_epoch_days(2024, 6, 1).unwrap();
|
|
|
|
// Three positive cash values whose unsorted left-to-right f64 sums differ bitwise:
|
|
// ((1.0 + 1e-16) + 1e-16) == 1.0, whereas ((1e-16 + 1e-16) + 1.0) > 1.0.
|
|
let c_small = 1e-16_f64;
|
|
let c_large = 1.0_f64;
|
|
assert_ne!(
|
|
((c_large + c_small) + c_small).to_bits(),
|
|
((c_small + c_small) + c_large).to_bits()
|
|
);
|
|
let expected_cash = (c_small + c_small) + c_large;
|
|
|
|
// One fixed fixture containing distinct finite same-currency prev_close values (99.5 vs
|
|
// 100.0) plus a missing prev_close and a zero-cash event; every permutation must coalesce
|
|
// to the exact same bit-identical cash sum and tie-broken prev_close (100.0).
|
|
let fixture = [
|
|
div(d, c_large, "USD", Some(99.5), Some("USD")),
|
|
div(d, c_small, "USD", None, None),
|
|
div(d, c_small, "USD", Some(100.0), Some("USD")),
|
|
div(d_zero, 0.0, "", None, None),
|
|
];
|
|
let perm_indices = [[0, 1, 2, 3], [2, 0, 3, 1], [1, 2, 0, 3], [3, 2, 1, 0]];
|
|
|
|
let mut baseline_cash_bits: Option<u64> = None;
|
|
let mut baseline_total_bits: Option<u64> = None;
|
|
|
|
for order in perm_indices {
|
|
let div_list = order.into_iter().map(|i| (101_i32, fixture[i].clone()));
|
|
let built = build_adj_factors(
|
|
[(
|
|
101_i32,
|
|
SplitEvent {
|
|
ex_date: d,
|
|
ratio: 2.0,
|
|
},
|
|
)],
|
|
div_list,
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(built.rows.len(), 1);
|
|
assert_eq!(built.stats.dividend_events_in, 4);
|
|
assert_eq!(built.stats.dividend_zero_cash_dropped, 1);
|
|
assert_eq!(built.stats.dividends_missing_prev_close, 0);
|
|
|
|
let row = &built.rows[0];
|
|
assert_eq!(row.key, 101);
|
|
assert_eq!(row.ex_date, d);
|
|
assert_eq!(row.split_factor, 2.0);
|
|
assert_eq!(row.div_cash.to_bits(), expected_cash.to_bits());
|
|
assert_eq!(row.div_currency.as_deref(), Some("USD"));
|
|
assert_eq!(row.cum_split_factor, 2.0);
|
|
assert_rel_eq(
|
|
row.cum_total_factor,
|
|
2.0 * (100.0 / (100.0 - expected_cash)),
|
|
1e-12,
|
|
);
|
|
|
|
match baseline_cash_bits {
|
|
None => baseline_cash_bits = Some(row.div_cash.to_bits()),
|
|
Some(bits) => assert_eq!(row.div_cash.to_bits(), bits),
|
|
}
|
|
match baseline_total_bits {
|
|
None => baseline_total_bits = Some(row.cum_total_factor.to_bits()),
|
|
Some(bits) => assert_eq!(row.cum_total_factor.to_bits(), bits),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn dividend_fallbacks_preserve_cash_and_currency_and_increment_exact_counters() {
|
|
let d1 = ymd_to_epoch_days(2024, 1, 10).unwrap();
|
|
let d2 = ymd_to_epoch_days(2024, 2, 10).unwrap();
|
|
let d3 = ymd_to_epoch_days(2024, 3, 10).unwrap();
|
|
let d4 = ymd_to_epoch_days(2024, 4, 10).unwrap();
|
|
let d5 = ymd_to_epoch_days(2024, 5, 10).unwrap();
|
|
let d6 = ymd_to_epoch_days(2024, 6, 10).unwrap();
|
|
|
|
let built = build_adj_factors(
|
|
std::iter::empty::<(String, SplitEvent)>(),
|
|
[
|
|
// Missing prev_close (None)
|
|
("F".to_string(), div(d1, 1.5, "USD", None, Some("USD"))),
|
|
// Missing prev_close (NaN)
|
|
(
|
|
"F".to_string(),
|
|
div(d2, 1.5, "USD", Some(f64::NAN), Some("USD")),
|
|
),
|
|
// Missing prev_close (Infinity)
|
|
(
|
|
"F".to_string(),
|
|
div(d3, 1.5, "USD", Some(f64::INFINITY), Some("USD")),
|
|
),
|
|
// Currency mismatch (CAD dividend vs USD close)
|
|
(
|
|
"F".to_string(),
|
|
div(d4, 1.25, "CAD", Some(50.0), Some("USD")),
|
|
),
|
|
// prev_close == div_cash
|
|
(
|
|
"F".to_string(),
|
|
div(d5, 10.0, "USD", Some(10.0), Some("USD")),
|
|
),
|
|
// prev_close < div_cash
|
|
(
|
|
"F".to_string(),
|
|
div(d6, 12.0, "USD", Some(10.0), Some("USD")),
|
|
),
|
|
],
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(built.rows.len(), 6);
|
|
assert_eq!(built.stats.dividends_missing_prev_close, 3);
|
|
assert_eq!(built.stats.dividends_currency_mismatch, 1);
|
|
assert_eq!(built.stats.dividends_not_below_prev_close, 2);
|
|
|
|
for row in &built.rows {
|
|
assert_eq!(row.split_factor, 1.0);
|
|
assert_eq!(row.cum_split_factor, 1.0);
|
|
assert_eq!(row.cum_total_factor, 1.0);
|
|
assert!(row.div_cash > 0.0);
|
|
assert!(row.div_currency.is_some());
|
|
}
|
|
assert_eq!(built.rows[3].div_cash, 1.25);
|
|
assert_eq!(built.rows[3].div_currency.as_deref(), Some("CAD"));
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_inputs_and_overflows_return_typed_errors() {
|
|
let d1 = ymd_to_epoch_days(2024, 1, 2).unwrap();
|
|
let d2 = ymd_to_epoch_days(2024, 6, 3).unwrap();
|
|
|
|
// Invalid split ratios
|
|
for bad_ratio in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
|
let err = build_adj_factors(
|
|
[(
|
|
"BAD".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: bad_ratio,
|
|
},
|
|
)],
|
|
std::iter::empty::<(String, DividendEvent)>(),
|
|
)
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, AdjError::InvalidSplitRatio { ex_date, .. } if ex_date == d1),
|
|
"expected InvalidSplitRatio for {bad_ratio}, got {err:?}"
|
|
);
|
|
}
|
|
|
|
// Invalid dividend cash
|
|
for bad_cash in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
|
let err = build_adj_factors(
|
|
std::iter::empty::<(String, SplitEvent)>(),
|
|
[(
|
|
"BAD".to_string(),
|
|
div(d1, bad_cash, "USD", Some(100.0), Some("USD")),
|
|
)],
|
|
)
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, AdjError::InvalidDividendCash { ex_date, .. } if ex_date == d1),
|
|
"expected InvalidDividendCash for {bad_cash}, got {err:?}"
|
|
);
|
|
}
|
|
|
|
// Empty dividend currency on positive cash
|
|
for empty_curr in ["", " "] {
|
|
let err = build_adj_factors(
|
|
std::iter::empty::<(String, SplitEvent)>(),
|
|
[(
|
|
"BAD".to_string(),
|
|
div(d1, 1.0, empty_curr, Some(100.0), Some("USD")),
|
|
)],
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(
|
|
err,
|
|
AdjError::EmptyDividendCurrency { ex_date } if ex_date == d1
|
|
));
|
|
}
|
|
|
|
// Conflicting dividend currencies on the same (key, ex_date)
|
|
let conflict = build_adj_factors(
|
|
std::iter::empty::<(String, SplitEvent)>(),
|
|
[
|
|
(
|
|
"MIX".to_string(),
|
|
div(d1, 1.0, "USD", Some(100.0), Some("USD")),
|
|
),
|
|
(
|
|
"MIX".to_string(),
|
|
div(d1, 1.0, "CAD", Some(100.0), Some("CAD")),
|
|
),
|
|
],
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(
|
|
conflict,
|
|
AdjError::ConflictingDividendCurrency { ex_date, .. } if ex_date == d1
|
|
));
|
|
|
|
// Cumulative split overflow
|
|
let split_overflow = build_adj_factors(
|
|
[
|
|
(
|
|
"OVF".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 1e200,
|
|
},
|
|
),
|
|
(
|
|
"OVF".to_string(),
|
|
SplitEvent {
|
|
ex_date: d2,
|
|
ratio: 1e200,
|
|
},
|
|
),
|
|
],
|
|
std::iter::empty::<(String, DividendEvent)>(),
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(
|
|
split_overflow,
|
|
AdjError::FactorOverflow { ex_date, .. } if ex_date == d1
|
|
));
|
|
|
|
// Cumulative split underflow to 0.0
|
|
let split_underflow = build_adj_factors(
|
|
[
|
|
(
|
|
"UDF".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 1e-200,
|
|
},
|
|
),
|
|
(
|
|
"UDF".to_string(),
|
|
SplitEvent {
|
|
ex_date: d2,
|
|
ratio: 1e-200,
|
|
},
|
|
),
|
|
],
|
|
std::iter::empty::<(String, DividendEvent)>(),
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(
|
|
split_underflow,
|
|
AdjError::FactorOverflow { ex_date, .. } if ex_date == d1
|
|
));
|
|
|
|
// Cumulative total overflow (split * div_factor > f64::MAX)
|
|
let total_overflow = build_adj_factors(
|
|
[(
|
|
"TOT".to_string(),
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 1e308,
|
|
},
|
|
)],
|
|
[(
|
|
"TOT".to_string(),
|
|
div(d2, 90.0, "USD", Some(100.0), Some("USD")),
|
|
)],
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(
|
|
total_overflow,
|
|
AdjError::FactorOverflow { ex_date, .. } if ex_date == d1
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn shuffled_inputs_are_strictly_sorted_and_unique_and_empty_input_is_zeroed() {
|
|
let empty = build_adj_factors(
|
|
std::iter::empty::<(i32, SplitEvent)>(),
|
|
std::iter::empty::<(i32, DividendEvent)>(),
|
|
)
|
|
.unwrap();
|
|
assert!(empty.rows.is_empty());
|
|
assert_eq!(empty.stats, AdjBuildStats::default());
|
|
|
|
let d1 = ymd_to_epoch_days(2020, 1, 15).unwrap();
|
|
let d2 = ymd_to_epoch_days(2021, 6, 15).unwrap();
|
|
let d3 = ymd_to_epoch_days(2022, 9, 15).unwrap();
|
|
|
|
let built = build_adj_factors(
|
|
[
|
|
(
|
|
30_i32,
|
|
SplitEvent {
|
|
ex_date: d3,
|
|
ratio: 2.0,
|
|
},
|
|
),
|
|
(
|
|
10_i32,
|
|
SplitEvent {
|
|
ex_date: d2,
|
|
ratio: 3.0,
|
|
},
|
|
),
|
|
(
|
|
20_i32,
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 0.5,
|
|
},
|
|
),
|
|
(
|
|
10_i32,
|
|
SplitEvent {
|
|
ex_date: d1,
|
|
ratio: 2.0,
|
|
},
|
|
),
|
|
],
|
|
[
|
|
(30_i32, div(d1, 0.5, "USD", Some(50.0), Some("USD"))),
|
|
(10_i32, div(d2, 1.0, "USD", Some(100.0), Some("USD"))),
|
|
(20_i32, div(d3, 0.25, "CAD", Some(25.0), Some("CAD"))),
|
|
],
|
|
)
|
|
.unwrap();
|
|
|
|
assert_eq!(built.stats.keys_out, 3);
|
|
assert_eq!(built.stats.rows_out, built.rows.len());
|
|
for pair in built.rows.windows(2) {
|
|
assert!(
|
|
(pair[0].key, pair[0].ex_date) < (pair[1].key, pair[1].ex_date),
|
|
"rows not strictly sorted: {:?} vs {:?}",
|
|
pair[0],
|
|
pair[1]
|
|
);
|
|
}
|
|
}
|
|
}
|