quantsupport 0.1.6

Rust quantitative finance library for derivatives pricing, yield-curve bootstrapping, AAD risk, Monte Carlo exposure, and XVA.
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
//! The atomic unit of exposure computation.
//!
//! A [`ContingentClaim`] represents a single contingent cashflow that can
//! declare its market-data requirements via [`simulation_requests`](ContingentClaim::simulation_requests)
//! and be valued on a simulated scenario via [`evaluate`](ContingentClaim::evaluate).
//!
//! Trades are decomposed into one or more `ContingentClaim`s by the
//! [`IntoContingentClaims`](super::makecontigentclaim::IntoContingentClaims) trait
//! or the [`MakeContingentClaim`](super::makecontigentclaim::MakeContingentClaim) builder.

use crate::{
    ad::{dual::DualFwd, scalar::Scalar},
    core::{
        collateral::Discountable,
        instrument::AssetClass,
        marketdatahandling::{
            forwardraterequest::ForwardRateRequest, fxrequest::FxRequest,
            pathdependentrequest::PathDependentRequest, spotrequest::SpotRequest,
        },
        trade::Side,
    },
    currencies::currency::Currency,
    indices::marketindex::MarketIndex,
    instruments::cashflows::payoffops::PayoffOps,
    time::{date::Date, daycounter::DayCounter},
    utils::errors::{QSError, Result},
    xva::{
        claimevaluationstrategy::ClaimEvaluationStrategy,
        visitors::{marketmodel::SimulationResponse, preprocessorexecutor::SimulationRequest},
    },
};

/// A single contingent cashflow — the atomic building block for XVA exposure.
///
/// Each claim carries:
/// * **Identity** — `trade_id`, `leg_id`, and a flat-vector `idx` assigned by
///   the [`PreprocessorExecutor`](super::visitors::preprocessorexecutor::PreprocessorExecutor).
/// * **Dates** — `payment_date`, optional `fixing_date`, `accrual_start`, `accrual_end`.
/// * **Economics** — `currency`, optional `foreign_currency`, `notional`, `side`.
/// * **Valuation rule** — a [`ClaimEvaluationStrategy`] that defines how the raw
///   payoff is computed from simulated market data.
/// * **Market reference** — an optional [`MarketIndex`] identifying the underlying
///   rate or spot used for simulation.
/// * **Fixing info** — if the fixing is fully or partially realized at the
///   reference date, the resolved values are stored here so the simulation
///   does not need to recompute them.
pub struct ContingentClaim {
    trade_id: String,
    leg_id: usize,
    idx: Option<usize>,
    payment_date: Date,
    fixing_date: Option<Date>,
    accrual_start: Option<Date>,
    accrual_end: Option<Date>,
    /// The currency in which this claim pays.
    currency: Currency,
    /// If set, the claim involves two currencies (e.g. FX forward, cross-currency swap).
    /// Both `currency` and `foreign_currency` are passed to the FX request so the context
    /// can triangulate and convert to the reporting currency.
    /// If `None`, only `currency` is passed — the context resolves conversion to reporting.
    foreign_currency: Option<Currency>,
    notional: f64,
    side: Side,
    evaluation_strategy: ClaimEvaluationStrategy,
    /// Market index for the underlying (forward rate, spot, etc.).
    /// Discounting is resolved by the context (CSA / discount policy).
    index: Option<MarketIndex>,
    /// Fully realized fixing rate (set at indexing time when the fixing is
    /// entirely determined before the reference date).
    realized_fixing: Option<f64>,
    /// Partially realized compound accrual factor and original accrual start
    /// for in-arrears coupons whose accrual period straddles the reference date.
    partial_fixing: Option<PartialFixing>,
}

/// Information for an in-arrears coupon whose accrual period straddles the
/// reference date: the realized portion is locked in, the rest is forecast.
pub struct PartialFixing {
    /// Compound accrual factor for the realized portion: `P₀(start)/P₀(ref_date)`.
    pub realized_accrual_factor: f64,
    /// Original accrual start date (before adjustment to `ref_date`).
    pub original_accrual_start: Date,
}

impl ContingentClaim {
    /// Creates a new `ContingentClaim` with all fields specified explicitly.
    ///
    /// Prefer using [`MakeContingentClaim`](super::makecontigentclaim::MakeContingentClaim)
    /// for a more ergonomic builder interface.
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub const fn new(
        trade_id: String,
        leg_id: usize,
        payment_date: Date,
        fixing_date: Option<Date>,
        accrual_start: Option<Date>,
        accrual_end: Option<Date>,
        currency: Currency,
        foreign_currency: Option<Currency>,
        notional: f64,
        side: Side,
        evaluation_strategy: ClaimEvaluationStrategy,
        index: Option<MarketIndex>,
    ) -> Self {
        Self {
            trade_id,
            leg_id,
            idx: None,
            payment_date,
            fixing_date,
            accrual_start,
            accrual_end,
            currency,
            foreign_currency,
            notional,
            side,
            evaluation_strategy,
            index,
            realized_fixing: None,
            partial_fixing: None,
        }
    }

    /// Returns the trade identifier this claim belongs to.
    #[must_use]
    pub fn trade_id(&self) -> &str {
        &self.trade_id
    }

    /// Returns the leg identifier within the trade.
    #[must_use]
    pub const fn leg_id(&self) -> usize {
        self.leg_id
    }

    /// Returns the date on which this cashflow is paid.
    #[must_use]
    pub const fn payment_date(&self) -> Date {
        self.payment_date
    }

    /// Returns the fixing date, if any.
    #[must_use]
    pub const fn fixing_date(&self) -> Option<Date> {
        self.fixing_date
    }

    /// Returns the accrual period start date, if any.
    #[must_use]
    pub const fn accrual_start(&self) -> Option<Date> {
        self.accrual_start
    }

    /// Returns the accrual period end date, if any.
    #[must_use]
    pub const fn accrual_end(&self) -> Option<Date> {
        self.accrual_end
    }

    /// Returns the payment currency.
    #[must_use]
    pub const fn currency(&self) -> Currency {
        self.currency
    }

    /// Returns the foreign currency, if this is a multi-currency claim.
    #[must_use]
    pub const fn foreign_currency(&self) -> Option<Currency> {
        self.foreign_currency
    }

    /// Returns the notional amount.
    #[must_use]
    pub const fn notional(&self) -> f64 {
        self.notional
    }

    /// Returns the side (long/receive or short/pay).
    #[must_use]
    pub const fn side(&self) -> Side {
        self.side
    }

    /// Returns the evaluation strategy that defines how the raw payoff is computed.
    #[must_use]
    pub const fn evaluation_strategy(&self) -> &ClaimEvaluationStrategy {
        &self.evaluation_strategy
    }

    /// Returns the market index for the underlying, if any.
    #[must_use]
    pub const fn index(&self) -> Option<&MarketIndex> {
        self.index.as_ref()
    }

    /// Returns the flat-vector index assigned by the [`PreprocessorExecutor`](super::visitors::preprocessorexecutor::PreprocessorExecutor).
    #[must_use]
    pub const fn idx(&self) -> Option<usize> {
        self.idx
    }

    /// Sets the flat-vector index used to locate this claim's
    /// [`SimulationResponse`] within a scenario step.
    pub const fn set_idx(&mut self, idx: usize) {
        self.idx = Some(idx);
    }

    /// Sets a fully realized fixing rate. When set, the claim will use this
    /// value instead of the simulated forward rate.
    pub const fn set_realized_fixing(&mut self, rate: f64) {
        self.realized_fixing = Some(rate);
    }

    /// Returns the realized fixing, if set.
    #[must_use]
    pub const fn realized_fixing(&self) -> Option<f64> {
        self.realized_fixing
    }

    /// Sets partial fixing info for an in-arrears coupon whose accrual
    /// period straddles the reference date. Also adjusts `accrual_start`
    /// to `new_start` so the forward rate request covers only the remaining
    /// forecast period.
    pub const fn set_partial_fixing(
        &mut self,
        realized_accrual_factor: f64,
        original_accrual_start: Date,
        new_start: Date,
    ) {
        self.partial_fixing = Some(PartialFixing {
            realized_accrual_factor,
            original_accrual_start,
        });
        self.accrual_start = Some(new_start);
    }

    /// Returns the partial fixing info, if set.
    #[must_use]
    pub const fn partial_fixing(&self) -> Option<&PartialFixing> {
        self.partial_fixing.as_ref()
    }

    /// Builds the simulation data requests needed to evaluate this claim.
    ///
    /// Discounting and reporting-currency conversion are handled by the context
    /// (discount policy / CSA). The claim only declares what market data it needs:
    /// currencies, forward rates, spot observations, or path-dependent observations.
    #[must_use]
    pub fn simulation_request(&self) -> SimulationRequest {
        let fx_request = Some(self.foreign_currency.map_or_else(
            || FxRequest::single(self.currency),
            |quote| FxRequest::pair(self.currency, quote),
        ));

        match &self.evaluation_strategy {
            ClaimEvaluationStrategy::Deterministic { .. }
            | ClaimEvaluationStrategy::Scripted { .. } => SimulationRequest {
                discount_request: None,
                forward_rate_request: None,
                fx_request,
                spot_request: None,
                path_dependent_request: None,
            },

            ClaimEvaluationStrategy::LinearRate { .. }
            | ClaimEvaluationStrategy::NonLinearRate { .. } => {
                // If the fixing is fully realized, no forward rate simulation needed.
                let forward_request = if self.realized_fixing.is_some() {
                    None
                } else {
                    let forward_index = self.index.clone();
                    let fixing_date = self.fixing_date.unwrap_or(self.payment_date);
                    forward_index.map(|idx| {
                        ForwardRateRequest::new(idx, fixing_date)
                            .with_start_date(self.accrual_start.unwrap_or(fixing_date))
                            .with_end_date(self.accrual_end.unwrap_or(self.payment_date))
                    })
                };

                SimulationRequest {
                    discount_request: None,
                    forward_rate_request: forward_request,
                    fx_request,
                    spot_request: None,
                    path_dependent_request: None,
                }
            }

            ClaimEvaluationStrategy::SpotPayoff {
                observation_date, ..
            } => {
                let spot_request = self
                    .index
                    .clone()
                    .map(|idx| SpotRequest::new(idx, *observation_date));

                SimulationRequest {
                    discount_request: None,
                    forward_rate_request: None,
                    fx_request,
                    spot_request,
                    path_dependent_request: None,
                }
            }

            ClaimEvaluationStrategy::PathDependent {
                observation_dates, ..
            } => {
                let path_request = self
                    .index
                    .clone()
                    .map(|idx| PathDependentRequest::new(observation_dates.clone(), idx));

                SimulationRequest {
                    discount_request: None,
                    forward_rate_request: None,
                    fx_request,
                    spot_request: None,
                    path_dependent_request: path_request,
                }
            }

            ClaimEvaluationStrategy::ExerciseContingent { inner, .. } => {
                let inner_request = inner.simulation_request();
                SimulationRequest {
                    discount_request: None,
                    forward_rate_request: inner_request.forward_rate_request,
                    fx_request,
                    spot_request: inner_request.spot_request,
                    path_dependent_request: inner_request.path_dependent_request,
                }
            }
        }
    }

    /// Builds the complete response block needed to evaluate this claim.
    ///
    /// Most claims need one request. A scripted claim adds the requests used
    /// while replaying its event stream after that primary discount/FX request.
    #[must_use]
    pub fn simulation_requests(&self) -> Vec<SimulationRequest> {
        let mut requests = vec![self.simulation_request()];
        if let ClaimEvaluationStrategy::Scripted { payoff } = self.evaluation_strategy() {
            requests.extend_from_slice(payoff.simulation_requests());
        }
        requests
    }

    /// Evaluates the linear-rate payoff for the three fixing scenarios.
    fn eval_linear_rate<T: Scalar + 'static>(
        &self,
        response: &SimulationResponse<T>,
        spread: f64,
        day_counter: DayCounter,
    ) -> T {
        let (start, end) = (
            self.accrual_start().unwrap_or_else(|| self.payment_date()),
            self.accrual_end().unwrap_or_else(|| self.payment_date()),
        );
        match (self.realized_fixing, &self.partial_fixing) {
            (Some(rf), _) => {
                let tau = day_counter.year_fraction(start, end);
                T::scalar((rf + spread) * tau)
            }
            (None, Some(pf)) => {
                let tau_full = day_counter.year_fraction(pf.original_accrual_start, end);
                let tau_rem = day_counter.year_fraction(start, end);
                let fwd = response.forward_rates.unwrap_or_else(T::zero);
                let compound = T::scalar(pf.realized_accrual_factor)
                    .mul_val(T::one().add_val(fwd.mul_val(T::scalar(tau_rem))));
                compound
                    .sub_val(T::one())
                    .div_val(T::scalar(tau_full))
                    .add_val(T::scalar(spread))
                    .mul_val(T::scalar(tau_full))
            }
            (None, None) => {
                let rate = response.forward_rates.unwrap_or_else(T::zero);
                let tau = day_counter.year_fraction(start, end);
                rate.add_val(T::scalar(spread)).mul_val(T::scalar(tau))
            }
        }
    }

    /// Evaluates the non-linear-rate payoff for the three fixing scenarios.
    fn eval_nonlinear_rate<T: Scalar + 'static>(
        &self,
        response: &SimulationResponse<T>,
        payoff_ops: &PayoffOps,
        spread: f64,
        day_counter: DayCounter,
    ) -> T {
        let (start, end) = (
            self.accrual_start().unwrap_or_else(|| self.payment_date()),
            self.accrual_end().unwrap_or_else(|| self.payment_date()),
        );
        match (self.realized_fixing, &self.partial_fixing) {
            (Some(rf), _) => {
                let tau = day_counter.year_fraction(start, end);
                let fixing = T::scalar(rf + spread);
                let payoff = payoff_ops.eval(fixing).unwrap_or_else(|_| T::zero());
                payoff.mul_val(T::scalar(tau))
            }
            (None, Some(pf)) => {
                let tau_full = day_counter.year_fraction(pf.original_accrual_start, end);
                let tau_rem = day_counter.year_fraction(start, end);
                let fwd = response.forward_rates.unwrap_or_else(T::zero);
                let compound = T::scalar(pf.realized_accrual_factor)
                    .mul_val(T::one().add_val(fwd.mul_val(T::scalar(tau_rem))));
                let rate = compound.sub_val(T::one()).div_val(T::scalar(tau_full));
                let fixing = rate.add_val(T::scalar(spread));
                let payoff = payoff_ops.eval(fixing).unwrap_or_else(|_| T::zero());
                payoff.mul_val(T::scalar(tau_full))
            }
            (None, None) => {
                let rate = response.forward_rates.unwrap_or_else(T::zero);
                let tau = day_counter.year_fraction(start, end);
                let fixing = rate.add_val(T::scalar(spread));
                let payoff = payoff_ops.eval(fixing).unwrap_or_else(|_| T::zero());
                payoff.mul_val(T::scalar(tau))
            }
        }
    }

    /// Evaluates the value of a single claim at a given evaluation date using
    /// the simulated market data in the [`SimulationResponse`].
    ///
    /// # Errors
    /// Returns an error if the evaluation strategy fails to compute a value.
    pub fn evaluate<T: Scalar + 'static>(&self, response: &SimulationResponse<T>) -> Result<T> {
        let sign = self.side().sign();
        let notional = self.notional();
        let fx = response.fx_rates.unwrap_or_else(T::one);
        let discount = response.discounts.unwrap_or_else(T::one);

        let raw: T = match self.evaluation_strategy() {
            ClaimEvaluationStrategy::Deterministic { amount } => T::scalar(*amount),

            ClaimEvaluationStrategy::LinearRate {
                spread,
                day_counter,
            } => self.eval_linear_rate(response, *spread, *day_counter),

            ClaimEvaluationStrategy::NonLinearRate {
                payoff_ops,
                spread,
                strike: _,
                day_counter,
            } => self.eval_nonlinear_rate(response, payoff_ops, *spread, *day_counter),

            ClaimEvaluationStrategy::SpotPayoff { payoff_ops, .. } => {
                let spot = response.spots.unwrap_or_else(T::zero);
                payoff_ops.eval(spot).unwrap_or_else(|_| T::zero())
            }

            ClaimEvaluationStrategy::PathDependent { payoff_ops, .. } => {
                let obs = response.path_dependent_observations.unwrap_or_else(T::zero);
                payoff_ops.eval(obs).unwrap_or_else(|_| T::zero())
            }

            ClaimEvaluationStrategy::ExerciseContingent { inner, .. } => {
                inner.evaluate(response)?
            }

            ClaimEvaluationStrategy::Scripted { .. } => {
                return Err(QSError::NotImplementedErr(
                    "scripted claims require scenario-row DualFwd evaluation".to_string(),
                ));
            }
        };

        Ok(raw
            .mul_val(discount)
            .mul_val(fx)
            .mul_val(T::scalar(sign * notional)))
    }

    /// Evaluates this claim from its indexed response block in a `DualFwd` scenario row.
    ///
    /// # Errors
    /// Returns an error if preprocessing has not assigned an index, the model
    /// returned an incomplete response block, or the scripted payoff fails.
    pub fn evaluate_dualfwd(
        &self,
        evaluation_date: Date,
        responses: &[SimulationResponse<DualFwd>],
    ) -> Result<DualFwd> {
        let index = self.idx.ok_or_else(|| {
            QSError::EvaluationErr(format!(
                "contingent claim '{}' has not been indexed",
                self.trade_id
            ))
        })?;
        let primary = responses.get(index).ok_or_else(|| {
            QSError::EvaluationErr(format!(
                "missing response {index} for contingent claim '{}'",
                self.trade_id
            ))
        })?;

        let ClaimEvaluationStrategy::Scripted { payoff } = self.evaluation_strategy() else {
            return self.evaluate(primary);
        };

        let first_script_response = index + 1;
        let end_script_response = first_script_response + payoff.simulation_requests().len();
        let script_responses = responses
            .get(first_script_response..end_script_response)
            .ok_or_else(|| {
                QSError::EvaluationErr(format!(
                    "incomplete scripted response block for contingent claim '{}'",
                    self.trade_id
                ))
            })?;
        let raw = payoff.evaluate(evaluation_date, script_responses)?;
        let discount = primary.discounts.unwrap_or_else(DualFwd::one);
        let fx = primary.fx_rates.unwrap_or_else(DualFwd::one);

        Ok(raw
            .mul_val(discount)
            .mul_val(fx)
            .mul_val(DualFwd::scalar(self.side.sign() * self.notional)))
    }
}

impl Discountable for ContingentClaim {
    fn asset_class(&self) -> AssetClass {
        AssetClass::InterestRate
    }

    fn currency(&self) -> Currency {
        self.currency
    }

    fn discount_index(&self) -> Option<MarketIndex> {
        self.index.clone()
    }
}