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 5

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.
For developersFor companies7 min read
open_in_newIllustrated series on Qiita (Japanese)The same topic is also published as an illustrated series on Qiita.

Endpoints used

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 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. build ZENITH Code, 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.

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.

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

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.

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.

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.

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

A Japanese-language walkthrough with screenshots is on Qiita.

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