Home | Login

Loading intraday market data into R Quantmod

10/26/2015

I was excited to find a source for free intraday data last night:

http://freemarketdataapi.barchartondemand.com/

 1 minute resolution, 3 months back for intraday data, 1500 requests per day and 2 years back of daily data, but you can get further back for free from sources like yahoo finance.

I whipped up this little bit of R to chart the API data using quantmod:

load.packages('quantmod')
load.packages('jsonlite')
library(lubridate)

# Here we get 5 min intervals from the API, docs: http://www.barchartondemand.com/api/getHistory
gdxjson <- fromJSON("http://marketdata.websol.barchart.com/getHistory.json?key=<< INSERT YOUR API KEY HERE >>&symbol=GDX&type=minutes&interval=5&startDate=20151019000000")

# Columns that need to be coerced to numeric types, and columns to remove
numeric_columns <- c('open','high','low','close','volume')
rm_columns <- c('timestamp','symbol','tradingDay')

results <- gdxjson$results

# Convert character vector to time objects using lubridate
results$timestamp <- ymd_hms(gdxjson$results$timestamp)
timestamp <- results$timestamp

# Now loop over columns coercing and removing as necessary, is there a better way?
for (col in names(results)) {
  if (is.element(col, numeric_columns)) {
    results[col] <- as.numeric(results[[col]])
  }
  if (is.element(col, rm_columns)) {
    results[col] <- NULL
  }
}

# Convert dataframe to XTS object
gdx_xts <- as.xts(results, timestamp)

chartSeries(gdx_xts)

gist of the code: https://gist.github.com/uberscientist/2330e4a5ba5b05c6bab6

The code is commented, so just read that, and hope it helps any other budget quants out there!

Here's the output chart with the addEMA() run on it.

#r #quantmod #chart #code