2016-07-07 12 views
0

xtsオブジェクトの毎日の値を毎月の有効期限OHLCVデータに変更したいとします。私は、集約された月次データのタイムスタンプは、(あなたがタイムスタンプ値のために起動したり、バーの端たいん慎重に考慮して、あなたがOHLCVを自分でバー作成することができます...私はそうするquantmod::options.expiryを使用することができます毎月のxts値を毎月のオプション有効期限に変更します。OHLCV xts in R

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

を考え出しなど):

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

関連する問題