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

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

```text
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).

```json
{
  "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](https://zenithcode.net/en/docs/metrics#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`.

```javascript
// 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.

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

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

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

```javascript
// 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.

```python
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](https://zenithcode.net/en/docs/metrics#revenue)).

### 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](https://zenithcode.net/en/docs/metrics#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

- [Income statement (income-statement)](https://zenithcode.net/en/docs/income-statement)
- [Metric definitions: operating margin](https://zenithcode.net/en/docs/metrics#operating-margin) and [ratio units](https://zenithcode.net/en/docs/metrics#ratio-units)
- [Japanese company revenue and operating income history via API](https://zenithcode.net/en/docs/cookbook/applied/practice-revenue-chart)
- [What to align before comparing two companies](https://zenithcode.net/en/docs/cookbook/applied/practice-compare-two-companies)
- [Choosing fiscal periods and year-over-year changes](https://zenithcode.net/en/docs/cookbook/applied/practice-periods-and-yoy)
- [Public examples on GitHub](https://github.com/Crab-grass/zenith-code-examples) — the `trend` command recomputes margins and checks them against the API (`marginCheck`)

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

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

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