R/fundamental.R

Defines functions fundamental

Documented in fundamental

#' Get Fundamental Data
#'
#' Fetches fundamental data for a specified stock symbol and range of dates,
#' and for specified accounting quarter(s), using the Limex API. Authentication
#' is done via an API token stored in an environment variable 'LIMEX_API_TOKEN'.
#'
#' @param symbol The stock symbol for which fundamental data is requested.
#' @param from The start date for the data retrieval in 'YYYY-MM-DD' format.
#' @param to The end date for the data retrieval in 'YYYY-MM-DD' format.
#' @param quarter Optional; specify the quarter and year 'Q1-2023', 'Q2-2023', 'Q1-2024'... for quarterly data.
#' @param fields Optional; specify particular fields of interest like 'roe'.
#' @return A data frame containing the requested fundamental data if successful, NULL otherwise.
#' @import jsonlite
#' @import httr
#' @examples
#' \dontrun{
#'   company_fundamental <- fundamental(symbol = "AAPL")
#'   universe <- fundamental(fields = 'pe-ratio',quarter = 'Q2-2023')
#'   hist_data <- fundamental(symbol = "AAPL",fields = 'pe-ratio')
#' }
#' @export
fundamental <- function(symbol=NULL, from = "2010-01-01", to = Sys.Date(), quarter = NULL, fields = NULL) {
  # Retrieve the API token from the environment variable
  token <- Sys.getenv('LIMEX_API_TOKEN')
  old <- options()
  on.exit(options(old))
  options(timeout=300)
  if (token == "") {
    stop("API token is not set. Use set_limex_token() to set it before making API calls.")
  }

  # Construct the URL with the provided parameters
  base_url <- 'https://hub.limex.com/v1/fundamental/'
  url_params <- list(token = token, from = as.character(from), to = as.character(to))

  if (!is.null(symbol)) {
    url_params$symbol <- symbol
  }
  if (!is.null(quarter)) {
    url_params$quarter <- quarter
  }
  if (!is.null(fields)) {
    url_params$fields <- fields
  }

  # Build the query URL
  url <- paste0(base_url, '?',
                      paste0(names(url_params), '=', url_params, collapse = '&'))

  # Use tryCatch to handle errors
  data <- tryCatch({
    response <- fromJSON(url, simplifyMatrix = TRUE)
    data = data.table(response)
    setkey(data,date)
    return(data)
  }, error = function(e) {
    message("An error occurred: ", e$message)
    return(NULL)
  })

  return(data)
}

Try the limexhub package in your browser

Any scripts or data that you put into this service are public.

limexhub documentation built on June 22, 2024, 6:58 p.m.