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
//! # black_scholes
//! A Black Scholes option pricing library.

use std::f64::consts::{PI, SQRT_2};
use special::Error;



fn cum_norm(x:f64)->f64 {
    (x/SQRT_2).erf()*0.5+0.5
}
fn inc_norm(x:f64)->f64 {
    (-x.powi(2)/2.0).exp()/(PI.sqrt()*SQRT_2)
}

/// Returns BS call option formula with discount and volatility already computed.
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let discount = 0.99;
/// let sigma = 0.3;
/// let maturity:f64 = 2.0;
/// let sqrt_maturity_sigma = sigma*maturity.sqrt();
/// let price = black_scholes::call_discount(
///     stock, strike, discount, 
///     sqrt_maturity_sigma
/// );
/// ```
pub fn call_discount(s:f64, k:f64, discount:f64, sqrt_maturity_sigma:f64)->f64{
    if sqrt_maturity_sigma>0.0{
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        s*cum_norm(d1)-k*discount*cum_norm(d1-sqrt_maturity_sigma)
    }
    else{
        if s>k {s-k} else {0.0}
    }
}

/// Returns standard BS call option formula.
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// assert_eq!(0.9848721043419868, black_scholes::call(stock, strike, rate, sigma, maturity));
/// ```
pub fn call(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    call_discount(s, k, (-rate*maturity).exp(), maturity.sqrt()*sigma)
}

/// Returns delta of a BS call option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let delta = black_scholes::call_delta(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn call_delta(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    let sqrt_maturity_sigma=maturity.sqrt()*sigma;
    if sqrt_maturity_sigma>0.0{
        let discount=(-rate*maturity).exp();
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        cum_norm(d1)
    }
    else{
        if s>k {1.0} else {0.0}
    }
}

/// Returns gamma of a BS call option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let gamma = black_scholes::call_gamma(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn call_gamma(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    let sqrt_maturity_sigma=maturity.sqrt()*sigma;    
    if sqrt_maturity_sigma>0.0{
        let discount=(-rate*maturity).exp();
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        inc_norm(d1)/(s*sqrt_maturity_sigma)
    }
    else{
        0.0
    }
}
/// Returns vega of a BS call option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let vega = black_scholes::call_vega(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn call_vega(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    let sqrt_maturity_sigma=maturity.sqrt()*sigma;    
    if sqrt_maturity_sigma>0.0{
        let discount=(-rate*maturity).exp();
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        s*inc_norm(d1)*sqrt_maturity_sigma/sigma
    }
    else{
        0.0
    }
}
/// Returns theta of a BS call option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let theta = black_scholes::call_theta(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn call_theta(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    let sqrt_t=maturity.sqrt();
    let sqrt_maturity_sigma=sqrt_t*sigma;    
    if sqrt_maturity_sigma>0.0{
        let discount=(-rate*maturity).exp();
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        -s*inc_norm(d1)*sigma/(2.0*sqrt_t)-rate*k*discount*cum_norm(d1-sqrt_maturity_sigma)
    }
    else{
        0.0
    }
}

/// Returns BS put option formula with discount and volatility already computed.
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let discount = 0.99;
/// let sigma = 0.3;
/// let maturity:f64 = 2.0;
/// let sqrt_maturity_sigma = sigma*maturity.sqrt();
/// let price = black_scholes::put_discount(
///     stock, strike, discount, 
///     sqrt_maturity_sigma
/// );
/// ```
pub fn put_discount(s:f64, k:f64, discount:f64, sqrt_maturity_sigma:f64)->f64{
    if sqrt_maturity_sigma>0.0{
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        k*discount*cum_norm(sqrt_maturity_sigma-d1)-s*cum_norm(-d1)
    }
    else{
        if k>s {k-s} else {0.0}
    }
}

/// Returns BS put option formula.
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma = 0.3;
/// let maturity = 1.0;
/// assert_eq!(0.2654045145951993, black_scholes::put(stock, strike, rate, sigma, maturity));
/// ```
pub fn put(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    put_discount(s, k, (-rate*maturity).exp(), maturity.sqrt()*sigma)
}

/// Returns delta of a BS put option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let delta = black_scholes::put_delta(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn put_delta(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    let sqrt_maturity_sigma=maturity.sqrt()*sigma;
    if sqrt_maturity_sigma>0.0{
        let discount=(-rate*maturity).exp();  
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        return cum_norm(d1)-1.0;
    }
    else{
        return if k>s {-1.0} else {0.0};
    }
}
/// Returns gamma of a BS put option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let gamma = black_scholes::put_gamma(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn put_gamma(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    call_gamma(s, k, rate, sigma, maturity)//same as call
}

/// Returns vega of a BS put option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let vega = black_scholes::put_vega(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn put_vega(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    call_vega(s, k, rate, sigma, maturity) //same as call
}

/// Returns theta of a BS put option
///
/// # Examples
///
/// ```
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let sigma=0.3;
/// let maturity=1.0;
/// let theta = black_scholes::put_theta(
///     stock, strike, rate, sigma, maturity
/// );
/// ```
pub fn put_theta(s:f64, k:f64, rate:f64, sigma:f64, maturity:f64)->f64{
    let sqrt_t=maturity.sqrt();
    let sqrt_maturity_sigma=sqrt_t*sigma;    
    if sqrt_maturity_sigma>0.0{
        let discount=(-rate*maturity).exp();
        let d1=(s/(k*discount)).ln()/sqrt_maturity_sigma+0.5*sqrt_maturity_sigma;
        -s*inc_norm(d1)*sigma/(2.0*sqrt_t)+rate*k*discount*cum_norm(-d1+sqrt_maturity_sigma)
    }
    else{
        0.0
    }
}
const SQRT_TWO_PI:f64=2.0*std::f64::consts::SQRT_2/std::f64::consts::FRAC_2_SQRT_PI;
//Corrado and Miller (1996) 
fn approximate_vol(price:f64, s:f64, k:f64, rate:f64, maturity:f64)->f64{
    let discount=(-rate*maturity).exp();
    let x=k*discount;
    let coef=SQRT_TWO_PI/(s+x);
    let helper_1=s-x;
    let c1=price-helper_1*0.5;
    let c2=c1.powi(2);
    let c3=helper_1.powi(2)/std::f64::consts::PI;
    let bridge_1=c2-c3;
    let bridge_m=if bridge_1>0.0 { bridge_1.sqrt() } else { 0.0 };
    coef*(c1+bridge_m)/maturity.sqrt()
}
/// Returns implied volatility from a call option with initial guess
///
/// # Examples
///
/// ```
/// let price = 1.0;
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let maturity = 1.0;
/// let initial_guess = 0.3;
/// let iv = black_scholes::call_iv_guess(
///     price, stock, strike, rate, 
///     maturity, initial_guess
/// ).unwrap();
/// ```
pub fn call_iv_guess(price:f64, s:f64, k:f64, rate:f64, maturity:f64, initial_guess:f64)->Result<f64, f64>{
    let obj_fn=|sigma|call(s, k, rate, sigma, maturity)-price;
    let dfn=|sigma|call_vega(s, k, rate, sigma, maturity);
    let precision=0.000001;
    let iterations=10000;
    nrfind::find_root(&obj_fn, &dfn, initial_guess, precision, iterations)
}
/// Returns implied volatility from a call option
///
/// # Examples
///
/// ```
/// let price = 1.0;
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let maturity = 1.0;
/// let iv = black_scholes::call_iv(
///     price, stock, strike, rate, 
///     maturity
/// ).unwrap();
/// ```
pub fn call_iv(price:f64, s:f64, k:f64, rate:f64, maturity:f64)->Result<f64, f64>{
    let initial_guess=approximate_vol(price, s, k, rate, maturity);
    call_iv_guess(price, s, k, rate, maturity, initial_guess)
}

/// Returns implied volatility from a put option with initial guess
///
/// # Examples
///
/// ```
/// let price = 0.3;
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let maturity = 1.0;
/// let initial_guess = 0.3;
/// let iv = black_scholes::put_iv_guess(
///     price, stock, strike, rate, 
///     maturity, initial_guess
/// ).unwrap();
/// ```
pub fn put_iv_guess(price:f64, s:f64, k:f64, rate:f64, maturity:f64, initial_guess:f64)->Result<f64, f64>{
    let obj_fn=|sigma|put(s, k, rate, sigma, maturity)-price;
    let dfn=|sigma|put_vega(s, k, rate, sigma, maturity);
    let precision=0.000001;
    let iterations=10000;
    nrfind::find_root(&obj_fn, &dfn, initial_guess, precision, iterations)
}
/// Returns implied volatility from a put option
///
/// # Examples
///
/// ```
/// let price = 0.3;
/// let stock = 5.0;
/// let strike = 4.5;
/// let rate = 0.05;
/// let maturity = 1.0;
/// let initial_guess = 0.3;
/// let iv = black_scholes::put_iv(
///     price, stock, strike, rate, 
///     maturity
/// ).unwrap();
/// ```
pub fn put_iv(price:f64, s:f64, k:f64, rate:f64, maturity:f64)->Result<f64, f64>{
    let c_price=price+s-k*(-rate*maturity).exp();
    let initial_guess=approximate_vol(c_price, s, k, rate, maturity);
    put_iv_guess(price, s, k, rate, maturity, initial_guess)
}



#[cfg(test)]
mod tests {
    use super::*;
    use rand::{SeedableRng, StdRng};
    use rand::distributions::{Distribution, Uniform};
    use approx::*;
    fn get_rng_seed(seed:[u8; 32])->StdRng{
        SeedableRng::from_seed(seed) 
    }
    fn get_over_region(lower:f64, upper:f64, rand:f64)->f64{
        lower+(upper-lower)*rand
    }
    #[test]
    fn sqrt_two_pi_is_right(){
        assert_abs_diff_eq!(SQRT_TWO_PI, (2.0*std::f64::consts::PI).sqrt(), epsilon=0.000000001);
    }
    #[test]
    fn call_formula_works() {
        assert_eq!(call(5.0, 4.5, 0.05, 0.3, 1.0), 0.9848721043419868);
    }
    #[test]
    fn call_formula_works_with_zero_vol() {
        assert_eq!(call(5.0, 4.5, 0.05, 0.3, 0.0), 0.5);
    }
    #[test]
    fn put_formula_works() {
        assert_eq!(put(5.0, 4.5, 0.05, 0.3, 1.0), 0.2654045145951993);
    }
    #[test]
    fn put_formula_works_with_zero_vol() {
        assert_eq!(put(5.0, 4.5, 0.05, 0.3, 0.0), 0.0);
    }
    #[test]
    fn call_iv_works(){
        let sigma=0.2;
        let initial_guess=0.5;
        let s=5.0;
        let k=4.5;
        let rate=0.05;
        let maturity=1.0;
        let price=call(s, k, rate, sigma, maturity);
        assert_abs_diff_eq!(call_iv_guess(price, s, k, rate, maturity , initial_guess).unwrap(), sigma, epsilon=0.00000001);
    }
    #[test]
    fn call_iv_approx(){
        let sigma=0.2;
        let s=5.0;
        let k=4.5;
        let rate=0.05;
        let maturity=1.0;
        let price=call(s, k, rate, sigma, maturity);
        let approx_vol=approximate_vol(price, s, k, rate, maturity);
        println!("approx: {}", approx_vol);
        assert_abs_diff_eq!(sigma, approx_vol, epsilon=0.01);
    }
    #[test]
    fn call_iv_works_with_broad_set_of_numbers(){
        let seed:[u8; 32]=[2; 32];
        let mut rng_seed=get_rng_seed(seed);
        let uniform=Uniform::new(0.0f64, 1.0);
        let num_total:usize=10000;
        
        (0..num_total).for_each(|_|{
            let s=1.0;
            let k=get_over_region(0.3, 3.0, uniform.sample(&mut rng_seed));
            let sigma=get_over_region(0.1, 2.0, uniform.sample(&mut rng_seed));
            let rate=0.0247;
            let maturity=0.7599;
            let price=call(s, k, rate, sigma, maturity);
            let initial_guess=approximate_vol(price, s, k, rate, maturity);
            //println!("s: {}, k: {}, sigma: {}, price: {}, initial_guess: {}", s, k, sigma, price, initial_guess);
            if price>0.000001{
                let _iv=call_iv_guess(price, s, k, rate, maturity , initial_guess).unwrap();
            }
            
        })
    }
    #[test]
    fn call_iv_works_with_difficult(){
        let s= 0.43065239380643594;
        let k=0.5016203266170813;
        let sigma=0.4192621453186373;
        let rate=0.0247;
        let maturity=0.7599;
        let price=call(s, k, rate, sigma, maturity);
        println!("s: {}, k: {}, sigma: {}, price: {}", s, k, sigma, price);
        let _iv=call_iv(price, s, k, rate, maturity).unwrap();
    }
    #[test]
    fn put_iv_works(){
        let sigma=0.2;
        //let initial_guess=0.195;
        let s=5.0;
        let k=4.5;
        let rate=0.05;
        let maturity=1.0;
        let price=put(s, k, rate, sigma, maturity);
        assert_abs_diff_eq!(put_iv(price, s, k, rate, maturity).unwrap(), sigma, epsilon=0.00000001);
    }
    #[test]
    fn call_iv_returns_err_if_no_possible_solution(){
        let price=50.275;
        let s=274.525;
        let k=225.000;
        let rate=0.0244;
        let maturity=0.156;
        assert!(call_iv(price, s, k, rate,maturity).is_err());
    }
}