# Compare revenue and operating margin of two Japanese competitors via API, after checking fiscal period, length, consolidation and accounting standard

Before putting two companies side by side, check in code that both rows cover the same fiscal period, a full 12 months, consolidated statements and the same accounting standard. Worked example comparing Toyota and Honda for the year ended March 2025.

## Key points

- When you compare a company with a competitor, first confirm four things match: **fiscal period, period length, consolidated vs parent-only, and accounting standard**.
- The income statement endpoint returns all four as `fiscalPeriod`, `fiscalPeriodDays`, `consolidation` and `accountingStandard`, so your code can decide before it compares.
- The example uses Toyota Motor (7203) and Honda Motor (7267) for the fiscal year ended March 2025, with values retrieved on October 27, 2026.

Lining up two companies' revenue and margins is routine in competitor research and supplier reviews. Fetching both sets of numbers does not tell you whether they are comparable. One company may have changed its year-end and reported a nine-month year, or one row may be parent-only. This page uses a Python script that checks the conditions before building the table.

## Conditions to align before you compare

Some conditions can be checked in code; others need a human to read the filings.

| Condition | Response field | What the code does | What the code cannot tell you |
|---|---|---|---|
| Same fiscal period | `fiscalPeriod` | Uses only periods common to every company | How to pair companies with different year-ends |
| Full 12 months | `fiscalPeriodDays` | Stops outside 360–366 days | — |
| Consolidated statements | `consolidation` | Stops on parent-only rows; warns when undetermined | Years where the scope of consolidation changed a lot |
| Accounting standard | `accountingStandard` | Warns when they differ | Which items each company put in operating income |
| Yen amounts exist | `nullReason` | Stops on years reported in a non-yen currency | — |
| Division is possible | `revenue`, `operatingIncome` | Stops when revenue is missing, zero or negative | — |

Stopping and warning are separate because the conditions carry different weight. Two periods of different length distort the scale of revenue. A different accounting standard does not make comparison impossible, but readers need to know.

## Endpoint

You only need [income statement](https://zenithcode.net/en/docs/income-statement), called once per company with a different securities code. Each call costs 1 token, so two companies cost 2 tokens.

```text
GET https://api.zenithcode.net/stable/income-statement?symbol=7203&period=annual&limit=10
GET https://api.zenithcode.net/stable/income-statement?symbol=7267&period=annual&limit=10
```

`period=annual` asks for full-year rows only, and those rows come back with `period` = `FY`. Rows are newest first, and the first one may not be the year you want. In our fetch, the first row was the year ended March 2026. Select by the value of `fiscalPeriod`, not by array position.

## Check conditions in Python, then build the table

The script takes two or more securities codes, picks the full year common to all of them, checks the conditions, and writes a comparison table and CSV. It uses only the Python 3.9+ standard library.

```python
"""Compare full-year results across companies only after checking they are comparable.

Usage: python compare_peers.py 7203 7267 --period 2025-03
Standard library only (Python 3.9+).
"""
from __future__ import annotations

import argparse
import csv
import json
import os
import sys
import urllib.parse
import urllib.request

BASE_URL = "https://api.zenithcode.net/stable"


def fetch_fy(symbol: str, api_key: str) -> list[dict]:
    query = urllib.parse.urlencode({"symbol": symbol, "period": "annual", "limit": 10})
    request = urllib.request.Request(f"{BASE_URL}/income-statement?{query}",
                                     headers={"x-api-key": api_key})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def is_amount(value) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool)


def row_issues(row: dict) -> tuple[list[str], list[str]]:
    """For one company and period, return reasons to stop and notes to show with the table."""
    stop, notes = [], []
    consolidation = row.get("consolidation")
    if consolidation == "nonconsolidated":
        stop.append("parent-only (non-consolidated) statements")
    elif consolidation != "consolidated":
        notes.append("consolidated or parent-only cannot be determined (consolidation is null)")
    days = row.get("fiscalPeriodDays")
    if not is_amount(days) or not 360 <= days <= 366:
        stop.append(f"period is {days} days")
    if row.get("nullReason"):
        stop.append(f"amounts are null ({row['nullReason']})")
    if not is_amount(row.get("revenue")) or row["revenue"] <= 0:
        stop.append("revenue missing, zero or negative")
    if not is_amount(row.get("operatingIncome")):
        stop.append("operating income missing")
    return stop, notes


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("symbols", nargs="+")
    parser.add_argument("--period", help="Fiscal period to compare (YYYY-MM). Defaults to the newest FY common to all")
    args = parser.parse_args()
    api_key = os.environ.get("ZENITH_API_KEY", "").strip() or sys.exit("Set ZENITH_API_KEY")

    by_symbol = {}
    for symbol in args.symbols:  # one company at a time (1 token each)
        rows = [r for r in fetch_fy(symbol, api_key) if r.get("period") == "FY"]
        by_symbol[symbol] = {r["fiscalPeriod"]: r for r in rows}

    common = set.intersection(*(set(p) for p in by_symbol.values()))
    period = args.period or (max(common) if common else None)
    if period not in common:
        for symbol, periods in by_symbol.items():
            print(f"{symbol}: full-year periods {sorted(periods)[-3:]}")
        sys.exit("No fiscal period common to all companies. Different year-ends need offset periods")

    picked = {s: by_symbol[s][period] for s in args.symbols}
    blocked = False
    for symbol, row in picked.items():
        stop, notes = row_issues(row)
        for message in notes:
            print(f"Note: {symbol} {period} {message}")
        for message in stop:
            print(f"Stopped: {symbol} {period} {message}")
        blocked = blocked or bool(stop)
    standards = {str(r.get("accountingStandard")).lower() for r in picked.values()}
    if len(standards) > 1:
        print(f"Note: accounting standards differ {sorted(standards)} (operating income may include different items)")
    if blocked:
        sys.exit("Conditions do not line up; no table was built")

    table = []
    for symbol, row in picked.items():
        provenance = row.get("provenance") or {}
        table.append({
            "symbol": symbol, "fiscalPeriod": period,
            "accountingStandard": row.get("accountingStandard"),
            "revenue_jpy": row["revenue"], "operatingIncome_jpy": row["operatingIncome"],
            "operatingMargin": row["operatingIncome"] / row["revenue"],
            "apiOperatingMargin": row.get("operatingMargin"),
            "source": provenance.get("source"), "docId": provenance.get("docId"),
        })
    with open(f"compare-{period}.csv", "w", encoding="utf-8-sig", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(table[0]))
        writer.writeheader()
        writer.writerows(table)

    print("| Code | Revenue (¥ tn) | Operating income (¥ tn) | Operating margin | Document ID |")
    print("|---|---:|---:|---:|---|")
    for t in sorted(table, key=lambda t: t["revenue_jpy"], reverse=True):
        print(f"| {t['symbol']} | {t['revenue_jpy'] / 1e12:.2f} | {t['operatingIncome_jpy'] / 1e12:.2f}"
              f" | {t['operatingMargin']:.2%} | {t['docId']} |")


if __name__ == "__main__":
    main()
```

Put the API key in an environment variable before running it.

```bash
export ZENITH_API_KEY="YOUR_API_KEY"
python compare_peers.py 7203 7267 --period 2025-03
```

### How it works

1. **Fetch once per company.** Full-year rows become a dictionary keyed by fiscal period. Calls run one after another, not in parallel.
2. **Find the fiscal period common to all companies.** The script intersects the sets and, without `--period`, uses the newest common period. With no common period, it prints each company's recent year-ends and stops.
3. **Check each company.** `row_issues()` returns reasons to stop and notes separately. If any company has a reason to stop, no table is built.
4. **Compare accounting standards.** Values are lowercased before comparison. A difference produces a note, and the table is still built.
5. **Write the table and CSV.** Operating margin is computed from yen, and the API's `operatingMargin` is kept alongside it in the CSV. The document ID lets you trace any number back to its filing.

Parent-only rows (`nonconsolidated`) stop the script because putting them next to a consolidated company compares one legal entity with a whole group. If you want to compare two companies that have no subsidiaries, remove that condition.

## Output: Toyota and Honda, year ended March 2025

With the values retrieved on October 27, 2026, the table prints like this. Any notes or stop reasons appear above it.

```text
| Code | Revenue (¥ tn) | Operating income (¥ tn) | Operating margin | Document ID |
|---|---:|---:|---:|---|
| 7203 | 48.04 | 4.80 | 9.98% | S100VWVY |
| 7267 | 21.69 | 1.21 | 5.59% | S100VYOD |
```

The output is a Markdown table, ready to paste into internal notes. Here are the yen values.

| Item | Toyota Motor (7203) | Honda Motor (7267) |
|---|---:|---:|
| Fiscal year ended | March 2025 | March 2025 |
| Accounting standard | `ifrs` | `ifrs` |
| Revenue (¥) | 48,036,704,000,000 | 21,688,767,000,000 |
| Operating income (¥) | 4,795,586,000,000 | 1,213,486,000,000 |
| Operating margin | 9.98% (0.0998 in the API) | 5.59% (0.0559 in the API) |
| Source | EDINET, S100VWVY | EDINET, S100VYOD |

Both cover the consolidated results for April 1, 2024 to March 31, 2025. We also confirmed this in the consolidated results section of each company's financial materials. Honda's earnings summary shows revenue of ¥21,688,767 million, which matches the API's yen value divided by one million. We checked revenue and operating income only, not every field in the response.

## Read amounts and ratios separately

Revenue shows scale; operating margin shows how much of revenue is left as operating income. They use different units, so show them in separate columns or separate charts rather than on one axis.

- Revenue: about ¥48.04 trillion for Toyota and about ¥21.69 trillion for Honda.
- Operating margin: about 9.98% for Toyota and about 5.59% for Honda, a gap of about 4.39 percentage points.

This compares each company's **consolidated results as a whole**. Both include businesses beyond automobiles, such as financial services, and Honda also has a motorcycle business. To compare automobile operations only, use segment figures as in [comparing competitors' segment revenue and profit](https://zenithcode.net/en/docs/cookbook/applied/analysis-segments).

The table also does not explain the gap. Product mix, currency, costs and one-off items have to be checked in each company's materials and notes. One year's margin does not rank future performance. The point of aligning conditions is not to erase differences but to make clear what is aligned and what is not.

## Companies with different fiscal year-ends

A March year-end company and a December year-end company have no row with the same `fiscalPeriod`, so the script prints each company's recent periods and stops. There are two common approaches.

1. **Compare each company's latest full year and state the offset.** For example, "year ended March 2025" against "year ended December 2024", with the three-month gap in the table heading.
2. **Build 12 months ending in the same month from quarterly figures.** Q2 and Q3 income figures are cumulative from the start of the fiscal year, so subtract to get single quarters, then add four together. See [cumulative quarters and TTM](https://zenithcode.net/en/learn/ttm-and-cumulative-quarters).

Either way, keep the original rows' `fiscalPeriod` and `fiscalPeriodDays` in the table so readers can check the basis of the comparison.

## Three or more companies, or a whole sector

The script accepts any number of securities codes. `python compare_peers.py 7203 7267 7201` builds a table using only periods common to all of them. The more companies you add, the more likely it is that year-ends or accounting standards differ. When the script stops, read the reasons and adjust the list.

To see where a company sits within its whole sector, an endpoint that returns sector statistics works better than calling companies one by one. [Building a peer benchmarking table](https://zenithcode.net/en/docs/cookbook/applied/analysis-peer-benchmark) shows how to compare against sector medians and quartiles. The `compare` command in the [public examples](https://github.com/Crab-grass/zenith-code-examples) also reports differing accounting standards or a missing common period in `notes` (try it on fictional data with `--demo`).

## Reading the numbers correctly

### Different accounting standards can mean different operating income

Under Japanese GAAP, operating income excludes non-operating items and extraordinary items. For IFRS filers, what goes into operating income can vary by company. When you compare margins across standards, show the standard in the table and tell readers that part of the gap may come from the standard ([accounting standards in Japan](https://zenithcode.net/en/learn/accounting-standards)). Ordinary income is specific to Japanese GAAP, so `ordinaryIncome` is `null` for IFRS filers and cannot be compared.

### `revenue` means different things in different industries

`revenue` is the top line a company leads with. For retailers that headline operating revenue, it is net sales plus other operating revenue. For banks and insurers it is ordinary revenues; for securities firms, operating revenues. Comparing revenue or margins across these industries compares different yardsticks. To compare gross profit across companies, use `operatingGrossProfit` (or `grossProfit` when it is `null`), which absorbs differences in how other operating revenue is presented.

### The consolidation flag cannot tell you everything

`consolidation` is `null` when there is nothing to decide from, or when the earnings summary and the annual report disagree. The script warns rather than stops in that case. Breaks caused by share exchanges or changes in the scope of consolidation are not shown by this flag. For years with large acquisitions, check the annual report notes for scope changes.

### A 12-month year is not always the same number of days

`fiscalPeriodDays` is the actual length of the period. Even 12-month years vary, for example 364 or 365 days. The script treats 360–366 days as 12 months. A transition year after a year-end change, such as a nine-month year, stops the script here.

### Some companies and years are not available

For years where a company prepares its statements in a currency other than yen, such as US dollars, every amount is `null` and `nullReason` is `non_jpy_material`. The API does not convert currencies. Newly listed companies may have no income statement for pre-listing years. Companies on TOKYO PRO Market have no financials loaded.

### Values reflect the time you fetched them

If a company files an amendment, a year's values can change later. Save the retrieval time and document IDs with your comparison table.

## Troubleshooting

| Symptom | What to check |
|---|---|
| "No fiscal period common to all companies" | A company with a different year-end is in the list. Look at the periods printed |
| Stops with "period is 275 days" | A year-end change. Pick 12-month periods before or after it |
| Stops with "parent-only statements" | A company with no subsidiaries, or the year it first acquired one at year-end |
| Note "cannot be determined" | Check whether the annual report includes consolidated statements |
| `HTTP 429` | Too many companies at once. Space out the runs |
| Margin differs from the company's materials in the last digit | Company figures are rounded; check whether the denominator is net sales or operating revenue |

## Showing the results to others

Building comparison tables for your own or your organization's internal research is allowed on every plan. Showing them to third parties, in external materials or your own product, depends on your plan. Financial figures can be displayed on the Business plan or higher. TDnet documents themselves (PDFs, text and links) cannot be shown to third parties on any plan. See [display rights](https://zenithcode.net/en/docs/display-rights).

## Related docs and articles

- [Income statement (income-statement)](https://zenithcode.net/en/docs/income-statement)
- [Metric definitions: period basis](https://zenithcode.net/en/docs/metrics#period-basis) and [revenue](https://zenithcode.net/en/docs/metrics#revenue)
- [Japanese company revenue and operating income history via API](https://zenithcode.net/en/docs/cookbook/applied/practice-revenue-chart)
- [Verify operating margin against your own calculation](https://zenithcode.net/en/docs/cookbook/applied/practice-operating-margin)
- [Build a peer benchmarking table with sector quartiles](https://zenithcode.net/en/docs/cookbook/applied/analysis-peer-benchmark)
- [Public examples on GitHub](https://github.com/Crab-grass/zenith-code-examples)

A Japanese series with screenshots is available on [Qiita](https://qiita.com/Sohei-Taniguchi-CG/items/c74edd2c330a69bc9dac).

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

---
Page: https://zenithcode.net/en/docs/cookbook/applied/practice-compare-two-companies
日本語: https://zenithcode.net/docs/cookbook/applied/practice-compare-two-companies.md
Site guide for AI tools: https://zenithcode.net/llms.txt
