PSX stock prices in Google Sheets
Google Sheets cannot read JSON with a plain formula, but a ten line Apps Script function can. After that, =PSX("OGDC") works like any other formula.
Add the function
- Open your sheet, then Extensions → Apps Script.
- Paste the code below and save.
- Back in the sheet, type =PSX("OGDC") or =PSX("OGDC", "change_pct").
/** Latest PSX Lens quote field for a symbol, e.g. =PSX("OGDC") or =PSX("HUBC","change_pct"). */
function PSX(symbol, field) {
field = field || "price";
var cache = CacheService.getScriptCache();
var key = "psx:" + symbol;
var body = cache.get(key);
if (!body) {
body = UrlFetchApp.fetch("https://api.psxlens.com/v1/quotes/" + encodeURIComponent(symbol), { muteHttpExceptions: true }).getContentText();
cache.put(key, body, 900); // prices change once a day; keep 15 minutes
}
var q = JSON.parse(body);
return q[field] === undefined ? "n/a" : q[field];
}The cache keeps a sheet with many cells from calling the API hundreds of times on every recalculation, which would hit the rate limit.
Useful fields
- price, change, change_pct, volume
- high_52, low_52
- previous_close, timestamp
For dividend yield, P/E and beta, read /v1/screener once and look rows up with VLOOKUP, instead of one call per stock.