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
//! The options dealer: one market maker quotes every listed option from the
//! surface, and is the counterparty to every option trade.
//!
//! There is no order book per contract. An index chain is hundreds of
//! contracts, the model has no background option flow to fill their books,
//! and listed options are quoted by market makers from a volatility surface
//! in the real market. Quotes from one surface satisfy put-call parity and
//! the butterfly and calendar bounds by construction, where independent
//! books would drift apart and hand agents arbitrage no real market offers.
//! A quote is a pure function of state, computed only for a contract asked
//! for, with no draws.
//!
//! # The quote
//!
//! The dealer's mid is Black's price at the surface's implied volatility
//! shifted by its inventory ([`OptionDealerSpec::inventory_shift`]). Its
//! half-spread, in volatility, is `option_dealer_spread` times the equity
//! maker's VIX multiplier (`microstructure::vix_spread_multiplier`) times
//! `1 + moneyness_slope |z|`, `z` the strike's distance from the forward in
//! at-the-money total sds; in price it is that times the option's vega, so
//! it grows with vega, distance from the money, time to expiry and the VIX.
//! Each side shows [`OptionDealerSpec::levels`] levels of
//! [`OptionDealerSpec::displayed_size`] contracts, level `j` at the
//! half-spread times `1 + j level_step`, rounded away from the mid onto the
//! option's grid (0.05 below 3.00, 0.10 at or above, as Cboe's SPX). A
//! larger order walks that implied-volatility ladder.
//!
//! # Inventory
//!
//! Each trade leaves the dealer holding its other side. Per expiry the
//! dealer keeps a pressure: the contracts it has sold less those it has
//! bought, each weighted by its vega over the expiry's at-the-money vega,
//! decaying at [`OptionDealerSpec::inventory_half_life`] ticks, the rate
//! maker's half-life (`rates::INVENTORY_HALF_LIFE_TICKS`), which stands for
//! the dealer hedging and laying the risk off. The pressure moves the
//! expiry's at-the-money volatility by `inventory_skew` at-the-money
//! half-spreads per displayed size, capped at `inventory_cap` of them, up
//! when the dealer is short. The shift scales the whole expiry's smile
//! through its `theta`, and the shifted thetas are held non-decreasing
//! across expiries ([`dealer_thetas`]), so quoted chains stay free of
//! static arbitrage ([`chain_violations`]).

use super::pricing::{black_price, Greeks};
use super::symbol::Right;
use crate::mathx;

/// The dealer's quoting constants: what its quote looks like, not how wide
/// it is, which is the dial `option_dealer_spread`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct OptionDealerSpec {
    /// The price grid below `tick_switch`, and at or above it.
    pub tick: f64,
    pub tick_large: f64,
    pub tick_switch: f64,
    /// Contracts shown at each level of each side.
    pub displayed_size: f64,
    /// Levels a side.
    pub levels: usize,
    /// Each level further out adds this share of the half-spread.
    pub level_step: f64,
    /// The half-spread grows by this share per at-the-money total sd the
    /// strike sits from the forward.
    pub moneyness_slope: f64,
    /// At-the-money half-spreads the volatility moves per displayed size of
    /// at-the-money-equivalent pressure, and the most it moves.
    pub inventory_skew: f64,
    pub inventory_cap: f64,
    /// The pressure halves in this many open ticks.
    pub inventory_half_life: f64,
}

/// The index options' dealer.
pub const INDEX_OPTION_DEALER: OptionDealerSpec = OptionDealerSpec {
    tick: 0.05,
    tick_large: 0.10,
    tick_switch: 3.0,
    displayed_size: 50.0,
    levels: 10,
    level_step: 0.5,
    moneyness_slope: 0.25,
    inventory_skew: 0.5,
    inventory_cap: 4.0,
    inventory_half_life: crate::rates::INVENTORY_HALF_LIFE_TICKS,
};

/// The single-name options' dealer: the index dealer's quote on the US
/// equity options' grid (a cent below 3.00, five cents at or above, the
/// penny programme's), ten levels of 20 contracts a side.
pub const NAME_OPTION_DEALER: OptionDealerSpec = OptionDealerSpec {
    tick: 0.01,
    tick_large: 0.05,
    tick_switch: 3.0,
    displayed_size: 20.0,
    levels: 10,
    level_step: 0.5,
    moneyness_slope: 0.25,
    inventory_skew: 0.5,
    inventory_cap: 4.0,
    inventory_half_life: crate::rates::INVENTORY_HALF_LIFE_TICKS,
};

impl OptionDealerSpec {
    /// The grid at `price`.
    pub fn tick_at(&self, price: f64) -> f64 {
        if price >= self.tick_switch {
            self.tick_large
        } else {
            self.tick
        }
    }

    /// The half-spread in volatility at the base `base`
    /// (`option_dealer_spread`), the VIX `vix` and a strike `z` at-the-money
    /// total sds from the forward.
    pub fn half_spread(&self, base: f64, vix: f64, z: f64) -> f64 {
        base * crate::microstructure::vix_spread_multiplier(vix) * (1.0 + self.moneyness_slope * z.abs())
    }

    /// The volatility shift a pressure of `pressure` at-the-money-equivalent
    /// contracts puts on its expiry, `atm_half_spread` the expiry's
    /// at-the-money half-spread: up while the dealer is short.
    pub fn inventory_shift(&self, pressure: f64, atm_half_spread: f64) -> f64 {
        if pressure == 0.0 || !(atm_half_spread > 0.0) {
            return 0.0;
        }
        let cap = self.inventory_cap * atm_half_spread;
        mathx::clamp(self.inventory_skew * atm_half_spread * pressure / self.displayed_size, -cap, cap)
    }

    /// What is left of a pressure after one open tick.
    pub fn decay(&self) -> f64 {
        mathx::pow(0.5, 1.0 / self.inventory_half_life)
    }
}

/// A price rounded onto the grid away from the mid: up for an ask, down for
/// a bid.
fn on_grid(spec: &OptionDealerSpec, price: f64, up: bool) -> f64 {
    let tick = spec.tick_at(price);
    if up {
        (price / tick - 1e-9).ceil() * tick
    } else {
        (price / tick + 1e-9).floor() * tick
    }
}

/// One level of the dealer's ladder.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Level {
    pub price: f64,
    pub size: f64,
    /// The volatility it is priced at, before the grid.
    pub vol: f64,
}

/// The dealer's ladder for one option: its mid and each side's levels, best
/// first. A bid below one tick is not shown.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Ladder {
    pub mid: f64,
    pub bids: Vec<Level>,
    pub asks: Vec<Level>,
}

/// The ladder of the option `right` struck at `strike` on the forward
/// `forward`, `years` to expiry, discounted by `discount`, at the mid
/// volatility `vol` and the half-spread `half_spread` (volatility).
#[allow(clippy::too_many_arguments)]
pub fn ladder(
    spec: &OptionDealerSpec,
    right: Right,
    forward: f64,
    strike: f64,
    years: f64,
    discount: f64,
    vol: f64,
    half_spread: f64,
) -> Ladder {
    ladder_with(spec, |v| black_price(right, forward, strike, years, v, discount), vol, half_spread)
}

/// The ladder of an American option whose tree prices it at `mid` at the
/// volatility `vol`: each level is `mid` moved by the European price's
/// change between `vol` and the level's volatility, Black's on the forward
/// `forward` (the escrowed price's), so a level costs no tree and the
/// ladder's steps are the European vega's. The rest is [`ladder`]'s.
#[allow(clippy::too_many_arguments)]
pub fn american_ladder(
    spec: &OptionDealerSpec,
    right: Right,
    forward: f64,
    strike: f64,
    years: f64,
    discount: f64,
    vol: f64,
    half_spread: f64,
    mid: f64,
) -> Ladder {
    let at_mid = black_price(right, forward, strike, years, vol, discount);
    ladder_with(
        spec,
        |v| if v == vol { mid } else { mid + black_price(right, forward, strike, years, v, discount) - at_mid },
        vol,
        half_spread,
    )
}

/// The ladder `price_at` gives: its mid at `vol`, each side's levels at the
/// volatility the half-spread `half_spread` moves it by, best first.
fn ladder_with(spec: &OptionDealerSpec, price_at: impl Fn(f64) -> f64, vol: f64, half_spread: f64) -> Ladder {
    let mid = price_at(vol);
    let mut asks: Vec<Level> = Vec::with_capacity(spec.levels);
    let mut bids: Vec<Level> = Vec::with_capacity(spec.levels);
    for j in 0..spec.levels {
        let h = half_spread * (1.0 + j as f64 * spec.level_step);
        let ask_vol = vol + h;
        let mut ask = on_grid(spec, price_at(ask_vol), true);
        let floor = match asks.last() {
            Some(prev) => prev.price + spec.tick_at(prev.price),
            // Strictly above the mid even where the spread is under a tick.
            None => on_grid(spec, mid, false) + spec.tick_at(mid),
        };
        if ask < floor - 1e-12 {
            ask = floor;
        }
        asks.push(Level { price: ask, size: spec.displayed_size, vol: ask_vol });
    }
    for j in 0..spec.levels {
        let h = half_spread * (1.0 + j as f64 * spec.level_step);
        let bid_vol = mathx::max(1e-4, vol - h);
        let mut bid = on_grid(spec, price_at(bid_vol), false);
        let cap = match bids.last() {
            Some(prev) => prev.price - spec.tick_at(prev.price - 1e-9),
            // Strictly below the mid.
            None => on_grid(spec, mid, true) - spec.tick_at(mid),
        };
        if bid > cap + 1e-12 {
            bid = cap;
        }
        // The bids fall level by level, so the first under a tick ends them.
        if bid < spec.tick - 1e-12 {
            break;
        }
        bids.push(Level { price: bid, size: spec.displayed_size, vol: bid_vol });
    }
    Ladder { mid, bids, asks }
}

/// The ladder of a dealer that quotes in price: each side's level `j` at
/// `mid` moved by `half` (a price) times `1 + j level_step`, with
/// [`ladder`]'s grid, ordering and cut-off below a tick. `vol` is recorded
/// on each level. The single-name dealer's under
/// `option_name_spread_otm` and `option_name_spread_itm`, where a
/// volatility ladder would set an in-the-money option's levels at
/// volatilities far off the surface.
pub fn price_ladder(spec: &OptionDealerSpec, mid: f64, half: f64, vol: f64) -> Ladder {
    let mut asks: Vec<Level> = Vec::with_capacity(spec.levels);
    let mut bids: Vec<Level> = Vec::with_capacity(spec.levels);
    for j in 0..spec.levels {
        let h = half * (1.0 + j as f64 * spec.level_step);
        let mut ask = on_grid(spec, mid + h, true);
        let floor = match asks.last() {
            Some(prev) => prev.price + spec.tick_at(prev.price),
            None => on_grid(spec, mid, false) + spec.tick_at(mid),
        };
        if ask < floor - 1e-12 {
            ask = floor;
        }
        asks.push(Level { price: ask, size: spec.displayed_size, vol });
    }
    for j in 0..spec.levels {
        let h = half * (1.0 + j as f64 * spec.level_step);
        let mut bid = on_grid(spec, mathx::max(0.0, mid - h), false);
        let cap = match bids.last() {
            Some(prev) => prev.price - spec.tick_at(prev.price - 1e-9),
            None => on_grid(spec, mid, true) - spec.tick_at(mid),
        };
        if bid > cap + 1e-12 {
            bid = cap;
        }
        if bid < spec.tick - 1e-12 {
            break;
        }
        bids.push(Level { price: bid, size: spec.displayed_size, vol });
    }
    Ladder { mid, bids, asks }
}

/// The relative half-spread's moneyness factor under
/// `option_name_spread_otm` and `option_name_spread_itm`: 1 at an absolute
/// delta of 0.5, `otm` at 0.25 and `itm` at 0.75, linear between and flat
/// beyond.
pub fn moneyness_factor(abs_delta: f64, otm: f64, itm: f64) -> f64 {
    let a = mathx::clamp(abs_delta, 0.25, 0.75);
    if a < 0.5 {
        otm + (1.0 - otm) * (a - 0.25) / 0.25
    } else {
        1.0 + (itm - 1.0) * (a - 0.5) / 0.25
    }
}

/// Walk a side of a ladder, best first, for `quantity` contracts at
/// `limit` or better (a buy takes asks at or below it, a sell bids at or
/// above): the fills, `(price, contracts)`, in order.
pub fn walk(levels: &[Level], quantity: f64, limit: Option<f64>, buying: bool) -> Vec<(f64, f64)> {
    let mut out = Vec::new();
    let mut left = quantity;
    for level in levels {
        if !(left > 1e-9) {
            break;
        }
        if let Some(l) = limit {
            let ok = if buying { level.price <= l + 1e-12 } else { level.price >= l - 1e-12 };
            if !ok {
                break;
            }
        }
        let take = mathx::min(left, level.size);
        out.push((level.price, take));
        left -= take;
    }
    out
}

/// A pressure after the dealer sells `sold` contracts (negative for
/// contracts it buys) of an option with vega `vega`, its expiry's
/// at-the-money vega `atm_vega`.
pub fn pressure_after(pressure: f64, sold: f64, vega: f64, atm_vega: f64) -> f64 {
    if !(atm_vega > 0.0) {
        return pressure;
    }
    pressure + sold * vega / atm_vega
}

/// The thetas the dealer quotes from: each expiry's (in expiry order)
/// at-the-money total variance `theta` over `sessions`, its at-the-money
/// volatility moved by `shift`, then held non-decreasing across expiries so
/// no calendar arbitrage opens between them. A shift is held above half the
/// volatility's fall.
pub fn dealer_thetas(expiries: &[(f64, f64)], shifts: &[f64]) -> Vec<f64> {
    let mut out = Vec::with_capacity(expiries.len());
    let mut top: f64 = 0.0;
    for (i, &(sessions, theta)) in expiries.iter().enumerate() {
        let shift = shifts.get(i).copied().unwrap_or(0.0);
        let shifted = if shift == 0.0 || !(theta > 0.0 && sessions > 0.0) {
            theta
        } else {
            let vol = mathx::sqrt(theta * 252.0 / sessions);
            let moved = mathx::max(0.5 * vol, vol + shift);
            theta * (moved / vol) * (moved / vol)
        };
        top = mathx::max(top, shifted);
        out.push(top);
    }
    out
}

/// A listed option's quote, as [`crate::engine::Engine::chain`] and
/// [`crate::engine::Engine::option_quote`] read it.
///
/// A single-name option (`options_names_listed`) is American: its `mid` and
/// `fair` are a Leisen-Reimer tree's values on the escrowed price with the
/// dividends to expiry (`derivatives::american`), at `iv` and `surface_iv`;
/// its delta and gamma are the tree's, per share, and its vega and theta
/// the European's on the escrowed price; `forward` is the escrowed price's
/// forward, `index` the name's price, `dividends` the dividends' present
/// value per share, and `multiplier` 100 shares.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct OptionQuote {
    /// `IDX.O0294.C1050.00`, or `ACME.O0294.C42.50`.
    pub symbol: String,
    pub root: String,
    pub expiry: i64,
    pub right: Right,
    pub strike: f64,
    /// The dealer's best bid and ask, and the contracts shown at each.
    /// `None` on a side it does not show (a bid under one tick).
    pub bid: Option<f64>,
    pub ask: Option<f64>,
    pub bid_size: f64,
    pub ask_size: f64,
    /// The dealer's mid: Black's price at `iv`. Not on the grid, so the
    /// mids of a strike's call and put meet put-call parity exactly.
    pub mid: f64,
    /// The surface's price, without the dealer's inventory.
    pub fair: f64,
    /// The dealer's mid volatility, and the surface's.
    pub iv: f64,
    pub surface_iv: f64,
    /// Black's Greeks at `iv`.
    pub greeks: Greeks,
    /// The forward to expiry, the index it reads, the financing rate (a
    /// fraction a year) and the dividends' present value, index points.
    pub forward: f64,
    pub index: f64,
    pub rate: f64,
    pub dividends: f64,
    pub sessions_to_expiry: f64,
    /// Dollars per index point, or shares a contract.
    pub multiplier: f64,
    /// The grid at the mid.
    pub tick: f64,
    /// Contracts open: every holder's long positions, the dealer's among
    /// them.
    pub open_interest: f64,
    /// The scan's initial margin on one short contract, dollars
    /// (`margin_scan_coverage`), and the maintenance margin; `None` without
    /// margin.
    pub initial_margin: Option<f64>,
    pub maintenance_margin: Option<f64>,
}

/// One listed expiry as a trader reads it off its quoted chain
/// ([`crate::engine::Engine::option_expiries`]): the strike grid that names
/// its contracts, the dealer's at-the-money volatility and the 25-delta
/// skew. Every volatility is the dealer's mid volatility (`iv`), a fraction
/// a year.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ExpirySummary {
    pub root: String,
    pub expiry: i64,
    pub sessions_to_expiry: f64,
    /// The forward to expiry, index points.
    pub forward: f64,
    /// The listed strikes: `strike_low` to `strike_high` in steps of
    /// `strike_step`, index points.
    pub strike_low: f64,
    pub strike_high: f64,
    pub strike_step: f64,
    /// The volatility at the forward ([`read_smile`]).
    pub atm_iv: Option<f64>,
    /// The volatility where a put's delta is -0.25, and where a call's is
    /// 0.25 ([`read_smile`]).
    pub put_25d_iv: Option<f64>,
    pub call_25d_iv: Option<f64>,
    /// `put_25d_iv - call_25d_iv`: positive when out-of-the-money puts are
    /// dearer than out-of-the-money calls, as on equity indices.
    pub skew_25d: Option<f64>,
}

/// The at-the-money and 25-delta volatilities of one expiry's chain, as
/// `(atm, put_25d, call_25d)`: the mid volatility (`iv`) at the forward,
/// linear in log-moneyness between the listed strikes either side of it;
/// and where a put's delta is -0.25 and where a call's is 0.25, each linear
/// in delta between the listed strikes either side. A strike's call and put
/// share one volatility, so the at-the-money point reads the calls. Each is
/// `None` where the grid does not reach it, and all three for a chain with
/// no time left, whose volatilities are 0.
pub fn read_smile(chain: &[OptionQuote]) -> (Option<f64>, Option<f64>, Option<f64>) {
    let side = |right: Right| {
        let mut v: Vec<&OptionQuote> =
            chain.iter().filter(|q| q.right == right && q.sessions_to_expiry > 0.0 && q.iv > 0.0).collect();
        v.sort_by(|a, b| a.strike.total_cmp(&b.strike));
        v
    };
    let (calls, puts) = (side(Right::Call), side(Right::Put));
    let atm = calls.windows(2).find_map(|w| {
        let (ka, kb) = (mathx::log(w[0].strike / w[0].forward), mathx::log(w[1].strike / w[1].forward));
        (ka <= 0.0 && 0.0 <= kb && kb > ka).then(|| w[0].iv + (w[1].iv - w[0].iv) * (0.0 - ka) / (kb - ka))
    });
    // A call's delta and a put's both fall as the strike rises.
    let at_delta = |quotes: &[&OptionQuote], target: f64| {
        quotes.windows(2).find_map(|w| {
            let (da, db) = (w[0].greeks.delta, w[1].greeks.delta);
            (da >= target && target >= db && da > db).then(|| w[0].iv + (w[1].iv - w[0].iv) * (da - target) / (da - db))
        })
    };
    (atm, at_delta(&puts, -0.25), at_delta(&calls, 0.25))
}

/// Static-arbitrage violations on quoted chains (row SV2), each a sentence:
/// within an expiry, call mids not increasing and put mids not decreasing in
/// the strike, both convex (no negative butterfly), and each strike's call
/// and put mids within half the smallest tick of put-call parity on the
/// quote's forward and rate; across consecutive expiries, total implied
/// variance at a fixed log-moneyness not falling, the later expiry's read
/// by linear interpolation between its strikes. Empty when there are none.
pub fn chain_violations(quotes: &[OptionQuote], half_tick: f64) -> Vec<String> {
    let mut out = Vec::new();
    let mut expiries: Vec<i64> = quotes.iter().map(|q| q.expiry).collect();
    expiries.sort_unstable();
    expiries.dedup();
    let mut smiles: Vec<(f64, Vec<(f64, f64)>)> = Vec::new();
    for &e in &expiries {
        for right in [Right::Call, Right::Put] {
            let mut side: Vec<&OptionQuote> = quotes.iter().filter(|q| q.expiry == e && q.right == right).collect();
            side.sort_by(|a, b| a.strike.total_cmp(&b.strike));
            for w in side.windows(2) {
                let tol = 1e-9 * mathx::max(1.0, w[0].mid.abs());
                let bad = match right {
                    Right::Call => w[1].mid > w[0].mid + tol,
                    Right::Put => w[1].mid < w[0].mid - tol,
                };
                if bad {
                    out.push(format!(
                        "expiry {e}: the {} mid moves the wrong way from strike {} ({}) to {} ({})",
                        if right == Right::Call { "call" } else { "put" },
                        w[0].strike, w[0].mid, w[1].strike, w[1].mid
                    ));
                }
            }
            for w in side.windows(3) {
                let left = (w[1].mid - w[0].mid) / (w[1].strike - w[0].strike);
                let rightslope = (w[2].mid - w[1].mid) / (w[2].strike - w[1].strike);
                if rightslope < left - 1e-9 {
                    out.push(format!(
                        "expiry {e}: the butterfly at strike {} is negative ({} then {})",
                        w[1].strike, left, rightslope
                    ));
                }
            }
        }
        let calls: Vec<&OptionQuote> = quotes.iter().filter(|q| q.expiry == e && q.right == Right::Call).collect();
        for c in &calls {
            let Some(p) = quotes.iter().find(|q| q.expiry == e && q.right == Right::Put && q.strike == c.strike) else {
                continue;
            };
            let discount = mathx::exp(-c.rate * c.sessions_to_expiry / 252.0);
            let gap = c.mid - p.mid - discount * (c.forward - c.strike);
            if gap.abs() > half_tick {
                out.push(format!("expiry {e}: strike {} is {gap} off put-call parity", c.strike));
            }
        }
        let mut smile: Vec<(f64, f64)> = calls
            .iter()
            .map(|c| (mathx::log(c.strike / c.forward), c.iv * c.iv * c.sessions_to_expiry / 252.0))
            .collect();
        smile.sort_by(|a, b| a.0.total_cmp(&b.0));
        if let Some(c) = calls.first() {
            smiles.push((c.sessions_to_expiry, smile));
        }
    }
    for w in smiles.windows(2) {
        let (early, late) = (&w[0].1, &w[1].1);
        for &(k, v) in early {
            let Some(j) = late.windows(2).position(|p| p[0].0 <= k && k <= p[1].0) else {
                continue;
            };
            let (a, b) = (late[j], late[j + 1]);
            let later = if b.0 > a.0 { a.1 + (b.1 - a.1) * (k - a.0) / (b.0 - a.0) } else { a.1 };
            if later < v - 1e-12 {
                out.push(format!(
                    "calendar: total variance falls from {v} at {} sessions to {later} at {} at log-moneyness {k}",
                    w[0].0, w[1].0
                ));
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::derivatives::pricing::black_greeks;
    use crate::derivatives::surface::Ssvi;

    const SPEC: OptionDealerSpec = INDEX_OPTION_DEALER;

    #[test]
    fn the_ladder_straddles_the_mid_on_the_grid_and_widens_outward() {
        for (k, t, v) in [(1000.0, 21.0, 0.2), (900.0, 63.0, 0.3), (1100.0, 5.0, 0.15), (600.0, 21.0, 0.6)] {
            for right in [Right::Call, Right::Put] {
                let years = t / 252.0;
                let l = ladder(&SPEC, right, 1000.0, k, years, 0.999, v, 0.004);
                assert_eq!(l.asks.len(), SPEC.levels);
                assert!(l.asks[0].price > l.mid, "{right:?} {k}");
                for w in l.asks.windows(2) {
                    assert!(w[1].price > w[0].price);
                }
                if let Some(b) = l.bids.first() {
                    assert!(b.price < l.mid && b.price >= SPEC.tick - 1e-12);
                }
                for w in l.bids.windows(2) {
                    assert!(w[1].price < w[0].price);
                }
                for level in l.asks.iter().chain(l.bids.iter()) {
                    // On the grid: every price a multiple of 0.05.
                    let steps = level.price / SPEC.tick;
                    assert!((steps - steps.round()).abs() < 1e-6, "{}", level.price);
                }
            }
        }
        // The half-spread in price is about the volatility half-spread times vega.
        let (p, g) = black_greeks(Right::Call, 1000.0, 1000.0, 21.0 / 252.0, 0.2, 0.0);
        let l = ladder(&SPEC, Right::Call, 1000.0, 1000.0, 21.0 / 252.0, 1.0, 0.2, 0.01);
        assert!((l.mid - p).abs() < 1e-9);
        let half = 0.5 * (l.asks[0].price - l.bids[0].price);
        assert!((half - 0.01 * g.vega).abs() <= SPEC.tick_large, "{half} {}", 0.01 * g.vega);
    }

    #[test]
    fn the_spread_grows_with_the_vix_and_the_distance_from_the_money() {
        let h = |vix: f64, z: f64| SPEC.half_spread(0.005, vix, z);
        assert_eq!(h(15.0, 0.0), 0.005);
        assert!(h(30.0, 0.0) > h(15.0, 0.0));
        assert!(h(15.0, 2.0) > h(15.0, 1.0));
        assert_eq!(h(15.0, -2.0), h(15.0, 2.0));
    }

    #[test]
    fn a_walk_takes_levels_in_order_up_to_its_limit() {
        let l = ladder(&SPEC, Right::Put, 1000.0, 980.0, 21.0 / 252.0, 1.0, 0.22, 0.005);
        let all = walk(&l.asks, 120.0, None, true);
        assert_eq!(all.len(), 3);
        assert_eq!(all[2].1, 20.0);
        assert_eq!(all.iter().map(|f| f.1).sum::<f64>(), 120.0);
        let limited = walk(&l.asks, 120.0, Some(l.asks[0].price), true);
        assert_eq!(limited, vec![(l.asks[0].price, 50.0)]);
        assert!(walk(&l.bids, 10.0, Some(l.bids[0].price + 1.0), false).is_empty());
        // More than the ladder shows fills what it shows.
        let big = walk(&l.asks, 1e6, None, true);
        assert_eq!(big.iter().map(|f| f.1).sum::<f64>(), SPEC.levels as f64 * SPEC.displayed_size);
    }

    #[test]
    fn inventory_moves_the_volatility_up_when_short_capped_and_decays() {
        assert_eq!(SPEC.inventory_shift(0.0, 0.01), 0.0);
        assert!((SPEC.inventory_shift(50.0, 0.01) - 0.005).abs() < 1e-15);
        assert!((SPEC.inventory_shift(-50.0, 0.01) + 0.005).abs() < 1e-15);
        assert_eq!(SPEC.inventory_shift(1e9, 0.01), 0.04);
        let d = SPEC.decay();
        assert!((mathx::pow(d, 15.0) - 0.5).abs() < 1e-12);
        let p = pressure_after(0.0, 10.0, 50.0, 100.0);
        assert_eq!(p, 5.0);
        assert_eq!(pressure_after(p, -10.0, 50.0, 100.0), 0.0);
    }

    #[test]
    fn shifted_thetas_stay_non_decreasing() {
        let e = [(10.0, 0.001), (31.0, 0.003), (52.0, 0.005)];
        let t = dealer_thetas(&e, &[0.05, 0.0, -0.05]);
        assert!(t[0] > 0.001);
        assert!(t[1] >= t[0] && t[2] >= t[1]);
        assert_eq!(dealer_thetas(&e, &[]), vec![0.001, 0.003, 0.005]);
        // A shift moves the at-the-money volatility by itself.
        let one = dealer_thetas(&[(21.0, 0.2 * 0.2 * 21.0 / 252.0)], &[0.01]);
        assert!(((one[0] * 252.0 / 21.0).sqrt() - 0.21).abs() < 1e-12);
    }

    fn quotes_from(ssvi: &Ssvi, thetas: &[(i64, f64, f64)], forward: f64, rate: f64) -> Vec<OptionQuote> {
        let mut out = Vec::new();
        for &(expiry, sessions, theta) in thetas {
            let years = sessions / 252.0;
            let fwd = forward * mathx::exp(rate * years);
            for i in 0..41 {
                let strike = 800.0 + 10.0 * i as f64;
                let k = mathx::log(strike / fwd);
                let iv = mathx::sqrt(ssvi.total_variance(k, theta) / years);
                for right in [Right::Call, Right::Put] {
                    let (mid, greeks) = black_greeks(right, forward, strike, years, iv, rate);
                    out.push(OptionQuote {
                        symbol: String::new(),
                        root: "IDX".into(),
                        expiry,
                        right,
                        strike,
                        bid: None,
                        ask: None,
                        bid_size: 0.0,
                        ask_size: 0.0,
                        mid,
                        fair: mid,
                        iv,
                        surface_iv: iv,
                        greeks,
                        forward: fwd,
                        index: forward,
                        rate,
                        dividends: 0.0,
                        sessions_to_expiry: sessions,
                        multiplier: 100.0,
                        tick: 0.05,
                        open_interest: 0.0,
                        initial_margin: None,
                        maintenance_margin: None,
                    });
                }
            }
        }
        out
    }

    /// The volatility where `right`'s delta is `target`, on the continuous
    /// smile the grid samples, by bisection on the strike.
    fn exact_at_delta(ssvi: &Ssvi, theta: f64, sessions: f64, right: Right, target: f64) -> f64 {
        let (spot, rate, years) = (1000.0, 0.03, sessions / 252.0);
        let fwd = spot * mathx::exp(rate * years);
        let iv = |strike: f64| mathx::sqrt(ssvi.total_variance(mathx::log(strike / fwd), theta) / years);
        let (mut lo, mut hi) = (700.0_f64, 1300.0_f64);
        for _ in 0..100 {
            let mid = 0.5 * (lo + hi);
            if black_greeks(right, spot, mid, years, iv(mid), rate).1.delta > target {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        iv(0.5 * (lo + hi))
    }

    #[test]
    fn the_smile_reads_the_forward_and_the_25_delta_points() {
        let (sessions, theta) = (34.6, 0.0056);
        // Flat: every point is the one volatility, and the skew nothing.
        let flat = quotes_from(&Ssvi::new(0.0, 0.0, 0.5), &[(35, sessions, theta)], 1000.0, 0.03);
        let sigma = mathx::sqrt(theta * 252.0 / sessions);
        let (atm, put, call) = read_smile(&flat);
        for v in [atm, put, call] {
            assert!((v.unwrap() - sigma).abs() < 1e-12, "{v:?} {sigma}");
        }
        // Skewed: the forward reads theta, and each 25-delta point the
        // continuous smile's within interpolation error on a 10-point grid.
        let ssvi = Ssvi::new(-0.7, 1.0, 0.5);
        let skewed = quotes_from(&ssvi, &[(35, sessions, theta)], 1000.0, 0.03);
        let (atm, put, call) = read_smile(&skewed);
        assert!((atm.unwrap() - sigma).abs() < 2e-4, "{atm:?} {sigma}");
        let (put, call) = (put.unwrap(), call.unwrap());
        assert!((put - exact_at_delta(&ssvi, theta, sessions, Right::Put, -0.25)).abs() < 5e-4, "{put}");
        assert!((call - exact_at_delta(&ssvi, theta, sessions, Right::Call, 0.25)).abs() < 5e-4, "{call}");
        assert!(put > atm.unwrap() && atm.unwrap() > call, "{put} {atm:?} {call}");
        // A grid that stops short of 25 delta reads the forward alone.
        let narrow: Vec<OptionQuote> =
            skewed.iter().filter(|q| (q.strike - 1000.0).abs() <= 20.0).cloned().collect();
        let (atm, put, call) = read_smile(&narrow);
        assert!(atm.is_some() && put.is_none() && call.is_none());
        // No time left: nothing to read.
        let expired: Vec<OptionQuote> = skewed
            .iter()
            .cloned()
            .map(|mut q| {
                q.sessions_to_expiry = 0.0;
                q.iv = 0.0;
                q
            })
            .collect();
        assert_eq!(read_smile(&expired), (None, None, None));
    }

    #[test]
    fn a_chain_from_one_surface_is_clean_and_a_planted_violation_is_found() {
        let ssvi = Ssvi::new(-0.7, 1.0, 0.5);
        let thetas = [(14, 13.6, 0.0022), (35, 34.6, 0.0056), (56, 55.6, 0.0091)];
        let quotes = quotes_from(&ssvi, &thetas, 1000.0, 0.03);
        assert_eq!(chain_violations(&quotes, 0.025), Vec::<String>::new());
        // A call mid bumped above its neighbour's: monotonicity and a butterfly.
        let mut bad = quotes.clone();
        let i = bad.iter().position(|q| q.expiry == 35 && q.right == Right::Call && q.strike == 1000.0).unwrap();
        bad[i].mid += 2.0;
        let v = chain_violations(&bad, 0.025);
        assert!(v.iter().any(|s| s.contains("butterfly")), "{v:?}");
        assert!(v.iter().any(|s| s.contains("parity")), "{v:?}");
        // A later expiry below an earlier one: a calendar violation.
        let inverted = quotes_from(&ssvi, &[(14, 13.6, 0.0060), (35, 34.6, 0.0056)], 1000.0, 0.03);
        let v = chain_violations(&inverted, 0.025);
        assert!(v.iter().any(|s| s.contains("calendar")), "{v:?}");
    }
}