This is a newbie question in R. I am downloading yahoo finance monthly stock price data using R where the ticker names are read from a text file. I am using a loop to read the ticker names to download the data and putting them in a list. My problem is some ticker names may not be correct thus my code stops when it encounters this case. I want the following.
Here is the sample code for the simplified version of my problem.
library(tseries) tckk <- c("MSFT", "C", "VIA/B", "MMM") # ticker names defined numtk <- length(tckk); ustart <- "2000-12-30"; uend <- "2007-12-30" # start and end date all_dat <- list(); # empty list to fill in the data for(i in 1:numtk) { all_dat[[i]] <- xxx <- get.hist.quote(instrument = tckk[i], start=ustart, end=uend, quote = c("Open", "High", "Low", "Close"), provider = "yahoo", compression = "m") }
The code stops at the third entry but I want to skip this ticker and move on to "MMM". I have heard about Trycatch() function but do not know how to use it.
As per question 2, I want the variable names for the first element of the list to be "MSFTopen", "MSFThigh", "MSFTlow", and "MSFTclose". Is there a better to way to do it apart from using a combination of loop and paste() function.
Finally, for question 3, I need a dataframe with three columns corresponding to closing prices. Again, I am trying to avoid a loop here.
Thank you.
You can install it by typing the command install. packages("quantmod") in your R console. The prices downloaded in by using quantmod are xts zoo objects. For our calculations we will use tidyquant package which downloads prices in a tidy format as a tibble .
In the Yahoo Finance site, if you click through the details page for a specific stock, you can access additional details that are not present in the page we just scraped. As a result, we will now tell ParseHub to click on each stock on the list we just scraped and pull additional data from these pages.
Your best bet is to use quantmod and store the results as a time series (in this case, it will be xts
):
library(quantmod) library(plyr) symbols <- c("MSFT","C","VIA/B","MMM") #1 l_ply(symbols, function(sym) try(getSymbols(sym))) symbols <- symbols[symbols %in% ls()] #2 sym.list <- llply(symbols, get) #3 data <- xts() for(i in seq_along(symbols)) { symbol <- symbols[i] data <- merge(data, get(symbol)[,paste(symbol, "Close", sep=".")]) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With