#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct IndexValue {
pub value: f64,
pub change: f64,
pub change_percent: f64,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct IndexConstituent {
pub id: String,
pub market_cap: f64,
pub is_bankrupt: bool,
}
impl IndexConstituent {
pub fn new(id: impl Into<String>, market_cap: f64) -> Self {
IndexConstituent { id: id.into(), market_cap, is_bankrupt: false }
}
}
pub const INDEX_BASE: f64 = 1000.0;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct IndexLevel {
pub level: f64,
pub close: Option<f64>,
pub divisor: Option<f64>,
pub constituents: usize,
}
pub fn rebased_divisor(cap: f64, level: f64) -> Option<f64> {
if !(cap > 0.0 && cap.is_finite() && level > 0.0 && level.is_finite()) {
return None;
}
let divisor = cap / level;
if divisor > 0.0 && divisor.is_finite() {
Some(divisor)
} else {
None
}
}
pub fn calculate_market_index(
companies: &[IndexConstituent],
component_ids: &[String],
previous_value: f64,
divisor: f64,
) -> IndexValue {
let mut total_market_cap = 0.0;
for company in companies {
if !component_ids.iter().any(|id| id == &company.id) {
continue;
}
if company.is_bankrupt {
continue;
}
total_market_cap += company.market_cap;
}
let unchanged = IndexValue {
value: previous_value,
change: 0.0,
change_percent: 0.0,
};
if total_market_cap == 0.0 || divisor <= 0.0 {
return unchanged;
}
let raw_value = total_market_cap / divisor;
if !raw_value.is_finite() || raw_value <= 0.0 {
return unchanged;
}
let change = raw_value - previous_value;
let change_percent = if previous_value > 0.0 {
(change / previous_value) * 100.0
} else {
0.0
};
IndexValue {
value: raw_value,
change,
change_percent,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn c(id: &str, cap: f64, bankrupt: bool) -> IndexConstituent {
IndexConstituent {
id: id.to_string(),
market_cap: cap,
is_bankrupt: bankrupt,
}
}
fn ids(names: &[&str]) -> Vec<String> {
names.iter().map(|s| s.to_string()).collect()
}
#[test]
fn the_index_is_the_aggregate_cap_over_the_divisor() {
let roster = vec![c("a", 1e11, false), c("b", 5e10, false)];
let out = calculate_market_index(&roster, &ids(&["a", "b"]), 100.0, 1e9);
assert_eq!(out.value, 150.0);
assert_eq!(out.change, 50.0);
assert_eq!(out.change_percent, 50.0);
}
#[test]
fn bankrupt_constituents_leave_the_index() {
let roster = vec![c("a", 1e11, false), c("b", 5e10, true)];
let out = calculate_market_index(&roster, &ids(&["a", "b"]), 100.0, 1e9);
assert_eq!(
out.value, 100.0,
"the bankrupt name must not contribute its cap"
);
}
#[test]
fn non_constituents_are_ignored_however_large() {
let roster = vec![c("a", 1e11, false), c("whale", 9e15, false)];
let out = calculate_market_index(&roster, &ids(&["a"]), 100.0, 1e9);
assert_eq!(out.value, 100.0);
}
#[test]
fn every_degenerate_input_holds_the_previous_value() {
let roster = vec![c("a", 1e11, false)];
let all = ids(&["a"]);
for (note, companies, divisor) in [
("zero divisor", roster.clone(), 0.0),
("negative divisor", roster.clone(), -5.0),
("NaN divisor", roster.clone(), f64::NAN),
("empty roster", vec![], 1e9),
("all bankrupt", vec![c("a", 1e11, true)], 1e9),
("zero cap", vec![c("a", 0.0, false)], 1e9),
] {
let out = calculate_market_index(&companies, &all, 4000.0, divisor);
assert_eq!(out.value, 4000.0, "{note}: must hold the previous value");
assert_eq!(out.change, 0.0, "{note}");
assert_eq!(out.change_percent, 0.0, "{note}");
}
}
#[test]
fn a_divisor_small_enough_to_overflow_holds_rather_than_printing_infinity() {
let roster = vec![c("a", 1e11, false)];
let out = calculate_market_index(&roster, &ids(&["a"]), 4000.0, 1e-300);
assert_eq!(out.value, 4000.0);
}
#[test]
fn a_non_positive_previous_value_reports_zero_percent_rather_than_infinity() {
let roster = vec![c("a", 1e11, false)];
for previous in [0.0, -1.0] {
let out = calculate_market_index(&roster, &ids(&["a"]), previous, 1e9);
assert_eq!(out.change_percent, 0.0);
assert_eq!(out.value, 100.0);
}
}
#[test]
fn there_is_no_rate_of_change_limit() {
let calm = vec![c("a", 1e11, false)];
let gapped = vec![c("a", 5e11, false)];
let before = calculate_market_index(&calm, &ids(&["a"]), 100.0, 1e9);
let after = calculate_market_index(&gapped, &ids(&["a"]), before.value, 1e9);
assert_eq!(after.value, 500.0, "a 5x cap move must print in full");
assert_eq!(after.change_percent, 400.0);
}
}