I am currently doing my master thesis on Merton KMV model and I need to implement it to a set of companies. Here is the link to the csv file I used.
I am trying to loop the process to solve the nonlinear equations. So far I have found a solution to solve it once by implementing each parameters manually but now I need to apply it to the whole dataframe.
This is the code I have come up with so far:
Loading file and Library, setting the index
library(nleqslv) #this is a package that solve a non linear equation to compute both the value of teh asset and its volatility according to the Black and Scholes formula in the Merton model
df <- read.csv("/AREX_D.csv")
rownames(df) <- df$Date
start <- as.Date("31-12-16",format="%d-%m-%y")
end <- as.Date("31-12-17",format="%d-%m-%y")
theDate <- start
Definition of the variables
E <- df$Market.Cap
D <- df$Default.point
T <- 1
sigmaE <- df$stdev
r <- -0.017
df$Asset <- NA
df$sigmaA <- NA
df$DD <- NA
df$PD <- NA
Function from the nleqslv package that solve the non linear equation
fnewton <- function(x)
{
y <- numeric(2)
d1 <- (log(x[1]/D)+(r+x[2]^2/2)*T)/x[2]*sqrt(T)
d2 <- d1-x[2]*sqrt(T)
y[1] <- E-(x[1]*pnorm(d1)-exp(-r*T)*D*pnorm(d2))
y[2] <- sigmaE*E-pnorm(d1)*x[2]*x[1]
y
}
Loop that should implement the function to every row in the dataset for the selected dates.
xstart <- c(E+D, sigmaE)#initialising the x-values (asset value and volatility for the function to solve the non linear equation
while (theDate<=end)
{
out <- nleqslv(xstart,fnewton,method="Newton")
df$Asset <- out[1]
df$sigmaA <- out[2]
theDate <- theDate+1
}
print(tail(df))
My two problems are:
- I need to solve the equation for each selected row in the dataset
- The output of the equation is a list and I need to append each value of teh list to two separate columns. I don't know if it is possible.
I have found a package that could solve this issue: ifrogs but it is not available through R version 3.5.1
If anyone has any insight on either problem that would be of termendous help.
Thank you in advance :)