Cam Cam - 3 months ago 24
R Question

Using the subsetting operator :: in quantmod with variables

How do I apply a user initialized date variables as the start and end values of the subset operator :: from the R-package, quantmod?

For example, when I apply user initialized date variables,

end.date <-Sys.Date()
start.date <-end.date - 5*365 #5- years to-date
start.date.char <-as.character(start.date)
end.date.char <-as.character(end.date)


to get 5-years of stock data

library(quantmod)

getSymbols("GILD",src="yahoo")

GILD.5YTD<-GILD['start.date.char::end.date.char']


I get the following error:

Error in if (length(c(year, month, day, hour, min, sec))
== 6 && c(year, :
missing value where TRUE/FALSE needed


In addition: Warning messages:

1: In as_numeric(YYYY) : NAs introduced by coercion

2: In as_numeric(MM) : NAs introduced by coercion

3: In as_numeric(DD) : NAs introduced by coercion

4: In as_numeric(YYYY) : NAs introduced by coercion

5: In as_numeric(MM) : NAs introduced by coercion

6: In as_numeric(DD) : NAs introduced by coercion


(I'm sure this is a basic question, but I'm a newbie)

Thanks

Answer

There are convenient high-level functions to subset an xts object as returned, e.g., by quantmod's getSymbol().

For a time-based subset, the last() function from the xts package (automatically loaded by quantmod) is quite handy:

library(quantmod)
getSymbols("GILD",src="yahoo")
GILD_last5Years <- last(GILD, "5 years")
#> head(GILD_last5Years)
#           GILD.Open GILD.High GILD.Low GILD.Close GILD.Volume GILD.Adjusted
#2012-01-03     41.46     41.99    41.35      41.86    19564000      20.46895
#2012-01-04     41.95     42.06    41.70      42.02    16236000      20.54719
#2012-01-05     42.04     42.97    42.00      42.52    18431800      20.79168
#2012-01-06     42.38     43.10    42.20      42.78    15542000      20.91882
#2012-01-09     42.49     42.99    42.35      42.73    16801200      20.89437
#2012-01-10     43.10     45.04    42.94      44.25    30110000      21.63763

This can be combined with an equivalent function first() to select a specific time span within the series.

Comments