루프 내에서 동물원 클래스를 병합하려고합니다. 각 반복마다 동물원 시리즈를 새로운 '열'로 누적합니다. 루프를 실행하기 전에 빈 zoo()
을 초기화합니다. 내 코드가 완료된 후에 str()
을 호출하면 '관찰하지 않고 동물원 시리즈'를 얻습니다. 그러나 빈 동물원을 초기화하고 데이터 자체와 다른 인스턴스를 병합하여 실험하면 잘 작동합니다. 아래 문제의 동물원은 두 번째 루프에서 'monthlyReturns
'입니다. Btw는 내가 해당 가족을 사용하여 더 잘 봉사 할 것임을 알고 있습니다. 그것은 다음 일 것입니다. 내가 도대체 뭘 잘못하고있는 겁니까? 당신이 이런 종류의 오류를 방지하고 R의 효율적인 코드를 구현하려면루프에서 시계열을 반복적으로 병합 할 수 있습니까?
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')
}
도움이되기를 바랍니다. 예를 들어 행동을 재현하고 코드를 제공하여'tseries :: get.hist.quote'를 통해 데이터를 얻고 예를 들어'symbs' 객체를 제공하면 코드가 완벽 해집니다. – dickoa
코드에서 진행되는 모든 작업을 이해할 수 있는지 확신 할 수 없지만 첫 번째 루프의 두 위치에서 importData [[sIdx]]를 원한다고 생각합니다. (즉,'['대신'[[''두 번째 루프에서 거대한 병합이'do.call (merge, monthlyPctChgs)'로 대체 될 수 있음을 알고 싶을 것입니다. 그러나, 나는 그것이 당신이 생각하는 것을하고 있는지 확신하지 못한다. 그것은 당신의 코드가'NROW (symbs) == 12 '라는 가정을하고있는 것처럼 보입니다. – GSee
방금 symbs을 제공, 나는 더 잘 알고 ... thx. – StatsViaCsh