Google Sheets yahooFinance

yahooFinance() function for GoogleSheets
 avatar
unknown
javascript
6 months ago
6.6 kB
31
No Index
function getCredentials() {
  const cookie = UrlFetchApp.fetch("https://fc.yahoo.com/", {
    muteHttpExceptions: true,
  }).getHeaders()["Set-Cookie"];

  const crumb = UrlFetchApp.fetch("https://query2.finance.yahoo.com/v1/test/getcrumb", {
    muteHttpExceptions: true,
    headers: { cookie },
  }).getContentText();
  
  //Cache cookie and crumb for later use
  PropertiesService.getScriptProperties().setProperties({ cookie, crumb });
  return { cookie, crumb };
};

function yahooQuoteSummary(ticker, module, cookie, crumb){
  /* AVAILABLE MODULES (https://cryptocointracker.com/yahoo-finance/yahoo-finance-api)
    `assetProfile` - The assetProfile object contains general information about the company, such as industry, fullTimeEmployees, and website and is useful for getting an overview of the company's assets.

    `defaultKeyStatistics` - The defaultKeyStatistics object contains information about a company's stock. This is useful for getting an idea of a company's stock.

    `recommendationTrend` - recommendationTrend object contains information about analyst recommendations. This is useful for getting an idea of whether a stock is being bought or sold by analysts.

    `financialData` - The financialData object contains information about a company's financial situation. This is useful for getting an idea of a company's financial situation.

    `majorHoldersBreakdown` - The majorHoldersBreakdown object contains information about the top holders of a stock. This is useful for getting an idea of who is buying or selling a stock.

    `earnings` - The earnings object contains information about a company's earnings. This is useful for getting an idea of a company's profitability.

    `earningsHistory` - The earningsHistory object contains information about a company's earnings history. This is useful for getting an idea of a company's past profitability.

    `earningsTrend` - The earningsTrend object contains information about a company's earnings trend. This is useful for getting an idea of a company's current and future profitability.

    `indexTrend` - The indexTrend object contains information about the direction of a stock market index. This is useful for getting an idea of the overall direction of the market.

    `industryTrend` - The industryTrend object contains information about the direction of an industry. This is useful for getting an idea of the overall direction of an industry.

    `netSharePurchaseActivity` - The netSharePurchaseActivity object contains information about the net share purchase activity of a company. This is useful for getting an idea of the overall direction of a company's stock.

    `sectorTrend` -The sectorTrend object contains information about the direction of a stock market sector. This is useful for getting an idea of the overall direction of a particular stock market sector.

    `insiderHolders` - The insiderHolders object contains information about the insider holders of a company's stock. This is useful for getting an idea of who owns a company's stock.

    `upgradeDowngradeHistory` - The upgradeDowngradeHistory object contains information about the upgrades and downgrades that analysts have given a company's stock. This is useful for getting an idea of analyst opinion on a company's stock
  */

  const url = `https://query2.finance.yahoo.com/` + 
    `v10/finance/quoteSummary/${ticker}?modules=${module}&crumb=${crumb}`

  const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true, headers: {cookie}})
  return JSON.parse(res)["quoteSummary"] || {}
}

function yahooQuote(ticker, cookie, crumb){
  const url = `https://query1.finance.yahoo.com/v7/finance/quote?symbols=${ticker}&crumb=${crumb}`

  const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true, headers: {cookie}})
  return JSON.parse(res)["quoteResponse"] || {}
}

function yahooChart(ticker){
  const url = `https://query1.finance.yahoo.com/v8/finance/chart/${ticker}`

  const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true, headers: {cookie}})
  return JSON.parse(res) || {}
}

function yahooFinance(ticker, info, iterative=true){
  /**
   * Get asset info from Yahoo Finance APIs. (use period)
   *
   * For now it just accepts these infos:
   *  - `name`: the asset full name.
   *  - `price`: the asset current price.
   *  - `currency`: the asset currency on the given exchange.
   *  - `sector`: the asset specific sector. Works only stocks, not with ETFs.
   *  - `pe`: the asset trailing price/earnings ratio. Most ETFs don't have it.
   * 
   * @link https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
   *
   * @param {String}  ticker          The ticker for the asset to query.
   * @param {String}  info            The type of info to query. It must be lowercase
   * @param {Boolean} iterative=true  Used to avoid infinite recursion.
   *
   * @return Returns the given info data, or `false` if the data couldn't be retrieved.
   */

  // GET COOKIES
  const properties = PropertiesService.getScriptProperties().getProperties()
  const {cookie, crumb} = properties || getCredentials()

  if (!cookie||!crumb){
    const {cookie, crumb} = getCredentials()
  }

  // QUERY
  if (info == "sector"){
    var result = yahooQuoteSummary(ticker, "assetProfile", cookie, crumb)
  } else{
    var result = yahooQuote(ticker, cookie, crumb)
  }
  result = result["result"] || {}

  // CHECK FOR ERRORS
  if(!result.length){
    var found = false
    // TRY DIFFERENT EXCHANGES
    if (iterative){
      for (const ex of [".MI", ".DE"]) {
        result = yahooFinance(ticker+ex, info, iterative=false)        
        if (result){
          found = true
          return result
        }
      }
    }

    if (!found){
      return false
    }
  }


  // PASE RESULTS
  switch(info){
    case "sector":
      try{
        result = result[0]["assetProfile"]["sector"]
      } catch{
        return false
      }
      break;

    case "name":
      try{
        result = result[0]["longName"]
      } catch{
        return false
      }
      break;

    case "price":
      try{
        result = result[0]["regularMarketPrice"]
      } catch{
        return false
      }
      break;

    case "currency":
      try{
        result = result[0]["currency"]
      } catch{
        return false
      }
      break;

    case "pe":
      try{
        result = result[0]["trailingPE"]
      } catch{
        return false
      }
      break;

  }

  return result

}

function test(){
  var ticker = "IUS5"

  var result = yahooFinance(ticker, "price")
  console.log(result)
}
Editor is loading...