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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
//! Price factors — the LIVE subset, ported from the reference
//! implementation.
//!
//! # Only four factors reach the price
//!
//! `calculatePriceFactors` returns fourteen. Under `STATIONARY_PRICE_MODEL`
//! the tick reads exactly four of them:
//!
//! | Factor | Role |
//! |---|---|
//! | `company_news` | news shock into `s` |
//! | `order_flow_impact` | the PERMANENT (information) component of flow |
//! | `short_squeeze_effect` | forced flow — squeezes and stop cascades |
//! | `random_noise` | the GARCH-scaled innovation |
//!
//! The other ten are dead on this path, and **D7 decided they are not
//! ported**: every driver they carried (economic impact, cycle drift, ERP,
//! earnings drift) now lives inside fair value, and every anchor
//! (`meanReversion`, `peMeanReversion`, `valueGrowthEffect`) is replaced by
//! the `s`-process's own reversion. Applying them here too would
//! double-count. The kill switch falls back to the reference implementation rather than to a
//! Rust legacy mode, so a Rust copy would be a second dead model.
//!
//! # Draw schedule
//!
//! **Exactly one normal, always** — the idiosyncratic noise term. It is taken
//! partway through the noise computation, BEFORE `crash_amplifier` is
//! evaluated, and that position is contractual: the tape records draws in
//! order, so a port that hoisted the draw to the top of the function would
//! produce the same count and a different stream.

use crate::mathx;

/// The components of one tick's change in `s`, in the order they are
/// reported.
///
/// Declared here, beside the factors, so the Arrow schema and the tick that
/// fills it cannot drift apart -- two hand-written orderings eventually
/// disagree and the columns would silently swap.
///
/// The first three are the model's own dynamics; the last four are the shock
/// factors. Together they account for `Δs` exactly, except where the `s` clamp
/// or a circuit breaker binds -- and a consumer can see that, because the
/// residual against `Δs` stops being zero.
/// The daily jump's slot in the ENGINE's attribution, after the seven tick
/// components. `apply_jumps` moves `mispricing_s` outside the tick loop, so
/// a decomposition of the seven alone does not reconstruct the day on any
/// preset that carries jumps (§74).
pub const JUMP_COMPONENT_KEY: &str = "jump";

/// The overnight move's slot in the ENGINE's attribution, after the jump.
/// `Engine::apply_overnight` moves `mispricing_s` at the open, before any
/// tick, so a decomposition without it would not reconstruct the first
/// tick of a day on any preset that carries the overnight process.
pub const OVERNIGHT_COMPONENT_KEY: &str = "overnight";

/// The jump's and the overnight move's slots in the engine's attribution,
/// after the tick's components, and the width of an attribution row. Every
/// array of components is sized from `COMPONENT_COUNT` rather than written
/// out, for the reason `rng::stream::COUNT` gives.
pub const JUMP_SLOT: usize = S_COMPONENT_KEYS.len();
pub const OVERNIGHT_SLOT: usize = JUMP_SLOT + 1;
pub const FAIR_VALUE_SLOT: usize = OVERNIGHT_SLOT + 1;
pub const DIVIDEND_SLOT: usize = FAIR_VALUE_SLOT + 1;
pub const COMPONENT_COUNT: usize = DIVIDEND_SLOT + 1;

/// A name's loading on its sector factor, from its beta (§108).
///
/// At slope zero the branch is not taken and the loading is exactly
/// `sector_loading`, so a preset that sets neither is bit-identical. Shared
/// by the tick and the overnight move so the two compose a name the same
/// way; the tick's arithmetic is this function's, operation for operation.
pub fn sector_loading_for(params: &crate::params::ModelParams, beta: f64) -> f64 {
    if params.sector_loading_beta_slope == 0.0 {
        params.sector_loading
    } else {
        // Tied to beta rather than to a new draw: a name that moves more
        // with the market plausibly moves more with its industry too, and
        // reusing an existing per-name attribute costs no RNG stream and
        // cannot shift the draw schedule.
        let b = beta;
        params.sector_loading * (1.0 + params.sector_loading_beta_slope * (b - 1.0))
    }
}

/// A name's idiosyncratic scale, from its beta.
///
/// The idiosyncratic scale was one number for every name in the roster:
/// cap size varies a name's noise through `cap_mult` and GARCH varies it
/// through the name's own conditional variance, but the SCALE itself did
/// not vary at all. Real rosters disperse well past that -- interquartile
/// volatility ratio 1.273..1.486 over ten reference windows against
/// pt-v12's 1.205 -- and no dial that moves every name together closes a
/// dispersion gap.
///
/// At exponent zero the branch is not taken and the scale is exactly
/// `idio_sigma_scale`, so a preset that leaves it unset is bit-identical.
/// Shared by the tick and the overnight move, as `sector_loading_for` is.
pub fn idio_scale_for(params: &crate::params::ModelParams, beta: f64) -> f64 {
    if params.idio_sigma_beta_exponent == 0.0 {
        params.idio_sigma_scale
    } else if beta <= 0.0 {
        // A non-positive beta has no exposure to raise to a power, and
        // `pow` of a negative base with a fractional exponent is NaN. The
        // homogeneous scale is the honest answer, following
        // `cap_size_multiplier_with`'s treatment of a non-positive cap.
        params.idio_sigma_scale
    } else {
        // Same choice as `sector_loading_beta_slope`: tied to beta, which
        // the universe already carries, so it costs no RNG stream and
        // cannot move the draw schedule.
        //
        // Bounded for the same reason the size effect is: a power law is
        // unbounded as its base leaves the ordinary range, and a degenerate
        // beta must not be able to silence a name or let one dominate the
        // roster's whole variance budget.
        let (lo, hi) = IDIO_BETA_BOUNDS;
        params.idio_sigma_scale
            * mathx::clamp(mathx::pow(beta, params.idio_sigma_beta_exponent), lo, hi)
    }
}

/// The two scales the down-tick reallocation applies to a name's
/// idiosyncratic shock, `(down, up)`, from `market_idio_down_suppress`.
///
/// `down` is `1 - c` and `up` is `sqrt(2 - down^2)`, so the two SQUARED
/// scales sum to 2 and average to exactly one over an even split of the
/// half-lines. That identity is the whole of the neutrality claim and it is
/// why this returns the pair rather than the up scale alone: a reader who
/// wants to check it has both numbers in one place, and
/// `the_two_scales_average_to_one_to_within_an_ulp` checks it here rather
/// than through a tick.
///
/// BOUNDED, and by the construction's own domain rather than by taste. The
/// down scale is clamped to `[0, sqrt(2)]`, which is `c` in
/// `[1 - sqrt(2), 1]`: at `c` = 1 the down tick's idiosyncratic shock is
/// silenced entirely and the up tick's is scaled by `sqrt(2)`, the extreme
/// of the reallocation, and past it `1 - c` goes negative and the transform
/// FLIPS THE SHOCK'S SIGN on a down tick, which is not a reallocation of
/// variance at all. The lower end admits the reversed arm a survey may want
/// to run as a sign check and stops where `2 - down^2` does. `max` on that
/// difference because `sqrt(2.0)` squared rounds to `2.0000000000000004`,
/// so the clamp's own endpoint would otherwise hand `sqrt` a negative
/// number and put a NaN into a price.
/// The market factor's share of a name's DAILY RETURN variance, MEASURED on
/// the composed pt-v19 at `510c65e`.
///
/// # What was measured, and how
///
/// Three seeds of the held roster (`Universe.random(40, seed=111)`), 252
/// recorded sessions after a 60-session warm-up, under a held VIX of 65 --
/// the condition the epicentre mechanism actually runs in. The numerator is
/// the day's accumulated MARKET part of `random_noise` (`noise_split`
/// "market": the factor's transmission through beta times the crash
/// amplifier, plus the tilt recentring). The denominator is the name's
/// realised daily log return, drift, news, order flow, jumps, mean
/// reversion and the overnight gap included, because that is the variance
/// [`crate::params::ModelParams::crisis_epicentre_extra`] is stated on.
/// Share per name, median over 120 name-seeds:
///
/// ```text
/// held VIX 65     0.3916      (mean 0.3946)
/// free-running    0.3225      (mean 0.3259)
/// ```
///
/// The crisis reading is the one taken, because the multiple is applied in
/// crises and nowhere else. The design note carried 0.35 from an earlier
/// reading; this is the same quantity measured on the composed vector, and
/// the two readings bracket it.
///
/// # What it is not
///
/// It is not a dial. It is a property of the composed model, and a model
/// whose factor share moved would want it re-measured rather than re-tuned
/// -- which is why the measurement is written down here beside the number
/// instead of being folded into a shipped multiple.
///
/// It is also an APPROXIMATION in one respect worth naming. The solve treats
/// everything that is not the market factor as scaled, and the code scales
/// only the sector leg and the idiosyncratic draw: news, order flow, jumps
/// and mean reversion are not scaled, and on the same measurement they are
/// `1 - 0.3916 - 0.3982 = 0.21` of the variance. So the realised extra comes
/// in UNDER the dial's nominal value, and the epicentre probe measures what
/// it actually is rather than assuming the algebra.
pub const CRISIS_EPICENTRE_MARKET_SHARE: f64 = 0.3916;

/// The EPICENTRE SECTOR's share of the roster's non-market variance,
/// MEASURED on the composed pt-v19 at `510c65e` on the registered roster.
///
/// # What was measured, and how
///
/// The same run and the same recipe as [`CRISIS_EPICENTRE_MARKET_SHARE`],
/// read off the other two parts: three seeds of the held roster
/// (`Universe.random(40, seed=111)`, the roster every registration reads),
/// 252 recorded sessions after a 60-session warm-up, under a held VIX of 65.
/// Per name the variance over days of the day's accumulated SECTOR plus
/// IDIOSYNCRATIC parts of `random_noise` (`noise_split` "sector" and
/// "idio") -- which is exactly the variance this mechanism scales -- and the
/// share is the epicentre sector's names' summed variance over the whole
/// roster's. Financial services carries the whole of the draw weight in
/// `crate::sectors::SECTORS`, so it is the sector measured:
///
/// ```text
/// held VIX 65     0.1019      (per seed 0.1019, 0.0953, 0.1030)
/// free-running    0.0883      (per seed 0.0883, 0.0845, 0.1088)
/// ```
///
/// The crisis reading is the one taken, for the reason the market share's
/// is: the multiple is applied in crises and nowhere else.
///
/// # Measured rather than computed from the sector table, and why
///
/// The other way to get this number is the roster's arithmetic: four of the
/// forty names are financials, so a count share is 0.1000. The two agree to
/// two per cent here, and the measurement is still the one taken, because
/// the agreement is a coincidence of this roster rather than an identity. A
/// name's non-market variance is `sector_loading_for(beta)^2` times a sector
/// factor sigma that is COMMON to every sector, plus its own GARCH variance
/// times `idio_scale_for(beta)^2` and `cap_size_multiplier_with(cap)^2`. So
/// the sector table's `daily_sigma` reaches the price through one of the two
/// legs and through a clamp band -- `market::garch` records that its 3.1x
/// spread arrives as about 1.4x -- while beta and cap disperse names WITHIN
/// a sector by more than the table disperses the sectors. A count-times-
/// table computation would be a different quantity that happens to land
/// nearby.
///
/// # What it is not
///
/// It is not a dial, for [`CRISIS_EPICENTRE_MARKET_SHARE`]'s reasons. It is
/// also a property of the REGISTERED ROSTER as much as of the model: a
/// roster with twice the financial weight would conserve the roster's mean
/// non-market variance only approximately under these gains. That is the
/// price of a two-number solve, and the alternative -- recomputing the share
/// from the live roster's GARCH states at every episode -- would make one
/// name's variance move every other name's gain, which is a feedback path
/// the mechanism does not need to do its job.
///
/// The limit worth knowing: at `w = 0` the pair below collapses to
/// `g_down = 1` and `g_up^2 = (e^2 - m) / (1 - m)`, which is exactly the
/// ADDITIVE form this mechanism shipped with on 2026-09-22 (measured that day
/// and refused for adding
/// variance to the roster rather than moving it). The additive arm is the
/// `w = 0` edge of the same solve and not a second mechanism.
pub const CRISIS_EPICENTRE_SECTOR_SHARE: f64 = 0.1019;

/// The two multiples an epicentre episode puts on its names' NON-MARKET
/// parts: `(g_up, g_down)`, the epicentre sector's and everyone else's.
///
/// # The two equations
///
/// [`crate::params::ModelParams::crisis_epicentre_extra`] is stated on a
/// name's TOTAL volatility and the market factor is untouched, so with `m`
/// [`CRISIS_EPICENTRE_MARKET_SHARE`] a name's total variance reads
/// `m + (1 - m) g^2` in units of the variance it would have had. The
/// epicentre REDISTRIBUTES: at a given VIX the roster's total crisis
/// variance is the VIX's to set and the epicentre only says who carries it.
/// That is two conditions, with `w` [`CRISIS_EPICENTRE_SECTOR_SHARE`]:
///
/// ```text
/// (a)  m + (1 - m) g_up^2  =  e^2 ( m + (1 - m) g_down^2 )
/// (b)  w g_up^2 + (1 - w) g_down^2  =  1
/// ```
///
/// (a) is the tape's ratio: the epicentre's names are `e` times the others
/// in total volatility, which is the row the mechanism exists to move. (b)
/// is conservation: the roster's mean non-market variance is what it was.
///
/// # The solve
///
/// Write `A = e^2 - 1`. Substituting (b) into (a) and collecting `g_down^2`:
///
/// ```text
/// g_down^2 = [ (1 - m) - m w A ] / [ (1 - m) (1 + w A) ]
/// g_up^2   = m A / (1 - m) + e^2 g_down^2
/// ```
///
/// The second line is (a) rearranged rather than (b), because it is EXACT at
/// `e = 1`: both squares are then 1.0 to the bit, so an extra of exactly one
/// is an epicentre no different from anywhere else and prices identically.
/// Reading it back through (b) is the check
/// `w g_up^2 + (1 - w) g_down^2 = w m A / (1 - m) + g_down^2 (1 + w A) = 1`.
///
/// At the DERIVED extra of 1.93, `m = 0.3916` and `w = 0.1019`:
///
/// ```text
/// A        = 3.7249 - 1      = 2.7249
/// g_down^2 = (0.6084 - 0.3916 * 0.1019 * 2.7249)
///            / (0.6084 * (1 + 0.1019 * 2.7249))
///          = 0.4996655 / 0.7773328 = 0.642795     g_down = 0.801745
/// g_up^2   = 0.3916 * 2.7249 / 0.6084 + 3.7249 * 0.642795
///          = 1.753897 + 2.394346 = 4.148243       g_up   = 2.036724
/// ```
///
/// The epicentre's names carry 2.0367 on their non-market parts where the
/// additive form carried 2.3407, and every other name carries 0.8017 where
/// the additive form carried one. Both readings of the tape's ratio are the
/// same 1.93.
///
/// # What is conserved, and what the GARCH gives back
///
/// (b) holds the variance of the INNOVATION -- the sector leg and the
/// idiosyncratic draw, the two things this multiplies -- and it holds it
/// exactly: the tick's non-market parts come out `g_up` and `g_down` times
/// what they would have been, to the bit, and a roster whose epicentre share
/// is `w` reads the same mean non-market variance either way.
///
/// It does NOT hold the REALISED variance of a long run, because the per-name
/// GARCH is convex in the innovation it is fed: `h` mean-reverts to a level
/// built from a fixed `garch_omega`, so multiplying a name's innovation by
/// `g > 1` raises its stationary variance by more than `g^2` while `g < 1`
/// lowers it by less. MEASURED on the registered roster, three seeds, 252
/// sessions under a held VIX of 65 with financials pinned -- a crisis that
/// never ends, which is the worst case this can be put in -- the roster's
/// realised mean non-market variance comes in 1.21 to 1.31 times the base
/// arm's where the innovation-level prediction is 0.98 to 1.01, and the
/// roster's pooled return volatility 1.03 to 1.06 times. Over a free-running
/// panel, where episodes are a minority of sessions, that arrives as
/// `annualised_vol_pct` 24.35 to 24.77 at two years against the additive
/// form's 25.60 (16 seeds; the paired per-seed move is +0.37 against +1.19).
///
/// The number this leaves on the table is not taken back by moving `w`.
/// Solving (b) against a `w` chosen to land a graded row would be fitting
/// the mechanism to the panel it is measured on, and `w` is a measurement.
/// What would take it back is conserving on the GARCH's stationary variance
/// rather than on the innovation, which is a different and larger mechanism
/// than a pair of multiples.
///
/// # The domain
///
/// Both squares are floored at zero under the square root, and
/// `ModelParams::invariants` refuses the extras that would reach the floor,
/// so the floor is for a caller who built params without going through the
/// check rather than for a supported value. The endpoints are
/// [`crisis_epicentre_extra_bounds`].
pub fn crisis_epicentre_gains(extra: f64) -> (f64, f64) {
    let (up2, down2) = crisis_epicentre_gain_squares(extra);
    (
        mathx::sqrt(mathx::max(0.0, up2)),
        mathx::sqrt(mathx::max(0.0, down2)),
    )
}

/// The solve itself, `(g_up^2, g_down^2)`, UNFLOORED so the invariant can
/// see a negative square rather than a zero that reads like a silenced name.
pub fn crisis_epicentre_gain_squares(extra: f64) -> (f64, f64) {
    let e2 = extra * extra;
    let m = CRISIS_EPICENTRE_MARKET_SHARE;
    let w = CRISIS_EPICENTRE_SECTOR_SHARE;
    let a = e2 - 1.0;
    let down2 = ((1.0 - m) - m * w * a) / ((1.0 - m) * (1.0 + w * a));
    let up2 = m * a / (1.0 - m) + e2 * down2;
    (up2, down2)
}

/// The open interval of extras the redistributing solve has an answer in,
/// `(lo, hi)`, both ENDPOINTS EXCLUDED.
///
/// Below `lo` the epicentre is so much quieter than the rest of the roster
/// that its own non-market variance would have to be negative; above `hi` it
/// is so much louder that, with the roster's mean held, everyone else's
/// would have to be. At `m = 0.3916` and `w = 0.1019`:
///
/// ```text
/// lo = sqrt( m (1 - w) / (1 - m w) )      = 0.605238
/// hi = sqrt( 1 + (1 - m) / (m w) )        = 4.030704
/// ```
///
/// `lo` is where the additive form's `sqrt(m) = 0.6258` went: conserving
/// moves it down a little, because the rest of the roster is lifted to make
/// room. `hi` is new and is the whole of what conservation costs at the top
/// -- it sits above `atlas_survey`'s box for the dial (0.0 to 3.0) and well
/// above the largest epicentre the tape has (2.43 in 2008-09), so nothing
/// the record asks for is out of reach.
pub fn crisis_epicentre_extra_bounds() -> (f64, f64) {
    let m = CRISIS_EPICENTRE_MARKET_SHARE;
    let w = CRISIS_EPICENTRE_SECTOR_SHARE;
    (
        mathx::sqrt(m * (1.0 - w) / (1.0 - m * w)),
        mathx::sqrt(1.0 + (1.0 - m) / (m * w)),
    )
}

pub fn idio_suppress_scales(suppress: f64) -> (f64, f64) {
    let down = mathx::clamp(1.0 - suppress, 0.0, mathx::sqrt(2.0));
    (down, mathx::sqrt(mathx::max(2.0 - down * down, 0.0)))
}

pub const S_COMPONENT_KEYS: [&str; 8] = [
    "reversion",
    "momentum",
    "crowd_lean",
    "company_news",
    "order_flow_impact",
    "short_squeeze_effect",
    "random_noise",
    // The session circuit breaker's own correction. When the model price
    // leaves the band the tick re-derives `s` from the clamped price, and
    // until 2026-08-26 that rewrite was booked to nobody: on any day the
    // breaker bound, the columns did not reconstruct the move. Measured on
    // one crisis window before the fix, the seven summed to -0.204 against a
    // change of -0.190 (§79).
    "circuit_breaker",
];

/// The fair-value shift's name: minus the part of a move's shocks that went
/// to the name's fair value for good instead of its mispricing, under
/// `fair_value_news_share` and `fair_value_market_share` (pt-v20). The other
/// factors report the whole shock, which is what moved the PRICE; this one
/// takes the permanent part back out of `s`, so every factor together sums
/// to the change in `mispricing_s`, and every factor but this one to the
/// change in `s` plus the fair-value level, the price's own move at a fixed
/// valuation. Exactly zero on every preset through pt-v19. The last factor,
/// so every earlier one keeps its position.
pub const FAIR_VALUE_COMPONENT_KEY: &str = "fair_value_shift";

/// The ex-date's slot in the ENGINE's attribution, after the fair-value
/// shift: the change in `s` when a name goes ex at the open and `s` is
/// re-read against the fair value without the accrued dividend
/// (`dividend_payout_share`). The price itself drops by the amount; this is
/// only what that did to the mispricing, so every slot together still sums
/// to the change in `s`. Exactly zero on every preset.
pub const DIVIDEND_COMPONENT_KEY: &str = "dividend";

/// The tick's own rows: the eight `S_COMPONENT_KEYS`, then the tick's
/// fair-value shift at [`TICK_FAIR_VALUE`].
pub const TICK_COMPONENT_COUNT: usize = S_COMPONENT_KEYS.len() + 1;

/// The fair-value shift's index in a tick row.
pub const TICK_FAIR_VALUE: usize = S_COMPONENT_KEYS.len();

/// The attribution slot a tick row's index `k` accumulates into.
pub const fn attribution_slot_for_tick(k: usize) -> usize {
    if k == TICK_FAIR_VALUE { FAIR_VALUE_SLOT } else { k }
}

/// Total impact coefficient for order flow, before the informed fraction.
pub const ORDER_FLOW_COEFFICIENT: f64 = 50.0;

/// The daily volume `order_flow_depth_law` restates the coefficient at.
///
/// It is the volume `order_imbalance` already assumes for a name that
/// reports none (its `truthy_or` fallback), and
/// `the_reference_liquidity_is_the_fallback_the_participation_term_uses`
/// reads it back out of that function so the two cannot drift apart. A name
/// trading this much is charged the same under either depth law.
pub const REFERENCE_DAILY_VOLUME: f64 = 1_000_000.0;

/// Weight of a sector-scoped news event on a name in that sector.
///
/// A §5.4 promotion: previously the inline `* 0.5` below. Named so the
/// preset can carry it and a recalibration cannot leave an unnamed copy
/// behind (the finding-14 lesson).
pub const NEWS_SECTOR_WEIGHT: f64 = 0.5;

/// Weight of a market-wide news event on every name. A §5.4 promotion.
pub const NEWS_MARKET_WEIGHT: f64 = 0.3;

/// Market-shock magnitude, in BASELINE factor sigmas, above which the crash
/// amplifier fires. A §5.4 promotion of the inline `2.0`.
pub const CRASH_AMPLIFIER_THRESHOLD: f64 = 2.0;

/// Extra market loading per baseline sigma beyond the threshold. A §5.4
/// promotion of the inline `0.2`.
pub const CRASH_AMPLIFIER_SLOPE: f64 = 0.2;

/// The share of order-flow impact that is PERMANENT.
///
/// The coefficient above was calibrated to represent both the temporary and
/// permanent components, because at the time there was no book and the factor
/// model was the only place impact could live. Order flow now moves the price
/// physically — orders walk real depth and leave the maker skewed — so
/// leaving the full coefficient here would charge flow twice.
///
/// This is a change of ROLE, not a retune. Published permanent/total
/// decompositions land roughly in 0.3–0.5; this sits at the conservative end
/// and is the one number here that still wants empirical calibration.
pub const INFORMED_FLOW_FRACTION: f64 = 0.35;

/// Shared factors, drawn once per tick and reused by every company.
///
/// This is what makes stocks CORRELATED rather than independently random: a
/// single market draw reaches every name through its beta, and a sector draw
/// reaches everything in that sector. Without it a 108-name index would have
/// almost no aggregate volatility, because independent noise cancels.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct SharedFactors {
    pub market_factor: f64,
    /// Indexed by the same sector key order the tick draws them in.
    pub sector_factors: Vec<(String, f64)>,
    /// The crisis correlation blend weight this tick, 0.0 below the crisis
    /// threshold. Read only when `crisis_blend_source` is nonzero.
    pub crisis_spike: f64,
    /// Yesterday's session closed with a down market factor. Read only by
    /// the lagged transmission wire (`market_beta_down_asym_lag`).
    pub prev_day_down: bool,
    /// The CONDITIONAL per-tick sigma `market_factor` was drawn with, which
    /// is `market_sigma_daily / sqrt(390)` and not
    /// `params.market_factor_sigma`. Carried rather than recomputed
    /// because the two differ by the whole of the factor's variance
    /// process, and the one quantity that can recentre the downside tilt
    /// exactly is the sigma the draw actually used. Read by
    /// `market_beta_down_asym_recentre`, and — since the crash amplifier
    /// gained a normaliser switch — by `crash_amplifier_conditional_sigma`
    /// as well, which is the same quantity for the same reason.
    pub market_sigma_tick: f64,
    /// The sector at the epicentre of the crisis episode this session is
    /// inside, if there is one.
    ///
    /// `None` in three cases that mean different things and read the same
    /// here on purpose: the dial
    /// [`crate::params::ModelParams::crisis_epicentre_extra`] is 0.0, which
    /// is every preset before pt-v19; no episode is running; or the episode
    /// drew `none` as its epicentre, which is two of the tape's five
    /// episodes and is a DRAW rather than the absence of one. In all three
    /// the tick does exactly what it did before this field existed. This
    /// read "`None` on every shipped preset" until 2026-09-24; pt-v19 ships
    /// the dial at 1.93.
    pub crisis_epicentre: Option<String>,
}

impl SharedFactors {
    fn sector(&self, sector: &str) -> f64 {
        // `sharedFactors.sectorFactors[company.sector] ?? 0` — an absent
        // sector is zero, not a panic.
        self.sector_factors
            .iter()
            .find(|(k, _)| k == sector)
            .map(|(_, v)| *v)
            .unwrap_or(0.0)
    }
}

/// A news event, as the factor model reads it.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct NewsEvent {
    pub company_id: Option<String>,
    pub sector: Option<String>,
    /// `event.impact.priceImpact || 0` — TRUTHY-or, so a zero or NaN impact
    /// contributes nothing.
    pub price_impact: Option<f64>,
}

/// Regular-session minutes, the ticks an endogenous news event is absorbed
/// over.
pub const NEWS_SESSION_TICKS: f64 = 390.0;

/// One component of the absorption profile: the share of its part of the
/// move priced after `n` ticks, 0 at the open and exactly 1 after tick 390.
///
/// Half-life 0.0 is the straight line `n / 390`, the spread every preset
/// ships. Above zero it is `1 - 2^(-n/h)`, rescaled so the component is
/// complete at the close whatever the half-life: the profile moves WHEN the
/// move lands, never how much of it lands.
fn absorbed_component(n: f64, half_life: f64) -> f64 {
    absorbed_component_over(n, half_life, NEWS_SESSION_TICKS)
}

/// [`absorbed_component`] over `horizon` ticks rather than the session's
/// 390: 0 at its start and exactly 1 after `horizon`. An event released
/// during the session (`news_session_release_share`) is absorbed over what
/// is left of the session, so it too is complete at the close. At a horizon
/// of 390 it is the same operations in the same order.
fn absorbed_component_over(n: f64, half_life: f64, horizon: f64) -> f64 {
    if n <= 0.0 {
        return 0.0;
    }
    if n >= horizon {
        return 1.0;
    }
    if half_life == 0.0 {
        return n / horizon;
    }
    let ln2 = core::f64::consts::LN_2;
    let at = 1.0 - mathx::exp(-ln2 * n / half_life);
    let full = 1.0 - mathx::exp(-ln2 * horizon / half_life);
    at / full
}

/// The share of an endogenous news event's `price_impact` priced after `n`
/// ticks of its session, under `news_absorption_half_life` and its two
/// companions. See [`crate::params::ModelParams::news_absorption_half_life`]
/// for the evidence each number is set from.
///
/// `(1 - d) * fast(n) + d * drift(n)`: a fast component at
/// `news_absorption_half_life` and a post-news drift, share
/// `d = news_absorption_drift_share`, at
/// `news_absorption_drift_half_life`. Each is complete at the close, so the
/// whole is too.
pub fn news_absorbed_share(params: &crate::params::ModelParams, n: f64) -> f64 {
    let fast = absorbed_component(n, params.news_absorption_half_life);
    let d = params.news_absorption_drift_share;
    if d == 0.0 {
        return fast;
    }
    let drift = absorbed_component(n, params.news_absorption_drift_half_life);
    (1.0 - d) * fast + d * drift
}

/// The multiple of `price_impact / 390` the tick at `minutes_since_open`
/// applies for each endogenous news event: `390 * (A(m + 1) - A(m))`, with
/// `A` [`news_absorbed_share`]. A full session's weights sum to 390 up to
/// rounding, as the shipped constant 1.0 per tick does.
///
/// Outside the regular session (pre-market, after-hours) it is 0.0: the
/// profile is keyed on the minute of the session, and a tick off it
/// prices none of the move. Only read with `news_absorption_half_life` off
/// zero; the shipped path never calls it.
pub fn news_absorption_weight(params: &crate::params::ModelParams,
                              minutes_since_open: i64) -> f64 {
    if !(0..390).contains(&minutes_since_open) {
        return 0.0;
    }
    let m = minutes_since_open as f64;
    NEWS_SESSION_TICKS
        * (news_absorbed_share(params, m + 1.0) - news_absorbed_share(params, m))
}

/// When the session's company news is released, as it is on the tape: the
/// EDGAR acceptance times of the certified forty's 8-Ks without item 2.02
/// (results of operations), 2014-2025, accepted between 09:30 and 16:00 New
/// York on a full trading day, counted by half hour of the session. 1,372
/// filings. 0.6% of them land in the first minute and 4.7% in the first half
/// hour; the mean is minute 223. Read by `news_session_release_share`.
pub const NEWS_RELEASE_PROFILE_COUNTS: [f64; 13] =
    [65.0, 103.0, 85.0, 93.0, 65.0, 79.0, 71.0, 96.0, 110.0, 129.0, 125.0, 235.0, 116.0];

/// The session minute, in [0, 390), at which an event whose release uniform
/// is `v` in [0, 1) is released under [`NEWS_RELEASE_PROFILE_COUNTS`]: the
/// profile's inverse, linear within each half hour.
pub fn news_release_minute(v: f64) -> f64 {
    let total: f64 = NEWS_RELEASE_PROFILE_COUNTS.iter().sum();
    let width = NEWS_SESSION_TICKS / NEWS_RELEASE_PROFILE_COUNTS.len() as f64;
    let target = v.clamp(0.0, 1.0) * total;
    let mut below = 0.0;
    for (k, c) in NEWS_RELEASE_PROFILE_COUNTS.iter().enumerate() {
        if target < below + c {
            return (k as f64 + (target - below) / c) * width;
        }
        below += c;
    }
    NEWS_SESSION_TICKS - 1e-9
}

/// The multiple of `price_impact / 390` the tick at `minutes_since_open`
/// applies for an endogenous news event released at session minute
/// `release` (`news_session_release_share`): `390 * (A(m + 1 - r) - A(m -
/// r))`, with `A` [`news_absorbed_share`] over the `390 - r` minutes left, so
/// the event prices nothing before its release and all of it by the close.
/// A release at 0.0 is [`news_absorption_weight`]'s profile. Off the regular
/// session it is 0.0.
pub fn news_release_weight(params: &crate::params::ModelParams,
                           minutes_since_open: i64, release: f64) -> f64 {
    if !(0..390).contains(&minutes_since_open) {
        return 0.0;
    }
    let m = minutes_since_open as f64;
    let horizon = NEWS_SESSION_TICKS - release;
    let share = |n: f64| {
        let fast = absorbed_component_over(n, params.news_absorption_half_life, horizon);
        let d = params.news_absorption_drift_share;
        if d == 0.0 {
            return fast;
        }
        let drift = absorbed_component_over(n, params.news_absorption_drift_half_life, horizon);
        (1.0 - d) * fast + d * drift
    };
    NEWS_SESSION_TICKS * (share(m + 1.0 - release) - share(m - release))
}

/// The company fields the live factor subset reads.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct FactorCompany {
    pub id: String,
    pub sector: String,
    pub beta: Option<f64>,
    pub market_cap: f64,
    pub avg_volume: f64,
    pub shares_outstanding: f64,
    pub short_interest: f64,
    pub float: f64,
    pub garch_variance: f64,
    /// The previous COMPLETED day's return, refreshed once at each close.
    pub last_daily_return: Option<f64>,
}

impl FactorCompany {
    /// A name with every number zero and every optional figure absent.
    /// Set the fields the factor model should read on the value.
    pub fn new(id: impl Into<String>, sector: impl Into<String>) -> Self {
        FactorCompany {
            id: id.into(),
            sector: sector.into(),
            beta: None,
            market_cap: 0.0,
            avg_volume: 0.0,
            shares_outstanding: 0.0,
            short_interest: 0.0,
            float: 0.0,
            garch_variance: 0.0,
            last_daily_return: None,
        }
    }
}

/// The four live factors.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct LiveFactors {
    pub company_news: f64,
    /// The part of `company_news` from MARKET-WIDE events (no company, no
    /// sector), as against the company's own news, a peer's or its
    /// sector's. A copy of the last branch's sum, written beside it, so
    /// nothing on the price path is re-associated; read only when
    /// [`crate::params::ModelParams::fair_value_news_share`] is non-zero.
    pub company_news_market: f64,
    pub order_flow_impact: f64,
    pub short_squeeze_effect: f64,
    pub random_noise: f64,
    /// `random_noise` split into the three draws it is the sum of. The sum
    /// above is still the statement that moves `s`; these are written after
    /// it as a copy of its parts, so no arithmetic on the price path is
    /// re-associated and every preset is bit-identical.
    ///
    /// The attribution's `random_noise` column is what the close feeds the
    /// per-name GJR as the day's innovation, and the column alone cannot
    /// say how much of that innovation is the name's OWN variance rather
    /// than the factor's and the sector's. Only the split says it, which is
    /// why the split exists: reported through `Engine::noise_part_column`,
    /// and read on the price path only when
    /// [`crate::params::ModelParams::garch_innovation_commensurate`] is
    /// non-zero.
    pub noise_market: f64,
    /// The name's plain loading on the tick's market draw, `beta * F`: the
    /// part of `noise_market` before the down-tick tilt, the lagged wire,
    /// the crisis injection, the crash amplifier and the recentring. Zero
    /// mean by construction. Read only under
    /// [`crate::params::ModelParams::fair_value_market_linear`].
    pub noise_market_linear: f64,
    pub noise_sector: f64,
    pub noise_idio: f64,
    /// The scale the idiosyncratic draw above was taken at, with the name's
    /// own daily sigma DIVIDED OUT: `idio_scale / sqrt(390) * cap_mult *
    /// volatility_multiplier` times the down-tick reallocation's scale.
    ///
    /// `noise_idio` is `z * sqrt(max(h, idio_sigma_floor))` times this, so
    /// squaring it and summing over the day gives `kappa^2`, the factor by
    /// which the day's own-noise variance differs from the `h` the
    /// recursion carries. The close needs it to put the innovation back in
    /// the units the GJR coefficients were fitted in; see
    /// [`crate::params::ModelParams::garch_innovation_commensurate`].
    pub noise_idio_unit: f64,
}

/// Reference capitalisation, in billions, where the continuous size effect
/// equals exactly 1.0. Chosen as the step function's third tier so the
/// smooth curve pivots where the discrete one already read 1.0.
pub const SIZE_EFFECT_REFERENCE_B: f64 = 25.0;

/// Bounds on the beta-driven idiosyncratic-volatility multiplier.
///
/// Wide enough not to bind on an ordinary roster -- the certified forty span
/// beta 0.384 to 1.580, which at exponent 2 gives 0.15 to 2.50 -- and there
/// only so that a degenerate beta cannot silence a name or hand one name the
/// roster's entire variance budget.
pub const IDIO_BETA_BOUNDS: (f64, f64) = (0.1, 4.0);

/// Bounds on the continuous size multiplier.
///
/// Wider than the step function's own [0.8, 1.6] on purpose -- the extra
/// spread at the tails is the dispersion this mechanism exists to add --
/// but bounded, because the power law is unbounded as capitalisation goes
/// to zero and a degenerate cap would otherwise produce unbounded
/// idiosyncratic volatility.
pub const SIZE_EFFECT_BOUNDS: (f64, f64) = (0.5, 3.0);

/// Small-cap size multiplier, applied to the idiosyncratic component only.
///
/// # The step function is an artifact, and this is how it gets removed
///
/// Four discrete tiers mean a $49B company gets 1.0 and a $51B company gets
/// 0.8: a 25% jump in idiosyncratic volatility from a $2B difference in
/// size. Every name in the roster lands on exactly one of four volatility
/// levels, which puts cliffs in the cross-section that no real market has
/// and compresses the dispersion of volatility across names into four
/// spikes.
///
/// `size_effect_smoothness` blends toward a continuous power law in size,
/// which is what the size effect empirically IS. At an exponent of 0.15 the
/// curve reproduces the step function's own tier values closely where the
/// steps are informative -- 5B reads 1.273 against 1.3, 25B reads 1.000
/// against 1.0, 100B reads 0.812 against 0.8 -- and departs below $1B,
/// where the step function stops being a size effect and becomes a floor.
/// That departure is the point: a $100M company and a $900M company are not
/// equally volatile, and the steps said they were.
///
/// At smoothness 0.0 this returns the step value by BRANCH, so every preset
/// before pt-v4 is bit-identical and owes nothing to an argument about how
/// a blend of `x` and `x` behaves.
pub fn cap_size_multiplier_with(params: &crate::params::ModelParams,
                                market_cap: f64) -> f64 {
    let stepped = cap_size_multiplier(market_cap);
    let s = params.size_effect_smoothness;
    if s == 0.0 {
        return stepped;
    }
    let mcap_billions = market_cap / 1e9;
    // A non-positive cap has no size to speak of; the step function's floor
    // is the honest answer rather than a power law of zero.
    if mcap_billions <= 0.0 {
        return stepped;
    }
    let ratio = mcap_billions / SIZE_EFFECT_REFERENCE_B;
    let (lo, hi) = SIZE_EFFECT_BOUNDS;
    let smooth = mathx::clamp(
        mathx::pow(ratio, -params.size_effect_exponent), lo, hi);
    (1.0 - s) * stepped + s * smooth
}

/// The original four-tier step. Kept as the shipped behaviour and as the
/// thing `size_effect_smoothness` blends away from.
pub fn cap_size_multiplier(market_cap: f64) -> f64 {
    let mcap_billions = market_cap / 1e9;
    if mcap_billions > 50.0 {
        0.8
    } else if mcap_billions > 10.0 {
        1.0
    } else if mcap_billions > 1.0 {
        1.3
    } else {
        1.6
    }
}

/// The news one name takes from a set of events, as `(company_news,
/// company_news_market)`: an event naming it at full weight, a sector peer's
/// at the transfer weight, a sector-wide one at `news_sector_weight` and a
/// market-wide one at `news_market_weight` (the second figure is that last
/// part alone). The tick's composition ([`calculate_live_factors`]), and the
/// open's for the news released before it (`news_preopen_share`).
pub fn news_terms(
    id: &str,
    sector: &str,
    news: &[NewsEvent],
    crisis_spike: f64,
    params: &crate::params::ModelParams,
) -> (f64, f64) {
    let mut company_news = 0.0;
    let mut company_news_market = 0.0;
    for event in news {
        let impact = truthy(event.price_impact);
        if event.company_id.as_deref() == Some(id) {
            company_news += impact;
        } else if event.company_id.is_some()
            && event.sector.as_deref() == Some(sector)
        {
            // Information transfer: a surprise at a PEER, not at this name.
            // Before this branch existed the chain fell straight through
            // here — the sector branch below requires `company_id.is_none()`
            // — so an earnings beat at one cloud name moved no other cloud
            // name. Sector co-movement was entirely exogenous: a per-tick
            // sector factor draw and market beta, never contagion from a
            // member.
            //
            // Asymmetric by construction, because the effect is: bad news
            // transfers more strongly than good. The weight is read by the
            // SIGN OF THE ANNOUNCER'S IMPACT, not of anything local.
            let base = if impact < 0.0 {
                params.news_peer_weight_down
            } else {
                params.news_peer_weight
            };
            // Contagion that knows what regime it is in (§104, §105). A
            // CONSTANT peer weight transfers as hard in a quiet July as in
            // March 2020, and measuring that is what killed the first
            // attempt to use news: calm-market sector excess is already in
            // band at +0.166 against a 0.11-to-0.22 ceiling, and constant
            // transfer pushed it to +0.256 at both horizons while raising
            // the crisis figure that was actually wanted.
            //
            // `crisis_spike` is ZERO below `crisis_vix_threshold`, so at any
            // coupling a calm market is untouched and only the crisis moves.
            // At coupling zero the branch is not taken at all, so every
            // preset is bit-identical.
            let weight = if params.news_peer_vix_coupling == 0.0 {
                base
            } else {
                base * (1.0 + params.news_peer_vix_coupling * crisis_spike)
            };
            // Guarded rather than multiplied through: at zero weight this
            // adds nothing at all, so the accumulator is untouched and the
            // branch is bit-identical to not existing. `+ 0.0` would not be
            // — it turns a -0.0 accumulator into +0.0.
            if weight != 0.0 {
                company_news += impact * weight;
            }
        } else if event.sector.as_deref() == Some(sector)
            && event.company_id.is_none()
        {
            company_news += impact * params.news_sector_weight;
        } else if event.company_id.is_none() && event.sector.is_none() {
            company_news += impact * params.news_market_weight;
            company_news_market += impact * params.news_market_weight;
        }
    }
    (company_news, company_news_market)
}

/// Compute the live factor subset.
///
/// `shared_factors` is required rather than optional. The fallback branch in
/// the original exists for callers that predate shared factors, and the live
/// tick is not one of them — it always supplies them. Both branches take one
/// normal draw, so this narrowing cannot change the draw COUNT; it removes a
/// path the live model never takes.
///
/// `params` carries the coefficients that used to be read as consts here
/// (the runtime seam). Passing
/// [`crate::params::PT_V1`] reproduces the const build bit for bit: same
/// values, same operations, same order.
pub fn calculate_live_factors(
    company: &FactorCompany,
    news: &[NewsEvent],
    order_imbalance: f64,
    volatility_multiplier: f64,
    shared: &SharedFactors,
    params: &crate::params::ModelParams,
    rng: &mut impl crate::rng::Rng,
) -> LiveFactors {
    // ── News ──────────────────────────────────────────────────────────────
    // Company-specific at full weight, a sector PEER's news at the transfer
    // weight, sector-wide at half, market-wide at 0.3. The branches are
    // exclusive and ORDERED, and the order carries the meaning: an event
    // naming this company counts once, as company news, whatever sector it
    // also carries. The same event reaches OTHER names in that sector
    // through the peer arm, which is off in every shipped preset — so
    // before pt-v4 an event with a companyId moved exactly one name.
    let (company_news, company_news_market) = news_terms(
        company.id.as_str(), company.sector.as_str(), news, shared.crisis_spike, params);

    // ── Order flow ────────────────────────────────────────────────────────
    // `order_imbalance` is already participation: flow over this name's
    // minute volume. Under `order_flow_depth_law` at 0.0 the depth is
    // divided out a second time here, so impact falls as depth at equal
    // participation; at 1.0 it is divided by the reference name's minute
    // volume instead, which restates the coefficient without retuning it.
    // A branch, so 0.0 is the arithmetic that stood, bit for bit.
    let liquidity_factor = if params.order_flow_depth_law == 0.0 {
        // NOTE this is `Math.max`, not the `||` fallback chain
        // `microstructure::base_quote_size` uses on the same field. A zero
        // `avg_volume` is KEPT here and compared, rather than falling
        // through.
        let avg_daily_volume =
            mathx::max(company.avg_volume, company.shares_outstanding * 0.005);
        // Per-minute volume, floored so a thin name cannot produce
        // unbounded impact.
        1.0 / mathx::max(avg_daily_volume / 390.0, 100.0)
    } else {
        1.0 / (REFERENCE_DAILY_VOLUME / 390.0)
    };
    let order_flow_impact = order_imbalance
        * liquidity_factor
        * params.order_flow_coefficient
        * params.informed_flow_fraction;

    // ── Noise ─────────────────────────────────────────────────────────────
    let beta = company.beta.unwrap_or(1.0);
    let cap_mult = cap_size_multiplier_with(params, company.market_cap);

    // With `crisis_blend_source` at 1.0 the crisis blend no longer rides the
    // sector slot: the market injection every name used to receive through
    // it (0.5 times the spike times the factor) is added here instead, and
    // the sector draw arrives intact. A branch, not arithmetic, so 0.0 is
    // bit-identical.
    // Downside transmission asymmetry (§round 102). Real correlation rises
    // in falling markets because names co-move harder on the way down --
    // exceedance correlation, the direct mechanism corr_asymmetry measures.
    // On a down tick of the factor the transmission is scaled by
    // (1 + market_beta_down_asym); up ticks are untouched. At 0.0 neither
    // branch below multiplies, so every shipped preset is bit-identical.
    let factor_through = if params.market_beta_down_asym == 0.0
        || shared.market_factor >= 0.0
    {
        beta * shared.market_factor
    } else {
        beta * shared.market_factor * (1.0 + params.market_beta_down_asym)
    };
    // The LAGGED wire (block 1201's signature, round 110's interim): on the
    // session AFTER a down day, transmission is boosted regardless of the
    // tick's own sign -- down moves continue into the next day. A branch,
    // so 0.0 is bit-identical.
    let factor_through = if params.market_beta_down_asym_lag == 0.0
        || !shared.prev_day_down
    {
        factor_through
    } else {
        factor_through * (1.0 + params.market_beta_down_asym_lag)
    };
    let market_component = if params.crisis_blend_source == 0.0 {
        factor_through
    } else {
        // At a held VIX the crisis spike is pinned at `crisis_blend_cap`, so
        // the only thing varying block to block in this injection is
        // `market_factor`'s magnitude -- the market variance level, which
        // GARCH persistence governs. That is why crisis co-movement's
        // across-block RANGE tracks persistence at rho +0.85 and why
        // tightening the range has always cost 504-day panel blocks.
        //
        // `crisis_blend_variance_damp` breaks that link: at `d` the
        // injection is scaled by |market_factor / baseline|^-d, so at 1.0 its
        // magnitude stops depending on how large the factor happens to be.
        // At 0.0 the branch is not taken and the tape is bit-identical.
        let injection = params.crisis_blend_source * params.crisis_blend_gain
            * shared.crisis_spike * shared.market_factor;
        let injection = if params.crisis_blend_variance_damp == 0.0 {
            injection
        } else {
            // The same normaliser `crash_amplifier` uses below, so
            // "ordinary" means one thing in both places. Guarded at both
            // ends: a near-zero factor would otherwise send the scale to
            // infinity, and the cap keeps a quiet tick from being amplified
            // into a loud one.
            let base = params.market_factor_sigma / mathx::sqrt(390.0);
            let rel = mathx::max(shared.market_factor.abs() / base, 1e-6);
            injection * mathx::clamp(
                mathx::pow(rel, -params.crisis_blend_variance_damp), 0.1, 10.0)
        };
        factor_through + injection
    };
    // The sector loading (§108). It was the literal 0.5 for every member of
    // every sector: a name's exposure to its own industry was the one
    // systematic loading the model did not let vary, where its exposure to
    // the MARKET varies by beta two lines above.
    //
    // The loading and the scale are `sector_loading_for` and
    // `idio_scale_for`, shared with the overnight move so the two compose
    // a name the same way; each is the arithmetic that stood here.
    let sector_loading = sector_loading_for(params, beta);
    let sector_component = sector_loading * shared.sector(&company.sector);

    // THE CRISIS EPICENTRE. While an episode with an epicentre is running,
    // EVERY name's non-market parts carry a multiple: this sector leg and
    // the idiosyncratic draw below. The epicentre sector's names carry
    // `g_up`, above one, and every other name carries `g_down`, below it, so
    // the mechanism REDISTRIBUTES the roster's crisis variance rather than
    // adding to it -- at a given VIX the total is the VIX's to set and the
    // epicentre only says who carries it. The market component is untouched
    // either way, which is the other half of the point: the index, the VIX
    // and the fear rows do not move, only who carries the crisis does.
    // `crisis_epicentre_gains` is where the pair is solved.
    //
    // `Some` only while `crisis_epicentre_extra` is non-zero AND an episode
    // is running AND that episode drew a sector rather than `none`. `None`
    // otherwise, and `None` is not a multiply by one: the branches below
    // leave the arithmetic exactly as it was written before this existed, so
    // every preset is bit-identical rather than multiplied by a pair of
    // ones.
    let epicentre_gain: Option<f64> = match shared.crisis_epicentre.as_deref() {
        Some(key) => {
            let (up, down) = crisis_epicentre_gains(params.crisis_epicentre_extra);
            Some(if key == company.sector.as_str() { up } else { down })
        }
        None => None,
    };
    let sector_component = match epicentre_gain {
        None => sector_component,
        Some(g) => sector_component * g,
    };

    // `garchVariance` is in DAILY units; the tick needs per-tick sigma.
    // `IDIO_SIGMA_SCALE` is the funding side of the market-factor variance
    // reallocation: the factor's variance share was raised out of THIS
    // term's budget, so total volatility holds still. At 1.0 the multiply
    // is bit-inert.
    // THE ABSOLUTE FLOOR, and why it is a parameter now. This 1e-4 was a
    // dead-stock guard: "a zero variance would make sigma zero and the
    // price would stop moving entirely". Against a recursion whose own
    // level is about 6.3e-5 it is not a guard, it is the law -- it binds on
    // 61 to 90 per cent of name-days in nine of the twelve sectors, and it
    // is what makes a utility and a bank carry the same idiosyncratic
    // sigma. The job it was written for is already done, per sector rather
    // than absolutely, by the `[0.25, 5.0] x sector_base_variance` clamp in
    // `garch::update_garch_variance_for`, which cannot return zero for a
    // positive base. So this REMOVES a constant rather than adding one:
    // shipping at 1e-4 leaves every existing preset bit-identical, and a
    // preset that sets it to 0.0 has one fewer number in it.
    let daily_sigma = mathx::sqrt(mathx::max(company.garch_variance, params.idio_sigma_floor));
    let idio_scale = idio_scale_for(params, beta);
    let idiosyncratic_sigma = daily_sigma * idio_scale / mathx::sqrt(390.0);

    // DRAW SITE — here, before `crash_amplifier` is computed. The order is
    // contractual for the tape even though the two are independent.
    let idiosyncratic_noise =
        rng.next_normal() * idiosyncratic_sigma * cap_mult * volatility_multiplier;

    // The variance-neutral down-tick REALLOCATION.
    // The tilt two blocks above is the same-day correlation wire and it
    // multiplies: it buys share by adding variance, and the added variance
    // is what makes its argmin on the nineteen the value it already ships.
    // This buys the same share by MOVING it. The market leg is untouched
    // and the idiosyncratic leg is suppressed by `(1 - c)` on a down tick
    // and inflated by `sqrt(2 - (1 - c)^2)` on an up tick, so the two
    // squared scales average to exactly one over an even split and no
    // moment moves — see `ModelParams::market_idio_down_suppress` for the
    // algebra, for what the `>= 0.0` boundary costs at a degenerate zero
    // factor, and for why no recentring dial stands beside this one.
    //
    // AFTER the draw, deliberately and not incidentally: this reshapes a
    // shock the tick has already taken, so no branch here can move the
    // count or the order. At 0.0 neither multiply happens, so every preset
    // that predates the dial is bit-identical rather than multiplied by a
    // pair of ones.
    //
    // The scale is named before it is applied so the close can read the
    // scale the draw ACTUALLY took without a second copy of this branch
    // drifting from it. At 0.0 the scale is exactly 1.0 and the branch
    // below returns the draw untouched, so no multiply by one happens on
    // any preset that predates the dial.
    let idio_down_suppress_scale = if params.market_idio_down_suppress == 0.0 {
        1.0
    } else {
        let (down, up) = idio_suppress_scales(params.market_idio_down_suppress);
        // `< 0.0`, the convention the tilt above already uses, so an exactly
        // zero factor is an up tick on both wires and the two cannot
        // disagree about what a down tick is.
        if shared.market_factor < 0.0 {
            down
        } else {
            up
        }
    };
    let idiosyncratic_noise = if params.market_idio_down_suppress == 0.0 {
        idiosyncratic_noise
    } else {
        idiosyncratic_noise * idio_down_suppress_scale
    };
    // The epicentre's other half, applied AFTER the draw for the reason the
    // reallocation above is: this reshapes a shock the tick has already
    // taken, so no branch here can move the draw count or the order. The
    // scale reaches `noise_idio_unit` below as well, so `noise_idio` is
    // still `z * sqrt(h)` times that unit term for term and the close's
    // commensurate innovation reads the scale the draw ACTUALLY took.
    let idiosyncratic_noise = match epicentre_gain {
        None => idiosyncratic_noise,
        Some(g) => idiosyncratic_noise * g,
    };

    // Crash correlation: when the market shock is extreme, everything loads
    // more heavily on it and diversification stops working — which is what
    // actually happens in a crash. `market_factor` is already at per-tick
    // scale, so the magnitude is normalised by the same scale.
    //
    // The normaliser is `MARKET_FACTOR_SIGMA` BY NAME, where the reference
    // implementation inlined the value — the recalibration lesson stands:
    // with a literal kept, recalibrating the sigma silently re-denominates
    // this threshold in the old units.
    //
    // Since the factor's variance became conditional (`factor_vol`), the
    // constant here was the BASELINE sigma, deliberately: "extreme" stayed
    // denominated in absolute units — the reference's own semantics — so a
    // high-variance factor regime pushed MORE ticks past the threshold and
    // the amplifier converted variance regimes into correlation regimes,
    // which is what real crises do. In a calm (floored) factor regime the
    // threshold sits ~9 conditional sigmas out and the amplifier is silent,
    // which is the other half of the same realism.
    //
    // `crash_amplifier_conditional_sigma` NORMALISES BY THE CONDITIONAL
    // SIGMA INSTEAD, and it is a switch: `== 0.0` is the baseline reading
    // and every other value is the conditional one, so a preset written
    // before the dial is bit-identical through the branch. The alternative
    // was built and measured on the published panel on 2026-08-22 and cost
    // 0.03 of volatility clustering (0.245 -> 0.216), 0.10 of excess
    // kurtosis (3.14 -> 3.04) and 0.006 of correlation at the shipped
    // constants (results/market-factor-vol-2026-08-22-*.json), and bought
    // "only the constancy of the firing rate". That appraisal was made on a
    // preset whose VIX could not see the amplifier at all. Under
    // `vix_level_identity` the amplifier's second moment is INSIDE the
    // VIX's own target, and with the baseline normaliser it grows as the
    // square of the regime ratio, so the loop's map is superlinear and
    // `vix_ceiling` is absorbing — measured on 11 of 120 rosters with the
    // crisis blend switched entirely off. Constancy of the firing rate now
    // buys the loop's stability. See `ModelParams::
    // crash_amplifier_conditional_sigma` and `market::index_var`.
    //
    // `market_sigma_tick` is the sigma the draw ACTUALLY used, carried on
    // `SharedFactors` rather than recomputed, for the same reason
    // `market_beta_down_asym_recentre` reads it: the two differ by the
    // whole of the factor's variance process. Guarded at zero, where the
    // quotient would be 0/0 — a factor that cannot move cannot be extreme,
    // and `amplifier_moments` returns the same no-amplifier pair there.
    let shock_magnitude = if params.crash_amplifier_conditional_sigma == 0.0 {
        shared.market_factor.abs() / (params.market_factor_sigma / mathx::sqrt(390.0))
    } else if shared.market_sigma_tick > 0.0 {
        shared.market_factor.abs() / shared.market_sigma_tick
    } else {
        0.0
    };
    let crash_amplifier = if shock_magnitude > params.crash_amplifier_threshold {
        1.0 + (shock_magnitude - params.crash_amplifier_threshold) * params.crash_amplifier_slope
    } else {
        1.0
    };

    // Give back the first moment the downside tilt injects, AFTER the
    // amplifier. `market_beta_down_asym` scales one side of a zero-mean
    // draw, which moves its mean, and a mean here is a drift: for
    // `f ~ N(0, s^2)`, `E[f 1{f<0}] = -s / sqrt(2 pi)`, so the tilt adds
    // `a * beta * -s / sqrt(2 pi)` to every name every tick whether the
    // market is calm or not.
    //
    // `s` is the CONDITIONAL sigma of this tick's draw, so the correction
    // tracks the variance process instead of assuming the baseline. AFTER
    // the amplifier because an offset added before it would be amplified
    // too, delivering the form times `E[A]` rather than the form. What
    // that leaves is the amplifier's own effect on the tilt, which has no
    // closed form and is about one per cent; see the parameter's doc.
    //
    // A branch, and gated on BOTH dials being nonzero, so every preset
    // that predates this parameter is bit-identical and so is any preset
    // that sets it without the tilt it corrects.
    let tilt_recentre = if params.market_beta_down_asym_recentre == 0.0
        || params.market_beta_down_asym == 0.0
    {
        0.0
    } else {
        params.market_beta_down_asym_recentre
            * params.market_beta_down_asym
            * beta
            * shared.market_sigma_tick
            / SQRT_TWO_PI
    };
    // The lagged wire multiplied the tilt by `1 + lag` on this session, so
    // its mean is `1 + lag` times what the line above gives back
    // (`market_beta_down_asym_lag_recentre`). The same condition the wire
    // itself reads, and a branch, so 0.0 is the arithmetic that stood.
    let tilt_recentre = if params.market_beta_down_asym_lag_recentre == 0.0
        || params.market_beta_down_asym_lag == 0.0
        || !shared.prev_day_down
    {
        tilt_recentre
    } else {
        tilt_recentre
            * (1.0 + params.market_beta_down_asym_lag_recentre * params.market_beta_down_asym_lag)
    };
    let random_noise =
        market_component * crash_amplifier + tilt_recentre + sector_component + idiosyncratic_noise;
    // The same three terms kept apart, written AFTER the sum so the sum
    // above is the statement that runs and this is a copy of its parts and
    // not a re-association of them. `noise_market + noise_sector +
    // noise_idio` is `random_noise` term for term.
    let noise_market = market_component * crash_amplifier + tilt_recentre;
    let noise_sector = sector_component;
    let noise_idio = idiosyncratic_noise;
    // The idiosyncratic draw's own scale with `daily_sigma` divided out --
    // the three multipliers `idiosyncratic_sigma` and the draw site apply
    // on top of the name's own sigma, plus the reallocation's scale.
    let noise_idio_unit =
        idio_scale / mathx::sqrt(390.0) * cap_mult * volatility_multiplier * idio_down_suppress_scale;
    let noise_idio_unit = match epicentre_gain {
        None => noise_idio_unit,
        Some(g) => noise_idio_unit * g,
    };

    // ── Forced flow ───────────────────────────────────────────────────────
    // Squeezes and stop cascades react to a move that ALREADY happened —
    // margin calls go out on yesterday's close. `last_daily_return` is the
    // previous COMPLETED day's return, so today's forced flow responds to
    // yesterday's move and today's price cannot re-trigger its own amplifier
    // within the day. That self-triggering is what turned the sector process
    // into observed bubble and crash runaways.
    let mut short_squeeze_effect = 0.0;
    let short_interest_ratio = company.short_interest / mathx::max(1.0, company.float);
    let daily_return = company.last_daily_return.unwrap_or(0.0);

    if short_interest_ratio > 0.2 && daily_return > 0.03 {
        short_squeeze_effect = short_interest_ratio * daily_return * 0.5;
        short_squeeze_effect = mathx::min(0.02, short_squeeze_effect);
    }

    // The two stop ladders, and how far they are matched. At symmetry 0.0
    // each side keeps its own literals and the arithmetic below is the
    // shipped arithmetic. At 1.0 both use the mean of the pair: threshold
    // 0.025, tiers 0.007, 0.0045, 0.0025 and 0.0005. That chooses neither
    // side and preserves the pair's total intervention exactly, 0.029
    // before and after.
    //
    // The GATES are untouched either way. A stop-loss sits under every
    // long, so the downside carries no condition beyond its threshold; a
    // buy-stop needs shorts to exist, so the upside keeps its short
    // interest gate. Those are finance rather than an accident.
    let (down_gate, down_a, down_b, down_c, down_d,
         up_gate, up_a, up_b, up_c, up_d) =
        if params.cascade_symmetry == 0.0 {
            (0.02, 0.008, 0.005, 0.003, 0.001,
             0.03, 0.006, 0.004, 0.002, 0.000)
        } else {
            let g = params.cascade_symmetry;
            (0.02 + 0.005 * g, 0.008 - 0.001 * g, 0.005 - 0.0005 * g,
             0.003 - 0.0005 * g, 0.001 - 0.0005 * g,
             0.03 - 0.005 * g, 0.006 + 0.001 * g, 0.004 + 0.0005 * g,
             0.002 + 0.0005 * g, 0.000 + 0.0005 * g)
        };

    // Downside stop cascade — denser stops at the -3/-5/-7% levels.
    if daily_return < -down_gate {
        let drop = daily_return.abs();
        let stop_cascade = if drop > 0.07 {
            down_a
        } else if drop > 0.05 {
            down_b
        } else if drop > 0.03 {
            down_c
        } else {
            down_d
        };
        short_squeeze_effect -= stop_cascade;
    }

    // Upside cascade — short sellers' buy-stops trigger on rallies. Note this
    // is NOT exclusive with the squeeze block above: a heavily-shorted name up
    // 8% gets both, which is the point.
    //
    // The fourth tier is 0.0 at symmetry 0.0, where the shipped ladder has
    // only three and this branch is the band between the gate and 3 per
    // cent that the shipped rule never reaches, since its gate IS 3 per
    // cent. It becomes reachable and non-zero together.
    if daily_return > up_gate && short_interest_ratio > 0.1 {
        let buy_cascade = if daily_return > 0.07 {
            up_a
        } else if daily_return > 0.05 {
            up_b
        } else if daily_return > 0.03 {
            up_c
        } else {
            up_d
        };
        short_squeeze_effect += buy_cascade;
    }

    // `cascade_gain` scales the whole forced-flow term -- the squeeze and
    // both stop ladders -- which reacts to the name's own previous day and
    // is therefore a daily momentum in the model price. A branch at 1.0, so
    // every preset through pt-v19 is bit-identical.
    let short_squeeze_effect = if params.cascade_gain == 1.0 {
        short_squeeze_effect
    } else {
        short_squeeze_effect * params.cascade_gain
    };

    LiveFactors {
        company_news,
        company_news_market,
        order_flow_impact,
        short_squeeze_effect,
        random_noise,
        noise_market,
        noise_market_linear: beta * shared.market_factor,
        noise_sector,
        noise_idio,
        noise_idio_unit,
    }
}

/// JavaScript truthiness for `x || 0` on a possibly-absent number.
fn truthy(value: Option<f64>) -> f64 {
    match value {
        Some(x) if x != 0.0 && !x.is_nan() => x,
        _ => 0.0,
    }
}

/// `sqrt(2 pi)`, the denominator of a standard normal's half-moment:
/// `E[f 1{f<0}] = -sigma / sqrt(2 pi)`.
///
/// A literal because `sqrt` is not a const function, and safe as a literal
/// because IEEE-754 specifies `sqrt` exactly, so there is one right answer
/// on every target and `the_half_moment_denominator_is_sqrt_two_pi` asserts
/// this is it, bit for bit, against the language's own `PI`. That test is
/// the reason this is not a second source of truth: a mistyped digit fails
/// it rather than shipping a slightly wrong recentring.
///
/// Note what this deliberately is NOT: `erf`. Recentring needs only the
/// half-moment of a normal, which is elementary. The normal TAIL would
/// need `erf`, `mathx` exposes none, and adding one would be a new
/// bit-pinned transcendental with its own known-answer obligation.
const SQRT_TWO_PI: f64 = 2.5066282746310002;

/// Order imbalance from a tick's pending orders, from the reference
/// implementation.
///
/// Scales with volume RELATIVE to the name's own average, so a 10,000-share
/// order moves a thin stock and not a liquid one — impact is about
/// participation, not absolute size.
pub fn order_imbalance(buy_vol: f64, sell_vol: f64, avg_volume: f64) -> f64 {
    let total_vol = buy_vol + sell_vol;
    // `company.stock.avgVolume || 1000000` — truthy-or, so a zero average
    // falls through to the default rather than dividing by zero.
    let avg_minute_vol = mathx::max(truthy_or(avg_volume, 1_000_000.0) / 390.0, 100.0);
    let volume_ratio = mathx::min(total_vol / avg_minute_vol, 10.0);
    let raw_imbalance = if total_vol > 0.0 {
        (buy_vol - sell_vol) / total_vol
    } else {
        0.0
    };
    // The floor of 0.2 means even a tiny order carries some impact.
    raw_imbalance * mathx::max(0.2, volume_ratio * 0.15)
}

fn truthy_or(value: f64, fallback: f64) -> f64 {
    if value != 0.0 && !value.is_nan() {
        value
    } else {
        fallback
    }
}

/// The participation at which the shipped multiplier stops responding, and
/// the slope it responds with below that. Both are read back out of
/// `order_imbalance` itself by `the_law_constants_are_the_shipped_ones`, so
/// they cannot drift away from the literals that function still uses.
const PARTICIPATION_KNEE: f64 = 10.0;
const PARTICIPATION_SLOPE: f64 = 0.15;

/// The measured participation multiplier: linear below the knee, square
/// root above it.
///
/// Continuous at the knee by construction and not by arrangement -- both
/// branches evaluate to `PARTICIPATION_SLOPE * PARTICIPATION_KNEE` there,
/// because `sqrt(1)` is exactly 1.0 in IEEE-754.
///
/// The linear branch reaches down to zero on its own, which is why there is
/// no floor here. The shipped 0.2 was the linear law clamped at precisely
/// the point it crosses 0.2, since `PARTICIPATION_SLOPE * 4.0 / 3.0` is
/// that value; removing the clamp continues the same line rather than
/// introducing a different one.
fn participation_multiplier(participation: f64) -> f64 {
    if participation <= PARTICIPATION_KNEE {
        PARTICIPATION_SLOPE * participation
    } else {
        PARTICIPATION_SLOPE
            * PARTICIPATION_KNEE
            * mathx::sqrt(participation / PARTICIPATION_KNEE)
    }
}

/// `order_imbalance` under `order_flow_impact_law`.
///
/// At 0.0 this IS `order_imbalance`, by branch rather than by arithmetic,
/// so every preset that predates the dial is bit-identical. At 1.0 the
/// participation multiplier follows the measured law instead of the clamped
/// one. `ModelParams::order_flow_impact_law` carries the sources, the
/// clock, and what the change does not claim. It does NOT restate the
/// depth exponent; `ModelParams::order_flow_depth_law` does, in
/// `calculate_live_factors`.
///
/// `order_imbalance` keeps its signature and its behaviour because it is
/// public API, re-exported through `market::mod`. This is the
/// `cap_size_multiplier` / `cap_size_multiplier_with` pattern already in
/// this file.
pub fn order_imbalance_with(
    params: &crate::params::ModelParams,
    buy_vol: f64,
    sell_vol: f64,
    avg_volume: f64,
) -> f64 {
    if params.order_flow_impact_law == 0.0 {
        return order_imbalance(buy_vol, sell_vol, avg_volume);
    }
    let total_vol = buy_vol + sell_vol;
    // Written as the negation so a NaN total takes this branch too, which is
    // what `order_imbalance`'s `if total_vol > 0.0` does. Returning the same
    // literal keeps the sign of the zero identical on both laws, and that is
    // what makes a run with no injected flow bit-identical rather than
    // merely equal.
    //
    // A NOTE FOR WHOEVER REVISES THE LAW BELOW. The shipped call site
    // multiplies a raw imbalance by the multiplier, and with no injected
    // flow that raw imbalance is a literal zero. Zero times a FINITE
    // multiplier is zero; zero times an infinity is NaN, and a NaN reaching
    // a price is a moved trajectory and a moved known-answer digest. So a
    // participation term must stay finite at zero participation even though
    // this early return means it is not evaluated there today. Putting a
    // division or a logarithm in `participation_multiplier` breaks that,
    // and `the_multiplier_is_finite_at_zero_participation` is what says so.
    if !(total_vol > 0.0) {
        return 0.0;
    }
    let avg_minute_vol = mathx::max(truthy_or(avg_volume, 1_000_000.0) / 390.0, 100.0);
    // Two finite sides can sum past the largest double. Then `(b - s) / inf`
    // reads zero whatever the direction, the participation is infinite, and
    // the unbounded multiplier made the product `0 * inf`, a NaN price.
    // Halving both sides is exact and keeps the ratio, and the participation
    // is held at the largest finite value, where the multiplier is still
    // finite. Both are branches on overflow alone, so every finite total
    // takes the arithmetic that stood.
    let raw_imbalance = if total_vol.is_finite() {
        (buy_vol - sell_vol) / total_vol
    } else {
        (0.5 * buy_vol - 0.5 * sell_vol) / (0.5 * buy_vol + 0.5 * sell_vol)
    };
    let participation = total_vol / avg_minute_vol;
    let participation = if participation.is_finite() { participation } else { f64::MAX };
    raw_imbalance * participation_multiplier(participation)
}

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

    struct Fixed(f64);
    impl Rng for Fixed {
        fn next_f64(&mut self) -> f64 {
            self.0
        }
        fn next_normal(&mut self) -> f64 {
            self.0
        }
    }

    fn company() -> FactorCompany {
        FactorCompany {
            id: "ACME".into(),
            sector: "technology".into(),
            beta: Some(1.0),
            market_cap: 20e9,
            avg_volume: 1e6,
            shares_outstanding: 1e8,
            short_interest: 0.0,
            float: 1e8,
            garch_variance: 0.015 * 0.015,
            last_daily_return: Some(0.0),
        }
    }

    fn shared() -> SharedFactors {
        SharedFactors {
            market_factor: 0.0,
            sector_factors: vec![("technology".into(), 0.0)],
            crisis_spike: 0.0,
            prev_day_down: false,
            market_sigma_tick: crate::params::PT_V1.market_factor_sigma
                / crate::mathx::sqrt(390.0),
            crisis_epicentre: None,
        }
    }

    fn factors(
        c: &FactorCompany,
        news: &[NewsEvent],
        imbalance: f64,
        s: &SharedFactors,
    ) -> LiveFactors {
        calculate_live_factors(c, news, imbalance, 1.0, s, &crate::params::PT_V1, &mut Fixed(0.0))
    }

    /// `factors` under explicit parameters, for the dials whose whole
    /// question is what a preset sets them to.
    fn factors_with(
        p: &crate::params::ModelParams,
        c: &FactorCompany,
        news: &[NewsEvent],
        imbalance: f64,
        s: &SharedFactors,
    ) -> LiveFactors {
        calculate_live_factors(c, news, imbalance, 1.0, s, p, &mut Fixed(0.0))
    }

    #[test]
    fn exactly_one_normal_is_drawn_however_the_branches_fall() {
        // The draw count must not depend on news, flow or squeeze state.
        struct Counting(usize);
        impl Rng for Counting {
            fn next_f64(&mut self) -> f64 {
                panic!("the factor subset must not draw uniforms")
            }
            fn next_normal(&mut self) -> f64 {
                self.0 += 1;
                0.0
            }
        }
        for daily_return in [-0.10, -0.03, 0.0, 0.05, 0.10] {
            for short_interest in [0.0, 3e7] {
                let mut c = company();
                c.last_daily_return = Some(daily_return);
                c.short_interest = short_interest;
                let mut rng = Counting(0);
                calculate_live_factors(&c, &[], 0.5, 1.0, &shared(), &crate::params::PT_V1, &mut rng);
                assert_eq!(rng.0, 1, "return {daily_return}, si {short_interest}");
            }
        }
    }

    // ── News ──────────────────────────────────────────────────────────────

    #[test]
    fn news_weights_are_company_then_sector_then_market_wide() {
        let c = company();
        let at = |e: NewsEvent| factors(&c, &[e], 0.0, &shared()).company_news;

        assert_eq!(
            at(NewsEvent {
                company_id: Some("ACME".into()),
                sector: None,
                price_impact: Some(0.1)
            }),
            0.1
        );
        assert_eq!(
            at(NewsEvent {
                company_id: None,
                sector: Some("technology".into()),
                price_impact: Some(0.1)
            }),
            0.1 * 0.5
        );
        assert_eq!(
            at(NewsEvent {
                company_id: None,
                sector: None,
                price_impact: Some(0.1)
            }),
            0.1 * 0.3
        );
    }

    /// A peer's news event, for the information-transfer tests.
    fn peer_event(impact: f64) -> NewsEvent {
        NewsEvent {
            company_id: Some("OTHER".into()),
            sector: Some("technology".into()),
            price_impact: Some(impact),
        }
    }

    fn with_peer_weights(up: f64, down: f64) -> crate::params::ModelParams {
        crate::params::PT_V1
            .with_override("news_peer_weight", up)
            .unwrap()
            .with_override("news_peer_weight_down", down)
            .unwrap()
    }

    #[test]
    fn an_event_for_another_company_is_ignored_at_the_shipped_weight() {
        let c = company();
        // Has a companyId, so it cannot fall through to the sector or
        // market-wide arms even though its sector matches — and the peer arm
        // that now sits between them is off in every shipped preset.
        //
        // This assertion is the inertness proof for the information-transfer
        // channel: EXACTLY zero, not approximately, because the branch is
        // skipped rather than multiplied by a zero weight.
        assert_eq!(factors(&c, &[peer_event(0.5)], 0.0, &shared()).company_news, 0.0);
    }

    #[test]
    fn a_peers_good_news_lifts_this_name_when_transfer_is_on() {
        let c = company();
        let p = with_peer_weights(0.2, 0.5);
        let got =
            calculate_live_factors(&c, &[peer_event(0.5)], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
                .company_news;
        assert_eq!(got, 0.5 * 0.2);
    }

    #[test]
    fn bad_news_transfers_on_its_own_weight() {
        // The asymmetry is the point: the same magnitude of surprise moves
        // peers further down than up. A single signed weight could not carry
        // this, and a search given only one could never find it.
        let c = company();
        let p = with_peer_weights(0.2, 0.5);
        let up =
            calculate_live_factors(&c, &[peer_event(0.4)], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
                .company_news;
        let down = calculate_live_factors(
            &c,
            &[peer_event(-0.4)],
            0.0,
            1.0,
            &shared(),
            &p,
            &mut Fixed(0.0),
        )
        .company_news;
        assert_eq!(up, 0.4 * 0.2);
        assert_eq!(down, -0.4 * 0.5);
        assert!(down.abs() > up.abs(), "bad news must transfer more strongly");
    }

    #[test]
    fn the_named_company_still_takes_the_full_impact_not_the_peer_weight() {
        // The company the event names is matched by id, before sector is
        // consulted at all. Transfer must not dilute the announcer's own move.
        let c = company();
        let p = with_peer_weights(0.2, 0.5);
        let own = NewsEvent {
            company_id: Some(c.id.clone()),
            sector: Some("technology".into()),
            price_impact: Some(0.5),
        };
        let got =
            calculate_live_factors(&c, &[own], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
                .company_news;
        assert_eq!(got, 0.5);
    }

    #[test]
    fn transfer_does_not_reach_a_different_sector() {
        let c = company(); // technology
        let p = with_peer_weights(0.2, 0.5);
        let elsewhere = NewsEvent {
            company_id: Some("OTHER".into()),
            sector: Some("energy".into()),
            price_impact: Some(0.5),
        };
        let got =
            calculate_live_factors(&c, &[elsewhere], 0.0, 1.0, &shared(), &p, &mut Fixed(0.0))
                .company_news;
        assert_eq!(got, 0.0);
    }

    #[test]
    fn news_accumulates_across_events() {
        let c = company();
        let news = vec![
            NewsEvent {
                company_id: Some("ACME".into()),
                sector: None,
                price_impact: Some(0.1),
            },
            NewsEvent {
                company_id: None,
                sector: None,
                price_impact: Some(0.1),
            },
        ];
        assert_eq!(factors(&c, &news, 0.0, &shared()).company_news, 0.1 + 0.03);
    }

    #[test]
    fn an_absent_or_zero_impact_contributes_nothing() {
        let c = company();
        for impact in [None, Some(0.0), Some(f64::NAN)] {
            let e = NewsEvent {
                company_id: Some("ACME".into()),
                sector: None,
                price_impact: impact,
            };
            assert_eq!(
                factors(&c, &[e], 0.0, &shared()).company_news,
                0.0,
                "{impact:?}"
            );
        }
    }

    // ── Order flow ────────────────────────────────────────────────────────

    #[test]
    fn a_thin_stock_takes_more_impact_from_the_same_imbalance() {
        let mut thin = company();
        thin.avg_volume = 50_000.0;
        thin.shares_outstanding = 1e6;
        let liquid = company();
        assert!(
            factors(&thin, &[], 0.5, &shared()).order_flow_impact
                > factors(&liquid, &[], 0.5, &shared()).order_flow_impact
        );
    }

    #[test]
    fn the_half_moment_denominator_is_sqrt_two_pi() {
        // SQRT_TWO_PI is a literal because `sqrt` is not const. This is
        // what stops it being a second source of truth: it must equal the
        // language's own PI put through the same `sqrt` the rest of this
        // crate uses, to the bit.
        assert_eq!(SQRT_TWO_PI, mathx::sqrt(2.0 * std::f64::consts::PI));
    }

    #[test]
    fn recentring_returns_the_mean_the_downside_tilt_injects() {
        // The claim, measured rather than argued: with the tilt on, the
        // market channel's mean over a symmetric factor is negative, and
        // with the recentring on it is zero. Averaged over a symmetric
        // grid of factor draws, which is what makes the two arms
        // comparable without an RNG.
        let mut params = crate::params::PT_V16;
        assert_ne!(params.market_beta_down_asym, 0.0, "the tilt must be on");
        let sigma_tick = params.market_factor_sigma / mathx::sqrt(390.0);

        // A symmetric grid, WEIGHTED BY THE NORMAL DENSITY. The weight is
        // the whole point: the correction gives back `E[f 1{f<0}]` for a
        // NORMAL factor, which is `-sigma / sqrt(2 pi)`. Averaging over a
        // uniform grid instead measures `E[f 1{f<0}]` for a uniform one,
        // which on [-4, 4] sigmas is -1.0 sigma against the normal's
        // -0.399, so a correct correction would look 60 per cent short.
        // This test asserted exactly that and failed the code for it.
        let grid: Vec<f64> = (1..=400)
            .map(|k| k as f64 * 0.01)
            .flat_map(|z| [z, -z])
            .collect();

        let mean_of = |p: &crate::params::ModelParams| -> f64 {
            let company = company();
            let mut total = 0.0;
            let mut weight_sum = 0.0;
            for z in &grid {
                let w = mathx::exp(-z * z / 2.0);
                let s = SharedFactors {
                    market_factor: z * sigma_tick,
                    sector_factors: vec![("technology".into(), 0.0)],
                    crisis_spike: 0.0,
                    prev_day_down: false,
                    market_sigma_tick: sigma_tick,
                    crisis_epicentre: None,
                };
                total += w * factors_with(p, &company, &[], 0.0, &s).random_noise;
                weight_sum += w;
            }
            total / weight_sum
        };

        let injected = mean_of(&params);
        assert!(
            injected < 0.0,
            "the tilt should inject a NEGATIVE mean, got {injected}"
        );

        params.market_beta_down_asym_recentre = 1.0;
        let corrected = mean_of(&params);

        // What remains is the crash amplifier's own effect on the tilt,
        // which this deliberately does not correct. It is a small
        // fraction of the term, and it is the ONLY thing left.
        let residual = corrected / injected;
        assert!(
            residual.abs() < 0.05,
            "recentring left {residual} of the injected mean, expected \
             only the amplifier's few per cent"
        );
        // And it did not overshoot into a positive drift.
        assert!(corrected <= 0.0, "recentring overshot to {corrected}");
    }

    #[test]
    fn recentring_is_inert_without_the_tilt_it_corrects() {
        // Gated on BOTH dials. A preset that sets the recentring without
        // the tilt has nothing to give back and must be bit-identical, or
        // the dial would inject the drift it exists to remove.
        let company = company();
        let s = shared();
        let mut params = crate::params::PT_V16;
        params.market_beta_down_asym = 0.0;
        let without = factors_with(&params, &company, &[], 0.0, &s).random_noise;
        params.market_beta_down_asym_recentre = 1.0;
        let with = factors_with(&params, &company, &[], 0.0, &s).random_noise;
        assert_eq!(without, with);
    }

    #[test]
    fn every_preset_before_pt_v18_is_bit_identical_under_the_new_dial() {
        // The parameter ships at 0.0 and the branch is at zero, so adding
        // it moved no trajectory. Asserted against the presets rather than
        // argued from the branch.
        for name in crate::params::ModelParams::preset_names() {
            let p = crate::params::ModelParams::preset(name).expect("named");
            // pt-v18 switched the recentring on; pt-v19 is built on pt-v18
            // and pt-v20 on pt-v19, and both inherit it. Every preset before
            // pt-v18 must read 0.0. pt-v21 (0.10.0) is built on pt-v20.
            // pt-v22's values are its arm's, which `PT_V22_DIGEST_PREFIX`
            // and tests/test_validation.py hold as a whole.
            if *name == "pt-v22" {
                continue;
            }
            if matches!(*name, "pt-v18" | "pt-v19" | "pt-v20" | "pt-v21") {
                assert_eq!(p.market_beta_down_asym_recentre, 1.0, "{name}");
                continue;
            }
            assert_eq!(p.market_beta_down_asym_recentre, 0.0, "{name}");
        }
    }

    // ── The down-tick reallocation ────────────────────────────────────────

    /// A name with no market and no sector exposure, so `random_noise` IS
    /// the idiosyncratic term and the reallocation can be read off it
    /// without the factor leg in the way. Beta 0.0 zeroes
    /// `market_component` and the amplifier multiplies it, so the only
    /// thing left in the sum is the shock this dial scales.
    fn idio_only_company() -> FactorCompany {
        let mut c = company();
        c.beta = Some(0.0);
        c
    }

    /// The tick's shared factors at a market factor of `z` conditional
    /// sigmas. Deliberately NOT the `shared()` fixture: that one hands the
    /// tick a factor of exactly 0.0, which is the up branch on both wires,
    /// and a neutrality measured there would measure the degenerate case
    /// the parameter's doc warns about.
    fn shared_at(z: f64) -> SharedFactors {
        let sigma_tick = crate::params::PT_V1.market_factor_sigma / mathx::sqrt(390.0);
        SharedFactors {
            market_factor: z * sigma_tick,
            sector_factors: vec![("technology".into(), 0.0)],
            crisis_spike: 0.0,
            prev_day_down: false,
            market_sigma_tick: sigma_tick,
            crisis_epicentre: None,
        }
    }

    fn with_suppress(c: f64) -> crate::params::ModelParams {
        crate::params::PT_V1.with_override("market_idio_down_suppress", c).unwrap()
    }

    #[test]
    fn the_two_scales_average_to_one_to_within_an_ulp() {
        // The whole of the variance-neutrality claim, checked on the
        // arithmetic rather than through a tick: `down^2 + up^2 == 2`, so
        // their mean over an even split is one. Exact in exact arithmetic;
        // in IEEE-754 the doubles round, and this pins HOW FAR -- the doc
        // says one ulp and a reader is entitled to see the number.
        let mut worst: f64 = 0.0;
        for k in 0..=200 {
            let c = k as f64 * 0.005; // 0.0 .. 1.0
            let (down, up) = idio_suppress_scales(c);
            let residual = (down * down + up * up - 2.0).abs();
            worst = mathx::max(worst, residual);
        }
        // Four ulps of 2.0. Measured worst case over the grid above is
        // under one; the bar is loose enough that a different rounding on
        // another target is not a failure and tight enough that an
        // arithmetic mistake is.
        assert!(worst <= 4.0 * f64::EPSILON * 2.0,
                "the two squared scales are off by {worst}, not by rounding");
    }

    #[test]
    fn the_scales_are_bounded_by_the_constructions_own_domain() {
        // At c = 0 the pair is exactly (1, 1) -- the identity, and it has
        // to be exact rather than close, because the branch above is what
        // makes a shipped preset bit-identical and this is what would be
        // multiplied if anyone removed it.
        assert_eq!(idio_suppress_scales(0.0), (1.0, 1.0));
        // At c = 1 the down tick is silenced and the up tick carries the
        // whole budget.
        let (down, up) = idio_suppress_scales(1.0);
        assert_eq!(down, 0.0);
        assert_eq!(up, mathx::sqrt(2.0));
        // Past the domain the clamp holds rather than flipping the shock's
        // sign, and -- the reason the `max` is there -- neither end is NaN.
        for c in [-5.0, -0.5, 1.5, 9.0] {
            let (down, up) = idio_suppress_scales(c);
            assert!(down.is_finite() && up.is_finite(), "c {c}: ({down}, {up})");
            assert!(down >= 0.0 && up >= 0.0, "c {c}: ({down}, {up})");
        }
    }

    #[test]
    fn the_reallocation_is_inert_at_zero_on_both_half_lines() {
        // The identity arm. `c` = 0.0 takes neither multiply, so a preset
        // that predates the dial is bit-identical -- and it has to hold on
        // a DOWN tick as well as an up one, because the branch that would
        // break it is the down one.
        let c = idio_only_company();
        for z in [-3.0, -1.0, -0.25, 0.25, 1.0, 3.0] {
            let s = shared_at(z);
            let base = calculate_live_factors(
                &c, &[], 0.0, 1.0, &s, &crate::params::PT_V1, &mut Fixed(0.7));
            let dialled = calculate_live_factors(
                &c, &[], 0.0, 1.0, &s, &with_suppress(0.0), &mut Fixed(0.7));
            assert_eq!(base.random_noise, dialled.random_noise, "z {z}");
        }
    }

    #[test]
    fn a_down_tick_is_suppressed_and_an_up_tick_is_inflated() {
        // The direction, which is the mechanism: the factor's SHARE has to
        // rise where the statistic looks and fall where it does not.
        let company = idio_only_company();
        let p = with_suppress(0.15);
        let base = |z: f64| calculate_live_factors(
            &company, &[], 0.0, 1.0, &shared_at(z), &crate::params::PT_V1,
            &mut Fixed(1.0)).random_noise;
        let dialled = |z: f64| calculate_live_factors(
            &company, &[], 0.0, 1.0, &shared_at(z), &p, &mut Fixed(1.0)).random_noise;

        let (down, up) = idio_suppress_scales(0.15);
        assert_eq!(dialled(-1.5), base(-1.5) * down);
        assert_eq!(dialled(1.5), base(1.5) * up);
        assert!(down < 1.0 && up > 1.0, "({down}, {up}) is not a reallocation");
    }

    #[test]
    fn the_reallocation_moves_no_first_moment_at_any_tick() {
        // Mean-neutrality, and it is stronger than "in expectation": the
        // scale depends on the FACTOR's sign and not on the shock's, so the
        // two arms of a symmetric shock are scaled by the same number and
        // cancel to the bit at every single tick. That is why no recentring
        // dial stands beside this one, where `market_beta_down_asym` needed
        // `market_beta_down_asym_recentre`.
        let company = idio_only_company();
        for c in [0.05, 0.15, 0.40, 1.0] {
            let p = with_suppress(c);
            for z in [-3.0, -0.5, 0.5, 3.0] {
                let s = shared_at(z);
                let plus = calculate_live_factors(
                    &company, &[], 0.0, 1.0, &s, &p, &mut Fixed(1.0)).random_noise;
                let minus = calculate_live_factors(
                    &company, &[], 0.0, 1.0, &s, &p, &mut Fixed(-1.0)).random_noise;
                assert_eq!(plus + minus, 0.0, "c {c}, z {z}");
            }
        }
    }

    #[test]
    fn the_reallocation_holds_the_second_moment_over_a_symmetric_factor() {
        // Variance-neutrality, measured through the tick rather than
        // argued: the density-weighted mean of the squared shock over a
        // symmetric grid of factor draws, dialled against undialled. The
        // grid is the one `recentring_returns_the_mean_the_downside_tilt_
        // injects` uses and it matters for the same reason it does there --
        // except that here the WEIGHTS are not what carries the result. The
        // scale depends on the factor only through its SIGN, so any
        // symmetric grid gives the same answer; the weights are kept so the
        // two tests read the factor the same way.
        //
        // The grid excludes z = 0 exactly. That is deliberate: an exactly
        // zero factor is an up tick, and a grid containing one would be an
        // uneven split of the half-lines, which is the one condition the
        // neutrality needs.
        let company = idio_only_company();
        let grid: Vec<f64> = (1..=400).map(|k| k as f64 * 0.01)
            .flat_map(|z| [z, -z]).collect();

        let mean_square = |p: &crate::params::ModelParams| -> f64 {
            let mut total = 0.0;
            let mut weight = 0.0;
            for z in &grid {
                let w = mathx::exp(-z * z / 2.0);
                let noise = calculate_live_factors(
                    &company, &[], 0.0, 1.0, &shared_at(*z), p, &mut Fixed(1.0))
                    .random_noise;
                total += w * noise * noise;
                weight += w;
            }
            total / weight
        };

        let base = mean_square(&crate::params::PT_V1);
        for c in [0.05, 0.15, 0.40, 1.0] {
            let ratio = mean_square(&with_suppress(c)) / base;
            assert!((ratio - 1.0).abs() < 1e-12,
                    "c {c}: the second moment moved to {ratio} of itself");
        }
    }

    #[test]
    fn a_degenerate_zero_factor_is_the_one_place_neutrality_fails() {
        // The caveat the doc states, asserted rather than left as prose. A
        // factor of exactly 0.0 takes the up branch on both wires, so a
        // configuration in which the factor cannot move at all inflates the
        // idiosyncratic variance by `2 - (1 - c)^2` instead of holding it.
        // This is what makes the `shared()` fixture the wrong place to
        // measure neutrality, and somebody will try.
        let company = idio_only_company();
        let s = shared();
        assert_eq!(s.market_factor, 0.0, "the fixture's premise");
        let base = calculate_live_factors(
            &company, &[], 0.0, 1.0, &s, &crate::params::PT_V1, &mut Fixed(1.0))
            .random_noise;
        let (_, up) = idio_suppress_scales(0.15);
        let dialled = calculate_live_factors(
            &company, &[], 0.0, 1.0, &s, &with_suppress(0.15), &mut Fixed(1.0))
            .random_noise;
        assert_eq!(dialled, base * up);
        assert!(up > 1.0, "and it is an INFLATION, which is the whole warning");
    }

    #[test]
    fn the_variance_residual_is_the_binomial_one() {
        // What "exactly neutral" does NOT mean. Neutrality is exact in
        // EXPECTATION; over a finite run of `N` ticks the realised
        // multiplier on the idiosyncratic variance is
        // `M_N = (k/N) down^2 + (1 - k/N) up^2` with `k` the down-tick
        // count, and `k ~ Binomial(N, 1/2)` because the sign of a symmetric
        // draw is a fair coin. Linear in `k`, so
        // `E[M_N] = 1` and `sd(M_N) = |down^2 - up^2| / (2 sqrt(N))`,
        // which is `|1 - (1-c)^2| / sqrt(N)`.
        //
        // The closed form is confirmed against flipped coins rather than
        // restated, because the step worth checking is the one from "a
        // binomial count" to that expression.
        let c = 0.15;
        let (down, up) = idio_suppress_scales(c);
        let n: usize = 390; // one session
        let closed = (1.0 - down * down).abs() / mathx::sqrt(n as f64);

        // A self-contained xorshift64*: this is a property of the ARITHMETIC
        // and must not reach for an engine stream, whose schedule is a
        // contract of its own.
        let mut state: u64 = 0x2026_0914_a575_4e07;
        let mut flip = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state & 1 == 1
        };

        let reps = 4000;
        let mut sum = 0.0;
        let mut sum_sq = 0.0;
        for _ in 0..reps {
            let mut k = 0usize;
            for _ in 0..n {
                if flip() {
                    k += 1;
                }
            }
            let frac = k as f64 / n as f64;
            let m = frac * down * down + (1.0 - frac) * up * up;
            sum += m;
            sum_sq += m * m;
        }
        let mean = sum / reps as f64;
        let sd = mathx::sqrt(sum_sq / reps as f64 - mean * mean);

        assert!((mean - 1.0).abs() < 5.0 * closed / mathx::sqrt(reps as f64),
                "the realised multiplier centres at {mean}, not at one");
        assert!((sd / closed - 1.0).abs() < 0.10,
                "sampled sd {sd} against the closed form {closed}");

        // And the two figures the parameter's doc quotes, so the prose
        // cannot drift from the arithmetic: 1.4 per cent of the
        // idiosyncratic variance over one session, 0.089 per cent over a
        // 252-session window.
        assert!((closed - 0.0140).abs() < 0.0002, "one session: {closed}");
        let window = (1.0 - down * down).abs() / mathx::sqrt((n * 252) as f64);
        assert!((window - 0.00089).abs() < 0.00002, "252 sessions: {window}");
    }

    #[test]
    fn every_preset_ships_the_reallocation_off() {
        // The dial ships at 0.0 and the branch is at zero, so adding it
        // moved no trajectory. Asserted against the presets rather than
        // argued from the branch, as the recentring's own guard is.
        for name in crate::params::ModelParams::preset_names() {
            let p = crate::params::ModelParams::preset(name).expect("named");
            assert_eq!(p.market_idio_down_suppress, 0.0, "{name}");
        }
    }

    #[test]
    fn order_flow_carries_only_the_informed_fraction() {
        // The structural claim behind INFORMED_FLOW_FRACTION: the book now
        // charges the mechanical part, so the factor must not.
        let c = company();
        let out = factors(&c, &[], 1.0, &shared()).order_flow_impact;
        let avg = 1e6f64.max(1e8 * 0.005);
        let expected = 1.0
            * (1.0 / (avg / 390.0).max(100.0))
            * ORDER_FLOW_COEFFICIENT
            * INFORMED_FLOW_FRACTION;
        assert_eq!(out, expected);
    }

    #[test]
    fn order_flow_uses_max_not_the_truthy_fallback_chain() {
        // `microstructure::base_quote_size` falls THROUGH a zero avgVolume;
        // this takes `Math.max` instead, so a zero is compared and loses to
        // the shares-outstanding term rather than being skipped.
        let mut c = company();
        c.avg_volume = 0.0;
        c.shares_outstanding = 1e8;
        let out = factors(&c, &[], 1.0, &shared()).order_flow_impact;
        let expected = 1.0
            * (1.0 / ((1e8f64 * 0.005) / 390.0).max(100.0))
            * ORDER_FLOW_COEFFICIENT
            * INFORMED_FLOW_FRACTION;
        assert_eq!(out, expected);
    }

    #[test]
    fn the_imbalance_scales_with_participation_not_absolute_size() {
        // 10,000 shares is a lot for a thin name and nothing for a liquid one.
        let thin = order_imbalance(10_000.0, 0.0, 50_000.0);
        let liquid = order_imbalance(10_000.0, 0.0, 500e6);
        assert!(thin > liquid, "{thin} vs {liquid}");
        // Balanced flow is neutral however large.
        assert_eq!(order_imbalance(1e6, 1e6, 1e6), 0.0);
        // No orders at all is neutral, not a division by zero.
        assert_eq!(order_imbalance(0.0, 0.0, 1e6), 0.0);
    }

    #[test]
    fn a_zero_average_volume_falls_through_to_the_default_in_the_imbalance() {
        assert!(order_imbalance(1000.0, 0.0, 0.0).is_finite());
        assert_eq!(
            order_imbalance(1000.0, 0.0, 0.0),
            order_imbalance(1000.0, 0.0, 1_000_000.0)
        );
    }

    // -- The participation law ---------------------------------------------

    fn law_on() -> crate::params::ModelParams {
        crate::params::PT_V16
            .with_override("order_flow_impact_law", 1.0)
            .unwrap()
    }

    /// The multiplier alone, at participation `phi`.
    ///
    /// A pure one-sided buy, so the raw imbalance is exactly 1.0 and what
    /// comes back is the participation term by itself. 390,000 shares a day
    /// is 1,000 a minute, well clear of the 100-share floor, so `phi`
    /// thousand shares of buying IS a participation of `phi`.
    fn multiplier(p: &crate::params::ModelParams, phi: f64) -> f64 {
        order_imbalance_with(p, phi * 1000.0, 0.0, 390_000.0)
    }

    /// `d log m / d log phi`, measured across one octave.
    ///
    /// A power law returns its own exponent. Anything else returns the
    /// average slope over the octave, which is what makes this readable on
    /// a clamped function too: a clamp reads zero.
    fn exponent(p: &crate::params::ModelParams, phi: f64) -> f64 {
        mathx::log(multiplier(p, 2.0 * phi) / multiplier(p, phi)) / mathx::log(2.0)
    }

    #[test]
    fn the_shipped_law_stops_responding_at_both_ends_and_not_just_the_top() {
        // Issue #166 reports the ceiling. The floor is the same defect at
        // the other end, and it is measured here rather than read off the
        // source because the two clamps are written differently -- one is a
        // `min` inside the product, the other a `max` around it -- and only
        // the elasticity shows they do the same thing.
        let off = crate::params::PT_V16;
        assert_eq!(
            off.order_flow_impact_law, 0.0,
            "the shipped law must remain the default"
        );
        for (phi, expected, what) in [
            (0.1, 0.0, "below the floor, size has stopped mattering"),
            (2.0, 1.0, "in the band, size maps straight through"),
            (20.0, 0.0, "above the ceiling, size has stopped mattering again"),
        ] {
            let k = exponent(&off, phi);
            assert!((k - expected).abs() < 1e-12, "phi {phi}: {k}, {what}");
        }
        // And WHERE the ends are, not only that they exist. Mutation
        // testing found this: with the elasticities alone, a ceiling moved
        // from ten to twenty still reads 0 at the point sampled above it,
        // because that point moved inside the new band. The multiplier is
        // already at its ceiling at exactly ten, and still rising just
        // below, so a ceiling anywhere else fails one of these two.
        assert_eq!(multiplier(&off, PARTICIPATION_KNEE), multiplier(&off, 1e9));
        assert!(multiplier(&off, 9.0) < multiplier(&off, PARTICIPATION_KNEE));
    }

    #[test]
    fn the_law_constants_are_read_back_out_of_the_shipped_function() {
        // `PARTICIPATION_SLOPE` and `PARTICIPATION_KNEE` are named here but
        // `order_imbalance` still uses its own literals, so the two could
        // drift apart. Recovered rather than compared against a number
        // written twice: the slope from two points inside the band, the
        // ceiling from a participation far outside it, and the knee as
        // their ratio.
        let off = crate::params::PT_V16;
        let slope = (multiplier(&off, 8.0) - multiplier(&off, 4.0)) / 4.0;
        assert!((slope - PARTICIPATION_SLOPE).abs() < 1e-15, "slope {slope}");
        let knee = multiplier(&off, 1e9) / slope;
        assert!((knee - PARTICIPATION_KNEE).abs() < 1e-9, "knee {knee}");
        // The floor is not an independent constant either: it is what the
        // same line reaches at four thirds.
        let floor_crossing = multiplier(&off, 1e-9) / slope;
        assert!(
            (floor_crossing - 4.0 / 3.0).abs() < 1e-9,
            "floor crossing {floor_crossing}"
        );
    }

    #[test]
    fn the_measured_law_leaves_the_band_between_the_clamps_untouched() {
        // The whole claim of the fix, stated as an equality: the shipped
        // law is already right where neither clamp binds, so the change is
        // confined to the two tails. Bit for bit, not approximately.
        let off = crate::params::PT_V16;
        let on = law_on();
        for phi in [1.4, 2.0, 5.0, 9.0, 9.999] {
            assert_eq!(multiplier(&off, phi), multiplier(&on, phi), "phi {phi}");
        }
        // Outside it they differ in OPPOSITE directions, which is the part
        // the issue's framing as saturation misses. The floor made small
        // orders too expensive; the ceiling made large ones too cheap.
        assert!(multiplier(&on, 0.1) < multiplier(&off, 0.1));
        assert!(multiplier(&on, 100.0) > multiplier(&off, 100.0));
    }

    #[test]
    fn the_measured_law_keeps_responding_above_the_knee() {
        // The test the shipped pair should have been. It fails if the
        // exponent above the knee is zero, which is what the `min` gave,
        // and it fails just as loudly at any other clamp, because a higher
        // ceiling is still a ceiling.
        //
        // One half is not chosen here. Toth et al. (Physical Review X 1,
        // 021006, 2011) measure it for orders large against available
        // volume; the citation and the reason the two regimes are one law
        // sit on `ModelParams::order_flow_impact_law`.
        let on = law_on();
        for phi in [11.0, 50.0, 1_000.0, 100_000.0] {
            let k = exponent(&on, phi);
            assert!((k - 0.5).abs() < 1e-12, "phi {phi} gave exponent {k}");
        }
        // Unbounded, so no two sizes are ever the same order to the model.
        // A hundredfold larger order costs ten times more, at any size.
        let ratio = multiplier(&on, 1e6) / multiplier(&on, 1e4);
        assert!((ratio - 10.0).abs() < 1e-9, "{ratio}");
    }

    #[test]
    fn the_measured_law_is_linear_below_the_knee_all_the_way_down() {
        // Cont, Kukanov and Stoikov (Journal of Financial Econometrics
        // 12(1), 2014) give exponent one at this scale, and the shipped
        // floor gives zero below four thirds. Asserted across four decades,
        // so a floor reintroduced anywhere in that range fails here.
        let on = law_on();
        for phi in [1e-4, 1e-3, 1e-2, 0.1, 0.5, 1.0, 4.0] {
            let k = exponent(&on, phi);
            assert!((k - 1.0).abs() < 1e-12, "phi {phi} gave exponent {k}");
        }
    }

    #[test]
    fn the_multiplier_is_finite_at_zero_participation() {
        // Not reachable through `order_imbalance_with` today, which returns
        // early on zero volume. This guards the law itself, because the
        // early return is not what the digests rest on: the call site
        // multiplies a literal zero by whatever comes back, and zero times
        // an infinity is NaN. A division or a logarithm added to the law
        // fails here rather than in a trajectory nobody re-runs.
        let m = participation_multiplier(0.0);
        assert!(m.is_finite(), "{m}");
        let product = 0.0 * m;
        assert_eq!(product, 0.0);
        assert!(product.is_sign_positive(), "{product}");
    }

    #[test]
    fn the_two_branches_meet_at_the_knee() {
        // Continuous by construction and not by arrangement: `sqrt(1)` is
        // exactly 1.0, so the square-root branch evaluates to the linear
        // branch's value at the crossover with no constant matched by hand.
        assert_eq!(
            participation_multiplier(PARTICIPATION_KNEE),
            PARTICIPATION_SLOPE * PARTICIPATION_KNEE
        );
        let above = participation_multiplier(PARTICIPATION_KNEE * (1.0 + 1e-12));
        let below = participation_multiplier(PARTICIPATION_KNEE * (1.0 - 1e-12));
        assert!((above - below).abs() < 1e-9, "{above} vs {below}");
    }

    #[test]
    fn the_measured_law_never_stops_responding_to_size() {
        // Monotone strictly increasing across nine decades of
        // participation. The shipped law fails this at both ends, and the
        // second assertion keeps this test honest by requiring that it
        // does -- otherwise a change that flattened BOTH laws would leave
        // the first assertion passing on a function that never moves.
        let on = law_on();
        let off = crate::params::PT_V16;
        let mut phi = 1e-4;
        let mut ties_off = 0;
        while phi < 1e5 {
            let next = phi * 2.0;
            assert!(
                multiplier(&on, next) > multiplier(&on, phi),
                "measured law flat between {phi} and {next}"
            );
            if multiplier(&off, next) == multiplier(&off, phi) {
                ties_off += 1;
            }
            phi = next;
        }
        assert!(
            ties_off > 0,
            "the shipped law is supposed to be the one that goes flat"
        );
    }

    #[test]
    fn every_shipped_preset_runs_the_shipped_law() {
        // The dial ships at 0.0 everywhere, so adding it moved no
        // trajectory. Asserted against the presets themselves rather than
        // argued from the branch, and it will fail the day a preset turns
        // the law on -- which is the day the change stops being free.
        // pt-v21 turned it on at 0.10.0, so injected order flow costs
        // differently on the default from then; every preset before it
        // still runs the clamped linear law.
        for name in crate::params::ModelParams::preset_names() {
            let p = crate::params::ModelParams::preset(name).expect("named");
            // pt-v22's values are its arm's, which `PT_V22_DIGEST_PREFIX`
            // and tests/test_validation.py hold as a whole.
            if *name == "pt-v22" {
                continue;
            }
            let want = if *name == "pt-v21" { 1.0 } else { 0.0 };
            assert_eq!(p.order_flow_impact_law, want, "{name}");
        }
    }

    #[test]
    fn the_dial_at_zero_is_the_shipped_function_bit_for_bit() {
        let off = crate::params::PT_V16;
        for (b, s, av) in [
            (10_000.0, 0.0, 50_000.0),
            (0.0, 10_000.0, 50_000.0),
            (1e6, 1e6, 1e6),
            (0.0, 0.0, 1e6),
            (1000.0, 0.0, 0.0),
            (3.0, 7.0, 1e9),
            (1e9, 1.0, 1e6),
        ] {
            assert_eq!(
                order_imbalance_with(&off, b, s, av),
                order_imbalance(b, s, av),
                "{b} {s} {av}"
            );
        }
    }

    #[test]
    fn no_injected_flow_is_bit_identical_under_either_law() {
        // Why the known-answer digests do not move. Every
        // `TickInputs.order_volumes` outside the two `order_flow=` paths is
        // the empty slice, so the tick reads a default `OrderVolume` and
        // calls this with two zeros.
        //
        // The SIGN is the assertion, not the value. A `-0.0` reaching an
        // accumulator is the one way a term that is arithmetically nothing
        // can still move a trajectory, and the two laws arrive at zero by
        // different routes -- one multiplies by a floor of 0.2, the other
        // by a slope of 0.0.
        let on = law_on();
        let off = crate::params::PT_V16;
        for (label, p) in [("measured", &on), ("shipped", &off)] {
            let out = order_imbalance_with(p, 0.0, 0.0, 1e6);
            assert_eq!(out, 0.0, "{label}");
            assert!(out.is_sign_positive(), "{label} returned {out}");
        }
    }

    #[test]
    fn the_measured_law_keeps_the_direction_and_neutrality_of_the_shipped_one() {
        // The properties the two shipped unit tests above assert, re-checked
        // under the new law. Neither of them fails under it, because both
        // are about direction and neutrality rather than about the clamps --
        // but that is a fact worth a test rather than a claim in a report.
        let on = law_on();
        let thin = order_imbalance_with(&on, 10_000.0, 0.0, 50_000.0);
        let liquid = order_imbalance_with(&on, 10_000.0, 0.0, 500e6);
        assert!(thin > liquid, "{thin} vs {liquid}");
        assert_eq!(order_imbalance_with(&on, 1e6, 1e6, 1e6), 0.0);
        assert_eq!(order_imbalance_with(&on, 0.0, 0.0, 1e6), 0.0);
        assert_eq!(
            order_imbalance_with(&on, 1000.0, 0.0, 0.0),
            order_imbalance_with(&on, 1000.0, 0.0, 1_000_000.0)
        );
        // Selling is the mirror of buying at every size, under a law that
        // now has two branches to get that wrong in.
        for phi in [0.5, 5.0, 500.0] {
            assert_eq!(
                order_imbalance_with(&on, 0.0, phi * 1000.0, 390_000.0),
                -order_imbalance_with(&on, phi * 1000.0, 0.0, 390_000.0),
                "phi {phi}"
            );
        }
    }

    // -- The depth law -----------------------------------------------------
    //
    // `order_imbalance` is already participation, flow over the name's own
    // minute volume. The shipped `calculate_live_factors` then divides by a
    // minute volume a second time, so at equal participation the impact
    // falls as depth and at a fixed share count as depth squared.
    // `order_flow_depth_law` at 1.0 divides once. The tests below read the
    // exponents off the function's own output rather than off the source.

    fn depth_on(p: &crate::params::ModelParams) -> crate::params::ModelParams {
        p.with_override("order_flow_depth_law", 1.0).unwrap()
    }

    /// The four combinations of the two switches, labelled.
    fn four_laws() -> Vec<(&'static str, crate::params::ModelParams)> {
        let shipped = crate::params::PT_V16;
        let sqrt = law_on();
        let (shipped_once, sqrt_once) = (depth_on(&shipped), depth_on(&sqrt));
        vec![
            ("shipped", shipped),
            ("depth once", shipped_once),
            ("square root", sqrt),
            ("square root, depth once", sqrt_once),
        ]
    }

    /// A name whose two depth definitions agree. Half a per cent of its
    /// shares is half its average volume, so the shipped
    /// `liquidity_factor` divides by the same minute volume the
    /// participation term does, and any exponent read off it is the law's.
    fn named(avg_volume: f64) -> FactorCompany {
        let mut c = company();
        c.avg_volume = avg_volume;
        c.shares_outstanding = avg_volume * 100.0;
        c
    }

    /// The minute volume the participation term divides by.
    fn minute_of(c: &FactorCompany) -> f64 {
        (c.avg_volume / 390.0).max(100.0)
    }

    /// One tick's order flow carried through both functions the tick calls:
    /// the participation term, then the factor that scales it.
    fn flow_impact(p: &crate::params::ModelParams, c: &FactorCompany, buy: f64, sell: f64) -> f64 {
        let imbalance = order_imbalance_with(p, buy, sell, c.avg_volume);
        factors_with(p, c, &[], imbalance, &shared()).order_flow_impact
    }

    /// Least-squares slope of `ln y` on `ln x`.
    fn log_slope(xs: &[f64], ys: &[f64]) -> f64 {
        let lx: Vec<f64> = xs.iter().map(|x| x.ln()).collect();
        let ly: Vec<f64> = ys.iter().map(|y| y.ln()).collect();
        let mx = lx.iter().sum::<f64>() / lx.len() as f64;
        let my = ly.iter().sum::<f64>() / ly.len() as f64;
        let num: f64 = lx.iter().zip(&ly).map(|(x, y)| (x - mx) * (y - my)).sum();
        let den: f64 = lx.iter().map(|x| (x - mx) * (x - mx)).sum();
        num / den
    }

    /// Thin, medium and mega-cap: minute volumes of 154, 6,154 and 230,769
    /// shares, three and a half orders of magnitude, all above the
    /// 100-share floor.
    const DEPTHS: [f64; 3] = [60_000.0, 2_400_000.0, 90_000_000.0];

    #[test]
    fn at_equal_participation_the_corrected_law_does_not_depend_on_depth() {
        // Participation is the dimensionless quantity, so once depth is
        // divided out once the same participation is the same impact on
        // every name: exponent 0. The shipped law divides twice and keeps
        // exponent -1. Read at a participation under the floor, one in the
        // band and one past the knee, under both participation laws.
        //
        // The tolerance is rounding only. This is `order_flow_impact`
        // itself, before the cent grid, the breaker or any price, and the
        // three values differ by at most an ulp of `phi * v / v`.
        for (label, p) in four_laws() {
            let depth_once = p.order_flow_depth_law != 0.0;
            for phi in [0.5, 5.0, 50.0] {
                let names: Vec<FactorCompany> = DEPTHS.iter().map(|&v| named(v)).collect();
                let minutes: Vec<f64> = names.iter().map(minute_of).collect();
                let out: Vec<f64> = names
                    .iter()
                    .map(|c| flow_impact(&p, c, phi * minute_of(c), 0.0))
                    .collect();
                let k = log_slope(&minutes, &out);
                let expected = if depth_once { 0.0 } else { -1.0 };
                assert!((k - expected).abs() < 1e-12, "{label}, phi {phi}: exponent {k}");
            }
        }
    }

    #[test]
    fn at_a_fixed_share_count_the_corrected_law_falls_as_depth_and_the_shipped_one_as_its_square() {
        // The same order in shares, which is a different participation on
        // each name. Under the square-root participation law every name
        // here is below the knee, where the law is linear, so the exponent
        // is the depth law's alone: -1 dividing once, -2 dividing twice.
        // (Under the shipped participation law the clamps bind on two of
        // the three names and no single exponent exists.)
        let sqrt = law_on();
        let names: Vec<FactorCompany> = DEPTHS.iter().map(|&v| named(v)).collect();
        let minutes: Vec<f64> = names.iter().map(minute_of).collect();
        for (p, expected) in [(depth_on(&sqrt), -1.0), (sqrt, -2.0)] {
            let out: Vec<f64> = names.iter().map(|c| flow_impact(&p, c, 1_000.0, 0.0)).collect();
            let k = log_slope(&minutes, &out);
            assert!((k - expected).abs() < 1e-12, "expected {expected}, got {k}");
        }
    }

    #[test]
    fn the_corrected_law_is_the_shipped_one_at_the_reference_liquidity() {
        // The restatement of `order_flow_coefficient`: removing one power
        // of depth needs a depth to remove it at, and the corrected law
        // takes the one `order_imbalance` already assumes for a name that
        // reports no volume. A name AT that volume is charged the same, to
        // the bit, under every participation law.
        let c = named(REFERENCE_DAILY_VOLUME);
        for (label, p) in four_laws() {
            let q = if p.order_flow_impact_law != 0.0 { law_on() } else { crate::params::PT_V16 };
            for (b, s) in [(10.0, 0.0), (5_000.0, 1_000.0), (0.0, 25_641.0), (1e9, 3.0)] {
                assert_eq!(
                    flow_impact(&p, &c, b, s).to_bits(),
                    flow_impact(&q, &c, b, s).to_bits(),
                    "{label} at {b}/{s}"
                );
            }
        }
    }

    #[test]
    fn the_reference_liquidity_is_the_fallback_the_participation_term_uses() {
        // Recovered from `order_imbalance`, so the constant cannot drift
        // from the literal it names.
        assert_eq!(
            order_imbalance(5_000.0, 0.0, 0.0),
            order_imbalance(5_000.0, 0.0, REFERENCE_DAILY_VOLUME)
        );
        assert_ne!(
            order_imbalance(5_000.0, 0.0, 0.0),
            order_imbalance(5_000.0, 0.0, REFERENCE_DAILY_VOLUME * 1.01)
        );
    }

    #[test]
    fn the_depth_switch_rescales_and_never_reshapes_the_participation_law() {
        // The two switches are independent. At a given name the depth law
        // multiplies the participation term by a constant, so the clamps of
        // the shipped participation law sit exactly where they did (just
        // below and above 4/3 and 10) and the square-root law's knee too.
        for avg in DEPTHS {
            let c = named(avg);
            let v = minute_of(&c);
            let scale = v / (REFERENCE_DAILY_VOLUME / 390.0);
            for base in [crate::params::PT_V16, law_on()] {
                let on = depth_on(&base);
                for phi in [
                    1e-6,
                    4.0 / 3.0 * (1.0 - 1e-9),
                    4.0 / 3.0 * (1.0 + 1e-9),
                    1.0,
                    9.999,
                    10.0,
                    10.0 * (1.0 + 1e-9),
                    1e6,
                ] {
                    let off_val = flow_impact(&base, &c, phi * v, 0.0);
                    let on_val = flow_impact(&on, &c, phi * v, 0.0);
                    let ratio = on_val / off_val;
                    assert!(
                        (ratio / scale - 1.0).abs() < 1e-14,
                        "avg {avg} phi {phi}: ratio {ratio} against {scale}"
                    );
                }
                // The shipped clamps survive the switch.
                if base.order_flow_impact_law == 0.0 {
                    assert_eq!(
                        flow_impact(&on, &c, 1e-6 * v, 0.0),
                        flow_impact(&on, &c, 4.0 / 3.0 * (1.0 - 1e-9) * v, 0.0)
                    );
                    assert!(
                        flow_impact(&on, &c, 4.0 / 3.0 * (1.0 + 1e-9) * v, 0.0)
                            > flow_impact(&on, &c, 4.0 / 3.0 * (1.0 - 1e-9) * v, 0.0)
                    );
                    assert_eq!(
                        flow_impact(&on, &c, 10.0 * v, 0.0),
                        flow_impact(&on, &c, 1e6 * v, 0.0)
                    );
                    assert!(flow_impact(&on, &c, 9.999 * v, 0.0) < flow_impact(&on, &c, 10.0 * v, 0.0));
                }
            }
        }
    }

    #[test]
    fn no_flow_is_positive_zero_under_every_combination() {
        // What keeps an untraded run bit-identical with either switch on:
        // the participation term returns `+0.0` and the depth law
        // multiplies it by a positive finite number.
        for (label, p) in four_laws() {
            for avg in [0.0, 30_000.0, 1e6, 9e7] {
                let out = flow_impact(&p, &named(avg), 0.0, 0.0);
                assert_eq!(out.to_bits(), 0.0f64.to_bits(), "{label} at {avg}: {out}");
            }
        }
    }

    #[test]
    fn a_zero_average_volume_reads_the_reference_name_under_the_corrected_law() {
        // The shipped law reads TWO depths and they disagree here: the
        // participation term falls through to a million shares a day, and
        // `liquidity_factor` takes half a per cent of the shares
        // outstanding. The corrected law reads only the first, so a name
        // that reports no volume is the reference name, whatever its share
        // count.
        let mut zero = company();
        zero.avg_volume = 0.0;
        for shares in [1e6, 1e8, 1e10] {
            zero.shares_outstanding = shares;
            for (b, s) in [(2_000.0, 0.0), (0.0, 40_000.0)] {
                let shipped = flow_impact(&crate::params::PT_V16, &zero, b, s);
                let corrected = flow_impact(&depth_on(&crate::params::PT_V16), &zero, b, s);
                let reference = flow_impact(&crate::params::PT_V16, &named(REFERENCE_DAILY_VOLUME), b, s);
                assert_eq!(corrected, reference, "{shares}");
                let liquid = mathx::max((shares * 0.005) / 390.0, 100.0);
                let expected = order_imbalance(b, s, 0.0)
                    * (1.0 / liquid)
                    * ORDER_FLOW_COEFFICIENT
                    * INFORMED_FLOW_FRACTION;
                assert_eq!(shipped, expected, "{shares}");
            }
        }
    }

    #[test]
    fn below_the_minute_floor_every_name_is_the_floor_name() {
        // `order_imbalance` floors the minute volume at 100 shares, which
        // is a daily volume of 39,000. Under both depth laws a thinner name
        // is charged as if it traded that much, so the same shares cost the
        // same on every name below the floor.
        for (label, p) in four_laws() {
            let at_floor = flow_impact(&p, &named(39_000.0), 500.0, 0.0);
            for avg in [1.0, 2_000.0, 20_000.0, 38_999.0] {
                assert_eq!(flow_impact(&p, &named(avg), 500.0, 0.0), at_floor, "{label} at {avg}");
            }
        }
        // So the corrected law's independence from depth stops at the
        // floor: at the same TRUE participation a sub-floor name is charged
        // less than a liquid one, because its participation is understated.
        let on = depth_on(&crate::params::PT_V16);
        let thin = named(10_000.0);
        let true_minute = thin.avg_volume / 390.0;
        let liquid = named(2_400_000.0);
        assert!(
            flow_impact(&on, &thin, 5.0 * true_minute, 0.0)
                < flow_impact(&on, &liquid, 5.0 * minute_of(&liquid), 0.0)
        );
    }

    #[test]
    fn a_nan_average_volume_reaches_only_the_shipped_depth_law() {
        // Refused at the Python boundary; a Rust caller can still build
        // one. The participation term falls through a NaN to the fallback,
        // and `liquidity_factor` propagates it. The corrected law reads
        // only the first.
        let mut c = company();
        c.avg_volume = f64::NAN;
        assert!(flow_impact(&crate::params::PT_V16, &c, 1_000.0, 0.0).is_nan());
        let corrected = flow_impact(&depth_on(&crate::params::PT_V16), &c, 1_000.0, 0.0);
        assert_eq!(corrected, flow_impact(&crate::params::PT_V16, &named(REFERENCE_DAILY_VOLUME), 1_000.0, 0.0));
    }

    #[test]
    fn nan_flow_is_what_each_participation_law_already_made_of_it() {
        // The depth law adds no NaN of its own and removes none: under the
        // shipped participation law a NaN volume reaches the impact, under
        // the square-root law the early return makes it zero, and the depth
        // switch leaves both as they were. The boundary refuses NaN flow
        // before it gets here.
        for (label, p) in four_laws() {
            let out = flow_impact(&p, &named(1e6), f64::NAN, 0.0);
            if p.order_flow_impact_law == 0.0 {
                assert!(out.is_nan(), "{label}: {out}");
            } else {
                assert_eq!(out, 0.0, "{label}: {out}");
            }
        }
    }

    #[test]
    fn a_flow_too_large_to_sum_stays_finite_under_every_law() {
        // Each side finite, so the boundary accepts it, and their sum past
        // the largest double. The square-root law used to return NaN here:
        // the total overflowed, the raw imbalance read 0/inf, and the
        // unbounded multiplier made that 0 * inf. A NaN reaching `s` is a
        // NaN price.
        let c = named(1e6);
        for (label, p) in four_laws() {
            for (b, s) in [(1e308, 1e308), (1.5e308, 0.5e308), (1e308, 0.0), (0.0, 1.7e308)] {
                let out = flow_impact(&p, &c, b, s);
                assert!(out.is_finite(), "{label} at {b}/{s}: {out}");
            }
            // Balanced flow is neutral at any size.
            assert_eq!(flow_impact(&p, &c, 1e308, 1e308), 0.0, "{label}");
        }
        // Under the square-root law the direction survives the overflow.
        let sqrt = law_on();
        assert!(flow_impact(&sqrt, &c, 1.5e308, 0.5e308) > 0.0);
        assert!(flow_impact(&sqrt, &c, 0.5e308, 1.5e308) < 0.0);
    }

    #[test]
    fn the_corrected_law_is_monotone_in_size_and_symmetric_in_sign() {
        // Under the square-root participation law, strictly increasing
        // across nine decades of participation, on a thin and a mega-cap
        // name; under the shipped one, never decreasing. Selling is the
        // exact mirror of buying under every combination.
        for (label, p) in four_laws() {
            for avg in [60_000.0, 90_000_000.0] {
                let c = named(avg);
                let v = minute_of(&c);
                let mut phi = 1e-4;
                while phi < 1e5 {
                    let (a, b) = (flow_impact(&p, &c, phi * v, 0.0), flow_impact(&p, &c, 2.0 * phi * v, 0.0));
                    if p.order_flow_impact_law != 0.0 {
                        assert!(b > a, "{label} at {avg}: flat between {phi} and {}", 2.0 * phi);
                    } else {
                        assert!(b >= a, "{label} at {avg}: falls between {phi} and {}", 2.0 * phi);
                    }
                    assert_eq!(
                        flow_impact(&p, &c, 0.0, phi * v).to_bits(),
                        (-a).to_bits(),
                        "{label} at {avg}, phi {phi}"
                    );
                    phi *= 2.0;
                }
            }
        }
    }

    #[test]
    fn every_shipped_preset_divides_by_depth_twice() {
        // The switch ships at 0.0 everywhere. This fails the day a preset
        // turns it on, which is the day order-flow costs change for every
        // caller who injects flow. pt-v21 turned it on at 0.10.0; every
        // preset before it divides twice.
        for name in crate::params::ModelParams::preset_names() {
            let p = crate::params::ModelParams::preset(name).expect("named");
            // pt-v22's values are its arm's, which `PT_V22_DIGEST_PREFIX`
            // and tests/test_validation.py hold as a whole.
            if *name == "pt-v22" {
                continue;
            }
            let want = if *name == "pt-v21" { 1.0 } else { 0.0 };
            assert_eq!(p.order_flow_depth_law, want, "{name}");
        }
    }

    // ── Forced flow ───────────────────────────────────────────────────────

    #[test]
    fn a_heavily_shorted_name_rallying_gets_both_the_squeeze_and_the_buy_cascade() {
        // The two blocks are deliberately NOT exclusive.
        let mut c = company();
        c.short_interest = 3e7; // 30% of float
        c.float = 1e8;
        c.last_daily_return = Some(0.08);
        let out = factors(&c, &[], 0.0, &shared()).short_squeeze_effect;
        // squeeze = min(0.02, 0.3 * 0.08 * 0.5) = 0.012, plus 0.006 cascade
        assert!((out - 0.018).abs() < 1e-12, "got {out}");
    }

    #[test]
    fn the_squeeze_saturates_rather_than_running_away() {
        let mut c = company();
        c.short_interest = 9e7;
        c.float = 1e8;
        c.last_daily_return = Some(0.9);
        let out = factors(&c, &[], 0.0, &shared()).short_squeeze_effect;
        // 0.02 cap plus the 0.006 cascade — bounded, not proportional to 90%.
        assert!(out <= 0.02 + 0.006 + 1e-12, "got {out}");
    }

    #[test]
    fn a_falling_price_produces_downward_pressure_in_widening_steps() {
        let mut c = company();
        let at = |c: &mut FactorCompany, r: f64| {
            c.last_daily_return = Some(r);
            factors(c, &[], 0.0, &shared()).short_squeeze_effect
        };
        assert_eq!(
            at(&mut c, -0.01),
            0.0,
            "above the -2% trigger, nothing fires"
        );
        assert_eq!(at(&mut c, -0.025), -0.001);
        assert_eq!(at(&mut c, -0.04), -0.003);
        assert_eq!(at(&mut c, -0.06), -0.005);
        assert_eq!(at(&mut c, -0.08), -0.008);
    }

    #[test]
    fn forced_flow_reacts_to_yesterday_not_today() {
        // `last_daily_return` is the previous COMPLETED day. If today's move
        // fed this, a fall would deepen itself within the session — the
        // runaway the comment in the source describes.
        let mut c = company();
        c.last_daily_return = None;
        assert_eq!(factors(&c, &[], 0.0, &shared()).short_squeeze_effect, 0.0);
    }

    // ── Noise ─────────────────────────────────────────────────────────────

    #[test]
    fn the_shared_market_factor_reaches_every_stock_through_beta() {
        let mut s = shared();
        s.market_factor = 0.001;
        let mut high_beta = company();
        high_beta.beta = Some(2.0);
        let low_beta = company();
        assert!(
            factors(&high_beta, &[], 0.0, &s).random_noise
                > factors(&low_beta, &[], 0.0, &s).random_noise
        );
    }

    #[test]
    fn a_crash_sized_market_shock_amplifies_the_market_loading() {
        // Below the 2-sigma threshold the loading is linear in the factor;
        // above it, it steepens. Diversification stops working in a crash.
        // Denominated in the CURRENT sigma, so the test keeps meaning
        // "2 standard deviations of the factor" across recalibrations.
        let tick_scale = crate::market::tick::MARKET_FACTOR_SIGMA / (390.0f64).sqrt();
        let c = company();
        let noise_at = |mult: f64| {
            let mut s = shared();
            s.market_factor = tick_scale * mult;
            factors(&c, &[], 0.0, &s).random_noise
        };
        let linear = noise_at(1.0);
        let amplified = noise_at(4.0);
        // 4x the shock would be 4x the noise if linear; the amplifier makes
        // it more than that.
        assert!(amplified > linear * 4.0, "{amplified} vs {}", linear * 4.0);
    }

    #[test]
    fn the_amplifier_is_denominated_in_absolute_units_so_regimes_move_its_rate() {
        // The deliberate half of the crash amplifier's denomination since
        // the factor-variance process: the threshold is 2x the BASELINE
        // sigma in absolute units, so a tick that is ordinary for a
        // crisis regime (1.5 conditional sigmas, but 3 baseline sigmas
        // when the regime runs at twice baseline) IS amplified, and the
        // same conditional multiple is amplified MORE in a hotter regime.
        // That regime-dependence is the measured crisis-correlation
        // channel, not a mis-denomination; see the comment at the
        // amplifier for the panel cost of the constant-rate alternative.
        let base_tick = crate::market::tick::MARKET_FACTOR_SIGMA / 390.0f64.sqrt();
        let c = company();
        let amplifier_at = |factor: f64| {
            let mut s = shared();
            s.market_factor = factor;
            // Divide the market component back out to expose the
            // amplifier itself: noise = beta*factor*amp with zero sector
            // and (Fixed(0)) zero idiosyncratic terms.
            factors(&c, &[], 0.0, &s).random_noise / s.market_factor
        };
        // 1.5 conditional sigmas of a 2x-baseline regime = 3 baseline
        // sigmas: amplified.
        assert!(amplifier_at(base_tick * 2.0 * 1.5) > 1.0);
        // The same 1.5-conditional-sigma tick of a HALF-baseline (calm,
        // floored) regime is nowhere near the absolute threshold: silent.
        assert_eq!(amplifier_at(base_tick * 0.5 * 1.5), 1.0);
    }

    /// **AND THE SWITCH TAKES THAT REGIME-DEPENDENCE OUT, WHICH IS THE
    /// WHOLE OF IT.**
    ///
    /// The test above is this dial's own negative: at 0.0 the same
    /// conditional multiple reads differently in two regimes, and above
    /// 0.0 it must read IDENTICALLY, because the normaliser is the sigma
    /// the draw used. That is what makes `E[z^2 A^2]` constant in the
    /// regime in `market::index_var::amplifier_moments`, and it is the
    /// stability condition's whole content.
    ///
    /// Asserted on BITS across three regimes spanning a factor of forty in
    /// variance, not to a tolerance: the claim is that the regime ratio
    /// divides out of the expression, and an expression it divides out of
    /// returns the same double.
    #[test]
    fn the_conditional_normaliser_fires_at_the_same_multiple_in_every_regime() {
        let base_tick = crate::market::tick::MARKET_FACTOR_SIGMA / 390.0f64.sqrt();
        let c = company();
        let mut p = crate::params::PT_V1;
        p.crash_amplifier_conditional_sigma = 1.0;
        // `z` in conditional sigmas, and the regime the tick was drawn in.
        let amplifier_at = |z: f64, regime: f64| {
            let mut s = shared();
            s.market_sigma_tick = base_tick * regime;
            s.market_factor = z * s.market_sigma_tick;
            factors_with(&p, &c, &[], 0.0, &s).random_noise / s.market_factor
        };
        for &z in &[0.5, 1.5, 1.99, 2.0, 2.5, 4.0, 7.0] {
            let at_base = amplifier_at(z, 1.0);
            for &regime in &[0.3, 0.5, 2.0, 6.3] {
                assert_eq!(
                    amplifier_at(z, regime), at_base,
                    "z {z} reads differently at regime {regime}: the regime \
                     ratio did not divide out");
            }
        }
        // And it is the amplifier being read and not a constant: the
        // threshold is 2.0 baseline sigmas, so a 1.99-sigma tick is silent
        // and a 2.5-sigma one is not, in EVERY regime.
        assert_eq!(amplifier_at(1.99, 6.3), 1.0);
        assert!(amplifier_at(2.5, 0.3) > 1.0);
        // A regime with no width at all cannot produce an extreme tick.
        // 0/0 would be NaN and would propagate into every name's price;
        // the guard makes it the no-amplifier reading instead.
        let mut dead = shared();
        dead.market_sigma_tick = 0.0;
        dead.market_factor = 0.0;
        assert_eq!(factors_with(&p, &c, &[], 0.0, &dead).random_noise, 0.0);
    }

    #[test]
    fn a_small_cap_carries_more_idiosyncratic_noise_than_a_mega_cap() {
        assert_eq!(cap_size_multiplier(100e9), 0.8);
        assert_eq!(cap_size_multiplier(20e9), 1.0);
        assert_eq!(cap_size_multiplier(5e9), 1.3);
        assert_eq!(cap_size_multiplier(0.5e9), 1.6);

        let mut small = company();
        small.market_cap = 0.5e9;
        let mut mega = company();
        mega.market_cap = 100e9;
        let mut rng = Fixed(1.0);
        let s = calculate_live_factors(&small, &[], 0.0, 1.0, &shared(), &crate::params::PT_V1, &mut rng).random_noise;
        let mut rng = Fixed(1.0);
        let m = calculate_live_factors(&mega, &[], 0.0, 1.0, &shared(), &crate::params::PT_V1, &mut rng).random_noise;
        assert!(s > m, "small-cap noise {s} should exceed mega-cap {m}");
    }

    #[test]
    fn the_idio_beta_exponent_is_inert_at_zero_and_disperses_when_it_is_not() {
        // With every shared factor at zero, `random_noise` IS the
        // idiosyncratic term -- beta reaches it only through the new dial,
        // so this isolates the mechanism rather than the factor structure.
        let noise = |p: &crate::params::ModelParams, beta: f64| {
            let mut c = company();
            c.beta = Some(beta);
            let mut rng = Fixed(1.0);
            calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), p, &mut rng).random_noise
        };

        // Inert: the shipped preset leaves the exponent at zero, so a
        // defensive name and an aggressive one carry identical idiosyncratic
        // noise and every preset's tape is bit-unchanged.
        let off = crate::params::PT_V1;
        assert_eq!(off.idio_sigma_beta_exponent, 0.0);
        assert_eq!(noise(&off, 0.6), noise(&off, 1.8));

        // Engaged: the same two names now differ, and in the right order.
        let mut on = crate::params::PT_V1;
        on.idio_sigma_beta_exponent = 2.0;
        let (lo, hi) = (noise(&on, 0.6), noise(&on, 1.8));
        assert!(hi > lo, "beta 1.8 noise {hi} should exceed beta 0.6 noise {lo}");
        // Beta 1.0 is the pivot: 1^k is 1 for every k, so it cannot move.
        assert_eq!(noise(&on, 1.0), noise(&off, 1.0));

        // The exponent form exists because the linear one it replaced drove
        // low-beta names to EXACTLY zero. Every positive beta must stay
        // audible however steep the exponent gets.
        let mut steep = crate::params::PT_V1;
        steep.idio_sigma_beta_exponent = 8.0;
        let quiet = noise(&steep, 0.3);
        assert!(quiet > 0.0, "a defensive name went silent at {quiet}");

        // A non-positive beta would be NaN under `pow` with a fractional
        // exponent. It falls back to the homogeneous scale instead.
        assert_eq!(noise(&on, -0.5), noise(&off, -0.5));
        assert!(noise(&on, -0.5).is_finite());
    }

    #[test]
    fn the_crisis_variance_damp_is_inert_at_zero_and_flattens_when_it_is_not() {
        // With a crisis spike present, the injection scales with the market
        // factor's magnitude. The damp is meant to remove that dependence,
        // so the test is whether DOUBLING the factor still doubles the
        // injection's share of the result.
        let injected = |p: &crate::params::ModelParams, mf: f64| {
            let mut sh = shared();
            sh.market_factor = mf;
            sh.crisis_spike = 0.8;
            let mut rng = Fixed(0.0);           // no idiosyncratic noise
            calculate_live_factors(&company(), &[], 0.0, 1.0, &sh, p, &mut rng)
                .random_noise
        };

        let off = crate::params::PT_V12;
        assert_eq!(off.crisis_blend_variance_damp, 0.0);

        // NOT a linearity test. `crash_amplifier` is itself non-linear in
        // the market factor, so doubling the factor already more than
        // doubles the shipped response -- 2.85x, not 2x. The claim is only
        // that damping makes the response LESS sensitive to the factor's
        // size, so the two ratios are compared against each other rather
        // than against an assumed slope.
        let shipped = injected(&off, 0.002) / injected(&off, 0.001);
        assert!(shipped > 1.0, "shipped response does not rise: {shipped}");

        let mut on = crate::params::PT_V12;
        on.crisis_blend_variance_damp = 1.0;
        let damped = injected(&on, 0.002) / injected(&on, 0.001);
        assert!(damped < shipped,
                "damp did not flatten the response: {damped} against {shipped}");
        assert!(damped > 1.0, "damp inverted the response: {damped}");

        // And it is bit-inert at zero: the same preset, spelled explicitly.
        let mut zero = crate::params::PT_V12;
        zero.crisis_blend_variance_damp = 0.0;
        assert_eq!(injected(&zero, 0.0015).to_bits(),
                   injected(&off, 0.0015).to_bits());
    }

    #[test]
    fn the_garch_variance_floor_stops_a_dead_stock_freezing() {
        // A zero variance would make sigma zero and the price would stop
        // moving entirely; `idio_sigma_floor` prevents that, and ships at
        // the 1e-4 this test was written against.
        let mut c = company();
        c.garch_variance = 0.0;
        let mut rng = Fixed(1.0);
        let out = calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), &crate::params::PT_V1, &mut rng).random_noise;
        assert!(out > 0.0, "noise collapsed to {out}");
    }

    /// The floor is READ FROM THE FIELD, not from a constant beside it.
    ///
    /// Both this site and the overnight path in `engine.rs` spelled the
    /// same 1e-4 inline, and a floor spelled twice is a floor that moves
    /// once. This asserts the tick's copy follows the field; the overnight
    /// copy has its own assertion in `engine.rs`.
    #[test]
    fn the_idio_sigma_floor_is_the_parameter_and_not_a_constant() {
        let mut c = company();
        // Well under the shipped 1e-4, so the floor decides at the default
        // and the recursion's own value decides once the floor is removed.
        c.garch_variance = 1.0e-6;
        let base = crate::params::PT_V1;
        let mut lifted = crate::params::PT_V1;
        lifted.idio_sigma_floor = 0.0;
        let mut r1 = Fixed(1.0);
        let mut r2 = Fixed(1.0);
        let floored = calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), &base, &mut r1).random_noise;
        let free = calculate_live_factors(&c, &[], 0.0, 1.0, &shared(), &lifted, &mut r2).random_noise;
        // sqrt(1e-4) against sqrt(1e-6) is a factor of ten in sigma, and
        // the noise is linear in sigma, so the ratio is the evidence.
        assert!(free < floored, "removing the floor did not lower the noise: {free} vs {floored}");
        let ratio = floored / free;
        assert!(
            (ratio - 10.0).abs() < 1e-9,
            "expected the floor to be exactly the parameter, ratio {ratio}"
        );
    }
}