user5552631
user5552631

Reputation:

Creating Variables via A loop in r

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!

Upvotes: 0

Views: 89

Answers (2)

Ivan Vanchev
Ivan Vanchev

Reputation: 111

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))))

Upvotes: 0

Tonio Liebrand
Tonio Liebrand

Reputation: 17719

Check ?assign

Example:

stock = "AAPL"
assign(paste0("AdjClose_", stock), 100)

Upvotes: 1

Related Questions