我最近開始使用R進行財務數據計算,所以請耐心等待。我會盡量做到儘可能具體。將指數從100開始的列添加到股票價格/收益矩陣
我想要做的事:與quantmod包使用R,我加載財務數據到矩陣,然後與日收益增加一列,如下所示:
> getSymbols("^GDAXI",from="1900-01-01")
> "GDAXI"
> GDAXI$Returns<-dailyReturn(Cl(GDAXI))
> head(GDAXI)
GDAXI.Open GDAXI.High GDAXI.Low GDAXI.Close GDAXI.Volume GDAXI.Adjusted Returns
1990-11-26 1466.3 1466.3 1443.2 1443.2 0 1443.2 0.000000000
1990-11-27 1438.3 1438.3 1415.3 1415.3 0 1415.3 -0.019332040
1990-11-28 1410.0 1431.9 1402.8 1420.6 0 1420.6 0.003744789
1990-11-29 1420.4 1424.6 1415.8 1418.9 0 1418.9 -0.001196677
1990-11-30 1421.5 1443.9 1421.5 1441.2 0 1441.2 0.015716400
1990-12-03 1470.1 1476.6 1458.7 1462.6 0 1462.6 0.014848737
然而,接下來我想添加另一列,索引從100開始,以便與其他時間系列進行後續比較。我一直無法這樣做。
首先,我想
GDAXI$Index[1]=100
for(i in 2:nrow(GDAXI)){ GDAXI$Index[i]<-GDAXI$Index[i-1]*(1+GDAXI$Returns[i]) }
但我收到此錯誤信息,這一點我不明白:
Error in NextMethod(.Generic) : replacement has length zero
然後,我試過
> GDAXI$Index<-ifelse(index(GDAXI$Returns)==index(first(GDAXI)),100,lag(GDAXI$Index,1)*(1+GDAXI$Returns))
,並得到另一錯誤消息:
Error in hasTsp(x) : attempt to set an attribute on NULL
所有我想要的是一個具有以下值的列(手動添加插圖):
1990-11-26 100.00
1990-11-27 98.066796
1990-11-28 98.4340255
1990-11-29 98.3162417
1990-11-30 99.8614191
1990-12-03 101.344235
請幫幫忙!之前在VBA編碼我可能會接近這個錯誤的方式。但是搜索web和stackoverflow並沒有讓我找到解決方案。非常感謝你!
謝謝你的幫助,文森特。你的代碼完美地工作。我不熟悉'coredata'和'is.na'的功能。 R代碼看起來很神祕。 :) Thx再次! – DMueller 2012-03-11 17:07:45