libitofin 0.52.1

A ground-up Rust port of QuantLib: quantitative-finance primitives for pricing, risk, and numerical methods.
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
//! Payoffs for various options.
//!
//! Port of the scalar payoff subset of `ql/instruments/payoffs.{hpp,cpp}`:
//! the [`TypePayoff`] and [`StrikedTypePayoff`] intermediate contracts, the
//! [`PlainVanillaPayoff`], [`CashOrNothingPayoff`], [`AssetOrNothingPayoff`],
//! [`GapPayoff`], [`PercentageStrikePayoff`], [`FloatingTypePayoff`] and [`NullPayoff`]. The remaining payoffs
//! (`SuperFundPayoff`,
//! `SuperSharePayoff`) are follow-up work.

use std::any::Any;

use crate::option::OptionType;
use crate::payoff::Payoff;
use crate::types::Real;

/// Dummy payoff for engines that define settlement independently of a scalar payoff.
///
/// Matches QuantLib's `NullPayoff` name and deliberate evaluation failure.
/// It is not a zero payoff and does not enable an additional pricing engine.
///
/// # Panics
/// [`Payoff::value`] always panics with `dummy payoff given`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NullPayoff;

impl Payoff for NullPayoff {
    fn name(&self) -> String {
        "Null".into()
    }

    fn description(&self) -> String {
        self.name()
    }

    fn value(&self, _price: Real) -> Real {
        panic!("dummy payoff given")
    }
}

/// Intermediate contract for put/call payoffs (QuantLib's `TypePayoff`).
pub trait TypePayoff: Payoff {
    /// The option type the payoff is written on.
    fn option_type(&self) -> OptionType;
}

/// Intermediate contract for payoffs based on a fixed strike (QuantLib's
/// `StrikedTypePayoff`).
///
/// The [`Any`] supertrait ports the C++ engines' `dynamic_pointer_cast`
/// dispatch on the concrete payoff (visiting by dynamic type); it is
/// auto-satisfied by every `'static` implementor.
pub trait StrikedTypePayoff: TypePayoff + Any {
    /// The strike the payoff is based on.
    fn strike(&self) -> Real;
}

/// Plain-vanilla payoff: `max(price - strike, 0)` for a call,
/// `max(strike - price, 0)` for a put.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlainVanillaPayoff {
    option_type: OptionType,
    strike: Real,
}

impl PlainVanillaPayoff {
    /// Builds a plain-vanilla payoff of the given type and strike.
    pub fn new(option_type: OptionType, strike: Real) -> PlainVanillaPayoff {
        PlainVanillaPayoff {
            option_type,
            strike,
        }
    }
}

impl Payoff for PlainVanillaPayoff {
    fn name(&self) -> String {
        "Vanilla".to_string()
    }

    fn description(&self) -> String {
        format!(
            "{} {}, {} strike",
            self.name(),
            self.option_type,
            self.strike
        )
    }

    fn value(&self, price: Real) -> Real {
        let intrinsic = match self.option_type {
            OptionType::Call => price - self.strike,
            OptionType::Put => self.strike - price,
        };
        if intrinsic < 0.0 { 0.0 } else { intrinsic }
    }
}

impl TypePayoff for PlainVanillaPayoff {
    fn option_type(&self) -> OptionType {
        self.option_type
    }
}

impl StrikedTypePayoff for PlainVanillaPayoff {
    fn strike(&self) -> Real {
        self.strike
    }
}

/// Binary cash-or-nothing payoff: a fixed `cash_payoff` when the price ends
/// strictly beyond the strike, nothing otherwise.
///
/// Ports `CashOrNothingPayoff` (`ql/instruments/payoffs.hpp:152`,
/// `payoffs.cpp:154-163`). The comparison is strict on both sides, so a price
/// exactly at the strike pays nothing for either option type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CashOrNothingPayoff {
    option_type: OptionType,
    strike: Real,
    cash_payoff: Real,
}

impl CashOrNothingPayoff {
    /// Builds a cash-or-nothing payoff of the given type, strike and cash
    /// amount.
    pub fn new(option_type: OptionType, strike: Real, cash_payoff: Real) -> CashOrNothingPayoff {
        CashOrNothingPayoff {
            option_type,
            strike,
            cash_payoff,
        }
    }

    /// The amount paid when the payoff is in the money.
    pub fn cash_payoff(&self) -> Real {
        self.cash_payoff
    }
}

impl Payoff for CashOrNothingPayoff {
    fn name(&self) -> String {
        "CashOrNothing".to_string()
    }

    fn description(&self) -> String {
        format!(
            "{} {}, {} strike, {} cash payoff",
            self.name(),
            self.option_type,
            self.strike,
            self.cash_payoff
        )
    }

    fn value(&self, price: Real) -> Real {
        let moneyness = match self.option_type {
            OptionType::Call => price - self.strike,
            OptionType::Put => self.strike - price,
        };
        if moneyness > 0.0 {
            self.cash_payoff
        } else {
            0.0
        }
    }
}

impl TypePayoff for CashOrNothingPayoff {
    fn option_type(&self) -> OptionType {
        self.option_type
    }
}

impl StrikedTypePayoff for CashOrNothingPayoff {
    fn strike(&self) -> Real {
        self.strike
    }
}

/// Binary asset-or-nothing payoff, paying the underlying price strictly beyond
/// the strike and zero otherwise.
///
/// Matches QuantLib's `AssetOrNothingPayoff`. At the strike both call and put
/// pay zero. Construction follows the existing infallible payoff contract;
/// no positivity or finiteness validation is imposed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AssetOrNothingPayoff {
    option_type: OptionType,
    strike: Real,
}

impl AssetOrNothingPayoff {
    /// Builds an asset-or-nothing payoff with the given type and strike.
    pub fn new(option_type: OptionType, strike: Real) -> Self {
        Self {
            option_type,
            strike,
        }
    }
}

impl Payoff for AssetOrNothingPayoff {
    fn name(&self) -> String {
        "AssetOrNothing".into()
    }

    fn description(&self) -> String {
        format!(
            "{} {}, {} strike",
            self.name(),
            self.option_type,
            self.strike
        )
    }

    fn value(&self, price: Real) -> Real {
        let moneyness = match self.option_type {
            OptionType::Call => price - self.strike,
            OptionType::Put => self.strike - price,
        };
        if moneyness > 0.0 { price } else { 0.0 }
    }
}

impl TypePayoff for AssetOrNothingPayoff {
    fn option_type(&self) -> OptionType {
        self.option_type
    }
}

impl StrikedTypePayoff for AssetOrNothingPayoff {
    fn strike(&self) -> Real {
        self.strike
    }
}

/// Gap payoff with a trigger strike and a separate payment strike.
///
/// A call pays `price - second_strike` when `price - strike >= 0`; a put
/// pays `second_strike - price` when `strike - price >= 0`. The trigger is
/// inclusive, and negative payments are not floored. Matches QuantLib's
/// `GapPayoff` and the existing infallible payoff construction contract.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GapPayoff {
    option_type: OptionType,
    strike: Real,
    second_strike: Real,
}

impl GapPayoff {
    /// Builds a gap payoff with a trigger `strike` and payment `second_strike`.
    /// No positivity or finiteness validation is imposed.
    pub fn new(option_type: OptionType, strike: Real, second_strike: Real) -> Self {
        Self {
            option_type,
            strike,
            second_strike,
        }
    }

    /// The payment strike, distinct from the trigger returned by
    /// [`StrikedTypePayoff::strike`].
    pub fn second_strike(&self) -> Real {
        self.second_strike
    }
}

impl Payoff for GapPayoff {
    fn name(&self) -> String {
        "Gap".into()
    }

    fn description(&self) -> String {
        format!(
            "{} {}, {} strike, {} strike payoff",
            self.name(),
            self.option_type,
            self.strike,
            self.second_strike
        )
    }

    fn value(&self, price: Real) -> Real {
        match self.option_type {
            OptionType::Call if price - self.strike >= 0.0 => price - self.second_strike,
            OptionType::Put if self.strike - price >= 0.0 => self.second_strike - price,
            OptionType::Call | OptionType::Put => 0.0,
        }
    }
}

impl TypePayoff for GapPayoff {
    fn option_type(&self) -> OptionType {
        self.option_type
    }
}

impl StrikedTypePayoff for GapPayoff {
    fn strike(&self) -> Real {
        self.strike
    }
}

/// Payoff with a dimensionless strike expressed as moneyness.
///
/// A call pays `price * max(1 - moneyness, 0)` and a put pays
/// `price * max(moneyness - 1, 0)`. The factor is floored before
/// multiplication, so a negative price can produce a negative payoff.
/// Matches QuantLib's `PercentageStrikePayoff` without positivity or
/// finiteness validation, following the existing infallible payoff API.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PercentageStrikePayoff {
    option_type: OptionType,
    moneyness: Real,
}

impl PercentageStrikePayoff {
    /// Builds a percentage-strike payoff. `moneyness` is a ratio, not an
    /// absolute strike or a percentage scaled by 100.
    pub fn new(option_type: OptionType, moneyness: Real) -> Self {
        Self {
            option_type,
            moneyness,
        }
    }
}

impl Payoff for PercentageStrikePayoff {
    fn name(&self) -> String {
        "PercentageStrike".into()
    }

    fn description(&self) -> String {
        format!(
            "{} {}, {} strike",
            self.name(),
            self.option_type,
            self.moneyness
        )
    }

    fn value(&self, price: Real) -> Real {
        let factor = match self.option_type {
            OptionType::Call => 1.0 - self.moneyness,
            OptionType::Put => self.moneyness - 1.0,
        };
        price * if factor < 0.0 { 0.0 } else { factor }
    }
}

impl TypePayoff for PercentageStrikePayoff {
    fn option_type(&self) -> OptionType {
        self.option_type
    }
}

impl StrikedTypePayoff for PercentageStrikePayoff {
    fn strike(&self) -> Real {
        self.moneyness
    }
}

/// Vanilla payoff with its strike supplied at evaluation rather than stored.
///
/// Matches QuantLib's `FloatingTypePayoff`. Use [`Self::value_with_strike`]
/// to evaluate a call or put. This is a [`TypePayoff`], not a
/// [`StrikedTypePayoff`], and does not enable an additional pricing engine.
/// The scalar Black calculator rejects it at compile time:
///
/// ```compile_fail
/// use libitofin::instruments::FloatingTypePayoff;
/// use libitofin::option::OptionType;
/// use libitofin::pricingengines::BlackCalculator;
/// let payoff = FloatingTypePayoff::new(OptionType::Call);
/// BlackCalculator::with_striked_payoff(&payoff, 100.0, 0.2, 1.0);
/// ```
///
/// # Panics
///
/// [`Payoff::value`] always panics with `floating payoff not handled` because
/// its one-input contract cannot supply the strike. This mirrors QuantLib's
/// deliberate evaluation failure and the existing [`NullPayoff`] convention.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FloatingTypePayoff {
    option_type: OptionType,
}

impl FloatingTypePayoff {
    /// Builds a floating-strike payoff of the given option type.
    pub fn new(option_type: OptionType) -> Self {
        Self { option_type }
    }

    /// Evaluates `max(price - strike, 0)` for a call or
    /// `max(strike - price, 0)` for a put, using this evaluation's strike.
    ///
    /// Neither input is validated. Negative values are supported; NaN,
    /// infinity and signed zero preserve QuantLib's subtraction followed by
    /// `std::max` comparison semantics. In particular, NaN is not floored.
    pub fn value_with_strike(&self, price: Real, strike: Real) -> Real {
        let intrinsic = match self.option_type {
            OptionType::Call => price - strike,
            OptionType::Put => strike - price,
        };
        if intrinsic < 0.0 { 0.0 } else { intrinsic }
    }
}

impl Payoff for FloatingTypePayoff {
    fn name(&self) -> String {
        "FloatingType".into()
    }

    fn description(&self) -> String {
        format!("{} {}", self.name(), self.option_type)
    }

    /// # Panics
    ///
    /// Always panics because no strike is provided. Use
    /// [`Self::value_with_strike`] for supported evaluation.
    fn value(&self, _price: Real) -> Real {
        panic!("floating payoff not handled")
    }
}

impl TypePayoff for FloatingTypePayoff {
    fn option_type(&self) -> OptionType {
        self.option_type
    }
}

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

    #[test]
    fn call_pays_excess_over_strike() {
        let payoff = PlainVanillaPayoff::new(OptionType::Call, 100.0);
        assert_eq!(payoff.value(110.0), 10.0);
        assert_eq!(payoff.value(100.0), 0.0);
        assert_eq!(payoff.value(90.0), 0.0);
    }

    #[test]
    fn put_pays_shortfall_under_strike() {
        let payoff = PlainVanillaPayoff::new(OptionType::Put, 100.0);
        assert_eq!(payoff.value(90.0), 10.0);
        assert_eq!(payoff.value(100.0), 0.0);
        assert_eq!(payoff.value(110.0), 0.0);
    }

    #[test]
    fn nan_price_propagates_like_cpp_std_max() {
        let call = PlainVanillaPayoff::new(OptionType::Call, 100.0);
        assert!(call.value(Real::NAN).is_nan());
        let put = PlainVanillaPayoff::new(OptionType::Put, 100.0);
        assert!(put.value(Real::NAN).is_nan());
    }

    #[test]
    fn accessors_expose_type_and_strike() {
        let payoff = PlainVanillaPayoff::new(OptionType::Put, 32.5);
        assert_eq!(payoff.option_type(), OptionType::Put);
        assert_eq!(payoff.strike(), 32.5);
    }

    #[test]
    fn name_and_description_match_quantlib() {
        let call = PlainVanillaPayoff::new(OptionType::Call, 100.0);
        assert_eq!(call.name(), "Vanilla");
        assert_eq!(call.description(), "Vanilla Call, 100 strike");

        let put = PlainVanillaPayoff::new(OptionType::Put, 32.5);
        assert_eq!(put.description(), "Vanilla Put, 32.5 strike");
    }

    #[test]
    fn usable_as_trait_object() {
        let payoff = PlainVanillaPayoff::new(OptionType::Call, 100.0);
        let dynamic: &dyn StrikedTypePayoff = &payoff;
        assert_eq!(dynamic.value(107.0), 7.0);
        assert_eq!(dynamic.option_type(), OptionType::Call);
        assert_eq!(dynamic.strike(), 100.0);
    }

    #[test]
    fn digital_pays_the_cash_amount_beyond_the_strike() {
        let call = CashOrNothingPayoff::new(OptionType::Call, 100.0, 10.0);
        assert_eq!(call.value(110.0), 10.0);
        assert_eq!(call.value(90.0), 0.0);

        let put = CashOrNothingPayoff::new(OptionType::Put, 100.0, 10.0);
        assert_eq!(put.value(90.0), 10.0);
        assert_eq!(put.value(110.0), 0.0);
    }

    /// `payoffs.cpp:156,158` compares `> 0.0`, so the strike itself is out of
    /// the money for both types - a non-strict comparison would pay twice.
    #[test]
    fn digital_at_the_strike_pays_nothing_either_way() {
        let call = CashOrNothingPayoff::new(OptionType::Call, 100.0, 10.0);
        let put = CashOrNothingPayoff::new(OptionType::Put, 100.0, 10.0);
        assert_eq!(call.value(100.0), 0.0);
        assert_eq!(put.value(100.0), 0.0);
    }

    #[test]
    fn digital_accessors_and_description_match_quantlib() {
        let put = CashOrNothingPayoff::new(OptionType::Put, 80.0, 10.0);
        assert_eq!(put.option_type(), OptionType::Put);
        assert_eq!(put.strike(), 80.0);
        assert_eq!(put.cash_payoff(), 10.0);
        assert_eq!(put.name(), "CashOrNothing");
        assert_eq!(
            put.description(),
            "CashOrNothing Put, 80 strike, 10 cash payoff"
        );
    }

    #[test]
    fn digital_usable_as_trait_object() {
        let payoff = CashOrNothingPayoff::new(OptionType::Call, 100.0, 10.0);
        let dynamic: &dyn StrikedTypePayoff = &payoff;
        assert_eq!(dynamic.value(107.0), 10.0);
        assert_eq!(dynamic.option_type(), OptionType::Call);
        assert_eq!(dynamic.strike(), 100.0);
    }
}