开发者

Reformatting xts object based on criteria

I have an xts object with series of monthly compounded returns of stocks in the following form:

       AALBERTS ABN_AMRO ABN_LNAM ACCELL_G    AEGON___  
1973-01       NA       NA       NA       NA          NA
1973-02       NA       NA       NA       NA -4.42149834
1973-03       NA       NA       NA       NA  0.03759308
1973-04       NA       NA       NA       NA -1.09827283
1973-05       NA       NA       NA       NA -7.30252682
1973-06       NA       NA       NA       NA -8.98970349
1973-07       NA       NA       NA       NA -5.59685493
:             :        :        :  开发者_JAVA百科      :            :
:             :        :        :        :            :

I would like to make the following selection: select only those stocks, which have both valid returns data at time t and valid returns data in the previous t-12 months. The stocks, which fulfil the mentioned criteria, need to be added to a separate xts object formatted in the following way:

1974-01    AEGON___       <mean of the values from t-12 to t>
1974-01    <other stock>  <mean of the values from t-12 to t>
1974-01    <other stock>  <mean of the values from t-12 to t>
:          :              :
1974-02    <other stock>  <mean of the values from t-12 to t>

So far I wasn't able to solve this issue, as my experience and understanding of R is very limited at this moment, so any help is appreciated.


Since xts objects are a matrix with an index attribute, you can't mix types. That means the example of what you want your result to look like is not possible. That said, you can just use the rollapply function.

require(quantmod)
getSymbols("SPY;QQQQ")
x <- merge(ROC(Cl(SPY)),ROC(Cl(QQQQ)))
#mx <- rollapply(x, 12, mean, na.rm=TRUE)  # default align="center"
mx <- rollapply(x, 12, (mean), align="right")
head(mx)
#               SPY.Close    QQQQ.Close
# 2007-01-10           NA            NA
# 2007-01-11 0.0005932477  0.0008627708
# 2007-01-12 0.0006620534 -0.0009128343
# 2007-01-16 0.0019978226  0.0008508299
# 2007-01-17 0.0006291557 -0.0002853558
# 2007-01-18 0.0006238259 -0.0010075785
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜