EDIT: In response to OP's comment:
So the bottom line seems to be that sites which provide free downloads of historical data are quirky, to say the least. They do not necessarily work for all valid symbols, and sometimes they become unavailable for no apparent reason. ichart.yahoo.com/table.csv
worked for me 24 hours ago, but does not work (for me) at the moment. This may be because Yahoo has imposed a 24 hour lockout on my IP, which they will do if they detect activity interpretable as a DDOS attack. Or it might be for some other reason...
The updated code below, which queries Google, does work (again, at the moment), for everything except DJIA. Note that there is more success if you specify the exchange and the symbol (EXCHANGE:SYMBOL
). I was unable to download SMH without the exchange. Finally, if your are having problems try uncommenting the print statement and pasting the url into a browser to see what happens.
tickers <- c("SPY","DJIA","IWM","NYSEARCA:SMH","OIH","XLY",
"XLP","XLE","XLI","XLB","XLK","XLU")
g <- function(x,from,to,output="csv") {
uri <- "http://www.google.com/finance/historical"
q.symbol <- paste("q",x,sep="=")
q.from <- paste("startdate",from,sep="=")
q.to <- paste("enddate",to,sep="=")
q.output <- paste("output",output,sep="=")
query <- paste(q.symbol,q.output,q.from,q.to,sep="&")
url <- paste(uri,query,sep="?")
# print(url)
try(assign(x,read.csv(url),envir=.GlobalEnv))
}
lapply(tickers,g,from="2001-03-01",to="2011-03-11",output="csv")
You can download DJI from the St. Louis Fed, which is very reliable. Unfortunately, you get all of it (from 1896), and it's a time series.
getSymbols("DJIA",src="FRED")
Original Response:
This worked for me, for everything except SMH and OIH.
tickers <- c("SPY","DJIA","IWM","SMH","OIH","XLY",
"XLP","XLE","XLI","XLB","XLK","XLU")
f <- function(x) {
uri <- "http://ichart.yahoo.com/table.csv"
symbol <- paste("s",x,sep="=")
from <- "a=2&b=1&c=2001"
to <- "d=2&e=11&f=2011"
period <- "g=d"
ignore <- "ignore=.csv"
query <- paste(symbol,from,to,period,ignore,sep="&")
url <- paste(uri,query,sep="?")
try(assign(x,read.csv(url),envir=.GlobalEnv))
}
lapply(tickers,f)
The main difference between this and getSymbols(...)
is that this uses ichart.yahoo.com
(as documented here), whereas getSymbols(...)
uses chart.yahoo.com
. The former seems to be much more reliable. In my experience, using getSymbols(...)
with Yahoo is a monumental headache.
If the suggestion of @user2492310, to use src="google"
works for you, then clearly this is the way to go. It didn't work for me.
One other note: SMH and OIH did not exist in 2001. The others all go back to at least 2000. So it might be that ichart.yahoo.com (and chart.yahoo.com) throws an error if you provide a date range outside of the symbol's operating range.