2016-07-07 90 views
0

我想將xts對象的每日價值更改爲每月到期OHLCV數據。我想我可以用quantmod::options.expiry這樣做......將每日xts值更改爲R月期權到期OHLCV xts

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')) 

回答

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 
+0

正是我在找什麼。非常感謝! – Rime