I just started with quantmod package. If I want to select stocks based on their recent performance, then I need to loop through all the stocks in, say, NYSE. So I need:
- get all the stock symbols
- select those symbols that do have data
- loop through them one by one(say, each time, download the stock data as $X$, and do some analysis. Then loop to next one, and set it as $X$)
My question is: how can I do these? Here is part of my thought:
use stockSymbols() function in TTR package:
AllSym <- stockSymbols()
. The first column ofAllSym
are all the potential symbols.Use
getSymbols(AllSym[i,1])
to loop all the stocki
:
Questions here:
Not all the symbols from TTR have data. Some may have error when using
getSymbols
. I actually do not care about this certain stock. So how can I continue with the loop? [How can I use thetry
function?]The
getSymbols
function will automatically make the stock symbols as the variables. How can I copy(or set) it to $X$(instead of something like $APPL$)?How can I loop trough the variables with their names saved as strings in a vector? For example, if we do use
getSymbols
function to get data with name as the stock symbol. How can I loop through those stocks?[Note that their variable name are stored in first columnAllSym
as string]
Thank you very much!
Answer
Try the following:
library(quantmod) # also loads xts and TTR
# Fetch all Symbols & store only the tickers to retrieve the data
symbols <- stockSymbols()
symbols <- symbols[,1]
Next we will specify where to to store data
dataset<- xts() # Only run once
The following code is the loop that will download OHLC data to your environment. It will then store the Adjusted Close of the downloaded companies and merge them in dataset
# cool progress bar to see the % of completion
n <- length(symbols)
pb <- txtProgressBar(min = 0, max = n, style=3)
# Actual loop:
for(i in 1:length(symbols)) {
symbols[i]-> symbol
# specify the "from" date to desired start date
tryit <- try(getSymbols(symbol,from="2014-01-01", src='yahoo'))
if(inherits(tryit, "try-error")){
i <- i+1
} else {
# specify the "from" date to desired start date
data <- getSymbols(symbol, from="2014-01-01", src='yahoo')
dataset <- merge(dataset, Ad(get(symbols[i])))
rm(symbol)
}
setTxtProgressBar(pb, i)
}
If the loop breaks, say on the 50th iteration, then just re run the last block of code by changing the following
# cool progress bar to see the % of completion
n <- length(symbols)
pb <- txtProgressBar(min = 0, max = n, style=3)
# Actual loop:
# IF IT BREAKS ON THE 50th ITERATION, it must be skipped, therefore change it to 51
for(i in 51:length(symbols)) {
symbols[i]-> symbol
...
Keep on doing it until symbols
is exhausted. Remember that it will download all the data unto your environment & that all the Adjusted Close prices are to be found in dataset
No comments:
Post a Comment