4

我有 CSV 文件,其日期格式如下:25-Aug-2004

我想将其读取为“xts”对象,以便使用 quantmod 包中的函数“periodReturn”。

我可以将以下文件用于该功能吗?

Symbol Series        Date Prev.Close Open.Price High.Price Low.Price

1       XXX     EQ 25-Aug-2004     850.00    1198.70    1198.70    979.00

2       XXX     EQ 26-Aug-2004     987.95     992.00     997.00    975.30

用同样的方法指导我。

4

2 回答 2

3

尝试这个。我们去掉讨厌的列并指定时间索引的格式,然后转换为 xts 并应用 dailyReturn 函数:

Lines <- "Symbol Series Date Prev.Close Open.Price High.Price Low.Price
1 XXX EQ 25-Aug-2004 850.00 1198.70 1198.70 979.00
2 XXX EQ 26-Aug-2004 987.95 992.00 997.00 975.30"

library(quantmod) # this also pulls in xts & zoo

z <- read.zoo(textConnection(Lines), format = "%d-%b-%Y",
    colClasses = rep(c(NA, "NULL", NA), c(1, 2, 5)))
x <- as.xts(z)
dailyReturn(x)

当然,textConnection(Lines)这只是为了保持示例自包含,实际上会被替换为"myfile.dat".

于 2011-01-21T11:04:02.093 回答
3

不幸的是,我不能代表这ts部分内容,但这就是您如何将日期转换为可以被其他函数读取为日期(或时间)的正确格式的方法。您可以像往常一样将数据导入 data.frame (如果您错过了,请参见此处)。然后,您可以使用函数将Date列转换为POSIXlt( POSIXt) 类。strptime

nibha <- "25-Aug-2004" # this should be your imported column
lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C") #temporarily change locale to C if you happen go get NAs
strptime(nibha, format = "%d-%b-%Y")
Sys.setlocale("LC_TIME", lct) #revert back to your locale
于 2011-01-21T08:10:04.857 回答