0

I am using the following code to download the YTD AdjClose of SPY.

library(tseries)
AjdClose_SPY <- get.hist.quote("SPY", quote="Adj", start="2015-01-01", retclass="zoo")

Now, say I have a portfolio

portfolio <- c('SPY','AAPL','HD')

How would I be able to loop through "portfolio" and create a variable "AdjClose_" for each ticker in my portfolio? Thanks in advance!

2
  • Just try setNames(lapply(portfolio, function(x) get.hist.quote(x, quote="Adj", start="2015-01-01", retclass="zoo")),paste0("AjdClose_",portfolio)). You'll get a list object whose names are what you indicated. Don't create several variables; a single named list is much cleaner and easier to use. Commented Nov 23, 2015 at 19:03
  • or maybe: setNames(do.call(merge, lapply(portfolio, get.hist.quote, quote="Adj", start="2015-01-01", retclass="zoo")), portfolio) Commented Nov 23, 2015 at 20:37

2 Answers 2

1

Check ?assign

Example:

stock = "AAPL"
assign(paste0("AdjClose_", stock), 100)
Sign up to request clarification or add additional context in comments.

Comments

0

Have you seen the quantmod package? Example:

library(quantmod)
portfolio <- c('SPY','AAPL','HD')
getSymbols(portfolio, start = "2015-01-01")

This will create xts objects for each ticker in portfolio in your current environment that hold "Open", "High", "Low", "Close", "Volume", and "Adjusted" price data for each ticker.

If you then want, you can put all Adjusted prices in a data frame like so:

AdjPrices <- do.call(merge, lapply(portfolio, function(x) Ad(get(x))))

2 Comments

This worked like a charm. I am utterly confused though, how the heck did: "AdjPrices <- do.call(merge, lapply(portfolio, function(x) Ad(get(x))))" know to take the adjusted close?
lapply cycles through all character strings in portfolio and applies Ad(get(x)) to them. The quantmod function Ad() extracts the Adjusted Close and get(x) calls an R object using a character string. do.call(merge,...) then merges all list items from lapply() into a single data frame.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.