I am starting to work with options data from optionmetrics. I use data frames, but it seems like xts or zoo objects are the way to go for features and speed. I can't figure out the best work-around to get 1 row per date. Should I be doing a list of xts objects with one object per optionid?
Here's my current approach: I am trying to price higher moments by looking at the returns to hedged portfolios of S&P 500 index options, so I really need to match next period's option price with this period's date. I use a data frame with the dates as a Date
class and peel off the date, optionid, and option price (boa) columns. I reshape to wide with the optionid as the column names and shift the date back (here I do daily, but it can be any holding period). Then I melt back to long dataframe and merge back on the original data frame. I will give code below.
If I do this for both calls and puts, then I can merge on date, strike, and expiry and form hedged portfolios. This approach works well enough, but it doesn't seem very extensible and probably ignoring a lot of good tools in R. Right now I am just looking at index options, but maybe later I'll be looking at the cross-section, so speed will come in handy.
How do you go about working with options data in R? Thanks!
Here's the code:
> head(call.l)
date exdate dte optionid strike close Xms boa delta
1 1996-01-04 1996-03-16 72 10003226 600 617.7 -17.7 25.250 0.768930
2 1996-01-04 1996-02-17 44 10016457 570 617.7 -47.7 48.750 0.000000
3 1996-01-04 1996-06-22 170 10019107 595 617.7 -22.7 39.000 0.732626
4 1996-01-04 1997-06-21 534 10050656 700 617.7 82.3 15.750 0.294790
5 1996-01-04 1996-02-17 44 10060564 615 617.7 -2.7 11.000 0.599153
6 1996-01-04 1996-02-17 44 10091463 655 617.7 37.3 0.375 0.046054
temp.l <- call.l[, c("date", "optionid", "boa")]
temp.w <- dcast(temp.l, formula = "date ~ optionid", value_var = "boa")
temp.w <- temp.w[ order(temp.w[, "date"]), ]
temp.w.shift <- tail(temp.w, -1)
temp.w.shift[, "date"] <- head(temp.w[, "date"], -1)
temp.l.shift <- melt(temp.w.shift, id.vars = "date", variable.name = "optionid", value.name = "boa.fut", na.rm = T)
call.l.new <- merge(call.l, temp.l.shift)
> head(subset(call.l.new, strike == 615))
date optionid exdate dte strike close Xms boa delta boa.fut
5 1996-01-04 10060564 1996-02-17 44 615 617.70 -2.70 11.000 0.599153 10.6250
43 1996-01-04 10372012 1996-03-16 72 615 617.70 -2.70 15.000 0.593709 14.6250
80 1996-01-04 10823593 1996-01-20 16 615 617.70 -2.70 7.750 0.597414 6.0000
144 1996-01-05 10060564 1996-02-17 43 615 616.71 -1.71 10.625 0.577407 12.2500
182 1996-01-05 10372012 1996-03-16 71 615 616.71 -1.71 14.625 0.578089 16.2500
219 1996-01-05 10823593 1996-01-20 15 615 616.71 -1.71 6.000 0.584558 7.0625
dput
but it was huge; please let me know if it would help. Thanks. $\endgroup$indexing
looks really promising. $\endgroup$