use crate::economy::cycle::{
downturn_quantile_days_for, mean_sojourn_days_for, sojourn_quantile_days_for,
sojourn_sd_days_for,
};
use crate::economy::{CyclePhase, CycleSpec, EconomicShock, MacroCalendar};
use crate::market::{GameTime, NewsEvent};
use crate::params::ModelParams;
const SESSION_TICKS: f64 = 390.0;
pub const COMMON_NEWS_TOLERANCE: f64 = 0.1;
pub const VIX_WRITE_TOLERANCE: f64 = 0.1;
pub const MACRO_STEP_TOLERANCE: f64 = 1.05;
pub const OFF_SESSION_TOLERANCE: f64 = 0.01;
pub const DRIFT_TOLERANCE: f64 = 0.01;
pub const DRIFT_STANDARD_ERRORS: f64 = 3.0;
pub const CYCLE_RUN_QUANTILE: f64 = 0.99;
const SESSIONS_A_YEAR: f64 = 252.0;
pub const CYCLE_PHASES: [CyclePhase; 5] = [
CyclePhase::Expansion,
CyclePhase::Peak,
CyclePhase::Contraction,
CyclePhase::Trough,
CyclePhase::Recovery,
];
fn phase_slot(phase: CyclePhase) -> usize {
match phase {
CyclePhase::Expansion => 0,
CyclePhase::Peak => 1,
CyclePhase::Contraction => 2,
CyclePhase::Trough => 3,
CyclePhase::Recovery => 4,
}
}
fn cycle_spec_of(params: &ModelParams) -> CycleSpec {
CycleSpec {
per_month: params.cycle_hazard_per_month,
month_days: MacroCalendar::from_days_per_year(params.macro_calendar_days_per_year)
.month_f64(),
us: params.cycle_us_calibration != 0.0,
equity_hazard: params.cycle_equity_hazard,
equity_knee: params.cycle_equity_hazard_knee,
equity_opening: 0.0,
inflation_hazard: params.cycle_inflation_hazard,
rate_hazard: params.cycle_rate_hazard,
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct CalibratedFlow {
pub company_news_rate: f64,
pub company_news_sigma: f64,
pub sector_news_rate: f64,
pub market_news_rate: f64,
pub news_sector_weight: f64,
pub news_market_weight: f64,
pub idio_jump_rate: f64,
pub idio_jump_sigma: f64,
pub market_jump_rate: f64,
pub market_jump_mean: f64,
pub market_jump_sigma: f64,
pub market_factor_sigma: f64,
pub macro_shock_share: f64,
pub macro_steps_per_session: f64,
pub off_session_ticks_per_session: f64,
pub news_drift: f64,
pub phase_shares: [f64; 5],
pub phase_mean_sessions: [f64; 5],
pub phase_sd_sessions: [f64; 5],
pub phase_run_limit: [i64; 5],
pub downturn_share: f64,
pub downturn_mean_sessions: f64,
pub downturn_run_limit: i64,
}
impl CalibratedFlow {
pub fn of(params: &ModelParams) -> Self {
let spec = cycle_spec_of(params);
let mut phase_mean_sessions = [0.0; 5];
let mut phase_sd_sessions = [0.0; 5];
let mut phase_run_limit = [0i64; 5];
for (k, &phase) in CYCLE_PHASES.iter().enumerate() {
phase_mean_sessions[k] = mean_sojourn_days_for(phase, &spec);
phase_sd_sessions[k] = sojourn_sd_days_for(phase, &spec);
phase_run_limit[k] = sojourn_quantile_days_for(phase, &spec, CYCLE_RUN_QUANTILE);
}
let cycle: f64 = phase_mean_sessions.iter().sum();
let phase_shares = phase_mean_sessions.map(|m| m / cycle);
let (c, t) = (phase_slot(CyclePhase::Contraction), phase_slot(CyclePhase::Trough));
CalibratedFlow {
company_news_rate: params.endogenous_news_intensity,
company_news_sigma: params.endogenous_news_sigma,
sector_news_rate: 0.0,
market_news_rate: 0.0,
news_sector_weight: params.news_sector_weight,
news_market_weight: params.news_market_weight,
idio_jump_rate: params.jump_intensity_idio,
idio_jump_sigma: params.jump_sigma_idio,
market_jump_rate: params.jump_intensity_market,
market_jump_mean: params.jump_mean_market,
market_jump_sigma: params.jump_sigma_market,
market_factor_sigma: params.market_factor_sigma,
macro_shock_share: 0.0,
macro_steps_per_session: 1.0,
off_session_ticks_per_session: 0.0,
news_drift: 0.0,
phase_shares,
phase_mean_sessions,
phase_sd_sessions,
phase_run_limit,
downturn_share: phase_shares[c] + phase_shares[t],
downturn_mean_sessions: phase_mean_sessions[c] + phase_mean_sessions[t],
downturn_run_limit: downturn_quantile_days_for(&spec, CYCLE_RUN_QUANTILE),
}
}
pub fn company_news_variance(&self) -> f64 {
self.company_news_rate * self.company_news_sigma * self.company_news_sigma
}
pub fn market_factor_variance(&self) -> f64 {
self.market_factor_sigma * self.market_factor_sigma
}
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ExternalFlow {
pub names: usize,
pub sessions: u64,
pub company_events: u64,
pub company_sum_sq: f64,
pub sector_events: u64,
pub sector_sum_sq: f64,
pub market_events: u64,
pub market_sum_sq: f64,
pub fundamental_events: u64,
pub fundamental_sum_sq: f64,
pub vix_writes: u64,
pub vix_write_abs: f64,
pub vix_write_max: f64,
pub macro_steps: u64,
pub macro_shock_steps: u64,
pub macro_shock_load: f64,
pub company_sum: f64,
pub sector_sum: f64,
pub market_sum: f64,
pub fundamental_sum: f64,
pub off_session_ticks: u64,
pub vix_target_writes: u64,
pub vix_target_write_abs: f64,
pub vix_target_floor_sessions: u64,
pub phase_sessions: [u64; 5],
pub phase_longest: [u64; 5],
pub downturn_longest: u64,
pub cycle_last: Option<CyclePhase>,
pub phase_run: u64,
pub downturn_run: u64,
}
impl ExternalFlow {
pub fn new(names: usize) -> Self {
ExternalFlow {
names,
..ExternalFlow::default()
}
}
pub fn record_news_move(&mut self, company_id: Option<&str>, sector: Option<&str>, size: f64) {
if !size.is_finite() || size == 0.0 {
return;
}
let sq = size * size;
if company_id.is_some() {
self.company_events += 1;
self.company_sum_sq += sq;
self.company_sum += size;
} else if sector.is_some() {
self.sector_events += 1;
self.sector_sum_sq += sq;
self.sector_sum += size;
} else {
self.market_events += 1;
self.market_sum_sq += sq;
self.market_sum += size;
}
}
pub fn record_tick_news(&mut self, news: &[NewsEvent]) {
for e in news {
let x = e.price_impact.unwrap_or(0.0) / SESSION_TICKS;
self.record_news_move(e.company_id.as_deref(), e.sector.as_deref(), x);
}
}
pub fn record_tick(&mut self, request: &crate::engine::TickRequest) {
self.record_tick_news(request.news);
self.record_tick_time(request.time);
}
pub fn record_tick_time(&mut self, time: GameTime) {
if !crate::market::is_market_open(time) {
self.off_session_ticks += 1;
}
}
pub fn record_session_news(&mut self, news: &[NewsEvent]) {
for e in news {
let x = e.price_impact.unwrap_or(0.0);
self.record_news_move(e.company_id.as_deref(), e.sector.as_deref(), x);
}
}
pub fn record_fundamental_move(&mut self, size: f64) {
if !size.is_finite() || size == 0.0 {
return;
}
self.fundamental_events += 1;
self.fundamental_sum_sq += size * size;
self.fundamental_sum += size;
}
pub fn record_vix_write(&mut self, delta: f64) {
if !delta.is_finite() || delta == 0.0 {
return;
}
self.vix_writes += 1;
self.vix_write_abs += delta.abs();
if delta.abs() > self.vix_write_max {
self.vix_write_max = delta.abs();
}
}
pub fn record_vix_target_premium(&mut self, delta: f64) {
if !delta.is_finite() || delta == 0.0 {
return;
}
self.vix_target_writes += 1;
self.vix_target_write_abs += delta.abs();
}
pub fn record_vix_target_floor_session(&mut self) {
self.vix_target_floor_sessions += 1;
}
pub fn record_macro_step(&mut self, shocks: &[EconomicShock]) {
self.macro_steps += 1;
if !shocks.is_empty() {
self.macro_shock_steps += 1;
}
let load: f64 = shocks.iter().map(|s| s.gdp_impact * s.severity).sum();
self.macro_shock_load += load.abs();
}
pub fn record_cycle_phase(&mut self, phase: CyclePhase) {
let k = phase_slot(phase);
self.phase_sessions[k] += 1;
self.phase_run = if self.cycle_last == Some(phase) { self.phase_run + 1 } else { 1 };
self.cycle_last = Some(phase);
if self.phase_run > self.phase_longest[k] {
self.phase_longest[k] = self.phase_run;
}
if matches!(phase, CyclePhase::Contraction | CyclePhase::Trough) {
self.downturn_run += 1;
if self.downturn_run > self.downturn_longest {
self.downturn_longest = self.downturn_run;
}
} else {
self.downturn_run = 0;
}
}
pub fn cycle_sessions(&self) -> u64 {
self.phase_sessions.iter().sum()
}
pub fn record_session(&mut self) {
self.sessions += 1;
}
pub fn assess(&self, params: &ModelParams) -> FlowAssessment {
assess(&CalibratedFlow::of(params), self)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct FlowAssessment {
pub inside: bool,
pub company_news_ratio: f64,
pub common_news_ratio: f64,
pub fundamental_ratio: f64,
pub vix_write_per_session: f64,
pub vix_target_per_session: f64,
pub vix_target_floor_share: f64,
pub macro_shock_share: f64,
pub macro_shock_load: f64,
pub macro_steps_per_session: f64,
pub off_session_ticks_per_session: f64,
pub news_drift: f64,
pub fundamental_drift: f64,
pub phase_shares: [f64; 5],
pub downturn_share: f64,
pub phase_longest: [u64; 5],
pub downturn_longest: u64,
pub findings: Vec<String>,
}
fn assess(fit: &CalibratedFlow, obs: &ExternalFlow) -> FlowAssessment {
let sessions = if obs.sessions > 0 {
obs.sessions as f64
} else {
1.0
};
let names = if obs.names > 0 { obs.names as f64 } else { 1.0 };
let company_var = obs.company_sum_sq / (names * sessions);
let fitted_company = fit.company_news_variance();
let company_news_ratio = if fitted_company > 0.0 {
company_var / fitted_company
} else if company_var > 0.0 {
f64::INFINITY
} else {
0.0
};
let sector_var = obs.sector_sum_sq * fit.news_sector_weight * fit.news_sector_weight
/ (crate::sectors::keys().len() as f64 * sessions);
let market_var = obs.market_sum_sq * fit.news_market_weight * fit.news_market_weight / sessions;
let factor_var = fit.market_factor_variance();
let common_news_ratio = if factor_var > 0.0 {
(sector_var + market_var) / factor_var
} else {
0.0
};
let fundamental_var = obs.fundamental_sum_sq / (names * sessions);
let fundamental_ratio = if fitted_company > 0.0 {
fundamental_var / fitted_company
} else if fundamental_var > 0.0 {
f64::INFINITY
} else {
0.0
};
let vix_write_per_session = obs.vix_write_abs / sessions;
let vix_target_per_session = obs.vix_target_write_abs / sessions;
let vix_target_floor_share = obs.vix_target_floor_sessions as f64 / sessions;
let steps = obs.macro_steps as f64;
let macro_shock_share = if steps > 0.0 {
obs.macro_shock_steps as f64 / steps
} else {
0.0
};
let macro_shock_load = if steps > 0.0 {
obs.macro_shock_load / steps
} else {
0.0
};
let macro_steps_per_session = if obs.sessions > 0 {
steps / sessions
} else {
0.0
};
let off_session_ticks_per_session = obs.off_session_ticks as f64 / sessions;
let year = SESSIONS_A_YEAR / sessions;
let sectors = crate::sectors::keys().len() as f64;
let news_drift = year
* (obs.company_sum / names
+ obs.sector_sum * fit.news_sector_weight / sectors
+ obs.market_sum * fit.news_market_weight)
- fit.news_drift;
let fundamental_drift = year * obs.fundamental_sum / names;
let sector_scale = fit.news_sector_weight / sectors;
let news_se = year
* crate::mathx::sqrt(
obs.company_sum_sq / (names * names)
+ obs.sector_sum_sq * sector_scale * sector_scale
+ obs.market_sum_sq * fit.news_market_weight * fit.news_market_weight,
);
let fundamental_se = year * crate::mathx::sqrt(obs.fundamental_sum_sq) / names;
let cycle_sessions = obs.cycle_sessions();
let (phase_shares, downturn_share) = if cycle_sessions > 0 {
let n = cycle_sessions as f64;
let shares = obs.phase_sessions.map(|k| k as f64 / n);
let (c, t) = (phase_slot(CyclePhase::Contraction), phase_slot(CyclePhase::Trough));
(shares, shares[c] + shares[t])
} else {
([0.0; 5], 0.0)
};
let mut findings = Vec::new();
if company_news_ratio > 1.0 {
findings.push(format!(
"company news adds {:.2}x the variance the preset's own company news carries \
({:.3} events a name a session, rms log move {:.4}, against {:.3} at sd {:.4}), \
so the news channel runs at {:.2}x its fitted size",
company_news_ratio,
obs.company_events as f64 / (names * sessions),
if obs.company_events > 0 {
crate::mathx::sqrt(obs.company_sum_sq / obs.company_events as f64)
} else {
0.0
},
fit.company_news_rate,
fit.company_news_sigma,
1.0 + company_news_ratio,
));
}
if common_news_ratio > COMMON_NEWS_TOLERANCE {
findings.push(format!(
"sector and market-wide news add {:.2} of the market factor's base daily variance \
({:.3} sector and {:.3} market-wide events a session); the preset draws no news \
of either scope, so every name moves together by that much more than it was fitted at",
common_news_ratio,
obs.sector_events as f64 / sessions,
obs.market_events as f64 / sessions,
));
}
if fundamental_ratio > 1.0 {
findings.push(format!(
"fundamental revisions add {:.2}x the fitted company news variance ({:.4} \
revisions a name a session, rms log change {:.4}); fair value moves one for one \
with earnings, and the preset was fitted with earnings moved only by its own \
nominal and cycle terms",
fundamental_ratio,
obs.fundamental_events as f64 / (names * sessions),
if obs.fundamental_events > 0 {
crate::mathx::sqrt(obs.fundamental_sum_sq / obs.fundamental_events as f64)
} else {
0.0
},
));
}
if vix_write_per_session > VIX_WRITE_TOLERANCE {
findings.push(format!(
"the host wrote the VIX {} times, {:.2} points a session in absolute terms and up to \
{:.1} points at once; the preset writes none, and the market factor's variance \
target follows the VIX on a preset with `market_vol_vix_coupling`",
obs.vix_writes, vix_write_per_session, obs.vix_write_max,
));
}
if obs.vix_target_writes > 0 {
findings.push(format!(
"the host wrote a premium on the VIX target {} times, {:.2} points a session in \
absolute terms; the preset was fitted with none, and the VIX reverts toward the \
target the premium raises for as long as it stands",
obs.vix_target_writes, vix_target_per_session,
));
}
if obs.vix_target_floor_sessions > 0 {
findings.push(format!(
"{:.0}% of sessions closed with a floor under the VIX target; the preset was \
fitted with none, and the VIX reverts toward the floor while the target is under it",
100.0 * vix_target_floor_share,
));
}
if obs.macro_shock_steps > 0 {
findings.push(format!(
"{:.0}% of macro steps carried an active economic shock, at a mean load of {:.2}; \
the preset was fitted with none, and each step's load adds twice itself to the \
VIX target, and on a preset with `market_vol_vix_coupling` the market factor's \
variance target follows the VIX",
100.0 * macro_shock_share,
macro_shock_load,
));
}
if obs.sessions > 0 && macro_steps_per_session > MACRO_STEP_TOLERANCE {
findings.push(format!(
"the economy stepped {:.2} times a trading session; the preset's macro calendar \
counts sessions, so its months, quarters and phases run {:.2}x fast",
macro_steps_per_session, macro_steps_per_session,
));
}
if off_session_ticks_per_session > OFF_SESSION_TOLERANCE * SESSION_TICKS {
findings.push(format!(
"the host ran {:.0} ticks a session outside 09:30 to 16:00; the preset is fitted on \
the regular session's 390, each tick outside it draws noise at the session's \
per-minute scale, and on a preset with an overnight move the open already \
carries the night",
off_session_ticks_per_session,
));
}
if news_drift.abs() > DRIFT_TOLERANCE + DRIFT_STANDARD_ERRORS * news_se {
findings.push(format!(
"the host's news leans {:+.1}% a year a name on average (standard error {:.1}%); \
the preset's own news has mean zero, and on a preset with \
`fair_value_news_share` a company's news moves its fair value for good, so the \
market drifts by about that much",
100.0 * news_drift,
100.0 * news_se,
));
}
if fundamental_drift.abs() > DRIFT_TOLERANCE + DRIFT_STANDARD_ERRORS * fundamental_se {
findings.push(format!(
"the host's earnings revisions move each name's fair value by {:+.1}% a year on \
average (standard error {:.1}%; log changes summing to {:+.4} over {} revisions \
across all names); fair value moves one for one with earnings, and a stock split \
written as an earnings cut without dividing the engine's price is a revision of \
-ln(ratio)",
100.0 * fundamental_drift,
100.0 * fundamental_se,
obs.fundamental_sum,
obs.fundamental_events,
));
}
for (k, &phase) in CYCLE_PHASES.iter().enumerate() {
let limit = fit.phase_run_limit[k];
if limit < i64::MAX && obs.phase_longest[k] as i64 > limit {
findings.push(format!(
"a {} ran {} sessions unbroken, where the preset's own {} lasts {:.0} \
sessions on average and {} of every 100 end by session {}; {:.0}% of the {} \
sessions recorded were in a {}, against {:.0}% on the preset's own cycle",
phase.as_str(),
obs.phase_longest[k],
phase.as_str(),
fit.phase_mean_sessions[k],
(100.0 * CYCLE_RUN_QUANTILE).round(),
limit,
100.0 * phase_shares[k],
cycle_sessions,
phase.as_str(),
100.0 * fit.phase_shares[k],
));
}
}
if fit.downturn_run_limit < i64::MAX && obs.downturn_longest as i64 > fit.downturn_run_limit {
findings.push(format!(
"a contraction and trough together ran {} sessions unbroken, where the preset's own \
last {:.0} on average and {} of every 100 end by session {}; {:.0}% of the {} \
sessions recorded were in a contraction or trough, against {:.0}% on the preset's \
own cycle, and on a preset with `market_vol_cycle_ratio` both phases raise the \
market's variance for as long as they hold",
obs.downturn_longest,
fit.downturn_mean_sessions,
(100.0 * CYCLE_RUN_QUANTILE).round(),
fit.downturn_run_limit,
100.0 * downturn_share,
cycle_sessions,
100.0 * fit.downturn_share,
));
}
FlowAssessment {
inside: findings.is_empty(),
company_news_ratio,
common_news_ratio,
fundamental_ratio,
vix_write_per_session,
vix_target_per_session,
vix_target_floor_share,
macro_shock_share,
macro_shock_load,
macro_steps_per_session,
off_session_ticks_per_session,
news_drift,
fundamental_drift,
phase_shares,
downturn_share,
phase_longest: obs.phase_longest,
downturn_longest: obs.downturn_longest,
findings,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::economy::ShockKind;
fn v20() -> ModelParams {
ModelParams::preset("pt-v20").unwrap()
}
fn company(x: f64) -> NewsEvent {
NewsEvent {
company_id: Some("A-0".into()),
sector: Some("technology".into()),
price_impact: Some(x),
}
}
#[test]
fn the_calibrated_flow_reads_the_preset() {
let p = v20();
let f = CalibratedFlow::of(&p);
assert_eq!(f.company_news_rate, p.endogenous_news_intensity);
assert_eq!(f.company_news_sigma, p.endogenous_news_sigma);
assert_eq!(f.market_jump_rate, p.jump_intensity_market);
assert_eq!(f.sector_news_rate, 0.0);
assert_eq!(f.market_news_rate, 0.0);
assert_eq!(f.macro_shock_share, 0.0);
assert_eq!(f.macro_steps_per_session, 1.0);
}
#[test]
fn no_external_flow_is_inside() {
let mut t = ExternalFlow::new(40);
for _ in 0..252 {
t.record_macro_step(&[]);
t.record_session();
}
let a = t.assess(&v20());
assert!(a.inside, "{:?}", a.findings);
assert_eq!(a.company_news_ratio, 0.0);
}
#[test]
fn a_tick_lands_one_390th_and_a_session_lands_the_whole_impact() {
let mut tick = ExternalFlow::new(1);
tick.record_tick_news(&[company(0.05 * 390.0)]);
let mut session = ExternalFlow::new(1);
session.record_session_news(&[company(0.05)]);
assert!((tick.company_sum_sq - 0.0025).abs() < 1e-15);
assert!((session.company_sum_sq - 0.0025).abs() < 1e-15);
}
#[test]
fn company_news_is_outside_past_the_fitted_variance() {
let p = v20();
let fit = CalibratedFlow::of(&p);
let names = 100usize;
let sessions = 1000u64;
let at = |scale: f64| {
let mut t = ExternalFlow::new(names);
t.sessions = sessions;
t.company_events = (fit.company_news_rate * names as f64 * sessions as f64) as u64;
t.company_sum_sq = scale * fit.company_news_variance() * names as f64 * sessions as f64;
t.assess(&p)
};
assert!(at(1.0).inside);
let over = at(2.0);
assert!(!over.inside);
assert!((over.company_news_ratio - 2.0).abs() < 1e-9);
}
#[test]
fn common_news_macro_shocks_and_a_fast_macro_clock_are_each_outside() {
let p = v20();
let mut market = ExternalFlow::new(100);
market.sessions = 252;
market.market_events = 252;
market.market_sum_sq = 252.0 * 0.03 * 0.03;
assert!(!market.assess(&p).inside);
let mut shocks = ExternalFlow::new(100);
shocks.record_session();
shocks.record_macro_step(&[EconomicShock {
kind: ShockKind::Pandemic,
severity: 0.5,
gdp_impact: -2.0,
}]);
let a = shocks.assess(&p);
assert!(!a.inside);
assert_eq!(a.macro_shock_share, 1.0);
assert!((a.macro_shock_load - 1.0).abs() < 1e-12);
let mut clock = ExternalFlow::new(100);
for d in 0..252 {
clock.record_session();
clock.record_macro_step(&[]);
if d % 5 < 2 {
clock.record_macro_step(&[]);
}
}
let a = clock.assess(&p);
assert!(!a.inside);
assert!(a.macro_steps_per_session > 1.3);
}
#[test]
fn written_vix_levels_are_outside_past_the_tolerance() {
let p = v20();
let mut t = ExternalFlow::new(10);
for _ in 0..100 {
t.record_session();
t.record_macro_step(&[]);
}
t.record_vix_write(5.0);
assert!(
t.assess(&p).inside,
"5 points over 100 sessions is 0.05 a session"
);
t.record_vix_write(-10.0);
let a = t.assess(&p);
assert!(!a.inside);
assert_eq!(t.vix_write_max, 10.0);
assert!((a.vix_write_per_session - 0.15).abs() < 1e-12);
}
#[test]
fn a_vix_target_premium_or_floor_is_outside_and_counted_apart_from_writes() {
let p = v20();
let mut t = ExternalFlow::new(10);
for _ in 0..100 {
t.record_session();
t.record_macro_step(&[]);
}
assert!(t.assess(&p).inside);
t.record_vix_target_premium(0.0);
assert!(t.assess(&p).inside, "a write that moved nothing is no write");
t.record_vix_target_premium(6.0);
t.record_vix_target_premium(-2.0);
let a = t.assess(&p);
assert!(!a.inside);
assert_eq!(t.vix_target_writes, 2);
assert_eq!(t.vix_writes, 0);
assert!((a.vix_target_per_session - 0.08).abs() < 1e-12);
let mut f = ExternalFlow::new(10);
for _ in 0..100 {
f.record_session();
f.record_macro_step(&[]);
}
for _ in 0..25 {
f.record_vix_target_floor_session();
}
let a = f.assess(&p);
assert!(!a.inside);
assert!((a.vix_target_floor_share - 0.25).abs() < 1e-12);
assert!(a.findings.iter().any(|x| x.contains("floor")), "{:?}", a.findings);
}
#[test]
fn quarterly_earnings_revisions_of_a_quarter_are_outside() {
let p = v20();
let mut t = ExternalFlow::new(10);
for d in 0..252 {
t.record_session();
t.record_macro_step(&[]);
if d % 63 == 0 {
for _ in 0..10 {
t.record_fundamental_move(0.25);
}
}
}
t.record_fundamental_move(0.0);
assert_eq!(t.fundamental_events, 40);
let a = t.assess(&p);
assert!(!a.inside);
assert!(a.fundamental_ratio > 50.0, "{}", a.fundamental_ratio);
}
#[test]
fn ticks_outside_the_session_are_counted_and_outside_past_the_tolerance() {
use crate::engine::TickRequest;
let p = v20();
let mut t = ExternalFlow::new(10);
for _ in 0..10 {
t.record_session();
t.record_macro_step(&[]);
for m in 0..390i64 {
let at = 9 * 60 + 30 + m;
t.record_tick(&TickRequest::new(GameTime::new(at / 60, at % 60, 3)));
}
}
assert_eq!(t.off_session_ticks, 0);
assert!(t.assess(&p).inside);
for _ in 0..30 {
t.record_tick_time(GameTime::new(9, 0, 3));
}
assert!(t.assess(&p).inside);
for _ in 0..10 {
for m in 0..150i64 {
let at = 7 * 60 + m;
t.record_tick_time(GameTime::new(at / 60, at % 60, 3));
}
for m in 0..240i64 {
let at = 16 * 60 + m;
t.record_tick_time(GameTime::new(at / 60, at % 60, 3));
}
}
let a = t.assess(&p);
assert!(!a.inside);
assert!((a.off_session_ticks_per_session - 393.0).abs() < 1e-9);
assert!(a.findings.iter().any(|f| f.contains("outside 09:30 to 16:00")));
}
#[test]
fn news_and_revisions_that_lean_one_way_are_outside_as_drift() {
let p = ModelParams::preset("pt-v21").unwrap();
let fit = CalibratedFlow::of(&p);
assert_eq!(fit.news_drift, 0.0);
assert_eq!(fit.off_session_ticks_per_session, 0.0);
let names = 100usize;
let at = |sign: &dyn Fn(usize) -> f64| {
let mut t = ExternalFlow::new(names);
for d in 0..252 {
t.record_session();
t.record_macro_step(&[]);
for i in 0..5 {
let x = sign(d * 5 + i) * fit.company_news_sigma;
t.record_session_news(&[company(x)]);
}
}
t.assess(&p)
};
let even = at(&|k| if k % 2 == 0 { 1.0 } else { -1.0 });
assert!(even.inside, "{:?}", even.findings);
assert!(even.news_drift.abs() < 1e-12);
let down = at(&|_| -1.0);
assert!(!down.inside);
let want = -0.05 * fit.company_news_sigma * 252.0;
assert!((down.news_drift - want).abs() < 1e-9, "{}", down.news_drift);
assert!(down.findings.iter().any(|f| f.contains("-22.1% a year")), "{:?}", down.findings);
let mut t = ExternalFlow::new(names);
for _ in 0..504 {
t.record_session();
t.record_macro_step(&[]);
}
for _ in 0..names {
t.record_fundamental_move(-(2.0f64).ln());
}
let a = t.assess(&p);
assert!(!a.inside);
assert!((a.fundamental_drift + 0.5 * (2.0f64).ln()).abs() < 1e-12);
assert!(a.findings.iter().any(|f| f.contains("-ln(ratio)")));
}
#[test]
fn the_calibrated_flow_states_the_presets_own_cycle() {
assert_eq!(CYCLE_PHASES, crate::economy::cycle::phase_cycle());
let f = CalibratedFlow::of(&ModelParams::preset("pt-v21").unwrap());
let (c, t) = (phase_slot(CyclePhase::Contraction), phase_slot(CyclePhase::Trough));
assert!((f.phase_shares.iter().sum::<f64>() - 1.0).abs() < 1e-12);
assert!((f.phase_mean_sessions[c] - 115.5).abs() < 0.05, "{}", f.phase_mean_sessions[c]);
assert!((f.phase_mean_sessions[t] - 73.5).abs() < 0.05, "{}", f.phase_mean_sessions[t]);
assert_eq!(f.phase_run_limit[c], 246);
assert_eq!(f.phase_run_limit[t], 170);
assert_eq!(f.downturn_run_limit, 338);
assert!((f.downturn_share - 0.0833).abs() < 5e-4, "{}", f.downturn_share);
assert!((f.downturn_mean_sessions - 189.0).abs() < 0.1);
assert!(f.phase_sd_sessions.iter().all(|&x| x > 0.0 && x.is_finite()));
let old = CalibratedFlow::of(&v20());
assert!((old.phase_shares.iter().sum::<f64>() - 1.0).abs() < 1e-12);
assert!(old.phase_run_limit.iter().all(|&d| d > 0 && d < i64::MAX));
}
fn cycle_tally(profile: &[(CyclePhase, u64)]) -> ExternalFlow {
let mut t = ExternalFlow::new(108);
for &(phase, n) in profile {
for _ in 0..n {
t.record_session();
t.record_macro_step(&[]);
t.record_cycle_phase(phase);
}
}
t
}
#[test]
fn a_phase_run_past_the_presets_own_99th_percentile_is_outside() {
use CyclePhase::*;
let p = ModelParams::preset("pt-v21").unwrap();
let (c, t) = (phase_slot(Contraction), phase_slot(Trough));
let own = cycle_tally(&[(Contraction, 104), (Trough, 66), (Recovery, 252), (Expansion, 334)]);
let a = own.assess(&p);
assert!(a.inside, "{:?}", a.findings);
assert_eq!(a.phase_longest[t], 66);
assert_eq!(a.downturn_longest, 170);
assert!((a.downturn_share - 170.0 / 756.0).abs() < 1e-12);
assert!((a.phase_shares.iter().sum::<f64>() - 1.0).abs() < 1e-12);
assert!(cycle_tally(&[(Trough, 170)]).assess(&p).inside);
let a = cycle_tally(&[(Trough, 171)]).assess(&p);
assert!(!a.inside);
assert!(a.findings[0].starts_with("a trough ran 171 sessions unbroken"), "{:?}", a.findings);
let held = cycle_tally(&[(Expansion, 126), (Contraction, 126), (Trough, 454), (Recovery, 50)]);
let a = held.assess(&p);
assert_eq!(a.findings.len(), 2, "{:?}", a.findings);
assert!(a.findings[1].contains("together ran 580 sessions"), "{:?}", a.findings);
let a = cycle_tally(&[(Contraction, 305), (Trough, 69), (Recovery, 382)]).assess(&p);
assert!(!a.inside);
assert!(a.findings[0].starts_with("a contraction ran 305"), "{:?}", a.findings);
assert_eq!(a.downturn_longest, 374);
let broken = cycle_tally(&[(Contraction, 200), (Recovery, 1), (Contraction, 200)]);
assert_eq!(broken.phase_sessions[c], 400);
assert_eq!(broken.phase_longest[c], 200);
assert_eq!(broken.downturn_longest, 200);
assert!(broken.assess(&p).inside);
}
#[test]
fn a_tally_without_phases_reports_no_cycle() {
let mut t = ExternalFlow::new(10);
for _ in 0..100 {
t.record_session();
t.record_macro_step(&[]);
}
let a = t.assess(&ModelParams::preset("pt-v21").unwrap());
assert!(a.inside);
assert_eq!(t.cycle_sessions(), 0);
assert_eq!(a.phase_shares, [0.0; 5]);
assert_eq!(a.downturn_share, 0.0);
assert_eq!(a.phase_longest, [0; 5]);
}
#[test]
fn news_of_mean_zero_is_not_flagged_for_its_sampling_noise() {
let p = ModelParams::preset("pt-v21").unwrap();
let fit = CalibratedFlow::of(&p);
let mut g = crate::rng::GameRng::new(11, 3);
let mut largest: f64 = 0.0;
for _ in 0..20 {
let mut t = ExternalFlow::new(40);
for _ in 0..252 {
t.record_session();
t.record_macro_step(&[]);
for _ in 0..40 {
if g.next_f64() < fit.company_news_rate {
let x = fit.company_news_sigma * g.next_normal();
t.record_session_news(&[company(x)]);
}
}
}
let a = t.assess(&p);
largest = largest.max(a.news_drift.abs());
assert!(!a.findings.iter().any(|f| f.contains("leans")), "{:?}", a.findings);
}
assert!(largest > DRIFT_TOLERANCE, "the test should draw a drift past the tolerance: {largest}");
}
}