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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! Python bindings, behind the `python` feature.
//!
//! Feature-gated so the WASM consumer's build never compiles
//! PyO3. The same core serves both; only this file is Python-specific.

#![allow(unexpected_cfgs, clippy::useless_conversion)]
// Both lints fire only inside pyo3 0.22 macro expansions -- create_exception!
// and #[pyfunction] -- as a "gil-refs" cfg value this crate does not define,
// and an identity Into on PyErr. Silenced at the module because the
// alternative is reshaping hand-written code to satisfy a lint aimed at code
// the macros generate.

use pyo3::prelude::*;
use pyo3::types::PyDict;

/// The seed range every surface states, in the words its errors use.
pub const SEED_RANGE: &str = "an integer from 0 to 2**64 - 1 (18446744073709551615)";

/// Read a seed from Python, or refuse it with the range in the message.
///
/// Every seed the library takes, simulation, universe or surgery, is a
/// `u64` from 0.8.5. Before that it was a `u32`, and a larger integer
/// reached the caller as pyo3's bare `OverflowError: out of range integral
/// type conversion attempted`, which named neither the argument nor the
/// range. This is the one place that turns a Python value into a seed, so
/// every surface refuses the same things in the same words: a negative
/// integer, one of `2**64` or more, a bool (an `int` to Python, and a bug
/// in a seed position), and anything that is not an integer at all, a
/// float included, since `3.7` truncated silently would be a different
/// market from the one the caller wrote down.
///
/// Anything with `__index__` is an integer here, so a numpy integer is
/// accepted as the `int` it holds.
pub(crate) fn seed_from(value: &Bound<'_, PyAny>, name: &str) -> PyResult<u64> {
    let refuse = |what: String| {
        ValidationError::new_err(format!("{name} must be {SEED_RANGE}, got {what}"))
    };
    let shown = || -> String {
        value.repr().map(|r| r.to_string()).unwrap_or_else(|_| "?".to_string())
    };
    let type_name = || -> String {
        value.get_type().name().map(|n| n.to_string()).unwrap_or_else(|_| "?".to_string())
    };
    if value.is_instance_of::<pyo3::types::PyBool>() {
        return Err(refuse(format!("{}, a bool", shown())));
    }
    match value.extract::<u64>() {
        Ok(seed) => Ok(seed),
        Err(e) if e.is_instance_of::<pyo3::exceptions::PyOverflowError>(value.py()) => {
            Err(refuse(shown()))
        }
        Err(_) => Err(refuse(format!("{}, a {}", shown(), type_name()))),
    }
}

/// " Did you mean \"x\"? <note>" when `given` differs from one of `valid`
/// only in case, and nothing otherwise.
///
/// Preset and sector names are lower case, and `"PT-V20"` or
/// `"Technology"` used to be refused with the full list of valid names and
/// nothing to say that case was the only problem.
pub(crate) fn case_hint(given: &str, valid: &[&str], note: &str) -> String {
    match valid
        .iter()
        .find(|v| **v != given && v.eq_ignore_ascii_case(given))
    {
        Some(v) => format!(" Did you mean {v:?}? {note}"),
        None => String::new(),
    }
}

/// The refusal for a model preset name this build does not ship.
pub(crate) fn unknown_preset(name: &str) -> String {
    let names = crate::params::ModelParams::preset_names();
    format!(
        "unknown model preset {name:?}.{} Shipped presets: {}",
        case_hint(name, names, "Preset names are lower case."),
        names.join(", ")
    )
}

/// The first sentence of the refusal for a sector name that is not in the
/// sector table, with the case hint when that is all that is wrong.
pub(crate) fn unknown_sector(sector: &str) -> String {
    format!(
        "unknown sector {sector:?}.{} Valid sectors: {}",
        case_hint(sector, &crate::sectors::keys(), "Sector names are lower case."),
        crate::sectors::keys().join(", ")
    )
}

/// A seed argument, read through [`seed_from`] under the name `seed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Seed(pub u64);

impl<'py> FromPyObject<'py> for Seed {
    fn extract_bound(value: &Bound<'py, PyAny>) -> PyResult<Self> {
        seed_from(value, "seed").map(Seed)
    }
}

/// A keyword argument that tells "left out" from "passed None".
///
/// pyo3 reads an `Option` argument's `None` default and a caller's `None`
/// as the same thing. `Engine` takes `*args` so it can refuse positional
/// arguments in its own words, which means `seed` and `universe` need a
/// default to be reachable at all, and this default says nothing was
/// passed: a missing seed stays a `TypeError`, as it was when the argument
/// was required, and `seed=None` stays the `ValidationError` that names
/// the range.
pub(crate) enum Given<'py> {
    Missing,
    Value(Bound<'py, PyAny>),
}

impl<'py> FromPyObject<'py> for Given<'py> {
    fn extract_bound(value: &Bound<'py, PyAny>) -> PyResult<Self> {
        Ok(Given::Value(value.clone()))
    }
}

/// Check a seed and return it as an `int`, or raise `ValidationError`.
///
/// The Python modules that take a seed before any engine sees it (a
/// checkpoint, a manifest, a sealed battery, the gym) call this, so their
/// refusals are the engine's word for word.
#[pyfunction]
#[pyo3(signature = (value, name = "seed"))]
fn check_seed(value: &Bound<'_, PyAny>, name: &str) -> PyResult<u64> {
    seed_from(value, name)
}

/// Deterministic seeded random number generator (PCG32 + Box-Muller).
///
/// Two instances constructed with the same `(seed, sequence)` produce the
/// same sequence of draws, on any platform. Each instance owns its state
/// completely: constructing two of them in one process gives two independent
/// streams, and importing the module draws nothing.
///
/// The normal-draw path caches a Box-Muller spare, so the *parity* of how
/// many normals have been drawn is part of the generator's state: Box-Muller
/// produces a PAIR from two uniforms and keeps the second. So two normals cost
/// two uniform draws, not four, and the second one advances the stream not at
/// all: a uniform drawn after one normal and after two normals is the same
/// value. Draw accounting is therefore not one-uniform-per-value, which
/// matters to anyone reasoning about where a stream is.
#[pyclass(name = "GameRng", module = "tradefloor._core")]
pub struct PyGameRng {
    inner: crate::GameRng,
}

#[pymethods]
impl PyGameRng {
    /// Construct a generator.
    ///
    /// `seed` and `sequence` together select the stream. `sequence` is
    /// required rather than defaulted: two generators differing only by
    /// sequence are independent, and silently sharing a default would make
    /// "two independent streams" quietly false.
    ///
    /// `seed` is any integer from 0 to `2**64 - 1`. Every seed below
    /// `2**32` gives the stream it gave when the seed was 32-bit.
    #[new]
    fn new(seed: Seed, sequence: u32) -> Self {
        Self {
            inner: crate::GameRng::new(seed.0, sequence),
        }
    }

    /// A uniform draw in [0, 1).
    fn next_float(&mut self) -> f64 {
        self.inner.next_f64()
    }

    /// A standard normal draw (mean 0, standard deviation 1).
    fn next_normal(&mut self) -> f64 {
        self.inner.next_normal()
    }

    /// A uniform integer in `[min, max]`, inclusive at both ends.
    fn next_int(&mut self, min: i64, max: i64) -> i64 {
        self.inner.next_int(min, max)
    }

    /// A boolean that is true with probability `p`.
    fn next_bool(&mut self, p: f64) -> bool {
        self.inner.next_bool(p)
    }

    /// An independent generator at this one's exact position.
    ///
    /// Both continue with the same draws, Box-Muller spare included, and
    /// neither moves the other. This is what `copy.deepcopy` of an agent
    /// holding a generator needs, and what `World.fork` does to an agent
    /// with no `fork()` of its own: until 0.8.5 the copy raised, because a
    /// native object with no `__deepcopy__` cannot be pickled, so a world
    /// holding the random baseline could not be forked at all.
    fn __copy__(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }

    fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self {
        self.__copy__()
    }

    fn __repr__(&self) -> String {
        "GameRng(...)".to_string()
    }
}

pyo3::create_exception!(
    _core,
    ValidationError,
    pyo3::exceptions::PyValueError,
    "Raised when construction input is rejected at the boundary. Subclasses \
     ValueError, so `except ValueError` keeps working while the specific type \
     is available to callers who want it. The taxonomy is deliberately tiny: \
     a simulator that invents an error type per field teaches users to catch \
     Exception, which catches the bugs too."
);

/// The package version.
/// The cross-binding determinism probe: one fixed simulation, hashed.
///
/// The same `engine::fixed_simulation_digest` the WebAssembly surface calls,
/// so "do the browser build and the Python build agree?" is answered by one
/// implementation rather than by two harnesses that must themselves be kept
/// in step. See that function for the hashing rules and for why the macro
/// state is in the digest.
#[pyfunction]
#[pyo3(signature = (*, size, universe_seed, seed, days, ticks, preset))]
fn fixed_simulation_digest(size: usize, universe_seed: &Bound<'_, PyAny>, seed: Seed,
                           days: usize, ticks: usize, preset: &str)
                           -> PyResult<String> {
    let universe_seed = seed_from(universe_seed, "universe_seed")?;
    crate::engine::fixed_simulation_digest(
        size, universe_seed, seed.0, days, ticks, preset)
        .ok_or_else(|| ValidationError::new_err(
            format!("unknown preset {preset:?}")))
}

#[pyfunction]
fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// A contract symbol read in its canonical spelling, as a dict: `symbol`
/// (the text, which is canonical when this returns), `root`, `expiry` (the
/// session it expires at), `kind` (`"future"` or `"option"`), and for an
/// option `right` (`"C"` or `"P"`) and `strike` (dollars), both None for a
/// future. Refuses anything [`crate::derivatives::ContractSymbol::parse`]
/// refuses, naming why. `tradefloor.contracts.parse` is the public name.
#[pyfunction]
fn parse_contract_symbol<'py>(py: Python<'py>, symbol: &str) -> PyResult<Bound<'py, PyDict>> {
    let parsed = crate::derivatives::ContractSymbol::parse(symbol).map_err(ValidationError::new_err)?;
    contract_symbol_dict(py, &parsed)
}

/// The canonical symbol for a future on `root` expiring at session
/// `expiry`, or with `right` (`"C"` or `"P"`) and `strike` (dollars, whole
/// cents) for an option. `tradefloor.contracts.format` is the public name.
#[pyfunction]
#[pyo3(signature = (root, expiry, right = None, strike = None))]
fn format_contract_symbol(root: &str, expiry: i64, right: Option<&str>, strike: Option<f64>) -> PyResult<String> {
    use crate::derivatives::{ContractSymbol, Right};
    let symbol = match (right, strike) {
        (None, None) => ContractSymbol::future(root, expiry),
        (Some(r), Some(k)) => {
            let right = match r {
                "C" => Right::Call,
                "P" => Right::Put,
                other => {
                    return Err(ValidationError::new_err(format!(
                        "an option's right is \"C\" or \"P\", got {other:?}"
                    )))
                }
            };
            ContractSymbol::option(root, expiry, right, k)
        }
        _ => {
            return Err(ValidationError::new_err(
                "an option needs both right and strike, and a future neither".to_string(),
            ))
        }
    };
    symbol.map(|s| s.to_string()).map_err(ValidationError::new_err)
}

fn contract_symbol_dict<'py>(
    py: Python<'py>,
    s: &crate::derivatives::ContractSymbol,
) -> PyResult<Bound<'py, PyDict>> {
    use crate::derivatives::SymbolKind;
    let d = PyDict::new_bound(py);
    d.set_item("symbol", s.to_string())?;
    d.set_item("root", &s.root)?;
    d.set_item("expiry", s.expiry)?;
    match s.kind {
        SymbolKind::Option { right, .. } => {
            d.set_item("kind", "option")?;
            d.set_item("right", right.letter().to_string())?;
            d.set_item("strike", s.strike())?;
        }
        _ => {
            d.set_item("kind", "future")?;
            d.set_item("right", py.None())?;
            d.set_item("strike", py.None())?;
        }
    }
    Ok(d)
}

/// Validate a fractional rate, raising `ValueError` if it looks wrong.
///
/// Exposed now, before the valuation surface that will call it, because the
/// fractional-units decision is only real if it is enforced somewhere a user
/// can see. The error names the percent-versus-fractional confusion
/// explicitly rather than reporting a bare range, because that confusion is
/// what an out-of-range rate almost always is.
#[pyfunction]
fn check_rate(name: &str, fraction: f64) -> PyResult<f64> {
    crate::units::check_rate(name, fraction).map_err(ValidationError::new_err)
}

/// The compiled extension.
///
/// Named `_core` because a Python package wraps it: `tradefloor/__init__.py`
/// re-exports everything here and adds the parts that are better written in
/// Python than in Rust -- JSON round-trips, and multiprocessing for seed
/// sweeps. Forcing those into the extension would mean hand-rolling JSON
/// escaping and reimplementing a process pool, both badly.
#[pymodule]
fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyGameRng>()?;
    m.add_function(wrap_pyfunction!(version, m)?)?;
    m.add_function(wrap_pyfunction!(parse_contract_symbol, m)?)?;
    m.add_function(wrap_pyfunction!(format_contract_symbol, m)?)?;
    m.add_function(wrap_pyfunction!(fixed_simulation_digest, m)?)?;
    m.add_function(wrap_pyfunction!(check_rate, m)?)?;
    m.add_function(wrap_pyfunction!(check_seed, m)?)?;
    m.add_function(wrap_pyfunction!(fair_value, m)?)?;
    m.add_function(wrap_pyfunction!(sectors, m)?)?;
    m.add_function(wrap_pyfunction!(step_mispricing_daily, m)?)?;
    m.add_function(wrap_pyfunction!(apply_mispricing, m)?)?;
    m.add_function(wrap_pyfunction!(characteristic_root_moduli, m)?)?;
    m.add_function(wrap_pyfunction!(crowd_adjusted_root_moduli, m)?)?;
    m.add_function(wrap_pyfunction!(impulse_response, m)?)?;
    m.add_function(wrap_pyfunction!(model_preset, m)?)?;
    m.add_function(wrap_pyfunction!(preset_names, m)?)?;
    m.add_function(wrap_pyfunction!(calibrated_flow, m)?)?;
    m.add_function(wrap_pyfunction!(assess_external_flow, m)?)?;
    m.add_class::<PyMispricingState>()?;
    m.add_class::<PyFairValue>()?;
    m.add_class::<crate::python_book::PyOrderBook>()?;
    m.add_class::<crate::python_book::PyFill>()?;
    m.add_class::<crate::python_book::PyMatchResult>()?;
    m.add_class::<crate::python_book::PyPriceLevel>()?;
    m.add_class::<crate::python_book::PySweepCost>()?;
    m.add_class::<crate::python_params::PyModelParams>()?;
    m.add_class::<crate::python_engine::PyEngine>()?;
    m.add_class::<crate::python_engine::PySurface>()?;
    m.add_class::<crate::python_engine::PyInstrument>()?;
    m.add_class::<crate::python_engine::PyMacro>()?;
    m.add_class::<crate::python_engine::PyTickResult>()?;
    m.add_class::<crate::python_batch::PyEngineBatch>()?;
    m.add_class::<crate::python_engine::PyNews>()?;
    m.add_class::<crate::python_engine::PyNewsImpact>()?;
    m.add_class::<crate::python_arrow::PyArrowStream>()?;
    m.add_function(wrap_pyfunction!(crate::python_arrow::fills_stream, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::market_status, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::random_instruments, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::rate_instruments, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::rate_specs, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::sector_volatility, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::sector_daily_sigma, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::stationary_sigma, m)?)?;
    m.add_function(wrap_pyfunction!(crate::python_engine::crisis_epicentre_solve, m)?)?;
    m.add("ValidationError", m.py().get_type_bound::<ValidationError>())?;
    m.add(
        "OrderError",
        m.py().get_type_bound::<crate::python_book::OrderError>(),
    )?;
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
    Ok(())
}

/// A fair-value result and its decomposition.
///
/// The decomposition is the point, not a debugging aid: the simulator knows
/// the multiple it applied and why, which no historical-data backtest can
/// tell you.
#[pyclass(name = "FairValue", module = "tradefloor._core", frozen, get_all)]
#[derive(Debug, Clone, Copy)]
pub struct PyFairValue {
    /// Fair value per share.
    pub fair_value: f64,
    /// The multiple actually applied. Zero on the book-value path.
    pub target_pe: f64,
    /// The sector's anchor multiple, before adjustment.
    pub sector_anchor_pe: f64,
    /// Rate adjustment applied to the anchor.
    pub rate_adjustment: f64,
    /// QE adjustment applied to the anchor.
    pub qe_adjustment: f64,
    /// True when valued off book because EPS was not positive.
    pub book_value_path: bool,
}

#[pymethods]
impl PyFairValue {
    fn __repr__(&self) -> String {
        format!(
            "FairValue(fair_value={:.4}, target_pe={:.4}, book_value_path={})",
            self.fair_value, self.target_pe, self.book_value_path
        )
    }
}

/// Fair value per share from fundamentals and the macro state.
///
/// # Which valuation
///
/// With no `model` and none of the five valuation keywords, this is the
/// reference valuation at fixed constants: a neutral discount rate of 0.04,
/// a rate sensitivity of 1.5, a QE adjustment of `1 + qe_pe_boost` (a QE
/// gain of 1.0), no QE stock channel and no book floor on profitable names.
/// That form does not follow any preset, the default included, so its
/// numbers stay fixed across releases. The manifest's era fingerprint and
/// the known-answer scripts are built on it.
///
/// An engine runs its own values for those five, and the default preset
/// differs from the reference in three of them (a neutral rate of 0.0482, a
/// rate sensitivity of 3.0 and a QE gain of 0.0). To get the valuation a
/// given engine applies, pass `model` (a preset name or a `ModelParams`) and
/// every value is read from it, or pass the values one at a time. Passing
/// `model` together with any of them is refused, because the call would
/// have two sources for one number.
///
/// With `model`, the result is the engine's valuation of these fundamentals
/// under this macro, to the bit. The engine's per-tick fair value can carry
/// more than the valuation: on presets that set them, the nominal and
/// earnings-cycle restatement, buybacks, a name's fair-value level and the
/// VIX discount, all read from the engine's state. `Engine.fair_values()`
/// returns that number for a running engine.
///
/// # Units
///
/// **Rates are fractional**: `corporate_bond_yield=0.052` means 5.2%. Two of
/// these numbers are rates and are converted to the core's percent
/// denomination here, at the boundary; the others are already fractional
/// in both and must NOT be scaled:
///
/// | argument | kind | converted? |
/// |---|---|---|
/// | `corporate_bond_yield` | rate | yes, x100 |
/// | `federal_funds_rate` | rate | yes, x100 |
/// | `neutral_discount_rate` | rate | no, compared with the yield over 100 |
/// | `revenue_growth` | growth fraction | no |
/// | `qe_pe_boost` | multiplier delta | no |
/// | `qe_assets_ratio` | ratio to a neutral 1.0 | no |
/// | `eps`, `book_value_per_share` | currency | no |
///
/// Getting that split wrong is silent: scaling `revenue_growth` by 100 turns
/// 22% growth into 2200% and produces a large, finite, entirely wrong
/// multiple. Hence the table, and hence the tests that pin each column.
///
/// # Absence versus zero
///
/// `corporate_bond_yield=None` falls through to the policy rate. A yield of
/// exactly `0.0` is a real observation and is used as-is. This is deliberately
/// the opposite of the sector anchor's behaviour, where a zero anchor falls
/// back to the default multiple.
///
/// # Negative EPS
///
/// Legal and meaningful. A loss-maker is valued off book value, and
/// `book_value_path` reports that it happened rather than leaving the caller
/// to infer it from a suspiciously round multiple.
#[pyfunction]
#[pyo3(signature = (
    *,
    eps = None,
    sector,
    revenue_growth = None,
    federal_funds_rate = 0.0,
    corporate_bond_yield = None,
    qe_pe_boost = None,
    book_value_per_share = None,
    neutral_discount_rate = None,
    qe_assets_ratio = None,
    qe_pe_gain = None,
    qe_pe_stock_gain = None,
    rate_pe_sensitivity = None,
    fair_value_book_floor = None,
    model = None,
))]
#[allow(clippy::too_many_arguments)]
fn fair_value(
    // Optional wherever the core is optional. Flattening `Option<f64>` to a
    // defaulted `f64` here would erase the absence-versus-zero distinction,
    // which is load-bearing in both directions: an absent bond yield falls
    // through to the policy rate, while a yield of exactly zero is used
    // as-is, and a zero sector anchor falls back to the default multiple
    // while an absent one does the same. Same type, opposite rules -- the
    // binding must not decide which the caller meant.
    eps: Option<f64>,
    sector: &str,
    revenue_growth: Option<f64>,
    federal_funds_rate: f64,
    corporate_bond_yield: Option<f64>,
    qe_pe_boost: Option<f64>,
    book_value_per_share: Option<f64>,
    // The five values below are the `ModelParams` fields the valuation
    // reads. Absent means the reference constant, so a call that names none
    // of them returns what it always has; that is what keeps the manifest's
    // probe and the known-answer digests off the default preset.
    neutral_discount_rate: Option<f64>,
    // Economy state, not a model value: the Fed's holdings over a neutral
    // baseline, read only by the QE stock channel. Absent is neutral.
    qe_assets_ratio: Option<f64>,
    qe_pe_gain: Option<f64>,
    qe_pe_stock_gain: Option<f64>,
    rate_pe_sensitivity: Option<f64>,
    fair_value_book_floor: Option<f64>,
    model: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyFairValue> {
    // Boundary rejections carry the specific type; PyO3's own argument-type
    // errors remain plain TypeError/ValueError, which is correct -- those are
    // "you passed a string where a float goes", not "your scenario is invalid".
    use ValidationError as Rejected;

    // Keyword-only (note the leading `*` in the signature). Seven positional
    // floats would be the roster-column hazard again: every one is a number,
    // so transposing two would typecheck, run, and quietly value the company
    // wrong.
    let s = crate::sectors::by_key(sector).ok_or_else(|| {
        Rejected::new_err(crate::python::unknown_sector(sector))
    })?;

    // Finite floats everywhere, per the validation policy. The core
    // reproduces the reference implementation's NaN behaviour faithfully -- that is what
    // the golden vectors pin -- but a NaN admitted HERE propagates silently
    // into prices: a NaN fair value takes early returns in settlement, books
    // stop trading, and the user gets a quietly frozen market instead of an
    // error. So the core keeps its faithfulness and the boundary makes sure
    // nobody reaches it by accident.
    //
    // Rates are checked separately below because their error message can be
    // more specific. This catches the rest.
    for (name, value) in [
        ("eps", eps),
        ("book_value_per_share", book_value_per_share),
        ("revenue_growth", revenue_growth),
        ("qe_pe_boost", qe_pe_boost),
        ("qe_assets_ratio", qe_assets_ratio),
        ("qe_pe_gain", qe_pe_gain),
        ("qe_pe_stock_gain", qe_pe_stock_gain),
        ("rate_pe_sensitivity", rate_pe_sensitivity),
        ("fair_value_book_floor", fair_value_book_floor),
    ] {
        if let Some(v) = value {
            if !v.is_finite() {
                return Err(Rejected::new_err(format!(
                    "{name} must be finite, got {v}"
                )));
            }
        }
    }

    // Rates. Validated in FRACTIONAL form, before conversion, so the error
    // can say "pass 0.045 for 4.5%" in the units the caller actually used.
    crate::units::check_rate("federal_funds_rate", federal_funds_rate)
        .map_err(Rejected::new_err)?;
    if let Some(y) = corporate_bond_yield {
        crate::units::check_rate("corporate_bond_yield", y).map_err(Rejected::new_err)?;
    }
    if let Some(r) = neutral_discount_rate {
        crate::units::check_rate("neutral_discount_rate", r).map_err(Rejected::new_err)?;
    }

    // One source per number. A model and an explicit value for a field it
    // carries would leave the caller to guess which one won.
    let explicit = [
        ("neutral_discount_rate", neutral_discount_rate),
        ("qe_pe_gain", qe_pe_gain),
        ("qe_pe_stock_gain", qe_pe_stock_gain),
        ("rate_pe_sensitivity", rate_pe_sensitivity),
        ("fair_value_book_floor", fair_value_book_floor),
    ];
    let (neutral, qe_gain, qe_stock_gain, sensitivity, book_floor) = match model {
        Some(m) => {
            let both: Vec<&str> = explicit
                .iter()
                .filter(|(_, v)| v.is_some())
                .map(|(name, _)| *name)
                .collect();
            if !both.is_empty() {
                return Err(Rejected::new_err(format!(
                    "model and {} were both given, and the model carries {}. Pass \
                     the model alone, or a ModelParams built with the value you want \
                     (ModelParams.from_preset(name, {}=...)).",
                    both.join(", "),
                    if both.len() == 1 { "it" } else { "them" },
                    both[0]
                )));
            }
            let p = crate::python_engine::model_params_from(Some(m))?;
            (p.neutral_discount_rate, p.qe_pe_gain, p.qe_pe_stock_gain,
             p.rate_pe_sensitivity, p.fair_value_book_floor)
        }
        // The reference constants, which are also what every preset through
        // pt-v15 ships.
        None => (
            // NOT converted. `discount_rate` divides the economy's percent by
            // 100 and compares the result against this, so the neutral point
            // is a FRACTION like the constant it defaults to, and a round trip
            // through percent would not return the caller's own bits.
            neutral_discount_rate.unwrap_or(crate::fair_value::NEUTRAL_DISCOUNT_RATE),
            qe_pe_gain.unwrap_or(1.0),
            qe_pe_stock_gain.unwrap_or(0.0),
            rate_pe_sensitivity.unwrap_or(crate::fair_value::RATE_PE_SENSITIVITY),
            fair_value_book_floor.unwrap_or(0.0),
        ),
    };

    let economy = crate::fair_value::EconomyValuationInputs {
        corporate_bond_yield: corporate_bond_yield.map(crate::units::fraction_to_percent),
        federal_funds_rate: crate::units::fraction_to_percent(federal_funds_rate),
        // NOT converted: a multiplier delta, fractional in both denominations.
        qe_pe_boost,
        // NOT converted: a ratio. Read only when the stock gain is non-zero,
        // so absent and 1.0 both contribute nothing.
        qe_assets_ratio,
    };
    let company = crate::fair_value::CompanyValuationInputs {
        sector_avg_pe: Some(s.avg_pe),
        eps,
        book_value_per_share,
        // NOT converted: already a fraction in both denominations.
        revenue_growth,
    };

    // The function every engine path calls (`market::tick`, the overnight
    // open). At the reference values it is the two-argument
    // `compute_fair_value` to the bit, which `fair_value_parity` pins.
    let b = crate::fair_value::compute_fair_value_at(
        &company, &economy, book_floor, qe_gain, qe_stock_gain, neutral, sensitivity,
    );
    Ok(PyFairValue {
        fair_value: b.fair_value,
        target_pe: b.target_pe,
        sector_anchor_pe: b.sector_anchor_pe,
        rate_adjustment: b.rate_adjustment,
        qe_adjustment: b.qe_adjustment,
        book_value_path: b.book_value_path,
    })
}

/// The twelve sector keys, in contractual declaration order.
#[pyfunction]
fn sectors() -> Vec<String> {
    crate::sectors::keys().iter().map(|s| s.to_string()).collect()
}

/// The daily log-mispricing state.
///
/// `s` is the log deviation of price from fair value, and `s_prev` is
/// yesterday's, which the momentum term needs. Immutable: a step returns a new
/// state rather than mutating, so a trajectory is a list of values you can
/// keep rather than a thing you have to copy defensively.
#[pyclass(name = "MispricingState", module = "tradefloor._core", frozen, get_all)]
#[derive(Debug, Clone, Copy)]
pub struct PyMispricingState {
    /// Current log-mispricing.
    pub s: f64,
    /// Previous day's value, the momentum term's other operand.
    pub s_prev: f64,
}

#[pymethods]
impl PyMispricingState {
    /// Build a state.
    ///
    /// With `s_prev` omitted this is the ordinary constructor: the value is
    /// clamped to the mispricing cap and `s_prev` is set equal to it, so a
    /// fresh state has zero momentum.
    ///
    /// Passing `s_prev` builds the pair VERBATIM, without clamping. That is
    /// for resuming a trajectory you already hold, where mid-trajectory `s` and
    /// `s_prev` genuinely differ, and that difference IS the momentum term.
    /// Routing it through the clamping constructor would silently zero the
    /// momentum and produce a different path from the one being resumed.
    #[new]
    #[pyo3(signature = (s = 0.0, s_prev = None))]
    fn new(s: f64, s_prev: Option<f64>) -> PyResult<Self> {
        for (name, v) in [("s", Some(s)), ("s_prev", s_prev)] {
            if let Some(v) = v {
                if !v.is_finite() {
                    return Err(ValidationError::new_err(format!(
                        "{name} must be finite, got {v}"
                    )));
                }
            }
        }
        match s_prev {
            // Verbatim: an out-of-cap value is preserved and propagates into
            // s_prev exactly once, which is the reference behaviour.
            Some(prev) => Ok(Self { s, s_prev: prev }),
            None => {
                let st = crate::mispricing::create_mispricing_state(s);
                Ok(Self { s: st.s, s_prev: st.s_prev })
            }
        }
    }

    fn __repr__(&self) -> String {
        format!("MispricingState(s={}, s_prev={})", self.s, self.s_prev)
    }
}

/// One DAILY step of the mispricing process.
///
/// # This is not the process the engine's tick loop runs
///
/// Said plainly because the two are easy to conflate and produce different
/// trajectories. This function is the clean daily AR(2) step: a 60-day
/// half-life decay, a momentum term in yesterday's change, and a shock, all
/// applied once per day. The engine applies related ideas per TICK, at 1/390
/// of a day, with crowd feedback the daily step does not have. They are
/// different processes, not rounding variants of one another, and a
/// trajectory from one will not reproduce a trajectory from the other.
///
/// The daily step is the library's public model because it is what can be
/// characterised: its stationarity is provable in closed form via
/// [`characteristic_root_moduli`], not merely observed by simulating and
/// hoping. The tick variant is deliberately not exposed as a standalone
/// function; it is reachable only by running the engine, which is where it
/// belongs.
///
/// # Arguments
///
/// `innovation` is the GARCH-scaled, zero-mean daily innovation, already
/// sized by the caller and NOT clamped. `shock` is the day's summed
/// directional pressure -- news, net order flow, squeezes -- and IS clamped to
/// the daily shock cap. That asymmetry is deliberate: noise is sized by the
/// volatility model, whereas directional shocks are bounded so a single day
/// cannot dominate.
#[pyfunction]
#[pyo3(signature = (state, *, innovation = 0.0, shock = 0.0))]
fn step_mispricing_daily(
    state: &PyMispricingState,
    innovation: f64,
    shock: f64,
) -> PyResult<PyMispricingState> {
    for (name, v) in [("innovation", innovation), ("shock", shock)] {
        if !v.is_finite() {
            return Err(ValidationError::new_err(format!(
                "{name} must be finite, got {v}"
            )));
        }
    }
    let next = crate::mispricing::step_mispricing(
        &crate::mispricing::MispricingState { s: state.s, s_prev: state.s_prev },
        &crate::mispricing::MispricingInputs { innovation, shock },
    );
    Ok(PyMispricingState { s: next.s, s_prev: next.s_prev })
}

/// Price from fair value and mispricing: `fair_value * exp(s)`, floored.
///
/// The floor is a JavaScript-semantics max, so a NaN propagates rather than
/// being silently replaced by the floor. A negative fair value survives the
/// multiply and is then floored, so this never returns a negative price.
#[pyfunction]
fn apply_mispricing(fair_value: f64, s: f64) -> f64 {
    crate::mispricing::apply_mispricing(fair_value, s)
}

/// Moduli of the AR(2) characteristic roots.
///
/// Both strictly inside the unit circle means the process is stationary --
/// proven, not sampled. This is the analytic backbone of the claim that the
/// daily model cannot wander off, and it is why the daily step is the public
/// surface.
#[pyfunction]
#[pyo3(signature = (phi = None, theta = None))]
fn characteristic_root_moduli(phi: Option<f64>, theta: Option<f64>) -> (f64, f64) {
    crate::mispricing::characteristic_root_moduli(phi, theta)
}

/// The same, with the crowd-feedback term included.
#[pyfunction]
fn crowd_adjusted_root_moduli() -> (f64, f64) {
    crate::mispricing::crowd_adjusted_root_moduli()
}

/// Impulse response of the daily process over `horizon_days`.
#[pyfunction]
#[pyo3(signature = (horizon_days, phi = None, theta = None))]
fn impulse_response(horizon_days: i64, phi: Option<f64>, theta: Option<f64>) -> PyResult<Vec<f64>> {
    if horizon_days < 0 {
        return Err(ValidationError::new_err(format!(
            "horizon_days must be >= 0, got {horizon_days}"
        )));
    }
    Ok(crate::mispricing::impulse_response(horizon_days, phi, theta))
}

/// The model coefficients, as a named immutable preset.
///
/// Coefficients ship as a versioned preset rather than as constructor
/// keywords so that two published results can be compared: "pt-v1" names an
/// exact model, whereas forty tunable keyword arguments guarantee no two users
/// ran the same one.
///
/// Only LIVE coefficients appear. A preset listing knobs wired to nothing
/// would be a documentation lie of the kind this port has already had to
/// correct once.
///
/// # Frozen shape, by the KAT
///
/// This dict is the mispricing coefficient table it has always been, and
/// its shape is LOAD-BEARING: `tests/known_answer.py` section 6 and
/// `tradefloor.manifest.era_fingerprint` both hash every value in it, so
/// growing it moves the committed v8 digest without a simulation change,
/// exactly what the KAT versioning rule forbids. The FULL preset surface
/// lives on `ModelParams.from_preset(name)`
/// and `.to_dict()` instead; this function gains `name=` so a preset can
/// be selected by the string an engine takes, and keeps its legacy shape
/// until the next KAT bump carries the growth deliberately.
///
/// # Values follow the name
///
/// The values come from the NAMED preset, not from the `pub const`s. While
/// `pt-v1` was the only entry the two were the same thing and reading the
/// consts was the shorter spelling; with a second preset in the table they
/// are not, and a `model_preset("pt-v2")` that answered with pt-v1's
/// coefficients under the label "pt-v1" would be the exact substitution the
/// fingerprint rule exists to make impossible, reached through the one
/// function on the surface that had not been taught the difference. The
/// default path is unchanged to the bit, so the KAT's digest does not move.
/// `daily_shock_cap` still reads its const because it is carried read-only
/// and identical in every preset by construction.
#[pyfunction]
#[pyo3(signature = (name = None))]
fn model_preset(py: Python<'_>, name: Option<&str>) -> PyResult<PyObject> {
    use crate::mispricing as m;
    // The default follows the engine's default preset rather than a literal.
    // It did not, once: this argument read "pt-v1" while engines ran pt-v3,
    // so every manifest recorded the wrong coefficient set under the wrong
    // name. See `params::DEFAULT_PRESET_NAME`, which a test ties to
    // `Engine::default_model()` so the two cannot drift apart again.
    let name = name.unwrap_or(crate::params::DEFAULT_PRESET_NAME);
    let preset = crate::params::ModelParams::preset(name).ok_or_else(|| {
        ValidationError::new_err(crate::python::unknown_preset(name))
    })?;
    let d = pyo3::types::PyDict::new_bound(py);
    d.set_item("name", name)?;
    d.set_item(
        "mispricing_half_life_days",
        preset.mispricing_half_life_days,
    )?;
    d.set_item("mispricing_phi", preset.mispricing_phi)?;
    d.set_item("momentum_theta", preset.momentum_theta)?;
    d.set_item("mispricing_cap", preset.mispricing_cap)?;
    d.set_item("daily_shock_cap", m::DAILY_SHOCK_CAP)?;
    d.set_item("crowd_valuation_gain", preset.crowd_valuation_gain)?;
    d.set_item("crowd_momentum_gain", preset.crowd_momentum_gain)?;
    d.set_item("crowd_lean_cap", preset.crowd_lean_cap)?;
    Ok(d.into())
}

/// The shock flow a preset generates for itself: `tradefloor.flow::CalibratedFlow`
/// as a dict. `tradefloor.envelope.CALIBRATED_FLOW` is built from this.
#[pyfunction]
#[pyo3(signature = (model = None))]
fn calibrated_flow(
    py: Python<'_>,
    model: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyObject> {
    let params = crate::python_engine::model_params_from(model)?;
    let f = crate::flow::CalibratedFlow::of(&params);
    let d = pyo3::types::PyDict::new_bound(py);
    d.set_item("company_news_rate", f.company_news_rate)?;
    d.set_item("company_news_sigma", f.company_news_sigma)?;
    d.set_item("company_news_variance", f.company_news_variance())?;
    d.set_item("sector_news_rate", f.sector_news_rate)?;
    d.set_item("market_news_rate", f.market_news_rate)?;
    d.set_item("news_sector_weight", f.news_sector_weight)?;
    d.set_item("news_market_weight", f.news_market_weight)?;
    d.set_item("idio_jump_rate", f.idio_jump_rate)?;
    d.set_item("idio_jump_sigma", f.idio_jump_sigma)?;
    d.set_item("market_jump_rate", f.market_jump_rate)?;
    d.set_item("market_jump_mean", f.market_jump_mean)?;
    d.set_item("market_jump_sigma", f.market_jump_sigma)?;
    d.set_item("market_factor_sigma", f.market_factor_sigma)?;
    d.set_item("macro_shock_share", f.macro_shock_share)?;
    d.set_item("macro_steps_per_session", f.macro_steps_per_session)?;
    d.set_item("off_session_ticks_per_session", f.off_session_ticks_per_session)?;
    d.set_item("news_drift", f.news_drift)?;
    for (k, phase) in crate::flow::CYCLE_PHASES.iter().enumerate() {
        let name = phase.as_str();
        d.set_item(format!("{name}_share"), f.phase_shares[k])?;
        d.set_item(format!("{name}_mean_sessions"), f.phase_mean_sessions[k])?;
        d.set_item(format!("{name}_sd_sessions"), f.phase_sd_sessions[k])?;
        d.set_item(format!("{name}_run_limit"), f.phase_run_limit[k])?;
    }
    d.set_item("downturn_share", f.downturn_share)?;
    d.set_item("downturn_mean_sessions", f.downturn_mean_sessions)?;
    d.set_item("downturn_run_limit", f.downturn_run_limit)?;
    Ok(d.into_py(py))
}

/// The keys `assess_external_flow` reads from its tally, every one required.
const FLOW_TALLY_KEYS: [&str; 16] = [
    "names", "sessions", "company_events", "company_sum_sq", "sector_events",
    "sector_sum_sq", "market_events", "market_sum_sq", "fundamental_events",
    "fundamental_sum_sq", "vix_writes", "vix_write_abs", "vix_write_max",
    "macro_steps", "macro_shock_steps", "macro_shock_load",
];

/// The keys it reads when present and takes as zero when not: the signed
/// sums behind the drift, the ticks outside the regular session, the
/// host's input to the VIX target, and `cycle_phases`, the phase name each
/// session traded in, in order. Added after 0.10.0, so a tally written for
/// 0.10.0 still reads.
const FLOW_TALLY_OPTIONAL_KEYS: [&str; 9] = [
    "company_sum", "sector_sum", "market_sum", "fundamental_sum", "off_session_ticks",
    "vix_target_writes", "vix_target_write_abs", "vix_target_floor_sessions", "cycle_phases",
];

/// `tradefloor.flow::ExternalFlow::assess`, from a tally a caller kept.
/// `tradefloor.envelope.external_flow` builds the tally; this is the one
/// implementation both languages share.
#[pyfunction]
#[pyo3(signature = (tally, model = None))]
fn assess_external_flow(
    py: Python<'_>,
    tally: &Bound<'_, pyo3::types::PyDict>,
    model: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyObject> {
    let params = crate::python_engine::model_params_from(model)?;
    for key in tally.keys().iter() {
        let k: String = key.extract()?;
        if !FLOW_TALLY_KEYS.contains(&k.as_str())
            && !FLOW_TALLY_OPTIONAL_KEYS.contains(&k.as_str())
        {
            return Err(ValidationError::new_err(format!(
                "unknown flow tally key {k:?}; the keys are {FLOW_TALLY_KEYS:?} and, \
                 optionally, {FLOW_TALLY_OPTIONAL_KEYS:?}")));
        }
    }
    let get = |k: &str| -> PyResult<Bound<'_, PyAny>> {
        tally.get_item(k)?.ok_or_else(|| ValidationError::new_err(format!(
            "the flow tally needs {k:?}; the keys are {FLOW_TALLY_KEYS:?}")))
    };
    let count = |k: &str| -> PyResult<u64> {
        get(k)?.extract::<u64>().map_err(|_| ValidationError::new_err(format!(
            "{k} must be a non-negative integer")))
    };
    let real = |k: &str| -> PyResult<f64> {
        let v: f64 = get(k)?.extract().map_err(|_| ValidationError::new_err(format!(
            "{k} must be a number")))?;
        if !(v >= 0.0) || !v.is_finite() {
            return Err(ValidationError::new_err(format!(
                "{k} must be finite and non-negative, got {v}")));
        }
        Ok(v)
    };
    let signed = |k: &str| -> PyResult<f64> {
        match tally.get_item(k)? {
            None => Ok(0.0),
            Some(v) => {
                let v: f64 = v.extract().map_err(|_| ValidationError::new_err(format!(
                    "{k} must be a number")))?;
                if !v.is_finite() {
                    return Err(ValidationError::new_err(format!(
                        "{k} must be finite, got {v}")));
                }
                Ok(v)
            }
        }
    };
    let mut obs = crate::flow::ExternalFlow::new(count("names")? as usize);
    obs.company_sum = signed("company_sum")?;
    obs.sector_sum = signed("sector_sum")?;
    obs.market_sum = signed("market_sum")?;
    obs.fundamental_sum = signed("fundamental_sum")?;
    let optional_count = |k: &str| -> PyResult<u64> {
        match tally.get_item(k)? {
            None => Ok(0),
            Some(v) => v.extract::<u64>().map_err(|_| ValidationError::new_err(format!(
                "{k} must be a non-negative integer"))),
        }
    };
    obs.off_session_ticks = optional_count("off_session_ticks")?;
    obs.vix_target_writes = optional_count("vix_target_writes")?;
    obs.vix_target_floor_sessions = optional_count("vix_target_floor_sessions")?;
    obs.vix_target_write_abs = match tally.get_item("vix_target_write_abs")? {
        None => 0.0,
        Some(_) => real("vix_target_write_abs")?,
    };
    obs.sessions = count("sessions")?;
    obs.company_events = count("company_events")?;
    obs.company_sum_sq = real("company_sum_sq")?;
    obs.sector_events = count("sector_events")?;
    obs.sector_sum_sq = real("sector_sum_sq")?;
    obs.market_events = count("market_events")?;
    obs.market_sum_sq = real("market_sum_sq")?;
    obs.fundamental_events = count("fundamental_events")?;
    obs.fundamental_sum_sq = real("fundamental_sum_sq")?;
    obs.vix_writes = count("vix_writes")?;
    obs.vix_write_abs = real("vix_write_abs")?;
    obs.vix_write_max = real("vix_write_max")?;
    obs.macro_steps = count("macro_steps")?;
    obs.macro_shock_steps = count("macro_shock_steps")?;
    obs.macro_shock_load = real("macro_shock_load")?;
    if let Some(v) = tally.get_item("cycle_phases")? {
        let names: Vec<String> = v.extract().map_err(|_| ValidationError::new_err(
            "cycle_phases must be a list of phase names, one a session"))?;
        for name in names {
            let phase = crate::economy::CyclePhase::from_name(&name).ok_or_else(|| {
                ValidationError::new_err(format!(
                    "unknown cycle phase {name:?} in cycle_phases; the phases are {:?}",
                    crate::flow::CYCLE_PHASES.map(|p| p.as_str())))
            })?;
            obs.record_cycle_phase(phase);
        }
    }
    let a = obs.assess(&params);
    let d = pyo3::types::PyDict::new_bound(py);
    d.set_item("inside", a.inside)?;
    d.set_item("company_news_ratio", a.company_news_ratio)?;
    d.set_item("common_news_ratio", a.common_news_ratio)?;
    d.set_item("fundamental_ratio", a.fundamental_ratio)?;
    d.set_item("vix_write_per_session", a.vix_write_per_session)?;
    d.set_item("vix_target_per_session", a.vix_target_per_session)?;
    d.set_item("vix_target_floor_share", a.vix_target_floor_share)?;
    d.set_item("macro_shock_share", a.macro_shock_share)?;
    d.set_item("macro_shock_load", a.macro_shock_load)?;
    d.set_item("macro_steps_per_session", a.macro_steps_per_session)?;
    d.set_item("off_session_ticks_per_session", a.off_session_ticks_per_session)?;
    d.set_item("news_drift", a.news_drift)?;
    d.set_item("fundamental_drift", a.fundamental_drift)?;
    for (k, phase) in crate::flow::CYCLE_PHASES.iter().enumerate() {
        d.set_item(format!("{}_share", phase.as_str()), a.phase_shares[k])?;
        d.set_item(format!("{}_longest", phase.as_str()), a.phase_longest[k])?;
    }
    d.set_item("downturn_share", a.downturn_share)?;
    d.set_item("downturn_longest", a.downturn_longest)?;
    d.set_item("findings", a.findings)?;
    Ok(d.into_py(py))
}

/// The shipped preset names, in the order the engine lists them.
///
/// The engine has always known this list -- `preset_names()` backs every
/// "unknown model preset" message and the WASM surface exports it -- and
/// Python could not read it, so every Python consumer that wanted the set
/// had to guess at it. `tools/calibration/preset_panel.py` guessed by
/// probing `pt-v1`, `pt-v2`, ... and stopping at the first name that did
/// not resolve, which measured sixteen presets on a build that ships
/// SEVENTEEN: `pt-v17` is reserved by the recomposition era, so the probe
/// stopped one short of `pt-v18` and the panel silently omitted the preset
/// the run existed to measure.
///
/// A guessed list fails quietly and a read list cannot. Returns the names,
/// not the coefficients; `model_preset(name)` reads one.
#[pyfunction]
fn preset_names() -> Vec<String> {
    crate::params::ModelParams::preset_names()
        .iter()
        .map(|s| (*s).to_string())
        .collect()
}