use super::state::*;
use crate::mathx::{self, clamp_via_min_max as clamp};
use super::central_bank::{CORPORATE_SPREAD_FLOOR, MORTGAGE_SPREAD_FLOOR};
use crate::rng::Rng;
#[inline]
fn random_normal(rng: &mut impl Rng, mean: f64, std_dev: f64) -> f64 {
mean + rng.next_normal() * std_dev
}
fn effective_gdp_range(
phase: &PhaseCharacteristics,
cycle: CyclePhase,
trough_floor: f64,
) -> (f64, f64) {
if trough_floor == 0.0 || cycle != CyclePhase::Trough {
phase.gdp_growth_range
} else {
let (lo, hi) = phase.gdp_growth_range;
(lo * (1.0 - trough_floor), hi)
}
}
fn phase_growth_target(stored: f64, range: (f64, f64), range_draw: f64) -> f64 {
if range_draw == 0.0 {
(range.0 + range.1) / 2.0
} else {
stored
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct DailyInputs<'a> {
pub volatility: f64,
pub active_shocks: &'a [EconomicShock],
pub market_return_pct: f64,
pub game_day: i64,
pub vix_mean_reversion: f64,
pub vix_decay_ratio: f64,
pub vix_anchor_reversion: f64,
pub vix_anchor_level: f64,
pub vix_anchor_weight: f64,
pub vix_anchor_memory: f64,
pub macro_compound_days_per_year: f64,
pub macro_calendar: MacroCalendar,
pub cycle_us_calibration: f64,
pub vix_anchor_centre: f64,
pub vix_anchor_weight_level: f64,
pub vix_anchor_weight_level_cap: f64,
pub vix_anchor_weight_level_knee: f64,
pub vix_anchor_weight_level_below: f64,
pub vix_anchor_weight_level_knee_fixed: f64,
pub vix_anchor_level_fixed: f64,
pub vix_anchor_slow: f64,
pub vix_fear_uptake: f64,
pub vix_fear: f64,
pub vix_target_premium: f64,
pub vix_target_floor: Option<f64>,
pub vix_jump_intensity: f64,
pub vix_jump_scale: f64,
pub vix_return_gain: f64,
pub vix_realised_vol_weight: f64,
pub vix_return_source: f64,
pub vix_cycle_amplitude: f64,
pub market_day_return_pct: f64,
pub vix_implied_from_market: f64,
pub vix_return_gain_up: f64,
pub vix_level_identity: f64,
pub vix_index_sigma_pct: f64,
pub vix_return_exponent: f64,
pub vix_return_clamp: f64,
pub vix_target_shock_cap: f64,
pub vix_ceiling: f64,
pub vix_target_offset: f64,
pub vix_return_level_exponent: f64,
pub vix_return_exponent_up: f64,
pub vix_return_level_exponent_up: f64,
pub vix_innovation_sigma: f64,
pub vix_innovation_return_sigma: f64,
pub vix_jump_level_scale: f64,
pub vix_jump_return_intensity: f64,
pub inflation_reversion: f64,
pub inflation_ceiling: f64,
pub inflation_floor: f64,
pub crisis_vix_threshold: f64,
pub usd_crisis_vix_threshold: f64,
pub daily_credit_floor_gain: f64,
pub oil_supply_response: f64,
pub oil_opec_symmetry: f64,
pub oil_seasonality_target: f64,
pub trough_growth_floor: f64,
pub phase_target_range_draw: f64,
pub unemployment_adjustment: f64,
pub unemployment_natural_pull: f64,
pub unemployment_okun_coefficient: f64,
pub unemployment_natural_rate: f64,
pub oil_inventory_reversion: f64,
pub oil_inflation_passthrough: f64,
pub oil_mean_reversion: f64,
pub oil_noise_sd: f64,
pub oil_inventory_level_gain: f64,
pub oil_convenience_yield: f64,
pub oil_convenience_inventory_var: f64,
pub oil_convenience_inventory_var_before: f64,
pub oil_target_drift: Option<(f64, f64)>,
pub oil_growth: Option<f64>,
pub oil_pushes_in_target: bool,
pub oil_noise_log_sd: f64,
pub oil_dollar_elasticity: f64,
pub oil_inventory_noise_sd: f64,
pub usd_mean_reversion: f64,
pub usd_noise_sd: f64,
pub usd_safe_haven_gain: f64,
pub oil_inflation_tracked: bool,
pub core_trend: f64,
pub oil_price_floor: f64,
pub oil_price_ceiling: f64,
pub fear_greed_published: Option<(CyclePhase, f64)>,
pub yields: YieldDials,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct YieldDials {
pub treasury_10y_noise: f64,
pub treasury_2y_noise: f64,
pub flight_to_quality_gain: f64,
pub flight_to_quality_reversal_cut: f64,
pub flight_to_quality_day: f64,
pub corporate_yield_daily: f64,
pub vix_pinned: bool,
pub corporate_pinned: bool,
pub spread_multiplier: Option<(f64, f64)>,
pub treasury_10y_pinned: bool,
pub treasury_2y_pinned: bool,
pub priced_put: f64,
pub priced_path: f64,
pub priced_anticipation: f64,
pub rate_damping: f64,
pub haven_gain: f64,
pub core_inflation: f64,
pub zlb_path: f64,
pub zlb_haven_gain: f64,
pub spread_vix_cut: f64,
pub spread_equity_gain: f64,
pub spread_equity_decay: f64,
pub spread_priced_keep: f64,
pub spread_priced_gain: f64,
pub treasury_equity_keep: f64,
pub treasury_equity_gain: f64,
pub spread_noise: Option<(f64, f64)>,
pub term_premium: Option<f64>,
pub two_year_path: Option<(f64, f64)>,
}
pub const CORPORATE_DAILY_MOVE_CAP: f64 = 0.50;
pub const TREASURY_HAVEN_VIX: f64 = 20.0;
pub const TREASURY_NEUTRAL_RATE: f64 = 2.5;
pub const TWO_YEAR_TERM_PREMIUM: f64 = 0.433;
pub const TWO_YEAR_TERM_PREMIUM_BETA: f64 = 0.452;
pub const ZLB_RATE: f64 = 0.25;
pub fn haven_term_cut(gain: f64, vix: f64) -> f64 {
gain * mathx::max(0.0, vix - TREASURY_HAVEN_VIX)
}
impl Default for YieldDials {
fn default() -> Self {
Self {
treasury_10y_noise: 0.03,
treasury_2y_noise: 0.0,
flight_to_quality_gain: 0.02,
flight_to_quality_reversal_cut: 0.0,
flight_to_quality_day: 0.0,
corporate_yield_daily: 0.0,
vix_pinned: false,
corporate_pinned: false,
spread_multiplier: None,
treasury_10y_pinned: false,
treasury_2y_pinned: false,
priced_put: 0.0,
priced_path: 0.0,
priced_anticipation: 0.0,
rate_damping: 0.0,
haven_gain: 0.0,
core_inflation: 0.0,
zlb_path: 0.0,
zlb_haven_gain: 0.0,
spread_vix_cut: 0.0,
spread_equity_gain: 0.0,
spread_equity_decay: 0.0,
spread_priced_keep: 0.0,
spread_priced_gain: 0.0,
treasury_equity_keep: 0.0,
treasury_equity_gain: 0.0,
spread_noise: None,
term_premium: None,
two_year_path: None,
}
}
}
impl<'a> Default for DailyInputs<'a> {
fn default() -> Self {
Self {
volatility: 1.0,
active_shocks: &[],
market_return_pct: 0.0,
game_day: 0,
trough_growth_floor: 0.0,
phase_target_range_draw: 0.0,
unemployment_adjustment: 0.0,
unemployment_natural_pull: 0.0,
unemployment_okun_coefficient: 0.0,
unemployment_natural_rate: 0.0,
oil_inventory_reversion: 0.0,
oil_mean_reversion: 0.0,
oil_noise_sd: 0.0,
oil_inventory_level_gain: 0.0,
oil_convenience_yield: 0.0,
oil_convenience_inventory_var: 0.0,
oil_convenience_inventory_var_before: 0.0,
oil_target_drift: None,
oil_growth: None,
oil_pushes_in_target: false,
oil_noise_log_sd: 0.0,
oil_dollar_elasticity: 0.0,
oil_inventory_noise_sd: 0.0,
usd_mean_reversion: 0.0,
usd_noise_sd: 0.0,
usd_safe_haven_gain: 0.0,
oil_inflation_tracked: false,
core_trend: 0.0,
oil_price_floor: 0.0,
oil_price_ceiling: 0.0,
oil_inflation_passthrough: 0.0,
fear_greed_published: None,
yields: YieldDials::default(),
vix_mean_reversion: VIX_MEAN_REVERSION,
vix_decay_ratio: 1.0,
vix_anchor_reversion: 0.0,
vix_anchor_level: 0.0,
vix_anchor_weight: 0.0,
vix_anchor_memory: 0.0,
macro_compound_days_per_year: 365.0,
macro_calendar: MacroCalendar::shipped(),
cycle_us_calibration: 0.0,
vix_anchor_centre: 0.0,
vix_anchor_weight_level: 0.0,
vix_anchor_weight_level_cap: 0.0,
vix_anchor_weight_level_knee: 0.0,
vix_anchor_weight_level_below: 0.0,
vix_anchor_weight_level_knee_fixed: 0.0,
vix_anchor_level_fixed: 0.0,
vix_anchor_slow: 0.0,
vix_fear_uptake: 0.0,
vix_fear: 0.0,
vix_target_premium: 0.0,
vix_target_floor: None,
vix_jump_intensity: 0.0,
vix_jump_scale: 0.0,
vix_return_gain: VIX_RETURN_GAIN,
vix_realised_vol_weight: 0.0,
vix_return_source: 0.0,
vix_cycle_amplitude: 1.0,
market_day_return_pct: 0.0,
vix_implied_from_market: 0.0,
vix_return_gain_up: VIX_RETURN_GAIN_UP,
vix_level_identity: 0.0,
vix_index_sigma_pct: 0.0,
vix_return_exponent: 1.0,
vix_return_clamp: VIX_RETURN_CLAMP,
vix_target_shock_cap: VIX_TARGET_SHOCK_CAP,
inflation_reversion: INFLATION_MEAN_REVERSION,
inflation_ceiling: INFLATION_CEILING,
inflation_floor: INFLATION_FLOOR,
crisis_vix_threshold: CRISIS_VIX_THRESHOLD,
usd_crisis_vix_threshold: CRISIS_VIX_THRESHOLD,
vix_ceiling: 80.0,
vix_target_offset: 0.0,
vix_return_level_exponent: 0.0,
vix_return_exponent_up: 1.0,
vix_return_level_exponent_up: 0.0,
vix_innovation_sigma: 0.0,
vix_innovation_return_sigma: 0.0,
vix_jump_level_scale: 0.0,
vix_jump_return_intensity: 0.0,
daily_credit_floor_gain: 0.0,
oil_supply_response: 0.0,
oil_opec_symmetry: 0.0,
oil_seasonality_target: 0.0,
}
}
}
pub fn expected_return_spike(sigma_pct: f64, gain: f64, gain_up: f64, exponent: f64) -> f64 {
if exponent == 1.0 {
return 0.5 * (gain - gain_up) * sigma_pct * (2.0 / SQRT_TWO_PI);
}
let e_abs = sigma_pct * (2.0 / SQRT_TWO_PI);
let e_pow = mathx::pow(sigma_pct, exponent)
* mathx::pow(2.0, 0.5 * exponent)
* mathx::tgamma(0.5 * (exponent + 1.0))
/ mathx::sqrt(core::f64::consts::PI);
0.5 * (gain * e_pow - gain_up * e_abs)
}
const SQRT_TWO_PI: f64 = 2.5066282746310002;
pub fn return_spike_for(current: f64, gain: f64, gain_up: f64, exponent: f64) -> f64 {
if current >= 0.0 || exponent == 1.0 {
if current < 0.0 {
-current * gain
} else {
-current * gain_up
}
} else {
gain * mathx::pow(-current, exponent)
}
}
pub fn anchor_weight_at_level(a: f64, eta: f64, cap: f64, below: f64, vix: f64, knee: f64) -> f64 {
if !(vix > 0.0) || !(knee > 0.0) {
return a;
}
let x = if cap != 0.0 { mathx::min(vix, cap * knee) } else { vix };
let x = if below == 0.0 { mathx::max(x, knee) } else { x };
let one_minus = (1.0 - a) * mathx::pow(knee / x, eta);
mathx::max(0.0, 1.0 - one_minus)
}
#[allow(clippy::too_many_arguments)]
pub fn return_spike_at_level(
current: f64,
gain: f64,
gain_up: f64,
exponent: f64,
exponent_up: f64,
level_exponent: f64,
level_exponent_up: f64,
vix: f64,
) -> f64 {
if level_exponent == 0.0 && exponent_up == 1.0 && level_exponent_up == 0.0 {
return return_spike_for(current, gain, gain_up, exponent);
}
if current < 0.0 {
let level = if level_exponent == 0.0 { 1.0 } else { mathx::pow(vix, -level_exponent) };
gain * mathx::pow(-current, exponent) * level
} else if current > 0.0 {
let level = if level_exponent_up == 0.0 { 1.0 } else { mathx::pow(vix, -level_exponent_up) };
-gain_up * mathx::pow(current, exponent_up) * level
} else {
0.0
}
}
#[allow(clippy::too_many_arguments)]
pub fn expected_return_spike_at_level(
sigma_pct: f64,
gain: f64,
gain_up: f64,
exponent: f64,
exponent_up: f64,
level_exponent: f64,
level_exponent_up: f64,
vix: f64,
) -> f64 {
if level_exponent == 0.0 && exponent_up == 1.0 && level_exponent_up == 0.0 {
return expected_return_spike(sigma_pct, gain, gain_up, exponent);
}
let moment = |q: f64| -> f64 {
mathx::pow(sigma_pct, q)
* mathx::pow(2.0, 0.5 * q)
* mathx::tgamma(0.5 * (q + 1.0))
/ mathx::sqrt(core::f64::consts::PI)
};
let down = if level_exponent == 0.0 { 1.0 } else { mathx::pow(vix, -level_exponent) };
let up = if level_exponent_up == 0.0 { 1.0 } else { mathx::pow(vix, -level_exponent_up) };
0.5 * (gain * down * moment(exponent) - gain_up * up * moment(exponent_up))
}
pub fn unemployment_drive(unemployment_trend: f64, phase: CyclePhase, growth: f64) -> f64 {
unemployment_drive_with(unemployment_trend, phase, growth, 0.0)
}
pub const OIL_INVENTORY_NORMAL: f64 = 50.0;
pub const OIL_CONVENIENCE_FLOOR: f64 = 25.0;
pub const OIL_CONVENIENCE_MIN: f64 = 0.25;
pub fn oil_convenience_factor(kappa: f64, inventory: f64, var: f64) -> f64 {
let at = |i: f64| {
let i = clamp(i, OIL_CONVENIENCE_FLOOR, 100.0);
mathx::max(OIL_CONVENIENCE_MIN, 1.0 - kappa * mathx::log(i / OIL_INVENTORY_NORMAL))
};
if !(var > 0.0) {
return at(inventory);
}
let sd = mathx::sqrt(var);
let (mut total, mut mass) = (0.0, 0.0);
for i in -60..=60 {
let z = i as f64 / 10.0;
let w = mathx::exp(-0.5 * z * z);
total += w * at(inventory + z * sd);
mass += w;
}
total / mass
}
pub const OIL_PASSTHROUGH_ANCHOR: f64 = OIL_BASELINE + 3.0 * 2.0;
pub fn unemployment_drive_with(
unemployment_trend: f64,
phase: CyclePhase,
growth: f64,
okun: f64,
) -> f64 {
if okun != 0.0 {
return unemployment_trend * 0.3 + (2.0 - growth) * (okun / 12.0);
}
let gdp_effect = (2.0 - growth) * 0.20;
let recovery_effect = if (phase == CyclePhase::Expansion || phase == CyclePhase::Recovery)
&& growth > 1.0
{
-growth * 0.08
} else {
0.0
};
unemployment_trend * 0.3 + gdp_effect + recovery_effect
}
pub fn vix_and_yields(
economy: &EconomyState,
inputs: &DailyInputs,
new_state: &mut EconomyState,
shock_gdp_impact: f64,
rng: &mut impl Rng,
) {
new_state.vix = vix_close(economy, inputs, shock_gdp_impact, rng);
let volatility = inputs.volatility;
close_yields(economy, inputs, new_state, volatility, rng);
}
pub fn identity_target_level(inputs: &DailyInputs, vix: f64) -> f64 {
let centre_level = if inputs.vix_anchor_centre != 0.0 {
inputs.vix_anchor_level * mathx::exp(-inputs.vix_anchor_centre)
} else {
inputs.vix_anchor_level
};
let weight = if inputs.vix_anchor_weight != 0.0 && inputs.vix_anchor_weight_level != 0.0 {
let knee_base = if inputs.vix_anchor_weight_level_knee_fixed != 0.0 {
inputs.vix_anchor_level_fixed
} else {
inputs.vix_anchor_level
};
let knee = if inputs.vix_anchor_weight_level_knee != 0.0 {
knee_base * mathx::exp(-inputs.vix_anchor_weight_level_knee)
} else {
knee_base
};
anchor_weight_at_level(
inputs.vix_anchor_weight,
inputs.vix_anchor_weight_level,
inputs.vix_anchor_weight_level_cap,
inputs.vix_anchor_weight_level_below,
vix,
knee,
)
} else {
inputs.vix_anchor_weight
};
if inputs.vix_anchor_weight != 0.0 && inputs.vix_anchor_memory != 0.0 {
inputs.vix_implied_from_market * mathx::exp(-weight * inputs.vix_anchor_slow)
} else if inputs.vix_anchor_weight != 0.0 {
let a = weight;
mathx::exp((1.0 - a) * mathx::log(inputs.vix_implied_from_market)
+ a * mathx::log(centre_level))
} else {
inputs.vix_implied_from_market
}
}
pub fn advance_vix_fear(fear: f64, inputs: &DailyInputs, vix: f64, half_life: f64) -> f64 {
let level = identity_target_level(inputs, vix);
if !(level > 0.0) || !(vix > 0.0) {
return fear;
}
let excursion = mathx::log(vix / level) - fear;
mathx::pow(0.5, 1.0 / half_life) * fear + inputs.vix_fear_uptake * excursion
}
pub fn vix_close(
economy: &EconomyState,
inputs: &DailyInputs,
shock_gdp_impact: f64,
rng: &mut impl Rng,
) -> f64 {
let volatility = inputs.volatility;
let day = inputs.game_day;
let cal = inputs.macro_calendar;
let year = cal.days_per_year;
let day_of_year = ((day - 1) % year) + 1;
let phase_vix = match economy.cycle_phase {
CyclePhase::Expansion => 14.0,
CyclePhase::Peak => 18.0,
CyclePhase::Contraction => 25.0,
CyclePhase::Trough => 22.0,
CyclePhase::Recovery => 16.0,
};
let identity_level = inputs.vix_level_identity != 0.0;
let mut target_vix = if identity_level {
let level = identity_target_level(inputs, economy.vix);
if inputs.vix_fear_uptake != 0.0 {
level * mathx::exp(inputs.vix_fear)
} else {
level
}
} else if inputs.vix_cycle_amplitude == 1.0 {
phase_vix
} else {
VIX_PHASE_MEAN + inputs.vix_cycle_amplitude * (phase_vix - VIX_PHASE_MEAN)
};
let clamp_vix = inputs.vix_return_clamp;
let driving_return = if identity_level {
inputs.market_day_return_pct
} else if inputs.vix_return_source == 0.0 {
inputs.market_return_pct
} else {
let s = inputs.vix_return_source;
(1.0 - s) * inputs.market_return_pct + s * inputs.market_day_return_pct
};
let current_mkt_ret_vix = mathx::max(-clamp_vix, mathx::min(clamp_vix, driving_return));
let return_spike = return_spike_at_level(
current_mkt_ret_vix, inputs.vix_return_gain,
inputs.vix_return_gain_up, inputs.vix_return_exponent,
inputs.vix_return_exponent_up, inputs.vix_return_level_exponent,
inputs.vix_return_level_exponent_up, economy.vix);
let inflation_adj = mathx::max(0.0, (economy.inflation_rate - 3.0) * 0.2);
let shock_adj = shock_gdp_impact.abs() * 2.0;
let excursion = if inputs.vix_target_premium != 0.0 {
return_spike + inflation_adj + shock_adj + inputs.vix_target_premium
} else {
return_spike + inflation_adj + shock_adj
};
target_vix += mathx::min(inputs.vix_target_shock_cap, excursion);
if identity_level {
target_vix -= expected_return_spike_at_level(
inputs.vix_index_sigma_pct,
inputs.vix_return_gain,
inputs.vix_return_gain_up,
inputs.vix_return_exponent,
inputs.vix_return_exponent_up,
inputs.vix_return_level_exponent,
inputs.vix_return_level_exponent_up,
economy.vix,
);
}
let month_len = cal.mean_month_len();
let earnings_month_vix = (((day_of_year - 1) % year) as f64 / month_len).floor() + 1.0;
let day_of_month_vix = day_of_year as f64 - ((earnings_month_vix - 1.0) * month_len).floor();
if !identity_level && day_of_month_vix <= cal.scale_days(15) as f64 {
target_vix += 0.5;
}
if !identity_level && inputs.vix_target_offset != 0.0 {
target_vix += inputs.vix_target_offset;
}
if !identity_level && inputs.vix_realised_vol_weight != 0.0 {
let w = inputs.vix_realised_vol_weight;
target_vix = (1.0 - w) * target_vix + w * inputs.vix_implied_from_market;
}
if let Some(floor) = inputs.vix_target_floor {
if target_vix < floor {
target_vix = floor;
}
}
let vix_mr = if target_vix < economy.vix {
inputs.vix_mean_reversion * inputs.vix_decay_ratio
} else {
inputs.vix_mean_reversion
};
let innovation_on = inputs.vix_innovation_sigma != 0.0
|| inputs.vix_innovation_return_sigma != 0.0;
let vix_noise_sd = if innovation_on {
let s0 = inputs.vix_innovation_sigma;
let sr = inputs.vix_innovation_return_sigma * current_mkt_ret_vix;
economy.vix * mathx::sqrt(s0 * s0 + sr * sr)
} else {
0.15 * volatility
};
let fear_jump = if inputs.vix_jump_intensity != 0.0
|| inputs.vix_jump_return_intensity != 0.0
{
let rate = if inputs.vix_jump_return_intensity != 0.0 {
inputs.vix_jump_intensity
+ inputs.vix_jump_return_intensity * mathx::max(0.0, -current_mkt_ret_vix)
} else {
inputs.vix_jump_intensity
};
let p_daily = rate / 252.0;
if rng.next_f64() < p_daily {
let draw = -mathx::log(mathx::max(rng.next_f64(), 1e-12));
if inputs.vix_jump_level_scale != 0.0 {
let unit = if innovation_on { vix_noise_sd } else { economy.vix };
inputs.vix_jump_level_scale * unit * draw
} else {
inputs.vix_jump_scale * draw
}
} else {
0.0
}
} else {
0.0
};
let stepped_vix = economy.vix
+ (target_vix - economy.vix) * vix_mr
+ random_normal(rng, 0.0, vix_noise_sd)
+ fear_jump;
let stepped_vix = if inputs.vix_anchor_reversion != 0.0 {
stepped_vix + inputs.vix_anchor_reversion * (inputs.vix_anchor_level - economy.vix)
} else {
stepped_vix
};
clamp(stepped_vix, 10.0, inputs.vix_ceiling)
}
fn two_year_target(legacy: f64, yields: &YieldDials) -> f64 {
match yields.two_year_path {
Some((d, path)) => {
let tp = match yields.term_premium {
Some(x) => TWO_YEAR_TERM_PREMIUM + TWO_YEAR_TERM_PREMIUM_BETA * x,
None => TWO_YEAR_TERM_PREMIUM,
};
legacy + d * (path + tp - legacy)
}
None => legacy,
}
}
fn close_yields(
economy: &EconomyState,
inputs: &DailyInputs,
new_state: &mut EconomyState,
volatility: f64,
rng: &mut impl Rng,
) {
let curve_inflation = if inputs.yields.core_inflation != 0.0 {
economy.inflation_rate - economy.oil_inflation_level
} else {
economy.inflation_rate
};
let debt_premium = mathx::max(0.0, (economy.government_debt_to_gdp - 100.0) * 0.002);
let term_premium_10y =
1.0 + mathx::max(0.0, (curve_inflation - 2.0) * 0.3) + debt_premium;
let term_premium_10y = if inputs.yields.haven_gain != 0.0
&& curve_inflation < crate::economy::central_bank::FED_PUT_INFLATION_CEILING
{
term_premium_10y - haven_term_cut(inputs.yields.haven_gain, new_state.vix)
} else {
term_premium_10y
};
let term_premium_10y = if inputs.yields.zlb_haven_gain != 0.0
&& new_state.federal_funds_rate <= ZLB_RATE
&& curve_inflation < crate::economy::central_bank::FED_PUT_INFLATION_CEILING
{
term_premium_10y - haven_term_cut(inputs.yields.zlb_haven_gain, new_state.vix)
} else {
term_premium_10y
};
let fed_rate_for_10y = if inputs.yields.priced_put != 0.0 {
new_state.federal_funds_rate - inputs.yields.priced_put
} else {
new_state.federal_funds_rate
};
let fed_rate_for_10y = if inputs.yields.zlb_path != 0.0 {
fed_rate_for_10y - inputs.yields.zlb_path
} else {
fed_rate_for_10y
};
let fed_rate_for_10y = if inputs.yields.priced_path != 0.0 {
fed_rate_for_10y + inputs.yields.priced_path
} else {
fed_rate_for_10y
};
let fed_rate_for_10y = if inputs.yields.priced_anticipation != 0.0 {
fed_rate_for_10y + inputs.yields.priced_anticipation
} else {
fed_rate_for_10y
};
let term_premium_10y = if let Some(x) = inputs.yields.term_premium {
term_premium_10y + x
} else {
term_premium_10y
};
let term_premium_10y = if inputs.yields.treasury_equity_gain != 0.0 {
term_premium_10y - inputs.yields.treasury_equity_gain * economy.treasury_equity_priced_gap
} else {
term_premium_10y
};
let current_10y = new_state.treasury_yield_10y;
let rate_for_10y_anchor = if inputs.yields.rate_damping != 0.0 {
let ladder = new_state.federal_funds_rate + new_state.fed_put_owed + inputs.yields.priced_path;
let ladder = if inputs.yields.priced_anticipation != 0.0 {
ladder + inputs.yields.priced_anticipation
} else {
ladder
};
fed_rate_for_10y - inputs.yields.rate_damping * (ladder - TREASURY_NEUTRAL_RATE)
} else {
fed_rate_for_10y
};
new_state.treasury_yield_10y = clamp(
current_10y
+ (rate_for_10y_anchor + term_premium_10y - current_10y) * 0.05
+ random_normal(rng, 0.0, inputs.yields.treasury_10y_noise * volatility),
0.5,
12.0,
);
if inputs.yields.treasury_10y_pinned {
new_state.treasury_yield_10y = current_10y;
}
let target_2y = fed_rate_for_10y * 0.85 + new_state.treasury_yield_10y * 0.15;
let target_2y = two_year_target(target_2y, &inputs.yields);
let own_2y = inputs.yields.treasury_2y_noise != 0.0;
new_state.treasury_yield_2y = if own_2y {
clamp(
economy.treasury_yield_2y
+ (target_2y - economy.treasury_yield_2y) * 0.05
+ random_normal(rng, 0.0, inputs.yields.treasury_2y_noise * volatility),
0.0,
12.0,
)
} else {
target_2y
};
if inputs.yields.treasury_2y_pinned {
new_state.treasury_yield_2y = economy.treasury_yield_2y;
}
let (prev_mkt_ret, ftq_gate) = if inputs.yields.flight_to_quality_day != 0.0 {
(inputs.market_day_return_pct, 0.0)
} else {
(economy.previous_day_market_return, 0.5)
};
let ftq_gain = inputs.yields.flight_to_quality_gain;
if prev_mkt_ret.abs() > ftq_gate {
let bond_stock_yield_shift = if curve_inflation > 4.0 {
if inputs.yields.flight_to_quality_reversal_cut != 0.0 {
-prev_mkt_ret * ftq_gain * (1.0 - inputs.yields.flight_to_quality_reversal_cut)
} else {
-prev_mkt_ret * ftq_gain
}
} else if curve_inflation < 3.0 {
prev_mkt_ret * ftq_gain
} else {
0.0
};
if !inputs.yields.treasury_10y_pinned {
new_state.treasury_yield_10y = clamp(
new_state.treasury_yield_10y + bond_stock_yield_shift,
0.5,
12.0,
);
}
if !inputs.yields.treasury_2y_pinned {
new_state.treasury_yield_2y = if own_2y {
clamp(new_state.treasury_yield_2y + bond_stock_yield_shift, 0.0, 12.0)
} else {
two_year_target(
new_state.federal_funds_rate * 0.85 + new_state.treasury_yield_10y * 0.15,
&inputs.yields,
)
};
}
}
let equity_gain = inputs.yields.spread_equity_gain;
let (gap_before, gap_after) = if equity_gain != 0.0 || inputs.yields.spread_equity_decay != 0.0 {
let r = mathx::log(mathx::max(1.0 + inputs.market_day_return_pct / 100.0, 1e-6));
let g = inputs.yields.spread_equity_decay * (economy.spread_equity_gap - r);
new_state.spread_equity_gap = g;
(economy.spread_equity_gap, g)
} else {
(0.0, 0.0)
};
if inputs.yields.treasury_equity_keep != 0.0 {
let p = economy.treasury_equity_priced_gap;
new_state.treasury_equity_priced_gap =
p + (1.0 - inputs.yields.treasury_equity_keep) * (new_state.spread_equity_gap - p);
}
let (gap_before, gap_after) = if equity_gain != 0.0 && inputs.yields.spread_priced_keep != 0.0 {
let p = economy.spread_priced_gap;
let q = p + (1.0 - inputs.yields.spread_priced_keep) * (gap_after - p);
new_state.spread_priced_gap = q;
let lagged = inputs.yields.spread_priced_gain;
if lagged != 0.0 {
let k = lagged / equity_gain;
(gap_before + k * p, gap_after + k * q)
} else {
(p, q)
}
} else {
(gap_before, gap_after)
};
if inputs.yields.corporate_yield_daily != 0.0 && !inputs.yields.corporate_pinned {
let cycle_spread_multiplier =
crate::economy::central_bank::spread_multiplier_of(economy.cycle_phase);
let spread_noise = inputs.yields.spread_noise;
let spread_dials = inputs.yields.spread_vix_cut != 0.0 || equity_gain != 0.0 || spread_noise.is_some();
let base_term = |gap: f64, x: f64| if spread_noise.is_some() { equity_gain * gap + x } else { equity_gain * gap };
let (x_before, x_after) = spread_noise.unwrap_or((0.0, 0.0));
let vix_term = if let Some((m0, m1)) = inputs.yields.spread_multiplier {
let vix_close = if inputs.yields.vix_pinned { economy.vix } else { new_state.vix };
if spread_dials {
let cut = inputs.yields.spread_vix_cut;
crate::economy::central_bank::spread_formula_with(
vix_close, m1, cut, base_term(gap_after, x_after))
- crate::economy::central_bank::spread_formula_with(
economy.vix, m0, cut, base_term(gap_before, x_before))
} else {
crate::economy::central_bank::spread_formula(vix_close, m1)
- crate::economy::central_bank::spread_formula(economy.vix, m0)
}
} else if spread_dials {
let vix_part = if inputs.yields.vix_pinned {
0.0
} else {
0.02 * (1.0 - inputs.yields.spread_vix_cut)
* cycle_spread_multiplier * (new_state.vix - economy.vix)
};
let own = if spread_noise.is_some() { cycle_spread_multiplier * (x_after - x_before) } else { 0.0 };
vix_part + equity_gain * cycle_spread_multiplier * (gap_after - gap_before) + own
} else if inputs.yields.vix_pinned {
0.0
} else {
0.02 * cycle_spread_multiplier * (new_state.vix - economy.vix)
};
let moved = clamp(
(new_state.treasury_yield_10y - economy.treasury_yield_10y) + vix_term,
-CORPORATE_DAILY_MOVE_CAP,
CORPORATE_DAILY_MOVE_CAP,
);
new_state.corporate_bond_yield = mathx::max(
economy.corporate_bond_yield + moved,
new_state.treasury_yield_10y + crate::economy::central_bank::CORPORATE_SPREAD_FLOOR,
);
}
}
pub struct MeanDraws;
impl Rng for MeanDraws {
fn next_f64(&mut self) -> f64 {
1.0 - f64::EPSILON
}
fn next_normal(&mut self) -> f64 {
0.0
}
}
pub fn inventory_pressure(inventory: f64) -> f64 {
let mut pressure = 0.0;
if inventory < 40.0 {
pressure = (40.0 - inventory) * 0.08;
} else if inventory > 60.0 {
pressure = (60.0 - inventory) * 0.08;
}
pressure
}
pub fn oil_bounds(floor: f64, ceiling: f64) -> (f64, f64) {
(if floor == 0.0 { 35.0 } else { floor }, if ceiling == 0.0 { 150.0 } else { ceiling })
}
pub fn oil_clamped_expectation(mean: f64, sd: f64, (lo, hi): (f64, f64)) -> f64 {
if !(sd > 0.0) {
return clamp(mean, lo, hi);
}
let (a, b) = ((lo - mean) / sd, (hi - mean) / sd);
let pdf = |x: f64| mathx::exp(-0.5 * x * x) / mathx::sqrt(2.0 * std::f64::consts::PI);
let cdf = |x: f64| 0.5 * mathx::erfc(-x / std::f64::consts::SQRT_2);
let (fa, fb) = (cdf(a), cdf(b));
lo * fa + hi * (1.0 - fb) + mean * (fb - fa) + sd * (pdf(a) - pdf(b))
}
pub fn oil_lognormal_censored(mean: f64, log_var: f64, (lo, hi): (f64, f64)) -> f64 {
if !(log_var > 0.0) || !(mean > 0.0) {
return clamp(mean, lo, hi);
}
let cdf = |x: f64| 0.5 * mathx::erfc(-x / std::f64::consts::SQRT_2);
let sd = mathx::sqrt(log_var);
let m = mathx::log(mean) - 0.5 * log_var;
let (l_lo, l_hi) = (mathx::log(lo), mathx::log(hi));
let p_lo = cdf((l_lo - m) / sd);
let p_hi = 1.0 - cdf((l_hi - m) / sd);
let inside = mean * (cdf((l_hi - m - log_var) / sd) - cdf((l_lo - m - log_var) / sd));
lo * p_lo + hi * p_hi + inside
}
pub fn oil_lognormal_log_truncation(mean: f64, log_var: f64, (lo, hi): (f64, f64)) -> f64 {
if !(log_var > 0.0) || !(mean > 0.0) {
return 0.0;
}
let pdf = |x: f64| mathx::exp(-0.5 * x * x) / mathx::sqrt(2.0 * std::f64::consts::PI);
let cdf = |x: f64| 0.5 * mathx::erfc(-x / std::f64::consts::SQRT_2);
let sd = mathx::sqrt(log_var);
let m = mathx::log(mean) - 0.5 * log_var;
let (a, b) = (mathx::log(hi), mathx::log(lo));
let za = (a - m) / sd;
let zb = (b - m) / sd;
let over = sd * pdf(za) + (m - a) * (1.0 - cdf(za));
let under = sd * pdf(zb) + (b - m) * cdf(zb);
under - over
}
pub fn oil_expected_log_truncation(mean: f64, sd: f64, (lo, hi): (f64, f64)) -> f64 {
if !(sd > 0.0) || !(mean > 0.0) {
return 0.0;
}
let (mut total, mut mass) = (0.0, 0.0);
for i in -60..=60 {
let z = i as f64 / 10.0;
let w = mathx::exp(-0.5 * z * z);
let x = mathx::max(mean + sd * z, 0.01 * mean);
total += w * mathx::log(clamp(x, lo, hi) / x);
mass += w;
}
total / mass
}
pub fn inventory_noise(inputs: &DailyInputs) -> f64 {
if inputs.oil_inventory_noise_sd == 0.0 {
0.5
} else {
inputs.oil_inventory_noise_sd
}
}
pub fn inventory_pressure_expected(mean: f64, sd: f64) -> f64 {
if !(sd > 0.0) {
return inventory_pressure(mean);
}
let shortfall = |a: f64, x_mean: f64| {
let d = (a - x_mean) / sd;
let cdf = 0.5 * mathx::erfc(-d / std::f64::consts::SQRT_2);
let pdf = mathx::exp(-0.5 * d * d) / mathx::sqrt(2.0 * std::f64::consts::PI);
(a - x_mean) * cdf + sd * pdf
};
0.08 * (shortfall(40.0, mean) - shortfall(-60.0, -mean))
}
pub const USD_SAFE_HAVEN_GAIN: f64 = 0.05;
pub fn usd_safe_haven_gain(dial: f64) -> f64 {
if dial == 0.0 {
USD_SAFE_HAVEN_GAIN
} else {
dial
}
}
pub fn phase_entry_growth_shock(phase: CyclePhase, u: f64, volatility: f64) -> f64 {
let contraction_shock = -(2.0 + u * (1.0 + volatility));
match phase {
CyclePhase::Contraction => contraction_shock,
CyclePhase::Trough => -0.5,
CyclePhase::Recovery => 1.0,
CyclePhase::Expansion => 0.5,
CyclePhase::Peak => 0.0,
}
}
const OPEC_TARGET: f64 = 80.0;
const OPEC_BAND: f64 = 10.0;
pub fn opec_rule(symmetry: f64) -> (f64, f64, f64, f64) {
if symmetry == 0.0 {
(0.6, 3.0, 0.5, 2.0)
} else {
let g = symmetry;
(0.6 - 0.05 * g, 3.0 - 0.5 * g, 0.5 + 0.05 * g, 2.0 + 0.5 * g)
}
}
pub fn opec_expected_impact(mean: f64, sd: f64, symmetry: f64) -> f64 {
let (cut_p, cut_lo, raise_p, raise_lo) = opec_rule(symmetry);
let below = OPEC_TARGET - OPEC_BAND;
let above = OPEC_TARGET + OPEC_BAND;
let (p_below, p_above) = if sd > 0.0 {
(
0.5 * mathx::erfc((mean - below) / (sd * std::f64::consts::SQRT_2)),
0.5 * mathx::erfc((above - mean) / (sd * std::f64::consts::SQRT_2)),
)
} else {
(
if mean < below { 1.0 } else { 0.0 },
if mean > above { 1.0 } else { 0.0 },
)
};
cut_p * (cut_lo + 1.5) * p_below - raise_p * (raise_lo + 1.5) * p_above
}
pub fn opec_expected_impact_lognormal(mean: f64, log_var: f64, symmetry: f64) -> f64 {
if !(mean > 0.0) || !(log_var > 0.0) {
return opec_expected_impact(mean, 0.0, symmetry);
}
let (cut_p, cut_lo, raise_p, raise_lo) = opec_rule(symmetry);
let mu = mathx::log(mean) - 0.5 * log_var;
let s = mathx::sqrt(2.0 * log_var);
let p_below = 0.5 * mathx::erfc((mu - mathx::log(OPEC_TARGET - OPEC_BAND)) / s);
let p_above = 0.5 * mathx::erfc((mathx::log(OPEC_TARGET + OPEC_BAND) - mu) / s);
cut_p * (cut_lo + 1.5) * p_below - raise_p * (raise_lo + 1.5) * p_above
}
pub fn project_close_yields(economy: &EconomyState, inputs: &DailyInputs) -> (f64, f64, f64) {
let next = project_close_state(economy, inputs);
(next.treasury_yield_2y, next.treasury_yield_10y, next.corporate_bond_yield)
}
pub fn project_close_state(economy: &EconomyState, inputs: &DailyInputs) -> EconomyState {
let mut next = economy.clone();
let mut shock_gdp_impact = 0.0;
for shock in inputs.active_shocks {
shock_gdp_impact += shock.gdp_impact * shock.severity;
}
vix_and_yields(economy, inputs, &mut next, shock_gdp_impact, &mut MeanDraws);
if inputs.daily_credit_floor_gain > 0.0 {
next.corporate_bond_yield = mathx::max(
next.corporate_bond_yield,
next.treasury_yield_10y + inputs.daily_credit_floor_gain * CORPORATE_SPREAD_FLOOR,
);
}
next
}
pub fn update_economy_daily(
economy: &EconomyState,
inputs: &DailyInputs,
rng: &mut impl Rng,
) -> EconomyState {
let volatility = inputs.volatility;
let mut new_state = economy.clone();
let phase = phase_characteristics_for(economy.cycle_phase, inputs.cycle_us_calibration != 0.0);
let day = inputs.game_day;
let cal = inputs.macro_calendar;
let is_month_start = day % cal.days_per_month == 0;
let is_quarter_start = day % cal.days_per_quarter() == 0;
let mut shock_gdp_impact = 0.0;
let mut shock_inflation_impact = 0.0;
let mut shock_oil_impact = 0.0;
for shock in inputs.active_shocks {
shock_gdp_impact += shock.gdp_impact * shock.severity;
if shock.kind == ShockKind::OilShock {
shock_oil_impact += shock.severity * 50.0;
}
if shock.kind == ShockKind::Pandemic || shock.kind == ShockKind::War {
shock_inflation_impact += shock.severity * 2.0;
}
}
let gdp_floor = -5.0 - (volatility - 0.5) * 10.0;
if economy.months_in_current_phase < 1.0 / cal.month_f64() + 0.001 {
let shock =phase_entry_growth_shock(economy.cycle_phase, rng.next_f64(), volatility);
if shock != 0.0 {
new_state.gdp_growth = clamp(economy.gdp_growth + shock, gdp_floor, 6.0);
}
if inputs.phase_target_range_draw != 0.0 {
let r = effective_gdp_range(
&phase, economy.cycle_phase, inputs.trough_growth_floor);
let mid = (r.0 + r.1) / 2.0;
let drawn = r.0 + rng.next_f64() * (r.1 - r.0);
new_state.phase_gdp_target =
mid + inputs.phase_target_range_draw * (drawn - mid);
}
}
if is_quarter_start {
let range = effective_gdp_range(
&phase, economy.cycle_phase, inputs.trough_growth_floor);
let target_gdp = phase_growth_target(
new_state.phase_gdp_target, range, inputs.phase_target_range_draw)
+ shock_gdp_impact;
new_state.gdp_growth = clamp(
new_state.gdp_growth
+ (target_gdp - new_state.gdp_growth) * 0.25
+ random_normal(rng, 0.0, 0.3 * volatility),
gdp_floor,
6.0,
);
}
new_state.gdp = economy.gdp * (1.0 + new_state.gdp_growth / 100.0 / inputs.macro_compound_days_per_year);
if is_month_start {
let range = effective_gdp_range(
&phase, economy.cycle_phase, inputs.trough_growth_floor);
let phase_gdp_target = phase_growth_target(
new_state.phase_gdp_target, range, inputs.phase_target_range_draw);
let gdp_gap = phase_gdp_target - new_state.gdp_growth;
#[allow(clippy::if_same_then_else)]
let gdp_correction_multiplier = if (economy.cycle_phase == CyclePhase::Contraction
|| economy.cycle_phase == CyclePhase::Trough)
&& new_state.gdp_growth > 0.0
{
2.0
} else if (economy.cycle_phase == CyclePhase::Recovery
|| economy.cycle_phase == CyclePhase::Expansion)
&& new_state.gdp_growth < 0.0
{
2.0
} else {
1.0
};
new_state.gdp_growth = clamp(
new_state.gdp_growth
+ gdp_gap * 0.12 * gdp_correction_multiplier
+ random_normal(rng, 0.0, 0.1 * volatility),
gdp_floor,
6.0,
);
let okun = inputs.unemployment_okun_coefficient;
let gdp_effect = if okun == 0.0 {
(2.0 - new_state.gdp_growth) * 0.20
} else {
(2.0 - new_state.gdp_growth) * (okun / 12.0)
};
let nairu = economy.structural_unemployment;
let nairu_pull = if inputs.unemployment_natural_pull == 0.0 {
(nairu - economy.unemployment_rate) * 0.06
} else {
(nairu - economy.unemployment_rate) * inputs.unemployment_natural_pull
};
let mut recovery_effect = 0.0;
if okun == 0.0
&& (economy.cycle_phase == CyclePhase::Expansion
|| economy.cycle_phase == CyclePhase::Recovery)
&& new_state.gdp_growth > 1.0
{
recovery_effect = -new_state.gdp_growth * 0.08;
}
new_state.unemployment_rate = if inputs.unemployment_adjustment == 0.0 {
clamp(
economy.unemployment_rate
+ phase.unemployment_trend * 0.3
+ gdp_effect
+ nairu_pull
+ recovery_effect
+ random_normal(rng, 0.0, 0.06 * volatility),
2.5,
15.0,
)
} else {
let drive = unemployment_drive_with(
phase.unemployment_trend, economy.cycle_phase, new_state.gdp_growth, okun);
let impulse = economy.unemployment_impulse
+ inputs.unemployment_adjustment * (drive - economy.unemployment_impulse);
new_state.unemployment_impulse = impulse;
clamp(
economy.unemployment_rate
+ impulse
+ nairu_pull
+ random_normal(rng, 0.0, 0.06 * volatility),
2.5,
15.0,
)
};
let unemployment_change = new_state.unemployment_rate - economy.unemployment_rate;
new_state.jobs_created = clamp(
200000.0 - unemployment_change * 500000.0
+ random_normal(rng, 0.0, 30000.0 * volatility),
-500000.0,
500000.0,
);
let inflation_target = if inputs.core_trend != 0.0 {
INFLATION_TARGET + inputs.core_trend
} else {
INFLATION_TARGET
};
let inflation_mean_rev_coeff = inputs.inflation_reversion;
let real_rate_suppression = if economy.federal_funds_rate > economy.inflation_rate {
-(economy.federal_funds_rate - economy.inflation_rate) * 0.04
} else if economy.federal_funds_rate > 3.0 {
-(economy.federal_funds_rate - 3.0) * 0.015
} else {
0.0
};
let oil_inflation_effect = if inputs.oil_inflation_passthrough != 0.0 {
(economy.oil_price - OIL_PASSTHROUGH_ANCHOR) * (0.01 * inputs.oil_inflation_passthrough)
} else if economy.oil_price > 80.0 {
(economy.oil_price - 80.0) * 0.01
} else if economy.oil_price < 50.0 {
(economy.oil_price - 50.0) * 0.005
} else {
0.0
};
let tariff_inflation_effect = (economy.tariff_rate - 5.0) * 0.01;
let nairu_for_phillips = economy.structural_unemployment;
let unemployment_gap = new_state.unemployment_rate - nairu_for_phillips;
let phillips_curve_effect = -unemployment_gap * PHILLIPS_CURVE_COEFF;
let usd_inflation_effect = -(economy.usd_index - 100.0) * 0.01;
let mut wage_growth_target =
economy.inflation_rate * 0.7 + (nairu_for_phillips - economy.unemployment_rate) * 0.5;
if economy.inflation_rate > 3.0 {
let cola_floor = economy.inflation_rate * 0.8;
wage_growth_target = mathx::max(wage_growth_target, cola_floor);
}
new_state.wage_growth =
economy.wage_growth + (wage_growth_target - economy.wage_growth) * 0.15;
let mut wage_pressure = mathx::max(0.0, new_state.wage_growth - 2.0) * 0.08;
let spiral_condition = economy.wage_growth > 4.0 && economy.inflation_rate > 3.0;
let spiral_boost = if spiral_condition {
(economy.wage_growth - 4.0) * (economy.inflation_rate - 3.0) * 0.02
} else {
0.0
};
wage_pressure += spiral_boost;
new_state.inflation_rate = clamp(
economy.inflation_rate
+ (inflation_target - economy.inflation_rate) * inflation_mean_rev_coeff
+ phase.inflation_trend * 0.04
+ shock_inflation_impact * 0.02
+ real_rate_suppression
+ oil_inflation_effect
+ tariff_inflation_effect * 0.03
+ usd_inflation_effect * 0.03
+ phillips_curve_effect
+ wage_pressure
+ random_normal(rng, 0.0, 0.04 * volatility),
inputs.inflation_floor,
inputs.inflation_ceiling,
);
if inputs.oil_inflation_tracked {
new_state.oil_inflation_level = economy.oil_inflation_level
+ (0.0 - economy.oil_inflation_level) * inflation_mean_rev_coeff
+ oil_inflation_effect;
}
new_state.core_inflation = clamp(
economy.core_inflation + (new_state.inflation_rate - economy.core_inflation) * 0.3,
-1.0,
12.0,
);
let confidence_phase_adj = match economy.cycle_phase {
CyclePhase::Contraction => -20.0,
CyclePhase::Trough => -15.0,
CyclePhase::Peak => 5.0,
CyclePhase::Recovery => -5.0,
CyclePhase::Expansion => 0.0,
};
let confidence_base = 100.0 + economy.gdp_growth * 5.0 - economy.unemployment_rate * 3.0
+ confidence_phase_adj;
let fear_greed_nudge = (economy.fear_greed_index - 50.0) / 50.0 * 2.0;
let market_return_nudge = economy.rolling_market_return_30d * 3.0;
new_state.consumer_confidence = clamp(
economy.consumer_confidence
+ (confidence_base - economy.consumer_confidence) * 0.25
+ fear_greed_nudge
+ market_return_nudge
+ random_normal(rng, 0.0, 3.0 * volatility),
40.0,
130.0,
);
new_state.business_confidence = clamp(
economy.business_confidence
+ (confidence_base - economy.business_confidence) * 0.20
+ market_return_nudge * 1.5
+ random_normal(rng, 0.0, 4.5 * volatility),
40.0,
130.0,
);
let confidence_housing_adj = (new_state.consumer_confidence - 100.0) * 0.1;
let housing_target = 100.0 - (economy.mortgage_rate_30y - 5.0) * 4.0
+ economy.gdp_growth * 2.0
+ confidence_housing_adj;
let volume_speed_factor = mathx::max(0.3, economy.housing_transaction_volume / 100.0);
let housing_mean_rev = (clamp(housing_target, 75.0, 130.0) - economy.housing_index)
* 0.08
* volume_speed_factor;
let recession_effect = if economy.recession_probability > 0.3 {
-(economy.recession_probability - 0.3) * 2.0
} else {
0.0
};
let housing_change =
housing_mean_rev + recession_effect + random_normal(rng, 0.0, 0.3 * volatility);
new_state.housing_index = clamp(economy.housing_index + housing_change, 75.0, 180.0);
let mortgage_effect = mathx::max(-0.3, -(economy.mortgage_rate_30y - 5.0) * 0.05);
let housing_gdp_effect = if economy.gdp_growth > 2.0 {
0.02
} else if economy.gdp_growth < 0.0 {
-0.05
} else {
0.0
};
new_state.home_starts_monthly = mathx::max(
500000.0,
mathx::min(
2000000.0,
economy.home_starts_monthly
* (1.0
+ mortgage_effect
+ housing_gdp_effect
+ random_normal(rng, 0.0, 1.0) * 0.02),
),
);
let rate_shock = mathx::max(0.0, economy.mortgage_rate_30y - 5.0);
let volume_target = mathx::max(
30.0,
100.0 - rate_shock * 15.0 - mathx::max(0.0, (economy.unemployment_rate - 5.0) * 5.0),
);
new_state.housing_transaction_volume = economy.housing_transaction_volume
+ (volume_target - economy.housing_transaction_volume) * 0.30;
if economy.cycle_phase == CyclePhase::Contraction
|| economy.cycle_phase == CyclePhase::Trough
{
let ltu_target = economy.unemployment_rate * 0.4;
new_state.long_term_unemployment_rate = economy.long_term_unemployment_rate
+ (ltu_target - economy.long_term_unemployment_rate) * 0.05;
} else {
new_state.long_term_unemployment_rate =
mathx::max(0.5, economy.long_term_unemployment_rate * 0.97);
}
let natural_base = if inputs.unemployment_natural_rate == 0.0 {
4.0
} else {
inputs.unemployment_natural_rate
};
new_state.structural_unemployment =
natural_base + new_state.long_term_unemployment_rate * 0.3;
let lfp_target = if economy.cycle_phase == CyclePhase::Contraction
|| economy.cycle_phase == CyclePhase::Trough
{
60.0 - (economy.unemployment_rate - 5.0) * 0.5
} else {
63.0 + (economy.gdp_growth - 1.0) * 0.3
};
let lfp_drift = (lfp_target - economy.labor_force_participation) * 0.01;
new_state.labor_force_participation = mathx::max(
55.0,
mathx::min(68.0, economy.labor_force_participation + lfp_drift),
);
if economy.cycle_phase == CyclePhase::Contraction
|| economy.cycle_phase == CyclePhase::Trough
{
let auto_stabilizer = 1.0;
let discretionary = if economy.unemployment_rate > 7.0 {
mathx::min(4.0, (economy.unemployment_rate - 5.0) * 0.8)
} else {
0.0
};
new_state.fiscal_stimulus = mathx::min(6.0, auto_stabilizer + discretionary);
new_state.gdp_growth += new_state.fiscal_stimulus * FISCAL_MULTIPLIER / 12.0;
new_state.government_debt_to_gdp =
economy.government_debt_to_gdp + new_state.fiscal_stimulus / 12.0;
} else {
new_state.fiscal_stimulus = mathx::max(0.0, economy.fiscal_stimulus - 0.2);
if new_state.gdp_growth > 2.0 {
new_state.government_debt_to_gdp =
mathx::max(60.0, economy.government_debt_to_gdp - 0.05);
} else {
new_state.government_debt_to_gdp = economy.government_debt_to_gdp;
}
}
}
new_state.cpi = economy.cpi * (1.0 + new_state.inflation_rate / 100.0 / inputs.macro_compound_days_per_year);
let oil_inventory = economy.oil_inventory_level;
let oil_last_opec = economy.oil_last_opec_day;
let oil_growth = inputs.oil_growth.unwrap_or(economy.gdp_growth);
let oil_demand_factor = oil_growth * 0.15;
let oil_supply_factor = if inputs.oil_supply_response == 0.0 {
0.0
} else {
oil_demand_factor * inputs.oil_supply_response
};
let inventory_change =
oil_demand_factor - oil_supply_factor + random_normal(rng, 0.0, inventory_noise(inputs) * volatility);
let new_oil_inventory = if inputs.oil_inventory_reversion == 0.0 {
clamp(oil_inventory - inventory_change, 0.0, 100.0)
} else {
clamp(
oil_inventory - inventory_change
+ inputs.oil_inventory_reversion * (OIL_INVENTORY_NORMAL - oil_inventory),
0.0,
100.0,
)
};
new_state.oil_inventory_level = new_oil_inventory;
let oil_inventory_pressure = if inputs.oil_inventory_level_gain == 0.0 {
inventory_pressure(new_oil_inventory)
} else {
inputs.oil_inventory_level_gain * (inventory_pressure(new_oil_inventory) - inventory_pressure(oil_inventory))
};
let year = cal.days_per_year;
let day_of_year = ((day - 1) % year) + 1;
let oil_seasonal_amplitude = 0.03
* mathx::sin(2.0 * std::f64::consts::PI
* (day_of_year as f64 - cal.scale_days(90) as f64) / year as f64);
let oil_usd_drag = if inputs.oil_dollar_elasticity == 0.0 {
-(economy.usd_index - 100.0) * 0.08
} else {
0.0
};
let mut opec_impact = 0.0;
if day - oil_last_opec >= cal.opec_interval() {
new_state.oil_last_opec_day = day;
let oil_price = economy.oil_price;
let price_diff = oil_price - OPEC_TARGET;
let (cut_p, cut_lo, raise_p, raise_lo) = opec_rule(inputs.oil_opec_symmetry);
if price_diff < -OPEC_BAND {
if rng.next_f64() < cut_p {
opec_impact = cut_lo + rng.next_f64() * 3.0;
}
} else if price_diff > OPEC_BAND {
if rng.next_f64() < raise_p {
opec_impact = -(raise_lo + rng.next_f64() * 3.0);
}
} else {
if rng.next_f64() < 0.2 {
opec_impact = (rng.next_f64() - 0.5) * 3.0;
}
}
}
let oil_target_level = OIL_BASELINE + oil_growth * 3.0 + shock_oil_impact * 10.0;
let (oil_target, oil_level_seasonality) = if inputs.oil_seasonality_target == 0.0 {
(oil_target_level, 1.0 + oil_seasonal_amplitude)
} else {
let g = inputs.oil_seasonality_target;
(
oil_target_level * (1.0 + g * oil_seasonal_amplitude),
1.0 + (1.0 - g) * oil_seasonal_amplitude,
)
};
let (oil_reversion_target, oil_premium_ratio) = if inputs.oil_convenience_yield == 0.0
&& inputs.oil_target_drift.is_none()
&& inputs.oil_dollar_elasticity == 0.0
{
(oil_target, None)
} else {
let (mut opened, mut left) = (1.0, 1.0);
if inputs.oil_convenience_yield != 0.0 {
let k = inputs.oil_convenience_yield;
opened = oil_convenience_factor(k, oil_inventory, inputs.oil_convenience_inventory_var_before);
left = oil_convenience_factor(k, new_oil_inventory, inputs.oil_convenience_inventory_var);
}
if let Some((d, d_next)) = inputs.oil_target_drift {
opened *= mathx::exp(d);
left *= mathx::exp(d_next);
}
if inputs.oil_dollar_elasticity != 0.0 {
let g = mathx::pow(economy.usd_index / 100.0, -inputs.oil_dollar_elasticity);
opened *= g;
left *= g;
}
(oil_target * opened, Some(left / opened))
};
let oil_reverting = if inputs.oil_pushes_in_target {
economy.oil_price - economy.oil_push_level
} else {
economy.oil_price
};
let oil_mean_rev = if inputs.oil_mean_reversion == 0.0 {
(oil_reversion_target - oil_reverting) * 0.03
} else {
(oil_reversion_target - oil_reverting) * inputs.oil_mean_reversion
};
let oil_volatility = if inputs.oil_noise_sd == 0.0 { 2.0 * volatility } else { inputs.oil_noise_sd * volatility };
let oil_volatility = if inputs.oil_noise_log_sd == 0.0 {
oil_volatility
} else {
inputs.oil_noise_log_sd * volatility * economy.oil_price
};
let oil_dollar_parts: (f64, f64);
let oil_level = if inputs.oil_pushes_in_target {
let noise = random_normal(rng, 0.0, oil_volatility);
let pushes = oil_inventory_pressure + oil_usd_drag + opec_impact + shock_oil_impact * 0.1;
let reverting = (oil_reverting + oil_mean_rev + noise) * oil_level_seasonality;
let reverting = match oil_premium_ratio {
None => reverting,
Some(ratio) => reverting * ratio,
};
let pushed = (0.97 * economy.oil_push_level + pushes) * oil_level_seasonality;
new_state.oil_push_level = pushed;
oil_dollar_parts = (reverting, pushed);
reverting + pushed
} else {
let oil_level = (economy.oil_price
+ oil_mean_rev
+ oil_inventory_pressure
+ oil_usd_drag
+ opec_impact
+ random_normal(rng, 0.0, oil_volatility)
+ shock_oil_impact * 0.1)
* oil_level_seasonality;
let oil_level = match oil_premium_ratio {
None => oil_level,
Some(ratio) => oil_level * ratio,
};
oil_dollar_parts = (oil_level, 0.0);
oil_level
};
let (oil_lo, oil_hi) = oil_bounds(inputs.oil_price_floor, inputs.oil_price_ceiling);
new_state.oil_price = clamp(oil_level, oil_lo, oil_hi);
if inputs.oil_target_drift.is_some() {
new_state.oil_bound_log_ratio = if oil_level > 0.0 {
mathx::log(new_state.oil_price / oil_level)
} else {
0.0
};
}
let real_rate = economy.federal_funds_rate - economy.inflation_rate;
let real_rate_drift = -real_rate * 0.8;
let inflation_hedge = mathx::max(0.0, (economy.inflation_rate - 2.0) * 1.5);
let crisis_premium = if economy.vix > inputs.crisis_vix_threshold && economy.gdp_growth < -1.0 {
mathx::min(
5.0,
economy.gdp_growth.abs() * 1.0 + (economy.vix - inputs.crisis_vix_threshold) * 0.15,
)
} else {
0.0
};
let prev_market_return = economy.previous_day_market_return;
let gold_safe_haven = if prev_market_return < -1.0 {
prev_market_return.abs() * 2.0
} else {
0.0
};
let inflation_premium_target = mathx::max(0.0, (economy.inflation_rate - 2.0) * 150.0)
+ (economy.inflation_rate - 2.5) * 50.0;
let real_rate_penalty = -real_rate * 100.0;
let gold_equilibrium = GOLD_EQUILIBRIUM_BASE + inflation_premium_target + real_rate_penalty;
let gold_mean_reversion = (gold_equilibrium - economy.gold_price) * GOLD_MEAN_REVERSION;
let sentiment_drift = (50.0 - economy.fear_greed_index) * 0.03;
let gold_change = real_rate_drift
+ inflation_hedge
+ crisis_premium
+ gold_safe_haven
+ gold_mean_reversion
+ sentiment_drift
+ random_normal(rng, 0.0, 3.0 * volatility);
new_state.gold_price = clamp(economy.gold_price + gold_change, 800.0, 5000.0);
let copper_demand = economy.gdp_growth * 0.02 + (economy.housing_index - 100.0) * 0.001;
let copper_usd_drag = -(economy.usd_index - 100.0) * 0.003;
let copper_change =
copper_demand + copper_usd_drag + random_normal(rng, 0.0, 0.04 * volatility);
new_state.copper_price = clamp(economy.copper_price + copper_change, 2.0, 8.0);
let usd_target = 100.0 + (economy.federal_funds_rate - 2.5) * 3.0;
let usd_mean_reversion = (usd_target - economy.usd_index) * 0.02;
let usd_noise = if inputs.usd_noise_sd == 0.0 { 0.3 * volatility } else { inputs.usd_noise_sd * volatility };
let safe_haven_drift = if economy.vix > inputs.usd_crisis_vix_threshold {
(economy.vix - inputs.usd_crisis_vix_threshold) * usd_safe_haven_gain(inputs.usd_safe_haven_gain)
} else {
0.0
};
if inputs.usd_mean_reversion == 0.0 {
let usd_change =
usd_mean_reversion + safe_haven_drift + random_normal(rng, 0.0, usd_noise);
new_state.usd_index = clamp(economy.usd_index + usd_change, 80.0, 130.0);
} else {
let base = economy.usd_index - economy.usd_haven_level;
let base_next = base + (usd_target - base) * inputs.usd_mean_reversion
+ random_normal(rng, 0.0, usd_noise);
let haven_next = 0.98 * economy.usd_haven_level + safe_haven_drift;
new_state.usd_haven_level = haven_next;
new_state.usd_index = clamp(base_next + haven_next, 80.0, 130.0);
}
if inputs.oil_dollar_elasticity != 0.0 {
let (reverting, pushed) = oil_dollar_parts;
let ratio = mathx::pow(new_state.usd_index / economy.usd_index, -inputs.oil_dollar_elasticity);
let unclamped = reverting * ratio + pushed;
new_state.oil_price = clamp(unclamped, oil_lo, oil_hi);
if inputs.oil_target_drift.is_some() {
new_state.oil_bound_log_ratio = if unclamped > 0.0 {
mathx::log(new_state.oil_price / unclamped)
} else {
0.0
};
}
}
let tariff_effect = economy.tariff_rate * 0.5;
let dollar_effect = -(economy.usd_index - 100.0) * 0.3;
new_state.trade_balance = clamp(
economy.trade_balance
+ (tariff_effect + dollar_effect) * 0.01
+ random_normal(rng, 0.0, 0.5 * volatility),
-200.0,
50.0,
);
vix_and_yields(economy, inputs, &mut new_state, shock_gdp_impact, rng);
let (fear_greed_phase, fear_greed_growth) = match inputs.fear_greed_published {
Some((phase, growth)) => (phase, growth),
None => (economy.cycle_phase, economy.gdp_growth),
};
let fear_greed_phase_bonus = match fear_greed_phase {
CyclePhase::Expansion => 15.0,
CyclePhase::Peak => 5.0,
CyclePhase::Contraction => -25.0,
CyclePhase::Trough => -20.0,
CyclePhase::Recovery => 10.0,
};
let market_sentiment = inputs.market_return_pct * 5.0;
let fear_greed_base = 50.0 + fear_greed_growth * 3.0 - (economy.vix - 15.0) * 0.8
+ fear_greed_phase_bonus
+ market_sentiment;
new_state.fear_greed_index = clamp(
economy.fear_greed_index
+ (fear_greed_base - economy.fear_greed_index) * 0.25
+ random_normal(rng, 0.0, 2.0 * volatility),
0.0,
100.0,
);
let target_recession_prob = match economy.cycle_phase {
CyclePhase::Expansion => 0.10,
CyclePhase::Peak => 0.30,
CyclePhase::Contraction => 0.70,
CyclePhase::Trough => 0.50,
CyclePhase::Recovery => 0.20,
};
let yield_spread = economy.treasury_yield_10y - economy.treasury_yield_2y;
let inversion_premium = if yield_spread < 0.0 {
mathx::min(0.25, yield_spread.abs() * 0.15)
} else {
0.0
};
let adjusted_target = mathx::min(0.95, target_recession_prob + inversion_premium);
new_state.recession_probability = clamp(
economy.recession_probability + (adjusted_target - economy.recession_probability) * 0.1,
0.05,
0.95,
);
new_state.months_in_current_phase = economy.months_in_current_phase + 1.0 / cal.month_f64();
new_state.previous_day_market_return = inputs.market_return_pct;
let prev_30d = economy.rolling_market_return_30d;
new_state.rolling_market_return_30d =
prev_30d + (inputs.market_return_pct - prev_30d) / cal.month_f64();
if inputs.daily_credit_floor_gain > 0.0 {
let g = inputs.daily_credit_floor_gain;
new_state.corporate_bond_yield = mathx::max(
new_state.corporate_bond_yield,
new_state.treasury_yield_10y + g * CORPORATE_SPREAD_FLOOR,
);
new_state.mortgage_rate_30y = mathx::max(
new_state.mortgage_rate_30y,
new_state.treasury_yield_10y + g * MORTGAGE_SPREAD_FLOOR,
);
}
new_state
}
#[cfg(test)]
mod phase_table_dials {
use super::*;
const PHASES: [CyclePhase; 5] = [
CyclePhase::Expansion, CyclePhase::Peak, CyclePhase::Contraction,
CyclePhase::Trough, CyclePhase::Recovery,
];
#[test]
fn a_zero_floor_returns_the_declared_range_unchanged() {
for phase in PHASES {
let c = phase_characteristics(phase);
assert_eq!(effective_gdp_range(&c, phase, 0.0), c.gdp_growth_range,
"{phase:?} moved at a zero floor");
}
}
#[test]
fn the_floor_moves_the_trough_and_nothing_else() {
for phase in PHASES {
let c = phase_characteristics(phase);
let moved = effective_gdp_range(&c, phase, 1.0);
if phase == CyclePhase::Trough {
assert_eq!(moved.0, 0.0, "the trough floor did not reach zero");
assert_eq!(moved.1, c.gdp_growth_range.1,
"the trough's upper end moved");
} else {
assert_eq!(moved, c.gdp_growth_range, "{phase:?} moved");
}
}
}
#[test]
fn a_partial_floor_is_a_share_of_the_distance() {
let c = phase_characteristics(CyclePhase::Trough);
let half = effective_gdp_range(&c, CyclePhase::Trough, 0.5);
assert_eq!(half.0, c.gdp_growth_range.0 / 2.0);
}
#[test]
fn a_zero_draw_ignores_the_stored_target() {
for phase in PHASES {
let c = phase_characteristics(phase);
let mid = (c.gdp_growth_range.0 + c.gdp_growth_range.1) / 2.0;
assert_eq!(phase_growth_target(999.0, c.gdp_growth_range, 0.0), mid,
"{phase:?} read the stored target at a zero draw");
}
}
#[test]
fn a_full_draw_reads_the_stored_target() {
let c = phase_characteristics(CyclePhase::Contraction);
assert_eq!(phase_growth_target(-2.75, c.gdp_growth_range, 1.0), -2.75);
}
#[test]
fn phase_entry_shock_is_the_steps_table() {
for u in [0.0, 0.25, 0.999] {
for v in [0.7, 1.0] {
assert_eq!(phase_entry_growth_shock(CyclePhase::Contraction, u, v), -(2.0 + u * (1.0 + v)));
}
}
let fixed = [0.5, 0.0, f64::NAN, -0.5, 1.0];
for (p, want) in PHASES.iter().zip(fixed) {
if *p != CyclePhase::Contraction {
assert_eq!(phase_entry_growth_shock(*p, 0.3, 1.0), want, "{p:?}");
}
}
let cycle: f64 = PHASES.iter().map(|p| phase_entry_growth_shock(*p, 0.5, 1.0)).sum();
assert_eq!(cycle, -2.0);
}
}
#[cfg(test)]
mod vix_level_identity {
use super::*;
use crate::economy::state::{create_initial_economy_state, InitialEconomyOptions};
struct Silent(f64);
impl crate::rng::Rng for Silent {
fn next_f64(&mut self) -> f64 {
self.0
}
fn next_normal(&mut self) -> f64 {
0.0
}
}
fn economy() -> EconomyState {
create_initial_economy_state(&InitialEconomyOptions::default())
}
fn arm(identity: f64) -> DailyInputs<'static> {
DailyInputs {
vix_level_identity: identity,
vix_index_sigma_pct: 1.04,
vix_implied_from_market: 20.7,
vix_realised_vol_weight: 0.3,
vix_cycle_amplitude: 0.85,
vix_mean_reversion: 0.06,
vix_decay_ratio: 0.6,
vix_return_gain: 30.0,
vix_return_gain_up: 14.0,
vix_return_source: 1.0,
vix_target_offset: -9.16,
vix_target_shock_cap: 150.0,
vix_return_clamp: 15.0,
market_day_return_pct: -1.7,
market_return_pct: -0.02,
game_day: 40,
..Default::default()
}
}
fn vix_after(inputs: &DailyInputs) -> f64 {
update_economy_daily(&economy(), inputs, &mut Silent(0.5)).vix
}
#[test]
fn the_index_sigma_is_not_read_while_the_identity_is_off() {
let want = vix_after(&arm(0.0));
for i in 0..=800 {
let mut inputs = arm(0.0);
inputs.vix_index_sigma_pct = i as f64 * 0.05;
assert_eq!(vix_after(&inputs), want, "moved at sigma = {}",
i as f64 * 0.05);
}
}
#[test]
fn the_unemployment_release_adds_the_partially_adjusted_impulse() {
let mut e = economy();
e.cycle_phase = CyclePhase::Contraction;
e.gdp_growth = -1.5;
e.unemployment_impulse = 0.05;
let off_inputs = DailyInputs { game_day: DAYS_PER_MONTH, ..Default::default() };
let off = update_economy_daily(&e, &off_inputs, &mut Silent(0.5));
assert_eq!(off.unemployment_impulse, 0.05);
let a = 0.2;
let on_inputs = DailyInputs {
game_day: DAYS_PER_MONTH,
unemployment_adjustment: a,
..Default::default()
};
let on = update_economy_daily(&e, &on_inputs, &mut Silent(0.5));
assert_eq!(on.gdp_growth, off.gdp_growth);
let gap = (off.unemployment_rate - e.unemployment_rate)
- (on.unemployment_rate - e.unemployment_rate);
let drive = 0.05 + gap / (1.0 - a);
assert!((on.unemployment_impulse - (0.05 + a * (drive - 0.05))).abs() < 1e-12);
let phase = phase_characteristics_for(e.cycle_phase, false);
let approx = unemployment_drive(phase.unemployment_trend, e.cycle_phase, on.gdp_growth);
assert!((drive - approx).abs() < 0.01, "{drive} {approx}");
assert!(drive > 1.0 && on.unemployment_rate - off.unemployment_rate < -0.9);
let mid = DailyInputs { game_day: DAYS_PER_MONTH + 1, unemployment_adjustment: a,
..Default::default() };
let quiet = update_economy_daily(&e, &mid, &mut Silent(0.5));
assert_eq!(quiet.unemployment_impulse, 0.05);
assert_eq!(quiet.unemployment_rate, e.unemployment_rate);
}
#[test]
fn the_index_sigma_is_read_once_the_identity_is_on() {
let mut last = f64::INFINITY;
for i in 1..=20 {
let mut inputs = arm(1.0);
inputs.vix_index_sigma_pct = i as f64 * 0.25;
let v = vix_after(&inputs);
assert!(v < last, "not falling at sigma {}: {v} after {last}",
i as f64 * 0.25);
last = v;
}
}
#[test]
fn the_earnings_bump_is_not_read_under_the_identity() {
let (early, late) = (5, 20);
let mut a = arm(1.0);
a.game_day = early;
let mut b = arm(1.0);
b.game_day = late;
assert_eq!(vix_after(&a), vix_after(&b),
"the month's half still moves the VIX under the identity");
let mut a = arm(0.0);
a.game_day = early;
let mut b = arm(0.0);
b.game_day = late;
assert_ne!(vix_after(&a), vix_after(&b),
"the bump moves nothing even with the identity off; the harness is not reaching the code");
}
#[test]
fn the_phase_table_is_not_read_under_the_identity() {
let phases = [CyclePhase::Expansion, CyclePhase::Peak,
CyclePhase::Contraction, CyclePhase::Trough,
CyclePhase::Recovery];
let of = |identity: f64, phase: CyclePhase| {
let mut e = economy();
e.cycle_phase = phase;
update_economy_daily(&e, &arm(identity), &mut Silent(0.5)).vix
};
let want = of(1.0, CyclePhase::Expansion);
for p in phases {
assert_eq!(of(1.0, p), want, "{p:?} moved the VIX under the identity");
}
let mut seen: Vec<f64> = phases.iter().map(|p| of(0.0, *p)).collect();
seen.sort_by(|a, b| a.partial_cmp(b).unwrap());
seen.dedup();
assert_eq!(seen.len(), phases.len(),
"the phase table moves nothing even with the identity off");
}
#[test]
fn a_symmetric_response_needs_no_correction() {
for i in 0..=200 {
let sigma = i as f64 * 0.05;
assert_eq!(expected_return_spike(sigma, 17.0, 17.0, 1.0), 0.0,
"a symmetric response was corrected at sigma {sigma}");
}
}
#[test]
fn the_correction_is_the_gaussian_absolute_moment() {
let two_over_pi = 2.0 / core::f64::consts::PI;
for &sigma in &[0.25, 0.8, 1.04, 2.5, 9.0] {
for &(g, gu) in &[(30.0, 14.0), (17.0, 5.0), (1.0, 0.0)] {
let want = 0.5 * (g - gu) * sigma * mathx::sqrt(two_over_pi);
let have = expected_return_spike(sigma, g, gu, 1.0);
assert!((have - want).abs() < 1e-12,
"sigma {sigma}, gains {g}/{gu}: {have} vs {want}");
}
}
}
#[test]
fn the_correction_scales_with_the_index_sigma() {
let a = expected_return_spike(1.0, 30.0, 14.0, 1.0);
let b = expected_return_spike(2.0, 30.0, 14.0, 1.0);
assert!((b - 2.0 * a).abs() < 1e-12, "{b} is not twice {a}");
assert!(a > 0.0, "an asymmetric down-heavy response has a positive mean");
}
#[test]
fn a_unit_exponent_is_the_linear_correction_to_the_bit() {
for i in 0..=200 {
let sigma = i as f64 * 0.05;
for &(g, gu) in &[(30.0, 14.0), (17.0, 5.0), (22.3, 11.15), (1.0, 0.0)] {
let want = 0.5 * (g - gu) * sigma * (2.0 / SQRT_TWO_PI);
assert_eq!(expected_return_spike(sigma, g, gu, 1.0), want,
"sigma {sigma}, gains {g}/{gu}");
}
}
}
#[test]
fn the_power_moment_matches_its_elementary_cases() {
let root_two_over_pi = 2.0 / SQRT_TWO_PI;
for &sigma in &[0.25, 0.8, 1.04, 2.5, 9.0] {
for &(g, gu) in &[(30.0, 14.0), (22.3, 11.15)] {
let e_abs = sigma * root_two_over_pi;
for &(p, e_pow) in &[
(2.0, sigma * sigma),
(3.0, 2.0 * sigma * sigma * sigma * root_two_over_pi),
] {
let want = 0.5 * (g * e_pow - gu * e_abs);
let have = expected_return_spike(sigma, g, gu, p);
assert!((have - want).abs() <= 1e-9 * want.abs().max(1.0),
"sigma {sigma}, p {p}, gains {g}/{gu}: {have} vs {want}");
}
}
}
}
#[test]
fn the_closed_form_is_the_integral_of_the_response() {
let n = 24_000usize;
for &sigma in &[0.6, 1.04, 2.5] {
for &(p, g, gu) in &[(1.2, 22.3, 11.15), (1.132, 30.0, 14.0), (1.0, 30.0, 14.0)] {
let (lo, hi) = (-12.0 * sigma, 12.0 * sigma);
let h = (hi - lo) / n as f64;
let f = |r: f64| {
let d = mathx::exp(-0.5 * (r / sigma) * (r / sigma))
/ (sigma * SQRT_TWO_PI);
return_spike_for(r, g, gu, p) * d
};
let mut acc = f(lo) + f(hi);
for i in 1..n {
let r = lo + i as f64 * h;
acc += f(r) * if i % 2 == 1 { 4.0 } else { 2.0 };
}
let quad = acc * h / 3.0;
let closed = expected_return_spike(sigma, g, gu, p);
assert!((quad - closed).abs() <= 1e-6 * closed.abs().max(1.0),
"sigma {sigma}, p {p}: quadrature {quad} vs closed {closed}");
}
}
}
#[test]
fn a_linear_correction_under_a_power_form_is_wrong_by_a_moving_factor() {
let (p, g, gu) = (1.2, 22.3, 11.15);
let ratio = |sigma: f64| {
expected_return_spike(sigma, g, gu, p) / expected_return_spike(sigma, g, gu, 1.0)
};
let mut last = f64::NEG_INFINITY;
for &sigma in &[0.25, 0.5, 0.91, 2.0, 4.0, 9.0] {
let r = ratio(sigma);
assert!(r > last, "the ratio did not rise at sigma {sigma}: {r} vs {last}");
last = r;
}
assert!(ratio(0.25) < 1.0,
"the linear correction did not over-correct a calm market: {}",
ratio(0.25));
assert!(ratio(9.0) > 1.0,
"the linear correction did not under-correct a violent one: {}",
ratio(9.0));
assert!(ratio(9.0) / ratio(0.25) > 1.5,
"a 36-fold volatility moved the correction by less than half: {}",
ratio(9.0) / ratio(0.25));
}
#[test]
fn the_identity_reads_the_session_return_at_every_source() {
let want = {
let mut i = arm(1.0);
i.vix_return_source = 1.0;
vix_after(&i)
};
for &s in &[0.0, 0.25, 0.5, 0.75, 1.0] {
let mut i = arm(1.0);
i.vix_return_source = s;
assert_eq!(vix_after(&i), want, "the source moved the VIX at {s}");
}
let off: Vec<f64> = [0.0f64, 0.5, 1.0].iter().map(|&s| {
let mut i = arm(0.0);
i.vix_return_source = s;
vix_after(&i)
}).collect();
assert!(off[0] != off[1] && off[1] != off[2],
"the source moves nothing even with the identity off: {off:?}");
}
}
#[cfg(test)]
mod vix_return_shape {
use super::*;
#[test]
fn a_unit_exponent_is_the_shipped_arithmetic_to_the_bit() {
let (gain, gain_up) = (30.0, 14.0);
for i in -400..=400 {
let r = i as f64 * 0.05;
let want = if r < 0.0 { -r * gain } else { -r * gain_up };
assert_eq!(return_spike_for(r, gain, gain_up, 1.0), want,
"moved at r = {r}");
}
}
#[test]
fn a_down_session_raises_fear_and_an_up_session_lowers_it() {
for &p in &[1.0, 1.132, 1.200, 1.287] {
assert!(return_spike_for(-2.0, 30.0, 15.0, p) > 0.0, "down at p={p}");
assert!(return_spike_for(2.0, 30.0, 15.0, p) < 0.0, "up at p={p}");
assert_eq!(return_spike_for(0.0, 30.0, 15.0, p), 0.0, "zero at p={p}");
}
}
#[test]
fn the_exponent_does_not_reach_the_up_side() {
for i in 0..=200 {
let r = i as f64 * 0.05;
let want = -r * 15.0;
for &p in &[1.0, 1.132, 1.200, 1.287, 1.8] {
assert_eq!(return_spike_for(r, 30.0, 15.0, p), want,
"the up side moved at r={r}, p={p}");
}
}
}
#[test]
fn the_response_per_per_cent_rises_only_above_a_unit_exponent() {
let per_pct = |r: f64, p: f64| return_spike_for(-r, 30.0, 15.0, p) / r;
for &r in &[0.71, 1.70, 2.75, 3.36, 6.39] {
assert!((per_pct(r, 1.0) - 30.0).abs() < 1e-12,
"the linear form is not flat at r={r}");
}
let mut last = f64::NEG_INFINITY;
for &r in &[0.71, 1.70, 2.75, 3.36, 6.39] {
let v = per_pct(r, 1.200);
assert!(v > last, "not rising at r={r}: {v} after {last}");
last = v;
}
}
#[test]
fn the_derived_scale_reproduces_the_fitted_curve() {
for &c in &[0.03138, 0.0600, 0.25] {
let scale = 1.003 / c;
for &r in &[0.710, 1.211, 1.704, 2.234, 2.746, 3.360, 4.415, 6.390] {
let realised = c * return_spike_for(-r, scale, scale / 2.0, 1.200);
let want = 1.003 * mathx::pow(r, 1.200);
assert!((realised - want).abs() < 1e-9,
"c {c}, bucket {r}: realised {realised}, fit {want}");
}
}
}
#[test]
fn the_fit_sits_within_its_own_worst_residual_of_every_bucket() {
const BUCKETS: [(f64, f64); 8] = [
(0.710, 0.710), (1.211, 1.255), (1.704, 1.890), (2.234, 2.440),
(2.746, 3.040), (3.360, 4.530), (4.415, 6.040), (6.390, 9.830)];
let worst = BUCKETS.iter()
.map(|&(r, d)| (1.003 * mathx::pow(r, 1.200) / d - 1.0).abs())
.fold(0.0_f64, f64::max);
assert!(worst < 0.15,
"the fit misses its worst bucket by {:.1} per cent, which is too far for a power law to be the right family",
100.0 * worst);
const C: f64 = 0.03138;
let scale = 1.003 / C;
for &(r, dvix) in BUCKETS.iter() {
let realised = C * return_spike_for(-r, scale, scale / 2.0, 1.200);
let err = (realised / dvix - 1.0).abs();
assert!(err <= worst + 1e-9,
"bucket {r} is off by {:.1} per cent, worse than the fit's own worst residual of {:.1}",
100.0 * err, 100.0 * worst);
}
}
}
#[cfg(test)]
mod fear_response_shape {
use super::*;
use crate::params::ModelParams;
const GRADED_ABS_R: f64 = 6.390;
const SHALLOW_ABS_R: f64 = 0.710;
const VIX_STATE_FLOOR: f64 = 10.0;
const SIGMAS: &[f64] = &[0.6, 1.0, 2.5];
const LEVELS: &[f64] = &[10.0, 15.0, 21.0, 30.0, 60.0, 120.0, 181.3295];
const FLATTENS_AT: &[(&str, f64, Binder)] = &[
("pt-v1", 0.030, Binder::Clamp),
("pt-v2", 0.030, Binder::Clamp),
("pt-v3", 0.030, Binder::Clamp),
("pt-v4", 0.030, Binder::Clamp),
("pt-v5", 0.030, Binder::Clamp),
("pt-v6", 0.030, Binder::Clamp),
("pt-v7", 0.030, Binder::Clamp),
("pt-v8", 0.030, Binder::Clamp),
("pt-v9", 2.647, Binder::Cap),
("pt-v10", 2.647, Binder::Cap),
("pt-v11", 2.647, Binder::Cap),
("pt-v12", 2.647, Binder::Cap),
("pt-v13", 2.647, Binder::Cap),
("pt-v14", 2.647, Binder::Cap),
("pt-v15", 2.647, Binder::Cap),
("pt-v16", 2.647, Binder::Cap),
("pt-v18", 2.647, Binder::Cap),
];
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Binder {
Clamp,
Cap,
}
fn fear_term(p: &ModelParams, r: f64, vix: f64) -> f64 {
let clamped = mathx::max(-p.vix_return_clamp, mathx::min(p.vix_return_clamp, r));
let spike = return_spike_at_level(
clamped,
p.vix_return_gain,
p.vix_return_gain_up,
p.vix_return_exponent,
p.vix_return_exponent_up,
p.vix_return_level_exponent,
p.vix_return_level_exponent_up,
vix,
);
mathx::min(p.vix_target_shock_cap, spike)
}
fn response(p: &ModelParams, r: f64, vix: f64) -> f64 {
fear_term(p, -r, vix)
}
fn give_back(p: &ModelParams, r: f64, vix: f64) -> f64 {
fear_term(p, r, vix)
}
fn flattens_at(p: &ModelParams, vix: f64) -> Option<f64> {
let steps = 63_900usize;
let mut prev = response(p, 0.0, vix);
for i in 1..=steps {
let r = GRADED_ABS_R * i as f64 / steps as f64;
let now = response(p, r, vix);
if now <= prev {
return Some(r);
}
prev = now;
}
None
}
fn cap_binds_at(p: &ModelParams, vix: f64) -> f64 {
if p.vix_return_gain <= 0.0 {
return f64::INFINITY;
}
let level = mathx::pow(vix, p.vix_return_level_exponent);
mathx::pow(
p.vix_target_shock_cap * level / p.vix_return_gain,
1.0 / p.vix_return_exponent,
)
}
fn most_binding_level(p: &ModelParams) -> f64 {
if p.vix_return_level_exponent >= 0.0 {
VIX_STATE_FLOOR
} else {
p.vix_ceiling
}
}
fn binder_of(p: &ModelParams) -> Binder {
if p.vix_return_clamp <= cap_binds_at(p, most_binding_level(p)) {
Binder::Clamp
} else {
Binder::Cap
}
}
fn down_is_level_dependent(p: &ModelParams) -> bool {
p.vix_return_level_exponent != 0.0
}
fn abs_moment(sigma: f64, k: f64) -> f64 {
mathx::pow(sigma, k) * mathx::pow(2.0, 0.5 * k) * mathx::tgamma(0.5 * (k + 1.0))
/ mathx::sqrt(core::f64::consts::PI)
}
fn zero_mean_correction(p: &ModelParams, sigma: f64, vix: f64) -> f64 {
let down = mathx::pow(vix, -p.vix_return_level_exponent);
let up = mathx::pow(vix, -p.vix_return_level_exponent_up);
0.5 * (p.vix_return_gain * down * abs_moment(sigma, p.vix_return_exponent)
- p.vix_return_gain_up * up * abs_moment(sigma, p.vix_return_exponent_up))
}
#[test]
fn every_preset_declares_where_its_fear_response_stops_rising() {
let mut wrong: Vec<String> = Vec::new();
for name in ModelParams::preset_names() {
let p = ModelParams::preset(name).expect("a name from preset_names resolves");
let declared = FLATTENS_AT.iter().find(|(n, _, _)| n == name);
if declared.is_some() && down_is_level_dependent(&p) {
wrong.push(format!(
"{name} has a row in FLATTENS_AT and a level-dependent response \
(vix_return_level_exponent {}). Its flattening point is a different \
number at every VIX, so one value cannot state it.",
p.vix_return_level_exponent
));
}
let mut earliest: Option<(f64, f64)> = None;
for &vix in LEVELS {
if let Some(at) = flattens_at(&p, vix) {
if earliest.is_none_or(|(best, _)| at < best) {
earliest = Some((at, vix));
}
}
if !down_is_level_dependent(&p) {
break;
}
}
match (earliest, declared) {
(Some((at, vix)), Some((_, want, want_binder))) => {
if (at - want).abs() >= 0.002 {
wrong.push(format!(
"{name} stops rising at {at:.3} per cent from a VIX of {vix}, not \
the declared {want:.3}. Read why the number moved before editing \
the table."
));
}
let binder = binder_of(&p);
if binder != *want_binder {
wrong.push(format!(
"{name} is declared bound by {want_binder:?} but its dials say \
{binder:?}. Those are different defects."
));
}
}
(Some((at, vix)), None) => wrong.push(format!(
"{name} stops rising at {at:.3} per cent from a VIX of {vix} and declares \
nothing. A response that goes flat inside the range the tape grades is a \
SHAPE change, not a boundary condition, and it must be declared."
)),
(None, Some(_)) => wrong.push(format!(
"{name} is declared in FLATTENS_AT but its response rises the whole \
way at every level. Remove it: a table that grants permission nobody \
needs will one day grant it to a preset that does."
)),
(None, None) => {}
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
#[test]
fn the_shipped_default_carries_its_fear_response_across_the_graded_range() {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
for &vix in LEVELS {
assert!(
flattens_at(&p, vix).is_none(),
"from a VIX of {vix} the default's fear response flattens at {:?} per cent, \
inside the {GRADED_ABS_R} per cent the tape grades. That is charter bar B4 \
lost again: read `ModelParams::vix_target_shock_cap` before adding a row to \
FLATTENS_AT.",
flattens_at(&p, vix)
);
let shallow = response(&p, SHALLOW_ABS_R, vix);
let deep = response(&p, GRADED_ABS_R, vix);
assert!(
deep > 8.0 * shallow,
"from a VIX of {vix} the response at -{GRADED_ABS_R} per cent is {deep:.2} \
against {shallow:.2} at -{SHALLOW_ABS_R}, a ratio of {:.2}. The tape's own \
conditional medians rise from 0.710 to 9.830 over that range, a ratio of 13.8.",
deep / shallow
);
let want = mathx::pow(GRADED_ABS_R / SHALLOW_ABS_R, p.vix_return_exponent);
assert!(
(deep / shallow - want).abs() < 1e-9,
"from a VIX of {vix} the deep-to-shallow ratio is {} where the exponent alone \
says {want}. The response has stopped factoring into a level and a shape.",
deep / shallow
);
}
assert_eq!(binder_of(&p), Binder::Clamp, "the clamp is the binding dial now");
the_default_cap_is_the_clamps_own_image();
}
#[test]
fn the_down_response_falls_with_the_level_and_the_up_response_rises_with_it() {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
assert!(
p.vix_return_level_exponent > 0.0,
"the down response no longer falls with the level. The tape puts g_dn at \
+0.49 +/- 0.12 with P(g > 0) = 1.000 and refuses the level-blind power form \
at F = 118 on 2 dof."
);
assert!(
p.vix_return_level_exponent_up < 0.0,
"the up response no longer rises with the level. The tape puts g_up at \
-0.85 +/- 0.12, P(g_up > 0) = 0.000."
);
assert!(
p.vix_return_exponent > 1.0 && p.vix_return_exponent_up < 1.0,
"the down side is convex in the move and the up side concave: p_dn \
1.44 +/- 0.08, p_up 0.60 +/- 0.04 with P(p_up > 1) = 0.000. Read \
{} and {}.",
p.vix_return_exponent,
p.vix_return_exponent_up
);
for &r in &[0.710, 2.5, GRADED_ABS_R] {
let base_dn = response(&p, r, LEVELS[0]);
let base_up = give_back(&p, r, LEVELS[0]);
assert!(base_dn > 0.0 && base_up < 0.0, "a down session raises the VIX and an up \
session gives it back: {base_dn} and {base_up}");
for &vix in LEVELS {
let want_dn = mathx::pow(vix / LEVELS[0], -p.vix_return_level_exponent);
let got_dn = response(&p, r, vix) / base_dn;
assert!(
(got_dn - want_dn).abs() < 1e-9,
"the down response at -{r} scales by {got_dn} from a VIX of {} to {vix}, \
where `v^(-g)` says {want_dn}",
LEVELS[0]
);
let want_up = mathx::pow(vix / LEVELS[0], -p.vix_return_level_exponent_up);
let got_up = give_back(&p, r, vix) / base_up;
assert!(
(got_up - want_up).abs() < 1e-9,
"the up give-back at +{r} scales by {got_up} from a VIX of {} to {vix}, \
where `v^(-g_up)` says {want_up}",
LEVELS[0]
);
}
}
let at_floor = response(&p, GRADED_ABS_R, VIX_STATE_FLOOR);
let at_ceiling = response(&p, GRADED_ABS_R, p.vix_ceiling);
assert!(
(at_floor - 46.1602).abs() < 1e-3 && (at_ceiling - 12.5920).abs() < 1e-3,
"the graded-top response reads {at_floor} at the floor and {at_ceiling} at the \
ceiling, where the dials say 46.1602 and 12.5920"
);
let one = give_back(&p, 1.0, 21.0).abs();
let two = give_back(&p, 2.0, 21.0).abs();
assert!(
(two / one - mathx::pow(2.0, p.vix_return_exponent_up)).abs() < 1e-9 && two < 2.0 * one,
"doubling an up session multiplied the give-back by {}, not by 2^p_up",
two / one
);
}
struct Silent;
impl crate::rng::Rng for Silent {
fn next_f64(&mut self) -> f64 {
0.5
}
fn next_normal(&mut self) -> f64 {
0.0
}
}
fn vix_after_one_session(vix: f64, implied: f64, sigma_pct: f64, session_pct: f64) -> f64 {
use crate::economy::state::{create_initial_economy_state, InitialEconomyOptions};
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
assert_eq!(p.vix_level_identity, 1.0, "the arithmetic below is the identity's");
let mut economy = create_initial_economy_state(&InitialEconomyOptions::default());
economy.vix = vix;
economy.inflation_rate = 2.0;
let inputs = DailyInputs {
vix_level_identity: p.vix_level_identity,
vix_implied_from_market: implied,
vix_index_sigma_pct: sigma_pct,
market_day_return_pct: session_pct,
vix_mean_reversion: p.vix_mean_reversion,
vix_decay_ratio: p.vix_decay_ratio,
vix_return_gain: p.vix_return_gain,
vix_return_gain_up: p.vix_return_gain_up,
vix_return_exponent: p.vix_return_exponent,
vix_return_exponent_up: p.vix_return_exponent_up,
vix_return_level_exponent: p.vix_return_level_exponent,
vix_return_level_exponent_up: p.vix_return_level_exponent_up,
vix_return_clamp: p.vix_return_clamp,
vix_target_shock_cap: p.vix_target_shock_cap,
vix_ceiling: p.vix_ceiling,
vix_return_source: p.vix_return_source,
game_day: 40,
..Default::default()
};
update_economy_daily(&economy, &inputs, &mut Silent).vix
}
fn vix_step_by_hand(
p: &ModelParams,
vix: f64,
implied: f64,
sigma_pct: f64,
session_pct: f64,
) -> f64 {
let target =
implied + fear_term(p, session_pct, vix) - zero_mean_correction(p, sigma_pct, vix);
let mr = if target < vix {
p.vix_mean_reversion * p.vix_decay_ratio
} else {
p.vix_mean_reversion
};
mathx::max(
VIX_STATE_FLOOR,
mathx::min(p.vix_ceiling, vix + (target - vix) * mr),
)
}
#[test]
fn a_graded_session_moves_the_state_its_reversion_share_of_the_way_to_its_target() {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
let m = p.vix_mean_reversion;
for &sigma in SIGMAS {
for i in 0..=45 {
let implied = 15.0 + i as f64;
for &session in &[-GRADED_ABS_R, -1.0, 0.0, 1.0, GRADED_ABS_R] {
let want = vix_step_by_hand(&p, implied, implied, sigma, session);
let got = vix_after_one_session(implied, implied, sigma, session);
assert!(
(got - want).abs() < 1e-9,
"from rest at {implied} with sigma {sigma} and a session of {session}: \
the update left {got}, the arithmetic says {want}"
);
}
let away = implied + 12.0;
let want = vix_step_by_hand(&p, away, implied, sigma, -GRADED_ABS_R);
let got = vix_after_one_session(away, implied, sigma, -GRADED_ABS_R);
assert!(
(got - want).abs() < 1e-9,
"from {away} against a read-back of {implied}: the update left {got}, \
the arithmetic says {want}"
);
assert!(
got < p.vix_ceiling - 100.0,
"a graded session from {away} reached {got}; the ceiling is {} and the \
old test's 'fear alone reaches it at 6.39 per cent' was never true of \
the state",
p.vix_ceiling
);
}
}
let from_rest = vix_after_one_session(21.0, 21.0, 1.0, -GRADED_ABS_R);
let fear = response(&p, GRADED_ABS_R, 21.0) - zero_mean_correction(&p, 1.0, 21.0);
assert!((from_rest - (21.0 + m * fear)).abs() < 1e-9, "{from_rest}");
assert!(
(from_rest - 29.791253).abs() < 1e-4,
"the graded session from rest at 21 leaves {from_rest}, where the dials say \
29.791253. If the dials moved, re-derive this rather than editing it."
);
}
fn vix_step_with_anchor(
kappa: f64,
anchor_level: f64,
vix: f64,
implied: f64,
sigma_pct: f64,
session_pct: f64,
) -> f64 {
use crate::economy::state::{create_initial_economy_state, InitialEconomyOptions};
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
let mut economy = create_initial_economy_state(&InitialEconomyOptions::default());
economy.vix = vix;
economy.inflation_rate = 2.0;
let inputs = DailyInputs {
vix_level_identity: p.vix_level_identity,
vix_implied_from_market: implied,
vix_index_sigma_pct: sigma_pct,
market_day_return_pct: session_pct,
vix_mean_reversion: p.vix_mean_reversion,
vix_decay_ratio: p.vix_decay_ratio,
vix_return_gain: p.vix_return_gain,
vix_return_gain_up: p.vix_return_gain_up,
vix_return_exponent: p.vix_return_exponent,
vix_return_exponent_up: p.vix_return_exponent_up,
vix_return_level_exponent: p.vix_return_level_exponent,
vix_return_level_exponent_up: p.vix_return_level_exponent_up,
vix_return_clamp: p.vix_return_clamp,
vix_target_shock_cap: p.vix_target_shock_cap,
vix_ceiling: p.vix_ceiling,
vix_return_source: p.vix_return_source,
vix_anchor_reversion: kappa,
vix_anchor_level: anchor_level,
game_day: 40,
..Default::default()
};
update_economy_daily(&economy, &inputs, &mut Silent).vix
}
#[test]
fn the_anchor_reversion_at_zero_is_the_step_that_stood_before_it() {
for &vix in &[10.5, 15.0, 23.25, 40.0, 90.0] {
for &implied in &[12.0, 21.0, 60.0] {
for &session in &[-3.0, 0.0, 1.5] {
let with = vix_step_with_anchor(0.0, 23.249857144842903, vix, implied,
1.0, session);
let without = vix_step_with_anchor(0.0, 0.0, vix, implied, 1.0, session);
let plain = vix_after_one_session(vix, implied, 1.0, session);
assert_eq!(
with.to_bits(), plain.to_bits(),
"the anchor reversion at 0.0 moved the step at VIX {vix}, \
read-back {implied}, session {session}: {with} against {plain}"
);
assert_eq!(without.to_bits(), plain.to_bits());
}
}
}
}
#[test]
fn the_anchor_reversion_moves_the_vix_toward_the_level_times_the_anchor() {
let kappa = 0.046081;
let anchor = 23.249857144842903;
for &level in &[1.0, 0.8, 1.25] {
let target = level * anchor;
for &vix in &[12.0, 18.0, 23.249857144842903, 30.0, 55.0] {
let base = vix_step_with_anchor(0.0, target, vix, vix, 1.0, 0.0);
let with = vix_step_with_anchor(kappa, target, vix, vix, 1.0, 0.0);
let pull = kappa * (target - vix);
assert!(
(with - base - pull).abs() < 1e-12,
"at level {level}, VIX {vix}: the term should be {pull}, read \
{} ({with} against {base})", with - base
);
if vix < target {
assert!(with > base, "below the anchor the reversion must lift");
} else if vix > target {
assert!(with < base, "above the anchor the reversion must pull down");
} else {
assert_eq!(with.to_bits(), base.to_bits(),
"at the anchor the term is exactly zero");
}
}
}
}
fn vix_step_with_weight(weight: f64, anchor_level: f64, vix: f64, implied: f64) -> f64 {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
use crate::economy::state::{create_initial_economy_state, InitialEconomyOptions};
let mut economy = create_initial_economy_state(&InitialEconomyOptions::default());
economy.vix = vix;
economy.inflation_rate = 2.0;
let inputs = DailyInputs {
vix_level_identity: p.vix_level_identity,
vix_implied_from_market: implied,
vix_index_sigma_pct: 1.0,
market_day_return_pct: 0.0,
vix_mean_reversion: p.vix_mean_reversion,
vix_decay_ratio: 1.0,
vix_return_gain: p.vix_return_gain,
vix_return_gain_up: p.vix_return_gain_up,
vix_return_exponent: p.vix_return_exponent,
vix_return_exponent_up: p.vix_return_exponent_up,
vix_return_level_exponent: p.vix_return_level_exponent,
vix_return_level_exponent_up: p.vix_return_level_exponent_up,
vix_return_clamp: p.vix_return_clamp,
vix_target_shock_cap: p.vix_target_shock_cap,
vix_ceiling: p.vix_ceiling,
vix_return_source: p.vix_return_source,
vix_anchor_weight: weight,
vix_anchor_level: anchor_level,
game_day: 40,
..Default::default()
};
update_economy_daily(&economy, &inputs, &mut Silent).vix
}
#[test]
fn the_anchor_weight_at_zero_is_the_step_that_stood_before_it() {
for &vix in &[10.5, 15.0, 23.25, 40.0, 90.0] {
for &implied in &[12.0, 21.0, 60.0] {
let with = vix_step_with_weight(0.0, 23.249857144842903, vix, implied);
let without = vix_step_with_weight(0.0, 0.0, vix, implied);
assert_eq!(with.to_bits(), without.to_bits(),
"the weight at 0.0 moved the step at VIX {vix}, read-back {implied}");
}
}
}
#[test]
fn the_anchor_weight_blends_the_target_geometrically_at_the_shipped_rate() {
let mr = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves")
.vix_mean_reversion;
let anchor = 23.249857144842903;
let a = 0.609944;
for &vix in &[12.0, 23.249857144842903, 55.0] {
for &implied in &[12.0, 23.249857144842903, 60.0] {
let base = vix_step_with_weight(0.0, anchor, vix, implied);
let with = vix_step_with_weight(a, anchor, vix, implied);
let blended = implied.powf(1.0 - a) * anchor.powf(a);
let want = mr * (blended - implied);
assert!((with - base - want).abs() < 1e-9,
"VIX {vix}, read-back {implied}: moved {} against {want}", with - base);
}
}
}
#[test]
fn a_vix_at_the_ceiling_is_held_there_iff_the_target_is_at_or_above_it() {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
let c = p.vix_ceiling;
for &sigma in SIGMAS {
let correction = zero_mean_correction(&p, sigma, c);
let reachable = response(&p, p.vix_return_clamp, c);
for implied in [40.0, 100.0, 134.5, 150.0, 160.0, 175.0] {
let need = c - implied + correction;
if need > reachable {
let held = vix_after_one_session(c, implied, sigma, -p.vix_return_clamp);
assert!(
held < c,
"a read-back of {implied} at sigma {sigma} needs {need:.4} points of \
spike and the clamp can only deliver {reachable:.4}, yet the state \
stayed at {held}"
);
continue;
}
let threshold = mathx::pow(
need * mathx::pow(c, p.vix_return_level_exponent) / p.vix_return_gain,
1.0 / p.vix_return_exponent,
);
assert!(
threshold > 0.0 && threshold <= p.vix_return_clamp,
"the holding session at a read-back of {implied} is {threshold}, outside \
the admissible range"
);
let above = vix_after_one_session(c, implied, sigma, -(threshold + 0.01));
assert_eq!(
above, c,
"target above the ceiling and the state came off it: {above}"
);
let below_r = threshold - 0.01;
let below = vix_after_one_session(c, implied, sigma, -below_r);
let want = vix_step_by_hand(&p, c, implied, sigma, -below_r);
assert!(
below < c && (below - want).abs() < 1e-9,
"target below the ceiling: the update left {below}, the arithmetic says \
{want}"
);
}
}
let worst = vix_after_one_session(c, 75.9, 2.5, -p.vix_return_clamp);
assert!(
worst < c - 10.0,
"from the map's highest settled read-back the worst admissible session left the \
state at {worst}, within 10 points of the ceiling at {c}. The census that makes \
the ceiling inert needs re-measuring."
);
}
#[test]
fn the_default_ceiling_is_pinned_to_its_solve_and_the_cap_ordering_is_withdrawn() {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
const CEILING_SOLVED: f64 = 181.3295;
assert_eq!(
p.vix_ceiling, CEILING_SOLVED,
"the ceiling is {} where b4fix7's settled ladder solved {CEILING_SOLVED}. Re-solve \
`C - implied(C) >= gain * GRADED_ABS_R` on a ladder and re-measure the \
census before moving it.",
p.vix_ceiling
);
let term = response(&p, GRADED_ABS_R, p.vix_ceiling);
assert!(
(term - 12.5920).abs() < 1e-3,
"the fear term at the ceiling reads {term}, where the dials say 12.5920"
);
assert!(
p.vix_ceiling > term,
"{} is under the target's fear term {term}",
p.vix_ceiling
);
assert_eq!(
binder_of(&p),
Binder::Clamp,
"the cap binds before the clamp, which is the ordering that does have a \
consequence"
);
}
#[test]
fn the_default_cap_is_the_clamps_own_image() {
let p = ModelParams::preset(crate::params::DEFAULT_PRESET_NAME)
.expect("the default preset resolves");
let floored = vix_after_one_session(VIX_STATE_FLOOR + 0.5, 0.0, 1.0, 0.0);
assert_eq!(
floored, VIX_STATE_FLOOR,
"the state floor is {floored}, not the {VIX_STATE_FLOOR} the cap's derivation \
evaluates the clamp's image at"
);
let image = p.vix_return_gain
* mathx::pow(p.vix_return_clamp, p.vix_return_exponent)
* mathx::pow(VIX_STATE_FLOOR, -p.vix_return_level_exponent);
assert!(
(p.vix_target_shock_cap - image).abs() < 1e-3,
"the cap is {} where the clamp's image at the floor is {image}. A cap above the \
image is inert and a cap below it is a second binding constraint.",
p.vix_target_shock_cap
);
assert!(
p.vix_target_shock_cap >= image,
"the cap {} is UNDER the spike's supremum {image}, so it truncates sessions the \
clamp admits and is a shape parameter again",
p.vix_target_shock_cap
);
for &vix in LEVELS {
let binds = cap_binds_at(&p, vix);
assert!(
binds >= p.vix_return_clamp,
"from a VIX of {vix} the cap truncates at {binds} per cent, inside the clamp \
at {}. It is a second binding constraint again.",
p.vix_return_clamp
);
}
assert!(
p.vix_return_clamp > GRADED_ABS_R,
"the clamp at {} is inside the graded {GRADED_ABS_R}, so it is now the \
shape parameter the cap used to be",
p.vix_return_clamp
);
}
}
#[cfg(test)]
mod anchor_weight_level {
use super::anchor_weight_at_level;
#[test]
fn at_and_below_the_knee_it_is_the_dial() {
for x in [9.0, 14.0, 18.5] {
assert!((anchor_weight_at_level(0.45, 1.0, 0.0, 0.0, x, 18.5) - 0.45).abs() < 1e-15);
}
}
#[test]
fn it_holds_one_minus_a_times_level_constant_below_the_cap() {
for x in [20.0, 25.0, 30.0, 36.0] {
let a = anchor_weight_at_level(0.45, 1.0, 1.95, 0.0, x, 18.5);
assert!(((1.0 - a) * x - 0.55 * 18.5).abs() < 1e-12, "x {x} a {a}");
}
}
#[test]
fn it_stops_rising_at_the_cap_and_below_the_knee_only_if_asked_it_falls() {
let at_cap = anchor_weight_at_level(0.45, 1.0, 1.95, 0.0, 1.95 * 18.5, 18.5);
assert_eq!(anchor_weight_at_level(0.45, 1.0, 1.95, 0.0, 80.0, 18.5), at_cap);
assert_eq!(anchor_weight_at_level(0.45, 1.0, 1.95, 1.0, 9.0, 18.5), 0.0);
}
}
#[cfg(test)]
mod live_projection {
use super::*;
use crate::economy::state::{create_initial_economy_state, InitialEconomyOptions};
#[test]
fn the_projection_is_the_steps_yields_at_the_means() {
let phases = [CyclePhase::Expansion, CyclePhase::Peak, CyclePhase::Contraction,
CyclePhase::Trough, CyclePhase::Recovery];
let mut checked = 0;
for (k, phase) in phases.iter().enumerate() {
for (day, ret) in [(17_i64, -2.3), (30, 1.1), (90, 0.0), (91, -0.4)] {
for (inflation, floor) in [(2.1, 0.0), (5.0, 1.0), (3.5, 1.0)] {
let mut e = create_initial_economy_state(&InitialEconomyOptions::default());
e.cycle_phase = *phase;
e.inflation_rate = inflation;
e.vix = 14.0 + 6.0 * k as f64;
let inputs = DailyInputs {
game_day: day,
market_day_return_pct: ret,
vix_return_source: 1.0,
daily_credit_floor_gain: floor,
yields: YieldDials {
treasury_10y_noise: 0.038,
treasury_2y_noise: 0.022,
flight_to_quality_gain: 0.016,
flight_to_quality_day: 1.0,
corporate_yield_daily: 1.0,
..YieldDials::default()
},
..Default::default()
};
let full = update_economy_daily(&e, &inputs, &mut MeanDraws);
let (y2, y10, corp) = project_close_yields(&e, &inputs);
assert_eq!(y2.to_bits(), full.treasury_yield_2y.to_bits());
assert_eq!(y10.to_bits(), full.treasury_yield_10y.to_bits());
assert_eq!(corp.to_bits(), full.corporate_bond_yield.to_bits());
let state = project_close_state(&e, &inputs);
assert_eq!(state.vix.to_bits(), full.vix.to_bits());
checked += 1;
}
}
}
assert_eq!(checked, 60);
}
#[test]
fn the_projection_moves_with_the_session() {
let e = create_initial_economy_state(&InitialEconomyOptions::default());
let at = |ret: f64| {
project_close_yields(&e, &DailyInputs {
market_day_return_pct: ret,
vix_return_source: 1.0,
yields: YieldDials {
flight_to_quality_gain: 0.016,
flight_to_quality_day: 1.0,
corporate_yield_daily: 1.0,
..YieldDials::default()
},
..Default::default()
})
};
let (down, flat, up) = (at(-2.0), at(0.0), at(2.0));
assert!(down.1 < flat.1 && flat.1 < up.1, "{down:?} {flat:?} {up:?}");
}
}
#[cfg(test)]
mod macro_anchors {
use super::*;
use crate::economy::state::{create_initial_economy_state, InitialEconomyOptions};
struct Silent(f64);
impl crate::rng::Rng for Silent {
fn next_f64(&mut self) -> f64 {
self.0
}
fn next_normal(&mut self) -> f64 {
0.0
}
}
const MONTH: i64 = DAYS_PER_MONTH;
fn economy() -> EconomyState {
create_initial_economy_state(&InitialEconomyOptions::default())
}
fn step(e: &EconomyState, inputs: DailyInputs) -> EconomyState {
update_economy_daily(e, &inputs, &mut Silent(0.5))
}
fn release() -> DailyInputs<'static> {
DailyInputs { game_day: MONTH, ..Default::default() }
}
#[test]
fn the_natural_pull_replaces_the_shipped_share() {
let mut e = economy();
e.unemployment_rate = 6.0;
e.structural_unemployment = 4.5;
let off = step(&e, release());
let same = step(&e, DailyInputs { unemployment_natural_pull: 0.06, ..release() });
assert_eq!(same.unemployment_rate.to_bits(), off.unemployment_rate.to_bits());
let on = step(&e, DailyInputs { unemployment_natural_pull: 0.3, ..release() });
let want = (0.3 - 0.06) * (4.5 - 6.0);
assert!((on.unemployment_rate - off.unemployment_rate - want).abs() < 1e-12);
assert_ne!(on.inflation_rate.to_bits(), off.inflation_rate.to_bits());
assert_eq!(on.gdp_growth.to_bits(), off.gdp_growth.to_bits());
}
#[test]
fn the_okun_coefficient_is_annual_and_drops_the_recovery_term() {
let phase = phase_characteristics_for(CyclePhase::Expansion, false);
let shipped = unemployment_drive(phase.unemployment_trend, CyclePhase::Expansion, 3.0);
assert_eq!(
unemployment_drive_with(phase.unemployment_trend, CyclePhase::Expansion, 3.0, 0.0)
.to_bits(),
shipped.to_bits());
assert!((shipped - (-0.05 * 0.3 - 0.2 - 0.24)).abs() < 1e-12);
let annual =
unemployment_drive_with(phase.unemployment_trend, CyclePhase::Expansion, 3.0, 0.5);
assert!((annual - (-0.05 * 0.3 - 0.5 / 12.0)).abs() < 1e-12);
let e = economy();
assert_eq!(e.cycle_phase, CyclePhase::Expansion);
let off = step(&e, release());
let on = step(&e, DailyInputs { unemployment_okun_coefficient: 0.5, ..release() });
assert_eq!(on.gdp_growth.to_bits(), off.gdp_growth.to_bits());
let g = off.gdp_growth;
let d_off = unemployment_drive(phase.unemployment_trend, CyclePhase::Expansion, g);
let d_on = unemployment_drive_with(phase.unemployment_trend, CyclePhase::Expansion, g, 0.5);
let moved = on.unemployment_rate - off.unemployment_rate;
assert!((moved - (d_on - d_off)).abs() < 1e-12, "{moved} {}", d_on - d_off);
}
#[test]
fn the_natural_rate_sets_the_nairu() {
let e = economy();
let off = step(&e, release());
let same = step(&e, DailyInputs { unemployment_natural_rate: 4.0, ..release() });
assert_eq!(same.structural_unemployment.to_bits(), off.structural_unemployment.to_bits());
let on = step(&e, DailyInputs { unemployment_natural_rate: 5.0, ..release() });
assert!((on.structural_unemployment - off.structural_unemployment - 1.0).abs() < 1e-12);
assert!((on.structural_unemployment
- (5.0 + 0.3 * on.long_term_unemployment_rate)).abs() < 1e-12);
}
#[test]
fn inventory_reverts_toward_its_normal_level() {
let mut e = economy();
e.oil_inventory_level = 90.0;
let day = DailyInputs { game_day: MONTH + 3, ..Default::default() };
let off = step(&e, day);
let on = step(&e, DailyInputs { oil_inventory_reversion: 0.01, ..day });
let want = 0.01 * (OIL_INVENTORY_NORMAL - 90.0);
assert!((on.oil_inventory_level - off.oil_inventory_level - want).abs() < 1e-12);
e.oil_inventory_level = 10.0;
let off = step(&e, day);
let on = step(&e, DailyInputs { oil_inventory_reversion: 0.01, ..day });
assert!((on.oil_inventory_level - off.oil_inventory_level - 0.4).abs() < 1e-12);
}
#[test]
fn the_oil_laws_dials_branch_at_their_standing_values_and_act_as_stated() {
let mut e = economy();
e.oil_price = 110.0;
let day = DailyInputs { game_day: MONTH + 3, ..Default::default() };
let off = step(&e, day);
let same = step(&e, DailyInputs { oil_mean_reversion: 0.03, oil_noise_sd: 2.0, ..day });
assert_eq!(same.oil_price.to_bits(), off.oil_price.to_bits());
let slow = step(&e, DailyInputs { oil_mean_reversion: 0.0035, ..day });
assert!(slow.oil_price > off.oil_price);
e.oil_inventory_level = 50.0;
let flat_off = step(&e, day);
let flat_on = step(&e, DailyInputs { oil_inventory_level_gain: 30.0, ..day });
assert_eq!(flat_on.oil_price.to_bits(), flat_off.oil_price.to_bits());
e.oil_inventory_level = 30.0;
let push = step(&e, day);
let level = step(&e, DailyInputs { oil_inventory_level_gain: 30.0, ..day });
let p_new = inventory_pressure(push.oil_inventory_level);
let moved = 30.0 * (p_new - inventory_pressure(30.0)) - p_new;
let ratio = (level.oil_price - push.oil_price) / moved;
assert!((ratio - 1.0).abs() <= 0.031, "{ratio}");
}
#[test]
fn the_convenience_premium_moves_the_target_with_inventory() {
let mut e = economy();
e.oil_price = 80.0;
let day = DailyInputs { game_day: MONTH + 3, oil_inventory_reversion: 0.002, ..Default::default() };
e.oil_inventory_level = 50.0;
let off = step(&e, day);
let on = step(&e, DailyInputs { oil_convenience_yield: 2.0, ..day });
let f = oil_convenience_factor(2.0, off.oil_inventory_level, 0.0);
assert!((f - 1.0).abs() < 0.05, "{f}");
e.oil_inventory_level = 42.0;
let low_off = step(&e, day);
let low_on = step(&e, DailyInputs { oil_convenience_yield: 2.0, ..day });
e.oil_inventory_level = 58.0;
let high_off = step(&e, day);
let high_on = step(&e, DailyInputs { oil_convenience_yield: 2.0, ..day });
assert!(low_on.oil_price - low_off.oil_price > high_on.oil_price - high_off.oil_price,
"{} {} {} {}", low_on.oil_price, low_off.oil_price, high_on.oil_price, high_off.oil_price);
assert_eq!(on.oil_inventory_level.to_bits(), off.oil_inventory_level.to_bits());
assert!((oil_convenience_factor(2.0, 25.0, 0.0) - (1.0 + 2.0 * 2f64.ln())).abs() < 1e-12);
assert_eq!(oil_convenience_factor(2.0, 5.0, 0.0), oil_convenience_factor(2.0, 25.0, 0.0));
assert!((oil_convenience_factor(1.0, 100.0, 0.0) - (1.0 - 2f64.ln())).abs() < 1e-12);
assert_eq!(oil_convenience_factor(4.0, 100.0, 0.0), OIL_CONVENIENCE_MIN);
let (k, m, sd) = (3.6, 45.0, 4.0);
let mut fine = 0.0;
let mut mass = 0.0;
for i in -4000..=4000 {
let z = i as f64 / 500.0;
let w = mathx::exp(-0.5 * z * z);
fine += w * oil_convenience_factor(k, m + z * sd, 0.0);
mass += w;
}
let quad = oil_convenience_factor(k, m, sd * sd);
assert!((quad / (fine / mass) - 1.0).abs() < 1e-4, "{quad} {}", fine / mass);
assert!((quad / oil_convenience_factor(k, m, 0.0) - 1.0).abs() < 0.02);
}
#[test]
fn the_clamped_oil_expectation_is_the_truncated_mean() {
for &(mean, sd) in &[(90.0, 5.0), (140.0, 20.0), (45.0, 15.0), (150.0, 30.0)] {
let (mut total, mut mass) = (0.0, 0.0);
for i in -8000..=8000 {
let z = i as f64 / 1000.0;
let w = mathx::exp(-0.5 * z * z);
total += w * clamp(mean + sd * z, 35.0, 150.0);
mass += w;
}
let want = total / mass;
let got = oil_clamped_expectation(mean, sd, (35.0, 150.0));
assert!((got - want).abs() < 1e-6, "{mean} {sd}: {got} {want}");
}
assert!((oil_clamped_expectation(90.0, 1.0, (35.0, 150.0)) - 90.0).abs() < 1e-12);
assert_eq!(oil_clamped_expectation(160.0, 0.0, (35.0, 150.0)), 150.0);
assert_eq!(oil_bounds(0.0, 0.0), (35.0, 150.0));
assert!(oil_expected_log_truncation(90.0, 5.0, (35.0, 150.0)).abs() < 1e-12);
assert!(oil_expected_log_truncation(145.0, 15.0, (35.0, 150.0)) < 0.0);
assert!(oil_expected_log_truncation(38.0, 8.0, (35.0, 150.0)) > 0.0);
for &(mean, v) in &[(140.0, 0.04), (45.0, 0.09), (90.0, 0.003)] {
let (m, sd) = (f64::ln(mean) - 0.5 * v, f64::sqrt(v));
let (mut cens, mut trunc, mut mass) = (0.0, 0.0, 0.0);
for i in -8000..=8000 {
let z = i as f64 / 1000.0;
let w = mathx::exp(-0.5 * z * z);
let x = mathx::exp(m + sd * z);
cens += w * clamp(x, 35.0, 150.0);
trunc += w * mathx::log(clamp(x, 35.0, 150.0) / x);
mass += w;
}
assert!((oil_lognormal_censored(mean, v, (35.0, 150.0)) - cens / mass).abs() < 1e-5);
assert!((oil_lognormal_log_truncation(mean, v, (35.0, 150.0)) - trunc / mass).abs() < 1e-6);
}
assert_eq!(oil_bounds(16.4, 279.0), (16.4, 279.0));
}
#[test]
fn the_safe_haven_gain_sets_the_dollars_crisis_drift() {
let mut e = economy();
e.vix = 35.0;
e.usd_index = 100.0;
let day = |g: f64, r: f64| DailyInputs {
game_day: MONTH + 3, usd_safe_haven_gain: g, usd_mean_reversion: r, ..Default::default() };
let excess = 35.0 - day(0.0, 0.0).usd_crisis_vix_threshold;
assert!(excess > 0.0);
for r in [0.0, 0.00095] {
let shipped = step(&e, day(0.0, r));
assert_eq!(shipped.usd_index.to_bits(), step(&e, day(USD_SAFE_HAVEN_GAIN, r)).usd_index.to_bits());
let measured = step(&e, day(0.001, r));
let gap = shipped.usd_index - measured.usd_index;
assert!((gap - (USD_SAFE_HAVEN_GAIN - 0.001) * excess).abs() < 1e-9, "{gap}");
if r != 0.0 {
assert!((measured.usd_haven_level - 0.001 * excess).abs() < 1e-12);
}
}
e.vix = 15.0;
assert_eq!(step(&e, day(0.0, 0.0)).usd_index.to_bits(), step(&e, day(0.001, 0.0)).usd_index.to_bits());
}
#[test]
fn a_stronger_dollar_lowers_oil_under_the_elasticity() {
let mut a = economy();
a.oil_price = 80.0;
a.usd_index = 100.0;
let mut b = a.clone();
b.federal_funds_rate = a.federal_funds_rate + 4.0;
let day = DailyInputs { game_day: MONTH + 3, oil_dollar_elasticity: 1.2, ..Default::default() };
let (sa, sb) = (step(&a, day), step(&b, day));
assert!(sb.usd_index > sa.usd_index, "{} {}", sb.usd_index, sa.usd_index);
assert!(sb.oil_price < sa.oil_price, "{} {}", sb.oil_price, sa.oil_price);
let want = mathx::pow(sb.usd_index / sa.usd_index, -1.2);
assert!((sb.oil_price / sa.oil_price - want).abs() < 1e-12, "{} {want}", sb.oil_price / sa.oil_price);
let off = DailyInputs { game_day: MONTH + 3, ..Default::default() };
assert_eq!(step(&a, off).oil_price.to_bits(), step(&b, off).oil_price.to_bits());
}
#[test]
fn the_oil_pass_through_is_symmetric_about_its_anchor() {
let at = |oil: f64, c: f64| {
let mut e = economy();
e.oil_price = oil;
step(&e, DailyInputs { oil_inflation_passthrough: c, ..release() }).inflation_rate
};
assert!(at(85.0, 0.0) - at(75.0, 0.0) > 0.04);
assert_eq!(at(65.0, 0.0).to_bits(), at(75.0, 0.0).to_bits());
assert_eq!(OIL_PASSTHROUGH_ANCHOR, 81.0);
let up = at(96.0, 1.0) - at(81.0, 1.0);
let down = at(66.0, 1.0) - at(81.0, 1.0);
assert!((up - 0.15).abs() < 1e-9, "{up}");
assert!((up + down).abs() < 1e-9, "{up} {down}");
}
#[test]
fn the_oil_part_of_headline_carries_the_pass_through_at_headlines_reversion() {
let mut e = economy();
e.oil_price = 121.0;
e.oil_inflation_level = 0.5;
let off = DailyInputs { oil_inflation_passthrough: 1.0, ..release() };
let on = DailyInputs { oil_inflation_tracked: true, ..off };
let (a, b) = (step(&e, off), step(&e, on));
assert_eq!(a.oil_inflation_level.to_bits(), 0.5f64.to_bits());
assert_eq!(a.inflation_rate.to_bits(), b.inflation_rate.to_bits());
let k = on.inflation_reversion;
let want = 0.5 + (0.0 - 0.5) * k + (121.0 - OIL_PASSTHROUGH_ANCHOR) * 0.01;
assert!((b.oil_inflation_level - want).abs() < 1e-12, "{} {want}", b.oil_inflation_level);
}
#[test]
fn the_zero_bound_pieces_lower_the_ten_year() {
let mut e = economy();
e.federal_funds_rate = 0.0;
e.vix = 40.0;
let ten = |e: &EconomyState, z: f64, g: f64| {
let mut i = DailyInputs::default();
i.yields.zlb_path = z;
i.yields.zlb_haven_gain = g;
step(e, i).treasury_yield_10y
};
let base = ten(&e, 0.0, 0.0);
assert!(((base - ten(&e, 1.0, 0.0)) - 0.05).abs() < 1e-9, "{}", base - ten(&e, 1.0, 0.0));
assert!(ten(&e, 0.0, 0.05) < base - 1e-6);
let mut off = e.clone();
off.federal_funds_rate = 2.0;
assert_eq!(ten(&off, 0.0, 0.05).to_bits(), ten(&off, 0.0, 0.0).to_bits());
}
#[test]
fn the_curve_reads_core_under_its_switch() {
let mut e = economy();
e.inflation_rate = 3.5;
e.oil_inflation_level = 1.0;
let y = |core: f64| {
let mut i = DailyInputs { market_day_return_pct: -3.0, ..Default::default() };
i.yields.flight_to_quality_gain = 0.05;
i.yields.flight_to_quality_day = 1.0;
i.yields.core_inflation = core;
step(&e, i).treasury_yield_10y
};
let mut f = e.clone();
f.oil_inflation_level = 0.0;
f.inflation_rate = 2.5;
let y_core_headline = {
let mut i = DailyInputs { market_day_return_pct: -3.0, ..Default::default() };
i.yields.flight_to_quality_gain = 0.05;
i.yields.flight_to_quality_day = 1.0;
step(&f, i).treasury_yield_10y
};
assert!(y(1.0) < y(0.0) - 0.1, "{} {}", y(1.0), y(0.0));
assert_eq!(y(1.0).to_bits(), y_core_headline.to_bits());
}
}