I'm a beginner in R programming and I need some help for a class assignment:
In fact I need to extract the stock prices with a FOR loop (its use is manadatory)
So I've tried the following:
options(digits=4, width=70)
install.packages("PerformanceAnalytics")
install.packages("tseries")
install.packages("zoo")
library("PerformanceAnalytics")
library("tseries")
library("zoo")
stocks<- c("AAPL","MSFT","AMZN","TSLA","NVDA","UNH","JNJ","JPM","XOM","CVX")
for(i in stocks)
{
stock.prices <- get.hist.quote(instrument=i, start="2010-01-01",
end="2020-01-31", quote="AdjClose",
provider="yahoo", origin="2000-01-09",
compression="m", ret)
}
and I'm getting the values for "CVX" only which is quite normal since each stock is discarding the previous one.
I need to pull the data into the following shape to be ale to analyze it.
AAPL MSFT GOOG
2015-01-02 107.9586 45.82758 524.8124
2015-01-05 104.9172 45.40616 513.8723
2015-01-06 104.9271 44.73971 501.9623
2015-01-07 106.3984 45.30815 501.1023
2015-01-08 110.4864 46.64103 502.6823
2015-01-09 110.6049 46.24900 496.1723
I've found several solutions that work without the R loop but it is mandatory for my assignment to use it.
Thank you in advance for your help.
CodePudding user response:
Sticking as closely as possible to your existing solution, the main issue is that you need to store each iteration of the loop somewhere (below, in a list called stocks.dl
. Once you have that, you can combine them with merge.zoo
:
library("PerformanceAnalytics")
library("tseries")
library("zoo")
stocks<- c("AAPL","MSFT","AMZN","TSLA","NVDA","UNH","JNJ","JPM","XOM","CVX")
stocks.dl <- list()
for(i in stocks) {
stocks.dl[[i]] <- get.hist.quote(instrument=i, start="2010-01-01",
end="2020-01-31", quote="AdjClose",
provider="yahoo", origin="2000-01-09",
compression="m", ret)
dimnames(stocks.dl[[i]])[[2]] <- i # update column name to match the stock name
}
data.stocks <- do.call(merge.zoo, stocks.dl)
AAPL MSFT AMZN TSLA NVDA UNH JNJ
2010-01-01 5.873429 21.72060 125.41 NA 3.533751 27.46159 43.88154
2010-02-01 6.257530 22.09827 118.40 NA 3.719738 28.17724 43.97926
2010-03-01 7.186587 22.68174 135.77 NA 3.995275 27.18697 45.86330
2010-04-01 7.984451 23.64971 137.10 NA 3.607228 25.22305 45.23025
2010-05-01 7.855704 19.97913 125.46 NA 3.017121 24.21340 41.00968
2010-06-01 7.692095 17.89899 109.26 NA 2.344354 23.65532 41.92373