2012-04-09 97 views
4

/plyr我在与以下信息的数据帧的数据集:[R使用申请与RQuantlib功能

> 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 

我试图使用AmericanOptionImpliedVolatility功能在RQuantLib包来获得隐含波动率。问题是,它似乎只需要值的单集:

> 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功能的地方,但我不知道如果我使用得当:

> 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 

有什么建议吗?

+1

你想'rs1 $ daysleft/252',不超过365. – 2012-04-09 14:48:16

+0

谢谢,不知道这一点。 – screechOwl 2012-04-09 15:37:06

回答

5

您可以使用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,它的第三个参数应该是一个函数。 此外,它会将每一行转换为向量, 当某些列包含字符串时会出现问题。

你也可以使用sapply上的行数, 但它只是一种变相的回路,比之mapply的可读性。

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

+1! 'mapply'和'Vectorize'之间的性能有差异,还是纯粹在语法上的差异。你喜欢哪个? – 2012-04-09 11:22:42

+0

@PaulHiemstra:由于'Vectorize'只是'mapply'的一个包装,所以性能应该是一样的。当我只想调用函数时,我发现'mapply'更具可读性,但是当我需要一个向量化函数(通常作为另一个函数的参数,通常是'outer')时,我使用'vectorize'。 – 2012-04-09 12:19:49