Search code examples
robjectenvironmentquantmod

Using quantmod periodReturn with an index of variables in the environment


I've written the following function to autmoatically assess the effect of missing the best/worst days of trading ina given stock. Unfortunately, one part of the function seems to fail:

library(quantmod)
    missingDays<- function(ticker,dmiss=10,type="best",period="days",fdate="2000-01-01",tdate=Sys.Date()) {
          getSymbols(ticker,from=fdate,to=tdate) #quantmod to pull ticker info
          d<-get(ls()[1])
          x<-as.data.frame(periodReturn(Cl(d),period=period))
          x<- x[order(x[1]),]
          if(type=="best") {
            (((mean(x[1:(length(x)-dmiss)],na.rm=TRUE)+1)^(251))-1)*100      #average daily return, annualized  
          } else {
            (((mean(x[dmiss:(length(x))],na.rm=TRUE)+1)^(251))-1)*100      #average daily return, annualized
          }  
        }
missingDays("^GSPC",10,type="best",period="daily",fdate="2000-01-01")

The error clearly happens in these two lines of code:

  d<-get(ls()[1])
  x<-as.data.frame(periodReturn(Cl(d),period=period))

This is very odd, because when I run this directly, rather than in a function, it works fine. It seems to not be able to identify d as an xts object.

My apologies if I've missed something obvious - I've been at this a while.

Much thanks for any help.


Solution

  • Don't use getSymbols like that inside a function. Set auto.assign=FALSE and assign the output of getSymbols to d directly:

    d <- getSymbols(ticker,from=fdate,to=tdate,auto.assign=FALSE)
    

    This is all described in detail in ?getSymbols. I would encourage you to read it carefully.


    UPDATE:

    Now that I think about it a bit more, it would probably be better for the missingDays function to accept the output from a call to getSymbols. Then you would avoid having to download the data for different sets of parameters.

    missingDays <- function(symbol, dmiss=10, type="best", period="daily",
            fdate="2000-01-01", tdate=Sys.Date()) {
      x <- as.data.frame(periodReturn(Cl(symbol),period=period))
      x <- x[order(x[1]),]
      if(type=="best") {
        #average daily return, annualized
        (((mean(x[1:(length(x)-dmiss)],na.rm=TRUE)+1)^(251))-1)*100
      } else {
        #average daily return, annualized
        (((mean(x[dmiss:(length(x))],na.rm=TRUE)+1)^(251))-1)*100
      }
    }
    getSymbols("^GSPC", from="2000-01-01")
    missingDays(GSPC)