在R中设置这些积分项时遇到问题。我创建了“term1”以更容易地将其插入到整数代码中,但在尝试不同的代码后我会不断收到各种错误消息。任何帮助或发现问题将不胜感激。
##
S<-readline(prompt="Enter underlying instrument price:")
X<-readline(prompt="Enter strike price:")
V<-readline(prompt="Enter absolute volatility in dollars:")
r<-readline(prompt="Enter risk-free rate (%):")
q<-readline(prompt="Enter dividend yield (%):")
T<-readline(prompt="Enter time to maturity, in fraction of years:")
t=0
##
S<-as.numeric(S)
X<-as.numeric(X)
V<-as.numeric(V)
r<-as.numeric(r)/100
q<-as.numeric(q)/100
T<-as.numeric(T)
##Bond Price
B<-exp(r*(T-t))
##Volatility
vol<-function(start,end,rate,yield,B) {
if(r==q){
V*(sqrt((B-1)/(2*(r-q))))
}
else{
V*(sqrt(T-t))
}
}
##d
d<-(S*B-X)/vol()
##N(d)
term1<-(exp(-(r^2)/2)/sqrt(2*pi))
#Call
Nc<-function(term1){
Nc<-((integrate(term1,-Inf,d)))}
#Put
Np<-function(term1){
Np<-(-(integrate(term1,-Inf,d)))}
这些是我得到的错误
> Nc(term1)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'term1' of mode 'function' was not found
> Nc()
Error in match.fun(f) : argument "term1" is missing, with no default
答案 0 :(得分:-1)
嗯,最大的问题是:您是否阅读了函数integrate
的文档?
您分配给该函数的第一个参数必须是一个函数。
第二个问题是,你定义的函数Nc没有返回任何输出(你可以通过不将integrate
的结果赋给一个对象来修复它,而只是返回它。相同的是Np.Np的另一个问题是,它实际上会向一元运算符返回一个错误&#34;意外的参数&#34;
无论如何,这里的代码有一些变化:
## Assign some "random" numbers to the variables, so that I can run the script
S<-100
X<-110
V<-3
r<-10
q<-15
# Is it a good idea to have variable called T? T stands also for TRUE
T <- 10
t=0
##
S<-as.numeric(S)
X<-as.numeric(X)
V<-as.numeric(V)
r<-as.numeric(r)/100
q<-as.numeric(q)/100
T<-as.numeric(T)
##Bond Price
B<-exp(r*(T-t))
##Volatility
vol<-function(start,end,rate,yield,B) {
if(r==q){
V*(sqrt((B-1)/(2*(r-q))))
}
else{
V*(sqrt(T-t))
}
}
##d
d<-(S*B-X)/vol()
# make term1 a function of r, so that there is actually something to integrate...
term1<-function(r) {(exp(-(r^2)/2)/sqrt(2*pi))}
# Do not assign the result of integration to an object, otherwise there will be no output from the function
Nc<-function(term1){
((integrate(term1,-Inf,d)))}
# In order to use the minus sign, you have to extract the value from the result of function "integrate"
Np<-function(term1){
(-(integrate(term1,-Inf,d)$value))}