Create intraday chart with R using chartSeries, candleChart, or barChart? -


can chartseries, candlechart, or barchart used create intraday chart in r?

chartseries, candlechart, , barchart part of quantmod package r.

first need example intraday trading data, can free a variety of sites including google's undocumented finance api.

get example data (hourly intervals)

query_addr <- 'https://www.google.com/finance/getprices' stock_symb <- 'goog' stock_exch <- 'nasd' intvl_size <- 60*60 # 1 hr interval (in seconds) -- use 24*this daily period_len <- '90d' output_fmt <- 'd,o,h,l,c,v' # date, open, high, low, close, volume  library(httr) resp <-    post(url = query_addr,         query = list(q = stock_symb,                      x = stock_exch,                      = intvl_size,                      p = period_len,                     f = output_fmt) )  df <-    read.csv(text = content(resp),            skip = 7,            header = false,            stringsasfactors = false)  # need function munge date convention used google finance api g_fin_date <- function(dstr, intvl_size){   unix_dates <- numeric(length(dstr))   date_is_unix <- grepl('^a',dstr)   unix_dates[date_is_unix] <- as.numeric(sub('^a','',dstr[date_is_unix]))   for(i in 2l:length(dstr)){     if(!date_is_unix[i]){       unix_dates[i] <- unix_dates[i-1] + intvl_size     }   }   return(as.posixct(unix_dates,origin="1970-01-01",tz="gmt" )) }  # see header of resp text column order names(df) <- c('close_date','close','high','low','open','volume')  df[,'close_date'] <- g_fin_date(df[,'close_date'], intvl_size=intvl_size) 

here have chosen hourly open (i.e. beginning price), high, low, close (i.e. ending price)-- can specify finer level of detail if desire -- still roll larger period quantmod::to.period().

make xts

once have data frame (such might obtain api or flat file) need convert data xts. note xts timestamp must row name (and can dropped columns).

library(xts) rownames(df) <- df$close_date df$close_date <- null 

convert ohlc (open, high, low, close) using xts

this straightforward aggregation -- see ?to.period

goog <- to.hourly(as.xts(df)) # daily use to.daily(as.xts(df)) 

more chart examples available at quantmod.com.

make charts using quantmod

there great charts built quantmod, including ones mentioned.

library(quantmod) chartseries(goog) barchart(goog, theme='white.mono',bar.type='hlc') candlechart(goog,multi.col=true,theme='white')  

enjoy charts

enter image description here

enter image description here

enter image description here


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -