I have a data set in a data frame with the following information:
> 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
I'm trying to get the implied volatility using the AmericanOptionImpliedVolatility
function in the RQuantLib
package. The problem is that it seems to only take single sets of values:
> 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
I think this is a spot for the apply
function but I'm not sure if I'm using it properly:
> 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
Any suggestions?
You can use Vectorize
or mapply
.
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
)
If you want to use apply
, its third argument should be a function. In addition, it would convert each row to a vector, which is problematic when some of the columns contain strings.
You could also use sapply
on the row numbers, but it is just a loop in disguise, less readable than mapply
.
sapply(
seq_len(nrows(rs1)),
function(i) AmericanOptionImpliedVolatility(
type="put",
value=rs1$ask[i],
... (add the other arguments)
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.