-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathBlackSholes.R
43 lines (39 loc) · 1023 Bytes
/
BlackSholes.R
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
## Black-Scholes Function
BS <- function(S, K, T, r, sig, type="C"){
d1 <- (log(S/K) + (r + sig^2/2)*T) / (sig*sqrt(T))
d2 <- d1 - sig*sqrt(T)
if(type=="C"){
value <- S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
}
if(type=="P"){
value <- K*exp(-r*T)*pnorm(-d2) - S*pnorm(-d1)
}
return(value)
}
## Function to find BS Implied Vol using Bisection Method
implied.vol <-
function(S, K, T, r, market, type){
sig <- 0.20
sig.up <- 1
sig.down <- 0.001
count <- 0
err <- BS(S, K, T, r, sig, type) - market
## repeat until error is sufficiently small or counter hits 1000
while(abs(err) > 0.00001 && count<1000){
if(err < 0){
sig.down <- sig
sig <- (sig.up + sig)/2
}else{
sig.up <- sig
sig <- (sig.down + sig)/2
}
err <- BS(S, K, T, r, sig, type) - market
count <- count + 1
}
## return NA if counter hit 1000
if(count==1000){
return(NA)
}else{
return(sig)
}
}