我可以在循环中迭代合并时间序列吗?

时间:2013-07-28 19:44:00

标签: r time-series zoo

我正在尝试在循环中合并动物园类,在每次迭代时将动物园系列累积为新的“列”。我在运行循环之前初始化一个空zoo()。在我的代码完成后,当我在其上调用str()时,我得到了“没有观察到的动物园系列”。然而,当我尝试初始化一个空的动物园,然后将它与自身和另一个实例与数据合并时,它可以正常工作。下面讨论的动物园在第二个循环中是'monthlyReturns'。顺便说一句我知道使用申请家庭我会得到更好的服务。那将是下一个。我做错了什么?

library(tseries)
library(zoo)
symbs = c('XLF', 'XLE', 'XLU', 'SPY')
importData = vector('list', length(symbs))
cumInvestmentReturns = zoo()
monthlyReturns = zoo()

#Get monthly pricing data.
for (sIdx in 1:length(symbs)){
    #Import the data for each symbol into the list.
    importData[sIdx] = get.hist.quote(instrument= symbs[sIdx], start="2000-01-01", end="2013-07-15", 
          quote="AdjClose", provider="yahoo", origin="1970-01-01", compression="m", retclass="zoo")
    names(importData[sIdx]) = symbs[sIdx]
}

#Loop over length of lookback months (1-12) to check for performance of best etf in past period.
for (numbOfMonths in 1:12){
    #Calculate performances on each symbol, using the lookback length of variable numbOfMonths.
    monthlyPctChgs = lapply(importData, function(x) diff(x, lag =numbOfMonths) / lag(x, k=-numbOfMonths))
    names(monthlyPctChgs) = symbs

    #combine all ticker time series into one time series.
    tsPctChgs = merge(monthlyPctChgs[[1]], monthlyPctChgs[[2]], monthlyPctChgs[[3]], monthlyPctChgs[[4]], 
          monthlyPctChgs[[5]], monthlyPctChgs[[6]], monthlyPctChgs[[7]], monthlyPctChgs[[8]], 
          monthlyPctChgs[[9]], monthlyPctChgs[[10]], monthlyPctChgs[[11]], monthlyPctChgs[[12]])
    names(tsPctChgs) = symbs

    curBestLagPerfs <- rollapplyr(tsPctChgs, 2, function(x) x[2,which.max(x[1,])], by.column=FALSE)
    monthlyReturns = merge(monthlyReturns, curBestLagPerfs)
    #finalSet = finalSet[2:length(finalSet$SPY),] #Remove first value, since there is an na.

    lookbackReturns = cumprod(1+curBestLag) * 10000
    cumInvestmentReturns = merge(cumInvestmentReturns, lookbackReturns)
    #names(investmentsPaired) = c('SPY', 'ETFRotation')
}

1 个答案:

答案 0 :(得分:1)

如果你想避免这种错误并在R中实现高效的代码,你必须学习如何使用像lapply,apply和其他* apply这样的函数。有一篇很棒的帖子here

以下是我对代码的简化,未经过全面测试,但它可以帮助您深入了解如何改进代码并纠正错误。

require(tseries)
require(zoo)
symbs <- c('XLF', 'XLE', 'XLU', 'SPY')

importData <- lapply(symbs, function(symb)
                     get.hist.quote(instrument= symb,
                                    start = "2000-01-01",
                                    end = "2013-07-15", 
                                    quote="AdjClose", provider = "yahoo",
                                    origin="1970-01-01", compression = "m",
                                    retclass="zoo"))

names(importData) <- symbs


monthlyPctChgs <- lapply(1:12, function(y)
                         lapply(importData,
                                function(x) diff(x, lag = y) / lag(x, lag = - y)))


tsPctChgs <- lapply(monthlyPctChgs, do.call, what = merge)


curBestLagPerfs <- lapply(tsPctChgs, function(y)
                          rollapplyr(y, 2,
                                     function(x) x[2,which.max(x[1,])],
                                     by.column=FALSE))

curBestLagPerfs <- do.call(merge, curBestLagPerfs)
names(curBestLagPerfs) <- month.abb
str(curBestLagPerfs)
## ‘zoo’ series from 2000-03-01 to 2013-06-03
##   Data: num [1:160, 1:12] 0.09156 0.00933 -0.00229 -0.06095 -0.01496 ...
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:12] "Jan" "Feb" "Mar" "Apr" ...
##   Index:  Date[1:160], format: "2000-03-01" "2000-04-03" "2000-05-01" ...

希望它会有所帮助