use crate::economy::EconomyState;
use crate::fair_value::{CompanyValuationInputs, EconomyValuationInputs};
use crate::mathx;
use crate::microstructure::{
decompose, settle_price_through_book, settle_price_through_book_with_orders,
CompanyMicrostructure, SettleOptions,
};
use crate::mispricing::crowd_lean_with;
use crate::params::ModelParams;
use crate::rng::Rng;
use super::factors::{
calculate_live_factors, order_imbalance_with, FactorCompany, LiveFactors, NewsEvent,
SharedFactors,
};
use super::hours::{intraday_vol, intraday_volume, MarketStatus};
pub const S_PHI_TICK: f64 = f64::from_bits(0x3FEF_FFC1_E138_5E9E);
pub const MARKET_FACTOR_SIGMA: f64 = 0.016;
pub const SECTOR_FACTOR_SIGMA: f64 = 0.002;
pub const CRISIS_BLEND_RAMP: f64 = 1.4;
pub const CRISIS_BLEND_CAP: f64 = 0.8;
pub const PRICE_BREAKER_FRACTION: f64 = 0.25;
pub const PRICE_HARD_CAP: f64 = 50_000.0;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TickStock {
pub price: f64,
pub previous_close: f64,
pub previous_tick_price: Option<f64>,
pub open: f64,
pub high: f64,
pub low: f64,
pub volume: f64,
pub avg_volume: f64,
pub shares_outstanding: f64,
pub market_cap: f64,
pub mispricing_s: Option<f64>,
pub mispricing_s_prev_close: Option<f64>,
pub mispricing_momentum: Option<f64>,
pub fair_value_offset: Option<f64>,
pub buyback_log_shares: Option<f64>,
pub dividend: Option<crate::market::dividends::DividendState>,
pub maker_inventory: Option<f64>,
pub garch_variance: f64,
pub garch_cascade: [f64; crate::market::garch::CASCADE_MAX],
pub last_daily_return: Option<f64>,
pub beta: Option<f64>,
pub short_interest: f64,
pub float: f64,
}
impl TickStock {
pub fn new(price: f64, shares_outstanding: f64) -> Self {
TickStock {
price,
previous_close: price,
previous_tick_price: None,
open: price,
high: price,
low: price,
volume: 0.0,
avg_volume: 0.0,
shares_outstanding,
market_cap: price * shares_outstanding,
mispricing_s: None,
mispricing_s_prev_close: None,
mispricing_momentum: None,
fair_value_offset: None,
buyback_log_shares: None,
dividend: None,
maker_inventory: None,
garch_variance: 0.0,
garch_cascade: [0.0; crate::market::garch::CASCADE_MAX],
last_daily_return: None,
beta: None,
short_interest: 0.0,
float: shares_outstanding,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TickCompany {
pub id: String,
pub ticker: String,
pub sector: String,
pub is_bankrupt: bool,
pub is_public: bool,
pub stock: TickStock,
pub sector_volatility: Option<f64>,
pub sector_avg_pe: Option<f64>,
pub eps: Option<f64>,
pub book_value_per_share: Option<f64>,
pub revenue_growth: Option<f64>,
}
impl TickCompany {
pub fn new(
id: impl Into<String>,
ticker: impl Into<String>,
sector: impl Into<String>,
stock: TickStock,
) -> Self {
TickCompany {
id: id.into(),
ticker: ticker.into(),
sector: sector.into(),
is_bankrupt: false,
is_public: true,
stock,
sector_volatility: None,
sector_avg_pe: None,
eps: None,
book_value_per_share: None,
revenue_growth: None,
}
}
}
pub const MARKET_DAYS_PER_YEAR: f64 = 252.0;
pub fn buyback_scale(p: &ModelParams, eps: Option<f64>, price: f64, elapsed_days: i64) -> f64 {
buyback_scale_at(p, p.buyback_payout_share, eps, price, elapsed_days)
}
pub fn buyback_scale_at(
p: &ModelParams,
share: f64,
eps: Option<f64>,
price: f64,
elapsed_days: i64,
) -> f64 {
if p.buyback_payout_share == 0.0 || share == 0.0 {
return 1.0;
}
let eps = match eps {
Some(e) if e > 0.0 && e.is_finite() => e,
_ => return 1.0,
};
if !(price > 0.0) || !price.is_finite() || elapsed_days <= 0 {
return 1.0;
}
let b = share * eps / price;
let b = if p.buyback_yield_cap == 0.0 { b } else { mathx::min(b, p.buyback_yield_cap) };
mathx::exp(b * elapsed_days as f64 / MARKET_DAYS_PER_YEAR)
}
pub fn buyback_factor(p: &ModelParams, share: f64, eps: Option<f64>, price: f64,
elapsed_days: i64, log_shares: Option<f64>) -> f64 {
if p.buyback_accrual != 0.0 {
return match log_shares {
Some(l) if l != 0.0 => mathx::exp(l),
_ => 1.0,
};
}
buyback_scale_at(p, share, eps, price, elapsed_days)
}
pub fn buyback_accrual_step(p: &ModelParams, share: f64, eps: Option<f64>, price: f64,
log_shares: f64) -> f64 {
if p.buyback_accrual == 0.0 || p.buyback_payout_share == 0.0 || share == 0.0 {
return 0.0;
}
let eps = match eps {
Some(e) if e > 0.0 && e.is_finite() => e,
_ => return 0.0,
};
if !(price > 0.0) || !price.is_finite() {
return 0.0;
}
let per_share = if log_shares == 0.0 { eps } else { eps * mathx::exp(log_shares) };
let b = share * per_share / price;
let b = if p.buyback_yield_cap == 0.0 { b } else { mathx::min(b, p.buyback_yield_cap) };
b / MARKET_DAYS_PER_YEAR
}
pub fn sector_sigma_for(p: &ModelParams, economy: &EconomyState) -> f64 {
sector_sigma_at(p, economy, p.market_vol_vix_anchor)
}
pub fn sector_sigma_at(p: &ModelParams, economy: &EconomyState, vix_anchor: f64) -> f64 {
if p.sector_vix_coupling == 0.0 {
p.sector_factor_sigma
} else {
let ratio = economy.vix / vix_anchor;
p.sector_factor_sigma
* mathx::sqrt(1.0 - p.sector_vix_coupling + p.sector_vix_coupling * (ratio * ratio))
}
}
pub fn crisis_spike_for(p: &ModelParams, vix: f64, universe_stress: f64) -> f64 {
let instant_stress = if vix > p.crisis_vix_threshold {
vix - p.crisis_vix_threshold
} else {
0.0
};
let effective_stress = if p.universe_stress_weight == 0.0 {
instant_stress
} else {
instant_stress
+ p.universe_stress_weight * mathx::max(universe_stress - instant_stress, 0.0)
};
if effective_stress > 0.0 {
mathx::min(p.crisis_blend_cap, effective_stress / p.crisis_blend_ramp)
} else {
0.0
}
}
pub fn nominal_scale(p: &ModelParams, economy: &EconomyState, base: f64) -> f64 {
let scale = nominal_scale_output(p, economy, base);
let level = economy.earnings_cycle + economy.earnings_anticipation;
let scale = if p.earnings_cycle_depth == 0.0 || level == 0.0 {
scale
} else {
scale * mathx::exp(level)
};
let look = economy.earnings_lookthrough;
if look == 0.0 {
scale
} else {
scale * mathx::exp(look)
}
}
fn nominal_scale_output(p: &ModelParams, economy: &EconomyState, base: f64) -> f64 {
if p.earnings_nominal_growth == 0.0 {
return 1.0;
}
if !(base > 0.0) || !base.is_finite() {
return 1.0;
}
let ratio = economy.gdp * economy.cpi / base;
1.0 + p.earnings_nominal_growth * (ratio - 1.0)
}
pub fn scale_valuation(
company: CompanyValuationInputs,
scale: f64,
) -> CompanyValuationInputs {
CompanyValuationInputs {
sector_avg_pe: company.sector_avg_pe,
eps: company.eps.map(|v| v * scale),
book_value_per_share: company.book_value_per_share.map(|v| v * scale),
revenue_growth: company.revenue_growth,
}
}
impl TickCompany {
pub(crate) fn valuation(&self) -> CompanyValuationInputs {
CompanyValuationInputs {
sector_avg_pe: self.sector_avg_pe,
eps: self.eps,
book_value_per_share: self.book_value_per_share,
revenue_growth: self.revenue_growth,
}
}
fn write_factor_view(&self, view: &mut FactorCompany) {
let FactorCompany {
id,
sector,
beta,
market_cap,
avg_volume,
shares_outstanding,
short_interest,
float,
garch_variance,
last_daily_return,
} = view;
id.clone_from(&self.id);
sector.clone_from(&self.sector);
*beta = self.stock.beta;
*market_cap = self.stock.market_cap;
*avg_volume = self.stock.avg_volume;
*shares_outstanding = self.stock.shares_outstanding;
*short_interest = self.stock.short_interest;
*float = self.stock.float;
*garch_variance = self.stock.garch_variance;
*last_daily_return = self.stock.last_daily_return;
}
pub fn micro_view(&self, price: f64) -> CompanyMicrostructure {
let mut view = CompanyMicrostructure::new(String::new(), price, 0.0);
self.write_micro_view(price, &mut view);
view
}
fn write_micro_view(&self, price: f64, view: &mut CompanyMicrostructure) {
let CompanyMicrostructure {
id,
sector_volatility,
price: at,
market_cap,
beta,
float,
short_interest,
avg_volume,
volume,
shares_outstanding,
maker_inventory,
} = view;
id.clone_from(&self.id);
*sector_volatility = self.sector_volatility;
*at = price;
*market_cap = self.stock.market_cap;
*beta = self.stock.beta;
*float = Some(self.stock.float);
*short_interest = Some(self.stock.short_interest);
*avg_volume = Some(self.stock.avg_volume);
*volume = Some(self.stock.volume);
*shares_outstanding = Some(self.stock.shares_outstanding);
*maker_inventory = self.stock.maker_inventory;
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[non_exhaustive]
pub struct OrderVolume {
pub buy: f64,
pub sell: f64,
}
impl OrderVolume {
pub const fn new(buy: f64, sell: f64) -> Self {
OrderVolume { buy, sell }
}
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct NewsImpactEntry {
pub company_id: Option<String>,
pub sector: Option<String>,
pub sectors: Vec<String>,
pub remaining_impact: f64,
pub reversal_phase: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SettleDrawPolicy {
FourAlways,
FourOrZero,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TickInputs<'a> {
pub economy: &'a EconomyState,
pub market_status: MarketStatus,
pub intraday_t: f64,
pub volatility_multiplier: f64,
pub news: &'a [NewsEvent],
pub news_impact_queue: &'a [NewsImpactEntry],
pub order_volumes: &'a [(String, OrderVolume)],
pub sector_keys: &'a [String],
pub sector_sigmas: &'a [f64],
pub idio_vol_ratios: &'a [f64],
pub prev_day_down: bool,
pub prev_day_factor: f64,
pub day_factor: f64,
pub forced_flow_eff: f64,
pub market_sigma_daily: f64,
pub market_permanent_ceiling_scale: f64,
pub pinned_mean: f64,
pub vix_anchor: f64,
pub universe_stress: f64,
pub volume_state: f64,
pub volume_idio: &'a [f64],
pub jump_move: &'a [f64],
pub earnings_volume: &'a [f64],
pub settle_draws: SettleDrawPolicy,
pub settle_depth_counterfactual: bool,
pub resting_orders: &'a [Vec<crate::microstructure::RestingOrder>],
pub fill_impact: &'a [f64],
pub nominal_output_base: f64,
pub crisis_epicentre: Option<&'a str>,
pub elapsed_days: i64,
pub params: &'a ModelParams,
}
impl<'a> TickInputs<'a> {
pub fn new(economy: &'a EconomyState, params: &'a ModelParams) -> Self {
TickInputs {
economy,
market_status: MarketStatus::Open,
intraday_t: 0.5,
volatility_multiplier: 1.0,
news: &[],
news_impact_queue: &[],
order_volumes: &[],
sector_keys: &[],
sector_sigmas: &[],
idio_vol_ratios: &[],
prev_day_down: false,
prev_day_factor: 0.0,
day_factor: 0.0,
forced_flow_eff: 1.0,
market_sigma_daily: MARKET_FACTOR_SIGMA,
market_permanent_ceiling_scale: 1.0,
pinned_mean: 0.0,
vix_anchor: params.market_vol_vix_anchor,
universe_stress: 0.0,
volume_state: 0.0,
volume_idio: &[],
jump_move: &[],
earnings_volume: &[],
settle_draws: SettleDrawPolicy::FourAlways,
settle_depth_counterfactual: false,
resting_orders: &[],
fill_impact: &[],
nominal_output_base: economy.gdp * economy.cpi,
crisis_epicentre: None,
elapsed_days: 0,
params,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct TickOutcome {
pub active_indices: Vec<usize>,
pub fair_values: Vec<f64>,
pub fundamental_values: Vec<f64>,
pub s_components: Vec<[f64; crate::market::factors::TICK_COMPONENT_COUNT]>,
pub noise_parts: Vec<[f64; 3]>,
pub noise_own_scale2: Vec<f64>,
pub volumes: Vec<f64>,
pub factors: Vec<LiveFactors>,
pub shared_factors: SharedFactors,
pub shock: Vec<f64>,
pub absorbed: Vec<f64>,
pub clamp: Vec<f64>,
pub unbounded_print: Vec<f64>,
pub liquidity_share: Vec<f64>,
pub agent_fills: Vec<(usize, crate::microstructure::SettledAgentFill)>,
}
fn persistent_volume_multiplier(inputs: &TickInputs) -> f64 {
if inputs.volume_state == 0.0 {
return 1.0;
}
mathx::clamp(mathx::exp(inputs.volume_state), 0.25, 4.0)
}
fn variance_volume_multiplier(inputs: &TickInputs) -> f64 {
let gain = inputs.params.volume_variance_gain;
if gain == 0.0 {
return 1.0;
}
let base_sigma = inputs.params.market_factor_sigma;
if !(base_sigma > 0.0) {
return 1.0;
}
let sigma_ratio = inputs.market_sigma_daily / base_sigma;
let raw = 1.0 + gain * (sigma_ratio * sigma_ratio - 1.0);
mathx::max(mathx::min(raw, 4.0), 0.25)
}
pub fn market_permanent_share(
p: &crate::params::ModelParams,
market_sigma_daily: f64,
ceiling_scale: f64,
) -> f64 {
let share = p.fair_value_market_share;
if p.fair_value_market_vol_cap == 0.0 {
return share;
}
let ceiling = p.fair_value_market_vol_cap * p.market_factor_sigma;
let ceiling = if ceiling_scale == 1.0 { ceiling } else { ceiling * ceiling_scale };
if market_sigma_daily > ceiling {
let capped = share * (ceiling / market_sigma_daily);
if p.fair_value_market_excess_share == 0.0 {
capped
} else {
capped + p.fair_value_market_excess_share * (share - capped)
}
} else {
share
}
}
pub fn simulate_market_tick(
companies: &mut [TickCompany],
inputs: &TickInputs,
rng: &mut impl Rng,
) -> TickOutcome {
if inputs.market_status == MarketStatus::Closed {
return TickOutcome {
active_indices: Vec::new(),
fair_values: Vec::new(),
fundamental_values: Vec::new(),
s_components: Vec::new(),
noise_parts: Vec::new(),
noise_own_scale2: Vec::new(),
volumes: Vec::new(),
factors: Vec::new(),
shared_factors: SharedFactors {
market_factor: 0.0,
sector_factors: Vec::new(),
crisis_spike: 0.0,
prev_day_down: false,
market_sigma_tick: 0.0,
crisis_epicentre: None,
},
shock: Vec::new(),
absorbed: Vec::new(),
clamp: Vec::new(),
unbounded_print: Vec::new(),
liquidity_share: Vec::new(),
agent_fills: Vec::new(),
};
}
let tick_scale_factor = 1.0 / 390.0;
let tick_scale = 1.0 / mathx::sqrt(390.0);
let economy = inputs.economy;
let open = inputs.market_status == MarketStatus::Open;
let p = inputs.params;
let tick_scale_market = if p.overnight_market_share == 0.0 {
tick_scale
} else {
tick_scale * mathx::sqrt(1.0 - p.overnight_market_share)
};
let (tick_scale_own, volatility_multiplier) = if p.overnight_idio_share == 0.0 {
(tick_scale, inputs.volatility_multiplier)
} else {
let k = mathx::sqrt(1.0 - p.overnight_idio_share);
(tick_scale * k, inputs.volatility_multiplier * k)
};
rng.site(crate::rng::Site::MarketFactorZ, 0);
let market_factor = rng.next_normal() * inputs.market_sigma_daily * tick_scale_market;
let vix_correlation_spike = crisis_spike_for(p, economy.vix, inputs.universe_stress);
let sector_sigma = sector_sigma_at(p, economy, inputs.vix_anchor);
let mut sector_factors = Vec::with_capacity(inputs.sector_keys.len());
for (sector_index, sector) in inputs.sector_keys.iter().enumerate() {
rng.site(crate::rng::Site::SectorZ, sector_index as u32);
let sector_sigma = match inputs.sector_sigmas.get(sector_index) {
Some(s) => *s,
None => sector_sigma,
};
let idiosyncratic = rng.next_normal() * sector_sigma * tick_scale_own;
let kept = if p.crisis_blend_source == 0.0 {
idiosyncratic * (1.0 - vix_correlation_spike) + market_factor * vix_correlation_spike
} else {
let consumed = idiosyncratic * (1.0 - vix_correlation_spike)
+ market_factor * vix_correlation_spike;
consumed * (1.0 - p.crisis_blend_source) + idiosyncratic * p.crisis_blend_source
};
sector_factors.push((sector.clone(), kept));
}
let lag_condition = if p.market_beta_down_asym_lag_live == 0.0 {
inputs.prev_day_down
} else {
let c = inputs.prev_day_factor * (1.0 - inputs.intraday_t) + inputs.day_factor;
if p.market_beta_down_asym_lag_live >= 2.0 {
c > 0.0
} else {
c < 0.0
}
};
let shared = SharedFactors {
market_factor,
sector_factors,
crisis_spike: vix_correlation_spike,
prev_day_down: lag_condition,
market_sigma_tick: inputs.market_sigma_daily * tick_scale_market,
crisis_epicentre: inputs.crisis_epicentre.map(|s| s.to_string()),
};
let intraday_vol_mult = intraday_vol(inputs.intraday_t);
let intraday_volume_mult = intraday_volume(inputs.intraday_t, inputs.market_status);
let roster = companies.len();
let mut active_indices: Vec<usize> = Vec::with_capacity(roster);
let mut all_factors: Vec<LiveFactors> = Vec::with_capacity(roster);
let mut all_drifts: Vec<f64> = Vec::with_capacity(roster);
let mut all_noises: Vec<f64> = Vec::with_capacity(roster);
let mut all_news_vol_mults: Vec<f64> = Vec::with_capacity(roster);
let mut all_randoms: Vec<f64> = Vec::with_capacity(roster);
let mut view = FactorCompany::new(String::new(), String::new());
for (idx, company) in companies.iter().enumerate() {
if company.is_bankrupt || !company.is_public {
continue;
}
active_indices.push(idx);
let vol = inputs
.order_volumes
.iter()
.find(|(t, _)| t == &company.ticker)
.map(|(_, v)| *v)
.unwrap_or_default();
let imbalance =
order_imbalance_with(p, vol.buy, vol.sell, company.stock.avg_volume);
rng.site(crate::rng::Site::FactorIdioZ, idx as u32);
let volatility_multiplier = match inputs.idio_vol_ratios.get(idx) {
Some(&r) => volatility_multiplier * mathx::sqrt(r),
None => volatility_multiplier,
};
company.write_factor_view(&mut view);
let factors = calculate_live_factors(
&view,
inputs.news,
imbalance,
volatility_multiplier,
&shared,
p,
rng,
);
let (drift, noise) = if open {
(
(factors.company_news + factors.order_flow_impact + factors.short_squeeze_effect)
* tick_scale_factor,
factors.random_noise,
)
} else {
(
(factors.company_news + factors.order_flow_impact) * tick_scale_factor,
factors.random_noise * 0.15,
)
};
let drift = match inputs.fill_impact.get(idx) {
Some(&x) if x != 0.0 => drift + x,
_ => drift,
};
all_drifts.push(drift);
all_noises.push(noise);
all_factors.push(factors);
let mut news_volume_mult = 1.0;
let mut impact_sum = 0.0;
for entry in inputs.news_impact_queue {
if entry.reversal_phase {
continue;
}
let matches = entry.company_id.as_deref() == Some(company.id.as_str())
|| entry.sector.as_deref() == Some(company.sector.as_str())
|| entry.sectors.iter().any(|s| s == &company.sector);
if matches {
impact_sum += entry.remaining_impact;
}
}
if impact_sum > 0.0 {
news_volume_mult = 1.0 + mathx::min(9.0, impact_sum / 0.01);
}
all_news_vol_mults.push(news_volume_mult);
rng.site(crate::rng::Site::StashU, idx as u32);
all_randoms.push(rng.next_f64());
}
let active_count = active_indices.len();
let previous_closes: Vec<f64> = active_indices
.iter()
.map(|&i| companies[i].stock.previous_close)
.collect();
let current_prices: Vec<f64> = active_indices
.iter()
.map(|&i| companies[i].stock.price)
.collect();
let econ_view = EconomyValuationInputs {
corporate_bond_yield: Some(economy.corporate_bond_yield),
federal_funds_rate: economy.federal_funds_rate,
qe_pe_boost: Some(economy.qe_pe_boost),
qe_assets_ratio: Some(economy.qe_assets_ratio),
};
let mut new_prices = vec![0.0; active_count];
let mut fundamentals = vec![f64::NAN; active_count];
let vix_exposure = vix_feedback_exposure(p, economy);
let mut s_components = vec![[0.0f64; crate::market::factors::TICK_COMPONENT_COUNT]; active_count];
let mut noise_parts = vec![[0.0f64; 3]; active_count];
let mut noise_own_scale2 = vec![0.0f64; active_count];
let mut crowd_leans = vec![0.0; active_count];
let nominal = nominal_scale(p, economy, inputs.nominal_output_base);
for i in 0..active_count {
let idx = active_indices[i];
let grown = if nominal == 1.0 {
companies[idx].valuation()
} else {
scale_valuation(companies[idx].valuation(), nominal)
};
let v_level = companies[idx].stock.fair_value_offset.unwrap_or(0.0);
let grown = if v_level == 0.0 {
grown
} else {
scale_valuation(grown, mathx::exp(v_level))
};
let buyback = buyback_factor(
p, crate::market::dividends::buyback_share(p, &companies[idx]),
grown.eps, current_prices[i], inputs.elapsed_days,
companies[idx].stock.buyback_log_shares);
let valuation = if buyback == 1.0 {
grown
} else {
scale_valuation(grown, buyback)
};
let breakdown = crate::fair_value::compute_fair_value_at(
&valuation, &econ_view, p.fair_value_book_floor,
p.qe_pe_gain, p.qe_pe_stock_gain, p.neutral_discount_rate, p.rate_pe_sensitivity);
let fv = with_vix_discount(p, breakdown.fair_value, vix_exposure, companies[idx].stock.beta);
let fv = crate::market::dividends::with_accrual(fv, &companies[idx]);
if companies[idx].stock.mispricing_s.is_none() {
let s0 = clamp_s(p, mathx::log(mathx::max(0.01, current_prices[i]) / fv));
companies[idx].stock.mispricing_s = Some(s0);
companies[idx].stock.mispricing_s_prev_close = Some(s0);
companies[idx].stock.mispricing_momentum = Some(0.0);
}
let mut s_val = companies[idx].stock.mispricing_s.unwrap();
let momentum = companies[idx].stock.mispricing_momentum.unwrap_or(0.0);
fundamentals[i] = fv;
let forced = if p.forced_flow_gain != 0.0 {
let common = -p.forced_flow_gain
* mathx::max(0.0, economy.vix - p.forced_flow_threshold)
* inputs.forced_flow_eff;
if p.forced_flow_beta_exponent != 0.0 {
let beta = companies[idx].stock.beta.unwrap_or(1.0);
common * mathx::pow(mathx::max(beta, 0.1), p.forced_flow_beta_exponent)
} else {
common
}
} else {
0.0
};
let raw = &all_factors[i];
let scale = 1.0 / 390.0;
let reversal = if open && p.market_factor_reversal != 0.0 {
let k = if p.market_factor_reversal_vix_power != 0.0 {
p.market_factor_reversal
* mathx::pow(mathx::max(economy.vix, 0.0) / 20.0, p.market_factor_reversal_vix_power)
} else {
p.market_factor_reversal
};
-k * companies[idx].stock.beta.unwrap_or(1.0) * inputs.prev_day_factor / 390.0
} else {
0.0
};
let pin_mean = if open && inputs.pinned_mean != 0.0 {
companies[idx].stock.beta.unwrap_or(1.0) * inputs.pinned_mean / 390.0
} else {
0.0
};
s_components[i] = if open {
[
s_val * (p.s_phi_tick - 1.0),
(p.momentum_theta * momentum) / 390.0,
if reversal != 0.0 {
(if p.forced_flow_gain != 0.0 {
crowd_lean_with(p, s_val, momentum) + forced
} else {
crowd_lean_with(p, s_val, momentum)
}) / 390.0
+ reversal
} else {
(if p.forced_flow_gain != 0.0 {
crowd_lean_with(p, s_val, momentum) + forced
} else {
crowd_lean_with(p, s_val, momentum)
}) / 390.0
},
raw.company_news * scale,
with_fill_impact(raw.order_flow_impact * scale, inputs.fill_impact.get(idx)),
raw.short_squeeze_effect * scale,
if pin_mean != 0.0 {
all_noises[i] * intraday_vol_mult + pin_mean
} else {
all_noises[i] * intraday_vol_mult
},
0.0,
0.0,
]
} else {
[
0.0,
0.0,
0.0,
raw.company_news * scale,
with_fill_impact(raw.order_flow_impact * scale, inputs.fill_impact.get(idx)),
0.0,
all_noises[i],
0.0,
0.0,
]
};
let noise_scale = if open { intraday_vol_mult } else { 0.15 };
noise_parts[i] = [
if pin_mean != 0.0 { raw.noise_market * noise_scale + pin_mean } else { raw.noise_market * noise_scale },
raw.noise_sector * noise_scale,
raw.noise_idio * noise_scale,
];
let own_scale = raw.noise_idio_unit * noise_scale;
noise_own_scale2[i] = own_scale * own_scale;
if open {
let lean = crowd_lean_with(p, s_val, momentum);
crowd_leans[i] = lean;
s_val = s_val * p.s_phi_tick
+ (p.momentum_theta * momentum) / 390.0
+ (if p.forced_flow_gain != 0.0 { lean + forced } else { lean }) / 390.0
+ all_drifts[i]
+ all_noises[i] * intraday_vol_mult;
if reversal != 0.0 {
s_val += reversal;
}
if pin_mean != 0.0 {
s_val += pin_mean;
}
} else {
s_val = s_val + all_drifts[i] + all_noises[i];
}
let mut fv_moved = fv;
if p.fair_value_news_share != 0.0 || p.fair_value_market_share != 0.0 || reversal != 0.0 {
let psi = p.fair_value_news_share;
let noise_scale = if open { intraday_vol_mult } else { 0.15 };
let own_noise = psi * ((raw.noise_idio + raw.noise_sector) * noise_scale);
let own_news = psi * ((raw.company_news - raw.company_news_market) * scale);
let dv = if p.fair_value_market_share == 0.0 {
own_noise + own_news
} else {
let psim = market_permanent_share(
p, inputs.market_sigma_daily, inputs.market_permanent_ceiling_scale);
let market_draw = if p.fair_value_market_linear == 0.0 {
raw.noise_market
} else {
raw.noise_market_linear
};
let dv = own_noise + own_news
+ psim * (market_draw * noise_scale)
+ psim * (raw.company_news_market * scale);
if pin_mean != 0.0 { dv + psim * pin_mean } else { dv }
};
let dv = if reversal != 0.0 {
if p.market_factor_reversal_transient != 0.0 {
let moved = (1.0 - p.market_factor_reversal_transient) * reversal;
if moved != 0.0 { dv + moved } else { dv }
} else {
dv + reversal
}
} else {
dv
};
if dv != 0.0 {
let before = s_val;
s_val -= dv;
s_components[i][crate::market::factors::TICK_FAIR_VALUE] += s_val - before;
let step = dv - 0.5 * dv * dv;
companies[idx].stock.fair_value_offset = Some(v_level + step);
fv_moved = fv * mathx::exp(step);
}
}
s_val = clamp_s(p, s_val);
let fv = fv_moved;
fundamentals[i] = fv;
let mut new_price = mathx::max(0.01, fv * mathx::exp(s_val));
let max_price = previous_closes[i] * p.breaker_up;
let min_price = mathx::max(previous_closes[i] * p.breaker_down, 0.01);
if new_price > max_price || new_price < min_price {
new_price = mathx::max(min_price, mathx::min(max_price, new_price));
let before = s_val;
s_val = clamp_s(p, mathx::log(new_price / fv));
s_components[i][7] += s_val - before;
}
companies[idx].stock.mispricing_s = Some(s_val);
new_prices[i] = mathx::min(new_price, p.price_hard_cap);
}
let volume_multiplier = if open { 1.0 } else { 0.1 };
let volume_multiplier = volume_multiplier * variance_volume_multiplier(inputs);
let volume_multiplier = volume_multiplier * persistent_volume_multiplier(inputs);
let mut volumes = vec![0.0; active_count];
for i in 0..active_count {
let idx = active_indices[i];
let volume_multiplier = match inputs.volume_idio.get(idx) {
Some(&s) if s != 0.0 => {
volume_multiplier * mathx::clamp(mathx::exp(s), 0.25, 4.0)
}
_ => volume_multiplier,
};
let volume_multiplier = if inputs.params.volume_idio_variance_gain == 0.0 {
volume_multiplier
} else {
match crate::sectors::by_key(&companies[idx].sector)
.map(|s| s.base_daily_variance())
{
Some(base) if base > 0.0 => {
let ratio = companies[idx].stock.garch_variance / base;
let raw = 1.0
+ inputs.params.volume_idio_variance_gain * (ratio - 1.0);
volume_multiplier * mathx::clamp(raw, 0.25, 4.0)
}
_ => volume_multiplier,
}
};
let stock = &companies[idx].stock;
let daily_change = if stock.open > 0.0 {
let move_from_open = (new_prices[i] - stock.open) / stock.open;
if p.overnight_market_share != 0.0 || p.overnight_idio_share != 0.0 {
if stock.previous_close > 0.0 {
((new_prices[i] - stock.previous_close) / stock.previous_close).abs()
} else {
move_from_open.abs()
}
} else if inputs.params.volume_move_jump_share == 1.0 {
move_from_open.abs()
} else {
match inputs.jump_move.get(idx) {
Some(&j) if j != 0.0 => {
let open_eff = stock.open
* mathx::exp((1.0 - inputs.params.volume_move_jump_share) * j);
((new_prices[i] - open_eff) / open_eff).abs()
}
_ => move_from_open.abs(),
}
}
} else {
0.0
};
let base_volume = stock.avg_volume / 390.0;
let price_magnitude = daily_change / 0.01;
let p = inputs.params;
let volume_scale = p.volume_move_floor
+ p.volume_move_response * mathx::min(price_magnitude, p.volume_move_cap)
+ all_randoms[i] * p.volume_move_noise;
volumes[i] = (base_volume
* volume_multiplier
* volume_scale
* intraday_volume_mult
* all_news_vol_mults[i])
.floor();
if let Some(&m) = inputs.earnings_volume.get(idx) {
if m != 1.0 {
volumes[i] = (volumes[i] * m).floor();
}
}
}
let mut shock_col = vec![0.0; active_count];
let mut absorbed_col = vec![0.0; active_count];
let mut clamp_col = vec![0.0; active_count];
let depth_arm = inputs.settle_depth_counterfactual
&& inputs.settle_draws == SettleDrawPolicy::FourAlways;
let mut unbounded_col = if depth_arm { vec![0.0; active_count] } else { Vec::new() };
let mut share_col = if depth_arm { vec![0.0; active_count] } else { Vec::new() };
let mut agent_fills: Vec<(usize, crate::microstructure::SettledAgentFill)> = Vec::new();
let mut micro = CompanyMicrostructure::new(String::new(), 0.0, 0.0);
for i in 0..active_count {
let idx = active_indices[i];
let fair_value = new_prices[i];
let volume = volumes[i].floor();
let last_print = companies[idx].stock.price;
let print_max = previous_closes[i] * p.breaker_up;
let print_min = mathx::max(previous_closes[i] * p.breaker_down, 0.01);
let breaker = |price: f64| {
if price > print_max || price < print_min {
mathx::max(print_min, mathx::min(print_max, price))
} else {
price
}
};
let mut unbounded_price = f64::NAN;
let mut new_price = fair_value;
if open {
rng.site(crate::rng::Site::SettleU, idx as u32);
let mut predrawn = match inputs.settle_draws {
SettleDrawPolicy::FourAlways => Some(PredrawnUniforms::new([
rng.next_f64(),
rng.next_f64(),
rng.next_f64(),
rng.next_f64(),
])),
SettleDrawPolicy::FourOrZero => None,
};
let quote_from = if p.quote_model_weight != 0.0 {
if p.quote_model_weight == 1.0 {
fair_value
} else {
let last = companies[idx].stock.price;
last * mathx::exp(p.quote_model_weight * mathx::log(fair_value / last))
}
} else if p.news_quote_revision == 0.0 || s_components[i][3] == 0.0 {
companies[idx].stock.price
} else {
companies[idx].stock.price * mathx::exp(s_components[i][3])
};
companies[idx].write_micro_view(quote_from, &mut micro);
let options = SettleOptions {
spread_size_smoothness: inputs.params.spread_size_smoothness,
spread_size_exponent: inputs.params.spread_size_exponent,
vix: economy.vix,
difficulty: None,
flow_lean: Some(crowd_leans[i]),
depth_multiplier: 1.0,
};
let resting = match inputs.resting_orders.get(idx) {
Some(orders) if !orders.is_empty() => orders.as_slice(),
_ => &[],
};
let settled = if resting.is_empty() {
match predrawn.as_mut() {
Some(buffer) => {
settle_price_through_book(µ, fair_value, volume, &options, buffer)
}
None => settle_price_through_book(µ, fair_value, volume, &options, rng),
}
} else {
let (settled, fills) = match predrawn.as_mut() {
Some(buffer) => settle_price_through_book_with_orders(
µ, fair_value, volume, &options, resting, buffer),
None => settle_price_through_book_with_orders(
µ, fair_value, volume, &options, resting, rng),
};
agent_fills.extend(fills.into_iter().map(|f| (idx, f)));
settled
};
new_price = settled.price;
let auction = p.closing_auction != 0.0 && inputs.intraday_t == 389.0 / 390.0;
if auction {
new_price = fair_value;
}
if depth_arm {
if let Some(buffer) = predrawn.as_mut() {
buffer.rewind();
let (deep, _) = settle_price_through_book_with_orders(
µ,
fair_value,
volume,
&SettleOptions {
depth_multiplier: f64::INFINITY,
..options
},
resting,
buffer,
);
unbounded_price = breaker(deep.price);
}
}
let settled_price = new_price;
new_price = breaker(new_price);
clamp_col[i] = mathx::log(new_price / settled_price);
if settled.maker_inventory_delta != 0.0 && !auction {
companies[idx].stock.maker_inventory = Some(
companies[idx].stock.maker_inventory.unwrap_or(0.0)
+ settled.maker_inventory_delta,
);
}
}
let (shock, absorbed) = decompose(last_print, fair_value, new_price);
shock_col[i] = shock;
absorbed_col[i] = absorbed;
if depth_arm {
let unbounded = if unbounded_price.is_nan() { new_price } else { unbounded_price };
unbounded_col[i] = unbounded;
let moved = mathx::log(new_price / last_print);
share_col[i] = if unbounded == new_price {
0.0
} else if moved == 0.0 {
f64::NAN
} else {
mathx::log(new_price / unbounded) / moved
};
}
let stock = &mut companies[idx].stock;
stock.previous_tick_price = Some(stock.price);
stock.price = new_price;
stock.high = mathx::max(stock.high, new_price);
stock.low = mathx::min(stock.low, new_price);
stock.volume += volume;
stock.market_cap = new_price * stock.shares_outstanding;
}
TickOutcome {
active_indices,
fair_values: new_prices,
fundamental_values: fundamentals,
s_components,
noise_parts,
noise_own_scale2,
volumes,
factors: all_factors,
shared_factors: shared,
shock: shock_col,
absorbed: absorbed_col,
clamp: clamp_col,
unbounded_print: unbounded_col,
liquidity_share: share_col,
agent_fills,
}
}
fn with_fill_impact(slot: f64, fill: Option<&f64>) -> f64 {
match fill {
Some(&x) if x != 0.0 => slot + x,
_ => slot,
}
}
pub fn vix_excess(p: &ModelParams, vix: f64) -> f64 {
if !(p.fair_value_vix_knee > 0.0) || !(vix > p.fair_value_vix_knee) {
return 0.0;
}
mathx::log(vix / p.fair_value_vix_knee)
}
pub fn pinned_vix_excess(p: &ModelParams, vix: f64) -> f64 {
let excess = vix_excess(p, vix);
if p.pinned_vix_calm_share == 0.0 || !(p.pinned_vix_calm_knee > 0.0) || !(vix > p.pinned_vix_calm_knee) {
return excess;
}
mathx::max(excess, p.pinned_vix_calm_share * mathx::log(vix / p.pinned_vix_calm_knee))
}
pub fn vix_feedback_exposure(p: &ModelParams, economy: &EconomyState) -> f64 {
if p.fair_value_vix_discount == 0.0 {
return 0.0;
}
if p.fair_value_vix_half_life == 0.0 {
vix_excess(p, economy.vix)
} else {
economy.vix_feedback
}
}
pub fn with_vix_discount(p: &ModelParams, fv: f64, exposure: f64, beta: Option<f64>) -> f64 {
if p.fair_value_vix_discount == 0.0 || !(exposure > 0.0) {
fv
} else {
fv * mathx::exp(-p.fair_value_vix_discount * beta.unwrap_or(1.0) * exposure)
}
}
pub fn published_fair_value(
p: &ModelParams,
economy: &EconomyState,
nominal_output_base: f64,
elapsed_days: i64,
company: &TickCompany,
) -> f64 {
let nominal = nominal_scale(p, economy, nominal_output_base);
let grown = if nominal == 1.0 {
company.valuation()
} else {
scale_valuation(company.valuation(), nominal)
};
let buyback = buyback_factor(
p, crate::market::dividends::buyback_share(p, company), grown.eps,
company.stock.price, elapsed_days, company.stock.buyback_log_shares);
let valuation = if buyback == 1.0 { grown } else { scale_valuation(grown, buyback) };
let econ_view = EconomyValuationInputs {
corporate_bond_yield: Some(economy.corporate_bond_yield),
federal_funds_rate: economy.federal_funds_rate,
qe_pe_boost: Some(economy.qe_pe_boost),
qe_assets_ratio: Some(economy.qe_assets_ratio),
};
let fv = crate::fair_value::compute_fair_value_at(
&valuation, &econ_view, p.fair_value_book_floor,
p.qe_pe_gain, p.qe_pe_stock_gain, p.neutral_discount_rate, p.rate_pe_sensitivity)
.fair_value;
let fv = with_vix_discount(p, fv, vix_feedback_exposure(p, economy), company.stock.beta);
crate::market::dividends::with_accrual(fv, company)
}
pub fn tick_fair_value(
p: &ModelParams,
economy: &EconomyState,
nominal_output_base: f64,
elapsed_days: i64,
company: &TickCompany,
price: f64,
) -> f64 {
let nominal = nominal_scale(p, economy, nominal_output_base);
let grown = if nominal == 1.0 {
company.valuation()
} else {
scale_valuation(company.valuation(), nominal)
};
let v_level = company.stock.fair_value_offset.unwrap_or(0.0);
let grown = if v_level == 0.0 {
grown
} else {
scale_valuation(grown, mathx::exp(v_level))
};
let buyback = buyback_factor(
p, crate::market::dividends::buyback_share(p, company), grown.eps, price, elapsed_days,
company.stock.buyback_log_shares);
let valuation = if buyback == 1.0 { grown } else { scale_valuation(grown, buyback) };
let econ_view = EconomyValuationInputs {
corporate_bond_yield: Some(economy.corporate_bond_yield),
federal_funds_rate: economy.federal_funds_rate,
qe_pe_boost: Some(economy.qe_pe_boost),
qe_assets_ratio: Some(economy.qe_assets_ratio),
};
let fv = crate::fair_value::compute_fair_value_at(
&valuation, &econ_view, p.fair_value_book_floor,
p.qe_pe_gain, p.qe_pe_stock_gain, p.neutral_discount_rate, p.rate_pe_sensitivity)
.fair_value;
let fv = with_vix_discount(p, fv, vix_feedback_exposure(p, economy), company.stock.beta);
crate::market::dividends::with_accrual(fv, company)
}
pub fn opening_print(
p: &ModelParams,
economy: &EconomyState,
nominal_output_base: f64,
elapsed_days: i64,
company: &TickCompany,
s: f64,
) -> f64 {
let clamp = |x: f64| mathx::min(mathx::max(x, 0.01), p.price_hard_cap);
let level = mathx::exp(s);
let last = company.stock.price;
let mut price = clamp(
tick_fair_value(p, economy, nominal_output_base, elapsed_days, company, last) * level);
if p.buyback_payout_share != 0.0 {
for _ in 0..16 {
let fv = tick_fair_value(p, economy, nominal_output_base, elapsed_days, company, price);
let next = clamp(fv * level);
if next == price {
break;
}
price = next;
}
}
price
}
pub fn clamp_s(params: &ModelParams, s: f64) -> f64 {
mathx::max(-params.mispricing_cap, mathx::min(params.mispricing_cap, s))
}
struct PredrawnUniforms {
draws: [f64; 4],
at: usize,
}
impl PredrawnUniforms {
fn new(draws: [f64; 4]) -> Self {
Self { draws, at: 0 }
}
fn rewind(&mut self) {
self.at = 0;
}
}
impl Rng for PredrawnUniforms {
fn next_f64(&mut self) -> f64 {
let value = self.draws[self.at];
self.at += 1;
value
}
fn next_normal(&mut self) -> f64 {
unreachable!("settlement draws uniforms only; a normal request here is a routing bug")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_excess_share_is_a_floor_under_the_share_above_the_ceiling() {
let mut p = crate::params::PT_V20;
let base = p.fair_value_market_vol_cap * p.market_factor_sigma;
assert_eq!(p.fair_value_market_excess_share, 0.0);
assert_eq!(market_permanent_share(&p, 0.5 * base, 1.0), p.fair_value_market_share);
assert_eq!(market_permanent_share(&p, 4.0 * base, 1.0), p.fair_value_market_share / 4.0);
p.fair_value_market_excess_share = 0.5;
assert_eq!(market_permanent_share(&p, 0.5 * base, 1.0), p.fair_value_market_share);
let capped = p.fair_value_market_share / 4.0;
let want = capped + 0.5 * (p.fair_value_market_share - capped);
assert!((market_permanent_share(&p, 4.0 * base, 1.0) - want).abs() < 1e-15);
assert!(market_permanent_share(&p, 1e6 * base, 1.0) >= 0.5 * p.fair_value_market_share);
p.fair_value_market_excess_share = 1.0;
assert_eq!(market_permanent_share(&p, 4.0 * base, 1.0), p.fair_value_market_share);
}
#[test]
fn buyback_accrual_is_inert_off_and_does_not_read_the_price_on() {
let mut p = crate::params::PT_V1;
p.buyback_payout_share = 0.75;
assert_eq!(buyback_factor(&p, p.buyback_payout_share, Some(2.0), 40.0, 500, Some(0.3)),
buyback_scale(&p, Some(2.0), 40.0, 500));
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, 0.0), 0.0);
p.buyback_accrual = 1.0;
let a = buyback_factor(&p, p.buyback_payout_share, Some(2.0), 40.0, 500, Some(0.3));
let b = buyback_factor(&p, p.buyback_payout_share, Some(2.0), 20.0, 9000, Some(0.3));
assert_eq!(a, b);
assert_eq!(a, mathx::exp(0.3));
assert_eq!(buyback_factor(&p, p.buyback_payout_share, Some(2.0), 40.0, 500, None), 1.0);
}
#[test]
fn buyback_accrual_step_is_the_capped_yield_on_the_grown_earnings() {
let mut p = crate::params::PT_V1;
p.buyback_payout_share = 0.5;
p.buyback_accrual = 1.0;
let l = 0.2;
let want = 0.5 * 2.0 * mathx::exp(l) / 40.0 / MARKET_DAYS_PER_YEAR;
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, l), want);
p.buyback_yield_cap = 0.01;
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, l), 0.01 / MARKET_DAYS_PER_YEAR);
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(-1.0), 40.0, l), 0.0);
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, None, 40.0, l), 0.0);
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 0.0, l), 0.0);
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), f64::NAN, l), 0.0);
p.buyback_payout_share = 0.0;
assert_eq!(buyback_accrual_step(&p, p.buyback_payout_share, Some(2.0), 40.0, l), 0.0);
}
#[test]
fn s_phi_tick_matches_the_recorded_v8_bits() {
assert_eq!(S_PHI_TICK.to_bits(), 0x3FEF_FFC1_E138_5E9E);
}
#[test]
fn market_factor_sigma_is_the_2026_08_sweep_calibration() {
assert_eq!(MARKET_FACTOR_SIGMA, 0.016);
}
#[test]
fn s_phi_tick_compounds_to_the_daily_phi_across_a_session() {
let mut compounded = 1.0f64;
for _ in 0..390 {
compounded *= S_PHI_TICK;
}
assert!(
(compounded - crate::mispricing::MISPRICING_PHI).abs() < 1e-12,
"390 ticks compounded to {compounded}, daily phi is {}",
crate::mispricing::MISPRICING_PHI
);
}
#[test]
fn universe_memory_holds_correlation_up_after_the_shock_passes() {
let base = crate::params::PT_V1;
let mut remembering = base.clone();
remembering.universe_stress_weight = 1.0;
remembering.universe_stress_decay = 0.97;
let calm_vix = crate::economy::CRISIS_VIX_THRESHOLD - 5.0;
let carried = 8.0;
let forgetful = blend_for(&base, calm_vix, carried);
let remembers = blend_for(&remembering, calm_vix, carried);
assert_eq!(forgetful, 0.0, "without memory a calm day decouples");
assert!(remembers > 0.0,
"with memory the blend survives the day the panic ended");
assert!(remembers <= base.crisis_blend_cap);
}
#[test]
fn universe_memory_is_inert_at_its_legacy_weight() {
let base = crate::params::PT_V1;
assert_eq!(base.universe_stress_weight, 0.0);
for vix in [5.0, 15.0, 22.0, 30.0, 65.0] {
for carried in [0.0, 3.0, 25.0] {
assert_eq!(
blend_for(&base, vix, carried),
blend_for(&base, vix, 0.0),
"vix {vix} carried {carried}"
);
}
}
}
fn blend_for(p: &crate::params::ModelParams, vix: f64, carried: f64) -> f64 {
let threshold = p.crisis_vix_threshold;
let instant = if vix > threshold { vix - threshold } else { 0.0 };
let effective = if p.universe_stress_weight == 0.0 {
instant
} else {
instant + p.universe_stress_weight * mathx::max(carried - instant, 0.0)
};
if effective > 0.0 {
mathx::min(p.crisis_blend_cap, effective / p.crisis_blend_ramp)
} else {
0.0
}
}
fn economy_at(gdp: f64, cpi: f64) -> EconomyState {
let mut e = crate::economy::create_initial_economy_state(
&crate::economy::InitialEconomyOptions::default());
e.gdp = gdp;
e.cpi = cpi;
e
}
fn with_dial(value: f64) -> crate::params::ModelParams {
let mut p = crate::params::PT_V16;
p.earnings_nominal_growth = value;
p
}
#[test]
fn the_scale_is_one_wherever_the_dial_is_off() {
let p = with_dial(0.0);
for (gdp, cpi) in [(25000.0, 100.0), (250000.0, 100.0),
(25000.0, 1000.0), (0.0, 100.0)] {
let e = economy_at(gdp, cpi);
assert_eq!(nominal_scale(&p, &e, 2_500_000.0), 1.0);
}
}
#[test]
fn the_scale_is_the_output_ratio_when_the_dial_is_full() {
let p = with_dial(1.0);
let base = 2_500_000.0;
assert_eq!(nominal_scale(&p, &economy_at(25000.0, 100.0), base), 1.0);
assert_eq!(nominal_scale(&p, &economy_at(50000.0, 100.0), base), 2.0);
assert_eq!(nominal_scale(&p, &economy_at(25000.0, 200.0), base), 2.0);
assert_eq!(nominal_scale(&p, &economy_at(20000.0, 100.0), base), 0.8);
}
#[test]
fn a_share_of_the_dial_is_a_share_of_the_level() {
let base = 2_500_000.0;
let e = economy_at(50000.0, 100.0);
assert_eq!(nominal_scale(&with_dial(0.5), &e, base), 1.5);
assert_eq!(nominal_scale(&with_dial(0.25), &e, base), 1.25);
}
#[test]
fn a_base_that_is_not_a_positive_number_gives_one() {
let p = with_dial(1.0);
let e = economy_at(25000.0, 100.0);
for base in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert_eq!(nominal_scale(&p, &e, base), 1.0);
}
}
#[test]
fn the_scaled_valuation_moves_both_fundamentals_and_nothing_else() {
let company = CompanyValuationInputs {
sector_avg_pe: Some(18.0),
eps: Some(4.0),
book_value_per_share: Some(20.0),
revenue_growth: Some(0.05),
};
let scaled = scale_valuation(company, 1.25);
assert_eq!(scaled.eps, Some(5.0));
assert_eq!(scaled.book_value_per_share, Some(25.0));
assert_eq!(scaled.revenue_growth, Some(0.05));
assert_eq!(scaled.sector_avg_pe, Some(18.0));
let empty = scale_valuation(CompanyValuationInputs {
sector_avg_pe: None, eps: None,
book_value_per_share: None, revenue_growth: None,
}, 1.25);
assert_eq!(empty.eps, None);
assert_eq!(empty.book_value_per_share, None);
}
}