【发布时间】:2013-12-05 19:54:36
【问题描述】:
我只是从 Bloomberg 下载时间序列并尝试制作一个 xts 对象:
library(Rbbg)
conn <- blpConnect()
tickers = c("SPX Index","GX1 Index","VG1 Index","NK1 Index",
"SM1 Index","RM1 Index","LT01TRUU Index")
df <- bdh(conn,tickers,c("PX_OPEN","PX_HIGH", "PX_LOW", "PX_LAST", "Volume"),
"19980101", "20131020",option_names = "CDR", option_values = "US")
blpDisconnect(conn)
make.xts <- function(x, order.by) {
tzone = Sys.getenv('TZ')
orderBy = class(order.by)
index = as.numeric(as.POSIXct(order.by, tz = tzone))
if( is.null(dim(x)) ) {
if( len(orderBy) == 1 )
x = t(as.matrix(x))
else
dim(x) = c(len(x), 1)
}
x = as.matrix(x)
x = structure(.Data = x,
index = structure(index, tzone = tzone, tclass = orderBy),
class = c('xts', 'zoo'), .indexCLASS = orderBy, tclass=orderBy,
.indexTZ = tzone, tzone=tzone)
return( x )
}
data <- new.env()
for(s in unique(df$ticker)) {
temp = df[df$ticker == s,]
date = as.Date(temp$date)
temp = temp[,spl('PX_OPEN,PX_HIGH,PX_LOW,PX_LAST,Volume')]
colnames(temp) = spl('Open,High,Low,Close,Volume')
temp = make.xts(temp[], date)
if (length(grep('Index',s)) == 1) {
data[[ trim(gsub('Index', '', s)) ]] = temp[!is.na(temp$Close),]
} else {
data[[ trim(gsub('US Equity', '', s)) ]] = temp[!is.na(temp$Close),]
}
}
这是 df 对象(抱歉,我不知道 dput) https://dl.dropboxusercontent.com/u/102669/df.rdata
这是 xts 对象: https://dl.dropboxusercontent.com/u/102669/temp.rdata
所有数据都是 CHR,但我想要数字数据。
我想问题出在 NA 上。 我无法删除所有 NA 行,因为某些时间序列只有收盘价。
所以一个规则可以是:当只存在收盘价时,将所有其他列与收盘价相等,否则什么都没有。如果任何列中存在某些 Na 值,则继续最后一个非 NA 值
最终结果应该是一个带有数字数据的 xts 对象。
有什么帮助吗?
【问题讨论】:
-
你是如何创建这个 xts 对象的?它有
rownames,xts 对象不应该有rownames。解决您的问题的最佳方法是,“首先不要像这样构造 xts 对象。” -
请告诉我们您已经编写了哪些代码。这就是 Stack Overflow——我们的想法不是我们为您完成工作,而是当您遇到困难时我们会帮助您。另外,不要使用
.rdata文件,请使用dput将一小部分数据粘贴到您的问题中。 -
如果您不知道如何使用
dput,请在 RGui 提示符处键入?dput寻求帮助。另请阅读this question 了解详细信息以及制作可重现示例的许多其他方法。 -
make.xts函数是什么? -
好的,理解输入。是否必须使用 dput?我对 .rdata 更有信心。下次我可以拉上拉链,好吗?抱歉,如您所见,我是 R 的新手。