繁体   English   中英

R 使用 apply/plyr 和 RQuantlib function

[英]R using apply/plyr with RQuantlib function

我在数据框中有一个数据集,其中包含以下信息:

> head(rs1)
       dater adjStkPrice                optSym     expire strike   bid   ask unadjStkPrice daysLeft   pnl
1 2011-01-03      127.05 SPY   131221P00115000 2013-12-21    115 14.89 15.40        127.05     1083 319.5
2 2011-01-04      126.98 SPY   131221P00115000 2013-12-21    115 15.00 15.39        126.98     1082 328.4
3 2011-01-05      127.64 SPY   131221P00115000 2013-12-21    115 14.39 14.86        127.64     1081 287.2
4 2011-01-06      127.39 SPY   131221P00115000 2013-12-21    115 14.38 14.80        127.39     1080 278.7
5 2011-01-07      127.14 SPY   131221P00115000 2013-12-21    115 14.67 15.10        127.14     1079 300.2
6 2011-01-10      126.98 SPY   131221P00115000 2013-12-21    115 14.75 15.19        126.98     1076 303.4

我正在尝试使用RQuantLib package 中的AmericanOptionImpliedVolatility function 来获取隐含波动率。问题是它似乎只采用单组值:

> rs1$impVol <- AmericanOptionImpliedVolatility("put", rs1$ask,
+ rs1$adjStkPrice, rs1$strike, .02, .05, rs1$daysLeft/ 365, .4)$impliedVol
Error in AmericanOptionImpliedVolatility.default("put", rs1$ask, rs1$adjStkPrice,  : 
  expecting a single value

我认为这是apply function 的地方,但我不确定我是否正确使用它:

> rs1$impVol <- apply(rs1, 1, AmericanOptionImpliedVolatility("put", rs1$ask,
+ rs1$adjStkPrice, rs1$strike, .02, .05, rs1$daysLeft/ 365, .4)$impliedVol)
Error in AmericanOptionImpliedVolatility.default("put", rs1$ask, rs1$adjStkPrice,  : 
  expecting a single value

有什么建议么?

您可以使用Vectorizemapply

Vectorize(AmericanOptionImpliedVolatility)(
  type="put", value=15:16, underlying=130:131, 
  strike=115, dividendYield=.02, riskFreeRate=.05, maturity=1, 
  volatility=.1
)

mapply(
  AmericanOptionImpliedVolatility,
  type="put", value=15:16, underlying=130:131, 
  strike=115, dividendYield=.02, riskFreeRate=.05, maturity=1, 
  volatility=.1
)  

如果你想使用apply ,它的第三个参数应该是 function。此外,它会将每一行转换为一个向量,当某些列包含字符串时,这是有问题的。

您也可以在行号上使用sapply ,但它只是一个伪装的循环,可读性不如mapply

sapply(
  seq_len(nrows(rs1)),
  function(i) AmericanOptionImpliedVolatility( 
    type="put", 
    value=rs1$ask[i],
   ... (add the other arguments)
  )
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM