Creating daily OHLC with custom starting time

感情迁移 提交于 2019-12-04 17:37:24

Most (all?) xts functions define time intervals using the endpoints() function, which creates the intervals based on offsets from the epoch. This is usually desirable, because it finds/creates breaks at round units of time (at the change of a minute, hour, etc).

If I understand correctly, you want intervals defined by the first observation in your data. I can see how you would expect endpoints at 17:00:00, since that's the hour and minute of your first observation. I'm not sure you would have the same expectation if your first observation was at an irregular time like 17:01:32.741.

So, that's the backstory, and therefore I can't think of an easy/straight-forward way to get the result you want. But here's an attempt at a kludge, using period.apply() with custom endpoints and function.

# custom aggregation function to convert a chunk of data to one OHLC observation
toOHLC <- function(x) {
  op <- as.vector(first(x))
  hl <- range(x, na.rm = TRUE)
  cl <- as.vector(last(x))
  xts(cbind(Open = op, High = hl[2], Low = hl[1], Close = cl), end(x))
}

Now a hack to get endpoints for days defined by 17:00.

# Convert to xts
y <- as.xts(x)
# Convert index to UTC
indexTZ(y) <- "UTC"
# Set first observation to epoch (zero)
.index(y) <- .index(y) - .index(y)[1]
# Get endpoints for y by day
ep <- endpoints(y, "days")

Now you can use ep in your call to period.apply() to get OHLC by days, where 17:00:00 is the breakpoint.

period.apply(x, ep, toOHLC)
#                          Open      High        Low      Close
# 2010-05-04 16:45:00 0.6415173 0.8440296 0.01497329 0.84402960
# 2010-05-05 16:45:00 0.8411363 0.8440296 0.01497329 0.08874158
# 2010-05-06 16:45:00 0.7843095 0.8440296 0.01497329 0.40912559
# 2010-05-06 17:00:00 0.5669512 0.5669512 0.56695121 0.56695121
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!