XTS: split FX intraday bar data by trading days

吃可爱长大的小学妹 提交于 2019-12-04 12:48:23
Darren Cook

Here is how to get the daybreak right:

x2=x
index(x2)=index(x2)+(7*3600)
indexTZ(x2)='America/New_York'

I.e. just setting the timezone puts the daybreak at 17:00; we want it to be at 24:00, so add 7 hours on first.

With help from: time zones in POSIXct and xts, converting from GMT in R

Here is the full function:

rollapply_chunks.FX.xts=function(data,width,FUN,...,on="days",k=1){
data <- try.xts(data)

x2 <- data
index(x2) <- index(x2)+(7*3600)
indexTZ(x2) <- 'America/New_York'

ep <- endpoints(x2,on=on,k=k)    #The end point of each calendar day (when on="days").
    #Each entry points to the final bar of the day. ep[1]==0.

if(length(ep)<2){
    stop("Cannot divide data up")
}else if(length(ep)==2){  #Can only fit one chunk in.
    sp <- 1;ep <- ep[-1]
}else{
    sp <- ep[1:(length(ep)-width)]+1
    ep <- ep[(width+1):length(ep)]
}

xx <- lapply(1:length(ep), function(ix) FUN(.subset_xts(data,sp[ix]:ep[ix]),...) )
xx <- do.call(rbind,xx)   #Join them up as one big matrix/data.frame.

tt <- index(data)[ep]  #Implicit align="right". Use sp for align="left"
res <- xts(xx, tt)
return (res)
}

You can see we use the modified index to split up the original data. (If R uses copy-on-write under the covers, then the only extra memory requirement should be for a copy of the index, not of the data.)

(Legal bit: please consider it licensed under MIT, but explicit permission given to use in the GPL-2 XTS package if that is desired.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!