use crate::mathx;
pub const JUMP_COMPONENT_KEY: &str = "jump";
pub const OVERNIGHT_COMPONENT_KEY: &str = "overnight";
pub const JUMP_SLOT: usize = S_COMPONENT_KEYS.len();
pub const OVERNIGHT_SLOT: usize = JUMP_SLOT + 1;
pub const FAIR_VALUE_SLOT: usize = OVERNIGHT_SLOT + 1;
pub const DIVIDEND_SLOT: usize = FAIR_VALUE_SLOT + 1;
pub const COMPONENT_COUNT: usize = DIVIDEND_SLOT + 1;
pub fn sector_loading_for(params: &crate::params::ModelParams, beta: f64) -> f64 {
if params.sector_loading_beta_slope == 0.0 {
params.sector_loading
} else {
let b = beta;
params.sector_loading * (1.0 + params.sector_loading_beta_slope * (b - 1.0))
}
}
pub fn idio_scale_for(params: &crate::params::ModelParams, beta: f64) -> f64 {
if params.idio_sigma_beta_exponent == 0.0 {
params.idio_sigma_scale
} else if beta <= 0.0 {
params.idio_sigma_scale
} else {
let (lo, hi) = IDIO_BETA_BOUNDS;
params.idio_sigma_scale
* mathx::clamp(mathx::pow(beta, params.idio_sigma_beta_exponent), lo, hi)
}
}
pub const CRISIS_EPICENTRE_MARKET_SHARE: f64 = 0.3916;
pub const CRISIS_EPICENTRE_SECTOR_SHARE: f64 = 0.1019;
pub fn crisis_epicentre_gains(extra: f64) -> (f64, f64) {
let (up2, down2) = crisis_epicentre_gain_squares(extra);
(
mathx::sqrt(mathx::max(0.0, up2)),
mathx::sqrt(mathx::max(0.0, down2)),
)
}
pub fn crisis_epicentre_gain_squares(extra: f64) -> (f64, f64) {
let e2 = extra * extra;
let m = CRISIS_EPICENTRE_MARKET_SHARE;
let w = CRISIS_EPICENTRE_SECTOR_SHARE;
let a = e2 - 1.0;
let down2 = ((1.0 - m) - m * w * a) / ((1.0 - m) * (1.0 + w * a));
let up2 = m * a / (1.0 - m) + e2 * down2;
(up2, down2)
}
pub fn crisis_epicentre_extra_bounds() -> (f64, f64) {
let m = CRISIS_EPICENTRE_MARKET_SHARE;
let w = CRISIS_EPICENTRE_SECTOR_SHARE;
(
mathx::sqrt(m * (1.0 - w) / (1.0 - m * w)),
mathx::sqrt(1.0 + (1.0 - m) / (m * w)),
)
}
pub fn idio_suppress_scales(suppress: f64) -> (f64, f64) {
let down = mathx::clamp(1.0 - suppress, 0.0, mathx::sqrt(2.0));
(down, mathx::sqrt(mathx::max(2.0 - down * down, 0.0)))
}
pub const S_COMPONENT_KEYS: [&str; 8] = [
"reversion",
"momentum",
"crowd_lean",
"company_news",
"order_flow_impact",
"short_squeeze_effect",
"random_noise",
"circuit_breaker",
];
pub const FAIR_VALUE_COMPONENT_KEY: &str = "fair_value_shift";
pub const DIVIDEND_COMPONENT_KEY: &str = "dividend";
pub const TICK_COMPONENT_COUNT: usize = S_COMPONENT_KEYS.len() + 1;
pub const TICK_FAIR_VALUE: usize = S_COMPONENT_KEYS.len();
pub const fn attribution_slot_for_tick(k: usize) -> usize {
if k == TICK_FAIR_VALUE { FAIR_VALUE_SLOT } else { k }
}
pub const ORDER_FLOW_COEFFICIENT: f64 = 50.0;
pub const REFERENCE_DAILY_VOLUME: f64 = 1_000_000.0;
pub const NEWS_SECTOR_WEIGHT: f64 = 0.5;
pub const NEWS_MARKET_WEIGHT: f64 = 0.3;
pub const CRASH_AMPLIFIER_THRESHOLD: f64 = 2.0;
pub const CRASH_AMPLIFIER_SLOPE: f64 = 0.2;
pub const INFORMED_FLOW_FRACTION: f64 = 0.35;
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct SharedFactors {
pub market_factor: f64,
pub sector_factors: Vec<(String, f64)>,
pub crisis_spike: f64,
pub prev_day_down: bool,
pub market_sigma_tick: f64,
pub crisis_epicentre: Option<String>,
}
impl SharedFactors {
fn sector(&self, sector: &str) -> f64 {
self.sector_factors
.iter()
.find(|(k, _)| k == sector)
.map(|(_, v)| *v)
.unwrap_or(0.0)
}
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct NewsEvent {
pub company_id: Option<String>,
pub sector: Option<String>,
pub price_impact: Option<f64>,
}
pub const NEWS_SESSION_TICKS: f64 = 390.0;
fn absorbed_component(n: f64, half_life: f64) -> f64 {
absorbed_component_over(n, half_life, NEWS_SESSION_TICKS)
}
fn absorbed_component_over(n: f64, half_life: f64, horizon: f64) -> f64 {
if n <= 0.0 {
return 0.0;
}
if n >= horizon {
return 1.0;
}
if half_life == 0.0 {
return n / horizon;
}
let ln2 = core::f64::consts::LN_2;
let at = 1.0 - mathx::exp(-ln2 * n / half_life);
let full = 1.0 - mathx::exp(-ln2 * horizon / half_life);
at / full
}
pub fn news_absorbed_share(params: &crate::params::ModelParams, n: f64) -> f64 {
let fast = absorbed_component(n, params.news_absorption_half_life);
let d = params.news_absorption_drift_share;
if d == 0.0 {
return fast;
}
let drift = absorbed_component(n, params.news_absorption_drift_half_life);
(1.0 - d) * fast + d * drift
}
pub fn news_absorption_weight(params: &crate::params::ModelParams,
minutes_since_open: i64) -> f64 {
if !(0..390).contains(&minutes_since_open) {
return 0.0;
}
let m = minutes_since_open as f64;
NEWS_SESSION_TICKS
* (news_absorbed_share(params, m + 1.0) - news_absorbed_share(params, m))
}
pub const NEWS_RELEASE_PROFILE_COUNTS: [f64; 13] =
[65.0, 103.0, 85.0, 93.0, 65.0, 79.0, 71.0, 96.0, 110.0, 129.0, 125.0, 235.0, 116.0];
pub fn news_release_minute(v: f64) -> f64 {
let total: f64 = NEWS_RELEASE_PROFILE_COUNTS.iter().sum();
let width = NEWS_SESSION_TICKS / NEWS_RELEASE_PROFILE_COUNTS.len() as f64;
let target = v.clamp(0.0, 1.0) * total;
let mut below = 0.0;
for (k, c) in NEWS_RELEASE_PROFILE_COUNTS.iter().enumerate() {
if target < below + c {
return (k as f64 + (target - below) / c) * width;
}
below += c;
}
NEWS_SESSION_TICKS - 1e-9
}
pub fn news_release_weight(params: &crate::params::ModelParams,
minutes_since_open: i64, release: f64) -> f64 {
if !(0..390).contains(&minutes_since_open) {
return 0.0;
}
let m = minutes_since_open as f64;
let horizon = NEWS_SESSION_TICKS - release;
let share = |n: f64| {
let fast = absorbed_component_over(n, params.news_absorption_half_life, horizon);
let d = params.news_absorption_drift_share;
if d == 0.0 {
return fast;
}
let drift = absorbed_component_over(n, params.news_absorption_drift_half_life, horizon);
(1.0 - d) * fast + d * drift
};
NEWS_SESSION_TICKS * (share(m + 1.0 - release) - share(m - release))
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct FactorCompany {
pub id: String,
pub sector: String,
pub beta: Option<f64>,
pub market_cap: f64,
pub avg_volume: f64,
pub shares_outstanding: f64,
pub short_interest: f64,
pub float: f64,
pub garch_variance: f64,
pub last_daily_return: Option<f64>,
}
impl FactorCompany {
pub fn new(id: impl Into<String>, sector: impl Into<String>) -> Self {
FactorCompany {
id: id.into(),
sector: sector.into(),
beta: None,
market_cap: 0.0,
avg_volume: 0.0,
shares_outstanding: 0.0,
short_interest: 0.0,
float: 0.0,
garch_variance: 0.0,
last_daily_return: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct LiveFactors {
pub company_news: f64,
pub company_news_market: f64,
pub order_flow_impact: f64,
pub short_squeeze_effect: f64,
pub random_noise: f64,
pub noise_market: f64,
pub noise_market_linear: f64,
pub noise_sector: f64,
pub noise_idio: f64,
pub noise_idio_unit: f64,
}
pub const SIZE_EFFECT_REFERENCE_B: f64 = 25.0;
pub const IDIO_BETA_BOUNDS: (f64, f64) = (0.1, 4.0);
pub const SIZE_EFFECT_BOUNDS: (f64, f64) = (0.5, 3.0);
pub fn cap_size_multiplier_with(params: &crate::params::ModelParams,
market_cap: f64) -> f64 {
let stepped = cap_size_multiplier(market_cap);
let s = params.size_effect_smoothness;
if s == 0.0 {
return stepped;
}
let mcap_billions = market_cap / 1e9;
if mcap_billions <= 0.0 {
return stepped;
}
let ratio = mcap_billions / SIZE_EFFECT_REFERENCE_B;
let (lo, hi) = SIZE_EFFECT_BOUNDS;
let smooth = mathx::clamp(
mathx::pow(ratio, -params.size_effect_exponent), lo, hi);
(1.0 - s) * stepped + s * smooth
}
pub fn cap_size_multiplier(market_cap: f64) -> f64 {
let mcap_billions = market_cap / 1e9;
if mcap_billions > 50.0 {
0.8
} else if mcap_billions > 10.0 {
1.0
} else if mcap_billions > 1.0 {
1.3
} else {
1.6
}
}
pub fn news_terms(
id: &str,
sector: &str,
news: &[NewsEvent],
crisis_spike: f64,
params: &crate::params::ModelParams,
) -> (f64, f64) {
let mut company_news = 0.0;
let mut company_news_market = 0.0;
for event in news {
let impact = truthy(event.price_impact);
if event.company_id.as_deref() == Some(id) {
company_news += impact;
} else if event.company_id.is_some()
&& event.sector.as_deref() == Some(sector)
{
let base = if impact < 0.0 {
params.news_peer_weight_down
} else {
params.news_peer_weight
};
let weight = if params.news_peer_vix_coupling == 0.0 {
base
} else {
base * (1.0 + params.news_peer_vix_coupling * crisis_spike)
};
if weight != 0.0 {
company_news += impact * weight;
}
} else if event.sector.as_deref() == Some(sector)
&& event.company_id.is_none()
{
company_news += impact * params.news_sector_weight;
} else if event.company_id.is_none() && event.sector.is_none() {
company_news += impact * params.news_market_weight;
company_news_market += impact * params.news_market_weight;
}
}
(company_news, company_news_market)
}
pub fn calculate_live_factors(
company: &FactorCompany,
news: &[NewsEvent],
order_imbalance: f64,
volatility_multiplier: f64,
shared: &SharedFactors,
params: &crate::params::ModelParams,
rng: &mut impl crate::rng::Rng,
) -> LiveFactors {
let (company_news, company_news_market) = news_terms(
company.id.as_str(), company.sector.as_str(), news, shared.crisis_spike, params);
let liquidity_factor = if params.order_flow_depth_law == 0.0 {
let avg_daily_volume =
mathx::max(company.avg_volume, company.shares_outstanding * 0.005);
1.0 / mathx::max(avg_daily_volume / 390.0, 100.0)
} else {
1.0 / (REFERENCE_DAILY_VOLUME / 390.0)
};
let order_flow_impact = order_imbalance
* liquidity_factor
* params.order_flow_coefficient
* params.informed_flow_fraction;
let beta = company.beta.unwrap_or(1.0);
let cap_mult = cap_size_multiplier_with(params, company.market_cap);
let factor_through = if params.market_beta_down_asym == 0.0
|| shared.market_factor >= 0.0
{
beta * shared.market_factor
} else {
beta * shared.market_factor * (1.0 + params.market_beta_down_asym)
};
let factor_through = if params.market_beta_down_asym_lag == 0.0
|| !shared.prev_day_down
{
factor_through
} else {
factor_through * (1.0 + params.market_beta_down_asym_lag)
};
let market_component = if params.crisis_blend_source == 0.0 {
factor_through
} else {
let injection = params.crisis_blend_source * params.crisis_blend_gain
* shared.crisis_spike * shared.market_factor;
let injection = if params.crisis_blend_variance_damp == 0.0 {
injection
} else {
let base = params.market_factor_sigma / mathx::sqrt(390.0);
let rel = mathx::max(shared.market_factor.abs() / base, 1e-6);
injection * mathx::clamp(
mathx::pow(rel, -params.crisis_blend_variance_damp), 0.1, 10.0)
};
factor_through + injection
};
let sector_loading = sector_loading_for(params, beta);
let sector_component = sector_loading * shared.sector(&company.sector);
let epicentre_gain: Option<f64> = match shared.crisis_epicentre.as_deref() {
Some(key) => {
let (up, down) = crisis_epicentre_gains(params.crisis_epicentre_extra);
Some(if key == company.sector.as_str() { up } else { down })
}
None => None,
};
let sector_component = match epicentre_gain {
None => sector_component,
Some(g) => sector_component * g,
};
let daily_sigma = mathx::sqrt(mathx::max(company.garch_variance, params.idio_sigma_floor));
let idio_scale = idio_scale_for(params, beta);
let idiosyncratic_sigma = daily_sigma * idio_scale / mathx::sqrt(390.0);
let idiosyncratic_noise =
rng.next_normal() * idiosyncratic_sigma * cap_mult * volatility_multiplier;
let idio_down_suppress_scale = if params.market_idio_down_suppress == 0.0 {
1.0
} else {
let (down, up) = idio_suppress_scales(params.market_idio_down_suppress);
if shared.market_factor < 0.0 {
down
} else {
up
}
};
let idiosyncratic_noise = if params.market_idio_down_suppress == 0.0 {
idiosyncratic_noise
} else {
idiosyncratic_noise * idio_down_suppress_scale
};
let idiosyncratic_noise = match epicentre_gain {
None => idiosyncratic_noise,
Some(g) => idiosyncratic_noise * g,
};
let shock_magnitude = if params.crash_amplifier_conditional_sigma == 0.0 {
shared.market_factor.abs() / (params.market_factor_sigma / mathx::sqrt(390.0))
} else if shared.market_sigma_tick > 0.0 {
shared.market_factor.abs() / shared.market_sigma_tick
} else {
0.0
};
let crash_amplifier = if shock_magnitude > params.crash_amplifier_threshold {
1.0 + (shock_magnitude - params.crash_amplifier_threshold) * params.crash_amplifier_slope
} else {
1.0
};
let tilt_recentre = if params.market_beta_down_asym_recentre == 0.0
|| params.market_beta_down_asym == 0.0
{
0.0
} else {
params.market_beta_down_asym_recentre
* params.market_beta_down_asym
* beta
* shared.market_sigma_tick
/ SQRT_TWO_PI
};
let tilt_recentre = if params.market_beta_down_asym_lag_recentre == 0.0
|| params.market_beta_down_asym_lag == 0.0
|| !shared.prev_day_down
{
tilt_recentre
} else {
tilt_recentre
* (1.0 + params.market_beta_down_asym_lag_recentre * params.market_beta_down_asym_lag)
};
let random_noise =
market_component * crash_amplifier + tilt_recentre + sector_component + idiosyncratic_noise;
let noise_market = market_component * crash_amplifier + tilt_recentre;
let noise_sector = sector_component;
let noise_idio = idiosyncratic_noise;
let noise_idio_unit =
idio_scale / mathx::sqrt(390.0) * cap_mult * volatility_multiplier * idio_down_suppress_scale;
let noise_idio_unit = match epicentre_gain {
None => noise_idio_unit,
Some(g) => noise_idio_unit * g,
};
let mut short_squeeze_effect = 0.0;
let short_interest_ratio = company.short_interest / mathx::max(1.0, company.float);
let daily_return = company.last_daily_return.unwrap_or(0.0);
if short_interest_ratio > 0.2 && daily_return > 0.03 {
short_squeeze_effect = short_interest_ratio * daily_return * 0.5;
short_squeeze_effect = mathx::min(0.02, short_squeeze_effect);
}
let (down_gate, down_a, down_b, down_c, down_d,
up_gate, up_a, up_b, up_c, up_d) =
if params.cascade_symmetry == 0.0 {
(0.02, 0.008, 0.005, 0.003, 0.001,
0.03, 0.006, 0.004, 0.002, 0.000)
} else {
let g = params.cascade_symmetry;
(0.02 + 0.005 * g, 0.008 - 0.001 * g, 0.005 - 0.0005 * g,
0.003 - 0.0005 * g, 0.001 - 0.0005 * g,
0.03 - 0.005 * g, 0.006 + 0.001 * g, 0.004 + 0.0005 * g,
0.002 + 0.0005 * g, 0.000 + 0.0005 * g)
};
if daily_return < -down_gate {
let drop = daily_return.abs();
let stop_cascade = if drop > 0.07 {
down_a
} else if drop > 0.05 {
down_b
} else if drop > 0.03 {
down_c
} else {
down_d
};
short_squeeze_effect -= stop_cascade;
}
if daily_return > up_gate && short_interest_ratio > 0.1 {
let buy_cascade = if daily_return > 0.07 {
up_a
} else if daily_return > 0.05 {
up_b
} else if daily_return > 0.03 {
up_c
} else {
up_d
};
short_squeeze_effect += buy_cascade;
}
let short_squeeze_effect = if params.cascade_gain == 1.0 {
short_squeeze_effect
} else {
short_squeeze_effect * params.cascade_gain
};
LiveFactors {
company_news,
company_news_market,
order_flow_impact,
short_squeeze_effect,
random_noise,
noise_market,
noise_market_linear: beta * shared.market_factor,
noise_sector,
noise_idio,
noise_idio_unit,
}
}
fn truthy(value: Option<f64>) -> f64 {
match value {
Some(x) if x != 0.0 && !x.is_nan() => x,
_ => 0.0,
}
}
const SQRT_TWO_PI: f64 = 2.5066282746310002;
pub fn order_imbalance(buy_vol: f64, sell_vol: f64, avg_volume: f64) -> f64 {
let total_vol = buy_vol + sell_vol;
let avg_minute_vol = mathx::max(truthy_or(avg_volume, 1_000_000.0) / 390.0, 100.0);
let volume_ratio = mathx::min(total_vol / avg_minute_vol, 10.0);
let raw_imbalance = if total_vol > 0.0 {
(buy_vol - sell_vol) / total_vol
} else {
0.0
};
raw_imbalance * mathx::max(0.2, volume_ratio * 0.15)
}
fn truthy_or(value: f64, fallback: f64) -> f64 {
if value != 0.0 && !value.is_nan() {
value
} else {
fallback
}
}
const PARTICIPATION_KNEE: f64 = 10.0;
const PARTICIPATION_SLOPE: f64 = 0.15;
fn participation_multiplier(participation: f64) -> f64 {
if participation <= PARTICIPATION_KNEE {
PARTICIPATION_SLOPE * participation
} else {
PARTICIPATION_SLOPE
* PARTICIPATION_KNEE
* mathx::sqrt(participation / PARTICIPATION_KNEE)
}
}
pub fn order_imbalance_with(
params: &crate::params::ModelParams,
buy_vol: f64,
sell_vol: f64,
avg_volume: f64,
) -> f64 {
if params.order_flow_impact_law == 0.0 {
return order_imbalance(buy_vol, sell_vol, avg_volume);
}
let total_vol = buy_vol + sell_vol;
if !(total_vol > 0.0) {
return 0.0;
}
let avg_minute_vol = mathx::max(truthy_or(avg_volume, 1_000_000.0) / 390.0, 100.0);
let raw_imbalance = if total_vol.is_finite() {
(buy_vol - sell_vol) / total_vol
} else {
(0.5 * buy_vol - 0.5 * sell_vol) / (0.5 * buy_vol + 0.5 * sell_vol)
};
let participation = total_vol / avg_minute_vol;
let participation = if participation.is_finite() { participation } else { f64::MAX };
raw_imbalance * participation_multiplier(participation)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rng::Rng;
struct Fixed(f64);
impl Rng for Fixed {
fn next_f64(&mut self) -> f64 {
self.0
}
fn next_normal(&mut self) -> f64 {
self.0
}
}
fn company() -> FactorCompany {
FactorCompany {
id: "ACME".into(),
sector: "technology".into(),
beta: Some(1.0),
market_cap: 20e9,
avg_volume: 1e6,
shares_outstanding: 1e8,
short_interest: 0.0,
float: 1e8,
garch_variance: 0.015 * 0.015,
last_daily_return: Some(0.0),
}
}
fn shared() -> SharedFactors {
SharedFactors {
market_factor: 0.0,
sector_factors: vec![("technology".into(), 0.0)],
crisis_spike: 0.0,
prev_day_down: false,
market_sigma_tick: crate::params::PT_V1.market_factor_sigma
/ crate::mathx::sqrt(390.0),
crisis_epicentre: None,
}
}
fn factors(
c: &FactorCompany,
news: &[NewsEvent],
imbalance: f64,
s: &SharedFactors,
) -> LiveFactors {
calculate_live_factors(c, news, imbalance, 1.0, s, &crate::params::PT_V1, &mut Fixed(0.0))
}
fn factors_with(
p: &crate::params::ModelParams,
c: &FactorCompany,
news: &[NewsEvent],
imbalance: f64,
s: &SharedFactors,
) -> LiveFactors {
calculate_live_factors(c, news, imbalance, 1.0, s, p, &mut Fixed(0.0))
}
#[test]
fn exactly_one_normal_is_drawn_however_the_branches_fall() {
struct Counting(usize);
impl Rng for Counting {
fn next_f64(&mut self) -> f64 {
panic!("the factor subset must not draw uniforms")
}
fn next_normal(&mut self) -> f64 {
self.0 += 1;
0.0
}
}
for daily_return in [-0.10, -0.03, 0.0, 0.05, 0.10] {
for short_interest in [0.0, 3e7] {
let mut c = company();
c.last_daily_return = Some(daily_return);
c.short_interest = short_interest;
let mut rng = Counting(0);
calculate_live_factors(&c, &[], 0.5, 1.0, &shared(), &crate::params::PT_V1, &mut rng);
assert_eq!(rng.0, 1, "return {daily_return}, si {short_interest}");
}
}
}
#[test]
fn news_weights_are_company_then_sector_then_market_wide() {
let c = company();
let at = |e: NewsEvent| factors(&c, &[e], 0.0, &shared()).company_news;
assert_eq!(
at(NewsEvent {
company_id: Some("ACME".into()),
sector: None,
price_impact: Some(0.1)
}),
0.1
);
assert_eq!(
at(NewsEvent {
company_id: None,
sector: Some("technology".into()),
price_impact: Some(0.1)
}),
0.1 * 0.5
);
assert_eq!(
at(NewsEvent {
company_id: None,
sector: None,
price_impact: Some(0.1)
}),
0.1 * 0.3
);
}
fn peer_event(impact: f64) -> NewsEvent {
NewsEvent {
company_id: Some("OTHER".into()),
sector: Some("technology".into()),
price_impact: Some(impact),
}
}
fn with_peer_weights(up: f64, down: f64) -> crate::params::ModelParams {
crate::params::PT_V1
.with_override("news_peer_weight", up)
.unwrap()
.with_override("news_peer_weight_down", down)
.unwrap()
}
#[test]
fn an_event_for_another_company_is_ignored_at_the_shipped_weight() {
let c = company();
assert_eq!(factors(&c, &[peer_event(0.5)], 0.0, &shared()).company_news, 0.0);
}
#[test]
fn a_peers_good_news_lifts_this_name_when_transfer_is_on() {
let c = company();
let p = with_peer_weights(0.2, 0.5);
let got =
calculate_live_factors(&c, &[peer_event(0.5)], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
.company_news;
assert_eq!(got, 0.5 * 0.2);
}
#[test]
fn bad_news_transfers_on_its_own_weight() {
let c = company();
let p = with_peer_weights(0.2, 0.5);
let up =
calculate_live_factors(&c, &[peer_event(0.4)], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
.company_news;
let down = calculate_live_factors(
&c,
&[peer_event(-0.4)],
0.0,
1.0,
&shared(),
&p,
&mut Fixed(0.0),
)
.company_news;
assert_eq!(up, 0.4 * 0.2);
assert_eq!(down, -0.4 * 0.5);
assert!(down.abs() > up.abs(), "bad news must transfer more strongly");
}
#[test]
fn the_named_company_still_takes_the_full_impact_not_the_peer_weight() {
let c = company();
let p = with_peer_weights(0.2, 0.5);
let own = NewsEvent {
company_id: Some(c.id.clone()),
sector: Some("technology".into()),
price_impact: Some(0.5),
};
let got =
calculate_live_factors(&c, &[own], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
.company_news;
assert_eq!(got, 0.5);
}
#[test]
fn transfer_does_not_reach_a_different_sector() {
let c = company(); let p = with_peer_weights(0.2, 0.5);
let elsewhere = NewsEvent {
company_id: Some("OTHER".into()),
sector: Some("energy".into()),
price_impact: Some(0.5),
};
let got =
calculate_live_factors(&c, &[elsewhere], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
.company_news;
assert_eq!(got, 0.0);
}
#[test]
fn news_accumulates_across_events() {
let c = company();
let news = vec![
NewsEvent {
company_id: Some("ACME".into()),
sector: None,
price_impact: Some(0.1),
},
NewsEvent {
company_id: None,
sector: None,
price_impact: Some(0.1),
},
];
assert_eq!(factors(&c, &news, 0.0, &shared()).company_news, 0.1 + 0.03);
}
#[test]
fn an_absent_or_zero_impact_contributes_nothing() {
let c = company();
for impact in [None, Some(0.0), Some(f64::NAN)] {
let e = NewsEvent {
company_id: Some("ACME".into()),
sector: None,
price_impact: impact,
};
assert_eq!(
factors(&c, &[e], 0.0, &shared()).company_news,
0.0,
"{impact:?}"
);
}
}
#[test]
fn a_thin_stock_takes_more_impact_from_the_same_imbalance() {
let mut thin = company();
thin.avg_volume = 50_000.0;
thin.shares_outstanding = 1e6;
let liquid = company();
assert!(
factors(&thin, &[], 0.5, &shared()).order_flow_impact
> factors(&liquid, &[], 0.5, &shared()).order_flow_impact
);
}
#[test]
fn the_half_moment_denominator_is_sqrt_two_pi() {
assert_eq!(SQRT_TWO_PI, mathx::sqrt(2.0 * std::f64::consts::PI));
}
#[test]
fn recentring_returns_the_mean_the_downside_tilt_injects() {
let mut params = crate::params::PT_V16;
assert_ne!(params.market_beta_down_asym, 0.0, "the tilt must be on");
let sigma_tick = params.market_factor_sigma / mathx::sqrt(390.0);
let grid: Vec<f64> = (1..=400)
.map(|k| k as f64 * 0.01)
.flat_map(|z| [z, -z])
.collect();
let mean_of = |p: &crate::params::ModelParams| -> f64 {
let company = company();
let mut total = 0.0;
let mut weight_sum = 0.0;
for z in &grid {
let w = mathx::exp(-z * z / 2.0);
let s = SharedFactors {
market_factor: z * sigma_tick,
sector_factors: vec![("technology".into(), 0.0)],
crisis_spike: 0.0,
prev_day_down: false,
market_sigma_tick: sigma_tick,
crisis_epicentre: None,
};
total += w * factors_with(p, &company, &[], 0.0, &s).random_noise;
weight_sum += w;
}
total / weight_sum
};
let injected = mean_of(¶ms);
assert!(
injected < 0.0,
"the tilt should inject a NEGATIVE mean, got {injected}"
);
params.market_beta_down_asym_recentre = 1.0;
let corrected = mean_of(¶ms);
let residual = corrected / injected;
assert!(
residual.abs() < 0.05,
"recentring left {residual} of the injected mean, expected \
only the amplifier's few per cent"
);
assert!(corrected <= 0.0, "recentring overshot to {corrected}");
}
#[test]
fn recentring_is_inert_without_the_tilt_it_corrects() {
let company = company();
let s = shared();
let mut params = crate::params::PT_V16;
params.market_beta_down_asym = 0.0;
let without = factors_with(¶ms, &company, &[], 0.0, &s).random_noise;
params.market_beta_down_asym_recentre = 1.0;
let with = factors_with(¶ms, &company, &[], 0.0, &s).random_noise;
assert_eq!(without, with);
}
#[test]
fn every_preset_before_pt_v18_is_bit_identical_under_the_new_dial() {
for name in crate::params::ModelParams::preset_names() {
let p = crate::params::ModelParams::preset(name).expect("named");
if *name == "pt-v22" {
continue;
}
if matches!(*name, "pt-v18" | "pt-v19" | "pt-v20" | "pt-v21") {
assert_eq!(p.market_beta_down_asym_recentre, 1.0, "{name}");
continue;
}
assert_eq!(p.market_beta_down_asym_recentre, 0.0, "{name}");
}
}
fn idio_only_company() -> FactorCompany {
let mut c = company();
c.beta = Some(0.0);
c
}
fn shared_at(z: f64) -> SharedFactors {
let sigma_tick = crate::params::PT_V1.market_factor_sigma / mathx::sqrt(390.0);
SharedFactors {
market_factor: z * sigma_tick,
sector_factors: vec![("technology".into(), 0.0)],
crisis_spike: 0.0,
prev_day_down: false,
market_sigma_tick: sigma_tick,
crisis_epicentre: None,
}
}
fn with_suppress(c: f64) -> crate::params::ModelParams {
crate::params::PT_V1.with_override("market_idio_down_suppress", c).unwrap()
}
#[test]
fn the_two_scales_average_to_one_to_within_an_ulp() {
let mut worst: f64 = 0.0;
for k in 0..=200 {
let c = k as f64 * 0.005; let (down, up) = idio_suppress_scales(c);
let residual = (down * down + up * up - 2.0).abs();
worst = mathx::max(worst, residual);
}
assert!(worst <= 4.0 * f64::EPSILON * 2.0,
"the two squared scales are off by {worst}, not by rounding");
}
#[test]
fn the_scales_are_bounded_by_the_constructions_own_domain() {
assert_eq!(idio_suppress_scales(0.0), (1.0, 1.0));
let (down, up) = idio_suppress_scales(1.0);
assert_eq!(down, 0.0);
assert_eq!(up, mathx::sqrt(2.0));
for c in [-5.0, -0.5, 1.5, 9.0] {
let (down, up) = idio_suppress_scales(c);
assert!(down.is_finite() && up.is_finite(), "c {c}: ({down}, {up})");
assert!(down >= 0.0 && up >= 0.0, "c {c}: ({down}, {up})");
}
}
#[test]
fn the_reallocation_is_inert_at_zero_on_both_half_lines() {
let c = idio_only_company();
for z in [-3.0, -1.0, -0.25, 0.25, 1.0, 3.0] {
let s = shared_at(z);
let base = calculate_live_factors(
&c, &[], 0.0, 1.0, &s, &crate::params::PT_V1, &mut Fixed(0.7));
let dialled = calculate_live_factors(
&c, &[], 0.0, 1.0, &s, &with_suppress(0.0), &mut Fixed(0.7));
assert_eq!(base.random_noise, dialled.random_noise, "z {z}");
}
}
#[test]
fn a_down_tick_is_suppressed_and_an_up_tick_is_inflated() {
let company = idio_only_company();
let p = with_suppress(0.15);
let base = |z: f64| calculate_live_factors(
&company, &[], 0.0, 1.0, &shared_at(z), &crate::params::PT_V1,
&mut Fixed(1.0)).random_noise;
let dialled = |z: f64| calculate_live_factors(
&company, &[], 0.0, 1.0, &shared_at(z), &p, &mut Fixed(1.0)).random_noise;
let (down, up) = idio_suppress_scales(0.15);
assert_eq!(dialled(-1.5), base(-1.5) * down);
assert_eq!(dialled(1.5), base(1.5) * up);
assert!(down < 1.0 && up > 1.0, "({down}, {up}) is not a reallocation");
}
#[test]
fn the_reallocation_moves_no_first_moment_at_any_tick() {
let company = idio_only_company();
for c in [0.05, 0.15, 0.40, 1.0] {
let p = with_suppress(c);
for z in [-3.0, -0.5, 0.5, 3.0] {
let s = shared_at(z);
let plus = calculate_live_factors(
&company, &[], 0.0, 1.0, &s, &p, &mut Fixed(1.0)).random_noise;
let minus = calculate_live_factors(
&company, &[], 0.0, 1.0, &s, &p, &mut Fixed(-1.0)).random_noise;
assert_eq!(plus + minus, 0.0, "c {c}, z {z}");
}
}
}
#[test]
fn the_reallocation_holds_the_second_moment_over_a_symmetric_factor() {
let company = idio_only_company();
let grid: Vec<f64> = (1..=400).map(|k| k as f64 * 0.01)
.flat_map(|z| [z, -z]).collect();
let mean_square = |p: &crate::params::ModelParams| -> f64 {
let mut total = 0.0;
let mut weight = 0.0;
for z in &grid {
let w = mathx::exp(-z * z / 2.0);
let noise = calculate_live_factors(
&company, &[], 0.0, 1.0, &shared_at(*z), p, &mut Fixed(1.0))
.random_noise;
total += w * noise * noise;
weight += w;
}
total / weight
};
let base = mean_square(&crate::params::PT_V1);
for c in [0.05, 0.15, 0.40, 1.0] {
let ratio = mean_square(&with_suppress(c)) / base;
assert!((ratio - 1.0).abs() < 1e-12,
"c {c}: the second moment moved to {ratio} of itself");
}
}
#[test]
fn a_degenerate_zero_factor_is_the_one_place_neutrality_fails() {
let company = idio_only_company();
let s = shared();
assert_eq!(s.market_factor, 0.0, "the fixture's premise");
let base = calculate_live_factors(
&company, &[], 0.0, 1.0, &s, &crate::params::PT_V1, &mut Fixed(1.0))
.random_noise;
let (_, up) = idio_suppress_scales(0.15);
let dialled = calculate_live_factors(
&company, &[], 0.0, 1.0, &s, &with_suppress(0.15), &mut Fixed(1.0))
.random_noise;
assert_eq!(dialled, base * up);
assert!(up > 1.0, "and it is an INFLATION, which is the whole warning");
}
#[test]
fn the_variance_residual_is_the_binomial_one() {
let c = 0.15;
let (down, up) = idio_suppress_scales(c);
let n: usize = 390; let closed = (1.0 - down * down).abs() / mathx::sqrt(n as f64);
let mut state: u64 = 0x2026_0914_a575_4e07;
let mut flip = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state & 1 == 1
};
let reps = 4000;
let mut sum = 0.0;
let mut sum_sq = 0.0;
for _ in 0..reps {
let mut k = 0usize;
for _ in 0..n {
if flip() {
k += 1;
}
}
let frac = k as f64 / n as f64;
let m = frac * down * down + (1.0 - frac) * up * up;
sum += m;
sum_sq += m * m;
}
let mean = sum / reps as f64;
let sd = mathx::sqrt(sum_sq / reps as f64 - mean * mean);
assert!((mean - 1.0).abs() < 5.0 * closed / mathx::sqrt(reps as f64),
"the realised multiplier centres at {mean}, not at one");
assert!((sd / closed - 1.0).abs() < 0.10,
"sampled sd {sd} against the closed form {closed}");
assert!((closed - 0.0140).abs() < 0.0002, "one session: {closed}");
let window = (1.0 - down * down).abs() / mathx::sqrt((n * 252) as f64);
assert!((window - 0.00089).abs() < 0.00002, "252 sessions: {window}");
}
#[test]
fn every_preset_ships_the_reallocation_off() {
for name in crate::params::ModelParams::preset_names() {
let p = crate::params::ModelParams::preset(name).expect("named");
assert_eq!(p.market_idio_down_suppress, 0.0, "{name}");
}
}
#[test]
fn order_flow_carries_only_the_informed_fraction() {
let c = company();
let out = factors(&c, &[], 1.0, &shared()).order_flow_impact;
let avg = 1e6f64.max(1e8 * 0.005);
let expected = 1.0
* (1.0 / (avg / 390.0).max(100.0))
* ORDER_FLOW_COEFFICIENT
* INFORMED_FLOW_FRACTION;
assert_eq!(out, expected);
}
#[test]
fn order_flow_uses_max_not_the_truthy_fallback_chain() {
let mut c = company();
c.avg_volume = 0.0;
c.shares_outstanding = 1e8;
let out = factors(&c, &[], 1.0, &shared()).order_flow_impact;
let expected = 1.0
* (1.0 / ((1e8f64 * 0.005) / 390.0).max(100.0))
* ORDER_FLOW_COEFFICIENT
* INFORMED_FLOW_FRACTION;
assert_eq!(out, expected);
}
#[test]
fn the_imbalance_scales_with_participation_not_absolute_size() {
let thin = order_imbalance(10_000.0, 0.0, 50_000.0);
let liquid = order_imbalance(10_000.0, 0.0, 500e6);
assert!(thin > liquid, "{thin} vs {liquid}");
assert_eq!(order_imbalance(1e6, 1e6, 1e6), 0.0);
assert_eq!(order_imbalance(0.0, 0.0, 1e6), 0.0);
}
#[test]
fn a_zero_average_volume_falls_through_to_the_default_in_the_imbalance() {
assert!(order_imbalance(1000.0, 0.0, 0.0).is_finite());
assert_eq!(
order_imbalance(1000.0, 0.0, 0.0),
order_imbalance(1000.0, 0.0, 1_000_000.0)
);
}
fn law_on() -> crate::params::ModelParams {
crate::params::PT_V16
.with_override("order_flow_impact_law", 1.0)
.unwrap()
}
fn multiplier(p: &crate::params::ModelParams, phi: f64) -> f64 {
order_imbalance_with(p, phi * 1000.0, 0.0, 390_000.0)
}
fn exponent(p: &crate::params::ModelParams, phi: f64) -> f64 {
mathx::log(multiplier(p, 2.0 * phi) / multiplier(p, phi)) / mathx::log(2.0)
}
#[test]
fn the_shipped_law_stops_responding_at_both_ends_and_not_just_the_top() {
let off = crate::params::PT_V16;
assert_eq!(
off.order_flow_impact_law, 0.0,
"the shipped law must remain the default"
);
for (phi, expected, what) in [
(0.1, 0.0, "below the floor, size has stopped mattering"),
(2.0, 1.0, "in the band, size maps straight through"),
(20.0, 0.0, "above the ceiling, size has stopped mattering again"),
] {
let k = exponent(&off, phi);
assert!((k - expected).abs() < 1e-12, "phi {phi}: {k}, {what}");
}
assert_eq!(multiplier(&off, PARTICIPATION_KNEE), multiplier(&off, 1e9));
assert!(multiplier(&off, 9.0) < multiplier(&off, PARTICIPATION_KNEE));
}
#[test]
fn the_law_constants_are_read_back_out_of_the_shipped_function() {
let off = crate::params::PT_V16;
let slope = (multiplier(&off, 8.0) - multiplier(&off, 4.0)) / 4.0;
assert!((slope - PARTICIPATION_SLOPE).abs() < 1e-15, "slope {slope}");
let knee = multiplier(&off, 1e9) / slope;
assert!((knee - PARTICIPATION_KNEE).abs() < 1e-9, "knee {knee}");
let floor_crossing = multiplier(&off, 1e-9) / slope;
assert!(
(floor_crossing - 4.0 / 3.0).abs() < 1e-9,
"floor crossing {floor_crossing}"
);
}
#[test]
fn the_measured_law_leaves_the_band_between_the_clamps_untouched() {
let off = crate::params::PT_V16;
let on = law_on();
for phi in [1.4, 2.0, 5.0, 9.0, 9.999] {
assert_eq!(multiplier(&off, phi), multiplier(&on, phi), "phi {phi}");
}
assert!(multiplier(&on, 0.1) < multiplier(&off, 0.1));
assert!(multiplier(&on, 100.0) > multiplier(&off, 100.0));
}
#[test]
fn the_measured_law_keeps_responding_above_the_knee() {
let on = law_on();
for phi in [11.0, 50.0, 1_000.0, 100_000.0] {
let k = exponent(&on, phi);
assert!((k - 0.5).abs() < 1e-12, "phi {phi} gave exponent {k}");
}
let ratio = multiplier(&on, 1e6) / multiplier(&on, 1e4);
assert!((ratio - 10.0).abs() < 1e-9, "{ratio}");
}
#[test]
fn the_measured_law_is_linear_below_the_knee_all_the_way_down() {
let on = law_on();
for phi in [1e-4, 1e-3, 1e-2, 0.1, 0.5, 1.0, 4.0] {
let k = exponent(&on, phi);
assert!((k - 1.0).abs() < 1e-12, "phi {phi} gave exponent {k}");
}
}
#[test]
fn the_multiplier_is_finite_at_zero_participation() {
let m = participation_multiplier(0.0);
assert!(m.is_finite(), "{m}");
let product = 0.0 * m;
assert_eq!(product, 0.0);
assert!(product.is_sign_positive(), "{product}");
}
#[test]
fn the_two_branches_meet_at_the_knee() {
assert_eq!(
participation_multiplier(PARTICIPATION_KNEE),
PARTICIPATION_SLOPE * PARTICIPATION_KNEE
);
let above = participation_multiplier(PARTICIPATION_KNEE * (1.0 + 1e-12));
let below = participation_multiplier(PARTICIPATION_KNEE * (1.0 - 1e-12));
assert!((above - below).abs() < 1e-9, "{above} vs {below}");
}
#[test]
fn the_measured_law_never_stops_responding_to_size() {
let on = law_on();
let off = crate::params::PT_V16;
let mut phi = 1e-4;
let mut ties_off = 0;
while phi < 1e5 {
let next = phi * 2.0;
assert!(
multiplier(&on, next) > multiplier(&on, phi),
"measured law flat between {phi} and {next}"
);
if multiplier(&off, next) == multiplier(&off, phi) {
ties_off += 1;
}
phi = next;
}
assert!(
ties_off > 0,
"the shipped law is supposed to be the one that goes flat"
);
}
#[test]
fn every_shipped_preset_runs_the_shipped_law() {
for name in crate::params::ModelParams::preset_names() {
let p = crate::params::ModelParams::preset(name).expect("named");
if *name == "pt-v22" {
continue;
}
let want = if *name == "pt-v21" { 1.0 } else { 0.0 };
assert_eq!(p.order_flow_impact_law, want, "{name}");
}
}
#[test]
fn the_dial_at_zero_is_the_shipped_function_bit_for_bit() {
let off = crate::params::PT_V16;
for (b, s, av) in [
(10_000.0, 0.0, 50_000.0),
(0.0, 10_000.0, 50_000.0),
(1e6, 1e6, 1e6),
(0.0, 0.0, 1e6),
(1000.0, 0.0, 0.0),
(3.0, 7.0, 1e9),
(1e9, 1.0, 1e6),
] {
assert_eq!(
order_imbalance_with(&off, b, s, av),
order_imbalance(b, s, av),
"{b} {s} {av}"
);
}
}
#[test]
fn no_injected_flow_is_bit_identical_under_either_law() {
let on = law_on();
let off = crate::params::PT_V16;
for (label, p) in [("measured", &on), ("shipped", &off)] {
let out = order_imbalance_with(p, 0.0, 0.0, 1e6);
assert_eq!(out, 0.0, "{label}");
assert!(out.is_sign_positive(), "{label} returned {out}");
}
}
#[test]
fn the_measured_law_keeps_the_direction_and_neutrality_of_the_shipped_one() {
let on = law_on();
let thin = order_imbalance_with(&on, 10_000.0, 0.0, 50_000.0);
let liquid = order_imbalance_with(&on, 10_000.0, 0.0, 500e6);
assert!(thin > liquid, "{thin} vs {liquid}");
assert_eq!(order_imbalance_with(&on, 1e6, 1e6, 1e6), 0.0);
assert_eq!(order_imbalance_with(&on, 0.0, 0.0, 1e6), 0.0);
assert_eq!(
order_imbalance_with(&on, 1000.0, 0.0, 0.0),
order_imbalance_with(&on, 1000.0, 0.0, 1_000_000.0)
);
for phi in [0.5, 5.0, 500.0] {
assert_eq!(
order_imbalance_with(&on, 0.0, phi * 1000.0, 390_000.0),
-order_imbalance_with(&on, phi * 1000.0, 0.0, 390_000.0),
"phi {phi}"
);
}
}
fn depth_on(p: &crate::params::ModelParams) -> crate::params::ModelParams {
p.with_override("order_flow_depth_law", 1.0).unwrap()
}
fn four_laws() -> Vec<(&'static str, crate::params::ModelParams)> {
let shipped = crate::params::PT_V16;
let sqrt = law_on();
let (shipped_once, sqrt_once) = (depth_on(&shipped), depth_on(&sqrt));
vec![
("shipped", shipped),
("depth once", shipped_once),
("square root", sqrt),
("square root, depth once", sqrt_once),
]
}
fn named(avg_volume: f64) -> FactorCompany {
let mut c = company();
c.avg_volume = avg_volume;
c.shares_outstanding = avg_volume * 100.0;
c
}
fn minute_of(c: &FactorCompany) -> f64 {
(c.avg_volume / 390.0).max(100.0)
}
fn flow_impact(p: &crate::params::ModelParams, c: &FactorCompany, buy: f64, sell: f64) -> f64 {
let imbalance = order_imbalance_with(p, buy, sell, c.avg_volume);
factors_with(p, c, &[], imbalance, &shared()).order_flow_impact
}
fn log_slope(xs: &[f64], ys: &[f64]) -> f64 {
let lx: Vec<f64> = xs.iter().map(|x| x.ln()).collect();
let ly: Vec<f64> = ys.iter().map(|y| y.ln()).collect();
let mx = lx.iter().sum::<f64>() / lx.len() as f64;
let my = ly.iter().sum::<f64>() / ly.len() as f64;
let num: f64 = lx.iter().zip(&ly).map(|(x, y)| (x - mx) * (y - my)).sum();
let den: f64 = lx.iter().map(|x| (x - mx) * (x - mx)).sum();
num / den
}
const DEPTHS: [f64; 3] = [60_000.0, 2_400_000.0, 90_000_000.0];
#[test]
fn at_equal_participation_the_corrected_law_does_not_depend_on_depth() {
for (label, p) in four_laws() {
let depth_once = p.order_flow_depth_law != 0.0;
for phi in [0.5, 5.0, 50.0] {
let names: Vec<FactorCompany> = DEPTHS.iter().map(|&v| named(v)).collect();
let minutes: Vec<f64> = names.iter().map(minute_of).collect();
let out: Vec<f64> = names
.iter()
.map(|c| flow_impact(&p, c, phi * minute_of(c), 0.0))
.collect();
let k = log_slope(&minutes, &out);
let expected = if depth_once { 0.0 } else { -1.0 };
assert!((k - expected).abs() < 1e-12, "{label}, phi {phi}: exponent {k}");
}
}
}
#[test]
fn at_a_fixed_share_count_the_corrected_law_falls_as_depth_and_the_shipped_one_as_its_square() {
let sqrt = law_on();
let names: Vec<FactorCompany> = DEPTHS.iter().map(|&v| named(v)).collect();
let minutes: Vec<f64> = names.iter().map(minute_of).collect();
for (p, expected) in [(depth_on(&sqrt), -1.0), (sqrt, -2.0)] {
let out: Vec<f64> = names.iter().map(|c| flow_impact(&p, c, 1_000.0, 0.0)).collect();
let k = log_slope(&minutes, &out);
assert!((k - expected).abs() < 1e-12, "expected {expected}, got {k}");
}
}
#[test]
fn the_corrected_law_is_the_shipped_one_at_the_reference_liquidity() {
let c = named(REFERENCE_DAILY_VOLUME);
for (label, p) in four_laws() {
let q = if p.order_flow_impact_law != 0.0 { law_on() } else { crate::params::PT_V16 };
for (b, s) in [(10.0, 0.0), (5_000.0, 1_000.0), (0.0, 25_641.0), (1e9, 3.0)] {
assert_eq!(
flow_impact(&p, &c, b, s).to_bits(),
flow_impact(&q, &c, b, s).to_bits(),
"{label} at {b}/{s}"
);
}
}
}
#[test]
fn the_reference_liquidity_is_the_fallback_the_participation_term_uses() {
assert_eq!(
order_imbalance(5_000.0, 0.0, 0.0),
order_imbalance(5_000.0, 0.0, REFERENCE_DAILY_VOLUME)
);
assert_ne!(
order_imbalance(5_000.0, 0.0, 0.0),
order_imbalance(5_000.0, 0.0, REFERENCE_DAILY_VOLUME * 1.01)
);
}
#[test]
fn the_depth_switch_rescales_and_never_reshapes_the_participation_law() {
for avg in DEPTHS {
let c = named(avg);
let v = minute_of(&c);
let scale = v / (REFERENCE_DAILY_VOLUME / 390.0);
for base in [crate::params::PT_V16, law_on()] {
let on = depth_on(&base);
for phi in [
1e-6,
4.0 / 3.0 * (1.0 - 1e-9),
4.0 / 3.0 * (1.0 + 1e-9),
1.0,
9.999,
10.0,
10.0 * (1.0 + 1e-9),
1e6,
] {
let off_val = flow_impact(&base, &c, phi * v, 0.0);
let on_val = flow_impact(&on, &c, phi * v, 0.0);
let ratio = on_val / off_val;
assert!(
(ratio / scale - 1.0).abs() < 1e-14,
"avg {avg} phi {phi}: ratio {ratio} against {scale}"
);
}
if base.order_flow_impact_law == 0.0 {
assert_eq!(
flow_impact(&on, &c, 1e-6 * v, 0.0),
flow_impact(&on, &c, 4.0 / 3.0 * (1.0 - 1e-9) * v, 0.0)
);
assert!(
flow_impact(&on, &c, 4.0 / 3.0 * (1.0 + 1e-9) * v, 0.0)
> flow_impact(&on, &c, 4.0 / 3.0 * (1.0 - 1e-9) * v, 0.0)
);
assert_eq!(
flow_impact(&on, &c, 10.0 * v, 0.0),
flow_impact(&on, &c, 1e6 * v, 0.0)
);
assert!(flow_impact(&on, &c, 9.999 * v, 0.0) < flow_impact(&on, &c, 10.0 * v, 0.0));
}
}
}
}
#[test]
fn no_flow_is_positive_zero_under_every_combination() {
for (label, p) in four_laws() {
for avg in [0.0, 30_000.0, 1e6, 9e7] {
let out = flow_impact(&p, &named(avg), 0.0, 0.0);
assert_eq!(out.to_bits(), 0.0f64.to_bits(), "{label} at {avg}: {out}");
}
}
}
#[test]
fn a_zero_average_volume_reads_the_reference_name_under_the_corrected_law() {
let mut zero = company();
zero.avg_volume = 0.0;
for shares in [1e6, 1e8, 1e10] {
zero.shares_outstanding = shares;
for (b, s) in [(2_000.0, 0.0), (0.0, 40_000.0)] {
let shipped = flow_impact(&crate::params::PT_V16, &zero, b, s);
let corrected = flow_impact(&depth_on(&crate::params::PT_V16), &zero, b, s);
let reference = flow_impact(&crate::params::PT_V16, &named(REFERENCE_DAILY_VOLUME), b, s);
assert_eq!(corrected, reference, "{shares}");
let liquid = mathx::max((shares * 0.005) / 390.0, 100.0);
let expected = order_imbalance(b, s, 0.0)
* (1.0 / liquid)
* ORDER_FLOW_COEFFICIENT
* INFORMED_FLOW_FRACTION;
assert_eq!(shipped, expected, "{shares}");
}
}
}
#[test]
fn below_the_minute_floor_every_name_is_the_floor_name() {
for (label, p) in four_laws() {
let at_floor = flow_impact(&p, &named(39_000.0), 500.0, 0.0);
for avg in [1.0, 2_000.0, 20_000.0, 38_999.0] {
assert_eq!(flow_impact(&p, &named(avg), 500.0, 0.0), at_floor, "{label} at {avg}");
}
}
let on = depth_on(&crate::params::PT_V16);
let thin = named(10_000.0);
let true_minute = thin.avg_volume / 390.0;
let liquid = named(2_400_000.0);
assert!(
flow_impact(&on, &thin, 5.0 * true_minute, 0.0)
< flow_impact(&on, &liquid, 5.0 * minute_of(&liquid), 0.0)
);
}
#[test]
fn a_nan_average_volume_reaches_only_the_shipped_depth_law() {
let mut c = company();
c.avg_volume = f64::NAN;
assert!(flow_impact(&crate::params::PT_V16, &c, 1_000.0, 0.0).is_nan());
let corrected = flow_impact(&depth_on(&crate::params::PT_V16), &c, 1_000.0, 0.0);
assert_eq!(corrected, flow_impact(&crate::params::PT_V16, &named(REFERENCE_DAILY_VOLUME), 1_000.0, 0.0));
}
#[test]
fn nan_flow_is_what_each_participation_law_already_made_of_it() {
for (label, p) in four_laws() {
let out = flow_impact(&p, &named(1e6), f64::NAN, 0.0);
if p.order_flow_impact_law == 0.0 {
assert!(out.is_nan(), "{label}: {out}");
} else {
assert_eq!(out, 0.0, "{label}: {out}");
}
}
}
#[test]
fn a_flow_too_large_to_sum_stays_finite_under_every_law() {
let c = named(1e6);
for (label, p) in four_laws() {
for (b, s) in [(1e308, 1e308), (1.5e308, 0.5e308), (1e308, 0.0), (0.0, 1.7e308)] {
let out = flow_impact(&p, &c, b, s);
assert!(out.is_finite(), "{label} at {b}/{s}: {out}");
}
assert_eq!(flow_impact(&p, &c, 1e308, 1e308), 0.0, "{label}");
}
let sqrt = law_on();
assert!(flow_impact(&sqrt, &c, 1.5e308, 0.5e308) > 0.0);
assert!(flow_impact(&sqrt, &c, 0.5e308, 1.5e308) < 0.0);
}
#[test]
fn the_corrected_law_is_monotone_in_size_and_symmetric_in_sign() {
for (label, p) in four_laws() {
for avg in [60_000.0, 90_000_000.0] {
let c = named(avg);
let v = minute_of(&c);
let mut phi = 1e-4;
while phi < 1e5 {
let (a, b) = (flow_impact(&p, &c, phi * v, 0.0), flow_impact(&p, &c, 2.0 * phi * v, 0.0));
if p.order_flow_impact_law != 0.0 {
assert!(b > a, "{label} at {avg}: flat between {phi} and {}", 2.0 * phi);
} else {
assert!(b >= a, "{label} at {avg}: falls between {phi} and {}", 2.0 * phi);
}
assert_eq!(
flow_impact(&p, &c, 0.0, phi * v).to_bits(),
(-a).to_bits(),
"{label} at {avg}, phi {phi}"
);
phi *= 2.0;
}
}
}
}
#[test]
fn every_shipped_preset_divides_by_depth_twice() {
for name in crate::params::ModelParams::preset_names() {
let p = crate::params::ModelParams::preset(name).expect("named");
if *name == "pt-v22" {
continue;
}
let want = if *name == "pt-v21" { 1.0 } else { 0.0 };
assert_eq!(p.order_flow_depth_law, want, "{name}");
}
}
#[test]
fn a_heavily_shorted_name_rallying_gets_both_the_squeeze_and_the_buy_cascade() {
let mut c = company();
c.short_interest = 3e7; c.float = 1e8;
c.last_daily_return = Some(0.08);
let out = factors(&c, &[], 0.0, &shared()).short_squeeze_effect;
assert!((out - 0.018).abs() < 1e-12, "got {out}");
}
#[test]
fn the_squeeze_saturates_rather_than_running_away() {
let mut c = company();
c.short_interest = 9e7;
c.float = 1e8;
c.last_daily_return = Some(0.9);
let out = factors(&c, &[], 0.0, &shared()).short_squeeze_effect;
assert!(out <= 0.02 + 0.006 + 1e-12, "got {out}");
}
#[test]
fn a_falling_price_produces_downward_pressure_in_widening_steps() {
let mut c = company();
let at = |c: &mut FactorCompany, r: f64| {
c.last_daily_return = Some(r);
factors(c, &[], 0.0, &shared()).short_squeeze_effect
};
assert_eq!(
at(&mut c, -0.01),
0.0,
"above the -2% trigger, nothing fires"
);
assert_eq!(at(&mut c, -0.025), -0.001);
assert_eq!(at(&mut c, -0.04), -0.003);
assert_eq!(at(&mut c, -0.06), -0.005);
assert_eq!(at(&mut c, -0.08), -0.008);
}
#[test]
fn forced_flow_reacts_to_yesterday_not_today() {
let mut c = company();
c.last_daily_return = None;
assert_eq!(factors(&c, &[], 0.0, &shared()).short_squeeze_effect, 0.0);
}
#[test]
fn the_shared_market_factor_reaches_every_stock_through_beta() {
let mut s = shared();
s.market_factor = 0.001;
let mut high_beta = company();
high_beta.beta = Some(2.0);
let low_beta = company();
assert!(
factors(&high_beta, &[], 0.0, &s).random_noise
> factors(&low_beta, &[], 0.0, &s).random_noise
);
}
#[test]
fn a_crash_sized_market_shock_amplifies_the_market_loading() {
let tick_scale = crate::market::tick::MARKET_FACTOR_SIGMA / (390.0f64).sqrt();
let c = company();
let noise_at = |mult: f64| {
let mut s = shared();
s.market_factor = tick_scale * mult;
factors(&c, &[], 0.0, &s).random_noise
};
let linear = noise_at(1.0);
let amplified = noise_at(4.0);
assert!(amplified > linear * 4.0, "{amplified} vs {}", linear * 4.0);
}
#[test]
fn the_amplifier_is_denominated_in_absolute_units_so_regimes_move_its_rate() {
let base_tick = crate::market::tick::MARKET_FACTOR_SIGMA / 390.0f64.sqrt();
let c = company();
let amplifier_at = |factor: f64| {
let mut s = shared();
s.market_factor = factor;
factors(&c, &[], 0.0, &s).random_noise / s.market_factor
};
assert!(amplifier_at(base_tick * 2.0 * 1.5) > 1.0);
assert_eq!(amplifier_at(base_tick * 0.5 * 1.5), 1.0);
}
#[test]
fn the_conditional_normaliser_fires_at_the_same_multiple_in_every_regime() {
let base_tick = crate::market::tick::MARKET_FACTOR_SIGMA / 390.0f64.sqrt();
let c = company();
let mut p = crate::params::PT_V1;
p.crash_amplifier_conditional_sigma = 1.0;
let amplifier_at = |z: f64, regime: f64| {
let mut s = shared();
s.market_sigma_tick = base_tick * regime;
s.market_factor = z * s.market_sigma_tick;
factors_with(&p, &c, &[], 0.0, &s).random_noise / s.market_factor
};
for &z in &[0.5, 1.5, 1.99, 2.0, 2.5, 4.0, 7.0] {
let at_base = amplifier_at(z, 1.0);
for ®ime in &[0.3, 0.5, 2.0, 6.3] {
assert_eq!(
amplifier_at(z, regime), at_base,
"z {z} reads differently at regime {regime}: the regime \
ratio did not divide out");
}
}
assert_eq!(amplifier_at(1.99, 6.3), 1.0);
assert!(amplifier_at(2.5, 0.3) > 1.0);
let mut dead = shared();
dead.market_sigma_tick = 0.0;
dead.market_factor = 0.0;
assert_eq!(factors_with(&p, &c, &[], 0.0, &dead).random_noise, 0.0);
}
#[test]
fn a_small_cap_carries_more_idiosyncratic_noise_than_a_mega_cap() {
assert_eq!(cap_size_multiplier(100e9), 0.8);
assert_eq!(cap_size_multiplier(20e9), 1.0);
assert_eq!(cap_size_multiplier(5e9), 1.3);
assert_eq!(cap_size_multiplier(0.5e9), 1.6);
let mut small = company();
small.market_cap = 0.5e9;
let mut mega = company();
mega.market_cap = 100e9;
let mut rng = Fixed(1.0);
let s = calculate_live_factors(&small, &[], 0.0, 1.0, &shared(), &crate::params::PT_V1, &mut rng).random_noise;
let mut rng = Fixed(1.0);
let m = calculate_live_factors(&mega, &[], 0.0, 1.0, &shared(), &crate::params::PT_V1, &mut rng).random_noise;
assert!(s > m, "small-cap noise {s} should exceed mega-cap {m}");
}
#[test]
fn the_idio_beta_exponent_is_inert_at_zero_and_disperses_when_it_is_not() {
let noise = |p: &crate::params::ModelParams, beta: f64| {
let mut c = company();
c.beta = Some(beta);
let mut rng = Fixed(1.0);
calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), p, &mut rng).random_noise
};
let off = crate::params::PT_V1;
assert_eq!(off.idio_sigma_beta_exponent, 0.0);
assert_eq!(noise(&off, 0.6), noise(&off, 1.8));
let mut on = crate::params::PT_V1;
on.idio_sigma_beta_exponent = 2.0;
let (lo, hi) = (noise(&on, 0.6), noise(&on, 1.8));
assert!(hi > lo, "beta 1.8 noise {hi} should exceed beta 0.6 noise {lo}");
assert_eq!(noise(&on, 1.0), noise(&off, 1.0));
let mut steep = crate::params::PT_V1;
steep.idio_sigma_beta_exponent = 8.0;
let quiet = noise(&steep, 0.3);
assert!(quiet > 0.0, "a defensive name went silent at {quiet}");
assert_eq!(noise(&on, -0.5), noise(&off, -0.5));
assert!(noise(&on, -0.5).is_finite());
}
#[test]
fn the_crisis_variance_damp_is_inert_at_zero_and_flattens_when_it_is_not() {
let injected = |p: &crate::params::ModelParams, mf: f64| {
let mut sh = shared();
sh.market_factor = mf;
sh.crisis_spike = 0.8;
let mut rng = Fixed(0.0); calculate_live_factors(&company(), &[], 0.0, 1.0, &sh, p, &mut rng)
.random_noise
};
let off = crate::params::PT_V12;
assert_eq!(off.crisis_blend_variance_damp, 0.0);
let shipped = injected(&off, 0.002) / injected(&off, 0.001);
assert!(shipped > 1.0, "shipped response does not rise: {shipped}");
let mut on = crate::params::PT_V12;
on.crisis_blend_variance_damp = 1.0;
let damped = injected(&on, 0.002) / injected(&on, 0.001);
assert!(damped < shipped,
"damp did not flatten the response: {damped} against {shipped}");
assert!(damped > 1.0, "damp inverted the response: {damped}");
let mut zero = crate::params::PT_V12;
zero.crisis_blend_variance_damp = 0.0;
assert_eq!(injected(&zero, 0.0015).to_bits(),
injected(&off, 0.0015).to_bits());
}
#[test]
fn the_garch_variance_floor_stops_a_dead_stock_freezing() {
let mut c = company();
c.garch_variance = 0.0;
let mut rng = Fixed(1.0);
let out = calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), &crate::params::PT_V1, &mut rng).random_noise;
assert!(out > 0.0, "noise collapsed to {out}");
}
#[test]
fn the_idio_sigma_floor_is_the_parameter_and_not_a_constant() {
let mut c = company();
c.garch_variance = 1.0e-6;
let base = crate::params::PT_V1;
let mut lifted = crate::params::PT_V1;
lifted.idio_sigma_floor = 0.0;
let mut r1 = Fixed(1.0);
let mut r2 = Fixed(1.0);
let floored = calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), &base, &mut r1).random_noise;
let free = calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), &lifted, &mut r2).random_noise;
assert!(free < floored, "removing the floor did not lower the noise: {free} vs {floored}");
let ratio = floored / free;
assert!(
(ratio - 10.0).abs() < 1e-9,
"expected the floor to be exactly the parameter, ratio {ratio}"
);
}
}