将每日xts值更改为R中的每月选项到期OHLCV xts

时间:2016-07-07 08:51:01

标签: r xts quantmod

我想将xts对象的每日值更改为每月到期的OHLCV数据。我想我可以使用quantmod::options.expiry这样做......

library("quantmod")

# get SPX daily values
SPX <- getSymbols("^GSPC",from="2016-01-01",auto.assign=FALSE)

# option expiration rows/dates using options.expiry()
spx_expiry <- SPX[options.expiry(SPX),]

# spx_expiry will only return the closing values for option expiration **day**
# it is missing the OHLCV data in between expiration months. 
# The Close/Adjusted columns are correct but the Open, High, Low, Volumes
# columns are incorrect. 

# Here is what I have tried:
period.apply(SPX,INDEX=options.expiry(SPX),FUN=function(x) to.monthly(x,indexAt='firstof'))

1 个答案:

答案 0 :(得分:2)

你可以自己创建OHLCV吧,仔细考虑聚合月度数据的时间戳(你想要时间戳值的开始或结束等),如下所示:

m2 <- period.apply(SPX,INDEX=options.expiry(SPX),FUN=
                    function(x) {
                      xts(x = matrix(c(coredata(Op(x))[1], max(coredata(Hi(x))), min(coredata(Lo(x))), coredata(Cl(x))[NROW(x)],
sum(coredata(Vo(x)))), nrow =1), order.by= index(x)[1])
                      })

# period.apply operates the `x` data rows between FUN(x[(INDEX[y] + 1):INDEX[y + 1]], ...)
# And you want bar timestamp to be at the start of the interval:

ep_times <- index(SPX[options.expiry(SPX) + 1])
out <- xts(order.by = ep_times[-length(ep_times)], x = m2, dimnames = list(NULL, c("Open", "High", "Low", "Close", "Volume")))

head(out)
              Open    High     Low   Close       Volume
2016-01-19 1888.66 1947.20 1810.10 1917.78 112760980000
2016-02-22 1924.44 2052.36 1891.00 2049.58  90177630000
2016-03-21 2047.88 2087.84 2022.49 2080.73  69548230000
2016-04-18 2078.83 2111.05 2025.91 2052.32  96873130000
2016-05-23 2052.23 2120.55 2047.26 2071.22  68773770000