当我使用sapply时,R说我的函数不是函数

问题描述 投票:0回答:2

我试图使用sapply函数来制作一个包含期权价格的向量。我有一个返回期权价格的函数,但是当我尝试使用sapply函数时,我收到了错误信息。

在match.fun(FUN)中出错: 'binomial_option(n, type)'不是一个函数,字符或符号。

我真的不明白为什么它会说它不是一个函数,而是因为在环境中它被指定为一个函数。这是我的代码。

#EXAMPLE PARAMETERS
strike=100
startprice = 110
sigma = 0.15
r=0.1
R=r+1
alpha = r-0.5*sigma^2
T = 1

#AktivTræ
StockTree <- function(n){
  tree = matrix(0, nrow = n+1, ncol =  n+1)
  dt = T/n
  u = exp(sigma*sqrt(dt))
  d = exp(-sigma*sqrt(dt))
  for(i in 1:(n+1)){
    for(j in 1:i){
      tree[i,j] <- startprice*u^(j-1)*d^((i-1)-(j-1))
    }
  }
  return(tree)
}

StockTree(5)

#q-ssh.
q_prob <- function(n){
  dt = T/n
  u = exp(sigma*sqrt(dt))
  d = exp(-sigma*sqrt(dt))

  return((exp(r*dt)-d)/(u-d))
}

q_prob(4)

#OptionsTræ
OptionValue <- function(n,type,tree){
  dt = T/n
  q = q_prob(n)
  OptionTree = matrix(0,nrow=nrow(tree), ncol=ncol(tree))

  if(type == 'put'){
    OptionTree[nrow(OptionTree),] <- pmax(strike-tree[nrow(tree),],0)
  }else if(type == 'call'){
    OptionTree[nrow(OptionTree),] <- pmax(tree[nrow(tree),]-strike,0)
  }
  for (i in (nrow(tree)-1):1) {
    for (j in 1:i){
      OptionTree[i,j] = ((1-q)*OptionTree[i+1,j]+q*OptionTree[i+1,j+1])/exp(r*dt)
    }
  }
  return(OptionTree)
}

OptionValue(5,'call',StockTree((5)))

#Standard Binomial Model
binomial_option <- function(n,type){
  q <- q_prob(n)
  tree <- StockTree(n)
  option <- OptionValue(n,type,tree)
  return(option[1,1])
}

binomial_option(500,'call')

6#New and improved?

Yeet <- function(n,type){
  g <- (1:n)
  Vec = sapply(g,binomial_option(n,type))
  return(Vec)
}

Yeet(5,"Call") 
r finance
2个回答
0
投票

你可能需要在函数中指定二项式期权的哪个参数,你希望在你的sapply函数中显示出g的顺序值。

也许这就是你想要的。

Yeet <- function(n,type){
  g <- (1:n)
  Vec = sapply(g,function(x) binomial_option(x,type))
  return(Vec)
}

Yeet(5,"call")

输出:

[1] 20.42243 20.32801 19.99258 20.30529 20.16248

(我假设你想让g的值是 g 成为 n 二项式_选项的参数)


0
投票

给你

Yeet <- function(n, type){
  g <- 1:n
  Vec = sapply(g, function(x) binomial_option(x, type))
  return(Vec)
}

Yeet(5,"call")
#[1] 20.42243 20.32801 19.99258 20.30529 20.16248
© www.soinside.com 2019 - 2024. All rights reserved.