tradefloor 0.11.0

A reproducible evaluation environment for financial AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Economy state, ported from the reference implementation's economy
//! module and its economy types.
//!
//! # What is here, and what is deliberately absent
//!
//! Only the fields the price-relevant chain reads or writes. `EconomyState`
//! in the reference implementation is wider; the omissions are listed in
//! the port notes under WP3 and summarised here:
//!
//! - **`derived` / `computeDerivedIndicators`** — a 70-field struct that
//!   `updateEconomyDaily` recomputes on its last line and nothing in the
//!   price loop reads (the surface audit §0). Verified to consume **zero** draws,
//!   which is what makes leaving it out safe: an omission that shifted the
//!   stream would not be an omission, it would be a divergence.
//! - **`SECTOR_SENSITIVITIES` / `calculateSectorEconomicImpact`** — feeds
//!   only the discarded `economicImpact` factor.
//! - **Narrative strings** — announcement text, forward guidance, shock
//!   headlines. The strings are out of scope; **the draws that select them
//!   are not**, and are consumed here exactly where the original consumes
//!   them.

use crate::mathx::clamp_via_min_max as clamp;

/// Days between the monthly data-release blocks.
pub const DAYS_PER_MONTH: i64 = 30;
/// Days between quarterly GDP releases.
pub const DAYS_PER_QUARTER: i64 = 90;

/// The macro calendar: how many economy steps make a macro year and a macro
/// month. See [`crate::params::ModelParams::macro_calendar_days_per_year`].
///
/// The economy steps once per trading session. As written it keeps a
/// 365-step year and 30-step months, so a macro year is 365 sessions, 1.45
/// trading years, and every release, phase duration, meeting interval and
/// seasonal period runs 1.45 times slow in market time. `shipped()` is that
/// calendar and every accessor returns the literal that stood at its site;
/// `from_days_per_year(252.0)` is the session calendar: 21-session months,
/// 63-session quarters, a 252-session year.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MacroCalendar {
    /// Economy steps in a macro year.
    pub days_per_year: i64,
    /// Economy steps in a macro month.
    pub days_per_month: i64,
    shipped: bool,
}

impl MacroCalendar {
    /// The calendar every preset through pt-v18 runs: 365-step years,
    /// 30-step months. pt-v19 runs the session calendar (252) since its
    /// fifth composition.
    pub const fn shipped() -> Self {
        MacroCalendar { days_per_year: 365, days_per_month: DAYS_PER_MONTH, shipped: true }
    }

    /// 365.0 is [`MacroCalendar::shipped`] exactly. Any other value is a
    /// year of that many steps and a month of a twelfth of it, rounded.
    pub fn from_days_per_year(days: f64) -> Self {
        if days == 365.0 {
            return Self::shipped();
        }
        let y = days.round() as i64;
        // Integer arithmetic, and no `.max`: the determinism lint keeps
        // float min/max inside `mathx` and does not tell the two apart.
        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
    }

    /// Steps in a macro month, as the f64 the phase clock advances by.
    pub fn month_f64(&self) -> f64 {
        self.days_per_month as f64
    }

    /// Steps between quarterly GDP releases: 90 as shipped.
    pub fn days_per_quarter(&self) -> i64 {
        if self.shipped { DAYS_PER_QUARTER } else { 3 * self.days_per_month }
    }

    /// Steps between OPEC decisions, a quarter: 90 as shipped.
    pub fn opec_interval(&self) -> i64 {
        if self.shipped { OIL_OPEC_INTERVAL } else { self.days_per_quarter() }
    }

    /// The mean month length the earnings-season bump reads: 30.44 as
    /// shipped, a twelfth of the year otherwise.
    pub fn mean_month_len(&self) -> f64 {
        if self.shipped { 30.44 } else { self.days_per_year as f64 / 12.0 }
    }

    /// A span written in calendar days, in steps of this calendar: the
    /// literal as shipped, `days * days_per_year / 365` rounded otherwise.
    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;
/// Monthly fraction of the inflation gap closed toward the target. The
/// shipped value; `ModelParams::inflation_reversion` carries it at runtime.
pub const INFLATION_MEAN_REVERSION: f64 = 0.55;
/// Hard ceiling on endogenous inflation, percent; `ModelParams::inflation_ceiling` at runtime.
pub const INFLATION_CEILING: f64 = 6.0;
/// Hard floor on endogenous inflation, percent; `ModelParams::inflation_floor` at runtime.
pub const INFLATION_FLOOR: f64 = -1.0;

/// Phillips-curve coefficient.
///
/// **D3, decided:** magnitude `0.20`. The SIGN lives at the use site
/// (`daily.rs`: `-unemployment_gap * PHILLIPS_CURVE_COEFF`), matching
/// the reference implementation — so this constant is positive and must stay positive.
///
/// `wasm/src/economy.rs:9` reads `-0.20` and is
/// commented "aligned with JS"; only the stale compiled binary in
/// `wasm/pkg` says `-0.18`, and no source in the repository endorses that.
/// Production has been running a coefficient nobody chose.
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;
/// VIX points added to the target per unit of a DOWN day's index return.
/// The shipped 25.0 with the clamp below gives a worst-case +0.75 to the
/// target and about +0.09 on the day; real markets move the VIX a median of
/// +6.03 points on a session at -3% or worse (FRED VIXCLS against SP500,
/// 2,511 common days to 2026-08). Carried at runtime as
/// `ModelParams::vix_return_gain`.
pub const VIX_RETURN_GAIN: f64 = 25.0;
/// Mean of the five cycle-phase VIX targets, the anchor `vix_cycle_amplitude`
/// scales deviations around: (14 + 18 + 25 + 22 + 16) / 5.
pub const VIX_PHASE_MEAN: f64 = 19.0;
/// The same for an UP day, where the real response is about half the size.
pub const VIX_RETURN_GAIN_UP: f64 = 10.0;
/// The index return is clamped to this before it drives the VIX, so a -10%
/// day and a -3% day produce identical fear at the shipped 0.03.
pub const VIX_RETURN_CLAMP: f64 = 0.03;
/// Ceiling on the whole target excursion (return spike plus inflation and
/// shock adjustments), in VIX points.
pub const VIX_TARGET_SHOCK_CAP: f64 = 12.0;
pub const FISCAL_MULTIPLIER: f64 = 0.30;

/// The VIX level above which crisis-gated behaviour engages: the gold
/// crisis premium and the USD safe-haven drift (`daily.rs`), and — once
/// its owning change lands — the correlation blend in `market/tick.rs`.
///
/// **Decided deviation from the reference**, which gates these at
/// inline literals of 30 (economy) and 40 (the blend). Endogenous VIX
/// cannot reach either: the daily target tops out near 26 without
/// exogenous shocks, and the Python surface never supplies shocks
/// (`python_engine.rs`: `active_shocks: &[]`), so under default
/// operation every crisis gate was dead code. Measured across 12 seeds
/// by 2,520 days (`tools/calibration/results/vix-endogenous-long-
/// 2026-08-21.json`): median 16.5, P90 25.3, hard ceiling 26.57, zero
/// days above 30 or 40 in 42,336 across both envelopes — and the
/// reference's own recorded trajectories agree (max 29.09 across all
/// five economy goldens, so the 30-gates never fire in the vectors
/// either).
///
/// 25.5 is the P94 of the long-run endogenous distribution: 5.7% of
/// days cross, all of them in contraction or trough (28% of contraction
/// days), every 10-year seed crosses, and no 252-day expansion-start
/// window does (48/48 stay below 24.4). That is "rare and real" in this
/// model's own units — the analogue of the 5-6% of real trading days
/// with VIX above 30 — rather than a level chosen for its real-world
/// name and unreachable in-model.
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 {
    /// How much stress this phase carries, on 0 (calm) to 1 (worst).
    ///
    /// The business cycle already runs in this engine and the MARKET has
    /// never read it: `cycle_phase` appears nowhere in `src/market/`. The
    /// central bank reads it -- recession cuts, contraction policy, a
    /// different Taylor coefficient per phase -- while the price process
    /// carries on as though the economy were always expanding.
    ///
    /// So every market parameter is static beside a regime chain that is
    /// already switching, already deterministic, and already drawn on its
    /// own stream. This is the number that lets the market listen.
    ///
    /// The profile is the cycle's own shape rather than a fit: expansion
    /// is calm, the peak is where risk builds unnoticed, contraction is
    /// the worst of it, the trough is bad but improving, and recovery
    /// still carries scar tissue.
    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",
        }
    }

    /// Not `FromStr`: the name is the reference implementation's union member, and a failed
    /// parse is a malformed vector rather than a user input error, so it
    /// returns `Option` rather than a `Result` nobody would read.
    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)
}

/// [`phase_characteristics`], or the table derived from NBER and BEA when
/// `us` is set (`cycle_us_calibration`); see [`us_phase_characteristics`].
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,
        },
    }
}

/// The US phase table (`cycle_us_calibration`), DERIVED from NBER recession
/// dates and BEA real GDP, 1990-2025 (the derivation is in the project's
/// unpublished design notes). Durations are months of
/// the macro calendar, so they are real months only on the session calendar
/// (`macro_calendar_days_per_year` 252).
///
/// Only the DURATIONS move. The growth ranges, trends, minima and Weibull
/// shapes are the shipped table's:
///
/// - growth: the shipped model realises 3.02 in expansion, 2.29 at the peak,
///   -1.77 across contraction and trough and 2.04 in recovery; BEA quarters
///   in the same positions 1990-2019 grow 3.12, 1.98, -1.51 and 2.60, and
///   -1.95 in recessions 1948-2025. Depth is not what is wrong.
/// - minima: contraction 4 plus trough 2 is six months, the shortest NBER
///   recession 1948-2019 (1980).
///
/// Mean sojourns on the hazard alone (`mean_sojourn_days_for`), each solved
/// for its scale at the shipped shape:
///
/// | phase | target, months | from |
/// |---|---:|---|
/// | contraction + trough | 9.0 | NBER 1990-2025: 8, 8, 18, 2 (1948-2025: 10.3) |
/// | split 5.5 / 3.5 | | the shipped model's own contraction:trough occupancy, 0.14:0.09 |
/// | peak | 6.0 | the two quarters before an NBER peak, as BEA positions are labelled |
/// | recovery | 12.0 | the four quarters after an NBER trough, likewise |
/// | expansion | 81.0 | a 108-month cycle (1.11 recessions a decade, 1990-2025) less 9 + 6 + 12 |
///
/// The state-dependent ladder in `economy::cycle` still adds to these
/// hazards, so realised durations are shorter; the measured ones are in the
/// result.
pub fn us_phase_characteristics(phase: CyclePhase) -> PhaseCharacteristics {
    phase_characteristics_for(phase, false)
}

/// The cap on the US table's monthly hazard. The shipped 0.3 is the
/// reference's cap on a DAILY probability carried over to the monthly
/// reading, and on its own it forbids a recession averaging nine months
/// after six months of minima (the least residual it admits is 3.3 months
/// a phase). 1.0 is the bound of a monthly rate; `weibull_hazard`'s own 0.8
/// still applies.
pub const US_HAZARD_CAP: f64 = 1.0;

/// Weibull `(shape, scale)` of the US table, scales in months, solved for
/// the targets in [`us_phase_characteristics`] at the shipped shapes, on a
/// 21-step month read per month.
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),
    }
}

/// The economy fields the ported chain touches.
///
/// A plain struct of `f64` rather than `Option<f64>` everywhere: the
/// The reference implementation declares most of these as required and reaches for `?? default`
/// only on the handful that were added later. Those defaults are applied at
/// construction, so the `??` sites in the original become ordinary reads
/// here — with one exception noted at [`EconomyState::market_pe`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct EconomyState {
    // Interest rates
    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,

    // Inflation
    pub cpi: f64,
    pub inflation_rate: f64,
    pub core_inflation: f64,

    // Growth
    pub gdp_growth: f64,
    pub gdp: f64,
    pub gdp_trend: [f64; 4],

    // Employment
    pub unemployment_rate: f64,
    pub jobs_created: f64,
    pub labor_force_participation: f64,

    // Currency
    pub usd_index: f64,

    // Commodities
    pub oil_price: f64,
    pub gold_price: f64,
    pub copper_price: f64,

    // Housing
    pub housing_index: f64,
    pub home_starts_monthly: f64,
    pub housing_transaction_volume: f64,

    // Labor-market hysteresis
    pub long_term_unemployment_rate: f64,
    pub structural_unemployment: f64,

    // Sentiment
    pub consumer_confidence: f64,
    pub business_confidence: f64,
    pub fear_greed_index: f64,
    pub vix: f64,

    // Trade
    pub tariff_rate: f64,
    pub trade_balance: f64,

    // Oil supply/demand
    pub oil_inventory_level: f64,
    pub oil_last_opec_day: i64,

    // Wages
    pub wage_growth: f64,

    // Cross-asset tracking
    pub previous_day_market_return: f64,
    pub rolling_market_return_30d: f64,
    /// The aggregate earnings cycle: the log level of every company's
    /// earnings relative to what nominal output alone would give them. 0.0,
    /// and never written, on every preset whose `earnings_cycle_depth` is
    /// 0.0 (every preset through pt-v19). See
    /// [`crate::params::ModelParams::earnings_cycle_depth`].
    pub earnings_cycle: f64,
    /// The smoothed log excess of the VIX over `fair_value_vix_knee` that
    /// the volatility-feedback discount reads when
    /// `fair_value_vix_half_life` is set. 0.0, and never written, on every
    /// preset through pt-v19, whose `fair_value_vix_discount` is 0.0.
    pub vix_feedback: f64,
    /// The index's log return since the last central-bank meeting: the
    /// log change of total public market cap, summed over the closes and
    /// restarted by every meeting. Written only with `fed_put_gain` set;
    /// 0.0, and never written, on every preset.
    pub intermeeting_return: f64,
    /// The Fed put's stock, percentage points: each put cut adds what it
    /// took off the ladder's path, and it decays at `fed_put_half_life`.
    /// The calm meetings give the put back once this has fallen an eighth
    /// under `fed_put_owed`. Written only with `fed_put_gain` set.
    pub fed_put: f64,
    /// The Fed put's overlay not yet given back, percentage points: the
    /// ladder's own path less the policy rate. The Taylor rate the ladder
    /// reads is lowered by it. Written only with `fed_put_gain` set.
    pub fed_put_owed: f64,
    /// Total public market cap at the previous close, the base the next
    /// close's log change is read against. Written only with
    /// `fed_put_gain` set.
    pub fed_put_mcap_prev: f64,
    /// The index's log fall below its own slow average, the credit leverage
    /// term's state (`ModelParams::corporate_spread_equity_gain`): each close
    /// steps `D = 0.5^(1/H) (D - ln(1 + r))` on the session's index return
    /// from the last close, H the dial's half-life. Written only with that
    /// gain set; 0.0, and never written, on every preset.
    pub spread_equity_gap: f64,
    /// The gap the corporate spread prices, following `spread_equity_gap`
    /// at the half-life `ModelParams::corporate_spread_equity_lag`. Written
    /// only with that lag and the credit gain set; 0.0, and never written,
    /// on every preset.
    pub spread_priced_gap: f64,
    /// The gap the 10-year's anchor prices, following `spread_equity_gap` at
    /// the half-life `ModelParams::treasury_equity_lag`. Written only with
    /// that lag, its gain and credit's leverage gap set; 0.0, and never
    /// written, on every preset.
    pub treasury_equity_priced_gap: f64,
    /// What the valuation reads beyond `earnings_cycle`: the anticipated
    /// level of the earnings cycle over the valuation's horizon minus the
    /// current one (`ModelParams::earnings_anticipation_half_life`). Derived
    /// from the phase and `earnings_cycle` and kept current by the engine
    /// after every change to either, so neither hashed nor snapshotted.
    pub earnings_anticipation: f64,
    /// What the valuation reads of the common multiplier `market.earnings`
    /// has written, less the multiplier itself: `-(1 - c) (m - a)` in logs
    /// (`ModelParams::earnings_lookthrough_half_life`). Derived from the
    /// engine's written level and anchor and kept current by the engine after
    /// every change to either, so neither hashed nor snapshotted. 0.0, and
    /// never written, while that dial is 0.0, which every preset carries.
    pub earnings_lookthrough: f64,
    /// The monthly change the unemployment rate is making from its cyclical
    /// drivers (the phase's trend and Okun's law), partially adjusted toward
    /// what they ask for at `ModelParams::unemployment_adjustment_half_life`.
    /// 0.0, and never read or written, while that dial is 0.0, which every
    /// preset carries; snapshotted and hashed only while it is set.
    pub unemployment_impulse: f64,
    /// The part of the oil price that the daily pushes made, decaying at the
    /// shipped 0.03 (`ModelParams::oil_pushes_in_target`). 0.0, and never
    /// read or written, while that switch is 0.0, which every preset
    /// carries; snapshotted and hashed only while it is set.
    pub oil_push_level: f64,
    /// The dollar's safe-haven bid, decaying at the shipped 0.02
    /// (`ModelParams::usd_mean_reversion`). 0.0, and never read or written,
    /// while that dial is 0.0, which every preset carries; snapshotted and
    /// hashed only while it is set.
    pub usd_haven_level: f64,
    /// The oil pass-through's accumulated part of headline inflation,
    /// percentage points: each month-start step adds the term
    /// `oil_inflation_passthrough` adds to headline and closes the
    /// headline's own `inflation_reversion` of the gap to 0.0, so headline
    /// less it is core (`ModelParams::fed_core_inflation`). 0.0, and never
    /// read or written, while `fed_core_inflation` and
    /// `treasury_core_inflation` are both 0.0, which every preset carries;
    /// snapshotted and hashed only while either is set.
    pub oil_inflation_level: f64,
    /// The Fed put's unmet asks, percentage points: each meeting adds the
    /// part of the put's ask the policy rate could not deliver, and it decays
    /// at `treasury_path_half_life` (`ModelParams::treasury_zlb_path`). 0.0,
    /// and never read or written, while that dial is 0.0, which every preset
    /// carries; snapshotted and hashed only while it is set.
    pub zlb_unmet: f64,
    /// The log of the oil price's truncation at its bounds on the last step,
    /// ln(clamped / unclamped), 0.0 where no bound bound it. TRANSIENT: set
    /// by every step that runs the long factor (`oil_target_drift_sd`) and
    /// read by the close straight after it, which adds it to the long
    /// factor, so a bound limits the long-run level rather than opening a
    /// gap in the short factor. Never snapshotted or hashed: no reading of
    /// it outlives the step that wrote it.
    pub oil_bound_log_ratio: f64,
    /// `economy.marketPE ?? 18` at the cycle-transition sites. Kept optional
    /// because the reference implementation genuinely leaves it unset before the first market
    /// tick, and the `?? 18` there is a real fallback rather than a
    /// constructor default.
    pub market_pe: Option<f64>,

    // QE pass-through
    pub qe_pe_boost: f64,
    /// Fed securities held outright over a neutral baseline. 1.0 is
    /// neutral. The central bank integrates its purchases into it; a
    /// scenario may pin it to a measured series. Consumed only by the
    /// stock channel (`qe_pe_stock_gain`), inert on every preset that
    /// ships that dial at 0.0.
    pub qe_assets_ratio: f64,

    // Fiscal policy
    pub fiscal_stimulus: f64,
    pub government_debt_to_gdp: f64,

    // Cycle
    pub cycle_phase: CyclePhase,
    pub months_in_current_phase: f64,
    /// The growth rate this phase is pulling toward, held for the phase.
    ///
    /// Written on a phase change and read at the monthly and quarterly
    /// updates. Under every preset before pt-v18 the two read sites take
    /// `(lo + hi) / 2.0` of the phase's declared range and never look
    /// here, so this stays at its initial value and no behaviour reads
    /// it. See [`crate::params::ModelParams::phase_target_range_draw`].
    pub phase_gdp_target: f64,
    pub recession_probability: f64,
}

/// The library's default opening economy:
/// `create_initial_economy_state(&InitialEconomyOptions::default())`.
/// A host that sets its own economy starts from this, or from
/// [`create_initial_economy_state`] with its options, and assigns fields.
impl Default for EconomyState {
    fn default() -> Self {
        create_initial_economy_state(&InitialEconomyOptions::default())
    }
}

/// Options for [`create_initial_economy_state`]. `None` selects the
/// reference-implementation default parameter.
#[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;
    // `Math.max(40, Math.min(130, x))` in the original, spelled out rather
    // than routed through `clamp` because the original spells it out too.
    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;

    // The same VIX-driven spread formula `update_central_bank` uses, so the
    // opening state is consistent with the first meeting's output.
    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,
        // NOTE the 0.70/0.30 split here. Every OTHER site in the module uses
        // 0.85/0.15 — `update_economy_daily` and `update_central_bank` both
        // do. The opening state is the odd one out, and it is reproduced
        // rather than harmonised: the first daily step overwrites it anyway,
        // so "fixing" it would change the opening 2Y for no benefit and
        // break parity on day zero.
        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,
        // The midpoint, which is what every preset before pt-v18 uses for
        // the whole run because nothing reads this field at their dial's
        // zero. Under `phase_target_range_draw` it is overwritten on the
        // FIRST simulated day rather than at the first phase change: the
        // draw is gated on `months_in_current_phase < 1/30 + 0.001` and
        // the engine opens at zero months in phase, so the opening phase
        // is drawn for like any other. This value is what the field holds
        // between construction and that first day.
        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",
        }
    }

    /// `Option` for the same reason as [`CyclePhase::from_name`]: a failed
    /// parse is a malformed snapshot, not a user input error.
    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 {
    /// Game timestamps are integer minutes.
    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,
    /// Momentum from past decisions. **Real state** — declared, maintained,
    /// and read by the Taylor rule under D1. Under the deployed WASM formula
    /// nothing read it, which is the defect D1 corrects.
    pub hawkish_dovish_score: f64,
    pub forward_guidance: ForwardGuidance,
}

impl CentralBankState {
    /// The opening central bank, as [`create_initial_central_bank_state`]
    /// builds it: last meeting at `start_timestamp` (game minutes), the next
    /// 45 days later, a 2 per cent inflation target, no QE.
    pub fn new(start_timestamp: i64) -> Self {
        create_initial_central_bank_state(start_timestamp)
    }
}

/// [`CentralBankState::new`] at timestamp 0.
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,
    }
}

/// An active economic shock, as `update_economy_daily` reads it.
#[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() {
        // Not a fit -- the cycle's own shape. Expansion is calm, the peak
        // is where risk builds unnoticed, contraction is the worst of it,
        // the trough is bad but improving, recovery carries scar tissue.
        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());
        }
    }
}