Search code examples
rquantmod

R yearly returns from dataframe with date and close


I have a data.frame df with date df$Date and a close df$Close column. I am trying to get yearly returns but I am having problems

I tried

library(quantmod)
yr <- data.frame( periodReturn(df, period='yearly', subset='2008::'))

and also having date as rownames, but cannot get it to work. Thank you for your help.


Solution

  • Your code almost works if you just convert to xts. If you're having difficulty converting your data.frame to xts, then provide more info about your data as requested in the comments of your question.

    getSymbols("SPY", src='yahoo', return.class='data.frame')
    #[1] "SPY"
    class(SPY)
    #[1] "data.frame"
    as.data.frame(periodReturn(xts(SPY[["SPY.Close"]], as.Date(rownames(SPY))), 
                               'yearly', subset="2008/"))
               yearly.returns
    2008-12-31   -0.382805554
    2009-12-31    0.234929078
    2010-12-31    0.128409907
    2011-12-30   -0.001988072
    2012-06-04    0.020717131