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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
//! The shock flow a preset was calibrated at, and a check on the flow a
//! caller adds to it.
//!
//! Every preset is fitted with the engine supplying its own shocks and
//! nothing else: company news drawn at each open, idiosyncratic and market
//! jumps, and one macro step per trading session with no active economic
//! shocks. A caller that hands the engine news through
//! [`crate::engine::TickRequest::news`] or [`crate::engine::SessionRequest`],
//! or macro shocks through [`crate::engine::DayAdvanceRequest::active_shocks`],
//! adds to that flow, and the model's realism statements describe the flow it
//! was fitted at, not the sum.
//!
//! [`CalibratedFlow`] states the fitted flow for any [`ModelParams`].
//! [`ExternalFlow`] is a tally a host keeps of what it supplied, and
//! [`ExternalFlow::assess`] compares the two. Neither touches an engine: the
//! tally is the caller's object, holds no model state and takes no draw, so
//! keeping one changes no trajectory.
//!
//! The comparison is per channel, because the channels reach prices
//! differently.
//!
//! - Company news lands on the one name it names. The fitted flow has it,
//!   at `endogenous_news_intensity` events a name a session with log size
//!   `endogenous_news_sigma`, so external company news is compared with that
//!   variance, and it is outside once it adds more than the fitted channel
//!   carries, which doubles the channel.
//! - Sector and market-wide news move many names at once, at weights
//!   `news_sector_weight` and `news_market_weight`. The fitted flow has none
//!   of either, so they are compared with the variance of the factor they
//!   move with, the market factor's base daily variance
//!   (`market_factor_sigma` squared), and are outside above
//!   [`COMMON_NEWS_TOLERANCE`] of it. The sector share assumes a roster
//!   spread evenly over the twelve sectors.
//! - Macro shocks have no fitted counterpart. A step's active shocks add
//!   twice the absolute sum of `gdp_impact x severity` to the VIX's daily
//!   target, and on a preset with `market_vol_vix_coupling` the market
//!   factor's variance target follows the VIX, so a sustained shock raises
//!   every name's volatility and the correlation between names. Any macro
//!   step with an active shock is outside.
//! - Fundamental revisions written with
//!   [`crate::engine::Engine::set_fundamentals`] move fair value one for one,
//!   since fair value is earnings times a target multiple. The fitted flow
//!   moves earnings only through the engine's own nominal and cycle terms,
//!   so a host's revisions are another per-name repricing and are compared
//!   with the fitted company news variance, outside once they exceed it.
//! - VIX levels a host writes into the economy (through
//!   [`crate::engine::Engine::economy_mut`]) move the market factor's
//!   variance target on a coupled preset as the VIX's own moves do. The
//!   fitted flow writes none, and the tally is outside once the written
//!   changes average more than [`VIX_WRITE_TOLERANCE`] points a session.
//! - A premium on the VIX target or a floor under it
//!   ([`crate::engine::Engine::set_vix_target_premium`],
//!   [`crate::engine::Engine::set_vix_target_floor`]) moves the VIX through
//!   the engine's own reversion rather than by a write, and lasts as long as
//!   the host holds it. The fitted flow has neither, so any premium written,
//!   or any session closed under a floor, is outside.
//! - From pt-v19 the macro calendar counts trading sessions
//!   (`macro_calendar_days_per_year` 252). A host that steps the economy on
//!   every calendar day, weekends included, runs the macro clock about 1.45
//!   times fast and applies its shocks that much more often, and is outside
//!   above [`MACRO_STEP_TOLERANCE`] steps a session.
//! - Every preset is fitted on the 390 ticks of the regular session, 09:30
//!   to 16:00. A tick outside it, pre-market or after-hours, draws noise at
//!   the session's per-minute scale all the same, so it adds variance the
//!   preset was not fitted with; on pt-v21 the open already applies the
//!   night's share of the day's move. [`ExternalFlow::record_tick`] counts
//!   them, and the tally is outside above [`OFF_SESSION_TOLERANCE`] of a
//!   session's ticks.
//! - The fitted news has mean zero, and from pt-v20 a company's news moves
//!   its fair value for good (`fair_value_news_share`). News or earnings
//!   revisions that lean one way move fair value by their sum, so beside
//!   their variance the tally keeps their signed sum, and is outside once
//!   either moves fair value by more than [`DRIFT_TOLERANCE`] a year on
//!   average, beyond [`DRIFT_STANDARD_ERRORS`] standard errors of the
//!   estimate, so a flow of mean zero is not flagged for its sampling noise.
//!   A stock split written as an earnings cut, without dividing the
//!   engine's price, is a revision of `-ln(ratio)`.
//! - The business cycle runs itself in a free run, and every preset's
//!   realism statements pool its own mix of phases. A host that writes the
//!   phase, pins it, or opens and drives the economy so that a phase lasts
//!   far longer than the preset's own, runs a market the preset was not
//!   fitted on: on a coupled preset a contraction or trough raises the
//!   market's variance for as long as it holds. [`ExternalFlow::record_cycle_phase`]
//!   counts the sessions in each phase and the longest unbroken run of
//!   each, and of a contraction and trough together, and the tally is
//!   outside once a run passes the [`CYCLE_RUN_QUANTILE`] quantile of the
//!   preset's own sojourn on the cycle's hazard. The share of sessions in
//!   each phase is reported against the preset's stationary share, and
//!   not judged: a run of a few years holds one or two cycles, so its share
//!   is mostly where it opened.

use crate::economy::cycle::{
    downturn_quantile_days_for, mean_sojourn_days_for, sojourn_quantile_days_for,
    sojourn_sd_days_for,
};
use crate::economy::{CyclePhase, CycleSpec, EconomicShock, MacroCalendar};
use crate::market::{GameTime, NewsEvent};
use crate::params::ModelParams;

/// Ticks in a regular session: what [`crate::engine::Engine::tick`] divides a
/// news event's `price_impact` by.
const SESSION_TICKS: f64 = 390.0;

/// Common (sector and market-wide) news is outside the fitted flow above
/// this share of the market factor's base daily variance. Chosen, not
/// fitted: a tenth of the factor's variance is about a five per cent rise in
/// its volatility.
pub const COMMON_NEWS_TOLERANCE: f64 = 0.1;

/// Mean absolute VIX points a host writes a session above which the tally is
/// outside. Chosen, not fitted: the VIX's own mean absolute daily change on
/// pt-v20 is about 0.64 points (20 seeds, 504 sessions, a 108-name roster),
/// so this is about a sixth of it.
pub const VIX_WRITE_TOLERANCE: f64 = 0.1;

/// Macro steps per trading session above which the macro clock is outside
/// the fitted flow. One step a session is the fitted rate; the tolerance
/// leaves room for a host that steps once on a holiday it does not trade.
pub const MACRO_STEP_TOLERANCE: f64 = 1.05;

/// Ticks outside the regular session, as a share of the session's 390, above
/// which the tally is outside. Chosen, not fitted: one per cent of the
/// session's ticks adds about one per cent to a name's daily noise variance.
/// A host that ticks from 07:00 to 20:00, 150 pre-market and 240
/// after-hours ticks a weekday, is at 1.0, and on a 108-name roster over 20
/// seeds and 504 sessions those ticks raised index volatility from 12.7 to
/// 14.7 per cent a year on pt-v21 and from 15.7 to 19.2 on pt-v20.
pub const OFF_SESSION_TOLERANCE: f64 = 0.01;

/// Mean log move a year, per name, that news or earnings revisions may add
/// to fair value before the tally is outside. Chosen, not fitted: the fitted
/// news has mean zero, and one per cent a year is a sixth of pt-v21's
/// long-run index return.
pub const DRIFT_TOLERANCE: f64 = 0.01;

/// Standard errors of the drift's estimate that it must clear beyond
/// [`DRIFT_TOLERANCE`] before the tally is outside. A tally of a few
/// hundred news events of mean zero reads a drift of a few per cent a year
/// from sampling alone; the estimate's standard error is the square root of
/// the moves' sum of squares, scaled as the drift is.
pub const DRIFT_STANDARD_ERRORS: f64 = 3.0;

/// The quantile of the preset's own sojourn in a phase past which a run held
/// in it is outside. Chosen, not fitted: one sojourn in a hundred on the
/// preset's own cycle runs longer, so a tally of a few cycles' phases is
/// flagged now and then on the preset's own cycle, as the drift check is.
pub const CYCLE_RUN_QUANTILE: f64 = 0.99;

/// Trading sessions a year, for the drift's annual rate.
const SESSIONS_A_YEAR: f64 = 252.0;

/// The phases in [`crate::economy::cycle::phase_cycle`] order, the order of every per-phase array
/// in this module: expansion, peak, contraction, trough, recovery.
pub const CYCLE_PHASES: [CyclePhase; 5] = [
    CyclePhase::Expansion,
    CyclePhase::Peak,
    CyclePhase::Contraction,
    CyclePhase::Trough,
    CyclePhase::Recovery,
];

/// `phase`'s place in [`CYCLE_PHASES`].
fn phase_slot(phase: CyclePhase) -> usize {
    match phase {
        CyclePhase::Expansion => 0,
        CyclePhase::Peak => 1,
        CyclePhase::Contraction => 2,
        CyclePhase::Trough => 3,
        CyclePhase::Recovery => 4,
    }
}

/// The cycle's clock and table under `params`, as the engine reads them in a
/// session ([`crate::engine::Engine::cycle_spec`]; the opening's hazard is
/// not read in a session). The economy steps once a session, so its days are
/// sessions.
fn cycle_spec_of(params: &ModelParams) -> CycleSpec {
    CycleSpec {
        per_month: params.cycle_hazard_per_month,
        month_days: MacroCalendar::from_days_per_year(params.macro_calendar_days_per_year)
            .month_f64(),
        us: params.cycle_us_calibration != 0.0,
        equity_hazard: params.cycle_equity_hazard,
        equity_knee: params.cycle_equity_hazard_knee,
        equity_opening: 0.0,
        inflation_hazard: params.cycle_inflation_hazard,
        rate_hazard: params.cycle_rate_hazard,
    }
}

/// The shocks a preset generates for itself, which is the flow its fitted
/// statistics were measured under.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct CalibratedFlow {
    /// Company news events a name a session (`endogenous_news_intensity`).
    pub company_news_rate: f64,
    /// Standard deviation of a company news event's log size
    /// (`endogenous_news_sigma`).
    pub company_news_sigma: f64,
    /// Sector-scoped news events a session. Zero on every preset: the engine
    /// draws none.
    pub sector_news_rate: f64,
    /// Market-wide news events a session. Zero on every preset.
    pub market_news_rate: f64,
    /// Weight a sector-scoped event lands on each name in its sector.
    pub news_sector_weight: f64,
    /// Weight a market-wide event lands on every name.
    pub news_market_weight: f64,
    /// Idiosyncratic jumps a name a session, and their log-size sd.
    pub idio_jump_rate: f64,
    pub idio_jump_sigma: f64,
    /// Market jumps a session, their mean and their sd.
    pub market_jump_rate: f64,
    pub market_jump_mean: f64,
    pub market_jump_sigma: f64,
    /// The market factor's base daily sigma (`market_factor_sigma`).
    pub market_factor_sigma: f64,
    /// Share of macro steps that carry an active economic shock. Zero: the
    /// library's own day loop passes none.
    pub macro_shock_share: f64,
    /// Macro steps a trading session. One: the library steps the economy at
    /// each close.
    pub macro_steps_per_session: f64,
    /// Ticks a session outside 09:30 to 16:00. Zero: the preset is fitted on
    /// the regular session's 390.
    pub off_session_ticks_per_session: f64,
    /// Mean log move a year the fitted news adds to a name's fair value.
    /// Zero: each event's size is a draw of mean zero.
    pub news_drift: f64,
    /// The share of sessions the preset's own cycle spends in each phase, in
    /// [`CYCLE_PHASES`] order, on the cycle's hazard alone
    /// ([`crate::economy::cycle::stationary_phase_shares_for`]). The state
    /// ladder (rates, unemployment, the curve) and the market's own hazard
    /// (`cycle_equity_hazard`) are left out, as the stationary opening
    /// leaves them out.
    pub phase_shares: [f64; 5],
    /// The mean sojourn in each phase, in sessions, on the hazard alone.
    pub phase_mean_sessions: [f64; 5],
    /// The standard deviation of each phase's sojourn, in sessions.
    pub phase_sd_sessions: [f64; 5],
    /// The [`CYCLE_RUN_QUANTILE`] quantile of each phase's sojourn, in
    /// sessions: a run held longer is outside.
    pub phase_run_limit: [i64; 5],
    /// The share of sessions in a contraction or a trough.
    pub downturn_share: f64,
    /// The mean of a contraction and its trough together, in sessions.
    pub downturn_mean_sessions: f64,
    /// The [`CYCLE_RUN_QUANTILE`] quantile of a contraction and its trough
    /// together, in sessions.
    pub downturn_run_limit: i64,
}

impl CalibratedFlow {
    /// The flow `params` generates for itself.
    pub fn of(params: &ModelParams) -> Self {
        let spec = cycle_spec_of(params);
        let mut phase_mean_sessions = [0.0; 5];
        let mut phase_sd_sessions = [0.0; 5];
        let mut phase_run_limit = [0i64; 5];
        for (k, &phase) in CYCLE_PHASES.iter().enumerate() {
            phase_mean_sessions[k] = mean_sojourn_days_for(phase, &spec);
            phase_sd_sessions[k] = sojourn_sd_days_for(phase, &spec);
            phase_run_limit[k] = sojourn_quantile_days_for(phase, &spec, CYCLE_RUN_QUANTILE);
        }
        let cycle: f64 = phase_mean_sessions.iter().sum();
        let phase_shares = phase_mean_sessions.map(|m| m / cycle);
        let (c, t) = (phase_slot(CyclePhase::Contraction), phase_slot(CyclePhase::Trough));
        CalibratedFlow {
            company_news_rate: params.endogenous_news_intensity,
            company_news_sigma: params.endogenous_news_sigma,
            sector_news_rate: 0.0,
            market_news_rate: 0.0,
            news_sector_weight: params.news_sector_weight,
            news_market_weight: params.news_market_weight,
            idio_jump_rate: params.jump_intensity_idio,
            idio_jump_sigma: params.jump_sigma_idio,
            market_jump_rate: params.jump_intensity_market,
            market_jump_mean: params.jump_mean_market,
            market_jump_sigma: params.jump_sigma_market,
            market_factor_sigma: params.market_factor_sigma,
            macro_shock_share: 0.0,
            macro_steps_per_session: 1.0,
            off_session_ticks_per_session: 0.0,
            news_drift: 0.0,
            phase_shares,
            phase_mean_sessions,
            phase_sd_sessions,
            phase_run_limit,
            downturn_share: phase_shares[c] + phase_shares[t],
            downturn_mean_sessions: phase_mean_sessions[c] + phase_mean_sessions[t],
            downturn_run_limit: downturn_quantile_days_for(&spec, CYCLE_RUN_QUANTILE),
        }
    }

    /// Log-price variance the fitted company news adds to one name each
    /// session: rate times size squared.
    pub fn company_news_variance(&self) -> f64 {
        self.company_news_rate * self.company_news_sigma * self.company_news_sigma
    }

    /// The market factor's base daily variance, the yardstick for news that
    /// moves many names at once.
    pub fn market_factor_variance(&self) -> f64 {
        self.market_factor_sigma * self.market_factor_sigma
    }
}

/// A tally of the shocks a caller supplied, kept by the caller.
///
/// Feed it what the engine is handed, in the units the engine is handed it:
/// [`ExternalFlow::record_tick`] with each request given to
/// [`crate::engine::Engine::tick`], which records its news and its clock,
/// [`ExternalFlow::record_session_news`] with the slice given to a whole
/// [`crate::engine::Engine::run_session`],
/// [`ExternalFlow::record_macro_step`] with the shocks given to each macro
/// step ([`crate::engine::Engine::advance_day`] or
/// [`crate::engine::Engine::close_day_with_shocks`]),
/// [`ExternalFlow::record_fundamental_move`] for each earnings figure a host
/// rewrites, [`ExternalFlow::record_vix_write`] for each VIX it writes,
/// [`ExternalFlow::record_vix_target_premium`] for each premium it writes on
/// the VIX target, [`ExternalFlow::record_vix_target_floor_session`] for each
/// session it closes under a floor,
/// [`ExternalFlow::record_cycle_phase`] with the cycle phase each session
/// traded in, and [`ExternalFlow::record_session`] once per trading
/// session. The tally then
/// holds rates and sizes [`ExternalFlow::assess`] can compare with the
/// fitted flow.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ExternalFlow {
    /// Names in the roster the news is spread over.
    pub names: usize,
    /// Trading sessions recorded.
    pub sessions: u64,
    /// Company-scoped events and the sum of their squared log moves.
    pub company_events: u64,
    pub company_sum_sq: f64,
    /// Sector-scoped events (a sector, no company) and the same sum.
    pub sector_events: u64,
    pub sector_sum_sq: f64,
    /// Market-wide events (no company, no sector) and the same sum.
    pub market_events: u64,
    pub market_sum_sq: f64,
    /// Fundamental revisions (log changes in earnings a host wrote) and the
    /// sum of their squares.
    pub fundamental_events: u64,
    pub fundamental_sum_sq: f64,
    /// VIX levels the host wrote: how many, the sum of their absolute
    /// changes in points, and the largest.
    pub vix_writes: u64,
    pub vix_write_abs: f64,
    pub vix_write_max: f64,
    /// Macro steps recorded, and how many carried an active shock.
    pub macro_steps: u64,
    pub macro_shock_steps: u64,
    /// Sum over macro steps of `|sum of gdp_impact x severity|`, the
    /// quantity the VIX target reads.
    pub macro_shock_load: f64,
    /// The signed sum of the company news's log moves: what it adds to fair
    /// value on average, where `company_sum_sq` gives its variance.
    pub company_sum: f64,
    /// The signed sum of the sector news's log moves.
    pub sector_sum: f64,
    /// The signed sum of the market-wide news's log moves.
    pub market_sum: f64,
    /// The signed sum of the fundamental revisions' log changes.
    pub fundamental_sum: f64,
    /// Ticks recorded outside the regular session, 09:30 to 16:00 on a
    /// weekday.
    pub off_session_ticks: u64,
    /// Premiums the host wrote on the VIX target: how many, and the sum of
    /// their absolute changes in points.
    pub vix_target_writes: u64,
    pub vix_target_write_abs: f64,
    /// Sessions closed with a floor under the VIX target.
    pub vix_target_floor_sessions: u64,
    /// Sessions recorded in each cycle phase, in [`CYCLE_PHASES`] order.
    pub phase_sessions: [u64; 5],
    /// The longest unbroken run of sessions in each phase, the run under way
    /// included.
    pub phase_longest: [u64; 5],
    /// The longest unbroken run of sessions in a contraction or a trough.
    pub downturn_longest: u64,
    /// The phase last recorded, and the runs under way: in it, and in a
    /// contraction or trough.
    pub cycle_last: Option<CyclePhase>,
    pub phase_run: u64,
    pub downturn_run: u64,
}

impl ExternalFlow {
    /// An empty tally for a roster of `names`.
    pub fn new(names: usize) -> Self {
        ExternalFlow {
            names,
            ..ExternalFlow::default()
        }
    }

    /// One event landing a log move of `size` (before the scope weight).
    pub fn record_news_move(&mut self, company_id: Option<&str>, sector: Option<&str>, size: f64) {
        if !size.is_finite() || size == 0.0 {
            return;
        }
        let sq = size * size;
        if company_id.is_some() {
            self.company_events += 1;
            self.company_sum_sq += sq;
            self.company_sum += size;
        } else if sector.is_some() {
            self.sector_events += 1;
            self.sector_sum_sq += sq;
            self.sector_sum += size;
        } else {
            self.market_events += 1;
            self.market_sum_sq += sq;
            self.market_sum += size;
        }
    }

    /// The news handed to one [`crate::engine::Engine::tick`]. The tick
    /// divides each event's `price_impact` by 390, so that is the move the
    /// event lands.
    pub fn record_tick_news(&mut self, news: &[NewsEvent]) {
        for e in news {
            let x = e.price_impact.unwrap_or(0.0) / SESSION_TICKS;
            self.record_news_move(e.company_id.as_deref(), e.sector.as_deref(), x);
        }
    }

    /// One [`crate::engine::Engine::tick`] call: the news it was handed, as
    /// [`ExternalFlow::record_tick_news`] takes it, and whether its clock
    /// lies outside the regular session.
    pub fn record_tick(&mut self, request: &crate::engine::TickRequest) {
        self.record_tick_news(request.news);
        self.record_tick_time(request.time);
    }

    /// A tick at `time`, counted when it lies outside the regular session
    /// (09:30 to 16:00 on a weekday, [`crate::market::is_market_open`]).
    pub fn record_tick_time(&mut self, time: GameTime) {
        if !crate::market::is_market_open(time) {
            self.off_session_ticks += 1;
        }
    }

    /// The news handed to one whole [`crate::engine::Engine::run_session`],
    /// which applies it on every tick, so an event lands its full
    /// `price_impact` over the session.
    pub fn record_session_news(&mut self, news: &[NewsEvent]) {
        for e in news {
            let x = e.price_impact.unwrap_or(0.0);
            self.record_news_move(e.company_id.as_deref(), e.sector.as_deref(), x);
        }
    }

    /// One name's earnings revised by a log change of `size`, as written
    /// with [`crate::engine::Engine::set_fundamentals`]. A write that leaves
    /// the figure where it was is not a revision; pass only the ones that
    /// moved it.
    pub fn record_fundamental_move(&mut self, size: f64) {
        if !size.is_finite() || size == 0.0 {
            return;
        }
        self.fundamental_events += 1;
        self.fundamental_sum_sq += size * size;
        self.fundamental_sum += size;
    }

    /// The host wrote the economy's VIX, changing it by `delta` points.
    pub fn record_vix_write(&mut self, delta: f64) {
        if !delta.is_finite() || delta == 0.0 {
            return;
        }
        self.vix_writes += 1;
        self.vix_write_abs += delta.abs();
        if delta.abs() > self.vix_write_max {
            self.vix_write_max = delta.abs();
        }
    }

    /// The host wrote the VIX target's premium
    /// ([`crate::engine::Engine::set_vix_target_premium`]), changing it by
    /// `delta` points from the premium standing.
    pub fn record_vix_target_premium(&mut self, delta: f64) {
        if !delta.is_finite() || delta == 0.0 {
            return;
        }
        self.vix_target_writes += 1;
        self.vix_target_write_abs += delta.abs();
    }

    /// One session closed with a floor under the VIX target
    /// ([`crate::engine::Engine::set_vix_target_floor`]).
    pub fn record_vix_target_floor_session(&mut self) {
        self.vix_target_floor_sessions += 1;
    }

    /// One call of [`crate::engine::Engine::advance_day`] with these shocks.
    pub fn record_macro_step(&mut self, shocks: &[EconomicShock]) {
        self.macro_steps += 1;
        if !shocks.is_empty() {
            self.macro_shock_steps += 1;
        }
        let load: f64 = shocks.iter().map(|s| s.gdp_impact * s.severity).sum();
        self.macro_shock_load += load.abs();
    }

    /// One session traded in `phase`. Call it once a session, with the
    /// phase the economy held while the session traded: read before the
    /// close's macro step, or, for a host that reads the phase back after
    /// each step and writes it into the next, the phase it wrote. Either
    /// reading works if it is the same one every session.
    pub fn record_cycle_phase(&mut self, phase: CyclePhase) {
        let k = phase_slot(phase);
        self.phase_sessions[k] += 1;
        self.phase_run = if self.cycle_last == Some(phase) { self.phase_run + 1 } else { 1 };
        self.cycle_last = Some(phase);
        if self.phase_run > self.phase_longest[k] {
            self.phase_longest[k] = self.phase_run;
        }
        if matches!(phase, CyclePhase::Contraction | CyclePhase::Trough) {
            self.downturn_run += 1;
            if self.downturn_run > self.downturn_longest {
                self.downturn_longest = self.downturn_run;
            }
        } else {
            self.downturn_run = 0;
        }
    }

    /// Sessions recorded with a cycle phase.
    pub fn cycle_sessions(&self) -> u64 {
        self.phase_sessions.iter().sum()
    }

    /// One trading session traded.
    pub fn record_session(&mut self) {
        self.sessions += 1;
    }

    /// Compare the tally with the flow `params` was fitted at.
    pub fn assess(&self, params: &ModelParams) -> FlowAssessment {
        assess(&CalibratedFlow::of(params), self)
    }
}

/// What [`ExternalFlow::assess`] found. `inside` is false when any channel is
/// outside the fitted flow, and `findings` says which and by how much.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct FlowAssessment {
    pub inside: bool,
    /// External company news variance a name a session over the fitted
    /// company news variance.
    pub company_news_ratio: f64,
    /// External sector and market-wide news variance a name a session over
    /// the market factor's base daily variance.
    pub common_news_ratio: f64,
    /// Fundamental revision variance a name a session over the fitted
    /// company news variance.
    pub fundamental_ratio: f64,
    /// Mean absolute VIX points the host wrote a session.
    pub vix_write_per_session: f64,
    /// Mean absolute points of VIX target premium the host wrote a session.
    pub vix_target_per_session: f64,
    /// Share of sessions closed with a floor under the VIX target.
    pub vix_target_floor_share: f64,
    /// Share of macro steps that carried an active shock.
    pub macro_shock_share: f64,
    /// Mean `|sum of gdp_impact x severity|` a macro step: half the VIX
    /// target points the shocks add.
    pub macro_shock_load: f64,
    /// Macro steps a session.
    pub macro_steps_per_session: f64,
    /// Ticks a session outside the regular session.
    pub off_session_ticks_per_session: f64,
    /// Mean log move a year the host's news adds to a name's fair value:
    /// its company news spread over the roster, its sector news at
    /// `news_sector_weight` over the twelve sectors, its market-wide news at
    /// `news_market_weight`.
    pub news_drift: f64,
    /// Mean log move a year the host's earnings revisions add to a name's
    /// fair value.
    pub fundamental_drift: f64,
    /// The share of the sessions recorded with a phase that were in each
    /// phase, in [`CYCLE_PHASES`] order, against
    /// [`CalibratedFlow::phase_shares`]. All zero with none recorded.
    pub phase_shares: [f64; 5],
    /// The share in a contraction or a trough, against
    /// [`CalibratedFlow::downturn_share`].
    pub downturn_share: f64,
    /// The longest run held in each phase, in sessions, against
    /// [`CalibratedFlow::phase_run_limit`].
    pub phase_longest: [u64; 5],
    /// The longest run in a contraction or trough, against
    /// [`CalibratedFlow::downturn_run_limit`].
    pub downturn_longest: u64,
    /// One sentence per channel outside the fitted flow.
    pub findings: Vec<String>,
}

fn assess(fit: &CalibratedFlow, obs: &ExternalFlow) -> FlowAssessment {
    let sessions = if obs.sessions > 0 {
        obs.sessions as f64
    } else {
        1.0
    };
    let names = if obs.names > 0 { obs.names as f64 } else { 1.0 };
    // Company news: each event lands on one name.
    let company_var = obs.company_sum_sq / (names * sessions);
    let fitted_company = fit.company_news_variance();
    let company_news_ratio = if fitted_company > 0.0 {
        company_var / fitted_company
    } else if company_var > 0.0 {
        f64::INFINITY
    } else {
        0.0
    };
    // Common news: a sector event lands on each member at the sector weight,
    // a market event on every name at the market weight. Per name a session.
    let sector_var = obs.sector_sum_sq * fit.news_sector_weight * fit.news_sector_weight
        / (crate::sectors::keys().len() as f64 * sessions);
    let market_var = obs.market_sum_sq * fit.news_market_weight * fit.news_market_weight / sessions;
    let factor_var = fit.market_factor_variance();
    let common_news_ratio = if factor_var > 0.0 {
        (sector_var + market_var) / factor_var
    } else {
        0.0
    };
    let fundamental_var = obs.fundamental_sum_sq / (names * sessions);
    let fundamental_ratio = if fitted_company > 0.0 {
        fundamental_var / fitted_company
    } else if fundamental_var > 0.0 {
        f64::INFINITY
    } else {
        0.0
    };
    let vix_write_per_session = obs.vix_write_abs / sessions;
    let vix_target_per_session = obs.vix_target_write_abs / sessions;
    let vix_target_floor_share = obs.vix_target_floor_sessions as f64 / sessions;
    let steps = obs.macro_steps as f64;
    let macro_shock_share = if steps > 0.0 {
        obs.macro_shock_steps as f64 / steps
    } else {
        0.0
    };
    let macro_shock_load = if steps > 0.0 {
        obs.macro_shock_load / steps
    } else {
        0.0
    };
    let macro_steps_per_session = if obs.sessions > 0 {
        steps / sessions
    } else {
        0.0
    };
    let off_session_ticks_per_session = obs.off_session_ticks as f64 / sessions;
    let year = SESSIONS_A_YEAR / sessions;
    let sectors = crate::sectors::keys().len() as f64;
    let news_drift = year
        * (obs.company_sum / names
            + obs.sector_sum * fit.news_sector_weight / sectors
            + obs.market_sum * fit.news_market_weight)
        - fit.news_drift;
    let fundamental_drift = year * obs.fundamental_sum / names;
    // The drift's standard error under a mean of zero: each scope's sum has
    // the variance of its sum of squares, scaled as the drift scales it.
    let sector_scale = fit.news_sector_weight / sectors;
    let news_se = year
        * crate::mathx::sqrt(
            obs.company_sum_sq / (names * names)
                + obs.sector_sum_sq * sector_scale * sector_scale
                + obs.market_sum_sq * fit.news_market_weight * fit.news_market_weight,
        );
    let fundamental_se = year * crate::mathx::sqrt(obs.fundamental_sum_sq) / names;

    let cycle_sessions = obs.cycle_sessions();
    let (phase_shares, downturn_share) = if cycle_sessions > 0 {
        let n = cycle_sessions as f64;
        let shares = obs.phase_sessions.map(|k| k as f64 / n);
        let (c, t) = (phase_slot(CyclePhase::Contraction), phase_slot(CyclePhase::Trough));
        (shares, shares[c] + shares[t])
    } else {
        ([0.0; 5], 0.0)
    };

    let mut findings = Vec::new();
    if company_news_ratio > 1.0 {
        findings.push(format!(
            "company news adds {:.2}x the variance the preset's own company news carries \
             ({:.3} events a name a session, rms log move {:.4}, against {:.3} at sd {:.4}), \
             so the news channel runs at {:.2}x its fitted size",
            company_news_ratio,
            obs.company_events as f64 / (names * sessions),
            if obs.company_events > 0 {
                crate::mathx::sqrt(obs.company_sum_sq / obs.company_events as f64)
            } else {
                0.0
            },
            fit.company_news_rate,
            fit.company_news_sigma,
            1.0 + company_news_ratio,
        ));
    }
    if common_news_ratio > COMMON_NEWS_TOLERANCE {
        findings.push(format!(
            "sector and market-wide news add {:.2} of the market factor's base daily variance \
             ({:.3} sector and {:.3} market-wide events a session); the preset draws no news \
             of either scope, so every name moves together by that much more than it was fitted at",
            common_news_ratio,
            obs.sector_events as f64 / sessions,
            obs.market_events as f64 / sessions,
        ));
    }
    if fundamental_ratio > 1.0 {
        findings.push(format!(
            "fundamental revisions add {:.2}x the fitted company news variance ({:.4} \
             revisions a name a session, rms log change {:.4}); fair value moves one for one \
             with earnings, and the preset was fitted with earnings moved only by its own \
             nominal and cycle terms",
            fundamental_ratio,
            obs.fundamental_events as f64 / (names * sessions),
            if obs.fundamental_events > 0 {
                crate::mathx::sqrt(obs.fundamental_sum_sq / obs.fundamental_events as f64)
            } else {
                0.0
            },
        ));
    }
    if vix_write_per_session > VIX_WRITE_TOLERANCE {
        findings.push(format!(
            "the host wrote the VIX {} times, {:.2} points a session in absolute terms and up to \
             {:.1} points at once; the preset writes none, and the market factor's variance \
             target follows the VIX on a preset with `market_vol_vix_coupling`",
            obs.vix_writes, vix_write_per_session, obs.vix_write_max,
        ));
    }
    if obs.vix_target_writes > 0 {
        findings.push(format!(
            "the host wrote a premium on the VIX target {} times, {:.2} points a session in \
             absolute terms; the preset was fitted with none, and the VIX reverts toward the \
             target the premium raises for as long as it stands",
            obs.vix_target_writes, vix_target_per_session,
        ));
    }
    if obs.vix_target_floor_sessions > 0 {
        findings.push(format!(
            "{:.0}% of sessions closed with a floor under the VIX target; the preset was \
             fitted with none, and the VIX reverts toward the floor while the target is under it",
            100.0 * vix_target_floor_share,
        ));
    }
    if obs.macro_shock_steps > 0 {
        findings.push(format!(
            "{:.0}% of macro steps carried an active economic shock, at a mean load of {:.2}; \
             the preset was fitted with none, and each step's load adds twice itself to the \
             VIX target, and on a preset with `market_vol_vix_coupling` the market factor's \
             variance target follows the VIX",
            100.0 * macro_shock_share,
            macro_shock_load,
        ));
    }
    if obs.sessions > 0 && macro_steps_per_session > MACRO_STEP_TOLERANCE {
        findings.push(format!(
            "the economy stepped {:.2} times a trading session; the preset's macro calendar \
             counts sessions, so its months, quarters and phases run {:.2}x fast",
            macro_steps_per_session, macro_steps_per_session,
        ));
    }
    if off_session_ticks_per_session > OFF_SESSION_TOLERANCE * SESSION_TICKS {
        findings.push(format!(
            "the host ran {:.0} ticks a session outside 09:30 to 16:00; the preset is fitted on \
             the regular session's 390, each tick outside it draws noise at the session's \
             per-minute scale, and on a preset with an overnight move the open already \
             carries the night",
            off_session_ticks_per_session,
        ));
    }
    if news_drift.abs() > DRIFT_TOLERANCE + DRIFT_STANDARD_ERRORS * news_se {
        findings.push(format!(
            "the host's news leans {:+.1}% a year a name on average (standard error {:.1}%); \
             the preset's own news has mean zero, and on a preset with \
             `fair_value_news_share` a company's news moves its fair value for good, so the \
             market drifts by about that much",
            100.0 * news_drift,
            100.0 * news_se,
        ));
    }
    if fundamental_drift.abs() > DRIFT_TOLERANCE + DRIFT_STANDARD_ERRORS * fundamental_se {
        findings.push(format!(
            "the host's earnings revisions move each name's fair value by {:+.1}% a year on \
             average (standard error {:.1}%; log changes summing to {:+.4} over {} revisions \
             across all names); fair value moves one for one with earnings, and a stock split \
             written as an earnings cut without dividing the engine's price is a revision of \
             -ln(ratio)",
            100.0 * fundamental_drift,
            100.0 * fundamental_se,
            obs.fundamental_sum,
            obs.fundamental_events,
        ));
    }
    for (k, &phase) in CYCLE_PHASES.iter().enumerate() {
        let limit = fit.phase_run_limit[k];
        if limit < i64::MAX && obs.phase_longest[k] as i64 > limit {
            findings.push(format!(
                "a {} ran {} sessions unbroken, where the preset's own {} lasts {:.0} \
                 sessions on average and {} of every 100 end by session {}; {:.0}% of the {} \
                 sessions recorded were in a {}, against {:.0}% on the preset's own cycle",
                phase.as_str(),
                obs.phase_longest[k],
                phase.as_str(),
                fit.phase_mean_sessions[k],
                (100.0 * CYCLE_RUN_QUANTILE).round(),
                limit,
                100.0 * phase_shares[k],
                cycle_sessions,
                phase.as_str(),
                100.0 * fit.phase_shares[k],
            ));
        }
    }
    if fit.downturn_run_limit < i64::MAX && obs.downturn_longest as i64 > fit.downturn_run_limit {
        findings.push(format!(
            "a contraction and trough together ran {} sessions unbroken, where the preset's own \
             last {:.0} on average and {} of every 100 end by session {}; {:.0}% of the {} \
             sessions recorded were in a contraction or trough, against {:.0}% on the preset's \
             own cycle, and on a preset with `market_vol_cycle_ratio` both phases raise the \
             market's variance for as long as they hold",
            obs.downturn_longest,
            fit.downturn_mean_sessions,
            (100.0 * CYCLE_RUN_QUANTILE).round(),
            fit.downturn_run_limit,
            100.0 * downturn_share,
            cycle_sessions,
            100.0 * fit.downturn_share,
        ));
    }
    FlowAssessment {
        inside: findings.is_empty(),
        company_news_ratio,
        common_news_ratio,
        fundamental_ratio,
        vix_write_per_session,
        vix_target_per_session,
        vix_target_floor_share,
        macro_shock_share,
        macro_shock_load,
        macro_steps_per_session,
        off_session_ticks_per_session,
        news_drift,
        fundamental_drift,
        phase_shares,
        downturn_share,
        phase_longest: obs.phase_longest,
        downturn_longest: obs.downturn_longest,
        findings,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::economy::ShockKind;

    fn v20() -> ModelParams {
        ModelParams::preset("pt-v20").unwrap()
    }

    fn company(x: f64) -> NewsEvent {
        NewsEvent {
            company_id: Some("A-0".into()),
            sector: Some("technology".into()),
            price_impact: Some(x),
        }
    }

    #[test]
    fn the_calibrated_flow_reads_the_preset() {
        let p = v20();
        let f = CalibratedFlow::of(&p);
        assert_eq!(f.company_news_rate, p.endogenous_news_intensity);
        assert_eq!(f.company_news_sigma, p.endogenous_news_sigma);
        assert_eq!(f.market_jump_rate, p.jump_intensity_market);
        assert_eq!(f.sector_news_rate, 0.0);
        assert_eq!(f.market_news_rate, 0.0);
        assert_eq!(f.macro_shock_share, 0.0);
        assert_eq!(f.macro_steps_per_session, 1.0);
    }

    #[test]
    fn no_external_flow_is_inside() {
        let mut t = ExternalFlow::new(40);
        for _ in 0..252 {
            t.record_macro_step(&[]);
            t.record_session();
        }
        let a = t.assess(&v20());
        assert!(a.inside, "{:?}", a.findings);
        assert_eq!(a.company_news_ratio, 0.0);
    }

    #[test]
    fn a_tick_lands_one_390th_and_a_session_lands_the_whole_impact() {
        let mut tick = ExternalFlow::new(1);
        tick.record_tick_news(&[company(0.05 * 390.0)]);
        let mut session = ExternalFlow::new(1);
        session.record_session_news(&[company(0.05)]);
        assert!((tick.company_sum_sq - 0.0025).abs() < 1e-15);
        assert!((session.company_sum_sq - 0.0025).abs() < 1e-15);
    }

    #[test]
    fn company_news_is_outside_past_the_fitted_variance() {
        let p = v20();
        let fit = CalibratedFlow::of(&p);
        let names = 100usize;
        let sessions = 1000u64;
        // Exactly the fitted variance: rate x sigma^2 a name a session.
        let at = |scale: f64| {
            let mut t = ExternalFlow::new(names);
            t.sessions = sessions;
            t.company_events = (fit.company_news_rate * names as f64 * sessions as f64) as u64;
            t.company_sum_sq = scale * fit.company_news_variance() * names as f64 * sessions as f64;
            t.assess(&p)
        };
        assert!(at(1.0).inside);
        let over = at(2.0);
        assert!(!over.inside);
        assert!((over.company_news_ratio - 2.0).abs() < 1e-9);
    }

    #[test]
    fn common_news_macro_shocks_and_a_fast_macro_clock_are_each_outside() {
        let p = v20();
        let mut market = ExternalFlow::new(100);
        market.sessions = 252;
        // One market-wide 3% event a session: 0.3^2 x 0.03^2 = 8.1e-5 a
        // session against a base factor variance of about 4.2e-5.
        market.market_events = 252;
        market.market_sum_sq = 252.0 * 0.03 * 0.03;
        assert!(!market.assess(&p).inside);

        let mut shocks = ExternalFlow::new(100);
        shocks.record_session();
        shocks.record_macro_step(&[EconomicShock {
            kind: ShockKind::Pandemic,
            severity: 0.5,
            gdp_impact: -2.0,
        }]);
        let a = shocks.assess(&p);
        assert!(!a.inside);
        assert_eq!(a.macro_shock_share, 1.0);
        assert!((a.macro_shock_load - 1.0).abs() < 1e-12);

        let mut clock = ExternalFlow::new(100);
        for d in 0..252 {
            clock.record_session();
            clock.record_macro_step(&[]);
            if d % 5 < 2 {
                clock.record_macro_step(&[]);
            }
        }
        let a = clock.assess(&p);
        assert!(!a.inside);
        assert!(a.macro_steps_per_session > 1.3);
    }

    #[test]
    fn written_vix_levels_are_outside_past_the_tolerance() {
        let p = v20();
        let mut t = ExternalFlow::new(10);
        for _ in 0..100 {
            t.record_session();
            t.record_macro_step(&[]);
        }
        t.record_vix_write(5.0);
        assert!(
            t.assess(&p).inside,
            "5 points over 100 sessions is 0.05 a session"
        );
        t.record_vix_write(-10.0);
        let a = t.assess(&p);
        assert!(!a.inside);
        assert_eq!(t.vix_write_max, 10.0);
        assert!((a.vix_write_per_session - 0.15).abs() < 1e-12);
    }

    #[test]
    fn a_vix_target_premium_or_floor_is_outside_and_counted_apart_from_writes() {
        let p = v20();
        let mut t = ExternalFlow::new(10);
        for _ in 0..100 {
            t.record_session();
            t.record_macro_step(&[]);
        }
        assert!(t.assess(&p).inside);
        t.record_vix_target_premium(0.0);
        assert!(t.assess(&p).inside, "a write that moved nothing is no write");
        t.record_vix_target_premium(6.0);
        t.record_vix_target_premium(-2.0);
        let a = t.assess(&p);
        assert!(!a.inside);
        assert_eq!(t.vix_target_writes, 2);
        assert_eq!(t.vix_writes, 0);
        assert!((a.vix_target_per_session - 0.08).abs() < 1e-12);
        let mut f = ExternalFlow::new(10);
        for _ in 0..100 {
            f.record_session();
            f.record_macro_step(&[]);
        }
        for _ in 0..25 {
            f.record_vix_target_floor_session();
        }
        let a = f.assess(&p);
        assert!(!a.inside);
        assert!((a.vix_target_floor_share - 0.25).abs() < 1e-12);
        assert!(a.findings.iter().any(|x| x.contains("floor")), "{:?}", a.findings);
    }

    #[test]
    fn quarterly_earnings_revisions_of_a_quarter_are_outside() {
        // Four revisions a name a year of rms log size 0.25: about 0.25 of
        // log variance a year, against the fitted news channel's 0.004.
        let p = v20();
        let mut t = ExternalFlow::new(10);
        for d in 0..252 {
            t.record_session();
            t.record_macro_step(&[]);
            if d % 63 == 0 {
                for _ in 0..10 {
                    t.record_fundamental_move(0.25);
                }
            }
        }
        t.record_fundamental_move(0.0);
        assert_eq!(t.fundamental_events, 40);
        let a = t.assess(&p);
        assert!(!a.inside);
        assert!(a.fundamental_ratio > 50.0, "{}", a.fundamental_ratio);
    }

    #[test]
    fn ticks_outside_the_session_are_counted_and_outside_past_the_tolerance() {
        use crate::engine::TickRequest;
        let p = v20();
        let mut t = ExternalFlow::new(10);
        for _ in 0..10 {
            t.record_session();
            t.record_macro_step(&[]);
            // The regular session is inside, 09:30 to 15:59 on a weekday.
            for m in 0..390i64 {
                let at = 9 * 60 + 30 + m;
                t.record_tick(&TickRequest::new(GameTime::new(at / 60, at % 60, 3)));
            }
        }
        assert_eq!(t.off_session_ticks, 0);
        assert!(t.assess(&p).inside);
        // Three ticks a session pre-market is under one per cent of 390.
        for _ in 0..30 {
            t.record_tick_time(GameTime::new(9, 0, 3));
        }
        assert!(t.assess(&p).inside);
        // A host that ticks from 07:00 to 20:00: 150 pre-market and 240
        // after-hours ticks.
        for _ in 0..10 {
            for m in 0..150i64 {
                let at = 7 * 60 + m;
                t.record_tick_time(GameTime::new(at / 60, at % 60, 3));
            }
            for m in 0..240i64 {
                let at = 16 * 60 + m;
                t.record_tick_time(GameTime::new(at / 60, at % 60, 3));
            }
        }
        let a = t.assess(&p);
        assert!(!a.inside);
        assert!((a.off_session_ticks_per_session - 393.0).abs() < 1e-9);
        assert!(a.findings.iter().any(|f| f.contains("outside 09:30 to 16:00")));
    }

    #[test]
    fn news_and_revisions_that_lean_one_way_are_outside_as_drift() {
        let p = ModelParams::preset("pt-v21").unwrap();
        let fit = CalibratedFlow::of(&p);
        assert_eq!(fit.news_drift, 0.0);
        assert_eq!(fit.off_session_ticks_per_session, 0.0);
        let names = 100usize;
        // Company news at the fitted rate and size, half up and half down,
        // is inside; the same events all down move fair value by about
        // 0.05 x 0.0175 x 252 = 22% a year.
        let at = |sign: &dyn Fn(usize) -> f64| {
            let mut t = ExternalFlow::new(names);
            for d in 0..252 {
                t.record_session();
                t.record_macro_step(&[]);
                for i in 0..5 {
                    let x = sign(d * 5 + i) * fit.company_news_sigma;
                    t.record_session_news(&[company(x)]);
                }
            }
            t.assess(&p)
        };
        let even = at(&|k| if k % 2 == 0 { 1.0 } else { -1.0 });
        assert!(even.inside, "{:?}", even.findings);
        assert!(even.news_drift.abs() < 1e-12);
        let down = at(&|_| -1.0);
        assert!(!down.inside);
        let want = -0.05 * fit.company_news_sigma * 252.0;
        assert!((down.news_drift - want).abs() < 1e-9, "{}", down.news_drift);
        assert!(down.findings.iter().any(|f| f.contains("-22.1% a year")), "{:?}", down.findings);

        // One 2:1 split a name over two years, written as an earnings cut.
        let mut t = ExternalFlow::new(names);
        for _ in 0..504 {
            t.record_session();
            t.record_macro_step(&[]);
        }
        for _ in 0..names {
            t.record_fundamental_move(-(2.0f64).ln());
        }
        let a = t.assess(&p);
        assert!(!a.inside);
        assert!((a.fundamental_drift + 0.5 * (2.0f64).ln()).abs() < 1e-12);
        assert!(a.findings.iter().any(|f| f.contains("-ln(ratio)")));
    }

    #[test]
    fn the_calibrated_flow_states_the_presets_own_cycle() {
        assert_eq!(CYCLE_PHASES, crate::economy::cycle::phase_cycle());
        let f = CalibratedFlow::of(&ModelParams::preset("pt-v21").unwrap());
        let (c, t) = (phase_slot(CyclePhase::Contraction), phase_slot(CyclePhase::Trough));
        assert!((f.phase_shares.iter().sum::<f64>() - 1.0).abs() < 1e-12);
        // The US table on a 21-session month: a contraction of 5.5 months, a
        // trough of 3.5, and a contraction and trough a twelfth of sessions.
        assert!((f.phase_mean_sessions[c] - 115.5).abs() < 0.05, "{}", f.phase_mean_sessions[c]);
        assert!((f.phase_mean_sessions[t] - 73.5).abs() < 0.05, "{}", f.phase_mean_sessions[t]);
        assert_eq!(f.phase_run_limit[c], 246);
        assert_eq!(f.phase_run_limit[t], 170);
        assert_eq!(f.downturn_run_limit, 338);
        assert!((f.downturn_share - 0.0833).abs() < 5e-4, "{}", f.downturn_share);
        assert!((f.downturn_mean_sessions - 189.0).abs() < 0.1);
        assert!(f.phase_sd_sessions.iter().all(|&x| x > 0.0 && x.is_finite()));
        // A preset on the shipped table and clock reads its own figures.
        let old = CalibratedFlow::of(&v20());
        assert!((old.phase_shares.iter().sum::<f64>() - 1.0).abs() < 1e-12);
        assert!(old.phase_run_limit.iter().all(|&d| d > 0 && d < i64::MAX));
    }

    /// A tally of `profile`, one session a step, every session with a macro
    /// step and its phase.
    fn cycle_tally(profile: &[(CyclePhase, u64)]) -> ExternalFlow {
        let mut t = ExternalFlow::new(108);
        for &(phase, n) in profile {
            for _ in 0..n {
                t.record_session();
                t.record_macro_step(&[]);
                t.record_cycle_phase(phase);
            }
        }
        t
    }

    #[test]
    fn a_phase_run_past_the_presets_own_99th_percentile_is_outside() {
        use CyclePhase::*;
        let p = ModelParams::preset("pt-v21").unwrap();
        let (c, t) = (phase_slot(Contraction), phase_slot(Trough));
        // Median sojourns on the preset's own cycle are inside.
        let own = cycle_tally(&[(Contraction, 104), (Trough, 66), (Recovery, 252), (Expansion, 334)]);
        let a = own.assess(&p);
        assert!(a.inside, "{:?}", a.findings);
        assert_eq!(a.phase_longest[t], 66);
        assert_eq!(a.downturn_longest, 170);
        assert!((a.downturn_share - 170.0 / 756.0).abs() < 1e-12);
        assert!((a.phase_shares.iter().sum::<f64>() - 1.0).abs() < 1e-12);
        // A trough at the 99th percentile is inside, and one session longer is not.
        assert!(cycle_tally(&[(Trough, 170)]).assess(&p).inside);
        let a = cycle_tally(&[(Trough, 171)]).assess(&p);
        assert!(!a.inside);
        assert!(a.findings[0].starts_with("a trough ran 171 sessions unbroken"), "{:?}", a.findings);
        // The held profile of issue #303: the trough and the downturn are outside.
        let held = cycle_tally(&[(Expansion, 126), (Contraction, 126), (Trough, 454), (Recovery, 50)]);
        let a = held.assess(&p);
        assert_eq!(a.findings.len(), 2, "{:?}", a.findings);
        assert!(a.findings[1].contains("together ran 580 sessions"), "{:?}", a.findings);
        // A long contraction from a weak opening, and its trough.
        let a = cycle_tally(&[(Contraction, 305), (Trough, 69), (Recovery, 382)]).assess(&p);
        assert!(!a.inside);
        assert!(a.findings[0].starts_with("a contraction ran 305"), "{:?}", a.findings);
        assert_eq!(a.downturn_longest, 374);
        // A run broken by another phase starts again.
        let broken = cycle_tally(&[(Contraction, 200), (Recovery, 1), (Contraction, 200)]);
        assert_eq!(broken.phase_sessions[c], 400);
        assert_eq!(broken.phase_longest[c], 200);
        assert_eq!(broken.downturn_longest, 200);
        assert!(broken.assess(&p).inside);
    }

    #[test]
    fn a_tally_without_phases_reports_no_cycle() {
        let mut t = ExternalFlow::new(10);
        for _ in 0..100 {
            t.record_session();
            t.record_macro_step(&[]);
        }
        let a = t.assess(&ModelParams::preset("pt-v21").unwrap());
        assert!(a.inside);
        assert_eq!(t.cycle_sessions(), 0);
        assert_eq!(a.phase_shares, [0.0; 5]);
        assert_eq!(a.downturn_share, 0.0);
        assert_eq!(a.phase_longest, [0; 5]);
    }

    #[test]
    fn news_of_mean_zero_is_not_flagged_for_its_sampling_noise() {
        // The fitted company news, drawn, on a small roster over a year: the
        // sum of a few hundred draws reads a drift of several per cent a
        // year from sampling alone, which the standard error absorbs.
        let p = ModelParams::preset("pt-v21").unwrap();
        let fit = CalibratedFlow::of(&p);
        let mut g = crate::rng::GameRng::new(11, 3);
        let mut largest: f64 = 0.0;
        for _ in 0..20 {
            let mut t = ExternalFlow::new(40);
            for _ in 0..252 {
                t.record_session();
                t.record_macro_step(&[]);
                for _ in 0..40 {
                    if g.next_f64() < fit.company_news_rate {
                        let x = fit.company_news_sigma * g.next_normal();
                        t.record_session_news(&[company(x)]);
                    }
                }
            }
            let a = t.assess(&p);
            largest = largest.max(a.news_drift.abs());
            assert!(!a.findings.iter().any(|f| f.contains("leans")), "{:?}", a.findings);
        }
        assert!(largest > DRIFT_TOLERANCE, "the test should draw a drift past the tolerance: {largest}");
    }
}