# Peer benchmarking with an API: ROE, ROA and revenue growth vs. sector quartiles

Build a competitor benchmarking table for Japanese listed companies: peer candidates, ROE, ROA and 3-year revenue growth, placed in sector quartiles and exported to CSV.

Corporate planning and investor relations teams often need one table that lines up a handful of competitors and answers a second question: where does each company sit within its industry? This page shortens that job with an API. The Python script below picks peer candidates, computes ROE, ROA and three-year revenue growth from each company's latest fiscal year, and adds the sector's quartiles from all listed companies in the same industry. The result is a CSV you can open in Excel.

All example figures were retrieved from ZENITH Code on November 12, 2026. Toyota Motor (7203) plays "our company," compared with five other transportation equipment makers.

## What you will get from this page

- How to gather a benchmarking table from four endpoints in a single run
- How to compute ROE, ROA and three-year growth only when the inputs are actually comparable
- How to label each company "top 25%," "middle 50%" or "bottom 25%" against the sector's Q1, median and Q3
- How to keep price-derived values out of the table by whitelisting the fields you accept

## Where competitor tables eat your time

Collecting the numbers is quick. Making them comparable is not. When you copy revenue and profit out of kessan tanshin (earnings summaries) and annual securities reports, three things tend to get lost.

- **Fiscal period.** Japanese companies end their fiscal years in different months. Putting a March year-end next to a December year-end in the same column mixes periods nine months apart.
- **Accounting standard.** Japanese GAAP and IFRS do not define operating profit or revenue in exactly the same way.
- **The industry baseline.** Ranking five rivals against each other says little if the whole group is weak. First place among five can still be near the bottom of the sector.

An API removes the copying, but not the need to line things up. The script keeps the fiscal period and accounting standard as columns in every row, and it leaves a cell blank whenever the inputs do not match.

## Endpoints and token cost

| Endpoint | What it provides | Tokens per call |
|---|---|---:|
| [`/peers`](https://zenithcode.net/en/docs/peers) | Candidates in the same TSE 33-sector with a similar size | 10 |
| [`/income-statement`](https://zenithcode.net/en/docs/income-statement) | Four fiscal years of income statements per company | 1 |
| [`/balance-sheet-statement`](https://zenithcode.net/en/docs/balance-sheet-statement) | The latest fiscal-year balance sheet per company | 1 |
| [`/industry-benchmarks`](https://zenithcode.net/en/docs/industry-benchmarks) | Sector quartiles of ROE, ROA and three-year growth | 10 |

For six companies (yours plus five peers), that is 10 + 6 × 2 + 10 = 32 tokens. If you already know your peer set, skip `/peers` and spend 22.

## Do not accept price-derived values

Alongside financial ratios, `/peers` and `/industry-benchmarks` return values computed from share prices.

| Endpoint | Price-derived fields |
|---|---|
| `/peers` | `price`, `marketCap`, `per`, `pbr`, `psr`, `evToEbitda`, `dividendYield`, `changePctYtd`, `marketCapRank`, `marketCapRatio` |
| `/industry-benchmarks` | Q1, median, Q3 and counts for PER, PBR, PSR, EV/EBITDA, dividend yield and market cap |

The table on this page is built only from disclosed financial figures. Keep price-derived values off your screens, out of material you share outside the company, and out of articles. The rules are on the [data display rights](https://zenithcode.net/en/docs/display-rights) page.

So the script does not delete unwanted fields; it copies only the fields it needs. If the API adds a field later, nothing unexpected leaks into the CSV.

```python
import csv, json, os, urllib.parse, urllib.request

BASE = "https://api.zenithcode.net/stable"
API_KEY = os.environ.get("ZENITH_API_KEY", "YOUR_API_KEY")

# /peers and /industry-benchmarks also return price-derived values.
# Anything not listed here is dropped as soon as it arrives.
PEER_KEEP = ("role", "symbol", "nameJa", "nameEn", "sector")
BAND_METRICS = ("roe", "roa", "revenueCagr3y")
BAND_KEEP = ("sector", "sectorEn", "count") + tuple(
    m + s for m in BAND_METRICS for s in ("Count", "Q1", "Median", "Q3"))


def get(path, **params):
    """Call once. On failure, raise and stop instead of building a partial table."""
    url = f"{BASE}{path}?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(url, headers={"x-api-key": API_KEY})
    with urllib.request.urlopen(req, timeout=30) as res:
        return json.load(res)


def keep(row, fields):
    return {k: row.get(k) for k in fields}
```

Each `/peers` row has a `role`: `target` is the company you asked for, `peer` is a candidate, and the last row, `sector-median`, is the sector median. The median row is mostly price-based values, so the script ignores it.

```python
def peer_candidates(symbol, limit=5):
    rows = [keep(r, PEER_KEEP) for r in get("/peers", symbol=symbol, limit=limit)]
    target = next(r for r in rows if r["role"] == "target")
    peers = [r for r in rows if r["role"] == "peer"]
    return target, peers
```

The candidates are companies in the same sector with a similar market cap. They are not necessarily companies whose businesses overlap with yours. Treat the list as a starting point and choose the final peer set yourself.

## Compute ROE, ROA and three-year growth

For each company, the script takes four fiscal years of income statements and one fiscal year of balance sheet. `period=annual` limits the rows to full fiscal years.

ROE and ROA are computed from the retrieved figures, under three rules.

- The income statement and balance sheet must cover the same fiscal period.
- The denominator must be positive. That stops a loss-making company with negative equity from showing a positive ROE.
- The denominator is the period-end balance, not the average of opening and closing balances.

```python
def ratio(top, bottom):
    if top is None or bottom is None or bottom <= 0:
        return None
    return top / bottom


def cagr_3y(years):
    """Four fiscal years, oldest first. Only when length, year-end month and standard match."""
    if len(years) != 4:
        return None
    for prev, cur in zip(years, years[1:]):
        if cur["fiscalPeriod"][5:] != prev["fiscalPeriod"][5:]:
            return None                      # the year-end month changed
        if int(cur["fiscalPeriod"][:4]) - int(prev["fiscalPeriod"][:4]) != 1:
            return None                      # a year is missing
    if any(not (360 <= (y.get("fiscalPeriodDays") or 0) <= 366) for y in years):
        return None                          # an irregular (shortened) fiscal year
    if len({y["accountingStandard"] for y in years}) != 1:
        return None                          # the accounting standard changed
    first, last = years[0]["revenue"], years[-1]["revenue"]
    if first is None or last is None or first <= 0 or last < 0:
        return None
    return (last / first) ** (1 / 3) - 1


def company_metrics(symbol):
    income = get("/income-statement", symbol=symbol, period="annual", limit=4)
    balance = get("/balance-sheet-statement", symbol=symbol, period="annual", limit=1)
    if not income:
        return {"symbol": symbol}
    latest, bs = income[0], (balance[0] if balance else None)
    same = bs is not None and bs["fiscalPeriod"] == latest["fiscalPeriod"]
    return {
        "symbol": symbol,
        "fiscalPeriod": latest["fiscalPeriod"],
        "accountingStandard": latest["accountingStandard"],
        "consolidation": latest.get("consolidation"),
        "revenue": latest["revenue"],
        "operatingMargin": latest["operatingMargin"],
        "roe": ratio(latest["netIncomeAttributableToOwners"], bs["ownersEquity"]) if same else None,
        "roa": ratio(latest["netIncome"], bs["totalAssets"]) if same else None,
        "revenueCagr3y": cagr_3y(list(reversed(income))),
    }
```

The API returns the newest period first, so the growth calculation reverses the list into chronological order.

The ROE denominator is `ownersEquity`, equity attributable to owners of the parent. A similar field, `shareholdersEquity`, excludes accumulated other comprehensive income. Mixing the two would change the denominator from company to company, so pick one and stick with it.

Anything that cannot be computed stays `None` and becomes a blank cell in the CSV. It never becomes zero.

## Place each company in the sector's quartiles

Pass your sector code to `/industry-benchmarks` and you get Q1 (the 25th percentile), the median and Q3 (the 75th percentile) across all listed companies in that sector. Labels such as "top 25%" travel better in a meeting deck than raw percentiles.

```python
def sector_band(sector):
    rows = get("/industry-benchmarks", sector=sector)
    row = next((r for r in rows if r.get("sector") == sector), None)
    return keep(row, BAND_KEEP) if row else None


def zone(value, band, metric):
    q1, median, q3 = (band.get(metric + s) for s in ("Q1", "Median", "Q3"))
    if value is None or None in (q1, median, q3) or not (q1 <= median <= q3):
        return ""                             # no label without a complete band
    if value >= q3:
        return "top 25%"
    return "bottom 25%" if value < q1 else "middle 50%"
```

If any of Q1, the median or Q3 is missing, or they are out of order, the script does not assign a label. The API returns a statistic as null when fewer than three valid values remain.

## Write everything to one CSV

The last step writes the six company rows plus the sector band to a single CSV. Ratios stay as 0–1 decimals, exactly as the API returns them; format them as percentages in your spreadsheet.

```python
def build(symbol, extra=()):
    target, peers = peer_candidates(symbol)
    names = {r["symbol"]: r["nameEn"] for r in [target, *peers]}
    symbols = [symbol] + [p["symbol"] for p in peers] + list(extra)
    band = sector_band(target["sector"])
    rows = []
    for s in symbols:                         # one company at a time
        m = company_metrics(s)
        m["name"] = names.get(s, "")
        for metric in BAND_METRICS:
            m[metric + "Zone"] = zone(m.get(metric), band, metric) if band else ""
        rows.append(m)
    return rows, band


def write_csv(rows, band, path="peer-benchmark.csv"):
    cols = ["symbol", "name", "fiscalPeriod", "accountingStandard", "consolidation",
            "revenue", "operatingMargin", "roe", "roeZone", "roa", "roaZone",
            "revenueCagr3y", "revenueCagr3yZone"]
    with open(path, "w", newline="", encoding="utf-8-sig") as f:
        w = csv.writer(f)
        w.writerow(cols)
        for r in rows:
            w.writerow(["" if r.get(c) is None else r.get(c) for c in cols])
        if band:
            for stat in ("Q1", "Median", "Q3"):
                w.writerow([f"sector {stat}", band["sectorEn"]] + [""] * 5 +
                           [band.get("roe" + stat), "", band.get("roa" + stat), "",
                            band.get("revenueCagr3y" + stat), ""])


rows, band = build("7203")
write_csv(rows, band)
```

The `utf-8-sig` encoding adds a byte-order mark, so Excel shows Japanese company names correctly if you switch to `nameJa`.

## Sample output: Toyota Motor and five peers

Rounded for display, the November 12, 2026 results look like this. Every company's latest year is the fiscal year ended March 2026.

The five peers are the candidates `/peers` returned on October 29. Candidates are picked by market cap, so the set changes from day to day; on November 12 it included Denso and Shimano. To keep the same five, skip `peer_candidates` and pass the list yourself (see "Adapting it to your company" below).

| Company | Standard | ROE | Position | ROA | Position | 3-year revenue CAGR | Position |
|---|---|---:|---|---:|---|---:|---|
| Toyota Motor | IFRS | 9.6% | middle | 3.7% | middle | 10.9% | top 25% |
| Honda Motor | IFRS | −3.6% | bottom 25% | −1.3% | bottom 25% | 8.8% | top 25% |
| Suzuki Motor | IFRS | 13.0% | top 25% | 6.6% | top 25% | — | — |
| Subaru | IFRS | 3.3% | bottom 25% | 1.7% | middle | 8.2% | middle |
| Mazda Motor | Japanese GAAP | 1.8% | bottom 25% | 0.8% | bottom 25% | 8.7% | top 25% |
| Nissan Motor | Japanese GAAP | −11.1% | bottom 25% | −2.7% | bottom 25% | 4.3% | middle |
| Transportation equipment band | | 3.7%–10.8% | median 6.8% | 1.6%–5.1% | median 3.6% | 2.3%–8.5% | median 4.9% |

The band covered 81 companies for ROE and ROA and 80 for growth. The band's ROE uses each company's trailing twelve months, while the table's ROE uses the fiscal year-end; "The sector band and your own calculation may not use the same definition" below explains the difference. In the CSV, Toyota's ROE is 0.0964, the same form the API uses; on screen or in a deck it reads 9.6%.

Two things worth reading closely:

- **Suzuki's growth cell is blank.** Of the four years retrieved, the fiscal years ended March 2023 and March 2024 were under Japanese GAAP, and IFRS applies from the year ended March 2025. A change of standard can change what revenue includes, and the script refuses to count that as growth.
- **Subaru's ROA of 1.65% sits just above Q1 at 1.60%,** so it lands in "middle." A company near a boundary can change position when the sector quartiles move only slightly, so show the number next to the label.

## Reading the numbers correctly

### Peer candidates are "similar market cap, same sector"

`/peers` returns common stocks in the same TSE 33-sector that are closest in market cap. They are not competitors chosen for business overlap. Expect to drop some and add others. The ordering and `marketCapRank` are also driven by share prices, so they stay out of the table.

### The sector band and your own calculation may not use the same definition

The band is the distribution of ROE, ROA and growth that ZENITH Code computes for every company in the sector. The sector PER and ROE use trailing-twelve-month (TTM) values; for ROE, a company without a TTM value counts with its latest fiscal year. ROA and growth use the latest fiscal year. Values of ROE or ROA above 1 (100%) are excluded as outliers.

The script on this page computes each company's ROE from the fiscal year-end, so its period basis differs from the band's TTM ROE. In addition, the API's fiscal-year ROE divides net income attributable to owners of the parent by average equity (the mean of opening and closing balances). The script divides by closing equity, so the same company can come out slightly different from the API's calculation. When you plot your own figures against the band, note "points use fiscal year-end balances" on the slide. Use the band to gauge the industry level, and check the definitions on the [metrics](https://zenithcode.net/en/docs/metrics) page.

### The band's universe differs slightly from market-wide counts

`/industry-benchmarks` counts common stocks, excluding preferred and other class shares and TOKYO PRO Market. Because it measures financial ratios, it also includes stocks without a price. That makes its universe slightly different from `/market-breadth`, which counts advancing and declining stocks (3,815 versus 3,806 companies when checked on November 3, 2026). If you show company counts from both endpoints in one document, say that the universes differ.

### Fetch the band for your own sector

The script fetches one band, for your sector code. If you add a peer from a different sector, the band does not describe that company's industry.

### Keep the fiscal period, standard and consolidation flag as columns

All six companies end their year in March only because this example uses automakers. Add a December year-end company and the "latest fiscal year" ends nine months apart. The income statement's `consolidation` field shows whether figures are consolidated (`consolidated`) or parent-only (`nonconsolidated`); a company that loses its last subsidiary switches partway through its history. That is why the CSV keeps `fiscalPeriod`, `accountingStandard` and `consolidation` columns.

### Right after an earnings release, the two statements can disagree on the period

If you fetch while a new year has reached one statement but not the other, the income statement and balance sheet can show different fiscal periods. The script leaves ROE and ROA blank in that case. Fetch again a few days later, or decide by looking at `fiscalPeriod`.

## Adapting it to your company

- If your peer set is fixed, add codes with `build("7203", extra=("7211",))`, or skip `peer_candidates` and pass your own list.
- If you refresh the table monthly, save the JSON responses to files and reuse them within the same month. Never calling the API more often than you mean to keeps token use predictable.
- For a version with a screen, see the [peer benchmark template](https://github.com/Crab-grass/zenith-code-examples/tree/main/templates/peer-benchmark), built on the same ideas. Its saved demo opens without an API key.

## Related

- API docs: [peers](https://zenithcode.net/en/docs/peers), [industry benchmarks](https://zenithcode.net/en/docs/industry-benchmarks), [income statement](https://zenithcode.net/en/docs/income-statement), [balance sheet](https://zenithcode.net/en/docs/balance-sheet-statement), [metric definitions](https://zenithcode.net/en/docs/metrics)
- Related articles: [Compare competitors' segment revenue and profit](https://zenithcode.net/en/docs/cookbook/applied/analysis-segments), [Compare competitors' free cash flow and shareholder returns](https://zenithcode.net/en/docs/cookbook/applied/analysis-cash-and-balance), [Accounting standards in Japan](https://zenithcode.net/en/learn/accounting-standards)
- Templates: [zenith-code-examples](https://github.com/Crab-grass/zenith-code-examples)
- [Data display rights](https://zenithcode.net/en/docs/display-rights)

An illustrated series on the same material is on [Qiita](https://qiita.com/Sohei-Taniguchi-CG/items/de733ed981cd5d21e738) (in Japanese).

This page explains how to handle financial data. It is not a recommendation to buy or sell any security.

---
Page: https://zenithcode.net/en/docs/cookbook/applied/analysis-peer-benchmark
日本語: https://zenithcode.net/docs/cookbook/applied/analysis-peer-benchmark.md
Site guide for AI tools: https://zenithcode.net/llms.txt
