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
//! Arrow record batches, behind the `python` feature.
//!
//! # Why Arrow rather than returning arrays
//!
//! One seed at tick grain for 100 names over a trading year is roughly 9.8
//! million rows per table. Returning that as Python objects is not slow, it is
//! unusable. Returning it as raw bytes — which is what this package did before
//! — is usable but leaves the consumer to reconstruct types, names and null
//! masks by hand, and gets no further than NumPy.
//!
//! Arrow record batches handed over through the **C Data Interface** reach
//! polars, pandas, pyarrow and duckdb zero-copy, without this crate taking a
//! dependency on any of them. The consumer picks the tool; the library ships
//! buffers.
//!
//! # The dtype rule
//!
//! Every numeric column is `Float64`. There is no f32 option and there will
//! not be one. Bit-exactness is the product: the known-answer gate hashes
//! these buffers, and a half-precision "memory-saving" variant would be a
//! different market that happens to plot the same — a silent parity-breaking
//! switch sitting in the public API.
//!
//! Identifiers are the exception, and are integers rather than strings:
//! `instrument_id` is a `UInt32` index into the roster, not a repeated ticker.
//! At 9.8 million rows the difference between an index and a string per row is
//! the difference between a column and a memory problem.

#![allow(unexpected_cfgs, clippy::useless_conversion)]

use std::sync::Arc;

use arrow::array::{ArrayRef, Float64Array, RecordBatch, UInt32Array};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use arrow::ffi_stream::FFI_ArrowArrayStream;
use arrow::record_batch::RecordBatchReader;
use pyo3::prelude::*;
use pyo3::types::PyCapsule;

use crate::python::ValidationError;

/// `bars`: one row per (tick, instrument).
///
/// At tick grain a bar IS the print, so `close` and `volume` are the whole
/// story and there is no open/high/low to report that would not simply repeat
/// `close`. Emitting four identical columns to look like a candle would be
/// padding, and padding at ten million rows is expensive padding.
pub fn bars_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("tick", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("close", DataType::Float64, false),
        Field::new("volume", DataType::Float64, false),
    ]))
}

/// `truth`: the labelled-dataset table.
///
/// The distinguishing output, and the reason it is worth building a simulator
/// rather than downloading history. A historical dataset gives you a price. It
/// cannot give you the fair value that price was deviating from, and it cannot
/// give you how much of a move was company news rather than order-flow
/// pressure rather than noise -- because nobody knows. Here the simulator
/// computed each of those to produce the print, so it can report them.
///
/// One row per instrument per tick, joining to `bars` on
/// `(day, tick, instrument_id)`, and carrying three kinds of column.
///
/// **Levels.** `fundamental_value` is the valuation -- earnings, sector
/// anchor, rates -- with no mispricing in it. `anchor_price` is
/// `fundamental_value * exp(mispricing_s)`: the price the model wanted before
/// the order book touched it. The printed price in `bars` is what the book
/// actually settled, so `close - anchor_price` isolates the microstructure and
/// `mispricing_s` isolates the valuation gap. Three quantities that are easy
/// to conflate, kept apart on purpose.
///
/// **The decomposition.** Twelve columns, in `FACTOR_NAMES` order, giving
/// every contribution to this tick's change in `s`: the eight
/// `S_COMPONENT_KEYS`, then the daily jump and the overnight move, which
/// land outside the tick loop and are booked onto the row where each is
/// observed, then `fair_value_shift`, minus the part of the shocks that
/// moved the name's fair value instead of `s` (pt-v20's permanent share),
/// then `dividend`, the change in `s` at an ex-date open, booked onto the
/// day's first row (zero on every model without dividends). `reversion`, `momentum` and `crowd_lean` are the model's own
/// dynamics; `company_news`, `order_flow_impact`, `short_squeeze_effect`
/// and `random_noise` are the shocks. They sum to `Δs`.
///
/// That they SUM is what makes this a dataset rather than a commentary. A
/// consumer can difference `mispricing_s` across ticks, add the nine columns,
/// and check the label against the outcome instead of trusting it. Where the
/// residual is not zero, the `s` clamp or a circuit breaker bound -- which is
/// itself worth seeing, and would be invisible in a summary.
///
/// Per TICK rather than per day, which is the whole point. The day-level
/// accumulator behind `attribution()` can say order flow moved a price today;
/// it cannot say when, and a label that cannot be aligned to a bar is not a
/// label.
///
/// A company that did not tick has zeros across all seven: it did not move, so
/// nothing contributed to it, and `Δs` was zero. The two level columns instead
/// PERSIST from its last tick, because a valuation does not disappear when
/// trading is quiet.
pub fn truth_schema() -> SchemaRef {
    let mut fields = vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("tick", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("mispricing_s", DataType::Float64, false),
        Field::new("fundamental_value", DataType::Float64, false),
        Field::new("anchor_price", DataType::Float64, false),
    ];
    // Generated from the same constant the tick fills, so the schema cannot
    // drift out of step with the data. Written out by hand in two places, the
    // columns would eventually swap and every value would still look
    // plausible.
    for key in crate::market::factors::S_COMPONENT_KEYS {
        fields.push(Field::new(key, DataType::Float64, false));
    }
    // The daily jump, which `apply_jumps` writes to `s` after the tick loop.
    // Without it the other eight columns do not reconstruct the move on any preset
    // that carries jumps, which is every preset from pt-v4 (§74).
    fields.push(Field::new(
        crate::market::factors::JUMP_COMPONENT_KEY,
        DataType::Float64,
        false,
    ));
    // The overnight move, which `apply_overnight` writes to `s` at the open
    // before any tick; booked on the day's first row.
    fields.push(Field::new(
        crate::market::factors::OVERNIGHT_COMPONENT_KEY,
        DataType::Float64,
        false,
    ));
    // The fair-value shift: minus what left `s` for the name's fair value
    // under the permanent share (pt-v20), on each tick and, beside the jump,
    // on the row where the close's jump is observed. Zero on every preset
    // through pt-v19. With it every component column sums to `Δs`.
    fields.push(Field::new(
        crate::market::factors::FAIR_VALUE_COMPONENT_KEY,
        DataType::Float64,
        false,
    ));
    // The ex-date's move in `s` (`dividend_payout_share`), booked on the
    // day's first row like the overnight move. Zero on every preset.
    fields.push(Field::new(
        crate::market::factors::DIVIDEND_COMPONENT_KEY,
        DataType::Float64,
        false,
    ));
    Arc::new(Schema::new(fields))
}

/// Build the `bars` batch from a session's row-major buffers.
///
/// Row-major means one tick's cross-section is contiguous, so this walks the
/// buffers in their natural order and the emitted row order is
/// tick-major — which is also the order a consumer wants for a time series.
pub fn bars_batch(
    day: u32,
    ticks: usize,
    instruments: usize,
    prices: &[f64],
    volumes: &[f64],
    volume_base: &[f64],
) -> Result<RecordBatch, String> {
    let rows = ticks * instruments;
    if prices.len() < rows || volumes.len() < rows {
        return Err(format!(
            "buffer shorter than {ticks} ticks x {instruments} instruments"
        ));
    }
    // One tick is a bar of one tick: its own volume, the running total less
    // the total a tick earlier. See [`bar_volume`].
    let mut volume_col = Vec::with_capacity(rows);
    for t in 0..ticks {
        for i in 0..instruments {
            volume_col.push(bar_volume(volumes, volume_base, instruments, i, t, t + 1));
        }
    }

    let mut day_col = Vec::with_capacity(rows);
    let mut tick_col = Vec::with_capacity(rows);
    let mut id_col = Vec::with_capacity(rows);
    for t in 0..ticks {
        for i in 0..instruments {
            day_col.push(day);
            tick_col.push(t as u32);
            id_col.push(i as u32);
        }
    }

    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(day_col)),
        Arc::new(UInt32Array::from(tick_col)),
        Arc::new(UInt32Array::from(id_col)),
        Arc::new(Float64Array::from(prices[..rows].to_vec())),
        Arc::new(Float64Array::from(volume_col)),
    ];
    RecordBatch::try_new(bars_schema(), columns).map_err(|e| e.to_string())
}

/// The volume traded in ticks `first..last` of one instrument's tape.
///
/// The engine keeps volume as a running total that the open resets to zero,
/// and the tape records that total after each tick. So a bar's volume is the
/// total at its last tick minus the total before its first, and the bar
/// grain changes nothing about the rule: one tick, five minutes and a day
/// are all the same subtraction.
///
/// The total before a tape's first tick is not on the tape. It is
/// `volume_base[i]`, zero after an open and the count so far for a session
/// that starts part way through a day; an empty `volume_base` reads as zero.
///
/// Until 0.8.5 the bucketed bars SUMMED these running totals, which made a
/// day bar about two hundred times the day's volume and made the five-minute
/// profile climb all day, and the tick rows served the running total as
/// though it were the minute's volume.
pub fn bar_volume(
    volumes: &[f64],
    volume_base: &[f64],
    instruments: usize,
    i: usize,
    first: usize,
    last: usize,
) -> f64 {
    let before = if first == 0 {
        volume_base.get(i).copied().unwrap_or(0.0)
    } else {
        volumes[(first - 1) * instruments + i]
    };
    volumes[(last - 1) * instruments + i] - before
}

/// Build the `truth` batch from a session's ground-truth buffers.
pub fn truth_batch(
    day: u32,
    ticks: usize,
    instruments: usize,
    mispricing: &[f64],
    fundamental: &[f64],
    anchor: &[f64],
    components: &[Vec<f64>; crate::market::factors::COMPONENT_COUNT],
) -> Result<RecordBatch, String> {
    let rows = ticks * instruments;
    if mispricing.len() < rows || fundamental.len() < rows || anchor.len() < rows {
        return Err(format!(
            "buffer shorter than {ticks} ticks x {instruments} instruments"
        ));
    }
    for column in components.iter() {
        if column.len() < rows {
            return Err(format!(
                "component buffer shorter than {ticks} ticks x {instruments} instruments"
            ));
        }
    }

    let mut day_col = Vec::with_capacity(rows);
    let mut tick_col = Vec::with_capacity(rows);
    let mut id_col = Vec::with_capacity(rows);
    for t in 0..ticks {
        for i in 0..instruments {
            day_col.push(day);
            tick_col.push(t as u32);
            id_col.push(i as u32);
        }
    }

    let mut columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(day_col)),
        Arc::new(UInt32Array::from(tick_col)),
        Arc::new(UInt32Array::from(id_col)),
        Arc::new(Float64Array::from(mispricing[..rows].to_vec())),
        Arc::new(Float64Array::from(fundamental[..rows].to_vec())),
        Arc::new(Float64Array::from(anchor[..rows].to_vec())),
    ];
    for column in components.iter() {
        columns.push(Arc::new(Float64Array::from(column[..rows].to_vec())));
    }
    RecordBatch::try_new(truth_schema(), columns).map_err(|e| e.to_string())
}

/// `prints`: how each print was arrived at.
///
/// One row per instrument per tick, joining to `bars` and `truth` on
/// `(day, tick, instrument_id)`. `truth` says what moved fair value;
/// this says what happened between fair value and the tape.
///
/// **The decomposition.** `shock` is `log(model_price / the last print)`:
/// the distance the price model put between the tape and this tick's anchor.
/// `absorbed` is `log(print / model_price)`: what stood in the way. They sum
/// to the print's own log move, so a consumer can difference `print` across
/// ticks and check the split rather than trust it.
///
/// `absorbed` carries the circuit breaker as well as the book, because the
/// breaker lands between the book's last trade and what is published. On a
/// halted name the breaker is what absorbed the shock, and booking it to the
/// book would be the more flattering of two wrong answers.
///
/// **The counterfactual.** `unbounded_print` is what the same tick printed
/// when it was settled a second time against every resting level, under the
/// same four uniforms and from the same book state. `liquidity_share` is
/// `log(print / unbounded_print) / log(print / the last print)`: how far the
/// depth bound moved the print, as a multiple of the move the print made.
/// Both columns are absent unless `Engine.settle_depth_counterfactual(True)`
/// was set before the run, and the schema metadata says which case a reader
/// is holding.
///
/// **The share is normally negative.** The bound TRUNCATES a walk: an order
/// that exhausts a shallow book stops there, while against every resting
/// level it keeps filling and prints further from where it started. So the
/// real print sits between the last print and the unbounded print and the
/// ratio comes out below zero. On the roster and seeds this table's tests
/// name, 1,409 of the 1,516 rows where the bound moved a print are negative.
///
/// Read it through the identity it satisfies: the unbounded book's move away
/// from the last print is `1 - share` times the printed move, so a share of
/// -1 means the deeper book would have moved the price twice as far. Nothing
/// bounds it by one. It is exactly zero where the two prints coincide, which
/// is most rows, and NaN where the print did not move and the deeper book
/// would have moved it, so filter the NaN before taking a mean. A mean over
/// the signed column is near zero because up moves and down moves cancel;
/// the useful statistic is taken over the rows where the bound moved a print.
///
/// # What it cannot say
///
/// The counterfactual prints one tick from the real state. It does not say
/// what a deeper book would have done to the NEXT tick, because the maker
/// inventory it would have left is discarded and the tick after this one is
/// the one that actually ran. A study wanting the compounded answer runs two
/// markets, not one market and an arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DepthColumns {
    /// The depth counterfactual ran for every session of every day served,
    /// so `unbounded_print` and `liquidity_share` are here.
    Present,
    /// It did not run, so the two columns are absent.
    Absent,
    /// It ran for some of a day's sessions and not others. The day's columns
    /// are shorter than the day, so they are dropped rather than served with
    /// a gap in them, and the caveat says which case a reader is holding.
    PartialDay,
}

/// The schema, and the one metadata key it carries.
///
/// # One key, because the metadata order is not ours to fix
///
/// `arrow::Schema::metadata` is a `std::collections::HashMap`, and the IPC
/// writer serialises it in that map's iteration order. `RandomState` reseeds
/// per map, so two writes of one table in ONE process produced different
/// footer bytes and two different digests -- measured, not reasoned about.
/// Nothing on this side can supply a hasher, because the field's type belongs
/// to `arrow`.
///
/// So the map holds exactly one entry, where iteration order cannot vary.
/// That costs nothing, because the two keys it used to carry beside the
/// caveat were both derivable from the schema itself: a consumer asking
/// whether the arm ran reads the column list, which is the more reliable
/// answer anyway.
pub fn prints_schema(depth: DepthColumns) -> SchemaRef {
    prints_schema_with(depth, false)
}

/// [`prints_schema`], with the `distribution` column on a model that pays
/// dividends: the cash dividend per share the instrument went ex for at the
/// day's open, on the day's first print, and 0.0 on every other row. The
/// first print's `repriced` carries the drop it made. Absent on a model
/// without dividends, so every such table is the one it was.
pub fn prints_schema_with(depth: DepthColumns, distribution: bool) -> SchemaRef {
    let mut fields = vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("tick", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("print", DataType::Float64, false),
        Field::new("model_price", DataType::Float64, false),
        Field::new("shock", DataType::Float64, false),
        Field::new("absorbed", DataType::Float64, false),
        Field::new("clamp", DataType::Float64, false),
        Field::new("repriced", DataType::Float64, false),
    ];
    if depth == DepthColumns::Present {
        fields.push(Field::new("unbounded_print", DataType::Float64, false));
        fields.push(Field::new("liquidity_share", DataType::Float64, false));
    }
    if distribution {
        fields.push(Field::new("distribution", DataType::Float64, false));
    }
    // Computed from the state the caller is actually in, so the caveat
    // cannot describe a table this is not. A retyped sentence per branch is
    // how a caveat becomes false.
    let absorbed = "absorbed is measured to the printed price, so it carries \
                    the circuit breaker as well as the book. clamp is the \
                    breaker's own part and book = absorbed - clamp is the \
                    book's. Read them apart: on a halted print the two pull \
                    opposite ways and often cancel exactly, so absorbed alone \
                    reads zero on a name the breaker had just moved. \
                    repriced is what was written to the price between the \
                    last print and the tick: the close's re-mark to a \
                    published macro figure, a pin_macro's re-mark and the \
                    overnight opening print. repriced + shock + absorbed is \
                    the print's log move from the last print; it is NaN \
                    where not known, on the first print after a restore on a \
                    model that can write a price between prints. ";
    let caveat = match depth {
        DepthColumns::Present => format!(
            "{absorbed}unbounded_print is the same tick settled against every \
             resting level, under the same draws and from the same book \
             state; it is one tick from the real state and says nothing \
             about the next one. liquidity_share is NEGATIVE where the depth \
             bound truncated a walk, which is most rows that carry one, it \
             is not bounded by one, and it is NaN where the print did not \
             move. The unbounded move is (1 - liquidity_share) times the \
             printed move."
        ),
        DepthColumns::Absent => format!(
            "{absorbed}The depth counterfactual did not run, so \
             unbounded_print and liquidity_share are absent. Set \
             Engine.settle_depth_counterfactual(True) before the run to get \
             them."
        ),
        DepthColumns::PartialDay => format!(
            "{absorbed}The depth counterfactual was switched part way \
             through a day, so that day recorded fewer counterfactual values \
             than it has rows. unbounded_print and liquidity_share are \
             dropped for the whole day rather than served with a gap in \
             them. Set Engine.settle_depth_counterfactual before the first \
             session of a day."
        ),
    };
    let metadata = std::collections::HashMap::from([("caveat".to_string(), caveat)]);
    Arc::new(Schema::new_with_metadata(fields, metadata))
}

/// Build the `prints` batch from a session's buffers.
///
/// `depth` says which of the three shapes to build, and the caller decides
/// it, because only the caller can see whether every day it is serving
/// agrees. A `Present` state with a buffer shorter than the table is an
/// error rather than a pad.
///
/// With the `distribution` column when `distribution` is `Some`: one
/// amount per instrument, written on the day's first print.
#[allow(clippy::too_many_arguments)]
pub fn prints_batch_with(
    day: u32,
    ticks: usize,
    instruments: usize,
    prints: &[f64],
    model_price: &[f64],
    shock: &[f64],
    absorbed: &[f64],
    clamp: &[f64],
    repriced: &[f64],
    unbounded_print: &[f64],
    liquidity_share: &[f64],
    depth: DepthColumns,
    distribution: Option<&[f64]>,
) -> Result<RecordBatch, String> {
    let rows = ticks * instruments;
    for (name, len) in [
        ("print", prints.len()),
        ("model_price", model_price.len()),
        ("shock", shock.len()),
        ("absorbed", absorbed.len()),
        ("clamp", clamp.len()),
        ("repriced", repriced.len()),
    ] {
        if len < rows {
            return Err(format!(
                "{name} buffer shorter than {ticks} ticks x {instruments} instruments"
            ));
        }
    }
    // The caller decides the state; this only refuses a state the buffers
    // cannot support, because a short column served as a full one would put
    // a real value on the wrong row for the rest of the day.
    if depth == DepthColumns::Present
        && (unbounded_print.len() < rows || liquidity_share.len() < rows)
    {
        return Err(format!(
            "counterfactual buffer shorter than {ticks} ticks x {instruments} instruments"
        ));
    }

    let mut day_col = Vec::with_capacity(rows);
    let mut tick_col = Vec::with_capacity(rows);
    let mut id_col = Vec::with_capacity(rows);
    for t in 0..ticks {
        for i in 0..instruments {
            day_col.push(day);
            tick_col.push(t as u32);
            id_col.push(i as u32);
        }
    }

    let mut columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(day_col)),
        Arc::new(UInt32Array::from(tick_col)),
        Arc::new(UInt32Array::from(id_col)),
        Arc::new(Float64Array::from(prints[..rows].to_vec())),
        Arc::new(Float64Array::from(model_price[..rows].to_vec())),
        Arc::new(Float64Array::from(shock[..rows].to_vec())),
        Arc::new(Float64Array::from(absorbed[..rows].to_vec())),
        Arc::new(Float64Array::from(clamp[..rows].to_vec())),
        Arc::new(Float64Array::from(repriced[..rows].to_vec())),
    ];
    if depth == DepthColumns::Present {
        columns.push(Arc::new(Float64Array::from(unbounded_print[..rows].to_vec())));
        columns.push(Arc::new(Float64Array::from(liquidity_share[..rows].to_vec())));
    }
    if let Some(amounts) = distribution {
        let mut col = vec![0.0; rows];
        if ticks > 0 {
            for (i, slot) in col.iter_mut().take(instruments).enumerate() {
                *slot = amounts.get(i).copied().unwrap_or(0.0);
            }
        }
        columns.push(Arc::new(Float64Array::from(col)));
    }
    let schema = if distribution.is_some() {
        prints_schema_with(depth, true)
    } else {
        prints_schema(depth)
    };
    RecordBatch::try_new(schema, columns).map_err(|e| e.to_string())
}

/// A reader over a fixed set of batches.
///
/// Deliberately a READER rather than a single batch, even when there is only
/// one batch to hand over. The C stream interface is a pull protocol, so a
/// consumer that wants to process a sweep day by day gets that for free; a
/// design that handed over one materialised table would have to be replaced
/// rather than extended when the first user runs out of memory.
struct BatchReader {
    schema: SchemaRef,
    batches: std::vec::IntoIter<RecordBatch>,
}

impl Iterator for BatchReader {
    type Item = Result<RecordBatch, arrow::error::ArrowError>;
    fn next(&mut self) -> Option<Self::Item> {
        self.batches.next().map(Ok)
    }
}

impl RecordBatchReader for BatchReader {
    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }
}

/// A stream of record batches, consumable by anything that speaks Arrow.
///
/// Exposes `__arrow_c_stream__`, so `polars.from_arrow`, `pyarrow.table`,
/// `pandas` and duckdb all read it directly and zero-copy. The package depends
/// on none of them.
#[pyclass(name = "ArrowStream", module = "tradefloor._core")]
pub struct PyArrowStream {
    schema: SchemaRef,
    batches: Vec<RecordBatch>,
    name: String,
}

impl PyArrowStream {
    pub fn new(name: &str, schema: SchemaRef, batches: Vec<RecordBatch>) -> Self {
        Self { schema, batches, name: name.to_string() }
    }
}

#[pymethods]
impl PyArrowStream {
    /// The Arrow PyCapsule stream protocol.
    ///
    /// `requested_schema` is accepted and ignored, which the protocol allows.
    /// It is a hint for casting, and this stream can produce exactly one
    /// schema. Casting f64 columns to something narrower on request would
    /// break the bit parity the dtype rule protects, so a caller who asks
    /// for that gets the stream's own schema.
    #[pyo3(signature = (requested_schema = None))]
    fn __arrow_c_stream__<'py>(
        &self,
        py: Python<'py>,
        requested_schema: Option<PyObject>,
    ) -> PyResult<Bound<'py, PyCapsule>> {
        let _ = requested_schema;
        let reader = BatchReader {
            schema: self.schema.clone(),
            batches: self.batches.clone().into_iter(),
        };
        let stream = FFI_ArrowArrayStream::new(Box::new(reader));
        // The capsule name is fixed by the protocol. A different name is not a
        // variant, it is invisible to every consumer.
        let name = std::ffi::CString::new("arrow_array_stream").unwrap();
        PyCapsule::new_bound(py, stream, Some(name))
    }

    /// Number of rows across every batch.
    #[getter]
    fn num_rows(&self) -> usize {
        self.batches.iter().map(|b| b.num_rows()).sum()
    }

    #[getter]
    fn num_batches(&self) -> usize {
        self.batches.len()
    }

    /// Column names, in schema order.
    #[getter]
    fn columns(&self) -> Vec<String> {
        self.schema.fields().iter().map(|f| f.name().clone()).collect()
    }

    fn __repr__(&self) -> String {
        // The reading hint is in the repr because the repr is what a user
        // sees at the prompt, and `pandas.DataFrame(stream)` fails with
        // "DataFrame constructor not properly called!", which names no
        // reader.
        format!(
            "ArrowStream({:?}, {} rows in {} batch(es)). Read it with \
             pyarrow.table(stream) or polars.from_arrow(stream); pip install \
             \"tradefloor[arrow]\" for pyarrow.",
            self.name,
            self.num_rows(),
            self.batches.len()
        )
    }
}

/// Map an arrow error onto the package's own taxonomy.
pub fn arrow_err(e: String) -> PyErr {
    ValidationError::new_err(e)
}

/// `macro`: one row per day, the evolved macro state.
///
/// Keyed by the same `day` as `bars` and `truth`, so aligning a macro signal
/// with prices is a join rather than a hand-rolled accumulation loop. That is
/// the whole reason it is a table at all instead of an accessor.
///
/// Rates are FRACTIONAL here, matching every other boundary in the package. A
/// results table that reported percent while the constructor took fractions
/// would be the unit trap reintroduced on the way out.
pub fn macro_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("vix", DataType::Float64, false),
        Field::new("federal_funds_rate", DataType::Float64, false),
        Field::new("corporate_bond_yield", DataType::Float64, false),
        Field::new("inflation_rate", DataType::Float64, false),
        Field::new("unemployment_rate", DataType::Float64, false),
        Field::new("gdp_growth", DataType::Float64, false),
        Field::new("qe_pe_boost", DataType::Float64, false),
        Field::new("fear_greed_index", DataType::Float64, false),
        // The universe's remembered stress, in VIX points above the crisis
        // threshold. Exposed because it is the market's REGIME as the model
        // actually holds it -- not an estimate of the regime, the thing
        // itself. A regime detector can be scored against this the way an
        // attribution model is scored against `truth`, which is the check
        // no real market can offer. Zero under any preset with the memory
        // disabled, which is every preset before pt-v4.
        Field::new("universe_stress", DataType::Float64, false),
    ]))
}

/// One day of macro state, already converted to the fractional boundary.
#[derive(Debug, Clone, Copy)]
pub struct MacroRow {
    pub day: u32,
    pub vix: f64,
    pub federal_funds_rate: f64,
    pub corporate_bond_yield: f64,
    pub inflation_rate: f64,
    pub unemployment_rate: f64,
    pub gdp_growth: f64,
    pub qe_pe_boost: f64,
    pub fear_greed_index: f64,
    pub universe_stress: f64,
}

pub fn macro_batch(rows: &[MacroRow]) -> Result<RecordBatch, String> {
    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.day).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.vix).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.federal_funds_rate).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.corporate_bond_yield).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.inflation_rate).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.unemployment_rate).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.gdp_growth).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.qe_pe_boost).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.fear_greed_index).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.universe_stress).collect::<Vec<_>>())),
    ];
    RecordBatch::try_new(macro_schema(), columns).map_err(|e| e.to_string())
}

/// `distributions`: one row per declared cash dividend. See
/// `PyEngine::distributions`.
pub fn distributions_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("declared_day", DataType::UInt32, false),
        Field::new("ex_day", DataType::UInt32, false),
        Field::new("amount", DataType::Float64, false),
        Field::new("kind", DataType::Utf8, false),
    ]))
}

pub fn distributions_batch(rows: &[&crate::engine::Distribution]) -> Result<RecordBatch, String> {
    let u = |x: i64| if x < 0 { 0u32 } else { x as u32 };
    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(rows.iter().map(|r| u(r.ex_day)).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.company as u32).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| u(r.declared_day)).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| u(r.ex_day)).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.amount).collect::<Vec<_>>())),
        Arc::new(arrow::array::StringArray::from(rows.iter().map(|_| "cash").collect::<Vec<_>>())),
    ];
    RecordBatch::try_new(distributions_schema(), columns).map_err(|e| e.to_string())
}

/// The version the derivatives' tables (`futures_bars`, `settlements` and
/// `option_quotes`) carry in their schema's `schema_version` metadata key.
/// The older tables carry no version, and their columns are frozen by the
/// known-answer gate; these are newer and may gain columns, so a reader can
/// tell which layout it holds from the stream alone. One key per schema,
/// for the reason [`prints_schema`] gives.
pub const FUTURES_TABLES_SCHEMA_VERSION: &str = "1";

fn versioned(fields: Vec<Field>) -> SchemaRef {
    let metadata = std::collections::HashMap::from([(
        "schema_version".to_string(),
        FUTURES_TABLES_SCHEMA_VERSION.to_string(),
    )]);
    Arc::new(Schema::new_with_metadata(fields, metadata))
}

/// `futures_bars`: one row per listed contract per recorded day, read when
/// `record` is called. Every day loop in the package records a day after
/// its last session and before its close, so `price` is the contract's
/// price at the day's last print and `mark` the settlement mark the
/// previous close set. `bid`, `ask`, `mark` and `initial_margin` are null
/// where the contract has none (an empty side, before its first close,
/// without `margin_scan_coverage`). Contracts are named by symbol: there
/// are at most a few dozen a day, so the string costs nothing.
pub fn futures_bars_schema() -> SchemaRef {
    versioned(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("symbol", DataType::Utf8, false),
        Field::new("root", DataType::Utf8, false),
        Field::new("expiry", DataType::Int64, false),
        Field::new("front", DataType::Boolean, false),
        Field::new("price", DataType::Float64, false),
        Field::new("fair", DataType::Float64, false),
        Field::new("basis_bp", DataType::Float64, false),
        Field::new("bid", DataType::Float64, true),
        Field::new("ask", DataType::Float64, true),
        Field::new("mark", DataType::Float64, true),
        Field::new("index", DataType::Float64, false),
        Field::new("sessions_to_expiry", DataType::Float64, false),
        Field::new("initial_margin", DataType::Float64, true),
    ])
}

/// One contract's row of [`futures_bars_schema`].
#[derive(Debug, Clone)]
pub struct FuturesBarRow {
    pub day: u32,
    pub symbol: String,
    pub root: String,
    pub expiry: i64,
    pub front: bool,
    pub price: f64,
    pub fair: f64,
    pub basis_bp: f64,
    pub bid: Option<f64>,
    pub ask: Option<f64>,
    pub mark: Option<f64>,
    pub index: f64,
    pub sessions_to_expiry: f64,
    pub initial_margin: Option<f64>,
}

pub fn futures_bars_batch(rows: &[&FuturesBarRow]) -> Result<RecordBatch, String> {
    use arrow::array::{BooleanArray, Int64Array, StringArray};
    let f = |g: fn(&FuturesBarRow) -> f64| -> ArrayRef {
        Arc::new(Float64Array::from(rows.iter().map(|r| g(r)).collect::<Vec<_>>()))
    };
    let o = |g: fn(&FuturesBarRow) -> Option<f64>| -> ArrayRef {
        Arc::new(Float64Array::from(rows.iter().map(|r| g(r)).collect::<Vec<_>>()))
    };
    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.day).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.symbol.as_str()).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.root.as_str()).collect::<Vec<_>>())),
        Arc::new(Int64Array::from(rows.iter().map(|r| r.expiry).collect::<Vec<_>>())),
        Arc::new(BooleanArray::from(rows.iter().map(|r| r.front).collect::<Vec<_>>())),
        f(|r| r.price),
        f(|r| r.fair),
        f(|r| r.basis_bp),
        o(|r| r.bid),
        o(|r| r.ask),
        o(|r| r.mark),
        f(|r| r.index),
        f(|r| r.sessions_to_expiry),
        o(|r| r.initial_margin),
    ];
    RecordBatch::try_new(futures_bars_schema(), columns).map_err(|e| e.to_string())
}

/// `settlements`: one row per contract's final settlement, in session
/// order, as `Engine.settlements` lists them: `session` (counted from 0,
/// the open or close it settled at), `symbol`, `root`, `kind` (`"future"`),
/// `value` (the settlement price) and `reference` (what it settles on).
pub fn settlements_schema() -> SchemaRef {
    versioned(vec![
        Field::new("session", DataType::Int64, false),
        Field::new("symbol", DataType::Utf8, false),
        Field::new("root", DataType::Utf8, false),
        Field::new("kind", DataType::Utf8, false),
        Field::new("value", DataType::Float64, false),
        Field::new("reference", DataType::Float64, false),
        // A single-name option's exercises and assignments
        // (`options_names_listed`): the event, the party, the contracts and
        // what it receives in shares and cash. A contract's settlement reads
        // "settlement", a null party and zeros.
        Field::new("event", DataType::Utf8, false),
        Field::new("agent", DataType::Utf8, true),
        Field::new("quantity", DataType::Float64, false),
        Field::new("shares", DataType::Float64, false),
        Field::new("cash", DataType::Float64, false),
    ])
}

pub fn settlements_batch(rows: &[crate::derivatives::Settlement]) -> Result<RecordBatch, String> {
    use arrow::array::{Int64Array, StringArray};
    let columns: Vec<ArrayRef> = vec![
        Arc::new(Int64Array::from(rows.iter().map(|r| r.session).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.symbol.as_str()).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.root.as_str()).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.kind.family()).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.value).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.reference).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.event.as_str()).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.agent.as_deref()).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.quantity).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.shares).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.cash).collect::<Vec<_>>())),
    ];
    RecordBatch::try_new(settlements_schema(), columns).map_err(|e| e.to_string())
}

/// `option_quotes`: one row per listed index option, as
/// `Engine.chain_table` reads the chains: `day` (the engine's day count when
/// read), `symbol`, `expiry`, `right` (`"C"` or `"P"`), `strike`; the
/// dealer's `bid` and `ask` (null on a side it does not show) and the
/// contracts shown at each; `mid`, `iv` (the dealer's volatility), `fair`
/// and `surface_iv` (the surface's, without the dealer's inventory);
/// `delta`, `gamma`, `vega` and `theta` at `iv`; the carry (`forward`,
/// `index`, `rate`, `dividends`), `sessions_to_expiry` and
/// `open_interest`. Every field is [`crate::derivatives::OptionQuote`]'s.
pub fn option_quotes_schema() -> SchemaRef {
    versioned(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("symbol", DataType::Utf8, false),
        Field::new("expiry", DataType::Int64, false),
        Field::new("right", DataType::Utf8, false),
        Field::new("strike", DataType::Float64, false),
        Field::new("bid", DataType::Float64, true),
        Field::new("ask", DataType::Float64, true),
        Field::new("bid_size", DataType::Float64, false),
        Field::new("ask_size", DataType::Float64, false),
        Field::new("mid", DataType::Float64, false),
        Field::new("iv", DataType::Float64, false),
        Field::new("fair", DataType::Float64, false),
        Field::new("surface_iv", DataType::Float64, false),
        Field::new("delta", DataType::Float64, false),
        Field::new("gamma", DataType::Float64, false),
        Field::new("vega", DataType::Float64, false),
        Field::new("theta", DataType::Float64, false),
        Field::new("forward", DataType::Float64, false),
        Field::new("index", DataType::Float64, false),
        Field::new("rate", DataType::Float64, false),
        Field::new("dividends", DataType::Float64, false),
        Field::new("sessions_to_expiry", DataType::Float64, false),
        Field::new("open_interest", DataType::Float64, false),
    ])
}

pub fn option_quotes_batch(day: u32, rows: &[crate::derivatives::OptionQuote]) -> Result<RecordBatch, String> {
    use crate::derivatives::OptionQuote;
    use arrow::array::{Int64Array, StringArray};
    let f = |g: fn(&OptionQuote) -> f64| -> ArrayRef {
        Arc::new(Float64Array::from(rows.iter().map(g).collect::<Vec<_>>()))
    };
    let o = |g: fn(&OptionQuote) -> Option<f64>| -> ArrayRef {
        Arc::new(Float64Array::from(rows.iter().map(g).collect::<Vec<_>>()))
    };
    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(vec![day; rows.len()])),
        Arc::new(StringArray::from(rows.iter().map(|r| r.symbol.as_str()).collect::<Vec<_>>())),
        Arc::new(Int64Array::from(rows.iter().map(|r| r.expiry).collect::<Vec<_>>())),
        Arc::new(StringArray::from(rows.iter().map(|r| r.right.letter().to_string()).collect::<Vec<_>>())),
        f(|r| r.strike),
        o(|r| r.bid),
        o(|r| r.ask),
        f(|r| r.bid_size),
        f(|r| r.ask_size),
        f(|r| r.mid),
        f(|r| r.iv),
        f(|r| r.fair),
        f(|r| r.surface_iv),
        f(|r| r.greeks.delta),
        f(|r| r.greeks.gamma),
        f(|r| r.greeks.vega),
        f(|r| r.greeks.theta),
        f(|r| r.forward),
        f(|r| r.index),
        f(|r| r.rate),
        f(|r| r.dividends),
        f(|r| r.sessions_to_expiry),
        f(|r| r.open_interest),
    ];
    RecordBatch::try_new(option_quotes_schema(), columns).map_err(|e| e.to_string())
}

/// `fills`: one row per execution.
///
/// The trader's own record, not the market's. It exists so a study can join
/// what it DID against what the market did -- `bars` says where the price was,
/// this says where you got filled, and the gap between them is your execution
/// quality.
///
/// `worst_price` is carried alongside the average deliberately. An average
/// alone hides how far up the book an order reached, and that tail is what
/// separates a large order that was worked from one that was dumped.
pub fn fills_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("step", DataType::UInt32, false),
        // The join key. `bars`, `truth` and `book` are keyed on a WITHIN-DAY
        // tick; `step` is a global counter, so without this column the fills
        // table cannot be joined to the tape from the data alone -- it would
        // need `steps_per_day` and `ticks_per_step`, which appear in no table.
        // A columnar contract whose tables do not join is not a contract.
        Field::new("tick", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("quantity", DataType::Float64, false),
        Field::new("price", DataType::Float64, false),
        Field::new("worst_price", DataType::Float64, false),
        Field::new("notional", DataType::Float64, false),
    ]))
}

#[allow(clippy::too_many_arguments)]
pub fn fills_batch(
    day: Vec<u32>,
    step: Vec<u32>,
    tick: Vec<u32>,
    instrument_id: Vec<u32>,
    quantity: Vec<f64>,
    price: Vec<f64>,
    worst_price: Vec<f64>,
    notional: Vec<f64>,
) -> Result<RecordBatch, String> {
    let n = day.len();
    for (name, len) in [
        ("step", step.len()),
        ("tick", tick.len()),
        ("instrument_id", instrument_id.len()),
        ("quantity", quantity.len()),
        ("price", price.len()),
        ("worst_price", worst_price.len()),
        ("notional", notional.len()),
    ] {
        if len != n {
            return Err(format!("{name} has {len} rows, expected {n}"));
        }
    }
    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(day)),
        Arc::new(UInt32Array::from(step)),
        Arc::new(UInt32Array::from(tick)),
        Arc::new(UInt32Array::from(instrument_id)),
        Arc::new(Float64Array::from(quantity)),
        Arc::new(Float64Array::from(price)),
        Arc::new(Float64Array::from(worst_price)),
        Arc::new(Float64Array::from(notional)),
    ];
    RecordBatch::try_new(fills_schema(), columns).map_err(|e| e.to_string())
}

/// Build a `fills` stream from parallel columns.
///
/// It takes columns rather than a list of row objects because the data is
/// already in columns on both sides. Marshalling a million small objects
/// across the boundary only to transpose them is the cost this surface
/// exists to avoid.
#[pyfunction]
#[allow(clippy::too_many_arguments)]
pub fn fills_stream(
    day: Vec<u32>,
    step: Vec<u32>,
    tick: Vec<u32>,
    instrument_id: Vec<u32>,
    quantity: Vec<f64>,
    price: Vec<f64>,
    worst_price: Vec<f64>,
    notional: Vec<f64>,
) -> PyResult<PyArrowStream> {
    let batch = fills_batch(
        day, step, tick, instrument_id, quantity, price, worst_price, notional,
    )
    .map_err(arrow_err)?;
    Ok(PyArrowStream::new("fills", fills_schema(), vec![batch]))
}

/// One recorded day, kept raw so grain stays a read-time decision.
///
/// Storing the buffers rather than a pre-built batch costs the same memory and
/// buys the ability to ask for tick, N-minute or day bars from one recording.
/// Building the batch is cheap; re-running the day to change grain is not.
#[derive(Debug, Clone)]
pub struct RecordedDay {
    pub day: u32,
    pub ticks: usize,
    pub instruments: usize,
    pub prices: Vec<f64>,
    /// Each instrument's running volume total after each tick, reset to
    /// zero at the open. A bar's own volume is a difference of these; see
    /// [`bar_volume`].
    pub volumes: Vec<f64>,
    /// Each instrument's running total before the tape's first tick: zero
    /// on a day recorded from its open, the count so far on a tape that
    /// starts later. One per instrument, or EMPTY for zero.
    pub volume_base: Vec<f64>,
    /// The price each instrument's SESSION opened at, before its first
    /// tick: the engine's `open` mark, taken at `open_market`. One per
    /// instrument, or EMPTY when the recording predates the field, in which
    /// case the day bar falls back to the first print. `prices` holds the
    /// print AFTER each tick, so without this the day bar's open was the
    /// first tick's close, one tick of movement presented as an opening
    /// price (issue #179). Stored rather than derived from the previous
    /// close, because an embedder may write prices between sessions and a
    /// derived open would miss that gap.
    pub opens: Vec<f64>,
    pub mispricing: Vec<f64>,
    pub fundamental: Vec<f64>,
    pub anchor: Vec<f64>,
    pub components: [Vec<f64>; crate::market::factors::COMPONENT_COUNT],
    /// The print decomposition. See [`prints_schema`].
    pub shock: Vec<f64>,
    pub absorbed: Vec<f64>,
    pub clamp: Vec<f64>,
    pub repriced: Vec<f64>,
    /// The depth counterfactual, EMPTY on a day that ran without it. A day
    /// carries its own answer because the arm can be switched between days,
    /// and a table that reported one day's setting for all of them would be
    /// wrong for the rest.
    pub unbounded_print: Vec<f64>,
    pub liquidity_share: Vec<f64>,
    /// The cash dividend per share each instrument went ex for at this
    /// day's open, one per instrument, or EMPTY on a model without
    /// dividends (`dividend_payout_share`), whose `prints` carry no
    /// `distribution` column.
    pub distribution: Vec<f64>,
}

/// `bars` at a coarser grain: real OHLCV.
///
/// At tick grain a bar is the print and open/high/low would simply repeat
/// close, which is why the tick schema omits them. Once ticks are bucketed
/// they carry real information, so the coarse schema is wider rather than the
/// same columns downsampled.
pub fn ohlc_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("bar", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("open", DataType::Float64, false),
        Field::new("high", DataType::Float64, false),
        Field::new("low", DataType::Float64, false),
        Field::new("close", DataType::Float64, false),
        Field::new("volume", DataType::Float64, false),
    ]))
}

/// Bucket one day's ticks into OHLCV bars.
///
/// `bucket` is ticks per bar; a bucket at or beyond the day's length produces
/// exactly one bar, which is the day-grain case.
///
/// A bar's volume is what traded inside it; see [`bar_volume`].
///
/// The final bucket is kept even when short. Dropping a partial bar would
/// silently discard the end of every session whose length is not a multiple of
/// the bucket — including the close, which is the single most-used price in
/// the table.
pub fn ohlc_batch(day: &RecordedDay, bucket: usize) -> Result<RecordBatch, String> {
    if bucket == 0 {
        return Err("bucket must be at least one tick".to_string());
    }
    let n = day.instruments;
    if n == 0 || day.ticks == 0 {
        return RecordBatch::try_new(
            ohlc_schema(),
            vec![
                Arc::new(UInt32Array::from(Vec::<u32>::new())),
                Arc::new(UInt32Array::from(Vec::<u32>::new())),
                Arc::new(UInt32Array::from(Vec::<u32>::new())),
                Arc::new(Float64Array::from(Vec::<f64>::new())),
                Arc::new(Float64Array::from(Vec::<f64>::new())),
                Arc::new(Float64Array::from(Vec::<f64>::new())),
                Arc::new(Float64Array::from(Vec::<f64>::new())),
                Arc::new(Float64Array::from(Vec::<f64>::new())),
            ],
        )
        .map_err(|e| e.to_string());
    }

    let bars = day.ticks.div_ceil(bucket);
    let rows = bars * n;
    let (mut day_c, mut bar_c, mut id_c) = (
        Vec::with_capacity(rows),
        Vec::with_capacity(rows),
        Vec::with_capacity(rows),
    );
    let (mut o, mut h, mut l, mut c, mut v) = (
        Vec::with_capacity(rows),
        Vec::with_capacity(rows),
        Vec::with_capacity(rows),
        Vec::with_capacity(rows),
        Vec::with_capacity(rows),
    );

    for bar in 0..bars {
        let first = bar * bucket;
        let last = core::cmp::min(first + bucket, day.ticks);
        for i in 0..n {
            // The first bar of a day opens at the SESSION's open, the price
            // the day started at, which the recording carries in `opens`; a
            // later bar opens at its first print, the exchange convention
            // for an intraday bar. The session open is a print too, the one
            // the day opened on, so it belongs in the first bar's range.
            let session_open = if first == 0 && day.opens.len() == n {
                day.opens[i]
            } else {
                f64::NAN
            };
            let mut open = session_open;
            let mut high = if session_open.is_nan() { f64::NEG_INFINITY } else { session_open };
            let mut low = if session_open.is_nan() { f64::INFINITY } else { session_open };
            let mut close = f64::NAN;
            for t in first..last {
                let price = day.prices[t * n + i];
                if t == first && open.is_nan() {
                    open = price;
                }
                // `>` and `<` rather than a max/min helper: NaN must not
                // silently win a comparison and become the high of a bar.
                if price > high {
                    high = price;
                }
                if price < low {
                    low = price;
                }
                close = price;
            }
            let volume = bar_volume(&day.volumes, &day.volume_base, n, i, first, last);
            day_c.push(day.day);
            bar_c.push(bar as u32);
            id_c.push(i as u32);
            o.push(open);
            h.push(high);
            l.push(low);
            c.push(close);
            v.push(volume);
        }
    }

    RecordBatch::try_new(
        ohlc_schema(),
        vec![
            Arc::new(UInt32Array::from(day_c)),
            Arc::new(UInt32Array::from(bar_c)),
            Arc::new(UInt32Array::from(id_c)),
            Arc::new(Float64Array::from(o)),
            Arc::new(Float64Array::from(h)),
            Arc::new(Float64Array::from(l)),
            Arc::new(Float64Array::from(c)),
            Arc::new(Float64Array::from(v)),
        ],
    )
    .map_err(|e| e.to_string())
}

/// `book`: one row per (tick, instrument, side, level).
///
/// # Why this one is opt-in and the others are not
///
/// Arithmetic, not preference. A hundred names at 390 ticks with ten levels a
/// side is 780,000 rows per day per side -- roughly 1.5 million rows daily
/// against 39,000 for `bars`. Recording depth by default would make every run
/// forty times more expensive to serve a question most runs never ask.
///
/// So the caller chooses when to snapshot and how deep. Nothing samples on
/// their behalf, because a sampling rate baked into the engine is a modelling
/// decision disguised as a default.
///
/// `side` is 0 for bids and 1 for asks. An integer rather than a string
/// because it repeats on every row, and at these counts the difference is the
/// difference between a column and a memory problem -- the same reason
/// `instrument_id` is an index.
pub fn book_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("day", DataType::UInt32, false),
        Field::new("tick", DataType::UInt32, false),
        Field::new("instrument_id", DataType::UInt32, false),
        Field::new("side", DataType::UInt32, false),
        Field::new("level", DataType::UInt32, false),
        Field::new("price", DataType::Float64, false),
        Field::new("size", DataType::Float64, false),
    ]))
}

/// One row of recorded depth.
#[derive(Debug, Clone, Copy)]
pub struct BookRow {
    pub day: u32,
    pub tick: u32,
    pub instrument_id: u32,
    pub side: u32,
    pub level: u32,
    pub price: f64,
    pub size: f64,
}

pub fn book_batch(rows: &[BookRow]) -> Result<RecordBatch, String> {
    let columns: Vec<ArrayRef> = vec![
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.day).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.tick).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.instrument_id).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.side).collect::<Vec<_>>())),
        Arc::new(UInt32Array::from(rows.iter().map(|r| r.level).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.price).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(rows.iter().map(|r| r.size).collect::<Vec<_>>())),
    ];
    RecordBatch::try_new(book_schema(), columns).map_err(|e| e.to_string())
}