use super::state::*;
use crate::mathx::{self, clamp_via_min_max as clamp};
use crate::rng::Rng;
pub fn weibull_hazard(months: f64, shape: f64, scale: f64) -> f64 {
if months <= 0.0 {
return 0.0;
}
let t = months / scale;
mathx::min(0.8, (shape / scale) * mathx::pow(t, shape - 1.0))
}
#[inline]
fn per_day(monthly: f64, spec: &CycleSpec) -> f64 {
let per_month = spec.per_month;
if per_month == 0.0 {
monthly
} else {
let m = spec.month_days;
monthly * (m - (m - 1.0) * per_month) / m
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct CycleSpec {
pub per_month: f64,
pub month_days: f64,
pub us: bool,
pub equity_hazard: f64,
pub equity_knee: f64,
pub equity_opening: f64,
pub inflation_hazard: f64,
pub rate_hazard: f64,
}
impl CycleSpec {
pub const fn shipped(per_month: f64) -> Self {
CycleSpec {
per_month, month_days: 30.0, us: false,
equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
inflation_hazard: 0.0, rate_hazard: 0.0,
}
}
}
pub fn cycle_hazard_params(phase: CyclePhase) -> (f64, f64) {
cycle_hazard_params_for(phase, false)
}
pub fn cycle_hazard_params_for(phase: CyclePhase, us: bool) -> (f64, f64) {
if us {
return us_cycle_hazard_params(phase);
}
match phase {
CyclePhase::Expansion => (1.8, 36.0),
CyclePhase::Peak => (2.0, 6.0),
CyclePhase::Contraction => (0.7, 12.0),
CyclePhase::Trough => (1.5, 4.0),
CyclePhase::Recovery => (1.3, 12.0),
}
}
pub fn get_cycle_transition_probability(
economy: &EconomyState,
per_month: f64,
) -> (f64, CyclePhase) {
get_cycle_transition_probability_for(economy, &CycleSpec::shipped(per_month))
}
pub fn get_cycle_transition_probability_for(
economy: &EconomyState,
spec: &CycleSpec,
) -> (f64, CyclePhase) {
let phase = phase_characteristics_for(economy.cycle_phase, spec.us);
let months = economy.months_in_current_phase;
if months < phase.min_months {
return (0.0, phase.next_phase);
}
let (shape, scale) = cycle_hazard_params_for(economy.cycle_phase, spec.us);
let p = adjust_transition_probability(economy, weibull_hazard(months, shape, scale), spec);
(per_day(clamp(p, 0.0, hazard_cap(spec.us)), spec), phase.next_phase)
}
#[inline]
pub fn hazard_cap(us: bool) -> f64 {
if us { US_HAZARD_CAP } else { 0.3 }
}
fn adjust_transition_probability(economy: &EconomyState, p: f64, spec: &CycleSpec) -> f64 {
adjust_transition_probability_in(economy, economy.cycle_phase, p, spec, None)
}
fn adjust_transition_probability_in(
economy: &EconomyState,
phase: CyclePhase,
mut p: f64,
spec: &CycleSpec,
equity_excess: Option<f64>,
) -> f64 {
if spec.equity_hazard != 0.0
&& matches!(phase, CyclePhase::Expansion | CyclePhase::Peak)
{
p += spec.equity_hazard
* equity_excess.unwrap_or_else(|| mathx::max(0.0, economy.spread_equity_gap - spec.equity_knee));
}
if spec.equity_opening != 0.0
&& matches!(phase, CyclePhase::Expansion | CyclePhase::Peak)
{
p += spec.equity_opening;
}
match phase {
CyclePhase::Expansion => {
if economy.inflation_rate > 4.0 {
p += if spec.inflation_hazard != 0.0 { spec.inflation_hazard } else { 0.1 };
}
if economy.federal_funds_rate > 5.0 {
p += if spec.rate_hazard != 0.0 { spec.rate_hazard } else { 0.1 };
}
if economy.treasury_yield_2y > economy.treasury_yield_10y {
let inversion_depth = economy.treasury_yield_2y - economy.treasury_yield_10y;
p += mathx::min(0.15, inversion_depth * 0.08);
}
let mkt_pe = economy.market_pe.unwrap_or(18.0);
if mkt_pe > 28.0 {
p += mathx::min(0.1, (mkt_pe - 28.0) * 0.005);
}
if economy.unemployment_rate > 8.0 || economy.gdp_growth < 1.0 {
p = mathx::max(0.0, p - 0.2);
}
}
CyclePhase::Recovery => {
if economy.unemployment_rate > 10.0 {
p = mathx::max(0.0, p - 0.1);
}
}
CyclePhase::Contraction => {
if economy.federal_funds_rate < 1.0 {
p += 0.1;
}
if economy.gdp_growth < -2.0 {
p += 0.05;
}
if economy.unemployment_rate > 10.0 {
p += 0.05;
}
if economy.treasury_yield_10y - economy.treasury_yield_2y > 1.5 {
p += 0.05;
}
}
CyclePhase::Trough => {
if economy.federal_funds_rate < 3.0 {
p += 0.1;
}
if economy.unemployment_rate > 8.0 {
p += 0.05;
}
}
CyclePhase::Peak => {}
}
p
}
pub fn check_cycle_transition(
economy: &EconomyState,
rng: &mut impl Rng,
per_month: f64,
) -> EconomyState {
check_cycle_transition_for(economy, rng, &CycleSpec::shipped(per_month))
}
pub fn check_cycle_transition_for(
economy: &EconomyState,
rng: &mut impl Rng,
spec: &CycleSpec,
) -> EconomyState {
let phase = phase_characteristics_for(economy.cycle_phase, spec.us);
let months = economy.months_in_current_phase;
if months < phase.min_months {
return economy.clone();
}
let (shape, scale) = cycle_hazard_params_for(economy.cycle_phase, spec.us);
let p = adjust_transition_probability(economy, weibull_hazard(months, shape, scale), spec);
let transition_probability = per_day(clamp(p, 0.0, hazard_cap(spec.us)), spec);
if rng.next_f64() < transition_probability {
let mut next = economy.clone();
next.cycle_phase = phase.next_phase;
next.months_in_current_phase = 0.0;
return next;
}
economy.clone()
}
pub fn phase_cycle() -> [CyclePhase; 5] {
let mut out = [CyclePhase::Expansion; 5];
for k in 1..out.len() {
out[k] = phase_characteristics(out[k - 1]).next_phase;
}
out
}
fn hazard_only_transition_probability(phase: CyclePhase, days: i64, spec: &CycleSpec) -> f64 {
let months = days as f64 / spec.month_days;
if months < phase_characteristics_for(phase, spec.us).min_months {
return 0.0;
}
let (shape, scale) = cycle_hazard_params_for(phase, spec.us);
let mut h = weibull_hazard(months, shape, scale);
if spec.equity_opening != 0.0 && matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) {
h += spec.equity_opening;
}
per_day(clamp(h, 0.0, hazard_cap(spec.us)), spec)
}
fn walk_survival(
phase: CyclePhase,
spec: &CycleSpec,
mut visit: impl FnMut(i64, f64) -> bool,
) -> f64 {
let (mut s, mut acc, mut a) = (1.0, 0.0, 0i64);
loop {
let next = acc + s;
if next == acc {
return acc;
}
acc = next;
if !visit(a, acc) {
return acc;
}
s *= 1.0 - hazard_only_transition_probability(phase, a + 1, spec);
a += 1;
}
}
pub fn mean_sojourn_days(phase: CyclePhase, per_month: f64) -> f64 {
mean_sojourn_days_for(phase, &CycleSpec::shipped(per_month))
}
pub fn mean_sojourn_days_for(phase: CyclePhase, spec: &CycleSpec) -> f64 {
walk_survival(phase, spec, |_, _| true)
}
pub fn transition_probability_for(
economy: &EconomyState,
phase: CyclePhase,
days: f64,
spec: &CycleSpec,
gap_var: f64,
) -> f64 {
let months = days / spec.month_days;
if months < phase_characteristics_for(phase, spec.us).min_months {
return 0.0;
}
let (shape, scale) = cycle_hazard_params_for(phase, spec.us);
let excess = if gap_var > 0.0 && spec.equity_hazard != 0.0 {
let s = mathx::sqrt(gap_var);
let x = economy.spread_equity_gap - spec.equity_knee;
let z = x / s;
let cdf = 0.5 * mathx::erfc(-z / core::f64::consts::SQRT_2);
let pdf = mathx::exp(-0.5 * z * z) / mathx::sqrt(2.0 * core::f64::consts::PI);
Some(x * cdf + s * pdf)
} else {
None
};
let p = adjust_transition_probability_in(economy, phase, weibull_hazard(months, shape, scale), spec, excess);
per_day(clamp(p, 0.0, hazard_cap(spec.us)), spec)
}
pub fn sojourn_quantile_days_for(phase: CyclePhase, spec: &CycleSpec, q: f64) -> i64 {
let mut s = 1.0;
let mut d = 0i64;
while d < 1_000_000 {
d += 1;
s *= 1.0 - hazard_only_transition_probability(phase, d, spec);
if 1.0 - s >= q {
return d;
}
}
i64::MAX
}
pub fn sojourn_sd_days_for(phase: CyclePhase, spec: &CycleSpec) -> f64 {
let mut prev = 0.0;
let mut second = 0.0;
let mean = walk_survival(phase, spec, |a, c| {
second += (2.0 * a as f64 + 1.0) * (c - prev);
prev = c;
true
});
mathx::sqrt(mathx::max(0.0, second - mean * mean))
}
pub fn downturn_quantile_days_for(spec: &CycleSpec, q: f64) -> i64 {
if !(q < 1.0) {
return i64::MAX;
}
let (mut sc, mut st) = (1.0, 1.0);
let mut pc: Vec<f64> = vec![0.0];
let mut ft: Vec<f64> = vec![0.0];
let mut d = 0usize;
while d < 100_000 {
d += 1;
let p = hazard_only_transition_probability(CyclePhase::Contraction, d as i64, spec);
pc.push(sc * p);
sc *= 1.0 - p;
st *= 1.0 - hazard_only_transition_probability(CyclePhase::Trough, d as i64, spec);
ft.push(1.0 - st);
let mut cdf = 0.0;
for c in 1..d {
cdf += pc[c] * ft[d - c];
}
if cdf >= q {
return d as i64;
}
}
i64::MAX
}
pub fn stationary_phase_shares(per_month: f64) -> ([f64; 5], f64) {
stationary_phase_shares_for(&CycleSpec::shipped(per_month))
}
pub fn stationary_phase_shares_for(spec: &CycleSpec) -> ([f64; 5], f64) {
type Key = (u64, u64, bool, u64, u64, u64);
type Shares = ([f64; 5], f64);
thread_local! {
static LAST: std::cell::Cell<Option<(Key, Shares)>> =
const { std::cell::Cell::new(None) };
}
let key: Key = (
spec.per_month.to_bits(),
spec.month_days.to_bits(),
spec.us,
spec.equity_hazard.to_bits(),
spec.equity_knee.to_bits(),
spec.equity_opening.to_bits(),
);
if let Some((k, v)) = LAST.with(|c| c.get()) {
if k == key {
return v;
}
}
let v = stationary_phase_shares_walk(spec);
LAST.with(|c| c.set(Some((key, v))));
v
}
fn stationary_phase_shares_walk(spec: &CycleSpec) -> ([f64; 5], f64) {
#[cfg(test)]
SHARE_WALKS.with(|n| n.set(n.get() + 1));
let mut mean = [0.0; 5];
let mut cycle = 0.0;
for (k, &phase) in phase_cycle().iter().enumerate() {
mean[k] = mean_sojourn_days_for(phase, spec);
cycle += mean[k];
}
(mean, cycle)
}
#[cfg(test)]
thread_local! {
static SHARE_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn share_walks() -> u64 {
SHARE_WALKS.with(|n| n.get())
}
pub fn stationary_opening(per_month: f64, u_phase: f64, u_age: f64) -> (CyclePhase, f64) {
stationary_opening_for(&CycleSpec::shipped(per_month), u_phase, u_age)
}
pub fn stationary_opening_for(spec: &CycleSpec, u_phase: f64, u_age: f64) -> (CyclePhase, f64) {
let phases = phase_cycle();
let (mean, cycle) = stationary_phase_shares_for(spec);
let mut cumulative = 0.0;
let mut pick = phases.len() - 1;
for (k, share) in mean.iter().enumerate().take(phases.len()) {
cumulative += share;
if cumulative / cycle >= u_phase {
pick = k;
break;
}
}
let phase = phases[pick];
let mut age = 0;
walk_survival(phase, spec, |a, cdf| {
age = a;
cdf / mean[pick] < u_age
});
(phase, age as f64 / spec.month_days)
}
#[cfg(test)]
mod stationary_law {
use super::*;
#[test]
fn the_memo_returns_the_walk_and_walks_once_per_spec() {
fn bits(v: ([f64; 5], f64)) -> ([u64; 5], u64) {
(v.0.map(f64::to_bits), v.1.to_bits())
}
let a = CycleSpec::shipped(1.0);
let b = CycleSpec { us: true, ..CycleSpec::shipped(1.0) };
let start = share_walks();
let first = stationary_phase_shares_for(&a);
for _ in 0..10 {
assert_eq!(bits(stationary_phase_shares_for(&a)), bits(first));
}
assert_eq!(share_walks() - start, 1, "one spec, one walk");
let other = stationary_phase_shares_for(&b);
assert_eq!(share_walks() - start, 2, "a new spec walks again");
assert_eq!(bits(stationary_phase_shares_for(&a)), bits(first));
assert_eq!(bits(first), bits(stationary_phase_shares_walk(&a)));
assert_eq!(bits(other), bits(stationary_phase_shares_walk(&b)));
}
#[test]
fn the_phase_order_closes_on_itself() {
let phases = phase_cycle();
assert_eq!(phase_characteristics(phases[4]).next_phase, phases[0]);
for i in 0..5 {
for j in (i + 1)..5 {
assert_ne!(phases[i], phases[j], "{i} and {j} are the same phase");
}
}
}
#[test]
fn the_hazard_only_probability_is_the_transition_the_engine_rolls() {
for per_month in [0.0, 1.0] {
for phase in phase_cycle() {
for &days in &[1, 59, 60, 119, 120, 179, 180, 181, 400, 2000] {
let mut e = ladder_free_economy();
e.cycle_phase = phase;
e.months_in_current_phase = days as f64 / 30.0;
let p = hazard_only_transition_probability(phase, days, &CycleSpec::shipped(per_month));
let (engine_p, _) = get_cycle_transition_probability(&e, per_month);
assert_eq!(p, engine_p, "{phase:?} at {days} days, clock {per_month}");
}
}
}
}
#[test]
fn the_survival_sum_is_the_mean_of_the_sojourn() {
for per_month in [0.0, 1.0] {
for phase in phase_cycle() {
let sum = mean_sojourn_days(phase, per_month);
let mut horizon = 0;
walk_survival(phase, &CycleSpec::shipped(per_month), |a, _| {
horizon = a;
true
});
let mut survival = 1.0;
let mut mean = 0.0;
for j in 1..=(horizon + 1) {
let p = hazard_only_transition_probability(phase, j, &CycleSpec::shipped(per_month));
mean += j as f64 * survival * p;
survival *= 1.0 - p;
}
assert!((mean - sum).abs() / sum < 1e-9,
"{phase:?} clock {per_month}: {mean} against {sum}");
}
}
}
#[test]
fn the_share_below_the_minimum_is_the_minimum_over_the_mean() {
for per_month in [0.0, 1.0] {
for phase in phase_cycle() {
let min_days = (phase_characteristics(phase).min_months * 30.0) as i64;
let mean = mean_sojourn_days(phase, per_month);
let mut below = 0.0;
walk_survival(phase, &CycleSpec::shipped(per_month), |a, cdf| {
if a == min_days - 1 {
below = cdf / mean;
return false;
}
true
});
let identity = min_days as f64 / mean;
assert!((below - identity).abs() < 1e-12,
"{phase:?} clock {per_month}: {below} against {identity}");
}
}
}
#[test]
fn the_shares_and_the_age_density_are_both_distributions() {
for per_month in [0.0, 1.0] {
let (mean, cycle) = stationary_phase_shares(per_month);
let total: f64 = mean.iter().sum::<f64>() / cycle;
assert!((total - 1.0).abs() < 1e-12, "shares sum to {total}");
for (k, &phase) in phase_cycle().iter().enumerate() {
let mut last = 0.0;
walk_survival(phase, &CycleSpec::shipped(per_month), |_, cdf| {
last = cdf / mean[k];
true
});
assert!((last - 1.0).abs() < 1e-12,
"{phase:?} clock {per_month}: age density sums to {last}");
}
}
}
#[test]
fn the_draw_picks_the_phase_whose_interval_holds_the_uniform() {
for per_month in [0.0, 1.0] {
let (mean, cycle) = stationary_phase_shares(per_month);
let phases = phase_cycle();
let mut lower = 0.0;
for k in 0..phases.len() {
let upper = lower + mean[k] / cycle;
let inside = (upper - lower) * 1e-6;
for u in [lower + inside, (lower + upper) / 2.0, upper - inside] {
let (got, _) = stationary_opening(per_month, u, 0.5);
assert_eq!(got, phases[k],
"u = {u} clock {per_month} wanted {:?}", phases[k]);
}
lower = upper;
}
assert!((lower - 1.0).abs() < 1e-12, "the intervals end at {lower}");
}
}
#[test]
fn the_drawn_age_is_the_quantile_of_the_age_density_in_engine_months() {
for per_month in [0.0, 1.0] {
let (mean, cycle) = stationary_phase_shares(per_month);
for (k, &phase) in phase_cycle().iter().enumerate() {
let mut cdf = Vec::new();
walk_survival(phase, &CycleSpec::shipped(per_month), |_, c| {
cdf.push(c / mean[k]);
true
});
for w in cdf.windows(2) {
assert!(w[1] >= w[0], "{phase:?} clock {per_month}: the CDF fell");
}
let u_phase = (mean[..k].iter().sum::<f64>() + mean[k] / 2.0) / cycle;
for &u in &[1e-9, 0.1, 0.25, 0.5, 0.731, 0.9, 0.999] {
let want = cdf.iter().position(|&c| c >= u).unwrap() as i64;
let (got_phase, months) = stationary_opening(per_month, u_phase, u);
assert_eq!(got_phase, phase, "clock {per_month} at u = {u}");
assert_eq!(months, want as f64 / 30.0,
"{phase:?} clock {per_month} at u = {u}: wanted {want} days");
}
}
}
}
#[test]
fn the_ends_of_the_uniform_stay_inside_the_law() {
let below_one = 1.0 - f64::EPSILON / 2.0;
for per_month in [0.0, 1.0] {
let (first, age) = stationary_opening(per_month, 0.0, 0.0);
assert_eq!(first, phase_cycle()[0]);
assert_eq!(age, 0.0);
let (last, age) = stationary_opening(per_month, below_one, below_one);
assert!(phase_cycle().contains(&last));
assert!(age.is_finite() && age > 0.0, "age {age}");
}
}
#[test]
fn the_equity_hazard_off_is_the_ladder_that_stood() {
for us in [false, true] {
for per_month in [0.0, 1.0] {
for phase in phase_cycle() {
for gap in [-0.3, 0.0, 0.2, 0.9] {
let mut e = ladder_free_economy();
e.cycle_phase = phase;
e.months_in_current_phase = 7.0;
e.spread_equity_gap = gap;
let shipped = CycleSpec { us, ..CycleSpec::shipped(per_month) };
let off = CycleSpec { equity_knee: 0.05, ..shipped };
assert_eq!(get_cycle_transition_probability_for(&e, &shipped),
get_cycle_transition_probability_for(&e, &off),
"{phase:?} gap {gap} us {us} clock {per_month}");
}
}
}
}
}
#[test]
fn the_equity_hazard_adds_in_an_expansion_and_at_a_peak_above_the_knee() {
let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
inflation_hazard: 0.0, rate_hazard: 0.0 };
let on = CycleSpec { equity_hazard: 4.0, equity_knee: 0.05, ..base };
for phase in phase_cycle() {
let mut e = ladder_free_economy();
e.cycle_phase = phase;
e.months_in_current_phase = 7.0;
for gap in [-0.2, 0.0, 0.05, 0.1, 0.15] {
e.spread_equity_gap = gap;
let (p0, next0) = get_cycle_transition_probability_for(&e, &base);
let (p1, next1) = get_cycle_transition_probability_for(&e, &on);
assert_eq!(next0, next1);
let fires = matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) && gap > 0.05;
if fires {
let monthly0 = p0 * 21.0;
let want = (monthly0 + 4.0 * (gap - 0.05)).min(US_HAZARD_CAP) / 21.0;
assert!((p1 - want).abs() < 1e-12, "{phase:?} gap {gap}: {p1} against {want}");
assert!(p1 > p0, "{phase:?} gap {gap}");
} else {
assert_eq!(p0, p1, "{phase:?} gap {gap}");
}
}
}
}
#[test]
fn the_expansion_guard_still_applies_to_the_equity_hazard() {
let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
inflation_hazard: 0.0, rate_hazard: 0.0 };
let on = CycleSpec { equity_hazard: 1.0, equity_knee: 0.0, ..base };
let mut e = ladder_free_economy();
e.cycle_phase = CyclePhase::Expansion;
e.months_in_current_phase = 7.0;
e.gdp_growth = 0.5;
e.spread_equity_gap = 0.1;
let (p0, _) = get_cycle_transition_probability_for(&e, &base);
let (p1, _) = get_cycle_transition_probability_for(&e, &on);
assert_eq!(p0, 0.0);
assert_eq!(p1, 0.0);
}
#[test]
fn the_forecast_reads_the_market_term_over_the_gap_spread() {
let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
inflation_hazard: 0.0, rate_hazard: 0.0 };
let on = CycleSpec { equity_hazard: 5.0, equity_knee: 0.1, ..base };
for phase in phase_cycle() {
for gap in [-0.06, 0.0, 0.12] {
let mut e = ladder_free_economy();
e.cycle_phase = phase;
e.months_in_current_phase = 147.0 / 21.0;
e.spread_equity_gap = gap;
let (law, _) = get_cycle_transition_probability_for(&e, &on);
assert_eq!(transition_probability_for(&e, phase, 147.0, &on, 0.0), law, "{phase:?} gap {gap}");
let var: f64 = 0.08 * 0.08;
let have = transition_probability_for(&e, phase, 147.0, &on, var);
if matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) {
let (p0, _) = get_cycle_transition_probability_for(&e, &base);
let (n, sd) = (20_000, var.sqrt());
let mut excess = 0.0;
for i in 0..n {
let z = -8.0 + 16.0 * (i as f64 + 0.5) / n as f64;
let w = (-0.5 * z * z).exp() / (2.0 * std::f64::consts::PI).sqrt() * 16.0 / n as f64;
excess += w * (gap + sd * z - 0.1).max(0.0);
}
let want = (p0 * 21.0 + 5.0 * excess).min(US_HAZARD_CAP) / 21.0;
assert!((have - want).abs() < 1e-9, "{phase:?} gap {gap}: {have} against {want}");
assert!(have > law || gap > 0.1, "{phase:?} gap {gap}");
} else {
assert_eq!(have, law, "{phase:?} gap {gap}");
}
}
}
}
#[test]
fn the_opening_stand_in_adds_to_the_law_and_the_ladder() {
let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
inflation_hazard: 0.0, rate_hazard: 0.0 };
let on = CycleSpec { equity_opening: 0.01, ..base };
for phase in phase_cycle() {
let mut e = ladder_free_economy();
e.cycle_phase = phase;
e.months_in_current_phase = 7.0;
let (p0, _) = get_cycle_transition_probability_for(&e, &base);
let (p1, _) = get_cycle_transition_probability_for(&e, &on);
let m0 = mean_sojourn_days_for(phase, &base);
let m1 = mean_sojourn_days_for(phase, &on);
if matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) {
let want = ((p0 * 21.0) + 0.01).min(US_HAZARD_CAP) / 21.0;
assert!((p1 - want).abs() < 1e-12, "{phase:?}: {p1} against {want}");
assert!(m1 < m0, "{phase:?}: {m1} against {m0}");
} else {
assert_eq!(p0, p1, "{phase:?}");
assert_eq!(m0, m1, "{phase:?}");
}
}
let zero = CycleSpec { equity_opening: 0.0, ..on };
assert_eq!(stationary_phase_shares_for(&zero), stationary_phase_shares_for(&base));
}
#[test]
fn the_sojourn_quantiles_and_spread_are_the_walks_own_law() {
let us = CycleSpec { per_month: 1.0, month_days: 21.0, us: true, ..CycleSpec::shipped(1.0) };
for spec in [CycleSpec::shipped(1.0), us] {
let pmf = |phase| {
let (mut s, mut out) = (1.0, vec![0.0]);
for d in 1..200_000i64 {
let p = hazard_only_transition_probability(phase, d, &spec);
out.push(s * p);
s *= 1.0 - p;
if s < 1e-18 {
break;
}
}
out
};
for phase in phase_cycle() {
let f = pmf(phase);
let mean: f64 = f.iter().enumerate().map(|(d, p)| d as f64 * p).sum();
let second: f64 = f.iter().enumerate().map(|(d, p)| (d * d) as f64 * p).sum();
let sd = (second - mean * mean).sqrt();
let walked = mean_sojourn_days_for(phase, &spec);
assert!((walked - mean).abs() < 1e-6 * mean, "{phase:?}: {walked} against {mean}");
let got = sojourn_sd_days_for(phase, &spec);
assert!((got - sd).abs() < 1e-6 * sd, "{phase:?}: sd {got} against {sd}");
for q in [0.5, 0.9, 0.99] {
let mut c = 0.0;
let want = f.iter().position(|p| { c += p; c >= q }).unwrap() as i64;
assert_eq!(sojourn_quantile_days_for(phase, &spec, q), want, "{phase:?} {q}");
}
}
let (c, t) = (pmf(CyclePhase::Contraction), pmf(CyclePhase::Trough));
let mut sum = vec![0.0; c.len() + t.len()];
for (i, a) in c.iter().enumerate() {
for (j, b) in t.iter().enumerate() {
sum[i + j] += a * b;
}
}
for q in [0.5, 0.99] {
let mut acc = 0.0;
let want = sum.iter().position(|p| { acc += p; acc >= q }).unwrap() as i64;
assert_eq!(downturn_quantile_days_for(&spec, q), want, "{q}");
}
assert_eq!(downturn_quantile_days_for(&spec, 1.0), i64::MAX);
}
assert_eq!(sojourn_quantile_days_for(CyclePhase::Trough, &us, 0.99), 170);
assert_eq!(sojourn_quantile_days_for(CyclePhase::Contraction, &us, 0.99), 246);
assert_eq!(downturn_quantile_days_for(&us, 0.99), 338);
}
fn ladder_free_economy() -> EconomyState {
let mut e = create_initial_economy_state(&InitialEconomyOptions::default());
e.inflation_rate = 2.0;
e.federal_funds_rate = 3.0;
e.treasury_yield_2y = 2.0;
e.treasury_yield_10y = 3.0;
e.market_pe = Some(18.0);
e.unemployment_rate = 4.0;
e.gdp_growth = 2.0;
e
}
}