# Track the source of every financial figure: filing IDs, disclosure times, and restatements in tables and CSV

Record which filing every financial figure came from and when it was published, using the provenance object. Covers restatements, missing sources, UTC to JST, and safe CSV export.

Once financial data lands in a report or a model, someone will eventually ask, "Which filing is this number from, and when was it published?" This page shows how to keep the answer next to the number. The ZENITH Code [income statement endpoint](https://zenithcode.net/en/docs/income-statement) returns a `provenance` object for every period, and we'll flatten it into tables and CSV files.

- Store one row per period with the filing ID, source type, disclosure time, and any restatement.
- Convert timestamps from UTC to Japan time before you show them.
- Write raw API values to CSV, not the formatted strings you display.

The examples use the annual figures of Toyota Motor (7203), retrieved from the production API on October 27, 2026 at 16:50 JST.

We at [Crabgrass Inc.](https://crabgrass.co.jp/) build [ZENITH Code](https://zenithcode.net/en), an API for financial and disclosure data on Japanese companies. This article is an implementation guide for using our own data.

## Why keep the source with the number

The same "revenue for the fiscal year ended March 2025" can change depending on which filing it came from. A kessan tanshin (earnings summary) is a preliminary release and may later be corrected. When the annual securities report (yuho) comes out, the figure may be replaced with the audited one.

If you store only the numbers, you'll miss problems like these:

- Last month's deck and this month's deck show different revenue for the same year.
- Pre- and post-correction values are mixed in one table.
- A margin you computed uses revenue from a different point in time.

Keeping the filing ID and your retrieval time with each value lets you trace any figure later. It also gives reviewers and internal auditors something concrete to check.

## What's inside provenance

Each period returned by the income statement endpoint carries a `provenance` object. These five fields are always present:

| Field | Meaning |
|---|---|
| `source` | Type of source. `tdnet` = earnings summary (preliminary); `edinet` = securities reports and other statutory filings (final) |
| `docId` | ID of the filing the values came from |
| `announcedAt` | When that filing was published (UTC) |
| `sourceUrl` | Official EDINET viewer link. `null` for TDnet filings and for EDINET filings past the public viewing period |
| `archiveUrl` | PDF served through ZENITH Code (`/stable/filing-document`). Requires an API key |

Some periods have extra fields:

| Field | When it appears |
|---|---|
| `amended`, `amendedDocId`, `amendedAnnouncedAt` | Values were replaced by a correction. The values are post-correction; `docId` still points to the original filing |
| `basis: "summary"` | No full statement was available, so values came from the multi-year summary in the yuho or the tanshin summary page |
| `fieldSources` | Older periods where different fields came from different filings. Keys are field names such as `revenue` and `operatingIncome` |

When `fieldSources` spans more than one filing, `source` is `mixed` and `docId` is `null`. Read the per-field filing IDs from `fieldSources` instead.

Each row also has `updatedAt`, the time the data platform last rebuilt that row. It is not the disclosure date. Rebuilds move it forward, so it can be long after the filing was published.

## Flatten the source into one row per period

`provenance` is nested, which spreadsheets handle poorly. Flatten each period into a single dictionary before saving it.

First, a function that calls the API and records when you fetched the data. The response doesn't include your retrieval time, so capture it yourself.

```python
import json
import os
import urllib.parse
import urllib.request
from datetime import datetime, timezone

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


def fetch_annual_income(symbol: str, limit: int = 5):
    """Fetch up to `limit` fiscal years, newest first, plus the retrieval time in UTC."""
    query = urllib.parse.urlencode({"symbol": symbol, "period": "annual", "limit": limit})
    request = urllib.request.Request(
        f"{BASE_URL}/income-statement?{query}",
        headers={"x-api-key": API_KEY, "Accept": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        rows = json.load(response)
    retrieved_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    return rows, retrieved_at
```

`period=annual` returns full fiscal years (FY) only. `limit` caps the number of rows; the default is 10 and the maximum is 40.

### Convert timestamps to Japan time

`announcedAt` and `updatedAt` are in UTC. Since the November 3, 2026 release, both use ISO 8601 such as `2026-06-10T06:33:00Z`. Data you saved earlier may contain values without an offset, such as `2026-06-10 06:33:00`. Treat those as UTC too.

```python
import re
from datetime import timedelta

JST = timezone(timedelta(hours=9))
_TS = re.compile(r"^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})(?:\.\d+)?(Z|[+-]\d{2}(?::?\d{2})?)?$")


def to_jst(value):
    """Return 'YYYY-MM-DD HH:MM' in JST. Date-only or unparseable values pass through."""
    if not value:
        return ""
    m = _TS.match(value)
    if not m:
        return value
    date, time, tz = m.groups()
    dt = datetime.fromisoformat(f"{date}T{time}")
    if tz in (None, "Z"):
        dt = dt.replace(tzinfo=timezone.utc)  # no offset means UTC
    else:
        digits = tz[1:].replace(":", "")
        offset = timedelta(hours=int(digits[:2]), minutes=int(digits[2:4] or 0))
        dt = dt.replace(tzinfo=timezone(offset if tz[0] == "+" else -offset))
    return dt.astimezone(JST).strftime("%Y-%m-%d %H:%M")
```

For example, Toyota's yuho for the fiscal year ended March 2026 (`S100Y8NY`) has `announcedAt` of `2026-06-10T06:33:00Z`. In Japan time that's 15:33 on June 10. Writing "06:33 on June 10" would put the release nine hours off.

### Build one row per period

```python
def source_row(row: dict, retrieved_at: str) -> dict:
    """Turn one period into a flat row of values and their source."""
    prov = row.get("provenance") or {}
    field_docs = prov.get("fieldSources") or {}
    return {
        "symbol": row["symbol"],
        "fiscalPeriod": row["fiscalPeriod"],
        "period": row["period"],
        "accountingStandard": row.get("accountingStandard"),
        "consolidation": row.get("consolidation"),
        "revenue": row.get("revenue"),
        "operatingIncome": row.get("operatingIncome"),
        "netIncome": row.get("netIncome"),
        "operatingMargin": row.get("operatingMargin"),
        "source": prov.get("source") or "none",
        "docId": prov.get("docId"),
        "announcedAtJst": to_jst(prov.get("announcedAt")),
        "basis": prov.get("basis"),
        "amendedDocId": prov.get("amendedDocId") if prov.get("amended") else None,
        "amendedAtJst": to_jst(prov.get("amendedAnnouncedAt")) if prov.get("amended") else "",
        "fieldSourceDocs": ";".join(f"{k}={v['docId']}" for k, v in sorted(field_docs.items())),
        "rowUpdatedAtJst": to_jst(row.get("updatedAt")),
        "retrievedAtUtc": retrieved_at,
    }
```

Three things matter here:

- When `provenance` is `null`, keep the row and set `source` to `none`. Dropping it hides the fact that a value exists without a stated source.
- Put the correction filing in its own `amendedDocId` column. Overwriting `docId` breaks the link to the original filing.
- Don't store `sourceUrl` or `archiveUrl`. You can rebuild links from the filing ID, and `archiveUrl` only opens with an API key, so it's useless to anyone reading a shared file.

Toyota's fiscal year ended March 2025 becomes this row:

| Column | Value |
|---|---|
| `fiscalPeriod` | `2025-03` |
| `accountingStandard` | `ifrs` |
| `revenue` | `48036704000000` |
| `operatingIncome` | `4795586000000` |
| `operatingMargin` | `0.09983170369057794` |
| `source` | `edinet` |
| `docId` | `S100VWVY` |
| `announcedAtJst` | `2025-06-18 15:30` |

`revenue` is in yen: ¥48.04 trillion. The operating margin is 0.0998 in the API and 9.98% on screen. The disclosure time comes from the sample response in our docs (retrieved October 23, 2026), `2025-06-18T06:30:00Z`, converted to JST.

## Export to CSV

For spreadsheets or other programs, write a CSV. Always write the raw API values, never the strings you formatted for display.

| Value | On screen | In the CSV |
|---|---|---|
| Revenue | `¥48.04 trillion` | `48036704000000` |
| Operating margin | `9.98%` | `0.09983170369057794` |
| Missing | `—` | empty |

Exporting rounded values introduces small errors when someone recalculates from the CSV. Writing "—" for a missing value makes spreadsheets treat the column as text, which quietly breaks sums and averages.

```python
import csv

_FORMULA_PREFIX = ("=", "+", "-", "@", "\t", "\r")


def cell(value):
    """None becomes empty. Strings that could run as formulas get a leading apostrophe."""
    if value is None:
        return ""
    if isinstance(value, str) and value.startswith(_FORMULA_PREFIX):
        return "'" + value
    return value


def write_sources_csv(path: str, rows: list, retrieved_at: str) -> None:
    records = [source_row(r, retrieved_at) for r in sorted(rows, key=lambda r: r["fiscalPeriod"])]
    with open(path, "w", encoding="utf-8-sig", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(records[0].keys()))
        writer.writeheader()
        for rec in records:
            writer.writerow({k: cell(v) for k, v in rec.items()})


rows, retrieved_at = fetch_annual_income("7203", limit=5)
if rows:
    write_sources_csv("7203-income-sources.csv", rows, retrieved_at)
```

- `encoding="utf-8-sig"` adds a byte order mark so Excel opens Japanese text correctly.
- `cell()` prefixes strings that start with `=`, `+`, `-`, or `@` so a spreadsheet won't execute them (CSV injection). Numbers aren't strings, so a negative operating income stays numeric.
- The API returns the newest period first. Sorting oldest first makes charting easier.
- A company with no reported fiscal years returns an empty array. Stop there instead of writing an empty file.

### Verify the CSV

Read the file back and compare it with the API response.

```python
def verify_csv(path: str, rows: list) -> list:
    """Compare the CSV with the API response. An empty list means they match."""
    by_period = {r["fiscalPeriod"]: r for r in rows}
    problems = []
    with open(path, encoding="utf-8-sig", newline="") as f:
        for rec in csv.DictReader(f):
            api = by_period.get(rec["fiscalPeriod"])
            if api is None:
                problems.append(f"{rec['fiscalPeriod']}: not in the API response")
                continue
            for field in ("revenue", "operatingIncome", "netIncome"):
                saved = int(rec[field]) if rec[field] else None  # empty means None, not 0
                if saved != api.get(field):
                    problems.append(f"{rec['fiscalPeriod']} {field}: CSV {saved} / API {api.get(field)}")
            if (rec["docId"] or None) != (api.get("provenance") or {}).get("docId"):
                problems.append(f"{rec['fiscalPeriod']}: filing ID differs")
    return problems
```

Mapping empty cells back to `None` is the important part. `int("")` raises an error, and "fixing" that with 0 silently turns a missing value into ¥0.

## Show the source on screen

In a browser view, list the filing ID and disclosure time for each period. Insert strings from the API with `textContent`, not `innerHTML`, so any markup in a string is shown as text instead of being parsed.

```javascript
const SOURCE_LABEL = { tdnet: "Earnings summary", edinet: "Securities report", mixed: "Multiple filings", none: "No source stated" };

function sourceCell(row) {
  const prov = row.provenance ?? null;
  const box = document.createElement("div");
  const label = document.createElement("strong");
  label.textContent = SOURCE_LABEL[prov?.source ?? "none"] ?? prov.source;
  box.append(label);

  const detail = document.createElement("span");
  const parts = [];
  if (prov?.docId) parts.push(`Filing ${prov.docId}`);
  if (prov?.announcedAt) parts.push(`Published ${toJst(prov.announcedAt)} JST`);
  if (prov?.amended) parts.push(`Restated (${prov.amendedDocId})`);
  if (prov?.basis === "summary") parts.push("Summary figures");
  detail.textContent = parts.join(" / ");
  box.append(detail);
  return box;
}

function toJst(iso) {
  // Values without an offset (2026-06-10 06:33:00) are UTC
  const hasZone = /(Z|[+-]\d{2}:?\d{2})$/i.test(iso);
  const normalized = iso.replace(" ", "T") + (hasZone ? "" : "Z");
  return new Intl.DateTimeFormat("en-US", {
    timeZone: "Asia/Tokyo", year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: false,
  }).format(new Date(normalized));
}
```

Keep three timestamps apart on screen:

| Timestamp | Meaning | Where to show it |
|---|---|---|
| Disclosure time | When the company published the filing (`announcedAt`) | Per-period source line |
| Row updated | When the data platform last rebuilt the row (`updatedAt`) | Per-period source line, small |
| Retrieved | When you fetched the data | Under the table title |

To answer "what did this screen show back then?", the pair of retrieval time and filing ID is your best clue.

### Don't link filings on public pages

On a page only you use, `archiveUrl` lets you open the original PDF. Pages shown to other people are different:

- TDnet filings themselves (PDFs, text, and the links our service returns) can't be shown on public pages.
- Cite the source as text: filing type, filing ID, and disclosure time.
- Showing financial figures to third parties in your own service requires the Business plan or above.

See [What you can and can't display](https://zenithcode.net/en/docs/display-rights) for the full rules.

## Read the numbers carefully

- **Some periods have no source.** For companies that don't use Japanese GAAP (IFRS or US GAAP), the source of the income statement section can't always be shown, and `provenance` is `null`. That doesn't mean the values are wrong. Keep the row and label it "no source stated."
- **Restated periods carry post-correction values.** When `amended` is `true`, the values were replaced by a correction. `docId` still names the original filing; the correction is in `amendedDocId`.
- **`basis: "summary"` periods aren't full statements.** The values come from the yuho's multi-year summary or the tanshin summary page. Line items such as cost of revenue or SG&A are often `null` in these periods.
- **`mixed` periods have a `null` `docId`.** Read the per-field filings from `fieldSources`.
- **Timestamps are UTC.** Add nine hours for Japan time. Values saved before November 3, 2026 may lack an offset; they're UTC as well.
- **`updatedAt` isn't a filing date.** It moves every time the row is rebuilt. Use `announcedAt` for "when was this published."
- **A period's source can change.** An earnings-summary value (`tdnet`) may be replaced by the securities-report value (`edinet`). When you compare against an older CSV, check whether the filing ID changed first.
- **Non-yen periods have `null` amounts.** We don't convert currencies. Companies that report in US dollars (6269 and 9399) return `null` amounts with `nullReason` set to `non_jpy_material`.

## Summary

- Flatten the filing ID, source type, and disclosure time into the same row as the values.
- Convert UTC to Japan time, and record your own retrieval time.
- Write raw API values to CSV and leave missing values empty. Never read them back as 0.
- Keep restated, summary-based, and source-less periods, each with a clear label.

## Related

- [Income statement API docs](https://zenithcode.net/en/docs/income-statement)
- [What you can and can't display](https://zenithcode.net/en/docs/display-rights)
- [TDnet vs EDINET](https://zenithcode.net/en/learn/tdnet-vs-edinet)
- [Point-in-time data](https://zenithcode.net/en/learn/point-in-time)
- [Calculate year-over-year growth correctly](https://zenithcode.net/en/docs/cookbook/applied/practice-periods-and-yoy)
- [Display rules for financial tables and charts](https://zenithcode.net/en/docs/cookbook/applied/practice-responsive-layout)
- [Sample code repository (company-analysis template)](https://github.com/Crab-grass/zenith-code-examples/tree/main/templates/company-analysis)

A Japanese-language walkthrough with screenshots is on [Qiita](https://qiita.com/Sohei-Taniguchi-CG/items/9ec079444e5a818ccb7d).

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