R/Options App/Robinhood/functions.R

Defines functions create_chart rh_historicals_one rh_historicals rh_quote robinhood_quotes robinhood_intraday_historicals robinhood_daily_historicals get_equity_holdings get_watchlist_tickers access_robinhood

Documented in rh_historicals rh_historicals_one rh_quote

##### Required dependencies ################################################
library(httr)
library(R6)
library(jsonlite)
library(XML)
library(xml2)
library(magrittr)
library(plyr)
library(xts)
library(plotly)

#' Gain access to the robinhood API
#'
#' @param username Your robinhood account username.
#' @param password Your robinhood account password.
access_robinhood <- function(username, password){

  source("Robinhood/BaseEndpoints.R")
  source("Robinhood/Login.R")
  source("Robinhood/Account.R")
  source("Robinhood/RobinhoodQuotes.R")
  source("Robinhood/Orders.R")
  userLogin=Login$new(username=username,password=password)
  userAccount=Account$new(userLogin)
  userQuotes=RobinhoodQuotes$new(userAccount)

  toReturn<-list(login=userLogin, account=userAccount,quotes=userQuotes)

  assign("robinhoodUser", toReturn, envir=.GlobalEnv)

  rm(BaseEndpoints,envir=.GlobalEnv)
  #rm(Login,envir=.GlobalEnv)
  #rm(Account,envir=.GlobalEnv)
  rm(RobinhoodQuotes,envir=.GlobalEnv)

}

#' Get your watch list tickers
#'
get_watchlist_tickers <- function() {
  toReturn <- robinhoodUser$account$positionsTable
  toReturn <- toReturn[toReturn$quantity == 0, ]
  return(rownames(toReturn))
}

#' Get your equity portfolio holdings with average prices.
#'
#' @param tickersOnly logical. If TRUE, returns character vector of ticker names currently held in your portfolio
get_equity_holdings <- function(tickersOnly=FALSE) {
  toReturn <- robinhoodUser$account$positionsTable
  toReturn <- toReturn[toReturn$quantity > 0, ]
  if(tickersOnly)
    return(rownames(toReturn))
  else
    return(list(table = toReturn[-1,], tickers = rownames(toReturn)))
}

##### Quotes and Historicals #####

#' Dowload one year of OHLCV daily data from robinhood
#'
#' @param symbols A character vector or list specifying the names of each symbol to download
robinhood_daily_historicals <- function(symbols){
  return(robinhoodUser$quotes$get_daily_historicals(symbols))
}

#' Dowload one week of OHLCV 5 minute intraday data from robinhood
#'
#' @param symbols A character vector or list specifying the names of each symbol to download
#' @param span A character string specifying the amount of data to retrieve (day or week)
robinhood_intraday_historicals <- function(symbols,span){
  return(robinhoodUser$quotes$get_intraday_historicals(symbols,span))
}

#' Download current quote data from robinhood
#'
#' @param symbols A character vector or list specifying the names of each symbol to download
robinhood_quotes <-function(symbols){
  return(robinhoodUser$quotes$get_quotes(symbols))
}

#' Get the last quotes for a symbol.
#'
#' @param symbols The shorthand symbols.
#' @param header Authentication header generated by instance of the R6 Login class. login$authHeader.
rh_quote<-function(ticker,header){

  url<-paste0("https://api.robinhood.com/quotes/",toupper(ticker),"/",sep="")
  res <- httr::GET(url, httr::add_headers(.headers=header))
  res<-as.numeric(content(res)$last_trade_price)
  return(res)
}

#' Get the historical quotes for a symbol.
#'
#' @param symbols The shorthand symbols.
#' @param interval The interval: week|day|10minute|5minute
#' @param span The span: day|week|year
#' @param bounds extended|regular|trading
#' @param keep_meta whether to keep meta data. Defaults to FALSE.
#' @param to_xts    whether to convert to xts. Defaults to TRUE.
#' @param account Initialized instance of the R6 Account class. Generated by Account$new(login).
rh_historicals <- function(symbols, interval = "day",
                           span = "year", bounds = "regular",
                           keep_meta = FALSE, to_xts = TRUE,account){

  # Get the data
  hist_list <- lapply(X = symbols,
                      function(x){rh_historicals_one(symbol = x,
                                                     interval = interval,
                                                     span = span,
                                                     bounds = bounds,account=account)})

  # Keep only the historical data
  if(!keep_meta){
    hist_list <- lapply(hist_list, function(x) x$historicals[[1]])
  }

  if(to_xts & !keep_meta){

    hist_list <- lapply(hist_list,
                        function(x){
                          x_converted <- xts::xts(x = x[, c("open_price", "close_price", "high_price", "low_price", "volume")],
                                                  order.by = x$begins_at)
                          attr(x_converted, "session") <- x$session
                          attr(x_converted, "interpolated") <- x$interpolated

                          x_converted
                        })
  }

  # name the list.
  names(hist_list) <- symbols

  hist_list
}

#' Historical data helper.
#'
#' @param symbol The shorthand symbols.
#' @param interval The interval: week|day|10minute|5minute
#' @param span The span: day|week|year
#' @param bounds extended|regular|trading
#' @param account Initialized instance of the R6 Account class. Generated by Account$new(login).
rh_historicals_one <- function(symbol, interval = interval, span = span, bounds = bounds,account=account){

  header=account$user$authHeader

  # Create the url
  #' Base url

  rh_base_url <- function(){

    httr::parse_url("https://api.robinhood.com")
  }
  rh_url <- rh_base_url()
  rh_url$path <- paste0("quotes/historicals/", symbol, "/")
  rh_url$query <- list(interval = interval,
                       span = span,
                       bounds = bounds)
  rh_url <- httr::build_url(rh_url)

  # GET the quotes
  quotes_rh <- httr::GET(url = rh_url,httr::add_headers(.headers=header))

  # Check the responce
  if (httr::http_error(quotes_rh)) {
    stop(
      httr::content(x = quotes_rh, as = "text", encoding = "UTF-8"),
      call. = FALSE)
  }

  # parse the content
  content_rh <- httr::content(x = quotes_rh, as = "text", encoding = "UTF-8")
  content_rh <- jsonlite::fromJSON(txt = content_rh)

  meta_rh <- as.data.frame(content_rh[1:6], stringsAsFactors = FALSE)

  hist_rh <- content_rh$historicals
  hist_rh$begins_at <- lubridate::ymd_hms(hist_rh$begins_at,
                                          tz = "UTC")
  hist_rh$open_price <- as.numeric(hist_rh$open_price)
  hist_rh$close_price <- as.numeric(hist_rh$close_price)
  hist_rh$high_price <- as.numeric(hist_rh$high_price)
  hist_rh$low_price <- as.numeric(hist_rh$low_price)

  meta_rh$historicals <- list(hist_rh)

  meta_rh
}

##### Charting #####

#' Build a plotly chart.
#'
#' @param tickerSymbol short hand ticker symbol
#' @param ohlcvData an xts object with OHLCV data
create_chart <- function(tickerSymbol=NULL, ohlcvData){
  source("Robinhood/BasicChartBuilder.R")
  return(BasicChartBuilder$new(ohlcvData=ohlcvData, tickerSymbol=tickerSymbol))
}
QuantumFuse/robinhoodQF documentation built on April 2, 2019, 12:50 a.m.