R中的Black Scholes期权定价模型

问题描述 投票:1回答:1

我在这里尝试过用R对BS模型进行编码。从数学上讲,我认为这很好,但是代码返回了错误。


price = function(S, K, r, T, sigma, type){

  if(type=="C"){
  d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
  d2 <- d1 - sigma*sqrt(T)

  price = S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
  return(price)}

  if (type=="P"){
  d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
  d2 <- d1 - sig*sqrt(T)

  price =  (K*exp(-r*T)*pnorm(-d2) - S*pnorm(-d1))
  return(price)}

[我试图使用if,否则,如果两个都返回一个“错误:不完整的表达式:”-我希望远离其他地方,因为选项类型必须通过“ C”看涨期权或“ P”进行认沽。

我需要您的帮助来检查为什么代码未运行。

问候

r finance
1个回答
1
投票

您需要关闭功能的支架。另外,第二个if语句具有sig而不是sigma。我已经更改了以下内容:

price = function(S, K, r, T, sigma, type){

  if(type=="C"){
    d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
    d2 <- d1 - sigma*sqrt(T)

    price = S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
    return(price)}

  if (type=="P"){
    d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
    d2 <- d1 - sigma*sqrt(T)

    price =  (K*exp(-r*T)*pnorm(-d2) - S*pnorm(-d1))
    return(price)}
}

这将起作用:

price(50,50,0.05,0.5,0.25,'C')
[1] 4.130008

price(50,50,0.05,0.5,0.25,'P')
[1] 2.895503
© www.soinside.com 2019 - 2024. All rights reserved.