Kian
Kian

Reputation: 3229

Quantmod in R... downloading stock data

In the Quantmod package in R, you can download share price data as follows

my_portfolio <- c("AAPL", "SBUX")
getSymbols(my_portfolio)

And this works fine. I can access the stock data by typing in AAPL or SBUX. For example

> head(AAPL)
           AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2007-01-03     86.29     86.58    81.90      83.80   309579900         11.34
2007-01-04     84.05     85.95    83.82      85.66   211815100         11.59
2007-01-05     85.77     86.20    84.40      85.05   208685400         11.51
2007-01-08     85.96     86.53    85.28      85.47   199276700         11.56
2007-01-09     86.45     92.98    85.15      92.57   837324600         12.52
2007-01-10     94.75     97.80    93.45      97.00   738220000         13.12

... and I can do lots of nice stats in this way.

But this is inconvenient because if I change my_portfolio, say by replacing "AAPL" with "IBM", then I have to change all future occurrences of AAPL's with IBM's later in the script.

My Question: How can I find the downloaded data associated with my_portfolio obtained from getSymbols without having to explicitly typing AAPL and SBUX for a second time?

Upvotes: 0

Views: 2017

Answers (1)

jlhoward
jlhoward

Reputation: 59335

I'd be inclined to do it this way:

library(quantmod)
my_portfolio <- c("AAPL", "SBUX")
stocks <- lapply(my_portfolio,getSymbols,auto.assign=FALSE)
names(stocks) <- my_portfolio
# access the data
head(stocks[[my_portfolio[1]]])
#            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
# 2007-01-03     86.29     86.58    81.90      83.80   309579900         11.34
# 2007-01-04     84.05     85.95    83.82      85.66   211815100         11.59
# 2007-01-05     85.77     86.20    84.40      85.05   208685400         11.51
# 2007-01-08     85.96     86.53    85.28      85.47   199276700         11.56
# 2007-01-09     86.45     92.98    85.15      92.57   837324600         12.52
# 2007-01-10     94.75     97.80    93.45      97.00   738220000         13.12

So this generates a named list of xts objects containing the stock prices. The list elements have the same names as the stocks in your portfolio.

Unfortunately, the column names are still stock-specific (e.g., AAPL.Close rather than just Close), but you can overcome that problem using, e.g., the Cl(...) function in quantmod.

Upvotes: 1

Related Questions