user7075507
user7075507

Reputation:

Trying to Create my Very First User Defined Function

I've been using R for a while now, just for simple things. Now, I'm trying to create a function to calculate the Black-Scholes value of an asset. This is a pretty standard thing in the finance sector. I'm pretty sure the syntax is right, but I'm getting a weird result.

Here are my parameters:

myfunction(1000000000,500000000,.04,.2,5)

Here is my function:

myfunction <- function(Firm_Value, Face_Value, Rate, Volatility_Value, Time)
{
s <- Firm_Value
X <- Face_Value
r <- Rate
v <- Volatility_Value
T <- Time
t1 <- log(s / X) + (r + v ^ 2 / 2) * T
t2 <- v * sqrt(T)
d1 <- t1 / t2
t3 <- log(s / X) + (r - v ^ 2 / 2) * T
d2 <- t3 / t2
ta <- s * qnorm(d1)
tb <- X * exp( - r * T) * qnorm(d2)
Equityvalue <- ta - tb
}

Here is my result:

Warning messages:
1: In qnorm(d1) : NaNs produced
2: In qnorm(d2) : NaNs produced

The result should actually be:

$593,035,186.31

What am I doing wrong here?

Upvotes: 0

Views: 69

Answers (1)

Brandon LeBeau
Brandon LeBeau

Reputation: 331

The issue is that the qnorm function wants a probability. If you go through the individual calculations in the function, d1 and d2 do not give a probability. I'm thinking they give a quantile instead. I think you want pnorm instead of qnorm.

myfunction <- function(Firm_Value, Face_Value, Rate, Volatility_Value, Time)
{
s <- Firm_Value
X <- Face_Value
r <- Rate
v <- Volatility_Value
T <- Time
t1 <- log(s / X) + (r + v ^ 2 / 2) * T
t2 <- v * sqrt(T)
d1 <- t1 / t2
t3 <- log(s / X) + (r - v ^ 2 / 2) * T
d2 <- t3 / t2
ta <- s * pnorm(d1)
tb <- X * exp( - r * T) * pnorm(d2)
Equityvalue <- ta - tb
Equityvalue
}

Note: I also returned the final calculation by adding Equityvalue at the end. Your function above would not have printed the final result when calling the function.

Upvotes: 3

Related Questions