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
//! Contracts: what a listed derivative is, how it settles, and what a quote
//! of one says.
//!
//! The engine lists contracts from the price index, the economy and the
//! roster; they are not roster instruments and hold no slot in a column.
//! Each is named by its [`crate::derivatives::ContractSymbol`], which does not
//! depend on the order contracts were listed in.

use super::symbol::{ContractSymbol, Right, SymbolKind};

/// What kind of contract this is: index futures (`futures_index_listed`),
/// VIX futures (`futures_vix_listed`), policy-rate and term-rate futures
/// (`futures_rates_listed`), oil futures (`futures_oil_listed`), index
/// options (`options_index_listed`) and single-name options
/// (`options_names_listed`); the enum is non-exhaustive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ContractKind {
    /// A future on the engine's price index (`Engine::index_level`),
    /// cash-settled on the index of its expiry session's opening prints.
    IndexFuture,
    /// A future on the published VIX, cash-settled on the published VIX at
    /// its expiry session's open: the previous close's value.
    VixFuture,
    /// A future on the policy rate over a 21-session month, the 30-day fed
    /// funds analogue, cash-settled at the close of the month's last session
    /// at 100 less the mean of the policy rate the month's closes set.
    PolicyRateFuture,
    /// A future on the policy rate compounded over a 63-session quarter, the
    /// three-month SOFR analogue, cash-settled at the close of the quarter's
    /// last session.
    TermRateFuture,
    /// A future on the oil price, cash-settled on the oil price at its expiry
    /// session's open: the previous close's.
    OilFuture,
    /// A European call or put on the engine's price index, cash-settled on
    /// the index of its expiry session's opening prints.
    IndexOption,
    /// An American call or put on one roster name, 100 shares a contract,
    /// physically settled: exercise delivers the shares at the strike.
    NameOption,
}

impl ContractKind {
    /// The root its symbols carry. A single-name option's root is its
    /// name's ticker, which is not the kind's: it reads `""` here.
    pub fn root(self) -> &'static str {
        match self {
            ContractKind::IndexFuture => "IDX",
            ContractKind::VixFuture => "VIX",
            ContractKind::PolicyRateFuture => "FF",
            ContractKind::TermRateFuture => "TR3",
            ContractKind::OilFuture => "OIL",
            ContractKind::IndexOption => "IDX",
            ContractKind::NameOption => "",
        }
    }

    /// Whether this is a future (rather than an option).
    pub fn is_future(self) -> bool {
        match self {
            ContractKind::IndexFuture
            | ContractKind::VixFuture
            | ContractKind::PolicyRateFuture
            | ContractKind::TermRateFuture
            | ContractKind::OilFuture => true,
            ContractKind::IndexOption | ContractKind::NameOption => false,
        }
    }

    /// `"future"` or `"option"`, as the Python surface spells it.
    pub fn family(self) -> &'static str {
        if self.is_future() {
            "future"
        } else {
            "option"
        }
    }

    /// How a contract of this kind settles.
    pub fn settlement(self) -> SettlementRule {
        match self {
            ContractKind::IndexFuture => SettlementRule::OpeningPrintIndex,
            ContractKind::VixFuture => SettlementRule::PublishedVixAtOpen,
            ContractKind::PolicyRateFuture => SettlementRule::AveragePolicyRateAtClose,
            ContractKind::TermRateFuture => SettlementRule::CompoundedPolicyRateAtClose,
            ContractKind::OilFuture => SettlementRule::OilPriceAtOpen,
            ContractKind::IndexOption => SettlementRule::OpeningPrintIndex,
            ContractKind::NameOption => SettlementRule::PhysicalAtClose,
        }
    }
}

/// How a contract settles at expiry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SettlementRule {
    /// In cash, on the price index of the expiry session's opening prints:
    /// the level after the open has applied the night and the ex-dates, and
    /// before the session's first tick (the AM settlement of an index
    /// future).
    OpeningPrintIndex,
    /// In cash, on the published VIX at the expiry session's open, which is
    /// the previous close's value: the VIX moves only at a close.
    PublishedVixAtOpen,
    /// In cash, at the close of the period's last session, at 100 less the
    /// mean of the policy rate (per cent) each of the period's closes set.
    AveragePolicyRateAtClose,
    /// In cash, at the close of the period's last session, at 100 less the
    /// policy rate each of the period's closes set, compounded a session at
    /// a time (`1 + r / 25200`) and quoted as a simple rate over the period.
    CompoundedPolicyRateAtClose,
    /// In cash, on the oil price at the expiry session's open: the previous
    /// close's, since oil moves only at a close.
    OilPriceAtOpen,
    /// In shares, at the expiry session's close: an option in the money by
    /// a cent or more on the name's closing print is exercised, the OCC's
    /// exercise by exception, and delivers its shares at the strike.
    PhysicalAtClose,
}

impl SettlementRule {
    /// The rule's name, as the Python surface spells it.
    pub fn as_str(self) -> &'static str {
        match self {
            SettlementRule::OpeningPrintIndex => "opening_print_index",
            SettlementRule::PublishedVixAtOpen => "published_vix_at_open",
            SettlementRule::AveragePolicyRateAtClose => "average_policy_rate_at_close",
            SettlementRule::CompoundedPolicyRateAtClose => "compounded_policy_rate_at_close",
            SettlementRule::OilPriceAtOpen => "oil_price_at_open",
            SettlementRule::PhysicalAtClose => "physical_at_close",
        }
    }
}

/// What a contract's specification fixes, as [`crate::engine::Engine::contracts`]
/// lists it.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ContractSpec {
    /// The canonical symbol, `IDX.F0119` for the index future expiring at
    /// session 119.
    pub symbol: String,
    pub kind: ContractKind,
    /// The underlying's root: `IDX` for the price index.
    pub root: String,
    /// The session it expires at, counted from 0 as the engine's elapsed
    /// sessions are: an index, VIX or oil future settles at that session's
    /// open, a rate future at its close, the last of its period.
    pub expiry: i64,
    /// The session from which the next contract is the front by the roll
    /// rule: [`super::calendar::ROLL_SESSIONS`] before the expiry.
    pub roll: i64,
    /// Dollars per index point.
    pub multiplier: f64,
    /// The price grid, index points.
    pub tick: f64,
    pub settlement: SettlementRule,
    /// Whether it is the front contract by the roll rule: the first listed
    /// contract whose roll date has not come. False for an option.
    pub front: bool,
    /// An option's right and strike (index points); `None` for a future.
    pub right: Option<Right>,
    pub strike: Option<f64>,
}

/// A contract's quote, as [`crate::engine::Engine::quote`] reads it.
///
/// For an index future: `fair` is the carry fair value, `(S - PV(D)) *
/// exp(r tau)`, `price` is `fair` plus the basis, the price the maker quotes
/// around, and `bid` and `ask` are the agent-facing book's touch.
///
/// For a VIX future: `fair` is the expected settlement plus the premium,
/// moved within a session by the live VIX's surprise (`expected`,
/// `premium`, `loading`), `price` is `fair` plus the mark of agents' own
/// flow, `index` is the VIX the price reads (the live VIX in a session, the
/// published VIX outside one), and `rate` and `dividends` are 0.
///
/// For a rate future: `fair` is 100 less the period's expected rate and the
/// premium, `expected` the period's rate (per cent) as the closes so far set
/// it and the forecast expects the rest, `premium` the premium in rate
/// points, `index` the policy rate now (per cent), `rate` the expected
/// rate as a fraction, `basis_bp` the mark of agents' flow in rate basis
/// points, and `dividends` 0; `loading` is None.
///
/// For an oil future: `fair` and `expected` are the forecast's expected oil
/// price at its settlement, `premium` is 0, `index` the oil price now,
/// `rate` the mean policy rate the forecast expects to expiry (a fraction),
/// `basis_bp` the mark of agents' flow in basis points of the price, and
/// `dividends` 0; `loading` is None.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Quote {
    pub symbol: String,
    pub kind: ContractKind,
    pub expiry: i64,
    /// The book's best bid and ask, and their mean. `None` on an empty side.
    pub bid: Option<f64>,
    pub ask: Option<f64>,
    pub mid: Option<f64>,
    /// The futures price now: `fair` plus the basis.
    pub price: f64,
    /// The carry fair value now.
    pub fair: f64,
    /// The last close's settlement mark, `price` at that close. `None` before
    /// the contract's first close.
    pub mark: Option<f64>,
    /// The basis, `price - fair`, in basis points of the index.
    pub basis_bp: f64,
    /// The index level `fair` reads: the live level within a session, the
    /// night's path between sessions under `night_session_steps`, and the
    /// close otherwise.
    pub index: f64,
    /// The financing rate `fair` compounds at: the average expected policy
    /// rate to expiry, a fraction a year.
    pub rate: f64,
    /// The present value of the dividends going ex before the contract
    /// settles, index points.
    pub dividends: f64,
    /// Sessions from now to the expiry's open, the carry's time.
    pub sessions_to_expiry: f64,
    pub multiplier: f64,
    pub tick: f64,
    /// The daily volume the book's depth is sized to, contracts.
    pub daily_volume: f64,
    /// The initial margin a contract asks, dollars, as the last close set it
    /// (`margin_scan_coverage`). `None` with no margin and before the
    /// contract's first close.
    pub initial_margin: Option<f64>,
    /// The maintenance margin, dollars: the initial over 1.1. `None` where
    /// `initial_margin` is.
    pub maintenance_margin: Option<f64>,
    /// A VIX future's expected settlement, the forecast's published VIX at
    /// its expiry as the last close (or pin) expected it; `None` for other
    /// kinds.
    pub expected: Option<f64>,
    /// A VIX future's premium over its expected settlement now, VIX points;
    /// `None` for other kinds.
    pub premium: Option<f64>,
    /// A VIX future's intraday loading on the live VIX's surprise
    /// (`futures_vix_live_fast_share`); `None` for other kinds.
    pub loading: Option<f64>,
}

/// What a settlement row records: a contract's final settlement, or one
/// party's side of an option's exercise.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SettlementEvent {
    /// A contract's final settlement: its value at expiry.
    Settlement,
    /// A holder exercised `quantity` contracts.
    Exercise,
    /// A writer was assigned `quantity` contracts of others' exercises.
    Assignment,
}

impl SettlementEvent {
    /// `"settlement"`, `"exercise"` or `"assignment"`.
    pub fn as_str(self) -> &'static str {
        match self {
            SettlementEvent::Settlement => "settlement",
            SettlementEvent::Exercise => "exercise",
            SettlementEvent::Assignment => "assignment",
        }
    }
}

/// A contract's final settlement, or one party's side of an option's
/// exercise, as [`crate::engine::Engine::settlements`] lists them.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Settlement {
    pub symbol: String,
    pub kind: ContractKind,
    pub root: String,
    /// The session it settled at.
    pub session: i64,
    /// The settlement price.
    pub value: f64,
    /// What it settles on: for an index future, the index of the expiry
    /// session's opening prints; for a VIX future, the published VIX at the
    /// expiry session's open; for a rate future, 100 less the period's
    /// realised rate; for an oil future, the oil price at the expiry open;
    /// for a single-name option, the name's closing print at expiry, and at
    /// an exercise the name's price at the close it was exercised at.
    /// `value` is set from it, so the two agree.
    pub reference: f64,
    /// What the row records. Every row but a single-name option's exercise
    /// and assignment is a [`SettlementEvent::Settlement`].
    pub event: SettlementEvent,
    /// Whose exercise or assignment it is: an agent's label, or the
    /// dealer's (`crate::market_maker::MARKET_MAKER_ID`). `None` on a
    /// settlement.
    pub agent: Option<String>,
    /// Contracts exercised or assigned; 0 on a settlement.
    pub quantity: f64,
    /// Shares the party receives (negative: delivers), 100 a contract.
    pub shares: f64,
    /// Cash the party receives (negative: pays), the strike times the
    /// shares, to the cent.
    pub cash: f64,
}

impl Settlement {
    /// A contract's final settlement at `session` on `reference`, at `value`.
    pub fn new(symbol: String, kind: ContractKind, root: String, session: i64, value: f64, reference: f64) -> Self {
        Settlement {
            symbol,
            kind,
            root,
            session,
            value,
            reference,
            event: SettlementEvent::Settlement,
            agent: None,
            quantity: 0.0,
            shares: 0.0,
            cash: 0.0,
        }
    }
}

/// The index future's specification: constants of the contract, not dials.
///
/// The book's latent depth and the flow's impact take the shape pt-v21
/// gives the equities' book (`book_depth_coefficient` 0.75 and exponent 0.5
/// out to a day's volume, refilling at 27 ticks; `fill_impact_coefficient`
/// 0.15), so the futures book prices size as a name's does, whatever the
/// equity dials of the model it runs under.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct IndexFutureSpec {
    /// Dollars per index point: 250, so a contract on the base level of
    /// 1,000 is $250,000, about an E-mini S&P 500 at 5,000.
    pub multiplier: f64,
    /// The price grid: 0.05 index points, half a basis point at the base.
    pub tick: f64,
    /// The stated daily volume, as a share of the index constituents' daily
    /// dollar volume: 1.0, the futures trading the cash market's notional,
    /// as E-minis roughly do.
    pub volume_share: f64,
    /// The maker's levels a side, one tick apart.
    pub maker_levels: usize,
    /// Each maker level, as a share of the daily volume: 0.3 per cent, so
    /// ten levels hold 3 per cent a side, inside the 2.6 to 5 per cent the
    /// equity maker quotes (`crate::agent_book`).
    pub maker_level_share: f64,
    /// The latent depth's coefficient, exponent and reach (in days' volume).
    pub depth_coefficient: f64,
    pub depth_exponent: f64,
    pub depth_reach: f64,
    /// Consumed latent depth refills at this half-life, in steps.
    pub refill_half_life: f64,
    /// Agents' net taker flow against the house moves the basis by this
    /// times the index's daily sigma times the flow over the daily volume.
    pub impact_coefficient: f64,
    /// The flow's mark on the basis decays at this half-life, in steps:
    /// index arbitrage closes a futures dislocation within the half hour.
    pub impact_half_life: f64,
}

/// The index future's specification.
pub const INDEX_FUTURE: IndexFutureSpec = IndexFutureSpec {
    multiplier: 250.0,
    tick: 0.05,
    volume_share: 1.0,
    maker_levels: 10,
    maker_level_share: 0.003,
    depth_coefficient: 0.75,
    depth_exponent: 0.5,
    depth_reach: 1.0,
    refill_half_life: 27.0,
    impact_coefficient: 0.15,
    impact_half_life: 30.0,
};

/// The VIX futures' premium over the expected settlement, frozen: fitted
/// once to the CFE VX monthly settlements, 266 contracts from May 2004,
/// and not to any row of the model's. For a contract `n` sessions from
/// expiry, on the VIX `vix`, the premium is `a(n) + b(n) (vix - centre)`,
/// with `a(n) = k (n - 1)^p` the settlement `n` sessions before expiry less
/// the final settlement, mean over contracts, and `b(n) = beta (1 -
/// exp(-(n - 1) / tau))` its slope on the VIX's close that day; both are 0
/// at `n = 1`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct VixPremium {
    pub centre: f64,
    pub k: f64,
    pub p: f64,
    pub beta: f64,
    pub tau: f64,
    /// The time-series response's size and its rise in `n`, `g(n)`
    /// ([`VixPremium::response`]): read only under
    /// `futures_vix_premium_response`. Measured once on the same settlements
    /// and the Cboe VIX close: a day's change of a contract `n` sessions from
    /// expiry less the tape's own expected change of its settlement (the
    /// local projection of the VIX `n - 1` closes on, on the day's VIX move
    /// with the previous close held, 1990-2026), regressed on the day's VIX
    /// move, pooled over contracts with `n` of 2 to 126 (31,643 day pairs,
    /// 2004-2026). `gamma` -0.0716 (se 0.053 by whole years), flat in `n` (the
    /// least-squares `tau` is the grid's floor, 0.5): by contract position
    /// F1 -0.080 (0.031), F2 -0.090 (0.062), F4 -0.071 (0.039), against
    /// `b(n)` +0.023, +0.067 and +0.140 there. On CFE the premium falls a
    /// little when the VIX jumps, at every tenor.
    pub response_gamma: f64,
    pub response_tau: f64,
}

impl VixPremium {
    /// The premium's level part, `a(n)`.
    pub fn level(&self, n: f64) -> f64 {
        if n <= 1.0 {
            0.0
        } else {
            self.k * crate::mathx::pow(n - 1.0, self.p)
        }
    }

    /// The premium's slope on the VIX, `b(n)`.
    pub fn slope(&self, n: f64) -> f64 {
        if n <= 1.0 {
            0.0
        } else {
            self.beta * (1.0 - crate::mathx::exp(-(n - 1.0) / self.tau))
        }
    }

    /// The premium of a contract `n` sessions from expiry on the VIX `vix`.
    pub fn at(&self, n: f64, vix: f64) -> f64 {
        self.level(n) + self.slope(n) * (vix - self.centre)
    }

    /// The premium's time-series response to the VIX, `g(n) = gamma (1 -
    /// exp(-(n - 1) / tau))`: 0 at `n = 1`.
    pub fn response(&self, n: f64) -> f64 {
        if n <= 1.0 {
            0.0
        } else {
            self.response_gamma * (1.0 - crate::mathx::exp(-(n - 1.0) / self.response_tau))
        }
    }

    /// The premium with its VIX slope moved a share `w` of the way from the
    /// level slope `b(n)` to the time-series response `g(n)`
    /// (`futures_vix_premium_response`); `at` itself at `w = 0`.
    pub fn at_response(&self, n: f64, vix: f64, w: f64) -> f64 {
        if w == 0.0 {
            return self.at(n, vix);
        }
        let slope = (1.0 - w) * self.slope(n) + w * self.response(n);
        self.level(n) + slope * (vix - self.centre)
    }
}

/// The VIX future's specification: constants of the contract, not dials.
///
/// The book takes the index future's shape (`INDEX_FUTURE`): a maker's
/// ladder one tick apart, latent square-root depth at 0.75 and 0.5 out to
/// a day's volume, and agents' flow marking the price and decaying. The
/// stated daily volumes are about CFE VX's by position, 2023-2025.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct VixFutureSpec {
    /// Dollars per VIX point: 1,000, as CFE VX.
    pub multiplier: f64,
    /// The price grid: 0.05 VIX points, as CFE VX's outright tick.
    pub tick: f64,
    /// The daily volume of the front three contracts, in listing order,
    /// contracts; their books carry latent depth sized to it.
    pub front_daily_volume: [f64; 3],
    /// The daily volume each deferred contract's maker ladder is sized to.
    pub deferred_daily_volume: f64,
    /// The maker's levels a side, one tick apart.
    pub maker_levels: usize,
    /// Each maker level, as a share of the daily volume.
    pub maker_level_share: f64,
    /// The latent depth's coefficient, exponent and reach (in days' volume).
    pub depth_coefficient: f64,
    pub depth_exponent: f64,
    pub depth_reach: f64,
    /// Consumed latent depth refills at this half-life, in steps.
    pub refill_half_life: f64,
    /// A contract's daily sd of its log price, the sigma its latent depth
    /// and its flow's mark are scaled by: about the front CFE VX future's.
    pub daily_sigma: f64,
    /// Agents' net taker flow against the house moves the price by this
    /// times `daily_sigma` times the flow over the daily volume, a share of
    /// the price.
    pub impact_coefficient: f64,
    /// The flow's mark decays at this half-life, in steps.
    pub impact_half_life: f64,
    /// The premium over the expected settlement.
    pub premium: VixPremium,
}

/// The VIX future's specification.
pub const VIX_FUTURE: VixFutureSpec = VixFutureSpec {
    multiplier: 1000.0,
    tick: 0.05,
    front_daily_volume: [110_000.0, 55_000.0, 25_000.0],
    deferred_daily_volume: 8_000.0,
    maker_levels: 10,
    maker_level_share: 0.003,
    depth_coefficient: 0.75,
    depth_exponent: 0.5,
    depth_reach: 1.0,
    refill_half_life: 27.0,
    daily_sigma: 0.05,
    impact_coefficient: 0.15,
    impact_half_life: 30.0,
    premium: VixPremium { centre: 19.3197, k: 0.26, p: 0.4925, beta: 0.36, tau: 148.0, response_gamma: -0.0716,
                           response_tau: 0.5 },
};

/// The rate futures' premium over the expected rate, frozen: fitted once,
/// weighted by their standard errors, to the fed funds futures' excess
/// returns (the free 2000-2026 front-month reading of 1.28 bp at one month;
/// Piazzesi and Swanson, Journal of Monetary Economics 55(4), 2008, Table 1,
/// 6.3, 10.5, 16.1, 23.2 and 30.7 bp at two to six months), and to no row of
/// the model's. For a contract `h` sessions from its last close, `k (h /
/// 21)^p` basis points, held at its value at `cap` sessions beyond: no
/// figure past six months was verified.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RatePremium {
    pub k: f64,
    pub p: f64,
    pub cap: f64,
}

impl RatePremium {
    /// The premium `h` sessions from the last close, in rate points.
    pub fn at(&self, h: f64) -> f64 {
        if h <= 0.0 {
            return 0.0;
        }
        let h = crate::mathx::min(h, self.cap);
        self.k * crate::mathx::pow(h / 21.0, self.p) / 100.0
    }
}

/// The rate futures' premium.
pub const RATE_PREMIUM: RatePremium = RatePremium { k: 1.5956, p: 1.683, cap: 126.0 };

/// The rate futures' premium taken at each close of a contract's period
/// (`rate_premium_per_fixing`): `k (h / 21)^p` basis points for a close `h`
/// sessions away, held at its value at `cap`, so a month's premium is the
/// mean of the premium over its 21 closes and a quarter's is that of its
/// three months. Refitted, in the same way and to the same figures as
/// [`RATE_PREMIUM`] (the free 2000-2026 front-month reading, 1.28 bp se 0.67;
/// Piazzesi and Swanson, JME 55(4), 2008, Table 1, 6.3, 10.5, 16.1, 23.2
/// and 30.7 bp at two to six months, se the mean over its HAC t), with each
/// month's premium the mean over its closes: k 3.1679, p 1.3235, every point
/// within 0.39 se (1.44, 5.57, 10.82, 16.80, 23.37, 30.44 bp). The frozen
/// form read per close would give 0.63 bp at one month.
pub const RATE_PREMIUM_PER_FIXING: RatePremium = RatePremium { k: 3.1679, p: 1.3235, cap: 126.0 };

/// A rate future's specification: constants of the contract, not dials.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RateFutureSpec {
    /// Dollars per price point: CME ZQ's $41.67 a basis point, SR3's $25.
    pub multiplier: f64,
    /// The price grid: a quarter of a basis point.
    pub tick: f64,
    /// The daily volume each listed contract's maker ladder is sized to, in
    /// listing order: stated, not measured.
    pub daily_volume: &'static [f64],
    /// The maker's levels a side, one tick apart, and each level's size as a
    /// share of the daily volume.
    pub maker_levels: usize,
    pub maker_level_share: f64,
    /// A contract's daily sd in price points, the scale of its flow's mark.
    pub daily_sigma: f64,
    /// Agents' net taker flow against the house moves the price by this
    /// times `daily_sigma` times the flow over the daily volume; the mark
    /// decays at `impact_half_life` steps.
    pub impact_coefficient: f64,
    pub impact_half_life: f64,
}

/// The policy-rate future's specification (thirteen listed).
pub const POLICY_RATE_FUTURE: RateFutureSpec = RateFutureSpec {
    multiplier: 4167.0,
    tick: 0.0025,
    daily_volume: &[100_000.0, 80_000.0, 60_000.0, 40_000.0, 25_000.0, 15_000.0, 10_000.0, 6_000.0,
                    4_000.0, 3_000.0, 2_000.0, 1_500.0, 1_000.0],
    maker_levels: 10,
    maker_level_share: 0.003,
    daily_sigma: 0.015,
    impact_coefficient: 0.15,
    impact_half_life: 30.0,
};

/// The term-rate future's specification (eight listed).
pub const TERM_RATE_FUTURE: RateFutureSpec = RateFutureSpec {
    multiplier: 2500.0,
    tick: 0.0025,
    daily_volume: &[300_000.0, 300_000.0, 250_000.0, 200_000.0, 150_000.0, 100_000.0, 80_000.0, 60_000.0],
    maker_levels: 10,
    maker_level_share: 0.003,
    daily_sigma: 0.05,
    impact_coefficient: 0.15,
    impact_half_life: 30.0,
};

/// The symbol of the rate future of kind `kind` whose period ends at session
/// `expiry`.
pub fn rate_future_symbol(kind: ContractKind, expiry: i64) -> String {
    ContractSymbol { root: kind.root().to_string(), expiry, kind: SymbolKind::Future }.to_string()
}

/// The oil future's specification: constants of the contract, not dials.
/// NYMEX WTI's size and grid; the stated daily volumes, by listing order,
/// are not measured.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct OilFutureSpec {
    /// Dollars per dollar of the oil price: 1,000 barrels.
    pub multiplier: f64,
    /// The price grid: one cent a barrel.
    pub tick: f64,
    pub daily_volume: &'static [f64],
    pub maker_levels: usize,
    pub maker_level_share: f64,
    /// A contract's daily sd of its log price, the scale of its flow's mark.
    pub daily_sigma: f64,
    pub impact_coefficient: f64,
    pub impact_half_life: f64,
}

/// The oil future's specification (twelve listed).
pub const OIL_FUTURE: OilFutureSpec = OilFutureSpec {
    multiplier: 1000.0,
    tick: 0.01,
    daily_volume: &[300_000.0, 150_000.0, 80_000.0, 50_000.0, 35_000.0, 25_000.0, 20_000.0, 15_000.0,
                    12_000.0, 10_000.0, 8_000.0, 6_000.0],
    maker_levels: 10,
    maker_level_share: 0.003,
    daily_sigma: 0.02,
    impact_coefficient: 0.15,
    impact_half_life: 30.0,
};

/// The symbol of the oil future expiring at session `expiry`.
pub fn oil_future_symbol(expiry: i64) -> String {
    ContractSymbol { root: ContractKind::OilFuture.root().to_string(), expiry, kind: SymbolKind::Future }
        .to_string()
}

/// The symbol of the VIX future expiring at session `expiry`.
pub fn vix_future_symbol(expiry: i64) -> String {
    ContractSymbol { root: ContractKind::VixFuture.root().to_string(), expiry, kind: SymbolKind::Future }
        .to_string()
}

/// The symbol of the index future expiring at session `expiry`.
pub fn index_future_symbol(expiry: i64) -> String {
    ContractSymbol { root: ContractKind::IndexFuture.root().to_string(), expiry, kind: SymbolKind::Future }
        .to_string()
}

/// The index option's specification: constants of the contract, not dials.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct IndexOptionSpec {
    /// Dollars per index point: 100, as SPX.
    pub multiplier: f64,
    /// Strikes listed either side of the index.
    pub strikes_each_side: i64,
    /// The strike grid at listing, as a share of the at-the-money sd to
    /// expiry at the VIX then, before rounding to 1, 2, 2.5 or 5 times a
    /// power of ten.
    pub strike_step_sd: f64,
}

/// The index option's specification.
pub const INDEX_OPTION: IndexOptionSpec = IndexOptionSpec { multiplier: 100.0, strikes_each_side: 20, strike_step_sd: 0.2 };

impl IndexOptionSpec {
    /// The strike grid an expiry `sessions` away is listed on, at the index
    /// `index` and the volatility `vol` (a fraction a year): a
    /// [`IndexOptionSpec::strike_step_sd`] share of the at-the-money sd in
    /// index points, rounded in log to the nearest of 1, 2, 2.5 and 5 times
    /// a power of ten, and at least 0.05.
    pub fn strike_step(&self, index: f64, vol: f64, sessions: f64) -> f64 {
        let raw = self.strike_step_sd * index * vol * crate::mathx::sqrt(crate::mathx::max(sessions, 1.0) / 252.0);
        if !(raw > 0.05 && raw.is_finite()) {
            return 0.05;
        }
        let decade = (crate::mathx::log(raw) / std::f64::consts::LN_10).floor();
        let power = crate::mathx::pow(10.0, decade);
        let mut best = power;
        let mut gap = f64::INFINITY;
        // Ties go to the finer grid.
        for m in [1.0, 2.0, 2.5, 5.0, 10.0] {
            let step = m * power;
            let d = (crate::mathx::log(step) - crate::mathx::log(raw)).abs();
            if d < gap {
                gap = d;
                best = step;
            }
        }
        crate::mathx::max(0.05, best)
    }
}

/// The symbol of the index option of right `right` struck at `strike`
/// (whole cents) expiring at session `expiry`.
pub fn index_option_symbol(expiry: i64, right: Right, strike: f64) -> String {
    let cents = (strike * 100.0).round() as u64;
    ContractSymbol {
        root: ContractKind::IndexOption.root().to_string(),
        expiry,
        kind: SymbolKind::Option { right, strike_cents: cents },
    }
    .to_string()
}

/// The single-name option's specification: constants of the contract, not
/// dials.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct NameOptionSpec {
    /// Shares a contract: 100, as a listed US equity option.
    pub multiplier: f64,
    /// Strikes listed either side of the name's price.
    pub strikes_each_side: i64,
    /// The strike grid by price tier: `(below, step)` in ascending order, the
    /// first tier whose `below` the price is under giving the step, the last
    /// step above them all.
    pub tiers: [(f64, f64); 4],
    /// The step at or above the last tier.
    pub top_step: f64,
}

/// The single-name option's specification: a $0.50 grid under $5, $1
/// under $50, $2.50 under $100, $5 under $200 and $10 above, the US listing
/// programmes' intervals.
pub const NAME_OPTION: NameOptionSpec = NameOptionSpec {
    multiplier: 100.0,
    strikes_each_side: 10,
    tiers: [(5.0, 0.5), (50.0, 1.0), (100.0, 2.5), (200.0, 5.0)],
    top_step: 10.0,
};

impl NameOptionSpec {
    /// The strike grid an expiry is listed on at the name's price `price`.
    pub fn strike_step(&self, price: f64) -> f64 {
        for (below, step) in self.tiers {
            if price < below {
                return step;
            }
        }
        self.top_step
    }
}

/// The symbol of `ticker`'s option of right `right` struck at `strike`
/// (whole cents) expiring at session `expiry`.
pub fn name_option_symbol(ticker: &str, expiry: i64, right: Right, strike: f64) -> String {
    let cents = (strike * 100.0).round() as u64;
    ContractSymbol { root: ticker.to_string(), expiry, kind: SymbolKind::Option { right, strike_cents: cents } }
        .to_string()
}