I have a data frame which could be approximated by the following example:
firm <-seq(c(rep(6,253), rep(7, 252), rep(8,254), rep(9,251))
LTD05 <- seq(1, 1010, 1)
cap <- seq(2,1011,1)
riskfree <- c(rep(1,253), rep(2, 252), rep(3,254), rep(4,251))
equityvol <- seq(0.1, 0.101, 0.1)
df <- data.frame(firm,LTD05,cap,riskfree,equityvol)
LTD 05 is the liabilities of the company, cap is market equity value, riskfree is the risk free return, equityvol is the equity volatility of the company. I want to estimate asset value and asset volatility for each observation in my sample using numerical approach in the Merton model. I run for loop
.
for( i in 1:nrow(df)) {
fnewton <- function(x){
y <- numeric(2)
d1 <- (log(x[1]/df$LTD05[i])+(df$riskfree[i]+x[2]^2/2))/x[2]
d2 <- d1-x[2]
y[1] <- df$cap[i]- (x[1]*pnorm(d1) - exp(-df$riskfree[i])*df$LTD05[i]*pnorm(d2))
y[2]<-df$equityvol[i]*df$cap[i]-pnorm(d1)*x[2]*x[1]
y
}
xstart <- c(df$cap[i]+df$LTD05[i],df$equityvol[i])
data$asset_new_value[i]<-nleqslv(xstart, fnewton, method="Newton")$x[1]
data$asset_new_volat[i]<-nleqslv(xstart, fnewton, method="Newton")$x[2]
i=i+1
}
This question has been discussed already : here . However, my problem is that I get negative value for asset volatility (which is not case in reality) when I run this loop. I suspect that I may have bugs in for loop
. Could you please give any feedback?