# Compare risk factors across Japanese competitors: pull annual report text by API and line up the headings in Python

Pull the "business risks" and "issues to address" sections of Japanese annual securities reports by API, split them into headings in Python, and compare five competitors. Covers keyword counts per heading and filings that paste text as images.

The risk section of a Japanese annual securities report (*yuka shoken hokokusho*, or *yuho*, roughly Japan's 10-K) comes back from `/stable/text-blocks` with `tag=risks`: one call per company. Split the body into headings by the markers at the start of each line, and you can see which risks each competitor treats as a heading of its own, and how it groups them, before reading every page.

This guide builds four things with nothing but the Python standard library:

- A table of section length, heading count and image count per company
- A table of where a keyword (for example 為替, foreign exchange, or 関税, tariffs) appears, heading by heading
- A CSV with one heading per row, ready to sort in a spreadsheet
- A prompt for an AI assistant that contains only headings and sources, not the body text

The examples use the reports for the fiscal year ended March 2026 of Toyota Motor (7203), Denso (6902), Honda Motor (7267), Mazda Motor (7261) and Tein (7217). All figures were counted from API responses retrieved at 14:48 Japan time on October 31, 2026.

The reports are written in Japanese, and so is the text the API returns. Keywords have to be Japanese too; the guide gives English glosses.

## Decide what to compare first

Line up the same section and the same fiscal period. If either drifts, the comparison table compares nothing.

These are the `text-blocks` aliases most useful for peer comparison:

| Alias (`tag`) | Section of the annual report | What a comparison shows |
|---|---|---|
| `risks` | Business risks (事業等のリスク) | How risks are grouped, which ones get their own heading |
| `policy` | Management policy, business environment and issues to address | Where the issues sit, how many pillars a mid-term plan has |
| `mdna` | Management's discussion and analysis | The angles used to explain results |
| `rnd` | Research and development activities | How detailed the R&D write-up is |
| `sustainability` | Sustainability approach and initiatives | How human capital and climate are covered |
| `business` | Description of business | Business segments and their descriptions |

`governance`, `officers`, `remuneration` and `shareholdings` also work. Calling without `tag` returns the report's table of contents, which is the safest way to check what is there.

Without `fiscalPeriod`, each company's latest annual report is used. If you mix March and December year-ends, the "latest" reports are nine months apart. Always keep the fiscal period, document ID and submission time columns in the output.

## Step 1: the request helper and the table of contents

Create an API key after [signing up](https://zenithcode.net/en/sign-up) and send it in the `x-api-key` header. One curl call to the table of contents shows the response shape.

```bash
curl -s -H "x-api-key: YOUR_API_KEY" \
  "https://api.zenithcode.net/stable/text-blocks?symbol=7203"
```

The response is an array. Its first element carries the filing (`docId`, `fiscalPeriod`, `submittedAt`, `sourceUrl`) and `blocks`, the list of sections. Each block has `tag`, `alias` (null when there is no short name), `labelJa` and `chars`.

In Python, one helper does the HTTP work and two small functions sit on top of it. A 404 (no such section or filing) is returned as `None` rather than raised.

```python
import csv
import json
import re
import sys
import unicodedata
import urllib.error
import urllib.parse
import urllib.request

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


def get(path, **params):
    """Return the response array. A 404 (section or filing missing) returns None."""
    url = BASE_URL + path + "?" + urllib.parse.urlencode(params)
    request = urllib.request.Request(url, headers={"x-api-key": API_KEY, "Accept": "application/json"})
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        if error.code == 404:
            return None
        raise


def table_of_contents(symbol):
    """Sections in the report: {alias or tag: length of the original XHTML}."""
    rows = get("/text-blocks", symbol=symbol)
    if not rows:
        return None
    return {b["alias"] or b["tag"]: b["chars"] for b in rows[0]["blocks"]}


def fetch_section(symbol, tag, fiscal_period=None):
    params = {"symbol": symbol, "tag": tag}
    if fiscal_period:
        params["fiscalPeriod"] = fiscal_period
    rows = get("/text-blocks", **params)
    return rows[0] if rows else None
```

With `tag`, the response adds the body `content`, `chars` (length of the returned body) and `htmlChars` (length of the original XHTML). The body is plain text by default, with tables turned into tab-separated lines.

## Step 2: find headings from line markers

The body has no structural markup, so headings are inferred from the marker at the start of each line.

Four rules:

1. Lines starting with （１）, (1), ①, 1., ⅰ), ア., a., 【…】, ＜…＞ or ■ are candidates.
2. A line that ends with 。 (the Japanese full stop) or runs past 60 characters is body text.
3. A short unmarked line directly above the first item of a numbered list, such as (1) or ①, is a group heading.
4. A line repeated three times or more (labels such as ＜リスク＞ "risk" and ＜対応策＞ "response" inside every item) is not a heading.

Levels follow the order in which marker families appear. The first family is level 1, and a family that first appears inside it is one level down. For （１）→①→②→（２）, （１） and （２） are level 1 and ① ② are level 2.

```python
# Marker families. The order in which they appear sets the heading level.
MARKERS = [
    ("paren_num", re.compile(r"^[（(][0-9０-９]{1,2}[）)]")),   # （１） (1)
    ("circled", re.compile(r"^[①-⑳]")),                        # ①
    ("dot_num", re.compile(r"^[0-9０-９]{1,2}[.．]\s*\S")),      # 1. １．
    ("roman", re.compile(r"^[ⅰ-ⅹⅠ-Ⅹ][)）]")),                   # ⅰ)
    ("kana", re.compile(r"^[ア-ン][.．、]")),                    # ア.
    ("alpha", re.compile(r"^[a-zａ-ｚ][.．)）]")),                # a.
    ("bracket", re.compile(r"^[【＜<■].+")),                    # 【…】 ＜…＞ ■
]
MAX_TITLE = 60  # longer lines are body text
# The first item of a numbered list: （１） ① 1. ⅰ) ア. a.
FIRST = re.compile(r"^(?:[（(][1１][）)]|①|[1１][.．]|[ⅰⅠ][)）]|ア[.．、]|[aａ][.．)）])")


def marker_type(line):
    for name, pattern in MARKERS:
        if pattern.match(line):
            return name
    return None


def find_headings(text):
    lines = [line.strip() for line in text.splitlines()]
    found = []
    for number, line in enumerate(lines):
        kind = marker_type(line)
        if kind is None or len(line) > MAX_TITLE or line.endswith("。"):
            continue
        # A short unmarked line right above the first numbered item is a group heading
        above = next((j for j in range(number - 1, -1, -1) if lines[j]), None)
        if FIRST.match(line) and above is not None:
            prev = lines[above]
            if marker_type(prev) is None and len(prev) <= 30 and not prev.endswith("。"):
                found.append({"line": above, "kind": "group", "title": prev})
        found.append({"line": number, "kind": kind, "title": line})
    # Labels repeated under every item are not headings
    counts = {}
    for h in found:
        counts[h["title"]] = counts.get(h["title"], 0) + 1
    found = [h for h in found if counts[h["title"]] < 3]
    # A family not open yet goes one level deeper; an open family closes everything below it
    open_kinds = []
    for h in found:
        if h["kind"] in open_kinds:
            del open_kinds[open_kinds.index(h["kind"]) + 1:]
        else:
            open_kinds.append(h["kind"])
        h["level"] = len(open_kinds)
    return lines, found
```

Rule 2 matters for Denso. Some of its ⅰ) lines are full sentences ending in 。 and drop out; only short lines such as "unexpected changes in laws or regulations" stay. Rule 3 exists for Mazda, which leaves its three group lines unmarked and restarts numbering at (1) under each.

## Step 3: count where a keyword appears

Counts run from a heading's line to just before the next heading, whatever its level. Both body and keyword are NFKC-normalized first, so full-width and half-width characters match.

```python
def norm(s):
    return unicodedata.normalize("NFKC", s)


def keyword_hits(lines, headings, keyword):
    """Occurrences from each heading's line up to the next heading (any level)."""
    word = norm(keyword)
    bounds = [h["line"] for h in headings] + [len(lines)]
    for i, h in enumerate(headings):
        block = "\n".join(lines[bounds[i]:bounds[i + 1]])
        h.setdefault("hits", {})[keyword] = norm(block).count(word)
    return norm("\n".join(lines)).count(word)


def rollup(headings, keyword):
    """Add each sub-heading's count to the level-1 heading above it."""
    out = []
    for h in headings:
        if h["level"] == 1:
            out.append({"title": h["title"], "hits": h["hits"][keyword]})
        elif out:
            out[-1]["hits"] += h["hits"][keyword]
    return out
```

`keyword_hits` returns the count for the whole section. It includes the preamble before the first heading, so it can exceed the sum of the per-heading counts. Use `rollup` to compare at the group level.

## Step 4: line up five companies, write a CSV and a prompt

The last part collects the results. It calls the API one company at a time, never in parallel.

```python
def compare(symbols, tag, keywords):
    results = []
    for symbol in symbols:  # one company at a time, not in parallel
        row = fetch_section(symbol, tag)
        if row is None:
            results.append({"symbol": symbol, "missing": True})
            continue
        lines, heads = find_headings(row["content"])
        totals = {k: keyword_hits(lines, heads, k) for k in keywords}
        results.append({
            "symbol": symbol, "missing": False,
            "fiscalPeriod": row["fiscalPeriod"], "docId": row["docId"],
            "docTypeCode": row["docTypeCode"], "submittedAt": row["submittedAt"],
            "chars": row["chars"], "images": row["content"].count("[画像]"),
            "headings": heads, "totals": totals,
        })
    return results


def write_csv(results, path, keywords):
    with open(path, "w", newline="", encoding="utf-8-sig") as f:  # BOM so Excel reads Japanese correctly
        w = csv.writer(f)
        w.writerow(["symbol", "fiscalPeriod", "docId", "level", "heading", *keywords])
        for r in results:
            for h in r.get("headings", []):
                w.writerow([r["symbol"], r["fiscalPeriod"], r["docId"], h["level"], h["title"],
                            *[h["hits"][k] for k in keywords]])


def headings_prompt(results, section_name):
    """A prompt with headings and sources only. No body text."""
    out = [f'Below are the headings of the "{section_name}" section of each company\'s annual securities report. Body text is not included.',
           "Tabulate the themes all companies share, themes only some have, and differences in how they group them. Answer in English.",
           'Do not guess what the headings do not say; write "check the body text" instead.',
           "Do not forecast figures or comment on buying or selling shares.", ""]
    for r in results:
        if r["missing"]:
            out += [f"## {r['symbol']}: section not found", ""]
            continue
        out.append(f"## {r['symbol']} fiscal period {r['fiscalPeriod']} document {r['docId']}")
        out += ["  " * (h["level"] - 1) + h["title"] for h in r["headings"]]
        out.append("")
    return "\n".join(out)


if __name__ == "__main__":
    symbols = sys.argv[1:] or ["7203", "6902", "7267", "7261", "7217"]
    words = ("為替", "サイバー", "関税", "人材")  # FX, cyber, tariffs, talent
    results = compare(symbols, "risks", words)
    for r in results:
        if r["missing"]:
            print(r["symbol"], "section not found")
            continue
        top = sum(1 for h in r["headings"] if h["level"] == 1)
        print(r["symbol"], r["docId"], r["chars"], len(r["headings"]), top, r["images"],
              *[f"{k}={v}" for k, v in r["totals"].items()])
    write_csv(results, "risks_headings.csv", words)
    with open("risks_prompt.txt", "w", encoding="utf-8") as f:
        f.write(headings_prompt(results, "business risks"))
```

Save it as `risk_headings.py` and run `python3 risk_headings.py`. Pass other securities codes as arguments to compare other companies. `text-blocks` costs 10 tokens per call, so one section for five companies is 50 tokens.

The prompt leaves out the body on purpose. It separates what the headings tell you from what only the text can. Whatever the AI drafts, confirm it against the original on EDINET (`sourceUrl`).

## Example: business risks of five Japanese automakers and suppliers

Here is the script's output for the five companies (reports for the fiscal year ended March 2026, retrieved October 31, 2026).

```text
7203 S100Y8NY 8539 19 3 0 為替=12 サイバー=1 関税=10 人材=4
6902 S100Y9T1 6269 24 3 0 為替=6 サイバー=3 関税=1 人材=1
7267 S100YDD9 10079 18 13 0 為替=2 サイバー=9 関税=3 人材=2
7261 S100YDZ1 5981 20 3 0 為替=7 サイバー=2 関税=1 人材=4
7217 S100YIDI 2575 19 9 0 為替=4 サイバー=0 関税=0 人材=3
```

The columns are securities code, document ID, characters, headings, level-1 headings, images and keyword counts. As a table:

| Company | Characters | Headings | Level 1 | How risks are grouped |
|---|---:|---:|---:|---|
| Toyota Motor | 8,539 | 19 | 3 | Three groups, items ① onward under each |
| Denso | 6,269 | 24 | 3 | Three groups, items ①…, then ⅰ)… (three levels) |
| Honda Motor | 10,079 | 18 | 13 | (1) to (13) side by side, a few split into ①… |
| Mazda Motor | 5,981 | 20 | 3 | Three unmarked groups, (1)… under each |
| Tein | 2,575 | 19 | 9 | (1) to (9), with ① to ⑩ inside (2) |

What the table shows is how each company structures the section.

- Toyota and Mazda use nearly the same three groups: markets and business; finance and the economy; politics, regulation, litigation and disasters. Denso groups by business environment, business activities and other.
- Honda puts 13 items, including geopolitical risk, information security risk and intellectual property risk, at the top level instead of under groups.
- Tein collects ten items, such as exchange-rate movements and competitors, under (2) "risks inherent in business activities".

Information security sits in a different place at each company: item ⑧ under markets and business at Toyota, ⑨ under business activities at Denso, (7) under markets and business at Mazda, and top-level heading (3) at Honda. That is a useful reference point when you compare your own report's structure.

### Look at where a keyword appears, not just how often

Read the per-heading columns of the CSV:

- **為替 (foreign exchange)**: all five have a heading containing the word. Of Toyota's 12 hits, 10 are under "effects of exchange-rate and interest-rate movements" and 2 under "laws, regulations and government action applying to the automotive industry". Tein's hits are split between ④ "exchange-rate movements" inside (2) (1 hit) and the top-level (3) "on exchange-rate movements" (3 hits).
- **関税 (tariffs)**: none of the five has a tariff heading. Of Toyota's 10 hits, 9 are under the laws-and-regulations heading and 1 under "fluctuations in vehicle demand". Honda's 3 are one each under geopolitical risk, economic security and changes in the market environment.
- **サイバー (cyber)**: all 9 of Honda's hits are under information security risk. The word does not appear in Tein's risk section.
- **人材 (talent, human resources)**: every company except Honda has a heading with the word. Honda's 2 hits are under information security risk and changes in the market environment.

With `rollup`, foreign exchange gathers 10 hits under Toyota's "finance and economic risks" and 7 under Mazda's equivalent group. Similar group names do not mean similar contents, so treat counts as a pointer to what to read.

## Use the same functions for "issues to address"

Change the call to `compare(symbols, "policy", words)` to build the same table for the management policy and issues section. Lengths and the level-1 heading that carries the issues:

| Company | Characters | Heading that covers the issues |
|---|---:|---|
| Toyota Motor | 5,789 | （３）会社の対処すべき課題 (issues the company should address) |
| Denso | 1,470 | (3) 対処すべき課題 (issues to address) |
| Honda Motor | 7,113 | (4) 優先的に対処すべき課題 (priority issues to address) |
| Mazda Motor | 7,358 | (2) 経営環境及び対処すべき課題 (business environment and issues) |
| Tein | 2,690 | (5) 事業上及び財務上の対処すべき課題 (business and financial issues) |

This section is written more freely than the risk section. Some companies use initiative names in ［…］ or phase names such as 第１フェーズ (phase 1) as headings, and the Step 2 rules miss some of them. Before comparing heading counts, check the CSV against the original table of contents and add markers to `MARKERS` where needed.

Research and development (`rnd`) is often written without headings. With the rules in this guide, only Toyota (2 headings) produced any. Treat a company with zero headings as one block of text.

## Before you trust the numbers

Some `text-blocks` values look wrong if you misread them.

- **There are two kinds of `chars`.** In the table of contents (no `tag`), `chars` is the length of the original XHTML, a size hint. With `tag`, `chars` is the length of the returned body, and the XHTML length moves to `htmlChars`. For Toyota's risk section, the XHTML is 17,543 characters and the body 8,539. Compare the `chars` of a `tag` response, or `len(content)`.
- **Some companies paste text as images.** Figures, or even the body itself, can be images, and the text inside them is not returned. In the latest reports, the risk sections of 8869, Terumo (4543), 1860 and 1959 are like this. The body carries the marker 「[画像]」 ("image") where each image was, so check the original on EDINET whenever the `images` column is 1 or more, even if a keyword count is zero. If a section is suspiciously short, a few lines of preamble, suspect images first.
- **Zero hits does not mean the topic is absent.** Counts are occurrences of the exact word. A company that writes 円高 (strong yen) instead of 為替 is not counted, and neither is text inside images.
- **Length and heading count do not measure risk.** They measure how finely a company writes. Tables are flattened into text and counted, so table-heavy sections run longer.
- **Headings are inferred.** The report has no structure data, so headings come mechanically from line markers. They may not match what the company intended. Compare with the original table of contents before using them in internal material.
- **The filing is the latest annual report.** Without `fiscalPeriod`, the latest report is used, and an amended report (`docTypeCode` 130) replaces the original when one exists. When fiscal year-ends differ, check the fiscal period column for the time gap.
- **A missing section is a 404.** ETFs and REITs do not have the main sections. A company that has just listed and not yet filed an annual report also returns 404. The `get` helper turns 404 into `None`, so the output says "section not found".
- **Some sections run to hundreds of thousands of characters.** Mind input limits when you send text to an AI model. Narrowing down by headings first, as in this guide, is more reliable.
- **Headings are Japanese only.** The `label` field follows `?lang`, but annual-report section titles exist only in Japanese, so it equals `labelJa` even with `lang=en`.
- **Submission times are UTC.** `submittedAt` is ISO 8601 UTC (ending in Z). Add nine hours for Japan time.

If you reuse report text in material for others, check the [display rules](https://zenithcode.net/en/docs/display-rights) as well.

## Troubleshooting

| Symptom | Where to look |
|---|---|
| Zero headings | The company writes without line markers, or uses a marker not in `MARKERS` |
| A body sentence shows up as a heading | A short marked line that does not end in 。. Lower `MAX_TITLE` or compare with the original contents |
| Levels differ from the original | Levels follow the order of marker families; the first family is level 1 |
| A level-1 count exceeds its sub-headings' sum | Text between the level-1 line and its first sub-heading is counted too |
| Counts differ from your browser's find | This guide normalizes full-width and half-width characters; browser search may not |

## Related links

- [Annual report text sections (`/docs/text-blocks`)](https://zenithcode.net/en/docs/text-blocks)
- [Compare major shareholders, ownership mix and 5% filings across peers](https://zenithcode.net/en/docs/cookbook/applied/deep-shareholders)
- [Benchmark financials against competitors](https://zenithcode.net/en/docs/cookbook/applied/analysis-peer-benchmark)
- [Display rules](https://zenithcode.net/en/docs/display-rights)
- [Sample code repository (disclosure reader template)](https://github.com/Crab-grass/zenith-code-examples/tree/main/templates/disclosure-reader)

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

---
Page: https://zenithcode.net/en/docs/cookbook/applied/deep-annual-report-text
日本語: https://zenithcode.net/docs/cookbook/applied/deep-annual-report-text.md
Site guide for AI tools: https://zenithcode.net/llms.txt
