Docs menuexpand_more
travel_exploreTry in the API Viewer

Guides

Reference

Other pages

Endpoints

search
appsAll APIs
functionHow metrics are calculated

Cookbook · Applied · Analysis 2

Compare competitors' segment revenue and profit with an API: business mix and margins

Turn the segment note of Japanese annual reports into one table: business mix, segment margins and capex, with totals separated, revenue reconciled and Python code.
For companiesFor investors8 min read
open_in_newIllustrated series on Qiita (Japanese)The same topic is also published as an illustrated series on Qiita.

Endpoints used

A company's total revenue and margin are easy to find in its kessan tanshin (earnings summary). The questions in a management meeting go one level down: which business earns the profit, and which business gets the capital spending? This page pulls the segment note of Japanese annual securities reports through an API and turns competitors' segment revenue, profit and capex into one table.

The examples use fiscal-year data for the year ended March 2026 for Toyota Motor (7203) and Suzuki Motor (7269), retrieved from ZENITH Code on October 29, 2026.

What you will get from this page

  • How to take only the reportable-segment table from /segments and turn it into one row per segment
  • Rules for separating total and adjustment rows, such as 連結 (consolidated) or 消去又は全社 (eliminations or corporate), from business rows
  • An example of how much a margin moves depending on whether intersegment sales are in the denominator
  • A reconciliation against income-statement revenue that catches misread rows
  • When a year-over-year comparison is valid

Common ways segment comparisons go wrong

Each company defines its own segments, so names and counts differ. Copying them into a spreadsheet invites four mistakes.

  • Adding parts to totals. The table also has rows for the consolidated total, subtotals and eliminations. Summing everything nearly doubles the number.
  • Mixing in geographic tables. Besides the reportable-segment table, an annual report has "related information" tables by product or service and by region. "Japan" or "North America" there is a different table's number.
  • Inconsistent margin denominators. Whether intragroup (intersegment) sales are in the denominator can change a margin dramatically.
  • Comparing across a reorganization. Matching similarly named segments across a resegmentation year counts a change in scope as growth.

An API removes the copying, but you still need a rule for each of these. The code below writes every one of them down.

The shape of the /segments response

/segments returns the segment note of an annual securities report as one row per segment and metric. Each call costs one token.

Field Contents
items Rows of the reportable-segment table only. No related-information rows
relatedItems Rows of related-information tables, each with tableKind: product_service, geographic or condensed_statements (condensed statements by business)
unitMultiplier The table's unit, such as 1000000 for millions of yen. Multiply value by it to get yen
note Why items is empty, when it is (a single-segment company, or a table layout that could not be read)
fiscalPeriod, docId, submittedAt Fiscal period, document ID and filing time

Each row in items has segment (the segment name), metric (what the number is), rawLabel (the row heading in the filing) and value. This page uses five metrics.

metric Meaning
net_sales_external Sales to external customers
net_sales_intersegment Intersegment sales or transfers
segment_profit Segment profit or loss
capital_expenditure Increase in property, plant and equipment and intangible assets
depreciation Depreciation and amortization

rawLabel varies by company: Toyota writes 外部顧客への営業収益 and Suzuki writes 外部顧客からの売上収益. Decide what a row means from metric, not from rawLabel.

Turn one company's rows into one row per segment

First, group the incoming rows by segment name and lay out sales, profit and capex side by side.

import csv, json, os, re, urllib.parse, urllib.request
from urllib.error import HTTPError

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

FIELDS = {
    "net_sales_external": "external",
    "net_sales_intersegment": "intersegment",
    "segment_profit": "profit",
    "capital_expenditure": "capex",
    "depreciation": "depreciation",
}


def get(path, **params):
    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 fetch_segments(symbol, fiscal_period=None):
    params = {"symbol": symbol}
    if fiscal_period:
        params["fiscalPeriod"] = fiscal_period
    try:
        return get("/segments", **params)[0]
    except HTTPError as e:
        if e.code == 404:          # no annual securities report
            return None
        raise

Next, classify each segment by its name. Total and adjustment rows never share an axis with business rows. Segment names arrive in Japanese, so the patterns are Japanese too.

# 連結 = consolidated, 合計/計/総計 = total, 報告セグメント計 = reportable segments total
TOTAL = re.compile(r"^(連結|連結計|合計|計|総計|報告セグメント計|セグメント計)$")
# 消去 = elimination, 調整 = adjustment, 全社 = corporate, セグメント間 = intersegment
ADJUST = re.compile(r"消去|調整|全社|セグメント間")


def kind(name):
    n = re.sub(r"\s", "", name)
    if TOTAL.match(n) or n.endswith("計上額"):       # "...amount on the consolidated statements"
        return "total"
    # 消去又は全社 is an adjustment row; 自動車事業及び消去 is a business (事業) reported with eliminations
    if ADJUST.search(n) and "事業" not in n:
        return "adjustment"
    return "segment"


def segment_rows(doc):
    mult = doc.get("unitMultiplier")
    rows, conflicts = {}, set()
    for item in doc["items"]:
        field = FIELDS.get(item["metric"])
        if field is None:
            continue
        name = item["segment"].strip()
        row = rows.setdefault(name, {"segment": name, "kind": kind(name)})
        value = None if item["value"] is None or mult is None else item["value"] * mult
        if field in row and row[field] != value:
            conflicts.add((name, field))   # two different values for one segment and metric
        row[field] = value
    for name, field in conflicts:
        rows[name][field] = None           # do not pick a winner
    return list(rows.values())

Three rules are built in.

  • Convert to yen. Multiply value by unitMultiplier. If the unit is unknown (unitMultiplier is null), leave the amount blank.
  • Two different values for the same segment and metric means neither is used. Picking one leaves you unable to explain the number in the deck.
  • Name rules grow over time. Disclosure wording varies. When you meet a new pattern, add it to TOTAL or ADJUST.

Compute margins and the business mix

Keep both versions of the margin.

def share(a, b):
    return None if a is None or b is None or b <= 0 else a / b


def add_ratios(rows):
    segs = [r for r in rows if r["kind"] == "segment"]
    total_external = sum(r.get("external") or 0 for r in segs)
    for r in rows:
        ext, inter = r.get("external"), r.get("intersegment")
        gross = None if ext is None else ext + (inter or 0)
        r["marginOnExternal"] = share(r.get("profit"), ext)
        r["marginOnTotal"] = share(r.get("profit"), gross)
        r["mix"] = share(ext, total_external) if r["kind"] == "segment" else None
    return rows

The mix uses business rows only. Totals and adjustments stay out of both the numerator and the denominator.

Reconcile the segment total with reported revenue

If a total or breakdown row slips past the name rules, the mix goes wrong. To catch that, add up external sales across business rows and compare the sum with income-statement revenue for the same fiscal year. External sales across all segments should come very close to company-wide revenue.

def coverage(symbol, fiscal_period, rows):
    income = get("/income-statement", symbol=symbol, period="annual", limit=3)
    year = next((y for y in income if y["fiscalPeriod"] == fiscal_period), None)
    revenue = year and year["revenue"]
    total = sum(r.get("external") or 0 for r in rows if r["kind"] == "segment")
    return share(total, revenue)            # None without a matching fiscal year

If the result is off by more than 1%, check the table in the filing. Rounding to the table's unit (often millions of yen) can make the sum differ slightly from revenue, so it does not have to be exactly 1.

Put several companies into one CSV

Finally, write all competitors to a long table, one row per company and segment. A long table drops straight into an Excel pivot table, by company or by segment.

COLS = ["symbol", "fiscalPeriod", "docId", "segment", "kind", "external", "intersegment",
        "profit", "marginOnExternal", "marginOnTotal", "mix", "capex", "depreciation", "coverage"]


def run(symbols, path="segments.csv"):
    with open(path, "w", newline="", encoding="utf-8-sig") as f:
        w = csv.DictWriter(f, fieldnames=COLS)
        w.writeheader()
        for symbol in symbols:                    # one company at a time
            doc = fetch_segments(symbol)
            if doc is None or not doc["items"]:
                reason = "no annual report" if doc is None else doc.get("note") or "no segments"
                w.writerow({"symbol": symbol, "segment": reason})
                continue
            rows = add_ratios(segment_rows(doc))
            cov = coverage(symbol, doc["fiscalPeriod"], rows)
            for r in rows:
                w.writerow({**{c: r.get(c) for c in COLS}, "symbol": symbol,
                            "fiscalPeriod": doc["fiscalPeriod"], "docId": doc["docId"],
                            "coverage": cov})


run(["7203", "7269", "7267", "7270", "7261", "7201"])

When items is empty, the script writes the note text as its own row. Silently dropping the company would make "no segment data" indistinguishable from "failed to fetch." Each company costs two tokens (/segments and /income-statement), so six companies cost 12.

Sample output: Toyota Motor, fiscal year ended March 2026

Rounded to ¥100 million (oku yen, the unit Japanese decks commonly use), the CSV reads:

Segment Kind External sales Segment profit Margin (external) Capex Depreciation
Automotive (自動車) business 452,019.2 27,770.5 6.1% 24,536.4 14,172.4
Financial services (金融) business 48,190.0 8,517.2 17.7% 35,119.4 9,204.3
All other (その他) business 6,640.3 1,320.8 19.9% 647.5 548.5
Eliminations/corporate (消去又は全社) adjustment — 53.7 — 294.5 —
Consolidated (連結) total 506,849.5 37,662.2 7.4% 60,597.8 23,925.2

By sales, the mix is automotive 89.2%, financial services 9.5% and all other 1.3%. A slide that shows only the sales mix makes Toyota look like a pure carmaker. By segment profit, though, financial services' ¥851.72 billion is more than a fifth of the total. When the question is where the money is made, show sales and profit together.

External sales across the business rows add up to ¥50.68 trillion, matching income-statement revenue. The reconciliation value is 1.000, or 100.0% on screen.

Margins depend on the denominator

Toyota's "all other" segment sells ¥664.03 billion to external customers and ¥987.39 billion to other segments. Most of its sales stay inside the group.

Denominator Margin
External sales (¥664.03 billion) 19.9%
Sales including intersegment (¥1.65 trillion) 8.0%

The same segment's margin more than doubles depending on the denominator. If your figure disagrees with the company's investor presentation, check the denominator first, and always state which one you used.

Putting the mix next to a competitor's

For the fiscal year ended March 2026, Suzuki's mix was automobiles (四輪事業) 90.7%, motorcycles (二輪事業) 7.2%, marine (マリン事業) 1.9% and other (その他事業) 0.2%. That looks close to Toyota's automotive 89.2%, but each company draws its own segment boundaries. "Automotive" and "automobiles" need not cover the same scope. Do not combine segments across companies or match them by name. Show each company's segments as reported.

Comparing with the prior year

Fetch the prior year by passing its fiscal period to fiscalPeriod, for example fiscalPeriod=2025-03 for Toyota.

def comparable(now_rows, prev_rows):
    names = lambda rows: sorted(r["segment"] for r in rows if r["kind"] == "segment")
    return names(now_rows) == names(prev_rows)

Show a year-over-year change only when the business segment names match exactly in both years. If a single character differs, skip it. In a reorganization year, the annual report may restate the prior year under the new segments. To compare across a reorganization, read that note in the filing.

Reading the numbers correctly

Regional and product figures live in relatedItems

items holds the reportable-segment table only. Regional and product-or-service tables come back in relatedItems, labeled with tableKind. The same name can carry a different value in a different table. The API docs give Kuraray (3405) as an example: external sales of its vinyl acetate business are 387,169 in the reportable-segment table and 398,582 in the products-and-services table (both in millions of yen). For a regional mix, use the geographic rows in relatedItems, and never mix them with items.

When items is empty, read note

An empty items comes with a reason in note. 「単一セグメント(区分の表なし)」 means a single-segment company, including companies that omit other segments as immaterial. 「表パース未対応の様式(原文はtext_blocks参照)」 means the filing has a segment table, but the current-year rows could not be read. For those companies, read the original section with /text-blocks. Neither case means zero.

Segment capex is not cash-flow capex

Segment capital_expenditure is the increase in property, plant and equipment and intangible assets. The cash flow statement's capitalExpenditure is purchases of property, plant and equipment only. The segment total and the cash-flow figure usually do not match. Also note that Toyota's financial services capex (¥3.51 trillion) exceeds automotive capex (¥2.45 trillion). Each company defines capex in its notes, and some businesses include assets quite unlike factory equipment. Read the note before comparing capex across businesses.

Segment data comes from the annual securities report

Segments come from the annual securities report (yuho), which is filed after the earnings release. Right after a kessan tanshin, the income statement may already show the new year while segment data still shows the previous one. That is why the reconciliation requires matching fiscal periods. Check the fiscalPeriod column to see which year each row covers.

Segment names and rawLabel stay in Japanese

segment and rawLabel keep the filing's text and come back in Japanese even with lang=en. For English material, use the standard heading for each metric (labelEn) as the line item and translate segment names yourself.

Some period-end dates are filled in by the API

When periodEndInferred is true, the data platform left the period-end date empty and the API filled it in from the same filing. The value itself comes from the filing's table. You only need this flag when sorting by period-end date.

Adapting it to your company

  • For a mix chart, plot kind == "segment" rows only, and list totals and adjustments in a lighter row below. Drawing the whole and its parts on one axis makes bar lengths meaningless.
  • A mapping table ("their segment X corresponds to our business A") has to be built by a person and attached to the deck. API values are the raw material.
  • To drill into one company with a screen, try the company deep-dive template. Its saved demo opens without an API key.

Related

An illustrated series on the same material is on Qiita (in Japanese).

This page explains how to handle 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 designSingle-segment companies have no segment table

    For single-segment companies, segments returns an empty items array with the note "単一セグメント(区分の表なし)" (single segment, no segment table). This is not missing data; take company-wide figures from income-statement. For the few companies whose table format cannot be parsed (two, including 9432), the note is "表パース未対応の様式" (unsupported table format) and the data is not covered.

    Endpoints:/segments

  • 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 designCapital expenditure covers tangible assets only

    capitalExpenditure is only the cash-flow line for purchases of property, plant and equipment and excludes intangible assets. Companies that report tangible and intangible purchases under one combined heading have no tangible-only line, so the value is null. A combined tangible-plus-intangible figure is planned.

    Endpoints:/cash-flow-statement/cash-flow-statement-short/segments

  • 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 misreadSum only rows whose role is null

    Besides business rows, items in segments also contains total, subtotal, consolidated and adjustment rows as they appear in the filing. These rows are marked by role (total, subtotal, consolidated or adjustment) and isTotal. When adding up sales or profit across business segments, sum only rows whose role is null; adding every row counts the totals more than once.

    Endpoints:/segments

  • 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

  • FixedSegment and workforce tables were rebuilt for all periods

    Between Oct 29 and Nov 3, errors such as units or footnote marks in segment names, related-information rows mixed into reportable segments, two values for "total", quarterly three-month rows alongside year-to-date rows, and employee segments summed over three years were fixed and all periods were rebuilt. An equity-method loss entered with a positive sign was corrected to negative on Nov 2 (3696). Fetch segment data again if you saved it earlier.

    Fixed in: data platform rebuild; versions 34 and 35 (2026-10-29 to 2026-11-03)Endpoints:/segments/workforce

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