我有一个像这样排列的数据集:
NO0003659914 NO0003106700 NO0010014632 NO0003095309 NO0003666604 NO0003101404 NO0003679102 X
2015-12-21 "25" "1,85" "12" "0,3" "132,5" "10,255" "48" "3544,4"
2015-12-22 "25" "1,89" "11,8" "0,29" "132,5" "10,255" "50" "3564,46"
2015-12-23 "25" "1,8" "11,95" "0,4" "132,5" "10,255" "56,25" "3612,8"
2015-12-28 "25" "1,69" "12,7" "0,34" "132,5" "10,255" "53" "3608,38"
2015-12-29 "25" "1,58" "13,3" "0,36" "132,5" "10,255" "56" "3606,44"
2015-12-30 "25" "1,61" "12,9" "0,34" "132,5" "10,255" "56" "3622,9"
它是一个xts对象:
> class(tdata)
[1] "xts" "zoo"
我想将这些每日观察结果转化为月度回报,并尝试使用for循环。
symbols <- colnames(tdata)
for(symbol in symbols) {
tdata <- get(symbol)
tdata <- to.monthly(tdata,indexAt='lastof',drop.time=TRUE)
indexFormat(tdata) <- '%d.%m.%Y'
colnames(tdata) <- gsub("tdata",symbol,colnames(tdata))
assign(symbol,tdata)
}
我也试过了quantmod::monthlyReturn(x = tdata, subset = tdata$row.names)
,但后来我得到了:
na.omit.xts(x)中的错误:不支持的类型
这是错误,因为我的时间序列中有NA值吗?有关如何轻松将这些转换为月收益的任何帮助?现在已经挣扎了一段时间,任何帮助都会非常感激。
答案 0 :(得分:3)
您的数据似乎是字符,而不是数字,因为您导入的任何原始数据源都使用","
作为小数点分隔符而不是默认值"."
。数据采用数字格式后,您可以使用xts::endpoints
和TTR::ROC
的组合来计算特定周期的回报。
Lines <- 'Index NO0003659914 NO0003106700 NO0010014632 NO0003095309 NO0003666604 NO0003101404 NO0003679102 X
2015-12-21 "25" "1,85" "12" "0,3" "132,5" "10,255" "48" "3544,4"
2015-12-22 "25" "1,89" "11,8" "0,29" "132,5" "10,255" "50" "3564,46"
2015-12-23 "25" "1,8" "11,95" "0,4" "132,5" "10,255" "56,25" "3612,8"
2015-12-28 "25" "1,69" "12,7" "0,34" "132,5" "10,255" "53" "3608,38"
2015-12-29 "25" "1,58" "13,3" "0,36" "132,5" "10,255" "56" "3606,44"
2015-12-30 "25" "1,61" "12,9" "0,34" "132,5" "10,255" "56" "3622,9"'
tdata <- as.xts(read.zoo(text=Lines, header=TRUE, dec=","))
TTR::ROC(tdata[endpoints(tdata,'weeks')])