quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
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
//! Forward-mode automatic differentiation via Dual and Hyper-Dual numbers.
//!
//! Provides machine-precision first and second derivatives without finite-difference
//! discretization errors or step-size tuning.

use crate::math::distributions::{normal_cdf, normal_pdf};
use std::ops::{Add, Div, Mul, Neg, Sub};

/// First-order forward-mode dual number: $x + \epsilon x'$ where $\epsilon^2 = 0$.
///
/// # Examples
/// ```
/// use quantlib_rs::math::autodiff::Dual64;
///
/// // f(x) = x^3 + 2x, evaluate at x = 3: f(3) = 33, f'(3) = 3x^2 + 2 = 29
/// let x = Dual64::variable(3.0);
/// let y = x.powi(3) + x * 2.0;
///
/// assert_eq!(y.val, 33.0);
/// assert_eq!(y.der, 29.0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Dual64 {
    /// Function value
    pub val: f64,
    /// First derivative
    pub der: f64,
}

impl Dual64 {
    /// Create a constant dual number with zero derivative.
    #[inline]
    pub const fn constant(val: f64) -> Self {
        Self { val, der: 0.0 }
    }

    /// Create an active variable with unit derivative ($\epsilon$).
    #[inline]
    pub const fn variable(val: f64) -> Self {
        Self { val, der: 1.0 }
    }

    /// Create a dual number with custom value and derivative.
    #[inline]
    pub const fn new(val: f64, der: f64) -> Self {
        Self { val, der }
    }

    /// Natural logarithm: $\ln(u) + \epsilon \frac{u'}{u}$
    #[inline]
    pub fn ln(self) -> Self {
        Self {
            val: self.val.ln(),
            der: self.der / self.val,
        }
    }

    /// Exponential function: $e^u + \epsilon u' e^u$
    #[inline]
    pub fn exp(self) -> Self {
        let e = self.val.exp();
        Self {
            val: e,
            der: self.der * e,
        }
    }

    /// Square root function: $\sqrt{u} + \epsilon \frac{u'}{2\sqrt{u}}$
    #[inline]
    pub fn sqrt(self) -> Self {
        let s = self.val.sqrt();
        Self {
            val: s,
            der: self.der / (2.0 * s),
        }
    }

    /// Integer power: $u^n + \epsilon n u^{n-1} u'$
    #[inline]
    pub fn powi(self, n: i32) -> Self {
        Self {
            val: self.val.powi(n),
            der: (n as f64) * self.val.powi(n - 1) * self.der,
        }
    }

    /// Floating-point power: $u^n + \epsilon n u^{n-1} u'$
    #[inline]
    pub fn powf(self, n: f64) -> Self {
        Self {
            val: self.val.powf(n),
            der: n * self.val.powf(n - 1.0) * self.der,
        }
    }

    /// Standard normal cumulative distribution function ($\Phi(u)$).
    /// Derivative is $\phi(u) u'$.
    #[inline]
    pub fn normal_cdf(self) -> Self {
        Self {
            val: normal_cdf(self.val),
            der: normal_pdf(self.val) * self.der,
        }
    }

    /// Standard normal probability density function ($\phi(u)$).
    /// Derivative is $-u \phi(u) u'$.
    #[inline]
    pub fn normal_pdf(self) -> Self {
        let pdf = normal_pdf(self.val);
        Self {
            val: pdf,
            der: -self.val * pdf * self.der,
        }
    }
}

impl From<f64> for Dual64 {
    #[inline]
    fn from(v: f64) -> Self {
        Self::constant(v)
    }
}

impl Add for Dual64 {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val + rhs.val,
            der: self.der + rhs.der,
        }
    }
}

impl Add<f64> for Dual64 {
    type Output = Self;
    #[inline]
    fn add(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val + rhs,
            der: self.der,
        }
    }
}

impl Sub for Dual64 {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val - rhs.val,
            der: self.der - rhs.der,
        }
    }
}

impl Sub<f64> for Dual64 {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val - rhs,
            der: self.der,
        }
    }
}

impl Mul for Dual64 {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val * rhs.val,
            der: self.der * rhs.val + self.val * rhs.der,
        }
    }
}

impl Mul<f64> for Dual64 {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val * rhs,
            der: self.der * rhs,
        }
    }
}

impl Div for Dual64 {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val / rhs.val,
            der: (self.der * rhs.val - self.val * rhs.der) / (rhs.val * rhs.val),
        }
    }
}

impl Div<f64> for Dual64 {
    type Output = Self;
    #[inline]
    fn div(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val / rhs,
            der: self.der / rhs,
        }
    }
}

impl Neg for Dual64 {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self::Output {
        Self {
            val: -self.val,
            der: -self.der,
        }
    }
}

/// Second-order forward-mode hyper-dual number:
/// $$x + \epsilon_1 x_1 + \epsilon_2 x_2 + \epsilon_1\epsilon_2 x_{12}$$
/// where $\epsilon_1^2 = \epsilon_2^2 = 0$.
///
/// Enables calculating exact first and second derivatives simultaneously in a single pass.
///
/// # Examples
/// ```
/// use quantlib_rs::math::autodiff::HyperDual64;
///
/// // f(x) = x^4, at x = 2: f(2) = 16, f'(2) = 32, f''(2) = 48
/// let x = HyperDual64::variable(2.0);
/// let y = x.powi(4);
///
/// assert_eq!(y.val, 16.0);
/// assert_eq!(y.der1, 32.0);
/// assert_eq!(y.der12, 48.0); // Exact second derivative!
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct HyperDual64 {
    /// Function value
    pub val: f64,
    /// First derivative with respect to variable 1
    pub der1: f64,
    /// First derivative with respect to variable 2
    pub der2: f64,
    /// Second cross derivative $\partial^2 / \partial x_1 \partial x_2$
    pub der12: f64,
}

impl HyperDual64 {
    /// Create a constant with zero derivatives.
    #[inline]
    pub const fn constant(val: f64) -> Self {
        Self {
            val,
            der1: 0.0,
            der2: 0.0,
            der12: 0.0,
        }
    }

    /// Create an active variable for calculating first and second derivative with respect to itself.
    #[inline]
    pub const fn variable(val: f64) -> Self {
        Self {
            val,
            der1: 1.0,
            der2: 1.0,
            der12: 0.0,
        }
    }

    /// Create a custom hyper-dual number.
    #[inline]
    pub const fn new(val: f64, der1: f64, der2: f64, der12: f64) -> Self {
        Self {
            val,
            der1,
            der2,
            der12,
        }
    }

    /// Natural logarithm.
    #[inline]
    pub fn ln(self) -> Self {
        let inv_val = 1.0 / self.val;
        Self {
            val: self.val.ln(),
            der1: self.der1 * inv_val,
            der2: self.der2 * inv_val,
            der12: (self.der12 * self.val - self.der1 * self.der2) * (inv_val * inv_val),
        }
    }

    /// Exponential.
    #[inline]
    pub fn exp(self) -> Self {
        let e = self.val.exp();
        Self {
            val: e,
            der1: self.der1 * e,
            der2: self.der2 * e,
            der12: (self.der12 + self.der1 * self.der2) * e,
        }
    }

    /// Square root.
    #[inline]
    pub fn sqrt(self) -> Self {
        let s = self.val.sqrt();
        let inv_2s = 0.5 / s;
        Self {
            val: s,
            der1: self.der1 * inv_2s,
            der2: self.der2 * inv_2s,
            der12: inv_2s * (self.der12 - self.der1 * self.der2 * inv_2s / s),
        }
    }

    /// Integer power.
    #[inline]
    pub fn powi(self, n: i32) -> Self {
        let nf = n as f64;
        let v_nm1 = self.val.powi(n - 1);
        let v_nm2 = self.val.powi(n - 2);
        Self {
            val: self.val.powi(n),
            der1: nf * v_nm1 * self.der1,
            der2: nf * v_nm1 * self.der2,
            der12: nf * v_nm1 * self.der12 + nf * (nf - 1.0) * v_nm2 * self.der1 * self.der2,
        }
    }

    /// Standard normal cumulative distribution function ($\Phi(u)$).
    #[inline]
    pub fn normal_cdf(self) -> Self {
        let pdf = normal_pdf(self.val);
        Self {
            val: normal_cdf(self.val),
            der1: pdf * self.der1,
            der2: pdf * self.der2,
            der12: pdf * (self.der12 - self.val * self.der1 * self.der2),
        }
    }
}

impl From<f64> for HyperDual64 {
    #[inline]
    fn from(v: f64) -> Self {
        Self::constant(v)
    }
}

impl Add for HyperDual64 {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val + rhs.val,
            der1: self.der1 + rhs.der1,
            der2: self.der2 + rhs.der2,
            der12: self.der12 + rhs.der12,
        }
    }
}

impl Add<f64> for HyperDual64 {
    type Output = Self;
    #[inline]
    fn add(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val + rhs,
            der1: self.der1,
            der2: self.der2,
            der12: self.der12,
        }
    }
}

impl Sub for HyperDual64 {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val - rhs.val,
            der1: self.der1 - rhs.der1,
            der2: self.der2 - rhs.der2,
            der12: self.der12 - rhs.der12,
        }
    }
}

impl Sub<f64> for HyperDual64 {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val - rhs,
            der1: self.der1,
            der2: self.der2,
            der12: self.der12,
        }
    }
}

impl Mul for HyperDual64 {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Self {
            val: self.val * rhs.val,
            der1: self.der1 * rhs.val + self.val * rhs.der1,
            der2: self.der2 * rhs.val + self.val * rhs.der2,
            der12: self.der12 * rhs.val
                + self.der1 * rhs.der2
                + self.der2 * rhs.der1
                + self.val * rhs.der12,
        }
    }
}

impl Mul<f64> for HyperDual64 {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: f64) -> Self::Output {
        Self {
            val: self.val * rhs,
            der1: self.der1 * rhs,
            der2: self.der2 * rhs,
            der12: self.der12 * rhs,
        }
    }
}

impl Div for HyperDual64 {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        let inv_v = 1.0 / rhs.val;
        let inv_v2 = inv_v * inv_v;
        let d1 = (self.der1 * rhs.val - self.val * rhs.der1) * inv_v2;
        let d2 = (self.der2 * rhs.val - self.val * rhs.der2) * inv_v2;
        let d12 = (self.der12 * rhs.val + self.der1 * rhs.der2
            - d1 * rhs.der2 * rhs.val
            - self.der2 * rhs.der1
            - self.val * rhs.der12)
            * inv_v2
            - d1 * rhs.der2 * inv_v;
        Self {
            val: self.val * inv_v,
            der1: d1,
            der2: d2,
            der12: d12,
        }
    }
}

impl Div<f64> for HyperDual64 {
    type Output = Self;
    #[inline]
    fn div(self, rhs: f64) -> Self::Output {
        let inv = 1.0 / rhs;
        Self {
            val: self.val * inv,
            der1: self.der1 * inv,
            der2: self.der2 * inv,
            der12: self.der12 * inv,
        }
    }
}

impl Neg for HyperDual64 {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self::Output {
        Self {
            val: -self.val,
            der1: -self.der1,
            der2: -self.der2,
            der12: -self.der12,
        }
    }
}

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

    #[test]
    fn test_dual_differentiation() {
        // f(x) = x^2 * ln(x)
        // f'(x) = 2x * ln(x) + x
        let x_val = 2.5;
        let x = Dual64::variable(x_val);
        let y = (x * x) * x.ln();

        let expected_val = x_val * x_val * x_val.ln();
        let expected_der = 2.0 * x_val * x_val.ln() + x_val;

        assert!((y.val - expected_val).abs() < 1e-12);
        assert!((y.der - expected_der).abs() < 1e-12);
    }

    #[test]
    fn test_hyperdual_second_derivative() {
        // f(x) = exp(x^2)
        // f'(x) = 2x exp(x^2)
        // f''(x) = (2 + 4x^2) exp(x^2)
        let x_val = 1.2;
        let x = HyperDual64::variable(x_val);
        let y = (x * x).exp();

        let exp_term = (x_val * x_val).exp();
        let expected_der = 2.0 * x_val * exp_term;
        let expected_der2 = (2.0 + 4.0 * x_val * x_val) * exp_term;

        assert!((y.val - exp_term).abs() < 1e-12);
        assert!((y.der1 - expected_der).abs() < 1e-12);
        assert!((y.der12 - expected_der2).abs() < 1e-12);
    }
}