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.
Don’t use
getSymbolslike that inside a function. Setauto.assign=FALSEand assign the output ofgetSymbolstoddirectly: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
missingDaysfunction to accept the output from a call togetSymbols. Then you would avoid having to download the data for different sets of parameters.