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 2

Verify operating margin from a financial data API against your own calculation: decimals, percent and percentage points

The API returns operating margin as a 0–1 decimal. Recompute it from yen revenue and operating income, check it against the API, and display it correctly as percent and percentage points, with Node.js code and five years of Toyota data.
For developersFor investors7 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

  • The income statement endpoint returns operating margin as operatingMargin, a 0–1 decimal. It is 0.0998 in the API and 9.98% on screen.
  • Recomputing the ratio from the same row's revenue and operating income catches unit mistakes and explains why a ratio is null.
  • Use percentage points for the difference between two margins and percent for relative change. Figures are for Toyota Motor (7203), retrieved on October 27, 2026.

Operating margin is the share of revenue left as operating income. A chart of amounts alone makes it easy to miss a year where revenue grew but the margin fell. This page puts the API's ratio and your own ratio side by side in one script. It also prevents the classic display bugs, "0.10%" and "998%".

Definition and how the API returns it

Operating margin is operating income divided by revenue.

Operating margin (ratio)   = operating income ÷ revenue         … the form of operatingMargin in the API
Operating margin (percent) = operating income ÷ revenue × 100   … only when you display it

ZENITH Code returns every ratio as a 0–1 decimal. Here is Toyota's row for the fiscal year ended March 2025 (only the fields we need).

{
  "fiscalPeriod": "2025-03",
  "period": "FY",
  "revenue": 48036704000000,
  "operatingIncome": 4795586000000,
  "operatingMargin": 0.09983170369057794
}

4795586000000 ÷ 48036704000000 is 0.0998317…, the same as operatingMargin. As a percentage it is 9.98%. If you print operatingMargin to two decimals you get "0.10", and adding a % sign shrinks the meaning a hundredfold.

Calculate from the yen values, not from rounded figures like ¥4.80 trillion and ¥48.04 trillion. Dividing rounded numbers shifts the trailing digits. Round only right before display.

The definition and the conditions that produce null are also listed in metric definitions: operating margin.

Why recompute a ratio the API already gives you

If operatingMargin is there, you could just display it. There are three reasons to calculate it yourself as well.

  1. It checks your units. If your number and the API's differ by a factor of 100, you have mixed up percent and decimal somewhere.
  2. It explains null. When the API ratio is null, the amounts tell you whether revenue is missing, zero or negative, or operating income is missing.
  3. It is a base for ratios the API does not provide. The same function divides any two fields, such as an SG&A ratio.

Keep in mind that your ratio and the API's come from the same response. A match does not prove the original filing was read correctly. Checking against the filing is a separate step that follows provenance.docId.

One Node.js script to calculate and check

The script below fetches full-year rows from the API (or reads a saved JSON file) and prints both ratios and a status for each fiscal year. It needs Node.js 18 or later and no packages. Save it as margins.mjs.

// Recompute operating margin from yen amounts and check it against the API's operatingMargin.
// Usage: ZENITH_API_KEY=... node margins.mjs 7203
//        node margins.mjs --file income-7203.json   (reuse a saved response; no API call)
import { readFile, writeFile } from "node:fs/promises";

const BASE_URL = "https://api.zenithcode.net/stable";
const isNum = (v) => typeof v === "number" && Number.isFinite(v);

async function loadRows(args) {
  if (args[0] === "--file") return JSON.parse(await readFile(args[1], "utf8"));
  const symbol = args[0];
  const url = `${BASE_URL}/income-statement?symbol=${encodeURIComponent(symbol)}&period=annual&limit=10`;
  const res = await fetch(url, { headers: { "x-api-key": process.env.ZENITH_API_KEY ?? "" }, redirect: "error" });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const rows = await res.json();
  await writeFile(`income-${symbol}.json`, JSON.stringify(rows, null, 2));
  return rows;
}

// Check one row. `own` is your ratio (0–1 decimal); `api` is the API's ratio.
function marginCheck(row, numerator = "operatingIncome", apiField = "operatingMargin") {
  const revenue = row.revenue, income = row[numerator], api = row[apiField];
  const own = isNum(revenue) && revenue > 0 && isNum(income) ? income / revenue : null;
  let status;
  if (own === null && api == null) status = "both missing";
  else if (own === null) status = "cannot compute";
  else if (api == null) status = "API null";
  else status = Math.abs(own - api) <= 1e-9 ? "match" : "mismatch";
  return { fiscalPeriod: row.fiscalPeriod, own, api: isNum(api) ? api : null, status };
}

const pct = new Intl.NumberFormat("en-US", { style: "percent", minimumFractionDigits: 2, maximumFractionDigits: 2 });
const show = (ratio) => (ratio === null ? "—" : pct.format(ratio));

const rows = (await loadRows(process.argv.slice(2)))
  .filter((r) => r.period === "FY")
  .sort((a, b) => a.fiscalPeriod.localeCompare(b.fiscalPeriod));

let previous = null;
for (const row of rows) {
  const m = marginCheck(row);
  // The difference between two margins is in percentage points. Subtract unrounded values
  const diff = previous?.own != null && m.own !== null ? `${((m.own - previous.own) * 100).toFixed(2)} pp` : "—";
  console.log([m.fiscalPeriod, show(m.own), show(m.api), m.status, diff].join("\t"));
  previous = m;
}

The first run takes a securities code and calls the API. The response is saved to income-7203.json, so later runs can read it with --file. You do not need to call the API every time you change the output.

export ZENITH_API_KEY="YOUR_API_KEY"
node margins.mjs 7203
node margins.mjs --file income-7203.json

Five statuses

marginCheck() sorts each year into one of five statuses.

Status Meaning What to do
match Your ratio and the API's differ by 0.000000001 or less Use it
mismatch Both exist but differ Check you used the same row, the same units and revenue as the denominator
API null You could compute it from the amounts, but the API ratio is missing See whether a null condition below applies
cannot compute Revenue missing, zero or negative, or operating income missing Look at why the amounts are null
both missing Neither exists The industry or accounting standard may have no such profit line

The script avoids === because floating-point division can leave tiny differences in the last digits. It checks whether the absolute difference is small enough.

Do not rewrite "mismatch" or "API null" as "match" to make the output look clean. Keeping the status tells you which years to investigate.

Let Intl.NumberFormat handle percentages

Intl.NumberFormat with style: "percent" takes a 0–1 decimal, multiplies by 100 and adds %. If you pass a value you already multiplied by 100, you get "998.32%". Multiply by 100 in exactly one place. The same applies to spreadsheets: apply the percent format to the decimal column.

Output: Toyota, fiscal years ended March 2021–2025

From the response retrieved on October 27, 2026, the rows for FY2021 through FY2025 print as follows. Columns are fiscal period, your ratio, the API ratio, status and the change from the previous year.

2021-03	8.08%	8.08%	match	—
2022-03	9.55%	9.55%	match	1.47 pp
2023-03	7.33%	7.33%	match	-2.21 pp
2024-03	11.87%	11.87%	match	4.54 pp
2025-03	9.98%	9.98%	match	-1.89 pp

All five years match. As a table (amounts rounded to trillions; ratios computed from yen):

Fiscal year ended Revenue (¥ tn) Operating income (¥ tn) Operating margin Change
March 2021 27.21 2.20 8.08% —
March 2022 31.38 3.00 9.55% +1.47 pp
March 2023 37.15 2.73 7.33% −2.21 pp
March 2024 45.10 5.35 11.87% +4.54 pp
March 2025 48.04 4.80 9.98% −1.89 pp

In the year ended March 2025, revenue rose but operating margin fell from 11.87% to 9.98%. That shift is hard to see in amounts alone. The table does not say why. For cost and expense movements, look at costOfRevenue and sellingGeneralAndAdministrativeExpenses in the same response, or the company's own materials.

Percent, percentage points and relative change

Write the difference between two margins in percentage points. Operating margin for the year ended March 2025 was about 1.89 percentage points lower than the prior year.

Difference (pp)       = 9.983170… − 11.870263… = −1.887093… pp
Relative change (%)   = 9.983170… ÷ 11.870263… − 1 = −15.90%

The same two values give "down 1.89 points" and "down 15.90%". The first is a difference; the second is the change relative to the prior margin. "Down 1.89%" leaves readers guessing which you mean. When you show a difference, label it as points.

Compute both from unrounded values. Subtracting the displayed 9.98 and 11.87 happens to give −1.89 here, but rounding error becomes visible with small ratios.

Check other margins with the same function

marginCheck() takes the numerator field and the API ratio field as arguments, so net margin and ordinary-income margin work the same way. Append this to the script.

// Check other margins on the latest full-year row
const latest = rows.at(-1);
for (const [numerator, field] of [["netIncome", "netMargin"], ["ordinaryIncome", "ordinaryMargin"]]) {
  const m = marginCheck(latest, numerator, field);
  console.log(field, show(m.own), show(m.api), m.status);
}

The numerator of netMargin is net income attributable to owners of the parent (netIncome). Ordinary income is a profit subtotal specific to Japanese GAAP, so for IFRS and US GAAP filers ordinaryIncome and ordinaryMargin are mostly null. Toyota reports under IFRS, and in the documentation sample response both are null, so the status is "both missing". That means the line does not exist, not that data is missing.

Gross margin (grossMargin) follows the same idea, but it is null for companies that do not present gross profit. In Toyota's sample response, grossProfit and grossMargin are both null.

The same check in Python

In Python the core is a few lines. Use math.isclose with a tolerance.

import math

def operating_margin(row):
    revenue, income = row.get("revenue"), row.get("operatingIncome")
    if not isinstance(revenue, (int, float)) or revenue <= 0 or not isinstance(income, (int, float)):
        return None
    return income / revenue

own = operating_margin(row)
api = row.get("operatingMargin")
status = "match" if own is not None and api is not None and math.isclose(own, api, abs_tol=1e-9) else "check"
print(f"{own:.2%}" if own is not None else "—")  # :.2% multiplies by 100 and adds %

Python's :.2% format also takes a 0–1 decimal and multiplies by 100. As with Intl.NumberFormat, do not multiply first.

Reading the numbers correctly

When the ratio is null, and negative values

operatingMargin is null when revenue is zero, negative or missing. It is also null in industries without an operating income line, such as insurers. Years with an operating loss return a negative value. "0–1 decimal" describes the format, not a range the value must stay in. Do not clip negative margins to zero in charts or tables.

The denominator revenue is not always the "net sales" line

The API's margins use revenue as the denominator. revenue is the top line the company leads with. For retailers that headline operating revenue, it is net sales plus other operating revenue, so it will not match a margin computed on the "net sales" line (netSales). For banks and insurers the denominator is ordinary revenues, and for securities firms it is operating revenues, so their margins are not on the same scale as other companies' (revenue definition).

Company-reported margins may differ in the last digit

Margins that companies print in earnings summaries or presentations are often rounded, for example to one decimal place, and the denominator choice varies by company. The API's ratios are unrounded. A difference in the last digit does not by itself mean an error.

Quarterly rows give cumulative margins

If you request quarterly rows, for example with period=quarter, Q2 and Q3 revenue and operating income are cumulative from the start of the fiscal year. Their operatingMargin is a ratio of cumulative values, not a three-month margin, and it is not annualized. For single-quarter margins, subtract cumulative values to get each quarter first, then divide (period basis).

The change column compares with the previous row

The script's change column compares each year with the row before it. If a year is missing, or a shortened transition year sits in between, the change is no longer year over year. Check that fiscalPeriod steps by one year and that fiscalPeriodDays covers about 12 months.

Troubleshooting

Symptom What to check
Shows "0.10%" You added % to a 0–1 decimal without multiplying by 100
Shows "998.32%" You multiplied by 100 and then also used a percent format
Status is "mismatch" You divided by netSales, or by rounded amounts
Status is "API null" The industry may have no operating income line; check the rows are from the same period
HTTP 401 / 403 / 429 Key entry and status, plan coverage, quota
--file prints nothing Is the saved JSON an array? Does it contain rows with period = FY?

Related docs and articles

A Japanese series with screenshots is available on Qiita.

This page explains how to calculate financial ratios. 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