有一些属性会导致问题。我们可以用as.numeric 包裹起来
library(dplyr)
library(RQuantLib)
book %>%
rowwise %>%
mutate(impvol = as.numeric(EuropeanOptionImpliedVolatility(type,
value=last, underlying, strike,
dividendYield,riskFreeRate,maturity,volatility = 0.4)))
-输出
# A tibble: 6 x 8
# Rowwise:
# type strike last underlying dividendYield riskFreeRate maturity impvol
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 call 27800 240 26425 0 0.015 0.107 0.204
#2 call 27600 280 26425 0 0.015 0.107 0.202
#3 call 27400 320 26425 0 0.015 0.107 0.197
#4 put 24800 310 26425 0 0.015 0.107 0.275
#5 put 24600 270 26425 0 0.015 0.107 0.277
#6 put 24400 230 26425 0 0.015 0.107 0.278
如果我们想保留这些属性,也可以用list 包装
book %>%
rowwise %>%
mutate(impvol = list(EuropeanOptionImpliedVolatility(type,
value=last, underlying,strike,dividendYield,
riskFreeRate,maturity,volatility=0.4)))
-输出
# A tibble: 6 x 8
# Rowwise:
# type strike last underlying dividendYield riskFreeRate maturity impvol
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <list>
#1 call 27800 240 26425 0 0.015 0.107 <ErpnOpIV [1]>
#2 call 27600 280 26425 0 0.015 0.107 <ErpnOpIV [1]>
#3 call 27400 320 26425 0 0.015 0.107 <ErpnOpIV [1]>
#4 put 24800 310 26425 0 0.015 0.107 <ErpnOpIV [1]>
#5 put 24600 270 26425 0 0.015 0.107 <ErpnOpIV [1]>
#6 put 24400 230 26425 0 0.015 0.107 <ErpnOpIV [1]>
或者pmap的另一个选项
library(purrr)
book %>%
mutate(impvol = pmap_dbl(., ~ EuropeanOptionImpliedVolatility(..1, value = ..3,
..4, ..2, ..5, ..6, ..7, volatility = 0.4)))
# type strike last underlying dividendYield riskFreeRate maturity impvol
#1 call 27800 240 26425 0 0.015 0.1068493 0.2044270
#2 call 27600 280 26425 0 0.015 0.1068493 0.2019167
#3 call 27400 320 26425 0 0.015 0.1068493 0.1973822
#4 put 24800 310 26425 0 0.015 0.1068493 0.2745614
#5 put 24600 270 26425 0 0.015 0.1068493 0.2773029
#6 put 24400 230 26425 0 0.015 0.1068493 0.2780447
数据
book <- data.frame(
type=c("call","call","call","put","put","put"),
strike=c(27800,27600,27400,24800,24600,24400),
last=c(240,280,320,310,270,230),
underlying=rep(26425,6),
dividendYield=rep(0,6),
riskFreeRate=rep(0.015,6),
maturity=rep(39/365,6)
)