I generate a list of truncated random t variables, then download closing stock price (quantmod) then generate a list of possible random stock prices, when I try and plug this into a loop in lapply or for each, the random variates are not recognized. Below is my code the lapply function gives an error:
library(truncdist)
library(quantmod)
library(fOptions)
randomT <- rt(4,6)
randomOut <- dtrunc(randomT, spec = "t", df = 6,a= -2, b= 2)
startDate <- as.Date("2018-01-01")
# Specify period of time we are interested in
randomOut <- randomT
endDate <- as.Date("2019-05-09")
getSymbols('SPY',src='yahoo',from = startDate,to = endDate)
SpRtn <- dailyReturn(SPY,type='arithmetic')
rtn <- sum(SPYreturns)
dev <- sd(SPYreturns)
vol <- dev*sqrt(250)
dt <- 1/250
current <- tail(SPY$SPY.Close,1)
dayRtn <- rtn*dt
dayVol <- vol*sqrt(dt)
guess <- function (randomOut) current * exp(dayRtn + Vol * randomOut)
expected <- lapply (randomOut, FUN = guess)
gsb <- function() {
GBSOption (TypeFlag = "p", S = expected,
X = 280,
ime = 18/250,
r = 0.022,
b = 0,
sigma =0.16
)
}
lapply(expected, FUN = gsb)
答案 0 :(得分:0)
您提供的代码中存在许多问题。如此雄心勃勃,真是太好了,但我建议您放慢速度,集中精力清理问题,并了解各个部分的工作方式以及它们之间的相互作用。
我在有特定问题的地方添加了评论。请阅读它们,并尝试了解每个问题。还请理解,由于我对这个主题一无所知,因此我不得不对您的意图做出一些猜测。尽管如此,我仍然可以通过修复一些变量名并确保传递给函数的对象具有正确的类来使事情正常进行。具体来说,GBSOption
需要S
的数字变量,但是expected
具有类xts
。您需要使用S = expected[[1]]
之类的子集来使其工作。
该代码应该运行,但是我不能保证它正在执行应做的事情:
library(truncdist)
library(quantmod)
library(fOptions)
# You assign randomOut using dtrunc, then immediately overwrite it with
# randomT. Is that a mistake?
randomT <- rt(4,6)
randomOut <- dtrunc(randomT, spec = "t", df = 6, a = -2, b = 2)
#randomOut <- randomT
# Specify period of time we are interested in
startDate <- as.Date("2018-01-01")
endDate <- as.Date("2019-05-09")
getSymbols('SPY', src = 'yahoo', from = startDate, to = endDate)
SpRtn <- dailyReturn(SPY, type = 'arithmetic')
# You use SPYreturns in your orginal code, but there is no assignment to
# SPYreturns. Do you mean SpRtn?
rtn <- sum(SpRtn)
dev <- sd(SpRtn)
vol <- dev * sqrt(250)
dt <- 1/250
current <- tail(SPY$SPY.Close, 1)
dayRtn <- rtn*dt
dayVol <- vol*sqrt(dt)
# You use `Vol` in the `guess` function, but the variable is called `vol`.
guess <- function (randomOut) current * exp(dayRtn + vol * randomOut)
expected <- lapply (randomOut, FUN = guess)
gsb <- function(expected) {
GBSOption (TypeFlag = "p",
# This was probably your biggest issue. `expected` points to an
# xts object, but you need numeric, which means you need to
# extract the first SPY.Close value.
S = expected[[1]],
X = 280,
# You had `ime` here, but you need `Time`.
Time = 18/250,
r = 0.022,
b = 0,
sigma =0.16
)
}
lapply(expected, FUN = gsb)