I am trying to get stock prices of multiple tickers over long period, collecting them in a dataframe.
Here goes my code
library('quantmod')
symbol1 = c('SPY', # S$P500
'IEF', # 10Y treasury bond
'TLT', # 20Y treasury bond
'AGG', # Core U.S Aggregate Bond
'SHY', # Cash
'GLD', # Gold
'IWN') # Russell 2000 value
price = function(symbols){
loadSymbols(symbols, src = 'yahoo', from= '2000-11-01', periodicity = 'monthly')
prices = list()
for (i in 1:length(symbols)) {
prices[[i]] = Ad(get(symbols[i])[,6])
}
prices = do.call(cbind, prices)
colnames(prices) = gsub('\\.[A-z]*', '',colnames(prices))
prices = na.omit(prices)
return(prices)
}
a = price(symbol1)
I have two problems,
How can I solve this problems?
or is there any better and neat code to get time series monthly data (adjusted price) of multiple tickers?
Warnings about missing values:
If you take a look at one of the tickers,
loadSymbols('SPY', src = 'yahoo', from= '2000-11-01', periodicity = 'monthly')
> SPY[is.na(SPY$SPY.Open),]
SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
2021-02-01 NA NA NA NA NA NA
You will notice that the Yahoo API has returned a missing value for month of 2021-02-01. This makes sense, because you have requested monthly averages, which you cannot calculate for the ongoing month.
You would want to filter your data to exclude the ongoing month. For instance, this runs without errors:
loadSymbols(symbols, src = 'yahoo', from= '2000-11-01',to='2021-01-31', periodicity = 'monthly')
Regarding your second issue, I was not able to replicate that:
a = price(symbol1)
a %>% tail(10)
SPY IEF TLT AGG SHY GLD IWN
2020-04-01 286.8316 120.6718 164.8157 115.0776 86.24834 158.80 90.90018
2020-05-01 300.4978 121.0832 161.9357 115.8682 86.21467 162.91 93.73619
2020-06-01 304.4870 121.1411 162.4827 116.6548 86.23647 167.37 95.97152
2020-07-01 323.8377 122.1878 169.7082 118.2020 86.32609 185.43 98.42319
2020-08-01 346.4406 121.0134 161.1535 117.2467 86.31715 184.83 103.70540
2020-09-01 332.1390 121.4210 162.3971 117.1425 86.31710 177.12 98.25503
2020-10-01 325.1540 119.7535 156.9142 116.4811 86.28612 176.20 102.47127
2020-11-01 360.5232 120.1606 159.5191 117.8953 86.30606 166.67 122.00240
2020-12-01 372.2931 119.7973 157.4051 117.8594 86.31503 178.36 131.08641
2021-01-01 370.0700 118.6400 152.0000 117.3100 86.40000 172.61 138.39999
Nonetheless, comparison to this chart clearly shows that the values you attached for TLT prior to 2021-02-01 are wrong.