【发布时间】:2019-03-25 18:15:57
【问题描述】:
我目前正在完成关于 Merton KMV 模型的硕士论文,我需要将它实施到一组公司。这是我使用的csv file 的链接。
我正在尝试循环求解非线性方程的过程。到目前为止,我已经找到了一个解决方案,可以通过手动实现每个参数来解决它,但现在我需要将它应用到整个数据框。
这是我目前想出的代码:
加载文件和库,设置索引
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
变量的定义
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
nleqslv 包中求解非线性方程的函数
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
}
应该为所选日期的数据集中每一行实现函数的循环。
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))
我的两个问题是:
- 我需要求解数据集中每个选定行的方程
- 等式的输出是一个列表,我需要将列表的每个值附加到两个单独的列中。不知道有没有可能。
我找到了一个可以解决这个问题的包:ifrogs,但它在 R 版本 3.5.1 中不可用
如果有人对这两个问题有任何见解,那将是巨大的帮助。
提前谢谢你:)
【问题讨论】:
-
请提供一个可重现的例子。见here。请在
<-前后使用空格,避免使用r<--0.017之类的内容。r <- -0.017更容易阅读和理解。 -
感谢您的精确。我已经编辑了代码并包含了对我使用的 CSV 文件的引用。我希望它更接近于一个可重现的例子。
标签: r loops dataframe while-loop