From 52bc37e36ac581b479659c95cb357c8bef94b902 Mon Sep 17 00:00:00 2001 From: rsquaredin Date: Mon, 7 Aug 2023 20:03:49 +0530 Subject: [PATCH] fix: api changes --- DESCRIPTION | 3 +- NAMESPACE | 1 - NEWS.md | 6 +- R/index.R | 141 +- R/others.R | 241 ++- R/ticker.R | 1440 ++++------------- R/utils.R | 27 +- README.Rmd | 8 +- README.md | 59 +- _pkgdown.yml | 1 - cran-comments.md | 2 +- docs/404.html | 6 +- docs/CODE_OF_CONDUCT.html | 4 +- docs/LICENSE-text.html | 4 +- docs/LICENSE.html | 4 +- docs/authors.html | 8 +- .../bootstrap-5.2.2/bootstrap.bundle.min.js | 7 + .../bootstrap.bundle.min.js.map | 1 + docs/deps/bootstrap-5.2.2/bootstrap.min.css | 6 + docs/deps/data-deps.txt | 4 +- docs/index.html | 78 +- docs/news/index.html | 8 +- docs/pkgdown.yml | 4 +- docs/reference/Index-class.html | 385 ++++- docs/reference/Ticker-class.html | 766 ++++----- docs/reference/currency_converter.html | 48 +- docs/reference/get_currencies.html | 188 +-- docs/reference/get_market_summary.html | 898 +++++----- docs/reference/get_trending.html | 7 +- docs/reference/index.html | 9 +- docs/reference/validate.html | 4 +- docs/reference/yahoofinancer.html | 4 +- docs/search.json | 2 +- man/Index-class.Rd | 7 - man/Ticker-class.Rd | 207 --- man/currency_converter.Rd | 28 +- man/currency_summary.Rd | 25 - .../v8/finance/chart/aapl-01ad5e.json | 117 ++ .../v8/finance/chart/aapl-955a6a.json | 96 ++ tests/testthat/test-currency.R | 13 - tests/testthat/test-index.R | 23 +- tests/testthat/test-ticker.R | 713 +------- 42 files changed, 2070 insertions(+), 3533 deletions(-) create mode 100644 docs/deps/bootstrap-5.2.2/bootstrap.bundle.min.js create mode 100644 docs/deps/bootstrap-5.2.2/bootstrap.bundle.min.js.map create mode 100644 docs/deps/bootstrap-5.2.2/bootstrap.min.css delete mode 100644 man/currency_summary.Rd create mode 100644 tests/testthat/query2.finance.yahoo.com/v8/finance/chart/aapl-01ad5e.json create mode 100644 tests/testthat/query2.finance.yahoo.com/v8/finance/chart/aapl-955a6a.json diff --git a/DESCRIPTION b/DESCRIPTION index 12eee40..137f461 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: yahoofinancer Type: Package Title: Fetch Data from Yahoo Finance API -Version: 0.1.0.9000 +Version: 0.2.0 Authors@R: person("Aravind", "Hebbali", email = "hebbali.aravind@gmail.com", role = c("aut", "cre")) Description: Obtain historical and near real time data related to stocks, index and currencies from the Yahoo Finance API. This package is community maintained @@ -10,6 +10,7 @@ Description: Obtain historical and near real time data related to stocks, index Depends: R(>= 3.4) Imports: + curl, httr, jsonlite, lubridate, diff --git a/NAMESPACE b/NAMESPACE index d986360..ccec16b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -3,7 +3,6 @@ export(Index) export(Ticker) export(currency_converter) -export(currency_summary) export(get_currencies) export(get_market_summary) export(get_trending) diff --git a/NEWS.md b/NEWS.md index 49ac175..3023a4e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # yahoofinancer (development version) +# yahoofinancer 0.2.0 + +This is a minor release to fix bugs resulting from changes in Yahoo Finance API. + # yahoofinancer 0.1.0 -* Added a `NEWS.md` file to track changes to the package. +- Added a `NEWS.md` file to track changes to the package. diff --git a/R/index.R b/R/index.R index 65df7b7..5187016 100644 --- a/R/index.R +++ b/R/index.R @@ -1,15 +1,15 @@ #' R6 Class Representing a Ticker -#' -#' @description +#' +#' @description #' Base class for getting all data related to indices from Yahoo Finance API. -#' +#' #' @param index Index for which data has to be retrieved. -#' +#' #' @docType class #' @format An R6 class object #' @name Index-class -#' -#' @export +#' +#' @export Index <- R6::R6Class( "Index", @@ -29,7 +29,8 @@ Index <- R6::R6Class( if (validate(index)) { self$index <- index } else { - stop("Not a valid index.", call. = FALSE) + message("Not a valid index.") + return(invisible(NULL)) } }, @@ -43,11 +44,12 @@ Index <- R6::R6Class( if (validate(index)) { self$index <- index } else { - stop("Not a valid index.", call. = FALSE) + message("Not a valid index.") + return(invisible(NULL)) } }, - #' @description + #' @description #' Retrieves historical data #' @param period Length of time. Defaults to \code{'ytd'}. Valid values are: #' \itemize{ @@ -79,8 +81,8 @@ Index <- R6::R6Class( #' \item \code{'1mo'} #' \item \code{'3mo'} #' } - #' @param start Specific starting date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. - #' @param end Specific ending date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. + #' @param start Specific starting date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. + #' @param end Specific ending date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. #' @return A \code{data.frame}. #' @examples #' \donttest{ @@ -92,11 +94,11 @@ Index <- R6::R6Class( get_history = function(period = 'ytd', interval = '1d', start = NULL, end = NULL) { if (!is.null(start)) { - start_date <- as.numeric(as.POSIXct(ymd(start))) + start_date <- as.numeric(as.POSIXct(ymd(start, tz = "UTC"), tz = "UTC")) } if (!is.null(end)) { - end_date <- as.numeric(as.POSIXct(ymd(end))) + end_date <- as.numeric(as.POSIXct(ymd(end, tz = "UTC"), tz = "UTC")) } path <- 'v8/finance/chart/' @@ -106,75 +108,78 @@ Index <- R6::R6Class( if (!is.null(start) && !is.null(end)) { qlist <- list(period1 = start_date, period2 = end_date, interval = interval) } else if (!is.null(start) && is.null(end)) { - qlist <- list(period1 = start_date, period2 = round(as.numeric(as.POSIXct(now()))), interval = interval) + qlist <- list(period1 = start_date, period2 = round(as.numeric(as.POSIXct(now("UTC")))), interval = interval) } else { qlist <- list(range = period, interval = interval) } + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - data <- - parsed %>% - use_series(chart) %>% - use_series(result) %>% - extract2(1) - - indicators <- - data %>% - use_series(indicators) %>% - use_series(quote) %>% - extract2(1) - - result <- data.frame( - date = as_datetime(unlist(data$timestamp)), - volume = flatten_list(indicators$volume), - high = flatten_list(indicators$high), - low = flatten_list(indicators$low), - open = flatten_list(indicators$open), - close = flatten_list(indicators$close) - ) - - intervals <- c('1d', '5d', '1wk', '1mo', '3mo') - - if (interval %in% intervals) { - adj_close <- - data %>% - use_series(indicators) %>% - use_series(adjclose) %>% - extract2(1) %>% - use_series(adjclose) %>% - unlist() - result$adj_close <- adj_close + if (http_error(resp)) { - } + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) - result + return(invisible(NULL)) + } else { - } - ), + data <- + parsed %>% + use_series(chart) %>% + use_series(result) %>% + extract2(1) + + indicators <- + data %>% + use_series(indicators) %>% + use_series(quote) %>% + extract2(1) + + result <- data.frame( + date = as_datetime(unlist(data$timestamp)), + volume = flatten_list(indicators$volume), + high = flatten_list(indicators$high), + low = flatten_list(indicators$low), + open = flatten_list(indicators$open), + close = flatten_list(indicators$close) + ) + + intervals <- c('1d', '5d', '1wk', '1mo', '3mo') + + if (interval %in% intervals) { + adj_close <- + data %>% + use_series(indicators) %>% + use_series(adjclose) %>% + extract2(1) %>% + use_series(adjclose) %>% + unlist() + + result$adj_close <- adj_close + + } + + return(result) + } - active = list( - - #' @field summary_detail Contains information available via the Summary tab in Yahoo Finance - summary_detail = function() { - - path <- 'v7/finance/quote' - url <- modify_url(url = private$base_url, path = path) - qlist <- list(symbols = self$index) - resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - parsed %>% - use_series(quoteResponse) %>% - use_series(result) %>% - extract2(1) - } ), private = list( base_url = 'https://query2.finance.yahoo.com' ) -) \ No newline at end of file +) diff --git a/R/others.R b/R/others.R index d5e94e7..28b20bd 100644 --- a/R/others.R +++ b/R/others.R @@ -6,7 +6,7 @@ #' \donttest{ #' get_currencies() #' } -#' +#' #' @return Symbol, short and long name of the currencies. #' #' @export @@ -15,20 +15,45 @@ get_currencies <- function() { base_url <- 'https://query1.finance.yahoo.com' path <- 'v1/finance/currencies' url <- modify_url(url = base_url, path = path) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) - data <- - parsed %>% - use_series(currencies) %>% - use_series(result) - - data.frame( - short_name = map_chr(data, 'shortName'), - long_name = map_chr(data, 'longName'), - symbol = map_chr(data, 'symbol'), - local_long_name = map_chr(data, 'localLongName') - ) + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + data <- + parsed %>% + use_series(currencies) %>% + use_series(result) + + data.frame( + short_name = map_chr(data, 'shortName'), + long_name = map_chr(data, 'longName'), + symbol = map_chr(data, 'symbol'), + local_long_name = map_chr(data, 'localLongName') + ) + + } } @@ -37,7 +62,7 @@ get_currencies <- function() { #' Summary info of relevant exchanges for specific country. #' #' @param country Name of the country. -#' +#' #' @return A \code{data.frame}. #' #' @examples @@ -48,16 +73,42 @@ get_currencies <- function() { #' @export #' get_market_summary <- function(country = 'US') { + base_url <- 'https://query1.finance.yahoo.com' path <- 'v6/finance/quote/marketSummary' url <- modify_url(url = base_url, path = path) qlist <- list(region = country) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { - parsed %>% - use_series(marketSummaryResponse) %>% - use_series(result) + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + parsed %>% + use_series(marketSummaryResponse) %>% + use_series(result) + + } } #' Trending securities @@ -66,7 +117,7 @@ get_market_summary <- function(country = 'US') { #' #' @param country Name of the country. #' @param count Number of securities. -#' +#' #' @return Securities trending in the country. #' #' @examples @@ -77,26 +128,52 @@ get_market_summary <- function(country = 'US') { #' @export #' get_trending <- function(country = 'US', count = 10) { + base_url <- 'https://query1.finance.yahoo.com' path <- 'v1/finance/trending/' end_point <- paste0(path, country) url <- modify_url(url = base_url, path = end_point) qlist <- list(count = count) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) - data <- - parsed %>% - use_series(finance) %>% - use_series(result) + if (http_error(resp)) { - if (length(data) > 0) { - data %>% - extract2(1) %>% - use_series(quote) %>% - map_chr('symbol') + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) } else { - message('No trending securities.') + + data <- + parsed %>% + use_series(finance) %>% + use_series(result) + + if (length(data) > 0) { + data %>% + extract2(1) %>% + use_series(quote) %>% + map_chr('symbol') + } else { + message('No trending securities.') + } + } } @@ -107,34 +184,34 @@ get_trending <- function(country = 'US', count = 10) { #' #' @param from Currency to convert from. #' @param to Currency to convert to. -#' @param start Specific starting date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. -#' @param end Specific ending date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. +#' @param start Specific starting date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. +#' @param end Specific ending date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. #' @param period Length of time. Defaults to \code{'ytd'} Valid values are: -#' \itemize{ -#' \item \code{'1d'} -#' \item \code{'5d'} -#' \item \code{'1mo'} -#' \item \code{'3mo'} -#' \item \code{'6mo'} +#' \itemize{ +#' \item \code{'1d'} +#' \item \code{'5d'} +#' \item \code{'1mo'} +#' \item \code{'3mo'} +#' \item \code{'6mo'} #' \item \code{'1y'} #' \item \code{'2y'} -#' \item \code{'5y'} -#' \item \code{'10y'} -#' \item \code{'ytd'} +#' \item \code{'5y'} +#' \item \code{'10y'} +#' \item \code{'ytd'} #' \item \code{'max'} #' } #' @param interval Time between data points. Defaults to \code{'1d'} Valid values are: #' \itemize{ -#' \item \code{'1h'} -#' \item \code{'1d'} -#' \item \code{'5d'} -#' \item \code{'1wk'} -#' \item \code{'1mo'} +#' \item \code{'1h'} +#' \item \code{'1d'} +#' \item \code{'5d'} +#' \item \code{'1wk'} +#' \item \code{'1mo'} #' \item \code{'3mo'} #' } -#' +#' #' @return A \code{data.frame}. -#' +#' #' @examples #' \donttest{ #' currency_converter('GBP', 'USD', '2022-07-01', '2022-07-10') @@ -146,11 +223,11 @@ get_trending <- function(country = 'US', count = 10) { currency_converter <- function(from = 'EUR', to = 'USD', start = NULL, end = NULL, period = 'ytd', interval = '1d') { if (!is.null(start)) { - start_date <- as.numeric(as.POSIXct(ymd(start))) + start_date <- as.numeric(as.POSIXct(ymd(start, tz = "UTC"), tz = "UTC")) } if (!is.null(end)) { - end_date <- as.numeric(as.POSIXct(ymd(end))) + end_date <- as.numeric(as.POSIXct(ymd(end, tz = "UTC"), tz = "UTC")) } base_url <- 'https://query1.finance.yahoo.com' @@ -162,15 +239,35 @@ currency_converter <- function(from = 'EUR', to = 'USD', start = NULL, end = NUL if (!is.null(start) && !is.null(end)) { qlist <- list(period1 = start_date, period2 = end_date, interval = interval, corsDomain = cors_domain) } else if (!is.null(start) && is.null(end)) { - qlist <- list(period1 = start_date, period2 = round(as.numeric(as.POSIXct(now()))), interval = interval, corsDomain = cors_domain) + qlist <- list(period1 = start_date, period2 = round(as.numeric(as.POSIXct(now("UTC")))), interval = interval, corsDomain = cors_domain) } else { qlist <- list(range = period, interval = interval, corsDomain = cors_domain) } + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { - parsed + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { data <- parsed %>% @@ -208,42 +305,10 @@ currency_converter <- function(from = 'EUR', to = 'USD', start = NULL, end = NUL } - subset(result, !is.na(volume)) - -} + return(subset(result, !is.na(volume))) -#' Currency summary -#' -#' Contains information available via the Summary tab in Yahoo Finance. -#' -#' @param from Currency to convert from. -#' @param to Currency to convert to. -#' -#' @return A \code{list}. -#' -#' @examples -#' \donttest{ -#' currency_summary('GBP', 'USD') -#' } -#' -#' @export -#' -currency_summary <- function(from = 'USD', to = 'INR') { - - base_url <- 'https://query2.finance.yahoo.com' - path <- 'v7/finance/quote' - cors_domain <- 'finance.yahoo.com' - url <- modify_url(url = base_url, path = path) - qlist <- list(symbols = paste0(from, to, '=X'), corsDomain = cors_domain) - resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + } - parsed %>% - use_series(quoteResponse) %>% - use_series(result) %>% - extract2(1) } -flatten_list <- function(x) { - unlist(lapply(x, function(m) ifelse(is.null(m), NA, m))) -} \ No newline at end of file + diff --git a/R/ticker.R b/R/ticker.R index 0a8707a..f627f40 100644 --- a/R/ticker.R +++ b/R/ticker.R @@ -32,9 +32,10 @@ Ticker <- R6::R6Class( if (validate(symbol)) { self$symbol <- symbol } else { - stop("Not a valid symbol.", call. = FALSE) + message("Not a valid symbol.") + return(invisible(NULL)) } - + }, #' @description @@ -47,161 +48,12 @@ Ticker <- R6::R6Class( if (validate(symbol)) { self$symbol <- symbol } else { - stop("Not a valid symbol.", call. = FALSE) - } - }, - - #' @description - #' Retrieves balance sheet data for most recent four quarters or most recent four years. - #' @param frequency Annual or quarter. - #' @param clean_names Logical; if \code{TRUE}, converts column names to snake case. - #' @return A \code{tibble}. - #' @examples - #' \donttest{ - #' aapl <- Ticker$new('aapl') - #' aapl$get_balance_sheet('annual') - #' aapl$get_balance_sheet('quarter') - #' } - get_balance_sheet = function(frequency = c('annual', 'quarter'), clean_names = TRUE) { - - freq <- match.arg(frequency) - - if (freq == 'annual') { - module <- 'balanceSheetHistory' - } else { - module <- 'balanceSheetHistoryQuarterly' - } - - req <- private$resp_data(self$symbol, module) - - if (freq == 'annual') { - data <- - req %>% - private$display_data() %>% - use_series(balanceSheetHistory) - } else { - data <- - req %>% - private$display_data() %>% - use_series(balanceSheetHistoryQuarterly) - } - - balance_sheet <- - data %>% - use_series(balanceSheetStatements) %>% - map_depth(2, 'raw') %>% - map_dfr(extract) - - balance_sheet$endDate <- date(as_datetime(balance_sheet$endDate)) - - if (clean_names) { - names(balance_sheet) <- str_replace_all(names(balance_sheet), '[A-Z]', private$snake_case) - } - - balance_sheet - }, - - #' @description - #' Retrieves cash flow data for most recent four quarters or most recent four years. - #' @param frequency Annual or quarter. - #' @param clean_names Logical; if \code{TRUE}, converts column names to snake case. - #' @return A \code{tibble}. - #' @examples - #' \donttest{ - #' aapl <- Ticker$new('aapl') - #' aapl$get_cash_flow('annual') - #' aapl$get_cash_flow('quarter') - #' } - get_cash_flow = function(frequency = c('annual', 'quarter'), clean_names = TRUE) { - - freq <- match.arg(frequency) - - if (freq == 'annual') { - module <- 'cashflowStatementHistory' - } else { - module <- 'cashflowStatementHistoryQuarterly' - } - - req <- private$resp_data(self$symbol, module) - - if (freq == 'annual') { - data <- - req %>% - private$display_data() %>% - use_series(cashflowStatementHistory) - } else { - data <- - req %>% - private$display_data() %>% - use_series(cashflowStatementHistoryQuarterly) - } - - cash_flow <- - data %>% - use_series(cashflowStatements) %>% - map_depth(2, 'raw') %>% - map_dfr(extract) - - cash_flow$endDate <- date(as_datetime(cash_flow$endDate)) - - if (clean_names) { - names(cash_flow) <- str_replace_all(names(cash_flow), '[A-Z]', private$snake_case) + message("Not a valid symbol.") + return(invisible(NULL)) } - - cash_flow }, #' @description - #' Retrieves income statement data for most recent four quarters or most recent four years. - #' @param frequency Annual or quarter. - #' @param clean_names Logical; if \code{TRUE}, converts column names to snake case. - #' @return A \code{tibble}. - #' @examples - #' \donttest{ - #' aapl <- Ticker$new('aapl') - #' aapl$get_income_statement('annual') - #' aapl$get_income_statement('quarter') - #' } - get_income_statement = function(frequency = c('annual', 'quarter'), clean_names = TRUE) { - - freq <- match.arg(frequency) - - if (freq == 'annual') { - module <- 'incomeStatementHistory' - } else { - module <- 'incomeStatementHistoryQuarterly' - } - - req <- private$resp_data(self$symbol, module) - - if (freq == 'annual') { - data <- - req %>% - private$display_data() %>% - use_series(incomeStatementHistory) - } else { - data <- - req %>% - private$display_data() %>% - use_series(incomeStatementHistoryQuarterly) - } - - income_statement <- - data %>% - use_series(incomeStatementHistory) %>% - map_depth(2, 'raw') %>% - map_dfr(extract) - - income_statement$endDate <- date(as_datetime(income_statement$endDate)) - - if (clean_names) { - names(income_statement) <- str_replace_all(names(income_statement), '[A-Z]', private$snake_case) - } - - income_statement - }, - - #' @description #' Retrieves historical pricing data. #' @param period Length of time. Defaults to \code{'ytd'}. Valid values are: #' \itemize{ @@ -233,8 +85,8 @@ Ticker <- R6::R6Class( #' \item \code{'1mo'} #' \item \code{'3mo'} #' } - #' @param start Specific starting date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. - #' @param end Specific ending date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. + #' @param start Specific starting date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. + #' @param end Specific ending date. \code{String} or \code{date} object in \code{yyyy-mm-dd} format. #' @return A \code{data.frame}. #' @examples #' \donttest{ @@ -246,11 +98,11 @@ Ticker <- R6::R6Class( get_history = function(period = 'ytd', interval = '1d', start = NULL, end = NULL) { if (!is.null(start)) { - start_date <- as.numeric(as.POSIXct(ymd(start))) + start_date <- as.numeric(as.POSIXct(ymd(start, tz = "UTC"), tz = "UTC")) } if (!is.null(end)) { - end_date <- as.numeric(as.POSIXct(ymd(end))) + end_date <- as.numeric(as.POSIXct(ymd(end, tz = "UTC"), tz = "UTC")) } path <- 'v8/finance/chart/' @@ -260,822 +112,78 @@ Ticker <- R6::R6Class( if (!is.null(start) && !is.null(end)) { qlist <- list(period1 = start_date, period2 = end_date, interval = interval) } else if (!is.null(start) && is.null(end)) { - qlist <- list(period1 = start_date, period2 = round(as.numeric(as.POSIXct(now()))), interval = interval) + qlist <- list(period1 = start_date, period2 = round(as.numeric(as.POSIXct(now("UTC")))), interval = interval) } else { qlist <- list(range = period, interval = interval) } - resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - data <- - parsed %>% - use_series(chart) %>% - use_series(result) %>% - extract2(1) - - indicators <- - data %>% - use_series(indicators) %>% - use_series(quote) %>% - extract2(1) - - result <- data.frame( - date = as_datetime(unlist(data$timestamp)), - volume = unlist(indicators$volume), - high = unlist(indicators$high), - low = unlist(indicators$low), - open = unlist(indicators$open), - close = unlist(indicators$close) - ) - - intervals <- c('1d', '5d', '1wk', '1mo', '3mo') - - if (interval %in% intervals) { - adj_close <- - data %>% - use_series(indicators) %>% - use_series(adjclose) %>% - extract2(1) %>% - use_series(adjclose) %>% - unlist() - - result$adj_close <- adj_close - + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) } - result - - } - ), - - active = list( - - #' @field asset_profile Information related to the company's location, operations, and officers. - asset_profile = function() { - module <- 'assetProfile' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(assetProfile) - }, - - #' @field calendar_events Earnings and Revenue expectations for upcoming earnings date. - calendar_events = function() { - module <- 'calendarEvents' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(calendarEvents) - - earnings <- - data %>% - use_series(earnings) %>% - map('raw') - - earnings_date <- - data %>% - use_series(earnings) %>% - use_series(earningsDate) %>% - map_chr('fmt') - - ex_dividend_date <- - data %>% - use_series(exDividendDate) %>% - use_series('fmt') - - dividend_date <- - data %>% - use_series(dividendDate) %>% - use_series('fmt') - - earnings$earningsDate <- earnings_date - earnings$exDividendDate <- ex_dividend_date - earnings$dividendDate <- dividend_date - - earnings - - }, - - #' @field company_officers Retrieves top executives for given symbol and their total pay package. - company_officers = function() { - data <- - self$asset_profile %>% - use_series(companyOfficers) - - data.frame( - name = map_chr(data, 'name'), - age = map_int(data, 'age', .default = NA), - title = map_chr(data, 'title', .default = NA), - year_born = map_int(data, 'yearBorn', .default = NA), - fiscal_year = map_int(data, 'fiscalYear', .default = NA), - total_pay = map_dbl(map(data, 'totalPay'), 'raw', .default = NA), - exercised_value = map_dbl(map(data, 'exercisedValue'), 'raw', .default = NA), - unexercised_value = map_dbl(map(data, 'unexercisedValue'), 'raw', .default = NA) - ) - }, - - #' @field earnings_history Data related to historical earnings (actual vs. estimate) - earnings_history = function() { - - module <- 'earningsHistory' - req <- private$resp_data(self$symbol, module) - - data <- - private$display_data(req) %>% - use_series(earningsHistory) %>% - use_series(history) - - data.frame( - quarter = map_chr(map(data, 'quarter'), 'fmt', .default = NA), - period = map_chr(data, 'period', .default = NA), - eps_estimate = map_dbl(map(data, 'epsEstimate'), 'raw', .default = NA), - eps_actual = map_dbl(map(data, 'epsActual'), 'raw', .default = NA), - eps_difference = map_dbl(map(data, 'epsDifference'), 'raw', .default = NA), - surprise_percent = map_dbl(map(data, 'surprisePercent'), 'raw', .default = NA) - ) - }, - - #' @field earnings Historical earnings data. - earnings = function() { - - module <- 'earnings' - req <- private$resp_data(self$symbol, module) - - earnings <- - req %>% - private$display_data() %>% - use_series(earnings) - - estimate <- - earnings %>% - use_series(earningsChart) %>% - use_series(quarterly) - - earnings_estimate <- - data.frame( - date = map_chr(estimate, 'date'), - actual = map_dbl(map(estimate, 'actual'), 'raw', .default = NA), - estimate = map_dbl(map(estimate, 'estimate'), 'raw', .default = NA) - ) - - current_quarter <- list( - estimate = earnings$earningsChart$currentQuarterEstimate$raw, - estimate_date = earnings$earningsChart$currentQuarterEstimateDate, - estimate_year = earnings$earningsChart$currentQuarterEstimateYear - ) - - yearly <- - earnings %>% - use_series(financialsChart) %>% - use_series(yearly) - - yearly_estimate <- - data.frame( - date = map_chr(yearly, 'date'), - earnings = map_dbl(map(yearly, 'earnings'), 'raw', .default = NA), - revenue = map_dbl(map(yearly, 'revenue'), 'raw', .default = NA) - ) - - quarterly <- - earnings %>% - use_series(financialsChart) %>% - use_series(quarterly) - - quarterly_estimate <- - data.frame( - date = map_chr(quarterly, 'date'), - earnings = map_dbl(map(quarterly, 'earnings'), 'raw', .default = NA), - revenue = map_dbl(map(quarterly, 'revenue'), 'raw', .default = NA) - ) - - list( - earnings_estimate = earnings_estimate, - current_quarter = current_quarter, - yearly_earnings_revenue = yearly_estimate, - quarterly_earnings_revenue = quarterly_estimate - ) - }, - - #' @field earnings_trend Historical trend data for earnings and revenue estimations - earnings_trend = function() { - - module <- 'earningsTrend' - req <- private$resp_data(self$symbol, module) - - trend <- - req %>% - private$display_data() %>% - use_series(earningsTrend) %>% - use_series(trend) - - growth_data <- - data.frame( - date = map_chr(trend, 'endDate', .default = NA), - period = map_chr(trend, 'period', .default = NA), - growth = map_dbl(map(trend, 'growth'), 'raw', .default = NA) - ) - - earnings_data <- - data.frame( - date = map_chr(trend, 'endDate', .default = NA), - period = map_chr(trend, 'period', .default = NA), - analyst = map_int(map(map(trend, 'earningsEstimate'), 'numberOfAnalysts'), 'raw', .default = NA), - avg_estimate = map_dbl(map(map(trend, 'earningsEstimate'), 'avg'), 'raw', .default = NA), - low_estimate = map_dbl(map(map(trend, 'earningsEstimate'), 'low'), 'raw', .default = NA), - high_estimate = map_dbl(map(map(trend, 'earningsEstimate'), 'high'), 'raw', .default = NA), - year_ago_eps = map_dbl(map(map(trend, 'earningsEstimate'), 'yearAgoEps'), 'raw', .default = NA) - ) - - revenue_data <- - data.frame( - date = map_chr(trend, 'endDate', .default = NA), - period = map_chr(trend, 'period', .default = NA), - analyst = map_int(map(map(trend, 'revenueEstimate'), 'numberOfAnalysts'), 'raw', .default = NA), - avg_estimate = map_dbl(map(map(trend, 'revenueEstimate'), 'avg'), 'raw', .default = NA), - low_estimate = map_dbl(map(map(trend, 'revenueEstimate'), 'low'), 'raw', .default = NA), - high_estimate = map_dbl(map(map(trend, 'revenueEstimate'), 'high'), 'raw', .default = NA), - year_ago_revenue = map_dbl(map(map(trend, 'revenueEstimate'), 'yearAgoRevenue'), 'raw', .default = NA) - ) - - eps_trend <- - data.frame( - date = map_chr(trend, 'endDate', .default = NA), - period = map_chr(trend, 'period', .default = NA), - current = map_dbl(map(map(trend, 'epsTrend'), 'current'), 'raw', .default = NA), - seven_days_ago = map_dbl(map(map(trend, 'epsTrend'), '7daysAgo'), 'raw', .default = NA), - thirty_days_ago = map_dbl(map(map(trend, 'epsTrend'), '30daysAgo'), 'raw', .default = NA), - sixty_days_ago = map_dbl(map(map(trend, 'epsTrend'), '60daysAgo'), 'raw', .default = NA), - ninety_days_ago = map_dbl(map(map(trend, 'epsTrend'), '90daysAgo'), 'raw', .default = NA) - ) - - eps_revision <- - data.frame( - date = map_chr(trend, 'endDate', .default = NA), - period = map_chr(trend, 'period', .default = NA), - up_last_7_days = map_dbl(map(map(trend, 'epsRevisions'), 'upLast7days'), 'raw', .default = NA), - up_last_30_days = map_dbl(map(map(trend, 'epsRevisions'), 'upLast30days'), 'raw', .default = NA), - down_last_30_days = map_dbl(map(map(trend, 'epsRevisions'), 'downLast30days'), 'raw', .default = NA), - down_last_90_days = map_dbl(map(map(trend, 'epsRevisions'), 'downLast90days'), 'raw', .default = NA) - ) - - list( - growth = growth_data, - earnings_estimate = earnings_data, - revenue_estimate = revenue_data, - eps_trend = eps_trend, - eps_revision = eps_revision - ) - }, - - #' @field esg_scores Data related to environmental, social, and governance metrics - esg_scores = function() { - - module <- 'esgScores' - req <- private$resp_data(self$symbol, module) - req %>% - private$display_data() %>% - use_series(esgScores) - }, - - #' @field financial_data Financial key performance indicators - financial_data = function() { - - module <- 'financialData' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(financialData) - - fd <- map(data, 'raw') - fd$recommendationKey <- data$recommendationKey - fd$financialCurrency <- data$financialCurrency - fd - }, - - #' @field fund_bond_holdings Retrieves aggregated maturity and duration information for a given symbol - fund_bond_holdings = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(topHoldings) %>% - use_series(bondHoldings) %>% - compact() %>% - map_if(function(x) 'raw' %in% names(x), 'raw') - - }, - - #' @field fund_bond_ratings Retrieves aggregated maturity and duration information - fund_bond_ratings = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(topHoldings) %>% - use_series(bondRatings) %>% - map_depth(2, 'raw') %>% - unlist() %>% - as.list() - - }, - - #' @field fund_equity_holdings Fund equity holdings - fund_equity_holdings = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(topHoldings) %>% - use_series(equityHoldings) %>% - compact() %>% - map_if(function(x) 'raw' %in% names(x), 'raw') - - }, - - #' @field fund_holding_info Contains information for a funds top holdings, bond ratings, bond holdings, equity holdings, sector weightings, and category breakdown - fund_holding_info = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(topHoldings) + resp <- GET(url, query = qlist) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - holdings <- - data.frame( - symbol = map_chr(data$holdings, 'symbol'), - name = map_chr(data$holdings, 'holdingName'), - holding = map_dbl(map(data$holdings, 'holdingPercent'), 'raw') + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) ) - list( - cash_position = data$cashPosition$raw, - stock_position = data$stockPosition$raw, - bond_position = data$bondPosition$raw, - other_position = data$otherPosition$raw, - preferred_position = data$preferredPosition$raw, - convertible_position = data$convertiblePosition$raw, - holdings = holdings, - equity_holdings = map(data$equityHoldings, 'raw'), - bond_holdings = map(data$bondHoldings, 'raw'), - bond_ratings = map(flatten(data$bondRatings), 'raw'), - sector_weightings = map(flatten(data$sectorWeightings), 'raw') - ) - }, - - #' @field fund_ownership Top 10 owners of a given symbol - fund_ownership = function() { - - module <- 'fundOwnership' - req <- private$resp_data(self$symbol, module) - - data <- - private$display_data(req) %>% - use_series(fundOwnership) %>% - use_series(ownershipList) - - data.frame( - report_date = map_chr(map(data, 'reportDate'), 'fmt', .default = NA), - organization = map_chr(data, 'organization', .default = NA), - percent_held = map_dbl(map(data, 'pctHeld'), 'raw', .default = NA), - position = map_dbl(map(data, 'position'), 'raw', .default = NA), - value = map_dbl(map(data, 'value'), 'raw', .default = NA), - percent_change = map_dbl(map(data, 'pctChange'), 'raw', .default = NA) - ) - }, - - #' @field fund_performance Historical return data for a given symbol and its specific category - fund_performance = function() { - - module <- 'fundPerformance' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(fundPerformance) - - annual_total_returns <- data.frame( - year = map_chr(data$annualTotalReturns$returns, 'year', .default = NA), - returns = map_dbl(map(data$annualTotalReturns$returns, 'annualValue'), 'raw', .default = NA) - ) - - annual_total_returns_cat <- data.frame( - year = map_chr(data$annualTotalReturns$returnsCat, 'year', .default = NA), - returns = map_dbl(map(data$annualTotalReturns$returnsCat, 'annualValue'), 'raw', .default = NA) - ) - - quarterly_returns <- data$pastQuarterlyReturns$returns - - past_quarterly_returns <- data.frame( - year = map_chr(quarterly_returns, 'year', .default = NA), - q1 = map_dbl(map(quarterly_returns, 'q1'), 'raw', .default = NA), - q2 = map_dbl(map(quarterly_returns, 'q2'), 'raw', .default = NA), - q3 = map_dbl(map(quarterly_returns, 'q3'), 'raw', .default = NA), - q4 = map_dbl(map(quarterly_returns, 'q4'), 'raw', .default = NA) - ) - - risk_stats <- data$riskOverviewStatistics$riskStatistics - risk_statistics <- data.frame( - year = map_chr(risk_stats, 'year', .default = NA), - alpha = map_dbl(map(risk_stats, 'alpha'), 'raw', .default = NA), - beta = map_dbl(map(risk_stats, 'beta'), 'raw', .default = NA), - mean_annual_return = map_dbl(map(risk_stats, 'meanAnnualReturn'), 'raw', .default = NA), - rsquared = map_dbl(map(risk_stats, 'rSquared'), 'raw', .default = NA), - std_dev = map_dbl(map(risk_stats, 'stdDev'), 'raw', .default = NA), - sharpe_ratio = map_dbl(map(risk_stats, 'sharpeRatio'), 'raw', .default = NA), - treynor_ratio = map_dbl(map(risk_stats, 'treynorRatio'), 'raw', .default = NA) - ) - - risk_stats_cat <- data$riskOverviewStatisticsCat$riskStatisticsCat - risk_statistics_cat <- data.frame( - year = map_chr(risk_stats_cat, 'year', .default = NA), - alpha = map_dbl(map(risk_stats_cat, 'alpha'), 'raw', .default = NA), - beta = map_dbl(map(risk_stats_cat, 'beta'), 'raw', .default = NA), - mean_annual_return = map_dbl(map(risk_stats_cat, 'meanAnnualReturn'), 'raw', .default = NA), - rsquared = map_dbl(map(risk_stats_cat, 'rSquared'), 'raw', .default = NA), - std_dev = map_dbl(map(risk_stats_cat, 'stdDev'), 'raw', .default = NA), - sharpe_ratio = map_dbl(map(risk_stats_cat, 'sharpeRatio'), 'raw', .default = NA), - treynor_ratio = map_dbl(map(risk_stats_cat, 'treynorRatio'), 'raw', .default = NA) - ) - - - - list( - performance_overview = map(data$performanceOverview, 'raw'), - performance_overview_cat = map(data$performanceOverviewCat, 'raw'), - load_adjusted_returns = map(data$loadAdjustedReturns, 'raw'), - trailing_returns = map(data$trailingReturns, 'raw'), - trailing_returns_nav = map(data$trailingReturnsNav, 'raw'), - trailing_returns_cat = map(data$trailingReturnsCat, 'raw'), - annual_total_returns = annual_total_returns, - annual_total_returns_cat = annual_total_returns_cat, - past_quarterly_returns = past_quarterly_returns, - rank_in_category = map(data$rankInCategory, 'raw'), - risk_rating = data$riskOverviewStatistics$riskRating$raw, - risk_statistics = risk_statistics, - risk_statistics_cat = risk_statistics_cat - ) - }, - - #' @field fund_profile Summary level information for a given symbol - fund_profile = function() { - - module <- 'fundProfile' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(fundProfile) - - list( - family = data$family, - category_name = data$categoryName, - legal_type = data$legalType, - management_info = list( - manager_name = data$managementInfo$managerName, - manager_bio = data$managementInfo$managerBio, - start_date = data$managementInfo$startdate$fmt - ), - fees_expenses_investment = compact(map(data$feesExpensesInvestment, 'raw')), - fees_expenses_investment_cat = compact(map(data$feesExpensesInvestmentCat, 'raw')), - init_investment = data$initInvestment$raw, - init_ira_investment = data$initIraInvestment$raw, - subsequent_investment = data$subseqInvestment$raw, - brokerages = map_chr(data$brokerages, 1) - ) - - }, - - #' @field fund_section_weightings Retrieves aggregated sector weightings for a given symbol - fund_section_weightings = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(topHoldings) %>% - use_series(sectorWeightings) %>% - map_depth(2, 'raw') %>% - unlist() %>% - as.list() - }, - - #' @field fund_top_holdings Retrieves Top 10 holdings for a given symbol - fund_top_holdings = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(topHoldings) %>% - use_series(holdings) - - data.frame( - symbol = map_chr(data, 'symbol', .default = NA), - holding_name = map_chr(data, 'holdingName', .default = NA), - holding_percent = map_dbl(map(data, 'holdingPercent'), 'raw', .default = NA) - ) - }, - - #' @field fund_holdings Holding info for the given fund - fund_holdings = function() { - - module <- 'topHoldings' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(topHoldings) %>% - map_depth(1, 'raw') %>% - compact() - - }, - - #' @field grading_history Data related to upgrades / downgrades by companies - grading_history = function() { - - module <- 'upgradeDowngradeHistory' - req <- private$resp_data(self$symbol, module) - - data <- - req %>% - private$display_data() %>% - use_series(upgradeDowngradeHistory) %>% - use_series(history) - - data.frame( - date = date(as_datetime(map_int(data, 'epochGradeDate', .default = NA))), - firm = map_chr(data, 'firm', .default = NA), - to_grade = map_chr(data, 'toGrade', .default = NA), - from_grade = map_chr(data, 'fromGrade', .default = NA), - action = map_chr(data, 'action', .default = NA) - ) - }, - - #' @field index_trend Trend data related to given symbol's index, specificially PE and PEG ratios - index_trend = function() { - - module <- 'indexTrend' - req <- private$resp_data(self$symbol, module) - - resp <- - req %>% - private$display_data() %>% - use_series(indexTrend) + return(invisible(NULL)) + } else { - symbol <- resp$symbol - pe_ratio <- resp$peRatio$raw - peg_ratio <- resp$pegRatio$raw + data <- + parsed %>% + use_series(chart) %>% + use_series(result) %>% + extract2(1) - estimates <- - resp %>% - use_series(estimates) + indicators <- + data %>% + use_series(indicators) %>% + use_series(quote) %>% + extract2(1) - estimates_data <- - data.frame( - period = map_chr(estimates, 'period', .default = NA), - growth = map_dbl(map(estimates, 'growth'), 'raw', .default = NA) + result <- data.frame( + date = as_datetime(unlist(data$timestamp)), + volume = unlist(indicators$volume), + high = unlist(indicators$high), + low = unlist(indicators$low), + open = unlist(indicators$open), + close = unlist(indicators$close) ) - list( - symbol = symbol, - pe_ratio = pe_ratio, - peg_ratio = peg_ratio, - estimates = estimates_data - ) - - }, - - #' @field inside_holders Data related to stock holdings of a given symbol(s) insiders - inside_holders = function() { - - module <- 'insiderHolders' - req <- private$resp_data(self$symbol, module) - - resp <- - req %>% - private$display_data() %>% - use_series(insiderHolders) %>% - use_series(holders) - - data.frame( - name = map_chr(resp, 'name', .default = NA), - relation = map_chr(resp, 'relation', .default = NA), - url = map_chr(resp, 'url', .default = NA), - description = map_chr(resp, 'transactionDescription', .default = NA), - latest_transaction_date = map_chr(map(resp, 'latestTransDate'), 'fmt', .default = NA), - position_direct = map_dbl(map(resp, 'positionDirect'), 'raw', .default = NA), - position_direct_date = map_chr(map(resp, 'positionDirectDate'), 'fmt', .default = NA) - ) - - }, - - #' @field insider_transactions Transactions by insiders for a given symbol(s) - insider_transactions = function() { - - module <- 'insiderTransactions' - req <- private$resp_data(self$symbol, module) - - resp <- - req %>% - private$display_data() %>% - use_series(insiderTransactions) %>% - use_series(transactions) - - data.frame( - start_date = map_chr(map(resp, 'startDate'), 'fmt', .default = NA), - filer_name = map_chr(resp, 'filerName', .default = NA), - filer_relation = map_chr(resp, 'filerRelation', .default = NA), - transaction_text = map_chr(resp, 'transactionText', .default = NA), - ownership = map_chr(resp, 'ownership', .default = NA), - shares = map_chr(map(resp, 'shares'), 'raw', .default = NA), - value = map_chr(map(resp, 'value'), 'raw', .default = NA), - filer_url = map_chr(resp, 'filerUrl', .default = NA), - money_text = map_chr(resp, 'moneyText', .default = NA) - - ) - - }, - - #' @field institution_ownership Top 10 owners of a given symbol - institution_ownership = function() { - - module <- 'institutionOwnership' - req <- private$resp_data(self$symbol, module) - - resp <- - req %>% - private$display_data() %>% - use_series(institutionOwnership) %>% - use_series(ownershipList) - - data.frame( - date = map_chr(map(resp, 'reportDate'), 'fmt', .default = NA), - organization = map_chr(resp, 'organization', .default = NA), - percent_held = map_dbl(map(resp, 'percentHeld'), 'raw', .default = NA), - position = map_dbl(map(resp, 'position'), 'raw', .default = NA), - value = map_dbl(map(resp, 'value'), 'raw', .default = NA), - percent_change = map_dbl(map(resp, 'pctChange'), 'raw', .default = NA) - ) - - }, - - #' @field key_stats KPIs for given symbol - key_stats = function() { - - module <- 'defaultKeyStatistics' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(defaultKeyStatistics) %>% - compact() - }, - - #' @field major_holders Data showing breakdown of owners of given symbol(s), insiders, institutions, etc. - major_holders = function() { - - module <- 'majorHoldersBreakdown' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(majorHoldersBreakdown) %>% - map_at(-1, 'raw') - }, - - #' @field page_views Short, Mid, and Long-term trend data regarding a symbol's page views - page_views = function() { - - module <- 'pageViews' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(pageViews) - }, - - #' @field price Detailed pricing data for given symbol, exchange, quote type, currency, market cap, pre / post market data, etc. - price = function() { - - module <- 'price' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(price) %>% - map_at(c(2, 3, 5, 9, 10, 12:16, 19, 21, 42), 'raw') - }, - - #' @field quote_type Stock exchange specific data for given symbol - quote_type = function() { - - module <- 'quoteType' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(quoteType) - }, - - #' @field recommendation_trend Data related to historical recommendations (buy, hold, sell) for a given symbol - recommendation_trend = function() { - - module <- 'recommendationTrend' - req <- private$resp_data(self$symbol, module) - - resp <- - req %>% - private$display_data() %>% - use_series(recommendationTrend) %>% - use_series(trend) - - data.frame( - period = map_chr(resp, 'period', .default = NA), - strong_buy = map_int(resp, 'strongBuy', .default = NA), - buy = map_int(resp, 'buy', .default = NA), - hold = map_int(resp, 'hold', .default = NA), - sell = map_int(resp, 'sell', .default = NA), - strong_sell = map_int(resp, 'strongSell', .default = NA) - ) - - }, - - #' @field security_filings Historical SEC filings - security_filings = function() { - - module <- 'secFilings' - req <- private$resp_data(self$symbol, module) - - resp <- - req %>% - private$display_data() %>% - use_series(secFilings) %>% - use_series(filings) - - data.frame( - date = map_chr(resp, 'date', .default = NA), - type = map_chr(resp, 'type', .default = NA), - title = map_chr(resp, 'title', .default = NA), - edgar_url = map_chr(resp, 'edgarUrl', .default = NA) - ) - - }, - - #' @field share_purchase_activity High-level buy / sell data - share_purchase_activity = function() { + intervals <- c('1d', '5d', '1wk', '1mo', '3mo') - module <- 'netSharePurchaseActivity' - req <- private$resp_data(self$symbol, module) + if (interval %in% intervals) { + adj_close <- + data %>% + use_series(indicators) %>% + use_series(adjclose) %>% + extract2(1) %>% + use_series(adjclose) %>% + unlist() - req %>% - private$display_data() %>% - use_series(netSharePurchaseActivity) %>% - map_at(c(-1, -2), 'raw') - }, + result$adj_close <- adj_close - #' @field summary_detail Contains information available via the Summary tab in Yahoo Finance - summary_detail = function() { - - module <- 'summaryDetail' - req <- private$resp_data(self$symbol, module) - - req %>% - private$display_data() %>% - use_series(summaryDetail) %>% - compact() %>% - map_if(function(x) 'raw' %in% names(x), 'raw') - }, + } - #' @field summary_profile Return business summary of given symbol - summary_profile = function() { + return(result) + } - module <- 'summaryProfile' - req <- private$resp_data(self$symbol, module) + } + ), - req %>% - private$display_data() %>% - use_series(summaryProfile) - }, + active = list( #' @field valuation_measures Retrieves valuation measures for most recent four quarters valuation_measures = function() { @@ -1083,36 +191,59 @@ Ticker <- R6::R6Class( path <- 'ws/fundamentals-timeseries/v1/finance/timeseries/' end_point <- paste0(path, self$symbol) url <- modify_url(url = private$base_url, path = end_point) - + measure <- paste0('quarterly', c('MarketCap', 'EnterpriseValue', 'PeRatio', 'ForwardPeRatio', - 'PegRatio', 'PsRatio', 'PbRatio', 'EnterprisesValueRevenueRatio', - 'EnterprisesValueEBITDARatio'), collapse = ',') + 'PegRatio', 'PsRatio', 'PbRatio', 'EnterprisesValueRevenueRatio', + 'EnterprisesValueEBITDARatio'), collapse = ',') - qlist <- list(type = measure, - period1 = 493590046, + qlist <- list(type = measure, + period1 = 493590046, period2 = round(as.numeric(now())), corsDomain = private$cors_domain) + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - data <- - parsed %>% - use_series(timeseries) %>% - use_series(result) - - data.frame( - date = date(as_datetime(unlist(data[[1]]$timestamp))), - enterprise_value = private$extract_valuation(data, 'quarterlyEnterpriseValue'), - enterprise_value_ebitda_ratio = private$extract_valuation(data, 'quarterlyEnterprisesValueEBITDARatio'), - enterprise_value_revenue_ratio = private$extract_valuation(data, 'quarterlyEnterprisesValueRevenueRatio'), - forward_pe_ratio = private$extract_valuation(data, 'quarterlyForwardPeRatio'), - market_cap = private$extract_valuation(data, 'quarterlyMarketCap'), - pb_ratio = private$extract_valuation(data, 'quarterlyPbRatio'), - pe_ratio = private$extract_valuation(data, 'quarterlyPeRatio'), - peg_ratio = private$extract_valuation(data, 'quarterlyPegRatio'), - ps_ratio = private$extract_valuation(data, 'quarterlyPsRatio') - ) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + data <- + parsed %>% + use_series(timeseries) %>% + use_series(result) + + data.frame( + date = date(as_datetime(unlist(data[[1]]$timestamp))), + enterprise_value = private$extract_valuation(data, 'quarterlyEnterpriseValue'), + enterprise_value_ebitda_ratio = private$extract_valuation(data, 'quarterlyEnterprisesValueEBITDARatio'), + enterprise_value_revenue_ratio = private$extract_valuation(data, 'quarterlyEnterprisesValueRevenueRatio'), + forward_pe_ratio = private$extract_valuation(data, 'quarterlyForwardPeRatio'), + market_cap = private$extract_valuation(data, 'quarterlyMarketCap'), + pb_ratio = private$extract_valuation(data, 'quarterlyPbRatio'), + pe_ratio = private$extract_valuation(data, 'quarterlyPeRatio'), + peg_ratio = private$extract_valuation(data, 'quarterlyPegRatio'), + ps_ratio = private$extract_valuation(data, 'quarterlyPsRatio') + ) + } }, @@ -1123,38 +254,62 @@ Ticker <- R6::R6Class( end_point <- paste0(path, self$symbol) url <- modify_url(url = private$base_url, path = end_point) qlist <- list(getAllData = 'True', corsDomain = private$cors_domain) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - data <- - parsed %>% - use_series(optionChain) %>% - use_series(result) %>% - extract2(1) %>% - use_series(options) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) - calls <- - data %>% - map_dfr('calls') + return(invisible(NULL)) + } else { - calls$option_type <- 'call' + data <- + parsed %>% + use_series(optionChain) %>% + use_series(result) %>% + extract2(1) %>% + use_series(options) - puts <- - data %>% - map_dfr('puts') + calls <- + data %>% + map_dfr('calls') - puts$option_type <- 'put' + calls$option_type <- 'call' - result <- rbind(calls, puts) - names(result) <- str_replace_all(names(result), '[A-Z]', private$snake_case) + puts <- + data %>% + map_dfr('puts') + + puts$option_type <- 'put' + + result <- rbind(calls, puts) + names(result) <- str_replace_all(names(result), '[A-Z]', private$snake_case) - result$expiration <- as_datetime(result$expiration) - result$last_trade_date <- as_datetime(result$last_trade_date) + result$expiration <- as_datetime(result$expiration) + result$last_trade_date <- as_datetime(result$last_trade_date) - col_order <- c('expiration', 'option_type', 'contract_symbol', 'strike', 'currency', 'last_price', 'change', 'percent_change', 'open_interest', 'bid', 'ask', 'contract_size', 'last_trade_date', 'implied_volatility', 'in_the_money', 'volume') - - option_chain <- result[, col_order] - option_chain + col_order <- c('expiration', 'option_type', 'contract_symbol', 'strike', 'currency', 'last_price', 'change', 'percent_change', 'open_interest', 'bid', 'ask', 'contract_size', 'last_trade_date', 'implied_volatility', 'in_the_money', 'volume') + + option_chain <- result[, col_order] + return(option_chain) + } }, @@ -1165,17 +320,42 @@ Ticker <- R6::R6Class( end_point <- paste0(path, self$symbol) url <- modify_url(url = private$base_url, path = end_point) qlist <- list(getAllData = 'True', corsDomain = private$cors_domain) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - parsed %>% - use_series(optionChain) %>% - use_series(result) %>% - extract2(1) %>% - use_series(expirationDates) %>% - map_dbl(extract) %>% - as_datetime() %>% - date() + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + parsed %>% + use_series(optionChain) %>% + use_series(result) %>% + extract2(1) %>% + use_series(expirationDates) %>% + map_dbl(extract) %>% + as_datetime() %>% + date() + + } }, @@ -1186,15 +366,40 @@ Ticker <- R6::R6Class( end_point <- paste0(path, self$symbol) url <- modify_url(url = private$base_url, path = end_point) qlist <- list(getAllData = 'True', corsDomain = private$cors_domain) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - parsed %>% - use_series(optionChain) %>% - use_series(result) %>% - extract2(1) %>% - use_series(strikes) %>% - map_dbl(extract) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + parsed %>% + use_series(optionChain) %>% + use_series(result) %>% + extract2(1) %>% + use_series(strikes) %>% + map_dbl(extract) + + } }, @@ -1205,14 +410,39 @@ Ticker <- R6::R6Class( end_point <- paste0(path, self$symbol) url <- modify_url(url = private$base_url, path = end_point) qlist <- list(getAllData = 'True', corsDomain = private$cors_domain) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - parsed %>% - use_series(optionChain) %>% - use_series(result) %>% - extract2(1) %>% - use_series(quote) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + parsed %>% + use_series(optionChain) %>% + use_series(result) %>% + extract2(1) %>% + use_series(quote) + + } }, @@ -1223,20 +453,45 @@ Ticker <- R6::R6Class( end_point <- paste0(path, self$symbol) url <- modify_url(url = private$base_url, path = end_point) qlist <- list(corsDomain = private$cors_domain) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - data <- - parsed %>% - use_series(finance) %>% - use_series(result) %>% - extract2(1) %>% - use_series(recommendedSymbols) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { - data.frame( - symbol = map_chr(data, 'symbol'), - score = map_dbl(data, 'score') - ) + data <- + parsed %>% + use_series(finance) %>% + use_series(result) %>% + extract2(1) %>% + use_series(recommendedSymbols) + + data.frame( + symbol = map_chr(data, 'symbol'), + score = map_dbl(data, 'score') + ) + + } }, @@ -1246,65 +501,86 @@ Ticker <- R6::R6Class( path <- 'ws/insights/v2/finance/insights' url <- modify_url(url = private$base_url, path = path) qlist <- list(symbol = self$symbol, corsDomain = private$cors_domain) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - - parsed %>% - use_series(finance) %>% - use_series(result) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + simplifyVector = FALSE) + + if (http_error(resp)) { + + message( + cat( + "Yahoo Finance API request failed", '\n', + paste('Status:', status_code(resp)), '\n', + paste('Type:', http_status(resp)$category), '\n', + paste('Mesage:', parsed$quoteSummary$error$code), '\n', + paste('Description:', parsed$quoteSummary$error$description, '\n'), + sep = '' + ) + ) + + return(invisible(NULL)) + } else { + + parsed %>% + use_series(finance) %>% + use_series(result) + + } } ), private = list( - base_url = 'https://query1.finance.yahoo.com', + base_url = 'https://query2.finance.yahoo.com', path = 'v10/finance/quoteSummary/', cors_domain = 'finance.yahoo.com', - resp_data = function(symbol, module) { - end_point <- paste0(private$path, symbol) - url <- modify_url(url = private$base_url, path = end_point) - qlist <- list(modules = module, corsDomain = private$cors_domain) - resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) - list(resp = resp, parsed = parsed) - }, - - parse_data = function(parsed) { - parsed %>% - use_series(quoteSummary) %>% - use_series(result) %>% - extract2(1) - }, - - display_error = function(resp, parsed) { - cat( - "Yahoo Finance API request failed", '\n', - paste('Status:', status_code(resp)), '\n', - paste('Type:', http_status(resp)$category), '\n', - paste('Mesage:', parsed$quoteSummary$error$code), '\n', - paste('Description:', parsed$quoteSummary$error$description, '\n'), - sep = '' - ) - }, - - display_data = function(req) { - if (http_error(req$resp)) { - stop(private$display_error(req$resp, req$parsed), call. = FALSE) - } else { - private$parse_data(req$parsed) - } - }, + # resp_data = function(symbol, module) { + # end_point <- paste0(private$path, symbol) + # url <- modify_url(url = private$base_url, path = end_point) + # qlist <- list(modules = module, corsDomain = private$cors_domain) + # resp <- GET(url, query = qlist) + # parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + # list(resp = resp, parsed = parsed) + # }, + + # parse_data = function(parsed) { + # parsed %>% + # use_series(quoteSummary) %>% + # use_series(result) %>% + # extract2(1) + # }, + + # display_error = function(resp, parsed) { + # cat( + # "Yahoo Finance API request failed", '\n', + # paste('Status:', status_code(resp)), '\n', + # paste('Type:', http_status(resp)$category), '\n', + # paste('Mesage:', parsed$quoteSummary$error$code), '\n', + # paste('Description:', parsed$quoteSummary$error$description, '\n'), + # sep = '' + # ) + # }, + + # display_data = function(req) { + # private$parse_data(req$parsed) + # }, snake_case = function(x) { paste0('_', tolower(x)) }, extract_valuation = function(data, measure) { - data %>% - map_if(function(x) 'quarterlyEnterpriseValue' %in% names(x), 'quarterlyEnterpriseValue') %>% - map_depth(2, 'reportedValue') %>% - map_depth(2, 'raw') %>% + data %>% + map_if(function(x) 'quarterlyEnterpriseValue' %in% names(x), 'quarterlyEnterpriseValue') %>% + map_depth(2, 'reportedValue') %>% + map_depth(2, 'raw') %>% unlist() } ) diff --git a/R/utils.R b/R/utils.R index f37758b..2e9f27e 100644 --- a/R/utils.R +++ b/R/utils.R @@ -13,15 +13,21 @@ validate <- function(symbol = NULL) { base_url <- 'https://query2.finance.yahoo.com' - path <- 'v6/finance/quote/validate' - url <- modify_url(url = base_url, path = path) - qlist <- list(symbols = symbol) - resp <- GET(url, query = qlist) - parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), + path <- 'v6/finance/quote/validate' + url <- modify_url(url = base_url, path = path) + qlist <- list(symbols = symbol) + + if (!curl::has_internet()) { + message("No internet connection.") + return(invisible(NULL)) + } + + resp <- GET(url, query = qlist) + parsed <- fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) if (http_error(resp)) { - stop( + message( cat( "Yahoo Finance API request failed", '\n', paste('Status:', status_code(resp)), '\n', @@ -29,8 +35,9 @@ validate <- function(symbol = NULL) { paste('Mesage:', parsed$quoteSummary$error$code), '\n', paste('Description:', parsed$quoteSummary$error$description, '\n'), sep = '' - ), - call. = FALSE) + ) + ) + return(invisible(NULL)) } else { parsed %>% use_series(symbolsValidation) %>% @@ -40,3 +47,7 @@ validate <- function(symbol = NULL) { } } + +flatten_list <- function(x) { + unlist(lapply(x, function(m) ifelse(is.null(m), NA, m))) +} diff --git a/README.Rmd b/README.Rmd index d32c84b..88f757e 100644 --- a/README.Rmd +++ b/README.Rmd @@ -17,7 +17,7 @@ knitr::opts_chunk$set( [![CRAN status](https://www.r-pkg.org/badges/version/yahoofinancer)](https://CRAN.R-project.org/package=yahoofinancer) -[![cran checks](https://cranchecks.info/badges/summary/yahoofinancer)](https://cran.r-project.org/web/checks/check_results_yahoofinancer.html) +[![cran checks](https://badges.cranchecks.info/summary/yahoofinancer.svg)](https://cran.r-project.org/web/checks/check_results_yahoofinancer.html) [![R-CMD-check](https://github.com/rsquaredacademy/yahoofinancer/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/rsquaredacademy/yahoofinancer/actions/workflows/R-CMD-check.yaml) [![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) [![Codecov test coverage](https://codecov.io/gh/rsquaredacademy/yahoofinancer/branch/master/graph/badge.svg)](https://app.codecov.io/gh/rsquaredacademy/yahoofinancer?branch=master) @@ -50,7 +50,7 @@ To retrieve data from Yahoo Finance for a single stock, create an instance of th aapl <- Ticker$new('aapl') # get historical market data -aapl$get_history(start = '2022-09-01', interval = '1d') +aapl$get_history(start = '2023-08-01', interval = '1d') ``` ### Index @@ -61,13 +61,13 @@ To retrieve data from Yahoo Finance for an index, create an instance of the `Ind nifty_50 <- Index$new('^NSEI') # get historical data -nifty_50$get_history(start = '2022-09-01', interval = '1d') +nifty_50$get_history(start = '2023-08-01', interval = '1d') ``` ### Currency ```{r currency} -currency_converter('GBP', 'USD', '2022-09-01', '2022-09-10') +currency_converter('GBP', 'USD', '2023-08-01', '2023-08-04') ``` ## IMPORTANT LEGAL DISCLAIMER diff --git a/README.md b/README.md index c3258ec..bd3fac6 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ [![CRAN status](https://www.r-pkg.org/badges/version/yahoofinancer)](https://CRAN.R-project.org/package=yahoofinancer) [![cran -checks](https://cranchecks.info/badges/summary/yahoofinancer)](https://cran.r-project.org/web/checks/check_results_yahoofinancer.html) +checks](https://badges.cranchecks.info/summary/yahoofinancer.svg)](https://cran.r-project.org/web/checks/check_results_yahoofinancer.html) [![R-CMD-check](https://github.com/rsquaredacademy/yahoofinancer/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/rsquaredacademy/yahoofinancer/actions/workflows/R-CMD-check.yaml) [![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) @@ -42,20 +42,13 @@ an argument: aapl <- Ticker$new('aapl') # get historical market data -aapl$get_history(start = '2022-09-01', interval = '1d') -#> date volume high low open close adj_close -#> 1 2022-09-01 13:30:00 74229900 158.42 154.67 156.64 157.96 157.96 -#> 2 2022-09-02 13:30:00 76905200 160.36 154.97 159.75 155.81 155.81 -#> 3 2022-09-06 13:30:00 73714800 157.09 153.69 156.47 154.53 154.53 -#> 4 2022-09-07 13:30:00 87449600 156.67 153.61 154.82 155.96 155.96 -#> 5 2022-09-08 13:30:00 84923800 156.36 152.68 154.64 154.46 154.46 -#> 6 2022-09-09 13:30:00 68028800 157.82 154.75 155.47 157.37 157.37 -#> 7 2022-09-12 13:30:00 104956000 164.26 159.30 159.59 163.43 163.43 -#> 8 2022-09-13 13:30:00 122656600 160.54 153.37 159.90 153.84 153.84 -#> 9 2022-09-14 13:30:00 87965400 157.10 153.61 154.79 155.31 155.31 -#> 10 2022-09-15 13:30:00 90481100 155.24 151.38 154.65 152.37 152.37 -#> 11 2022-09-16 13:30:00 162157000 151.35 148.37 151.21 150.70 150.70 -#> 12 2022-09-19 13:30:00 81328800 154.56 149.10 149.31 154.48 154.48 +aapl$get_history(start = '2023-08-01', interval = '1d') +#> date volume high low open close adj_close +#> 1 2023-08-01 13:30:00 35175100 196.73 195.28 196.24 195.61 195.61 +#> 2 2023-08-02 13:30:00 50389300 195.18 191.85 195.04 192.58 192.58 +#> 3 2023-08-03 13:30:00 61235200 192.37 190.69 191.57 191.17 191.17 +#> 4 2023-08-04 13:30:00 115799700 187.38 181.92 185.52 181.99 181.99 +#> 5 2023-08-07 13:50:28 19412704 183.13 178.80 182.13 178.93 178.93 ``` ### Index @@ -67,36 +60,24 @@ the `Index` class by passing the index symbol as an argument: nifty_50 <- Index$new('^NSEI') # get historical data -nifty_50$get_history(start = '2022-09-01', interval = '1d') -#> date volume high low open close adj_close -#> 1 2022-09-01 03:45:00 308500 17695.60 17468.45 17485.70 17542.80 17542.80 -#> 2 2022-09-02 03:45:00 256300 17643.85 17476.45 17598.40 17539.45 17539.45 -#> 3 2022-09-05 03:45:00 230300 17683.15 17540.35 17546.45 17665.80 17665.80 -#> 4 2022-09-06 03:45:00 251200 17764.65 17587.65 17695.70 17655.60 17655.60 -#> 5 2022-09-07 03:45:00 354100 17650.75 17484.30 17519.40 17624.40 17624.40 -#> 6 2022-09-08 03:45:00 279800 17807.65 17691.95 17748.15 17798.75 17798.75 -#> 7 2022-09-09 03:45:00 270300 17925.95 17786.00 17923.35 17833.35 17833.35 -#> 8 2022-09-12 03:45:00 228200 17980.55 17889.15 17890.85 17936.35 17936.35 -#> 9 2022-09-13 03:45:00 259900 18088.30 18015.45 18044.45 18070.05 18070.05 -#> 10 2022-09-14 03:45:00 365900 18091.55 17771.15 17771.15 18003.75 18003.75 -#> 11 2022-09-15 03:45:00 289600 18096.15 17861.50 18046.35 17877.40 17877.40 -#> 12 2022-09-16 03:45:00 468500 17820.05 17497.25 17796.80 17530.85 17530.85 -#> 13 2022-09-19 03:45:00 258300 17667.20 17429.70 17540.65 17622.25 17622.25 -#> 14 2022-09-20 06:06:23 0 17879.65 17744.40 17770.40 17858.05 17858.05 +nifty_50$get_history(start = '2023-08-01', interval = '1d') +#> date volume high low open close adj_close +#> 1 2023-08-01 03:45:00 298000 19795.60 19704.60 19784.00 19733.55 19733.55 +#> 2 2023-08-02 03:45:00 290700 19678.25 19423.55 19655.40 19526.55 19526.55 +#> 3 2023-08-03 03:45:00 315700 19537.65 19296.45 19463.75 19381.65 19381.65 +#> 4 2023-08-04 03:45:00 280800 19538.85 19436.45 19462.80 19517.00 19517.00 +#> 5 2023-08-07 10:01:48 0 19620.45 19524.80 19576.85 19597.30 19597.30 ``` ### Currency ``` r -currency_converter('GBP', 'USD', '2022-09-01', '2022-09-10') +currency_converter('GBP', 'USD', '2023-08-01', '2023-08-04') #> date high low open close volume adj_close -#> 1 2022-08-31 23:00:00 1.161710 1.150324 1.159689 1.159851 0 1.159851 -#> 2 2022-09-01 23:00:00 1.158856 1.153136 1.154734 1.154894 0 1.154894 -#> 3 2022-09-04 23:00:00 1.152074 1.144518 1.147855 1.147460 0 1.147460 -#> 4 2022-09-05 23:00:00 1.160766 1.149624 1.156885 1.156644 0 1.156644 -#> 5 2022-09-06 23:00:00 1.152366 1.140953 1.151278 1.151185 0 1.151185 -#> 6 2022-09-07 23:00:00 1.156016 1.146158 1.152246 1.151981 0 1.151981 -#> 7 2022-09-08 23:00:00 1.164863 1.151662 1.152047 1.152160 0 1.152160 +#> 1 2023-07-31 23:00:00 1.283862 1.274161 1.283203 1.283401 0 1.283401 +#> 2 2023-08-01 23:00:00 1.279738 1.268183 1.279116 1.279574 0 1.279574 +#> 3 2023-08-02 23:00:00 1.272848 1.262594 1.271763 1.272038 0 1.272038 +#> 4 2023-08-03 23:00:00 1.278266 1.269164 1.271617 1.271634 0 1.271634 ``` ## IMPORTANT LEGAL DISCLAIMER diff --git a/_pkgdown.yml b/_pkgdown.yml index 2e84610..7f20ac1 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -54,7 +54,6 @@ reference: contents: - get_currencies - currency_converter - - currency_summary - title: Others diff --git a/cran-comments.md b/cran-comments.md index 858617d..fe982f6 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -2,4 +2,4 @@ 0 errors | 0 warnings | 1 note -* This is a new release. +There was 1 note about possibly invlalid URL. diff --git a/docs/404.html b/docs/404.html index 510d28d..d0a09c4 100644 --- a/docs/404.html +++ b/docs/404.html @@ -7,8 +7,8 @@ Page not found (404) • yahoofinancer - - + + Contributor Covenant Code of Conduct • yahoofinancerContributor Covenant Code of Conduct • yahoofinancer @@ -10,7 +10,7 @@ yahoofinancer - 0.1.0.9000 + 0.2.0