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
extern crate special;
fn cum_norm(x:f64)->f64 {
use special::Error;
use std::f64::consts::SQRT_2;
(x/SQRT_2).erf()*0.5+0.5
}
pub fn call(s:f64, k:f64, discount:f64, sigma:f64)->f64{
if sigma>0.0{
let d1=(s/(k*discount)).ln()/sigma+0.5*sigma;
return s*cum_norm(d1)-k*discount*cum_norm(d1-sigma);
}
else{
return if s>k {s-k} else {0.0};
}
}
pub fn put(s:f64, k:f64, discount:f64, sigma:f64)->f64{
if sigma>0.0{
let d1=(s/(k*discount)).ln()/sigma+0.5*sigma;
return k*discount*cum_norm(sigma-d1)-s*cum_norm(-d1);
}
else{
return if k>s {k-s} else {0.0};
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn call_formula_works() {
assert_eq!(call(5.0, 4.5, (-0.05 as f64).exp(), 0.3), 0.9848721043419868);
}
#[test]
fn call_formula_works_with_zero_vol() {
assert_eq!(call(5.0, 4.5, (-0.05 as f64).exp(), 0.0), 0.5);
}
#[test]
fn put_formula_works() {
assert_eq!(put(5.0, 4.5, (-0.05 as f64).exp(), 0.3), 0.2654045145951993);
}
#[test]
fn put_formula_works_with_zero_vol() {
assert_eq!(put(5.0, 4.5, (-0.05 as f64).exp(), 0.0), 0.0);
}
}