Reputation: 15
I would like to download historical Adjusted closing stock prices and save them in the same DataFrame
This was my attempt
library('quantmod')
start <- as.Date("2017-01-01")
end <- as.Date("2017-10-27")
tickers = c('AAPL','TSLA')
i=1
data <- getSymbols(tickers, src = "yahoo", from = start, to = end)
data
for (i in length(tickers)) {
data <- getSymbols(tickers[i], src = "yahoo", from = start, to = end)
Data <- as.data.frame(tickers[i])
Data <- Data[6] #6 is the column of the adjusted price
i=i+1
}
How can I make this possible ?
Thank you in advance
Upvotes: 0
Views: 1001
Reputation: 2986
Another alternative:
getSymbols(tickers)
tail(do.call(merge,lapply(tickers, function(x) Cl(get(x)))))
AAPL.Close TSLA.Close
2020-11-30 119.05 567.60
2020-12-01 122.72 584.76
2020-12-02 123.08 568.82
2020-12-03 122.94 593.38
2020-12-04 122.25 599.04
2020-12-07 123.75 641.76
If you want a data frame object:
tail(fortify.zoo(do.call(merge,lapply(tickers, function(x) Cl(get(x))))))
Index AAPL.Close TSLA.Close
3503 2020-11-30 119.05 567.60
3504 2020-12-01 122.72 584.76
3505 2020-12-02 123.08 568.82
3506 2020-12-03 122.94 593.38
3507 2020-12-04 122.25 599.04
3508 2020-12-07 123.75 641.76
If you want the adjusted close use Ad(get(x))
instead of Cl(get(x))
.
Upvotes: 3
Reputation: 276
The code set forth below produces a data frame with the adjusted closing prices for Apple and Tesla.
library('quantmod')
start <- as.Date("2017-01-01")
end <- as.Date("2017-10-27")
tickers = c('AAPL','TSLA')
Data <- c()
for (i in 1:length(tickers)) {
data <- getSymbols(tickers[i], src = "yahoo", from = start, to = end, auto.assign = FALSE)[,6]
Data <- merge.xts(Data, data)
}
Data <- as.data.frame(Data)
Upvotes: 1