use crate::mathx::{self, clamp};
pub const MISPRICING_HALF_LIFE_DAYS: f64 = 60.0;
pub const MISPRICING_PHI: f64 = f64::from_bits(0x3FEF_A1E8_27A1_B38C);
pub const MOMENTUM_THETA: f64 = 0.25;
pub const MISPRICING_CAP: f64 = 0.9;
pub const DAILY_SHOCK_CAP: f64 = 0.15;
pub const CROWD_VALUATION_GAIN: f64 = 0.006;
pub const CROWD_MOMENTUM_GAIN: f64 = 0.02;
pub const CROWD_LEAN_CAP: f64 = 0.02;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct MispricingState {
pub s: f64,
pub s_prev: f64,
}
impl Default for MispricingState {
fn default() -> Self {
create_mispricing_state(0.0)
}
}
pub fn create_mispricing_state(initial: f64) -> MispricingState {
let s = clamp(initial, -MISPRICING_CAP, MISPRICING_CAP);
MispricingState { s, s_prev: s }
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct MispricingInputs {
pub innovation: f64,
pub shock: f64,
}
impl MispricingInputs {
pub const fn new(innovation: f64, shock: f64) -> Self {
MispricingInputs { innovation, shock }
}
}
pub fn step_mispricing(state: &MispricingState, inputs: &MispricingInputs) -> MispricingState {
let shock = clamp(inputs.shock, -DAILY_SHOCK_CAP, DAILY_SHOCK_CAP);
let momentum = MOMENTUM_THETA * (state.s - state.s_prev);
let next = MISPRICING_PHI * state.s + momentum + inputs.innovation + shock;
MispricingState {
s: clamp(next, -MISPRICING_CAP, MISPRICING_CAP),
s_prev: state.s,
}
}
pub fn apply_mispricing(fair_value: f64, s: f64) -> f64 {
mathx::max(
0.01,
fair_value * mathx::exp(clamp(s, -MISPRICING_CAP, MISPRICING_CAP)),
)
}
pub fn crowd_lean(s: f64, momentum: f64) -> f64 {
crowd_lean_with(&crate::params::PT_V1, s, momentum)
}
pub fn crowd_lean_with(params: &crate::params::ModelParams, s: f64, momentum: f64) -> f64 {
let lean = -params.crowd_valuation_gain * s + params.crowd_momentum_gain * momentum;
clamp(lean, -params.crowd_lean_cap, params.crowd_lean_cap)
}
pub fn crowd_adjusted_root_moduli() -> (f64, f64) {
characteristic_root_moduli(
Some(MISPRICING_PHI - CROWD_VALUATION_GAIN),
Some(MOMENTUM_THETA + CROWD_MOMENTUM_GAIN),
)
}
pub fn characteristic_root_moduli(phi: Option<f64>, theta: Option<f64>) -> (f64, f64) {
let phi = phi.unwrap_or(MISPRICING_PHI);
let theta = theta.unwrap_or(MOMENTUM_THETA);
let a1 = phi + theta;
let a2 = -theta;
let disc = a1 * a1 + 4.0 * a2;
if disc >= 0.0 {
let sq = mathx::sqrt(disc);
(((a1 + sq) / 2.0).abs(), ((a1 - sq) / 2.0).abs())
} else {
let modulus = mathx::sqrt(-a2);
(modulus, modulus)
}
}
pub fn impulse_response(horizon_days: i64, phi: Option<f64>, theta: Option<f64>) -> Vec<f64> {
let phi = phi.unwrap_or(MISPRICING_PHI);
let theta = theta.unwrap_or(MOMENTUM_THETA);
let mut out = vec![1.0];
let mut prev = 0.0f64;
let mut curr = 1.0f64;
for _ in 1..=horizon_days {
let next = phi * curr + theta * (curr - prev);
prev = curr;
curr = next;
out.push(curr);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn phi_matches_the_recorded_v8_bits() {
assert_eq!(MISPRICING_PHI.to_bits(), 0x3FEF_A1E8_27A1_B38C);
assert_eq!(MISPRICING_PHI, 0.9885140203528962);
}
#[test]
fn phi_delivers_the_stated_half_life() {
let mut decayed = 1.0f64;
for _ in 0..60 {
decayed *= MISPRICING_PHI;
}
assert!((decayed - 0.5).abs() < 1e-13, "60-day decay was {decayed}");
}
#[test]
fn both_characteristic_roots_lie_inside_the_unit_circle() {
let (r1, r2) = characteristic_root_moduli(None, None);
assert!(
r1 < 1.0 && r2 < 1.0,
"roots {r1}, {r2} — process is not stationary"
);
}
#[test]
fn the_crowd_gains_do_not_push_the_roots_out() {
let (r1, r2) = crowd_adjusted_root_moduli();
assert!(
r1 < 1.0 && r2 < 1.0,
"crowd-adjusted roots {r1}, {r2} are not stationary"
);
}
#[test]
fn the_crowd_strengthens_reversion_rather_than_weakening_it() {
let (bare, _) = characteristic_root_moduli(None, None);
let (crowded, _) = crowd_adjusted_root_moduli();
assert!(
crowded < bare,
"crowd should tighten the dominant root: {crowded} vs {bare}"
);
}
#[test]
fn a_unit_root_stays_exactly_one() {
let path = impulse_response(64, Some(1.0), Some(0.0));
assert!(
path.iter().all(|&x| x == 1.0),
"unit root drifted: {path:?}"
);
}
#[test]
fn an_impulse_decays_to_nothing() {
let path = impulse_response(5000, None, None);
assert_eq!(path[0], 1.0);
assert!(
path[3] > path[0],
"momentum should extend the impulse first"
);
assert!(path.last().unwrap().abs() < 1e-9, "impulse never decayed");
}
#[test]
fn a_non_positive_horizon_returns_exactly_one_entry() {
for horizon in [0, -1, -100] {
assert_eq!(impulse_response(horizon, None, None), vec![1.0]);
}
}
#[test]
fn s_never_escapes_the_cap_however_hard_it_is_pushed() {
let mut state = create_mispricing_state(0.0);
for _ in 0..1000 {
state = step_mispricing(
&state,
&MispricingInputs {
innovation: 10.0,
shock: 100.0,
},
);
assert!(state.s.abs() <= MISPRICING_CAP, "s escaped to {}", state.s);
}
assert_eq!(state.s, MISPRICING_CAP);
}
#[test]
fn the_initial_state_is_clamped_too() {
assert_eq!(create_mispricing_state(50.0).s, MISPRICING_CAP);
assert_eq!(create_mispricing_state(-50.0).s, -MISPRICING_CAP);
}
#[test]
fn negative_zero_survives_state_creation() {
assert_eq!(
create_mispricing_state(-0.0).s.to_bits(),
(-0.0f64).to_bits()
);
}
#[test]
fn s_prev_takes_the_unclamped_input_exactly_once() {
let rogue = MispricingState {
s: 5.0,
s_prev: 0.0,
};
let next = step_mispricing(
&rogue,
&MispricingInputs {
innovation: 0.0,
shock: 0.0,
},
);
assert_eq!(next.s_prev, 5.0);
assert_eq!(next.s, MISPRICING_CAP);
}
#[test]
fn the_shock_is_capped_but_the_innovation_is_not() {
let state = create_mispricing_state(0.0);
let shocked = step_mispricing(
&state,
&MispricingInputs {
innovation: 0.0,
shock: 99.0,
},
);
assert_eq!(shocked.s, DAILY_SHOCK_CAP);
let innovated = step_mispricing(
&state,
&MispricingInputs {
innovation: 99.0,
shock: 0.0,
},
);
assert_eq!(innovated.s, MISPRICING_CAP);
}
#[test]
fn nan_passes_through_the_clamp_rather_than_becoming_a_bound() {
let state = create_mispricing_state(0.0);
let out = step_mispricing(
&state,
&MispricingInputs {
innovation: f64::NAN,
shock: 0.0,
},
);
assert!(out.s.is_nan(), "NaN was swallowed into {}", out.s);
}
#[test]
fn the_crowd_leans_against_mispricing() {
assert!(crowd_lean(0.5, 0.0) < 0.0, "overvalued should draw selling");
assert!(
crowd_lean(-0.5, 0.0) > 0.0,
"undervalued should draw buying"
);
}
#[test]
fn the_crowd_is_flat_at_fair_value_with_no_momentum() {
assert_eq!(crowd_lean(0.0, 0.0), 0.0);
}
#[test]
fn the_crowd_chases_yesterdays_re_rating() {
assert!(crowd_lean(0.0, 0.02) > 0.0);
assert!(crowd_lean(0.0, -0.02) < 0.0);
}
#[test]
fn the_crowd_lean_is_bounded_including_for_pathological_inputs() {
for (s, momentum) in [
(5.0, 5.0),
(-5.0, -5.0),
(0.9, 0.5),
(-0.9, -0.5),
(1e9, 1e9),
(100.0, -100.0),
] {
let lean = crowd_lean(s, momentum);
assert!(lean.abs() <= CROWD_LEAN_CAP, "lean {lean} escaped its cap");
}
}
#[test]
fn the_crowd_lean_stays_well_inside_the_daily_shock_cap() {
const { assert!(CROWD_LEAN_CAP < DAILY_SHOCK_CAP / 2.0) };
}
#[test]
fn the_valuation_lean_dominates_the_momentum_lean_at_realistic_magnitudes() {
let valuation = crowd_lean(-0.10, 0.0).abs();
let momentum = crowd_lean(0.0, 0.015).abs();
assert!(
valuation >= momentum * 2.0,
"valuation lean {valuation} should be at least twice the momentum lean {momentum}"
);
}
#[test]
fn the_crowd_adjusted_analytics_stay_in_sync_with_the_actual_gains() {
let (r1, r2) = characteristic_root_moduli(
Some(MISPRICING_PHI - CROWD_VALUATION_GAIN),
Some(MOMENTUM_THETA + CROWD_MOMENTUM_GAIN),
);
let (c1, c2) = crowd_adjusted_root_moduli();
assert_eq!(c1.to_bits(), r1.to_bits());
assert_eq!(c2.to_bits(), r2.to_bits());
}
#[test]
fn a_negative_zero_s_yields_positive_zero() {
assert_eq!(crowd_lean(-0.0, 0.0).to_bits(), 0.0f64.to_bits());
}
#[test]
fn opposing_infinities_yield_a_nan_that_the_clamp_passes_through() {
assert!(crowd_lean(f64::INFINITY, f64::INFINITY).is_nan());
}
#[test]
fn a_zero_mispricing_prices_at_fair_value() {
assert_eq!(apply_mispricing(100.0, 0.0), 100.0);
}
#[test]
fn the_price_floor_holds_even_for_a_negative_fair_value() {
assert_eq!(apply_mispricing(-100.0, 0.0), 0.01);
assert_eq!(apply_mispricing(0.0, 0.0), 0.01);
}
#[test]
fn a_nan_propagates_rather_than_becoming_the_floor() {
assert!(apply_mispricing(f64::NAN, 0.0).is_nan());
}
#[test]
fn s_is_clamped_before_the_exponential() {
assert_eq!(
apply_mispricing(100.0, 50.0),
apply_mispricing(100.0, MISPRICING_CAP)
);
}
}
pub fn stationary_variance(
phi: Option<f64>,
theta: Option<f64>,
innovation_variance: f64,
) -> Option<f64> {
let phi = phi.unwrap_or(MISPRICING_PHI);
let theta = theta.unwrap_or(MOMENTUM_THETA);
let a1 = phi + theta;
let a2 = -theta;
let denominator = (1.0 + a2) * ((1.0 - a2) * (1.0 - a2) - a1 * a1);
if !(denominator > 0.0) || !innovation_variance.is_finite() || innovation_variance < 0.0 {
return None;
}
let gamma0 = innovation_variance * (1.0 - a2) / denominator;
if gamma0.is_finite() && gamma0 >= 0.0 {
Some(gamma0)
} else {
None
}
}
pub fn stationary_sigma(phi: Option<f64>, theta: Option<f64>, innovation_sigma: f64) -> Option<f64> {
stationary_variance(phi, theta, innovation_sigma * innovation_sigma)
.map(crate::mathx::sqrt)
}
#[cfg(test)]
mod stationary_tests {
use super::*;
use crate::rng::GameRng;
#[test]
fn the_analytic_variance_matches_a_simulated_one() {
let sigma = 0.012;
let analytic = stationary_sigma(None, None, sigma).expect("stationary");
let mut rng = GameRng::new(4242, 99);
let mut state = MispricingState::default();
for _ in 0..5_000 {
state = step_mispricing(
&state,
&MispricingInputs { innovation: rng.next_normal() * sigma, shock: 0.0 },
);
}
let (mut sum, mut sum_sq, n) = (0.0, 0.0, 400_000);
for _ in 0..n {
state = step_mispricing(
&state,
&MispricingInputs { innovation: rng.next_normal() * sigma, shock: 0.0 },
);
sum += state.s;
sum_sq += state.s * state.s;
}
let mean = sum / n as f64;
let simulated = crate::mathx::sqrt(sum_sq / n as f64 - mean * mean);
let ratio = simulated / analytic;
assert!(
ratio > 0.9 && ratio < 1.1,
"analytic {analytic:.6} vs simulated {simulated:.6} (ratio {ratio:.4})"
);
}
#[test]
fn a_bigger_innovation_gives_a_wider_distribution() {
let small = stationary_sigma(None, None, 0.005).unwrap();
let large = stationary_sigma(None, None, 0.020).unwrap();
assert!((large / small - 4.0).abs() < 1e-9);
}
#[test]
fn non_stationary_parameters_return_none_rather_than_a_number() {
assert!(stationary_variance(Some(1.0), Some(0.0), 0.0001).is_none());
assert!(stationary_variance(Some(1.5), Some(0.25), 0.0001).is_none());
}
#[test]
fn the_shipped_parameters_are_stationary() {
assert!(stationary_sigma(None, None, 0.015).is_some());
let (a, b) = characteristic_root_moduli(None, None);
assert!(a < 1.0 && b < 1.0);
}
}