Skip to content

Instantly share code, notes, and snippets.

@dburger
Created January 27, 2021 16:08
Show Gist options
  • Save dburger/b3c7cbef3260f43112bb3a3d98e2332e to your computer and use it in GitHub Desktop.
Save dburger/b3c7cbef3260f43112bb3a3d98e2332e to your computer and use it in GitHub Desktop.
Google sheets apps script custom finviz function.
/**
* Returns a ticker's numeric data from finviz.com. If the (row, col)
* contains a "-", 0.0 is returned. Note that this is somewhat equivalent
* to the following composition of built in sheet functions:
*
* =VALUE(SUBSTITUTE(SUBSTITUTE(INDEX(IMPORTHTML("http://finviz.com/quote.ashx?t="&A3, "table", 8), 12, 6), "*", ""), "%", ""))
*
* @param {string} ticker - The security's ticker.
* @param {number} row - The row to return data from.
* @param {number} col - The column to return data from.
* @returns {number}
*/
const FINVIZ = (ticker, row, col) => {
const url = `http://finviz.com/quote.ashx?t=${ticker}`;
let html = UrlFetchApp.fetch(url).getContentText();
// Pull out just the table html.
let i = html.search(/<table.*class="snapshot-table2">/);
html = html.substring(i);
i = html.search("</table>");
html = html.substring(0, i + "</table>".length);
// Clean it up, so that it will parse.
html = html.replace(/S&P/g, "SnP");
html = html.replace(/<td[^>]*>/g, "<td>");
html = html.replace(/<tr[^>]*>/g, "<tr>");
html = html.replace(/<table[^>]*>/g, "<table>");
html = html.replace(/<br>/g, "");
// Finally, parse into XML doc and pull out the (row, col).
const doc = XmlService.parse(html);
const table = doc.getRootElement();
const val = table.getChildren()[row].getChildren()[col].getValue();
return val === "-" ? 0.0 : parseFloat(val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment