Docs menuexpand_more
travel_exploreTry in the API Viewer

Guides

Reference

Other pages

Endpoints

search
appsAll APIs
functionHow metrics are calculated

Cookbook · Applied · Hands-on 3

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.
For developersFor investorsFor companies8 min read
open_in_newIllustrated series on Qiita (Japanese)The same topic is also published as an illustrated series on Qiita.

Endpoints used

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, called once per company with a different securities code. Each call costs 1 token, so two companies cost 2 tokens.

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.

"""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.

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.

| 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.

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.

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 shows how to compare against sector medians and quartiles. The compare command in the public 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). 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.

Related docs and articles

A Japanese series with screenshots is available on Qiita.

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

Before you read the numbers

Points about the endpoints in this article that are easy to misread as wrong data.

  • By designTDnet-derived information is returned 24 hours after disclosure

    Under Article 7(1) of the JPX TDnet API service terms, information derived from TDnet (timely disclosures) is returned by the API and MCP 24 hours after the disclosure time (from 2026-11-13). Within 24 hours, rows of timely disclosures, dividends, dividend changes, splits, delisting schedules, earnings-release periods and earnings forecasts are left out, and TDnet PDFs (filing-document) return 403 tdnet_embargo with the time they become available (availableAt). Latest values (quote, key-metrics-latest, screener and so on) have no previous value to fall back to, so for stocks with a TDnet document in the last 24 hours the fields computed from documents (PER, PBR, dividend yield, market cap and so on) are null; prices and price changes are unaffected. The response headers X-TDnet-Embargoed-Count, X-TDnet-Embargoed-Symbols and X-TDnet-Embargo-Next-Release tell what was held back and when it becomes available. The boundary is disclosure time + 24 hours <= response time, compared in absolute time rather than Japan time. For shareholder benefits and dividend policies, versions sourced from TDnet are held back for 24 hours and the previous version is returned when there is one (versions from EDINET or company IR pages are not affected). Rows whose TDnet disclosure time is unknown are not returned. Calls whose whole content is held back (a list that is empty only because of this rule, or a single stock whose affected latest fields are all null) do not use tokens; calls where only part is held back do. EDINET filings (annual, extraordinary and large-holding reports) and stock prices are not affected.

    Endpoints:/disclosures/events-feed/filing-document/dividend-changes/dividends/dividends-calendar/dividends-bulk/dividend-streaks/splits/delisting-schedule/income-statement/balance-sheet-statement/cash-flow-statement/key-metrics/income-statement-short/balance-sheet-statement-short/cash-flow-statement-short/key-metrics-short/key-metrics-bulk/financial-statement-full/earnings-forecast/sga-breakdown/valuation-history/market-cap-history/quote/key-metrics-latest/batch-quote/batch-key-metrics-latest/market-capitalization/profile/screener/rankings/peers/screener-presets/industry-benchmarks/shareholder-benefits/shareholder-benefits-list/dividend-policy/dividend-policies

  • By designTOKYO PRO Market companies have no financials

    TOKYO PRO Market (the market for professional investors) companies file no XBRL results, so their financials are not ingested; statements and the metrics and market capitalization calculated from financials or share counts are empty or null. Describe them as "financials not covered", not as missing data. Market-wide aggregates (rankings, market-breadth and so on) also exclude this market by default.

    Endpoints:/income-statement/balance-sheet-statement/cash-flow-statement/income-statement-short/balance-sheet-statement-short/cash-flow-statement-short/financial-statement-full/key-metrics/key-metrics-short/key-metrics-latest/market-capitalization/market-cap-history/valuation-history/profile

  • By designRight after listing, prior-year income and ratios can be empty

    The first earnings release after listing does not include full-year income for the prior year, so for newly listed companies the pre-listing income statement is empty and the prior-year row has only total assets and net assets. Before the first results, market cap and PER/PBR history are empty too. Describe it as "income before listing not covered".

    Endpoints:/income-statement/income-statement-short/valuation-history/market-cap-history/key-metrics-short

  • By designQuarterly income figures are year to date

    Q2 and Q3 income and cash-flow figures are cumulative from the start of the fiscal year. Listing them as single-quarter revenue makes Q3 look large. Subtract the previous quarter's cumulative value to get a single quarter, and use key-metrics for trailing-twelve-month (TTM) values.

    Endpoints:/income-statement/cash-flow-statement/income-statement-short/cash-flow-statement-short/key-metrics

  • By designPeriods before and after a switch from consolidated to standalone do not connect

    Each statement period carries a consolidation flag (consolidated or nonconsolidated). For companies that moved from consolidated to standalone reporting, or that became a different business through a share exchange, the reporting scope changes at that point, so prior-period-end values and growth rates do not connect across it. Align consolidation before comparing across periods.

    Endpoints:/income-statement/balance-sheet-statement/cash-flow-statement/income-statement-short/balance-sheet-statement-short/cash-flow-statement-short/financial-statement-full

  • By designJPY amounts and missing-field reasons in foreign-currency statements

    reportedCurrency identifies the statement currency. Available JPY amounts are returned. nullReasons identifies missing fields, including non_jpy_material for unavailable JPY amounts and source_missing:operating_income when the statement lacks operating income used for the margin. Foreign-currency rows without any JPY amount retain nullReason = non_jpy_material.

    Endpoints:/income-statement/balance-sheet-statement/cash-flow-statement

  • By designGross profit scope differs for companies with other operating revenue

    For companies that report operating revenue (such as retailers), revenue = net sales (netSales) + other operating revenue (otherOperatingRevenue), and whether grossProfit includes the latter depends on the company (grossProfitIncludesOtherOperatingRevenue). Use operatingGrossProfit (or grossProfit when it is null) to compare companies. Adding other operating revenue to grossProfit before subtracting SG&A can count it twice.

    Endpoints:/income-statement/income-statement-short/financial-statement-full

  • By designFor annual reports with both Japanese GAAP and IFRS statements, financial-facts and the statements can look different

    For companies whose annual report includes both Japanese GAAP and IFRS statements (2130, 436A, 4494, 6532 and others), the summary of business results in financial-facts comes from the Japanese GAAP tables, while balance-sheet-statement and the other statement endpoints use the IFRS tables the company has adopted, so totals such as total assets can look different. Both are as filed. accountingStandard in financial-facts is the standard declared for the whole document, so rows with Japanese GAAP tags also show IFRS. Check which table a value comes from by its tag name, not by accountingStandard. A trailing _notes in a tag name is added when ZENITH ingests the data and is not part of the original tag.

    Endpoints:/financial-facts/balance-sheet-statement/income-statement/cash-flow-statement

  • Easy to misreadOperating income is not always gross profit minus SG&A

    Under Japanese GAAP, operating income = (operatingGrossProfit ?? grossProfit) − SG&A − (otherOperatingExpenses ?? 0). For companies with other operating revenue or with operating-expense lines besides SG&A, computing only grossProfit − SG&A does not match and looks like an error. Use this formula when you check the numbers.

    Endpoints:/income-statement/income-statement-short/financial-statement-full

  • Easy to misreadEPS can be negative even with positive net income

    Companies that deduct dividends on class shares when computing common-share EPS can show negative EPS even with positive net income, as in their earnings releases (7412 and 8836). A sign difference between net income and EPS is not an error by itself.

    Endpoints:/income-statement/key-metrics

  • Easy to misreadactualEps and estimateEps in earnings-calendar are for the quarter alone, not year to date or full year

    actualEps (reported) and estimateEps (estimate) in earnings-calendar are both earnings per share (yen) for that quarter alone (three months). Rows whose fiscalPeriod is FY also cover only the fourth quarter, not the full year. estimateEps is the market consensus, not the company forecast. Quarterly EPS in income-statement is cumulative from the start of the fiscal year, so the values differ (for 6230 in Q2, actualEps is 21.16 and the year-to-date figure is 38.27). Use the same basis, single quarter or year to date and full year, when you compare. Values are null for rows before the announcement, for reported rows whose results are not in yet, and for issues or periods without an estimate.

    Endpoints:/earnings-calendar/income-statement/income-statement-short

  • FixedStandalone income for periods with a first subsidiary at year end is back

    When a company acquired its first subsidiary at year end, the annual report had a consolidated balance sheet only and standalone income and cash-flow statements only, and those periods were missing entirely from the annual income and cash-flow data (12 periods, including 5572, 9262, 7370 and 3370). Those periods now return income and cash flow flagged consolidation: nonconsolidated, while the same period's balance sheet is consolidated. Mind the flag when comparing with adjacent periods.

    Fixed in: version 79 and data platform #3177 (2026-11-03)Endpoints:/income-statement/cash-flow-statement/income-statement-short/cash-flow-statement-short

  • FixedPeriods with no values are no longer returned

    Previously, rows for periods with every value null and no source could be returned (some cash-flow periods for 648A and 624A, for example). Since version 48, periods with no values are not returned (except non-yen periods, which come with nullReason). An all-null row in an older response does not mean results existed for that period.

    Fixed in: version 48 (2026-11-02)Endpoints:/income-statement/balance-sheet-statement/cash-flow-statement/income-statement-short/balance-sheet-statement-short/cash-flow-statement-short/financial-statement-full

visibility_off
The screens and numbers in these articles leave out stock prices and metrics calculated from them. Before showing live data on your own screens, check what you may display. What you can display
gavel

Disclaimer

This page explains how to use a Japanese equity data API and how its data is defined. It is not a solicitation to invest or a recommendation to buy or sell any security. The content reflects information at the time of writing and is not guaranteed to be accurate or complete. Investment decisions are your own responsibility.

What you may show or provide to third parties depends on your plan and Article 8 of the Terms. Exchange data such as stock prices may not be shown to third parties on any plan. Edited or processed information from which the original stock prices or similar market data can be readily reconstructed is treated as exchange data and may not be displayed or redistributed to third parties. No plan or separate agreement with us overrides this restriction. Terms, Article 8 · Data sources and terms of use