【问题标题】:R says my function isn't a function when I use sapply on itR 说我的函数在我使用 sapply 时不是函数
【发布时间】:2020-05-03 09:43:10
【问题描述】:

我正在尝试使用 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


    【解决方案1】:

    您可能需要指定 binomial_option 的哪个参数,您希望 g 的顺序值出现在您的 sapply 中。

    也许这就是你想要的:

    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 的值成为 binomial_option 的 n 参数)

    【讨论】:

      【解决方案2】:

      这里:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多