来自Quantmod的XTS对象

时间:2014-05-07 12:44:48

标签: r xts quantmod

您好我想知道如何使用具有许多代码的XTS对象应用适用于单个代码的相同代码。

这是适用于1个代码(关闭价格)的代码:

getSymbols("IYR",from="1995-01-01",to="2014-01-01")

adj<-IYR$IYR.Adjusted
rtnM<-ROC(adj)[2:length(adj)]
r05<-rtnM[rtnM<= -.05]
plot(sort(r05),type='o',main='US ETF Drops 1995-present returns <= -5%')
100*sort(r05)

在将这两行应用到我的完整股票列表

时,我似乎正在努力解决这两条问题
mb<- sub[sub<= -.05]
plot.xts(sort(mb),type='o',main='US ETF <= -5%')

如果我没有说清楚这是第一篇帖子,我道歉。

> head(sub)
           DIA.Close    EEM.Close    EFA.Close    EWZ.Close    FXI.Close    GLD.Close

    GSG.Close
2012-01-03  0.0145024539  0.030116502  0.026891372  0.039461948  0.031336368  0.025528326  0.035154052
2012-01-04  0.0027463668 -0.005642487 -0.005913678  0.003678319 -0.014839976  0.005053908  0.004672906
2012-01-05 -0.0001613424 -0.004382015 -0.014939029 -0.013610224  0.006747285  0.006804694 -0.015267472
2012-01-06 -0.0033942169 -0.012739026 -0.013740366 -0.010031539 -0.014677091 -0.003682778  0.004428052
2012-01-09  0.0010518226  0.010411338  0.003858265  0.020800615  0.021100797 -0.004462870  0.001177510
2012-01-10  0.0058055315  0.021517224  0.015086276  0.020376751  0.022299616  0.013581474  0.007620201

> mb<- sub[sub<= -.05]
Error in `[.xts`(sub, sub <= -0.05) : 'i' or 'j' out of range

1 个答案:

答案 0 :(得分:0)

假设您想为每个自动收报机一起绘制小于-5%的排序值,

如上所述@GSee,前两行

adj<-IYR$IYR.Adjusted
rtnM<-ROC(adj)[2:length(adj)]
可以将

结合起来以这种方式删除第一行的NA:

#
rtnM <- na.omit(ROC(IYR[,6]))  # remove all NA's 

使用您的xts对象sub,每列保存ROC&#39;

# get a list per column, with all the fields that are <= -0.05
answer.ls <- lapply(1:ncol(sub), function(i) sub[sub[,i] <= -0.05, i])

如果你直接使用列表,那么你的功能会更简单:

# import libraries
library(xts)
library(quantmod)
library(RColorBrewer)

mySymbols <- c("IYR", "DIA", "EEM", "EFA", "EWZ", "FXI", "GLD", "GSG")

# get symbols
getSymbols(mySymbols,
           from = "1995-01-01",
           to = "2014-01-01")

# apply ROC to the last column of each of them, 
# get() will allow to access the object using the character name
sub.ls <- lapply(mySymbols,
                 function(symbol) na.omit(ROC(get(symbol)[,6])))

# check dimensions (all are different)
lapply(sub.ls, dim)

answer.ls <- lapply(sub.ls,
                    function(sub.ticker) sub.ticker[sub.ticker[,1] <= -0.05, 1])

# each ticker has a different dimension
lapply(answer.ls, dim)

然后只是绘制它:

# plot each list
require(RColorBrewer)

# create colors palette
pal <- brewer.pal(length(answer.ls), "Set3")

# plot all series 
plot(sort(coredata(answer.ls[[1]])),
     type   = "o",
     col    = pal[1])
for(i in 2:length(answer.ls)){
   lines(sort(coredata(answer.ls[[i]])),
         col = pal[i])
}
legend("bottomright",
       legend  = mySymbols,
       col     = pal,
       pch     = c("o", rep("-", length(answer.ls) - 1)),
       lwd     = 4)

在排序XTS对象之前不要忘记coredata()