# Build a watchlist of prices and dividend yields

Write the securities codes and your watchlist of prices and dividend yields refreshes every morning. High yields turn green and big drops turn red, so you can see them at a glance.

## Key points

- In Google Sheets, paste the Apps Script and choose Set up. The script creates the sheets and the color rules.
- One call covers up to 50 stocks. Prices and metrics take two calls, 20 tokens in total, so the Free plan can refresh it every day.
- Your API key is kept in the script's per-user storage, not in the sheet.

## Endpoints to use

- [`batch-quote`](https://zenithcode.net/en/docs/batch-quote.md): Price, 1-day change and price date (up to 50 stocks)
- [`batch-key-metrics-latest`](https://zenithcode.net/en/docs/batch-key-metrics-latest.md): Dividend yield, PER, PBR and annual dividend (up to 50 stocks)

## Code

Replace YOUR_API_KEY with the key you created in the dashboard.

### Python

```python
import pandas as pd
import requests

CODES = ["7203", "8306", "9432"]  # up to 50 per call
HEADERS = {"x-api-key": "YOUR_API_KEY"}


def get(path):
    res = requests.get(f"https://api.zenithcode.net/stable/{path}", params={"symbols": ",".join(CODES)}, headers=HEADERS)
    res.raise_for_status()
    return pd.DataFrame(res.json())


quote = get("batch-quote")[["symbol", "found", "price", "changePct1d", "priceDate"]]
metrics = get("batch-key-metrics-latest")[["symbol", "dividendYield", "per", "pbr", "annualDividend"]]
df = quote.merge(metrics, on="symbol", how="left")

# Highlight rows: yield >= 3.5% in green, 1-day change <= -3% in red (pip install openpyxl jinja2)
styled = df.style.map(lambda v: "background-color: #dff3e6" if pd.notna(v) and v >= 0.035 else "", subset=["dividendYield"]) \
    .map(lambda v: "background-color: #fde4e1" if pd.notna(v) and v <= -0.03 else "", subset=["changePct1d"])
styled.to_excel("watchlist.xlsx", index=False)
```

### Google Sheets

```javascript
// ZENITH Code watchlist for Google Sheets
// 1. Extensions > Apps Script: paste this, save, then reload the spreadsheet.
// 2. Menu "ZENITH" > "Set up": creates the sheets and asks for your API key.
// 3. Write securities codes in the "Symbols" sheet, then "ZENITH" > "Refresh now".
// The key is kept in your user properties, not in the sheet.
const BASE = "https://api.zenithcode.net/stable";
const JA = Session.getActiveUserLocale().indexOf("ja") === 0;
const L = JA
  ? { symbols: "銘柄", list: "一覧", settings: "設定", refresh: "今すぐ更新", setup: "はじめの設定", daily: "毎朝 8 時台に自動で更新", key: "API キーを変える",
      head: ["証券コード", "名前（メモ）", "株価", "前日比", "配当利回り", "PER", "PBR", "年間配当", "株価の日付"],
      yieldAt: "配当利回りがこれ以上なら緑", dropAt: "前日比がこれ以下なら赤", notFound: "見つかりません",
      askKey: "ZENITH Code の API キーを貼り付けてください（ダッシュボードの「API キー」で作れます）", noKey: "先に「はじめの設定」で API キーを入れてください", badKey: "API キーを確かめてください（401）" }
  : { symbols: "Symbols", list: "Watchlist", settings: "Settings", refresh: "Refresh now", setup: "Set up", daily: "Refresh every morning (8 am)", key: "Change API key",
      head: ["Code", "Name (memo)", "Price", "1-day change", "Dividend yield", "PER", "PBR", "Annual dividend", "Price date"],
      yieldAt: "Green when dividend yield is at least", dropAt: "Red when 1-day change is at most", notFound: "Not found",
      askKey: "Paste your ZENITH Code API key (create one under API keys in the dashboard)", noKey: "Run Set up first to save your API key", badKey: "Check your API key (401)" };

function onOpen() {
  SpreadsheetApp.getUi().createMenu("ZENITH")
    .addItem(L.refresh, "refresh").addItem(L.setup, "setup").addItem(L.daily, "enableDaily").addItem(L.key, "setKey").addToUi();
}

function setup() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  if (!ss.getSheetByName(L.symbols)) {
    const s = ss.insertSheet(L.symbols);
    s.getRange(1, 1, 4, 2).setValues([[L.head[0], L.head[1]], ["7203", ""], ["8306", ""], ["9432", ""]]);
    s.getRange("A:A").setNumberFormat("@");
    s.setFrozenRows(1);
  }
  if (!ss.getSheetByName(L.settings)) {
    const s = ss.insertSheet(L.settings);
    s.getRange(1, 1, 2, 2).setValues([[L.yieldAt, 0.035], [L.dropAt, -0.03]]);
    s.getRange("B1:B2").setNumberFormat("0.0%");
  }
  if (!ss.getSheetByName(L.list)) ss.insertSheet(L.list, 0);
  setKey();
}

function setKey() {
  const ui = SpreadsheetApp.getUi();
  const r = ui.prompt(L.askKey, ui.ButtonSet.OK_CANCEL);
  if (r.getSelectedButton() === ui.Button.OK && r.getResponseText().trim()) {
    PropertiesService.getUserProperties().setProperty("ZENITH_API_KEY", r.getResponseText().trim());
  }
}

function enableDaily() {
  ScriptApp.getProjectTriggers().filter((t) => t.getHandlerFunction() === "refresh").forEach((t) => ScriptApp.deleteTrigger(t));
  // Prices for the previous trading day are ready by about 7:30 JST
  ScriptApp.newTrigger("refresh").timeBased().everyDays(1).atHour(8).inTimezone("Asia/Tokyo").create();
}

function zenith(path, symbols) {
  const key = PropertiesService.getUserProperties().getProperty("ZENITH_API_KEY");
  if (!key) throw new Error(L.noKey);
  const res = UrlFetchApp.fetch(BASE + path + "?symbols=" + encodeURIComponent(symbols.join(",")), {
    headers: { "x-api-key": key },
    muteHttpExceptions: true,
  });
  if (res.getResponseCode() === 401) throw new Error(L.badKey);
  if (res.getResponseCode() !== 200) throw new Error("HTTP " + res.getResponseCode() + ": " + res.getContentText().slice(0, 200));
  return JSON.parse(res.getContentText());
}

function refresh() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const rows = ss.getSheetByName(L.symbols).getDataRange().getValues().slice(1)
    .map((r) => [String(r[0]).trim().toUpperCase(), r[1]]).filter((r) => r[0]);
  const quote = {}, metrics = {};
  // The batch endpoints take up to 50 codes per call (10 tokens each)
  for (let i = 0; i < rows.length; i += 50) {
    const codes = rows.slice(i, i + 50).map((r) => r[0]);
    zenith("/batch-quote", codes).forEach((q) => (quote[q.symbol] = q));
    zenith("/batch-key-metrics-latest", codes).forEach((m) => (metrics[m.symbol] = m));
  }
  const out = rows.map(([code, memo]) => {
    const q = quote[code] || {}, m = metrics[code] || {};
    if (!q.found) return [code, memo ? memo + " (" + L.notFound + ")" : L.notFound, "", "", "", "", "", "", ""];
    return [code, memo, q.price, q.changePct1d, m.dividendYield, m.per, m.pbr, m.annualDividend, q.priceDate];
  });
  const sheet = ss.getSheetByName(L.list);
  sheet.clear();
  sheet.getRange(1, 1, 1, L.head.length).setValues([L.head]).setFontWeight("bold").setBackground("#0b1326").setFontColor("#ffffff");
  if (out.length) {
    sheet.getRange(2, 1, out.length, L.head.length).setValues(out);
    sheet.getRange(2, 3, out.length, 1).setNumberFormat("#,##0.##");
    sheet.getRange(2, 4, out.length, 2).setNumberFormat("0.0%");
    sheet.getRange(2, 6, out.length, 2).setNumberFormat("0.0");
    const s = "'" + L.settings + "'!";
    sheet.setConditionalFormatRules([
      SpreadsheetApp.newConditionalFormatRule().whenFormulaSatisfied("=AND(ISNUMBER($E2),$E2>=INDIRECT(\"" + s + "B1\"))")
        .setBackground("#dff3e6").setFontColor("#0f6b3a").setRanges([sheet.getRange(2, 5, out.length, 1)]).build(),
      SpreadsheetApp.newConditionalFormatRule().whenFormulaSatisfied("=AND(ISNUMBER($D2),$D2<=INDIRECT(\"" + s + "B2\"))")
        .setBackground("#fde4e1").setFontColor("#a5281b").setRanges([sheet.getRange(2, 4, out.length, 1)]).build(),
    ]);
  }
  sheet.setFrozenRows(1);
  sheet.autoResizeColumns(1, L.head.length);
}
```

### Excel

```text
// Excel (Microsoft 365): Data > Get Data > From Other Sources > Blank Query > Advanced Editor
// Before pasting: make a table named Symbols with a column "code",
// and a cell named ApiKey that holds your API key (Formulas > Define Name).
let
    Key = Excel.CurrentWorkbook(){[Name = "ApiKey"]}[Content]{0}[Column1],
    Codes = Text.Combine(List.Transform(Excel.CurrentWorkbook(){[Name = "Symbols"]}[Content][code], Text.From), ","),
    Get = (path as text) => Table.PromoteHeaders(
        Csv.Document(
            Web.Contents("https://api.zenithcode.net", [
                RelativePath = "stable/" & path,
                Query = [symbols = Codes, format = "csv"],
                Headers = [#"x-api-key" = Key]
            ]),
            [Encoding = 65001]
        ),
        [PromoteAllScalars = true]
    ),
    Quote = Table.SelectColumns(Get("batch-quote"), {"symbol", "found", "price", "changePct1d", "priceDate"}),
    Metrics = Table.SelectColumns(Get("batch-key-metrics-latest"), {"symbol", "dividendYield", "per", "pbr", "annualDividend"}),
    Joined = Table.ExpandTableColumn(
        Table.NestedJoin(Quote, {"symbol"}, Metrics, {"symbol"}, "m", JoinKind.LeftOuter),
        "m", {"dividendYield", "per", "pbr", "annualDividend"}
    ),
    // Ratios come as 0-1 decimals; Percentage.Type shows them as %
    Typed = Table.TransformColumnTypes(Joined, {
        {"price", type number}, {"changePct1d", Percentage.Type}, {"dividendYield", Percentage.Type},
        {"per", type number}, {"pbr", type number}, {"annualDividend", type number}
    }, "en-US")
in
    Typed
```

## How the code works

1. Create a Google spreadsheet and open Extensions > Apps Script. Paste the code from the Google Sheets tab, save, and reload the spreadsheet.
2. Choose ZENITH > Set up in the menu. Allow the Google permission prompt the first time, then paste your API key. The Symbols, Watchlist and Settings sheets are created.
3. Write securities codes in the Symbols sheet (the name column is a free memo). Choose ZENITH > Refresh now to fill the Watchlist sheet.
4. Change the color thresholds in the Settings sheet. Choose ZENITH > Refresh every morning to start the daily refresh.
5. In Excel (Microsoft 365), create a table named Symbols with a column called code and a cell named ApiKey, then paste the code from the Excel tab into a blank query. Add colors with conditional formatting.

## Things to note

- 1-day change and dividend yield come as decimals (0.03 = 3%). The sheet formats them as percentages.
- Prices are the previous trading day's close. Intraday moves are not included.
- If Excel asks for privacy levels, choose Organizational or Ignore for the data in this workbook.
- Sharing the sheet with others counts as providing data to third parties, which the Free and Pro plans do not allow.

## FAQ

### FAQ for investors and developers

**How many stocks can I list?**

Any number. The script splits calls into groups of 50, so 100 stocks take four calls (prices and metrics), 40 tokens.

**Can I add ETFs?**

Yes. Some metrics such as dividend yield can be empty for ETFs.

### FAQ for AI builders and researchers

**Which endpoints does it use?**

Prices for multiple stocks (/stable/batch-quote) and latest key metrics for multiple stocks (/stable/batch-key-metrics-latest). Both take up to 50 comma-separated securities codes.

**What happens with an unknown code?**

It comes back as a row with found set to false. The template shows Not found.

## Related articles

- [Export to Google Sheets](https://zenithcode.net/en/docs/cookbook/export-to-sheets): Load a list into a sheet with ?format=csv
- [Catch dividend increases and cuts daily](https://zenithcode.net/en/docs/cookbook/dividend-change-alerts): Append dividend changes to a sheet
- [Latest key metrics for multiple stocks (API reference)](https://zenithcode.net/en/docs/batch-key-metrics-latest): Parameters and response fields

---
Page: https://zenithcode.net/en/docs/cookbook/holdings-watchlist
日本語: https://zenithcode.net/docs/cookbook/holdings-watchlist.md
Site guide for AI tools: https://zenithcode.net/llms.txt
