Blackscholes_formula <- function(spot,timetomat,strike,r,q=0,sigma,opt_type=1,greek_type=1)
{
d_1<-(log(spot/k) + (r+ (sigma^2)/2)(timetomat))/sigma*sqrt(T-t)
d_2 <-d_1-((sigma^2)/2)*timetomat)
if(greek_type == 1) result <- spot*pnorm(d_1)- K exp(-r*timetomat)*pnorm(d_2)
if(greek_type == 2) result <- pnorm(d_1)
Blackscholes_formula <- result
}
I am starting to program, and due to my field I started with R. However I am struggling to write a piece of code that works. Upon programming the Black-Scholes valuation formula above I get the error message:
Error: unexpected '}' in "}"
I have searched on the web for similar errors but despite the fact that the "symptom" is the same, the source of errors are different. I do not know if I am doing a major mistake on the code or what it is the problem.
Question:
I would be grateful if someone could give feed-back on how to improve the aforementioned code.
Thanks in advance!
A few things. First, I think you are missing an asterisk, but there are other issues.
K
. This variable is also upper and lower case in your function. You also need variables t
and t_cap
. (We don't use T
as a variable because it is reserved for TRUE
)K
in the first if()
statement (how does K
interact with exp()
?)result
.Here's a function that compiled for me, with all new variables set to 1
Blackscholes_formula <- function(spot,timetomat,strike,r, K = 1, t = 1, t_cap = 1, q=0,sigma = 1,opt_type=1,greek_type=1){
d_1 <- (log(spot/K) + (r+ (sigma^2)/2) * (timetomat))/sigma*sqrt(t_cap-t)
d_2 <- d_1-((sigma^2)/2)*timetomat
if(greek_type == 1) result <- spot*pnorm(d_1)- K*exp(-r*timetomat)*pnorm(d_2)
if(greek_type == 2) result <- pnorm(d_1)
result
}
Blackscholes_formula(1,2,3,4)