# Build a private company analysis dashboard on a financial data API: a local proxy that hides your API key, and SVG charts that handle losses and missing data

Run a private dashboard that switches companies and metrics, using a public template. Learn how a local proxy keeps your API key out of the browser, how to draw SVG bars that tell losses from missing data, and how to read UTC timestamps, with fictional data and code.

## Key points

- A browser-based analysis page for your own use is easiest to keep safe in **three layers: browser, local proxy and API**, so the API key never reaches the browser.
- The public `company-analysis` template runs its proxy on the Python standard library alone, and with fictional data it needs no key and makes no network calls.
- In performance charts, **draw losses (negative values) and missing data (`null`) as different things**, and read timestamps as UTC.

Once you can render a chart image in Python, the next step is switching companies and metrics on screen. Changing a dropdown and having the table and charts redraw beats editing code each time. This page runs the company analysis template from the [public examples](https://github.com/Crab-grass/zenith-code-examples), explains the key design decisions, and gives you small parts to reuse in your own page. It describes the layout and behavior in text and tables rather than screenshots.

## Three layers: browser, local proxy, API

If browser JavaScript calls the API directly, the browser holds your API key. It shows up in developer tools and sits where extensions and other scripts can read it. The template splits the roles into three.

| Layer | Runs in | Holds | Role |
|---|---|---|---|
| Browser | Your browser | Display data only | Company and metric selection, tables and charts |
| Local proxy | Python on your computer (`server.py`) | API key | Validates requests from the page and calls the API |
| ZENITH Code API | Internet | — | Returns income statements and the latest close |

The browser only talks to `http://127.0.0.1:8765` on your own machine. The API key lives inside the proxy process and is never sent to the browser.

## Run the template on fictional data

You need Python 3.9+ and a browser. No packages, no Node.js.

```bash
git clone https://github.com/Crab-grass/zenith-code-examples.git
cd zenith-code-examples
python3 templates/company-analysis/server.py
```

When the terminal prints `Open http://127.0.0.1:8765`, open it in a browser on the same computer, and select **EN** for English. Stop the server with `Ctrl+C`. If the port is busy, add `--port 8766` and change the URL to match. On Windows, start it with `py -3 templates/company-analysis/server.py`.

Use the repository's folder layout as is, rather than copying `server.py` on its own. The proxy imports shared code from `python/zenith_examples.py`. Opening `index.html` by double-clicking leaves the page empty, because the proxy that serves the data is not running.

At first you can pick two fictional companies, Example Precision and Example Cloud. No account, no API key and no network calls. Choose a company and select **View company**, and the company name, metric cards, performance chart, operating margin chart, financial table and sources redraw. The performance chart menu switches between revenue, operating profit and net income. Both actions redraw data already loaded and make no requests.

Example Cloud's operating income includes three years designed to show the difference in rendering (all values are fictional).

| Fiscal period | Revenue | Operating income | How it is drawn |
|---|---:|---:|---|
| 2024-03 | ¥4.2 billion | −¥420 million | Bar below the zero line |
| 2025-03 | ¥5.8 billion | `null` | No bar; a "no value" mark |
| 2026-03 | ¥7.6 billion | ¥610 million | Bar above the zero line |

## What the local proxy protects

`server.py` is about 140 lines, but it covers the checks a local-only proxy needs. Use it as a checklist if you write your own.

| Check | Details |
|---|---|
| Only accept your own machine | Listens on `127.0.0.1` only. Returns 403 unless the `Host` header is `127.0.0.1:<port>` |
| Only accept requests from the page | Data fetches (POST) require an `Origin` of the same URL and a per-run token (`X-Local-Token`) |
| Narrow the input | Body is JSON of 256 bytes or less with only `symbol`. Securities codes are 4–5 alphanumeric characters (optional `.T` suffix) |
| No parallel calls | A request that arrives during a fetch gets 429 |
| Keep the key inside | The key comes from an environment variable or a hidden prompt. It is never sent to the browser or written to a file |
| Leave nothing extra behind | No access logs. Upstream error bodies are not relayed to the page |
| Restrict what the page loads | `Content-Security-Policy` blocks scripts from anywhere but the local server |

The proxy is built for a single user. It is not suitable for a shared office server or the public internet, because it has no login or permission system.

## API calls per fetch

With live data, each time you enter a securities code and press fetch, the proxy makes two API calls.

| Endpoint | Parameters | Used for | Tokens |
|---|---|---|---|
| [`/stable/quote`](https://zenithcode.net/en/docs/quote) | `symbol` | Latest close and its date | 1 |
| [`/stable/income-statement`](https://zenithcode.net/en/docs/income-statement) | `symbol`, `period=annual`, `limit=3` | Three full years of income statement and sources | 1 |

Opening the page, switching language and switching metrics make no API calls. There are no automatic refreshes or retries. A failed fetch is treated as a failure; partial data is not displayed.

The proxy combines both responses into one display object, `snapshot`.

```text
snapshot
├─ symbol              securities code
├─ retrievedAt         when you fetched it (UTC)
├─ latestClose[]       /stable/quote response (price, priceDate, ...)
└─ annualFinancials[]  /stable/income-statement response (three full years)
```

`snapshot` as a whole is not an API format; it is a shape the template builds for display. Here is how each part of the page maps to fields.

| Part of the page | Fields | Display unit |
|---|---|---|
| Revenue, operating income and net income cards and chart | `revenue`, `operatingIncome`, `netIncome` | JPY 100 million |
| Operating margin card and line | `operatingMargin` (API value as is) | % (0.125 in the API, 12.5% on screen) |
| Financial table | The amounts above plus `fiscalPeriodDays`, `accountingStandard` | JPY |
| Sources | `provenance.docId`, `provenance.announcedAt`, `updatedAt` | Japan time |
| Latest close | `price`, `priceDate` | JPY |

## SVG bars that handle losses and missing data

Two mistakes are common in performance charts: clipping negative values to zero, and letting `null` look like "¥0". The function below is a small part written separately from the template. It keeps the two apart and returns an SVG string, with no libraries.

```javascript
// Draw income-statement amounts as SVG bars. Negative values go below the zero line; null draws "—" instead of a bar.
const isNum = (v) => typeof v === "number" && Number.isFinite(v);
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);

export function barChartSvg(points, { width = 360, height = 200, unit = 1e8, unitLabel = "JPY 100M" } = {}) {
  const top = 20, bottom = height - 28;
  const scaled = points.map((p) => (isNum(p.value) ? p.value / unit : null));
  const known = scaled.filter((v) => v !== null);
  const max = Math.max(0, ...known), min = Math.min(0, ...known);
  const span = max - min || 1; // avoid dividing by zero when everything is null or 0
  const y = (v) => top + ((max - v) / span) * (bottom - top);
  const slot = width / points.length, barWidth = slot * 0.55;
  const parts = [`<line x1="0" x2="${width}" y1="${y(0)}" y2="${y(0)}" stroke="currentColor" stroke-opacity="0.4"/>`];
  points.forEach((p, i) => {
    const cx = slot * i + slot / 2, v = scaled[i];
    parts.push(`<text x="${cx}" y="${height - 8}" text-anchor="middle" font-size="11">${esc(p.label)}</text>`);
    if (v === null) {
      parts.push(`<text x="${cx}" y="${y(0) - 6}" text-anchor="middle" font-size="12">—<title>${esc(p.label)}: no value</title></text>`);
      return;
    }
    const y1 = Math.min(y(v), y(0)), h = Math.abs(y(v) - y(0));
    const text = `${esc(p.label)}: ${v.toLocaleString("en-US", { maximumFractionDigits: 1 })} ${unitLabel}`;
    parts.push(`<rect x="${cx - barWidth / 2}" y="${y1}" width="${barWidth}" height="${h}" fill="${v < 0 ? "#c2410c" : "#0f766e"}"><title>${text}</title></rect>`);
  });
  return `<svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${esc(unitLabel)}">${parts.join("")}</svg>`;
}
```

Pass pairs of fiscal period and amount in yen, after sorting the API rows.

```javascript
import { barChartSvg } from "./bars.mjs";

// rows: full-year income-statement rows. metric: a field name such as "revenue"
const points = rows
  .filter((r) => r.period === "FY")
  .sort((a, b) => a.fiscalPeriod.localeCompare(b.fiscalPeriod))
  .map((r) => ({ label: r.fiscalPeriod, value: r[metric] }));
document.querySelector("#chart").innerHTML = barChartSvg(points);
```

Given Example Cloud's operating income (−¥420 million, `null`, ¥610 million), the first bar goes below the zero line, the second shows "—" instead of a bar, and the third goes above the line.

### What the function gets right

- **Always include zero in the axis range.** `Math.max(0, …)` and `Math.min(0, …)` keep the zero line in view whether values are all positive or all negative. Bars grow from zero, so dropping zero from the range breaks the ratio between bar lengths.
- **Leave `null` out of the math.** `isNum()` keeps only numbers. In JavaScript, `Number(null)` and `null / 1e8` are `0`, so dividing without a type check turns missing data into a ¥0 bar.
- **Show losses by direction and color.** Negative bars sit below the zero line in a different color. Do not rely on color alone; `<title>` carries the value for screen readers and hover.
- **Always escape text.** Even fiscal-period strings go through `esc()` before entering the SVG, so the page stays safe if the data source changes.

For line charts such as operating margin, do not connect points across a `null` year. The template draws a segment only when both neighboring points are numbers.

## Read timestamps as UTC

The page shows several dates and times that mean different things. Decide how to treat each one.

| Field | Meaning | Display |
|---|---|---|
| `fiscalPeriod` | Period-end month | As is, e.g. `2026-03` |
| `priceDate` | Trading date of the latest close | As a date |
| `provenance.announcedAt` | When the source filing was published (UTC) | Convert to Japan time |
| `updatedAt` | When the data pipeline updated the row (UTC) | Convert to Japan time |
| `retrievedAt` | When you fetched it (recorded by the template) | Convert to Japan time |

Timestamps are UTC. With a trailing `Z`, as in `2026-10-22T20:07:26Z`, `new Date()` reads them correctly. But if you pass a string with no `Z` and no offset, such as `2026-10-22 20:07:26`, `new Date()` treats it as the browser's local time. On a machine set to Japan time, that is nine hours off. The function below reads strings without a zone marker as UTC.

```javascript
// Read a timestamp string as UTC, even without a trailing Z or +09:00; never as the browser's local time.
export function parseUtc(text) {
  if (typeof text !== "string" || !text) return null;
  const iso = text.trim().replace(" ", "T");
  const d = new Date(/(Z|[+-]\d\d:?\d\d)$/.test(iso) ? iso : iso + "Z");
  return Number.isNaN(d.getTime()) ? null : d;
}

export const toJst = (d) =>
  d ? new Intl.DateTimeFormat("en-US", { timeZone: "Asia/Tokyo", dateStyle: "medium", timeStyle: "short" }).format(d) : "—";

// toJst(parseUtc("2026-10-22 20:07:26")) → "Oct 23, 2026, 5:07 AM"
```

To show Japan time, pass `timeZone: "Asia/Tokyo"` to `Intl.DateTimeFormat`. It does not depend on the computer's settings, so the display is the same anywhere in the world. Treat `fiscalPeriod` and `priceDate` as dates and do not pass them through this function.

## Connect live data

For live data, [create an account](https://zenithcode.net/en/sign-up), create an API key, and restart the proxy with `--live`.

```bash
export ZENITH_API_KEY="YOUR_API_KEY"   # if unset, you are prompted for it with hidden input
python3 templates/company-analysis/server.py --live
```

On the page, choose **Connect live data**, enter a securities code such as `7203` or `130A`, and press **Fetch data**. `.env` files are not loaded automatically. There is no way to pass the key as a command-line argument, because it would stay in your shell history. For a full walkthrough of live data, see [running the analysis page on live data](https://zenithcode.net/en/docs/cookbook/applied/practice-live-data).

## Reading the numbers correctly

### The latest close is not a real-time price

`price` in `/stable/quote` is the split-adjusted closing price on `priceDate`. It does not reflect intraday moves. This value and the price changes `quote` returns are exchange data. Keep their display inside your own private environment. See "Showing the page to others" below.

### In the evening, endpoints can use different fiscal periods

Latest values such as `quote` are recomputed together in a daily update that starts at 18:30 JST on weekdays. Around that update, for example on the evening a company releases its earnings summary, some endpoints may use the new fiscal period while others still use the previous one for the same company. Check `priceDate` and each row's `fiscalPeriod` to confirm the values on the page are from the same point in time ([when the latest values refresh](https://zenithcode.net/en/docs/metrics#update-timing)).

### Market cap in `quote` has exceptions

The template does not display it, but the `quote` response also includes market capitalization (`marketCap`). For newly listed companies, it is based on the share count at the pre-listing fiscal year-end and does not include shares issued in the IPO. Companies on TOKYO PRO Market have no financials loaded, so market cap is empty for them as well.

### The template uses full-year data only

Financials are fetched with `period=annual`, full-year rows only. If you use quarterly rows, Q2 and Q3 income figures are cumulative from the start of the fiscal year. The template has no step that turns cumulative figures into single quarters, so add that subtraction yourself if you add quarters.

### Units differ across the page

Cards and charts show JPY 100 million; the financial table shows full yen. The digits look different, but the underlying values are the same. Operating margin is the API's 0–1 decimal, turned into a percentage only for display. For years where revenue is zero, negative or missing, the API returns `null` operating margin and the page shows "—".

### Period length, accounting standard and consolidation are not adjusted

The financial table shows `fiscalPeriodDays` and `accountingStandard`, but differences from fiscal year-end changes, consolidation scope changes or accounting standard changes are not adjusted. The conditions to check before computing year-over-year changes are covered in [year-over-year changes](https://zenithcode.net/en/docs/cookbook/applied/practice-periods-and-yoy).

## Showing the page to others

The template code is MIT-licensed, but that does not grant rights to the API data.

- **Pages with fictional data** can be shown to anyone. Every company name and figure is fictional.
- **Live financial figures** can be shown to people outside your organization, or to users of your product, on the Business plan or higher.
- **Exchange data such as the latest close and price changes** cannot be shown to third parties on any plan. Do not post screenshots with live prices on blogs, social media or external materials. Even within your organization, only the registered user can view it.

The full conditions are in [display rights](https://zenithcode.net/en/docs/display-rights).

## Troubleshooting

| Symptom | What to check |
|---|---|
| Page stays empty | Did you open `index.html` directly? Use the `http://127.0.0.1:…` URL from the terminal |
| `zenith_examples` not found | Are you running from the repository's folder layout? |
| Port already in use | Is the server already running? Change both `--port 8766` and the URL |
| Cannot open from a phone | The proxy only serves the same computer. This is by design |
| Fetch button is disabled | Did you start without `--live`? |
| Fetch returns 429 | Did you press it again before the previous fetch finished? |
| No bar for a year | That year is `null`, not ¥0. This is correct |
| Update times are nine hours off | Are you passing timestamps without a zone marker to `new Date()`? |

## Related docs and articles

- [Income statement (income-statement)](https://zenithcode.net/en/docs/income-statement) and [latest stock price (quote)](https://zenithcode.net/en/docs/quote)
- [Metric definitions: when the latest values refresh](https://zenithcode.net/en/docs/metrics#update-timing)
- [Display rules for financial tables and charts](https://zenithcode.net/en/docs/cookbook/applied/practice-responsive-layout)
- [Track the source of every financial figure](https://zenithcode.net/en/docs/cookbook/applied/practice-statements-and-sources)
- [Japanese company revenue and operating income history via API](https://zenithcode.net/en/docs/cookbook/applied/practice-revenue-chart)
- [company-analysis template on GitHub](https://github.com/Crab-grass/zenith-code-examples/tree/main/templates/company-analysis)

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

This page explains how to build an analysis page. It is not a recommendation to buy or sell any security.

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