我想通过我编写的R程序从交易应用程序运行一些1分钟的数据。到目前为止,我所有的xts对象都是来自Yahoo等的日常酒吧。如何创建xts索引的时间部分?请注意日期&时间在前2列。可能会有缺少日期,几乎可以保证会有错过的会议记录。不应该有任何重复。 (我会自己检查一下)
由于
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)
答案 0 :(得分:1)
你走了。
首先,您的数据。请注意,多余的第一列首先抛弃代码中使用的索引。虽然很容易纠正。
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>
更糟糕的是,您将日期和时间强制为因子类型。 不一个好主意:
R> sapply(TestData, class)
X Date Time Open High Low Close Volume
"integer" "factor" "factor" "numeric" "numeric" "numeric" "numeric" "integer"
R>
因此,当我们使用时,我们首先转换为字符,然后粘贴,然后解析并最后转换为as.POSIXct
,这是xts
非常满意的类型。
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瞧:
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>
但您真的应该花一些时间阅读xts
和zoo
的扩展文档。