very new to programming in R - but I am stumped on this one:
I'd like to only have to enter stock symbol data once in the script, but can't figure out how to reference ie adjusted close later on using Ad(x) without having to type the stock name again. I've tried passing a variable in like below but get error messages:
#get stock series data
stockPair <- c("SPY","DIA")
look_per <- "2015-01-01"
stckA <- suppressWarnings(getSymbols(stockPair[1], from = look_per))
stckB <- suppressWarnings(getSymbols(stockPair[2], from = look_per))
#get Adjusted close data
adA <- Ad(stckA )
adB <- Ad(stckB )
Error in Ad(stckA) :
subscript out of bounds: no column name containing "Adjusted"
The first thing you should do when you get an error is to look at your data. In this case, stckA
and stckB
are not what you think they are.
R> stckA <- suppressWarnings(getSymbols(stockPair[1], from = look_per))
R> stckB <- suppressWarnings(getSymbols(stockPair[2], from = look_per))
R> str(stckA)
chr "SPY"
R> str(stckB)
chr "DIA"
As you can see, those two objects are only character strings of the symbols returned by getSymbols
, not the data. You need to set auto.assign=FALSE
if you want to assign the output of getSymbols
to an object.
R> stckA <- getSymbols(stockPair[1], from = look_per, auto.assign = FALSE)
R> str(Ad(stckA)) # now stckA contains data
An ‘xts’ object on 2015-01-02/2015-08-05 containing:
Data: num [1:149, 1] 204 200 198 200 204 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr "SPY.Adjusted"
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr "yahoo"
$ updated: POSIXct[1:1], format: "2015-08-05 20:02:30"