I want to use a string of stock symbols and loop through it pulling pairs into a block of code for analysis. I can get the loop to pull in the data but then I want to assign the data to a generic data element so I can just run it through my code. Can't get hold of the xts object from the list programmatically and get it to execute - just returns the value.
library(quantmod)
library(xts)
asset1 = "ADBE"
asset2 = "VGT"
assets <- c(asset1, asset2)
assets # This returns [1] "ADBE "VGT"
getSymbols(assets[1]) # All good so far this returns an xts object [1:3247] [1:6] called ADBE
Manually if I enter:
df01 = ADBE # This makes df01 the same as the data values for ADBE.
df01 <- assets[1] # makes df01 a character string equal to "ADBE"
Question:
How do I make the df01 = ADBE piece happen programmatically using the values in assets. When I use assets[1] it fails and as I don't want to type the stock codes every time but assign it and as I loop through a list of assets(n) using generic code.
I realise this is probably a simple dumb question but its got me stumped and cannot find a solution on-line.
Keep the results in one list, by default getSymbols assigns every asset into the environment, we can change this by using auto.assign = FALSE
, example:
myResult <- lapply(assets, getSymbols, auto.assign = FALSE)
myResult <- setNames(myResult, assets)
# access using names
myResult$ADBE
# ADBE.Open ADBE.High ADBE.Low ADBE.Close ADBE.Volume ADBE.Adjusted
# 2007-01-03 40.72 41.32 38.89 39.92 7126000 39.92
# ...
# or using a variable
assets[ 1 ]
# [1] "ADBE"
myResult[[ assets[ 1 ] ]]
# ADBE.Open ADBE.High ADBE.Low ADBE.Close ADBE.Volume ADBE.Adjusted
# 2007-01-03 40.72 41.32 38.89 39.92 7126000 39.92
# ...
If we do not wish to keep them in a list, then maybe use get
:
getSymbols(assets)
df01 <- get(assets[ 1 ])
df01
# ADBE.Open ADBE.High ADBE.Low ADBE.Close ADBE.Volume ADBE.Adjusted
# 2007-01-03 40.72 41.32 38.89 39.92 7126000 39.92
# ...