Quantcast
Channel: ListenData
Viewing all articles
Browse latest Browse all 425

How to Import Dividend Data into Google Sheets

$
0
0

In this post, we will discuss how to pull stock dividend information into Google Sheets for free.

In Google Sheets, we can use the GOOGLEFINANCE function to get stock prices but for detailed dividend information (dividend yield or history), we will need to use external data sources like Yahoo Finance. We can use Google Apps Script to automate pulling data from Yahoo Finance and filling it into Google Sheets.

How to Use the File : First make a copy by selecting File > Make a copy. While running the script, Google will ask you to authorize Appscript once.

We will import the following data from YahooFinance into Google Sheets.

  1. Historical Dividend Data
  2. Forward Annual Dividend Rate
  3. Forward Annual Dividend Yield
  4. 5 Year Average Dividend Yield
  5. Trailing Annual Dividend Rate
  6. Trailing Annual Dividend Yield
  7. Payout Ratio
  8. Ex-Dividend Date
Import Dividend Data into Google Sheets

Historical Dividend Data

It includes information about dividends that a company has paid out to its shareholders between two specific period of time. The end date argument is not included in the range.

Once you click on the Get Historical Data button, dividend data will be fetched from yahoo finance and will appear in the "HistoricalData" sheet tab.
Historical Dividend Data in Google Sheets

This google sheet tool gets dividend information for hundreds of thousands of stocks from 48 countries. Make sure to use the correct ticker format from Yahoo Finance. For US stocks, just enter the ticker symbols but for stocks outside the US, you will need to add a suffix as shown in the table below.

Example : The ticker for LVMH is MC. So we need to input MC.PA as 'PA' refers to the exchange in france.
MarketExchangeSuffix
ArgentinaBuenos Aires Stock Exchange (BYMA).BA
AustriaVienna Stock Exchange.VI
AustraliaAustralian Stock Exchange (ASX).AX
BelgiumEuronext Brussels.BR
BrazilSao Paolo Stock Exchange (BOVESPA).SA
CanadaCanadian Securities Exchange.CN
CanadaNEO Exchange.NE
CanadaToronto Stock Exchange (TSX).TO
CanadaTSX Venture Exchange (TSXV).V
ChileSantiago Stock Exchange.SN
ChinaShanghai Stock Exchange.SS
ChinaShenzhen Stock Exchange.SZ
Czech RepublicPrague Stock Exchange Index.PR
DenmarkNasdaq OMX Copenhagen.CO
EgyptEgyptian Exchange Index (EGID).CA
EstoniaNasdaq OMX Tallinn.TL
EuropeEuronext.NX
FinlandNasdaq OMX Helsinki.HE
FranceEuronext Paris.PA
GermanyBerlin Stock Exchange.BE
GermanyBremen Stock Exchange.BM
GermanyDusseldorf Stock Exchange.DU
GermanyFrankfurt Stock Exchange.F
GermanyHamburg Stock Exchange.HM
GermanyHanover Stock Exchange.HA
GermanyMunich Stock Exchange.MU
GermanyStuttgart Stock Exchange.SG
GermanyDeutsche Boerse XETRA.DE
GreeceAthens Stock Exchange (ATHEX).AT
Hong KongHong Kong Stock Exchange (HKEX)***.HK
HungaryBudapest Stock Exchange.BD
IcelandNasdaq OMX Iceland.IC
IndiaBombay Stock Exchange.BO
IndiaNational Stock Exchange of India.NS
IndonesiaIndonesia Stock Exchange (IDX).JK
IrelandEuronext Dublin.IR
IsraelTel Aviv Stock Exchange.TA
ItalyEuroTLX.TI
ItalyItalian Stock Exchange.MI
JapanTokyo Stock Exchange.T
LatviaNasdaq OMX Riga.RG
LithuaniaNasdaq OMX Vilnius.VS
MalaysiaMalaysian Stock Exchange.KL
MexicoMexico Stock Exchange (BMV).MX
NetherlandsEuronext Amsterdam.AS
New ZealandNew Zealand Stock Exchange (NZX).NZ
NorwayOslo Stock Exchange.OL
PortugalEuronext Lisbon.LS
QatarQatar Stock Exchange.QA
RussiaMoscow Exchange (MOEX).ME
SingaporeSingapore Stock Exchange (SGX).SI
South AfricaJohannesburg Stock Exchange.JO
South KoreaKorea Stock Exchange.KS
South KoreaKOSDAQ.KQ
SpainMadrid SE C.A.T.S..MC
Saudi ArabiaSaudi Stock Exchange (Tadawul).SAU
SwedenNasdaq OMX Stockholm.ST
SwitzerlandSwiss Exchange (SIX).SW
TaiwanTaiwan OTC Exchange.TWO
TaiwanTaiwan Stock Exchange (TWSE).TW
ThailandStock Exchange of Thailand (SET).BK
TurkeyBorsa İstanbul.IS
United KingdomLondon Stock Exchange.L
VenezuelaCaracas Stock Exchange.CR

Note : The macro returns NA if no data is found on Yahoo Finance.

Key Dividend Statistics

Key statistics related to dividends are downloaded from Yahoo Finance when you click on the "Get Key Dividend Metrics" button in Google Sheets.

Key Dividend Statistics in Google Sheets
Google Apps Script

The following Google Apps Script is used to import historical dividend data from Yahoo Finance into Google Sheets.


function getData() {
  var inputControls = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inputs");
  var outputData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HistoricalData");
  
  var lastRow = inputControls.getLastRow();
  
  // Arguments
  var startDate = Math.floor((inputControls.getRange("B4").getValue() - new Date('January 1, 1970')) / 1000);
  var endDate = Math.floor((inputControls.getRange("B5").getValue() - new Date('January 1, 1970')) / 1000);
  
  var dateDifference = inputControls.getRange("B5").getValue() - inputControls.getRange("B4").getValue();
  
  if (inputControls.getRange("B5").getValue() > new Date()) {
    var result = Browser.msgBox("EndDate seems greater than today's date. Okay to you?", Browser.Buttons.YES_NO);
    if (result == 'no') return;
  }
  
  if (dateDifference < 1) {
    Browser.msgBox("Date difference must be at least one. Since EndDate is not inclusive of the date, you can have one day difference between start and end Date to fetch latest price");
    return;
  }

  var outputLastRow = outputData.getLastRow();
  if (outputLastRow > 1) {
    outputData.getRange("A2:H" + outputLastRow).clearContent();
  }

  // Loop over multiple symbols
  for (var i = 8; i <= lastRow; i++) {
    var symbol = inputControls.getRange("A" + i).getValue();
    var offsetCounter = 1;
    extractData(symbol, startDate, endDate, offsetCounter, outputData);
  }

  var rng = outputData.getRange("A:D");
  rng.removeDuplicates([1, 3, 4]);

  // Select the outputData sheet after the script finishes
  SpreadsheetApp.setActiveSheet(outputData);

}

function extractData(symbols, startDate, endDate, offsetCounter, outputData) {
  var tickerURL = "https://query1.finance.yahoo.com/v8/finance/chart/" + symbols +
    "?events=capitalGain%7Cdiv%7Csplit&formatted=true&includeAdjustedClose=true&interval=1d&period1=" + startDate +
    "&period2=" + endDate;

  var response = UrlFetchApp.fetch(tickerURL);
  var data = JSON.parse(response.getContentText());

  var combinedData = extractDividends(data, symbols);

  if (!combinedData || typeof combinedData === 'string') {
    outputData.getRange(outputData.getLastRow() + offsetCounter, 1, 1, 4).setValues([["NA", "NA", "NA", symbols]]);
  } else {
    outputData.getRange(outputData.getLastRow() + offsetCounter, 1, combinedData.length, combinedData[0].length).setValues(combinedData);
  }
}

function extractDividends(data, symbol) {
  if (!data.chart || !data.chart.result || data.chart.result.length === 0) {
    return "No dividends found.";
  }

  var result = [];
  var dividends = data.chart.result[0].events && data.chart.result[0].events.dividends; // Check if events exists

  if (!dividends) {
    return "No dividends found."; // Return if dividends is undefined
  }

  var exchangeTimezoneName = data.chart.result[0].meta.exchangeTimezoneName;
  var currency = data.chart.result[0].meta.currency;

  for (var date in dividends) {
    if (dividends.hasOwnProperty(date)) {
      var dividend = dividends[date];
      result.push([
        formatDate(new Date(date * 1000), exchangeTimezoneName), // Format date
        dividend.amount,
        currency,
        symbol
      ]);
    }
  }

  return result.length > 0 ? result : "No dividends found."; // Return result or a message
}

function formatDate(date, timezone) {
  // Convert date to local timezone if necessary
  return date.toISOString().split('T')[0];
}

Viewing all articles
Browse latest Browse all 425