Search code examples
rquantmod

How do I retrieve the key of a vector in R?


I am trying to find months in S&P 500 which yielded more than x%. The following code find such instances:

getSymbols('^GSPC', from='2010-01-01')
G <- monthlyReturn(Cl(GSPC))
names(G) <- 'RET.M'
G[G$RET.M>.05]

Now, I would like to find out what is the yearly return of such instances? I know I can calculate the yearly return as follow:

G$RET.Y <- yearlyReturn(Cl(GSPC))

But now, I want to query G$RET.Y to get the yearly return for months that yielded 5% or more.

Any suggestions?


Solution

  • You can merge them, fill backwards using na.locf with fromLast=TRUE, then subset as normal

    G$RET.Y <- yearlyReturn(Cl(GSPC))
    G$RET.Y <- na.locf(G$RET.Y, fromLast=TRUE)
    G$RET.Y[G$RET.M > 0.05]
    #                   RET.Y
    #2010-03-31  0.1100186233
    #2010-07-30  0.1100186233
    #2010-09-30  0.1100186233
    #2010-12-31  0.1100186233
    #2011-10-31 -0.0000318056
    #2013-01-31  0.0643252302
    

    Or, you could format the index as a character representation of the year -- format(index(G[G$RET.M > 0.05]), "%Y") -- then just subset the yearly data with that

    do.call(rbind, lapply(format(index(G[G$RET.M > 0.05]), "%Y"), function(x) {
      yearlyReturn(Cl(GSPC))[x]
    }))
    #           yearly.returns
    #2010-12-31   0.1100186233
    #2010-12-31   0.1100186233
    #2010-12-31   0.1100186233
    #2010-12-31   0.1100186233
    #2011-12-30  -0.0000318056
    #2013-02-08   0.0643252302