scirs2-integrate 0.4.1

Numerical integration module for SciRS2 (scirs2-integrate)
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
//! Vanilla derivatives pricing and analysis
//!
//! This module implements pricing models and analytical tools for standard vanilla derivatives
//! including European/American options, forwards, and futures contracts.

use crate::error::{IntegrateError, IntegrateResult};
use crate::specialized::finance::pricing::black_scholes::normal_cdf;
use crate::specialized::finance::risk::greeks::Greeks;
use crate::specialized::finance::types::OptionType;

/// European vanilla option
#[derive(Debug, Clone)]
pub struct EuropeanOption {
    pub spot: f64,
    pub strike: f64,
    pub rate: f64,
    pub dividend: f64,
    pub volatility: f64,
    pub time: f64,
    pub option_type: OptionType,
}

impl EuropeanOption {
    /// Create a new European option
    pub fn new(
        spot: f64,
        strike: f64,
        rate: f64,
        dividend: f64,
        volatility: f64,
        time: f64,
        option_type: OptionType,
    ) -> Self {
        Self {
            spot,
            strike,
            rate,
            dividend,
            volatility,
            time,
            option_type,
        }
    }

    /// Calculate option price using Black-Scholes formula
    pub fn price(&self) -> f64 {
        black_scholes_price(
            self.spot,
            self.strike,
            self.rate,
            self.dividend,
            self.volatility,
            self.time,
            self.option_type,
        )
    }

    /// Calculate Greeks
    pub fn greeks(&self) -> Greeks {
        Greeks::black_scholes(
            self.spot,
            self.strike,
            self.rate,
            self.dividend,
            self.volatility,
            self.time,
            self.option_type,
        )
    }

    /// Calculate implied volatility using Newton-Raphson method
    pub fn implied_volatility(&self, market_price: f64) -> IntegrateResult<f64> {
        implied_volatility_newton(
            market_price,
            self.spot,
            self.strike,
            self.rate,
            self.dividend,
            self.time,
            self.option_type,
        )
    }
}

/// American vanilla option (with early exercise)
#[derive(Debug, Clone)]
pub struct AmericanOption {
    pub spot: f64,
    pub strike: f64,
    pub rate: f64,
    pub dividend: f64,
    pub volatility: f64,
    pub time: f64,
    pub option_type: OptionType,
}

impl AmericanOption {
    /// Create a new American option
    pub fn new(
        spot: f64,
        strike: f64,
        rate: f64,
        dividend: f64,
        volatility: f64,
        time: f64,
        option_type: OptionType,
    ) -> Self {
        Self {
            spot,
            strike,
            rate,
            dividend,
            volatility,
            time,
            option_type,
        }
    }

    /// Calculate option price using Barone-Adesi-Whaley approximation
    pub fn price(&self) -> f64 {
        // For American call with no dividends, same as European
        if self.option_type == OptionType::Call && self.dividend == 0.0 {
            return black_scholes_price(
                self.spot,
                self.strike,
                self.rate,
                self.dividend,
                self.volatility,
                self.time,
                self.option_type,
            );
        }

        // Use Barone-Adesi-Whaley approximation for puts and dividend-paying calls
        barone_adesi_whaley(
            self.spot,
            self.strike,
            self.rate,
            self.dividend,
            self.volatility,
            self.time,
            self.option_type,
        )
    }

    /// Calculate approximate Greeks (using European as approximation)
    pub fn greeks(&self) -> Greeks {
        Greeks::black_scholes(
            self.spot,
            self.strike,
            self.rate,
            self.dividend,
            self.volatility,
            self.time,
            self.option_type,
        )
    }
}

/// Forward contract
#[derive(Debug, Clone)]
pub struct Forward {
    pub spot: f64,
    pub strike: f64,
    pub rate: f64,
    pub dividend: f64,
    pub time: f64,
}

impl Forward {
    /// Create a new forward contract
    pub fn new(spot: f64, strike: f64, rate: f64, dividend: f64, time: f64) -> Self {
        Self {
            spot,
            strike,
            rate,
            dividend,
            time,
        }
    }

    /// Calculate forward price
    pub fn price(&self) -> f64 {
        self.spot * ((self.rate - self.dividend) * self.time).exp() - self.strike
    }

    /// Calculate fair forward strike
    pub fn fair_strike(&self) -> f64 {
        self.spot * ((self.rate - self.dividend) * self.time).exp()
    }
}

/// Black-Scholes pricing formula
pub fn black_scholes_price(
    spot: f64,
    strike: f64,
    rate: f64,
    dividend: f64,
    volatility: f64,
    time: f64,
    option_type: OptionType,
) -> f64 {
    let sqrt_time = time.sqrt();
    let d1 = ((spot / strike).ln() + (rate - dividend + 0.5 * volatility * volatility) * time)
        / (volatility * sqrt_time);
    let d2 = d1 - volatility * sqrt_time;

    match option_type {
        OptionType::Call => {
            spot * (-(dividend * time)).exp() * normal_cdf(d1)
                - strike * (-(rate * time)).exp() * normal_cdf(d2)
        }
        OptionType::Put => {
            strike * (-(rate * time)).exp() * normal_cdf(-d2)
                - spot * (-(dividend * time)).exp() * normal_cdf(-d1)
        }
    }
}

/// Barone-Adesi-Whaley approximation for American options
fn barone_adesi_whaley(
    spot: f64,
    strike: f64,
    rate: f64,
    dividend: f64,
    volatility: f64,
    time: f64,
    option_type: OptionType,
) -> f64 {
    // European price as lower bound
    let european_price =
        black_scholes_price(spot, strike, rate, dividend, volatility, time, option_type);

    // Intrinsic value
    let intrinsic = match option_type {
        OptionType::Call => (spot - strike).max(0.0),
        OptionType::Put => (strike - spot).max(0.0),
    };

    // Simple approximation: use European price plus a fraction of early exercise premium
    // For a more accurate implementation, use binomial/trinomial trees
    let early_exercise_premium = match option_type {
        OptionType::Put => {
            // Puts have significant early exercise value
            let max_early_value = (intrinsic - european_price).max(0.0);
            // Approximate premium based on moneyness and time
            let moneyness = spot / strike;
            let time_factor = 1.0 - (-2.0 * time).exp();

            if moneyness < 0.95 {
                // Deep in the money - higher premium
                max_early_value * 0.5 * time_factor
            } else if moneyness < 1.05 {
                // At the money - moderate premium
                max_early_value * 0.3 * time_factor
            } else {
                // Out of the money - small premium
                max_early_value * 0.1 * time_factor
            }
        }
        OptionType::Call => {
            // Calls with dividends have early exercise value
            if dividend > 0.0 {
                let max_early_value = (intrinsic - european_price).max(0.0);
                let div_factor = dividend / rate;
                max_early_value * 0.2 * div_factor * (1.0 - (-time).exp())
            } else {
                0.0
            }
        }
    };

    // Return max of European price with premium or intrinsic value
    (european_price + early_exercise_premium).max(intrinsic)
}

/// Helper function for d1 at critical price
fn d1_star(s_star: f64, strike: f64, rate: f64, dividend: f64, volatility: f64, time: f64) -> f64 {
    ((s_star / strike).ln() + (rate - dividend + 0.5 * volatility * volatility) * time)
        / (volatility * time.sqrt())
}

/// Calculate implied volatility using Newton-Raphson method
pub fn implied_volatility_newton(
    market_price: f64,
    spot: f64,
    strike: f64,
    rate: f64,
    dividend: f64,
    time: f64,
    option_type: OptionType,
) -> IntegrateResult<f64> {
    // Initial guess using Brenner-Subrahmanyam approximation
    let mut vol = (2.0 * std::f64::consts::PI / time).sqrt() * (market_price / spot);
    vol = vol.max(0.01).min(5.0); // Bound initial guess

    const MAX_ITERATIONS: usize = 100;
    const TOLERANCE: f64 = 1e-6;

    for _ in 0..MAX_ITERATIONS {
        let price = black_scholes_price(spot, strike, rate, dividend, vol, time, option_type);
        let diff = price - market_price;

        if diff.abs() < TOLERANCE {
            return Ok(vol);
        }

        // Calculate vega for Newton step
        let sqrt_time = time.sqrt();
        let d1 =
            ((spot / strike).ln() + (rate - dividend + 0.5 * vol * vol) * time) / (vol * sqrt_time);
        let nprime_d1 = (1.0 / (2.0 * std::f64::consts::PI).sqrt()) * (-0.5 * d1 * d1).exp();
        let vega = spot * (-(dividend * time)).exp() * nprime_d1 * sqrt_time;

        if vega < 1e-10 {
            return Err(IntegrateError::ValueError(
                "Vega too small for convergence".to_string(),
            ));
        }

        // Newton step
        vol -= diff / vega;

        // Ensure vol stays in reasonable range
        vol = vol.max(0.001).min(5.0);
    }

    Err(IntegrateError::ValueError(
        "Implied volatility failed to converge".to_string(),
    ))
}

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

    #[test]
    fn test_european_call_price() {
        let option = EuropeanOption::new(
            100.0, // spot
            100.0, // strike
            0.05,  // rate
            0.0,   // dividend
            0.2,   // volatility
            1.0,   // time
            OptionType::Call,
        );

        let price = option.price();
        // Black-Scholes reference: ~10.45
        assert!(price > 10.0 && price < 11.0, "Price: {}", price);
    }

    #[test]
    fn test_european_put_price() {
        let option = EuropeanOption::new(
            100.0, // spot
            100.0, // strike
            0.05,  // rate
            0.0,   // dividend
            0.2,   // volatility
            1.0,   // time
            OptionType::Put,
        );

        let price = option.price();
        // Black-Scholes reference: ~5.57
        assert!(price > 5.0 && price < 6.0, "Price: {}", price);
    }

    #[test]
    fn test_put_call_parity() {
        let spot = 100.0;
        let strike = 100.0;
        let rate = 0.05;
        let dividend = 0.0;
        let volatility = 0.2;
        let time = 1.0;

        let call = EuropeanOption::new(
            spot,
            strike,
            rate,
            dividend,
            volatility,
            time,
            OptionType::Call,
        );
        let put = EuropeanOption::new(
            spot,
            strike,
            rate,
            dividend,
            volatility,
            time,
            OptionType::Put,
        );

        // Put-Call Parity: C - P = S - K*exp(-rT)
        let lhs = call.price() - put.price();
        let rhs = spot - strike * (-(rate * time)).exp();

        assert!((lhs - rhs).abs() < 1e-10, "Put-call parity violated");
    }

    #[test]
    fn test_american_put_premium() {
        let american = AmericanOption::new(
            100.0, // spot
            100.0, // strike
            0.05,  // rate
            0.0,   // dividend
            0.2,   // volatility
            1.0,   // time
            OptionType::Put,
        );

        let european = EuropeanOption::new(
            100.0, // spot
            100.0, // strike
            0.05,  // rate
            0.0,   // dividend
            0.2,   // volatility
            1.0,   // time
            OptionType::Put,
        );

        // American put should be worth more than European put
        assert!(
            american.price() >= european.price(),
            "American put should be >= European put"
        );
    }

    #[test]
    fn test_forward_price() {
        let forward = Forward::new(
            100.0, // spot
            105.0, // strike
            0.05,  // rate
            0.0,   // dividend
            1.0,   // time
        );

        let price = forward.price();
        let expected = 100.0 * (0.05_f64).exp() - 105.0; // ~0.13

        assert!((price - expected).abs() < 0.1, "Forward price: {}", price);
    }

    #[test]
    fn test_implied_volatility() {
        let option = EuropeanOption::new(
            100.0, // spot
            100.0, // strike
            0.05,  // rate
            0.0,   // dividend
            0.2,   // volatility (target)
            1.0,   // time
            OptionType::Call,
        );

        let market_price = option.price();
        let implied_vol = option
            .implied_volatility(market_price)
            .expect("Operation failed");

        // Should recover the original volatility
        assert!(
            (implied_vol - 0.2).abs() < 1e-4,
            "Implied vol: {}, expected: 0.2",
            implied_vol
        );
    }

    #[test]
    fn test_greeks_calculation() {
        let option = EuropeanOption::new(
            100.0, // spot
            100.0, // strike
            0.05,  // rate
            0.0,   // dividend
            0.2,   // volatility
            1.0,   // time
            OptionType::Call,
        );

        let greeks = option.greeks();

        // Sanity checks for Greeks
        assert!(
            greeks.delta > 0.0 && greeks.delta < 1.0,
            "Delta: {}",
            greeks.delta
        );
        assert!(greeks.gamma > 0.0, "Gamma: {}", greeks.gamma);
        assert!(greeks.vega > 0.0, "Vega: {}", greeks.vega);
        assert!(greeks.theta < 0.0, "Theta: {}", greeks.theta); // Time decay is negative
        assert!(greeks.rho > 0.0, "Rho: {}", greeks.rho); // Call has positive rho
    }
}