use crate::mathx::clamp_via_min_max as clamp;
pub const DAYS_PER_MONTH: i64 = 30;
pub const DAYS_PER_QUARTER: i64 = 90;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MacroCalendar {
pub days_per_year: i64,
pub days_per_month: i64,
shipped: bool,
}
impl MacroCalendar {
pub const fn shipped() -> Self {
MacroCalendar { days_per_year: 365, days_per_month: DAYS_PER_MONTH, shipped: true }
}
pub fn from_days_per_year(days: f64) -> Self {
if days == 365.0 {
return Self::shipped();
}
let y = days.round() as i64;
let m = (days / 12.0).round() as i64;
MacroCalendar {
days_per_year: y,
days_per_month: if m < 1 { 1 } else { m },
shipped: false,
}
}
pub fn is_shipped(&self) -> bool {
self.shipped
}
pub fn month_f64(&self) -> f64 {
self.days_per_month as f64
}
pub fn days_per_quarter(&self) -> i64 {
if self.shipped { DAYS_PER_QUARTER } else { 3 * self.days_per_month }
}
pub fn opec_interval(&self) -> i64 {
if self.shipped { OIL_OPEC_INTERVAL } else { self.days_per_quarter() }
}
pub fn mean_month_len(&self) -> f64 {
if self.shipped { 30.44 } else { self.days_per_year as f64 / 12.0 }
}
pub fn scale_days(&self, days: i64) -> i64 {
if self.shipped {
days
} else {
((days * self.days_per_year) as f64 / 365.0).round() as i64
}
}
}
pub const INFLATION_TARGET: f64 = 2.0;
pub const INFLATION_MEAN_REVERSION: f64 = 0.55;
pub const INFLATION_CEILING: f64 = 6.0;
pub const INFLATION_FLOOR: f64 = -1.0;
pub const PHILLIPS_CURVE_COEFF: f64 = 0.20;
pub const OIL_BASELINE: f64 = 75.0;
pub const OIL_OPEC_INTERVAL: i64 = 90;
pub const GOLD_EQUILIBRIUM_BASE: f64 = 2200.0;
pub const GOLD_MEAN_REVERSION: f64 = 0.002;
pub const VIX_MEAN_REVERSION: f64 = 0.12;
pub const VIX_RETURN_GAIN: f64 = 25.0;
pub const VIX_PHASE_MEAN: f64 = 19.0;
pub const VIX_RETURN_GAIN_UP: f64 = 10.0;
pub const VIX_RETURN_CLAMP: f64 = 0.03;
pub const VIX_TARGET_SHOCK_CAP: f64 = 12.0;
pub const FISCAL_MULTIPLIER: f64 = 0.30;
pub const CRISIS_VIX_THRESHOLD: f64 = 25.5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CyclePhase {
Expansion,
Peak,
Contraction,
Trough,
Recovery,
}
impl CyclePhase {
pub fn stress_intensity(self) -> f64 {
match self {
CyclePhase::Expansion => 0.0,
CyclePhase::Peak => 0.25,
CyclePhase::Contraction => 1.0,
CyclePhase::Trough => 0.75,
CyclePhase::Recovery => 0.25,
}
}
pub fn as_str(self) -> &'static str {
match self {
CyclePhase::Expansion => "expansion",
CyclePhase::Peak => "peak",
CyclePhase::Contraction => "contraction",
CyclePhase::Trough => "trough",
CyclePhase::Recovery => "recovery",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"expansion" => CyclePhase::Expansion,
"peak" => CyclePhase::Peak,
"contraction" => CyclePhase::Contraction,
"trough" => CyclePhase::Trough,
"recovery" => CyclePhase::Recovery,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct PhaseCharacteristics {
pub gdp_growth_range: (f64, f64),
pub unemployment_trend: f64,
pub inflation_trend: f64,
pub min_months: f64,
pub max_months: f64,
pub next_phase: CyclePhase,
}
pub fn phase_characteristics(phase: CyclePhase) -> PhaseCharacteristics {
phase_characteristics_for(phase, false)
}
pub fn phase_characteristics_for(phase: CyclePhase, us: bool) -> PhaseCharacteristics {
if us {
return us_phase_characteristics(phase);
}
match phase {
CyclePhase::Expansion => PhaseCharacteristics {
gdp_growth_range: (2.0, 4.0),
unemployment_trend: -0.05,
inflation_trend: 0.015,
min_months: 6.0,
max_months: 60.0,
next_phase: CyclePhase::Peak,
},
CyclePhase::Peak => PhaseCharacteristics {
gdp_growth_range: (0.5, 2.0),
unemployment_trend: 0.0,
inflation_trend: 0.015,
min_months: 2.0,
max_months: 6.0,
next_phase: CyclePhase::Contraction,
},
CyclePhase::Contraction => PhaseCharacteristics {
gdp_growth_range: (-3.0, 0.0),
unemployment_trend: 0.30,
inflation_trend: -0.02,
min_months: 4.0,
max_months: 12.0,
next_phase: CyclePhase::Trough,
},
CyclePhase::Trough => PhaseCharacteristics {
gdp_growth_range: (-1.0, 0.5),
unemployment_trend: 0.04,
inflation_trend: -0.01,
min_months: 2.0,
max_months: 6.0,
next_phase: CyclePhase::Recovery,
},
CyclePhase::Recovery => PhaseCharacteristics {
gdp_growth_range: (1.0, 3.5),
unemployment_trend: -0.1,
inflation_trend: 0.01,
min_months: 4.0,
max_months: 12.0,
next_phase: CyclePhase::Expansion,
},
}
}
pub fn us_phase_characteristics(phase: CyclePhase) -> PhaseCharacteristics {
phase_characteristics_for(phase, false)
}
pub const US_HAZARD_CAP: f64 = 1.0;
pub fn us_cycle_hazard_params(phase: CyclePhase) -> (f64, f64) {
match phase {
CyclePhase::Expansion => (1.8, 90.453),
CyclePhase::Peak => (2.0, 6.289),
CyclePhase::Contraction => (0.7, 0.546),
CyclePhase::Trough => (1.5, 2.564),
CyclePhase::Recovery => (1.3, 10.336),
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct EconomyState {
pub federal_funds_rate: f64,
pub prime_rate: f64,
pub corporate_bond_yield: f64,
pub treasury_yield_10y: f64,
pub treasury_yield_2y: f64,
pub mortgage_rate_30y: f64,
pub cpi: f64,
pub inflation_rate: f64,
pub core_inflation: f64,
pub gdp_growth: f64,
pub gdp: f64,
pub gdp_trend: [f64; 4],
pub unemployment_rate: f64,
pub jobs_created: f64,
pub labor_force_participation: f64,
pub usd_index: f64,
pub oil_price: f64,
pub gold_price: f64,
pub copper_price: f64,
pub housing_index: f64,
pub home_starts_monthly: f64,
pub housing_transaction_volume: f64,
pub long_term_unemployment_rate: f64,
pub structural_unemployment: f64,
pub consumer_confidence: f64,
pub business_confidence: f64,
pub fear_greed_index: f64,
pub vix: f64,
pub tariff_rate: f64,
pub trade_balance: f64,
pub oil_inventory_level: f64,
pub oil_last_opec_day: i64,
pub wage_growth: f64,
pub previous_day_market_return: f64,
pub rolling_market_return_30d: f64,
pub earnings_cycle: f64,
pub vix_feedback: f64,
pub intermeeting_return: f64,
pub fed_put: f64,
pub fed_put_owed: f64,
pub fed_put_mcap_prev: f64,
pub spread_equity_gap: f64,
pub spread_priced_gap: f64,
pub treasury_equity_priced_gap: f64,
pub earnings_anticipation: f64,
pub earnings_lookthrough: f64,
pub unemployment_impulse: f64,
pub oil_push_level: f64,
pub usd_haven_level: f64,
pub oil_inflation_level: f64,
pub zlb_unmet: f64,
pub oil_bound_log_ratio: f64,
pub market_pe: Option<f64>,
pub qe_pe_boost: f64,
pub qe_assets_ratio: f64,
pub fiscal_stimulus: f64,
pub government_debt_to_gdp: f64,
pub cycle_phase: CyclePhase,
pub months_in_current_phase: f64,
pub phase_gdp_target: f64,
pub recession_probability: f64,
}
impl Default for EconomyState {
fn default() -> Self {
create_initial_economy_state(&InitialEconomyOptions::default())
}
}
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct InitialEconomyOptions {
pub cycle_phase: Option<CyclePhase>,
pub inflation_rate: Option<f64>,
pub gdp_growth: Option<f64>,
pub unemployment_rate: Option<f64>,
}
pub fn create_initial_economy_state(options: &InitialEconomyOptions) -> EconomyState {
let cycle_phase = options.cycle_phase.unwrap_or(CyclePhase::Expansion);
let inflation_rate = options.inflation_rate.unwrap_or(2.0);
let gdp_growth = options.gdp_growth.unwrap_or(2.5);
let unemployment_rate = options.unemployment_rate.unwrap_or(4.0);
let confidence_base = 100.0 + gdp_growth * 5.0 - unemployment_rate * 3.0;
let confidence = clamp(confidence_base, 40.0, 130.0);
let fear_greed_base = match cycle_phase {
CyclePhase::Expansion => 60.0,
CyclePhase::Recovery => 55.0,
CyclePhase::Contraction => 30.0,
CyclePhase::Trough => 25.0,
CyclePhase::Peak => 55.0,
};
let vix = match cycle_phase {
CyclePhase::Contraction => 25.0,
CyclePhase::Trough => 30.0,
CyclePhase::Peak => 18.0,
_ => 15.0,
};
let federal_funds_rate = 2.5;
let treasury_yield_10y = 3.5;
let mortgage_spread = clamp(1.5 + (vix - 12.0) * 0.015, 1.5, 2.8);
let corporate_spread = clamp(1.0 + (vix - 12.0) * 0.02, 0.8, 3.5);
let prime_rate = federal_funds_rate + 3.0;
let mut mortgage_rate_30y =
crate::mathx::max(prime_rate + 0.5, treasury_yield_10y + mortgage_spread);
if mortgage_rate_30y - treasury_yield_10y > 3.5 {
mortgage_rate_30y = treasury_yield_10y + 3.5;
}
let corporate_bond_yield = crate::mathx::max(
treasury_yield_10y + 0.8,
treasury_yield_10y + corporate_spread,
);
EconomyState {
federal_funds_rate,
prime_rate,
corporate_bond_yield,
treasury_yield_10y,
treasury_yield_2y: federal_funds_rate * 0.70 + treasury_yield_10y * 0.30,
mortgage_rate_30y,
cpi: 100.0,
inflation_rate,
core_inflation: inflation_rate,
gdp_growth,
gdp: 25000.0,
gdp_trend: [
gdp_growth - 0.2,
gdp_growth - 0.1,
gdp_growth,
gdp_growth + 0.1,
],
unemployment_rate,
jobs_created: 200000.0,
labor_force_participation: 62.5,
usd_index: 100.0,
oil_price: 75.0,
gold_price: 1900.0,
copper_price: 4.0,
housing_index: 100.0,
home_starts_monthly: 1500000.0,
housing_transaction_volume: 100.0,
long_term_unemployment_rate: 1.5,
structural_unemployment: 4.5,
consumer_confidence: confidence,
business_confidence: confidence,
fear_greed_index: fear_greed_base,
vix,
tariff_rate: 5.0,
trade_balance: -50.0,
oil_inventory_level: 50.0,
oil_last_opec_day: 0,
wage_growth: 3.0,
previous_day_market_return: 0.0,
rolling_market_return_30d: 0.0,
earnings_cycle: 0.0,
vix_feedback: 0.0,
intermeeting_return: 0.0,
fed_put: 0.0,
fed_put_owed: 0.0,
fed_put_mcap_prev: 0.0,
spread_equity_gap: 0.0,
spread_priced_gap: 0.0,
treasury_equity_priced_gap: 0.0,
earnings_anticipation: 0.0,
earnings_lookthrough: 0.0,
unemployment_impulse: 0.0,
oil_push_level: 0.0,
usd_haven_level: 0.0,
oil_inflation_level: 0.0,
zlb_unmet: 0.0,
oil_bound_log_ratio: 0.0,
market_pe: Some(18.0),
qe_pe_boost: 0.0,
qe_assets_ratio: 1.0,
fiscal_stimulus: 0.0,
government_debt_to_gdp: 100.0,
cycle_phase,
months_in_current_phase: 0.0,
phase_gdp_target: {
let r = phase_characteristics(cycle_phase).gdp_growth_range;
(r.0 + r.1) / 2.0
},
recession_probability: match cycle_phase {
CyclePhase::Contraction => 0.5,
CyclePhase::Trough => 0.3,
_ => 0.1,
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ForwardGuidance {
OngoingIncreases,
Accommodative,
AsAppropriate,
}
impl ForwardGuidance {
pub fn as_str(self) -> &'static str {
match self {
ForwardGuidance::OngoingIncreases => "ongoing_increases",
ForwardGuidance::Accommodative => "accommodative",
ForwardGuidance::AsAppropriate => "as_appropriate",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"ongoing_increases" => ForwardGuidance::OngoingIncreases,
"accommodative" => ForwardGuidance::Accommodative,
"as_appropriate" => ForwardGuidance::AsAppropriate,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct CentralBankState {
pub last_meeting_date: i64,
pub next_meeting_date: i64,
pub target_inflation: f64,
pub target_unemployment: f64,
pub qe_active: bool,
pub qe_monthly_purchases: f64,
pub hawkish_dovish_score: f64,
pub forward_guidance: ForwardGuidance,
}
impl CentralBankState {
pub fn new(start_timestamp: i64) -> Self {
create_initial_central_bank_state(start_timestamp)
}
}
impl Default for CentralBankState {
fn default() -> Self {
CentralBankState::new(0)
}
}
pub fn create_initial_central_bank_state(start_timestamp: i64) -> CentralBankState {
CentralBankState {
last_meeting_date: start_timestamp,
next_meeting_date: start_timestamp + 45 * 24 * 60,
target_inflation: 2.0,
target_unemployment: 4.0,
qe_active: false,
qe_monthly_purchases: 0.0,
hawkish_dovish_score: 0.0,
forward_guidance: ForwardGuidance::AsAppropriate,
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct EconomicShock {
pub kind: ShockKind,
pub severity: f64,
pub gdp_impact: f64,
}
impl EconomicShock {
pub fn new(kind: ShockKind, severity: f64, gdp_impact: f64) -> Self {
EconomicShock { kind, severity, gdp_impact }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ShockKind {
OilShock,
Pandemic,
War,
Other,
}
#[cfg(test)]
mod regime_intensity_tests {
use super::*;
#[test]
fn the_cycle_orders_its_stress_the_way_the_cycle_runs() {
assert_eq!(CyclePhase::Expansion.stress_intensity(), 0.0);
assert!(CyclePhase::Contraction.stress_intensity()
> CyclePhase::Trough.stress_intensity());
assert!(CyclePhase::Trough.stress_intensity()
> CyclePhase::Recovery.stress_intensity());
assert!(CyclePhase::Recovery.stress_intensity()
>= CyclePhase::Expansion.stress_intensity());
for p in [CyclePhase::Expansion, CyclePhase::Peak,
CyclePhase::Contraction, CyclePhase::Trough,
CyclePhase::Recovery] {
let v = p.stress_intensity();
assert!((0.0..=1.0).contains(&v), "{} out of range", p.as_str());
}
}
}