r - Create xts index with both date & time -
i want run 1 minute data trading app through r program i've written. far of xts objects have been daily bars yahoo, etc. how create time part of xts index? note date & time in first 2 columns. possible there missing dates, it's pretty guaranteed there missing minutes. there should not duplicates. (i'll check myself)
thanks
library(timedate) testdata = structure(list(x = 1:6, date = structure(c(1l, 1l, 1l, 1l, 1l, 1l), .label = "07/01/1998", class = "factor"), time = structure(1:6, .label = c("06:31", "06:34", "06:35", "06:36", "06:38", "06:39"), class = "factor"), open = c(114.06, 114.11, 114.06, 114.09, 114.09, 114.06), high = c(114.06, 114.13, 114.13, 114.09, 114.09, 114.13), low = c(114, 114.06, 114.06, 114.03, 114.06, 114.06), close = c(114, 114.06, 114.13, 114.03, 114.06, 114.13), volume = c(257600l, 24400l, 2500l, 900l, 3000l, 16700l)), .names = c("x", "date", "time", "open", "high", "low", "close", "volume"), class = "data.frame", row.names = c(na, -6l)) mydates = as.date(testdata$date,format = "%m/%d/%y") mytimes = as.vector(testdata$time) myindexes = timedate(paste(mydates, mytimes), format = "%y-%m-%d %h:%m", zone="utc") newdata = xts(testdata[,3:7], order.by = myindexes) is.xts(newdata)
here go.
first, data. note superfluous first columns first throws off indices used in code. corrected though.
r> testdata x date time open high low close volume 1 1 07/01/1998 06:31 114.06 114.06 114.00 114.00 257600 2 2 07/01/1998 06:34 114.11 114.13 114.06 114.06 24400 3 3 07/01/1998 06:35 114.06 114.13 114.06 114.13 2500 4 4 07/01/1998 06:36 114.09 114.09 114.03 114.03 900 5 5 07/01/1998 06:38 114.09 114.09 114.06 114.06 3000 6 6 07/01/1998 06:39 114.06 114.13 114.06 114.13 16700 r>
much worse forced date , time factor type. not idea:
r> sapply(testdata, class) x date time open high low close volume "integer" "factor" "factor" "numeric" "numeric" "numeric" "numeric" "integer" r>
so when work with, first convert character, paste, parse , lastly convert as.posixct
type xts
rather happy with.
r> x <- xts(testdata[,4:8], + order.by=as.posixct(strptime(paste(as.character(testdata[,2]), + as.character(testdata[,3])), + "%m/%d/%y %h:%m"))) r>
et voila:
r> myxts open high low close volume 1998-07-01 06:31:00 114.06 114.06 114.00 114.00 257600 1998-07-01 06:34:00 114.11 114.13 114.06 114.06 24400 1998-07-01 06:35:00 114.06 114.13 114.06 114.13 2500 1998-07-01 06:36:00 114.09 114.09 114.03 114.03 900 1998-07-01 06:38:00 114.09 114.09 114.06 114.06 3000 1998-07-01 06:39:00 114.06 114.13 114.06 114.13 16700 r>
but should spend time extensive documentation xts
, zoo
.
Comments
Post a Comment