在R

时间:2018-10-13 00:46:18

标签: r finance volatility nlm

我有一项作业,要求我使用参数和市场价格来计算一系列期权的隐含波动率。我知道,执行此操作的简单方法是在R中使用compute.implied.volatility函数,但是这个问题需要我使用nlm函数来解决。我了解在这种情况下,我想最小化实际价格与我计算的价格之间的距离,以使该距离为零。为此,我显然希望更改期权的波动性,以使我的计算得出的价格等于市场价格。我在此问题上遇到的麻烦是使nlm函数正常工作,因为在本课程中我们并未对此进行过多的了解。

我知道我打算向nlm提供一个循环,使它可以迭代计算,直到找到产生结果的最小值为止。我认为我没有提供与nlm一起使用的函数,因为我目前遇到“ nlm优化器中无效的函数值”的错误。

我已经附加了我的代码以及可以使用的输入,请告诉我我是否写错了或者是否需要修改一下才能得到所需波动率的答案。感谢您提供的所有帮助!

```{r}
# Load in the library's and clear workspace
{cat("\014")  
   rm(list=ls(all=TRUE))  
   options(digits=6)}

library(fBasics)
library(knitr)
library(zoo)
library(psych)
library(lubridate)
library(stats)
library(boot)
library(matrixStats)

# First setup the parameter vectors to use in calculating IV
S <- rep(1200, 12) # Price at time = 0
r <- rep(0.01, 12) # Current interest rate
T <- rep(44/365, 12) # Time till maturity of the options
X <- c(1100,1120,1140,1160,1180,1200,1220,1240,1260,1280,1300,1320) # 
Strike prices of each option
type <- c(1,1,1,1,1,1,0,0,0,0,0,0) # 1 = Put and 0 = Call variable
mktprice <- c(10.5,13.8,18.2,23.9,31.2,40,31.8,23.9,17.5,12.5,9.0,6.3) 
# Market price of each option
sigma <- rep(0.2, 12) # Initial guess for sigma

options.df <- data.frame(S, X, r, T, type, mktprice, sigma)

# 1. First specify the Black-Scholes Function

BS.function.call <- function(sigma, options.df){

  d1 <- (log(S/X) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
  d2 <- d1 - sigma*sqrt(T)
  st <- S * pnorm(d1) - X*exp(-r*T)*pnorm(d2)
  distance <- abs(mktprice - st)
  return(distance) # We want to set the distance between market price 
  and calculated price = 0 using nlm by changing sigma
  }

BS.function.put <- function(sigma, options.df){

  d1 <- (log(S/X) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
  d2 <- d1 - sigma*sqrt(T)
  st <- -S * pnorm(-d1) + X*exp(-r*T)*pnorm(-d2)
  distance <- abs(mktprice - st)
  return(distance)
}

# 2. Create an initial guess for sigma

sigma.guess <- 0.2

# 3. Run the optimization function

for (i in 1:nrow(options.df)){
  if(type == 0){
    result[i] <- nlm(BS.function.call, sigma.guess, options.df)
  }
  else{
    result[i] <- nlm(BS.function.put, sigma.guess, options.df)
  }
}

1 个答案:

答案 0 :(得分:0)

我知道这篇文章很旧,但尚未解决,因此我会提供一些意见。您要查找的软件包是 RND,可以使用以下命令通过 R 控制台安装:

install.packages("RND")

另外,请确保在您的加载库部分加载包,如下所示:

library(RND)