0

I am blown away by all of the jargon. I’m new to R, using it for a few months to get some quote info for my Excel portfolio as a VBA call to a Bert subroutine. My (stripped down) R steps are as follows:

    local({r <- getOption("repos")
        r["CRAN"] <- "https://cran.microsoft.com/snapshot/2022-05-05/"
        options(repos=r)
      })
    library (quantmod)
    library(jsonlite)

    ticker <- "COKE"
    metrics <- yahooQF(
      c("Trade Time", "Last Trade (Price Only)", "Change in Percent",
        "Days High", "Days Low",
        "Dividend/Share",   "Dividend Yield",
        "Ex-Dividend Date", "Dividend Pay Date",
        "Earnings/Share", "EPS Forward",
        "Earnings Start Time", "Earnings End Time",
        "P/E Ratio (RT)", 
        "Previous Close", "Open",
        "50-day Moving Average", "200-day Moving Average"))
     quot <- getQuote(ticker, what=metrics)

From which I get: Error in open.connection(con, “rb”) : HTTP error 401.

I know there have been several questions/suggestions about this, but being a novice I don’t see how to get around this problem (which I’m understanding is due to changes at Yahoo). Can anyone help out with actual code that I’ll understand and can integrate with mine to try to get around the getQuote problem.

Marvin
  • 1

2 Answers2

2

TLDR:

Update quantmod to a patched version

remotes::install_github("ethanbsmith/quantmod@382_add_session_getQuote")

DETAILED EXPLANATION:

I set the following breakpoints:

debugonce(getQuote)
debugonce(getQuote.yahoo)

In the getQuote.yahoo() I extracted the following URL which represents your request:

Browse[2]> URL
[1] "https://query1.finance.yahoo.com/v7/finance/quote?symbols=COKE&fields=regularMarketPrice,regularMarketChangePercent,regularMarketDayHigh,regularMarketDayLow,trailingAnnualDividendRate,trailingAnnualDividendYield,exDividendDate,dividendDate,epsTrailingTwelveMonths,epsForward,earningsTimestampStart,earningsTimestampEnd,regularMarketPreviousClose,regularMarketOpen,fiftyDayAverage,twoHundredDayAverage"

Visting this url results in the following json reponse:

{"finance":{"result":null,"error":{"code":"Unauthorized","description":"Invalid Crumb. For Developers - [...] "}}}

A little googling "yahoo finance invalid crumb" lead me to the following quantmod issue: https://github.com/joshuaulrich/quantmod/issues/382

> packageVersion('quantmod')
[1] ‘0.4.22’

As suggested in the issue I upgrade to the specified version of quantmod that contains a patch for the issue...

remotes::install_github("ethanbsmith/quantmod@382_add_session_getQuote")
packageVersion("quantmod")
[1] ‘0.4.22.1’
library (quantmod)
library(jsonlite)

ticker <- "COKE"
metrics <- yahooQF(
  c("Trade Time", "Last Trade (Price Only)", "Change in Percent",
    "Days High", "Days Low",
    "Dividend/Share",   "Dividend Yield",
    "Ex-Dividend Date", "Dividend Pay Date",
    "Earnings/Share", "EPS Forward",
    "Earnings Start Time", "Earnings End Time",
    "P/E Ratio (RT)", 
    "Previous Close", "Open",
    "50-day Moving Average", "200-day Moving Average"))
quot <- getQuote(ticker, what=metrics)
print(quot)
              Trade Time   Last   % Change   High     Low Dividend/Share Dividend Yield Ex-Dividend Date Dividend Pay Date Earnings/Share EPS Forward
COKE 2023-05-31 16:00:04 661.74 -0.9104275 670.49 658.445           1.25    0.001871762       1682553600        1683849600          48.35       38.94
     Earnings Start Time Earnings End Time P. Close   Open 50-day MA 200-day MA
COKE          1690801140        1691150400   667.82 667.14   582.332   511.4602

... and we're back in business!

br00t
  • 1,440
  • 8
  • 10
  • Thanks much for your suggestion. As mentioned, I am a COMPLETE novice, using BERT - Basic Excel R Toolkit, which allows me to run user-defined R functions from Excel. When I try to include the patch you suggested I get the message: " Error in loadNamespace(name) : there is no packaged named 'remotes'" Is 'remotes' a functionality that doesn't exist in BERT? If so, can I install the patch another way? – Marvin Jun 04 '23 at 16:41
0

Some of the answers to this question: Yahoo Finance API - GET quotes returns "Invalid Cookie" indicate that Yahoo! has disabled this API intentionally.

Based on that news, I've begun using Tiingo (https://www.tiingo.com/) which can provide most of the same data. Register and you will be assigned an API Key. The free level is fairly generous and there's a paid level ($30/mo) if you need more data/bandwidth.

Here's a script (R) you can use:

# define a function to get quotes from Tiingo
getQuotesTiingo <- function(tickers, apiKey) {
  url <- paste0("https://api.tiingo.com/iex/?token=", apiKey)
  url <- paste0(url, "&tickers=", paste(tickers, collapse = ","))
  jsonlite::fromJSON(curl::curl(url))
}

# set the ticker symbol array
ticks <- c("MSFT", "LRCX", "FERG", "AMP")

# provide your API Key
tiingoKey <- "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# get the quotes from Tiingo as a data.frame
getQuotesTiingo(ticks, tiingoKey)
pjheink
  • 306
  • 2
  • 5