I was trying to replicate the momentum strategy by rbresearch with S&P 500 companies. However it turned out that getSymbols
was not able to grab price data for all tickers and I only got around 300 stocks by using:
getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='2000-01-01', to = '2015-12-31')
I found this thread discussing about this issue and it might be coming from the source "chart.yahoo.com". Therefore I adopted the method suggested by jlhoward and it seemed to work perfectly without warnings.
UPDATE: After checking quantmod
package, I found it is also grabbing data from ichart.yahoo.com now.
However when it comes to calculating the monthly close, an error read like,
Error in try.xts(x) :
Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format
Called from: try.xts(x)
Here are my questions and what I don't understand:
1) Is there a possible way to direct getSymbols to "ichart.yahoo.com" which gives more reliable quotes?
2) I have converted all symbols to xts objects so why the error was called from try.xts?
3) I presume the problem is with the dates, which are not in ISO 8601 format. But I haven't found a way to convert the dates to POSIXct since the dates are only round to days.
4) Any comments to the codes are much appreciated.
I attached with the codes and the sp500components.csv could be downloaded from here.
Thanks for your time and kind help! All the best.
library(quantstrat)
library(FinancialInstrument)
library(TTR)
symbols <- read.table("sp500components.csv", header = FALSE, sep = ",")$V1
symbols <- as.character(symbols)
currency("USD")
stock(symbols, currency="USD",multiplier=1)
MonthlyAd <- function(x){
# Converts daily data to monthly and returns only the monthly close
# Note: only used with Yahoo Finance data so far
# Thanks to Joshua Ulrich for the Monthly Ad function
#
# args:
# x = daily price data from Yahoo Finance
#
# Returns:
# xts object with the monthly adjusted close prices
sym <- sub("\\..*$", "", names(x)[1])
Ad(to.monthly(x, indexAt = 'lastof', drop.time = TRUE, name = sym))
}
symEnv <- new.env()
f <- function(x) {
uri <- "http://ichart.yahoo.com/table.csv"
symbol <- paste("s",x,sep="=")
from <- "a=1&b=1&c=2000"
to <- "d=31&e=12&f=2015"
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=symEnv))
}
lapply(symbols,f)
ts <- function(x) {
x["Date"] <- as.Date.character(x[["Date"]], "%Y-%m-%d")
x <- xts(x[,-1], order.by = x$Date)
colnames(x) <- gsub("Adj", "Adjusted", colnames(x))
assign(symbol, x)
}
eapply(symEnv, ts)
symbols.close <- do.call(merge, eapply(symEnv, MonthlyAd))