Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading intraday data into R for handling it with quantmod

I need to modify this example code for using it with intraday data which I should get from here and from here. As I understand, the code in that example works well with any historical data (or not?), so my problem then boils down to a question of loading the initial data in a necessary format (I mean daily or intraday).

As I also understand from answers on this question, it is impossible to load intraday data with getSymbols(). I tried to download that data into my hard-drive and to get it then with a read.csv() function, but this approach didn't work as well. Finally, I found few solutions of this problem in various articles (e.g. here), but all of them seem to be very complicated and "artificial".

So, my question is how to load the given intraday data into the given code elegantly and correctly from programmer's point of view, without reinventing the wheel?

P.S. I am very new to analysis of time series in R and quantstrat thus if my question seems to be obscure let me know what you need to know to answer it.

like image 696
Mstislav Toivonen Avatar asked Jan 17 '15 14:01

Mstislav Toivonen


1 Answers

I don't know how to do this without "reinventing the wheel" because I'm not aware of any existing solutions. It's pretty easy to do with a custom function though.

intradataYahoo <- function(symbol, ...) {
  # ensure xts is available
  stopifnot(require(xts))
  # construct URL
  URL <- paste0("http://chartapi.finance.yahoo.com/instrument/1.0/",
    symbol, "/chartdata;type=quote;range=1d/csv")

  # read the metadata from the top of the file and put it into a usable list
  metadata <- readLines(paste(URL, collapse=""), 17)[-1L]
  # split into name/value pairs, set the names as the first element of the
  # result and the values as the remaining elements
  metadata <- strsplit(metadata, ":")
  names(metadata) <- sub("-","_",sapply(metadata, `[`, 1))
  metadata <- lapply(metadata, function(x) strsplit(x[-1L], ",")[[1]])
  # convert GMT offset to numeric
  metadata$gmtoffset <- as.numeric(metadata$gmtoffset)

  # read data into an xts object; timestamps are in GMT, so we don't set it
  # explicitly. I would set it explicitly, but timezones are provided in
  # an ambiguous format (e.g. "CST", "EST", etc).
  Data <- as.xts(read.zoo(paste(URL, collapse=""), sep=",", header=FALSE,
    skip=17, FUN=function(i) .POSIXct(as.numeric(i))))
  # set column names and metadata (as xts attributes)
  colnames(Data) <- metadata$values[-1L]
  xtsAttributes(Data) <- metadata[c("ticker","Company_Name",
    "Exchange_Name","unit","timezone","gmtoffset")]
  Data
}

I'd consider adding something like this to quantmod, but it would need to be tested. I wrote this in under 15 minutes, so I'm sure there will be some issues.

like image 179
Joshua Ulrich Avatar answered Sep 21 '22 19:09

Joshua Ulrich