{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Taiwan fundamentals in five minutes\n### TSMC (2330.TW), point-in-time, with the one convention you must know\n\nTaiwan's exchange publishes condensed IFRS statements for **every listed company**. This dataset ingests them from the official TWSE OpenAPI (Open Government Data License 1.0 — the statutory attribution rides in every API response).\n\n*Runs as-is on the public `demo` key. Free tier includes 2330/2317/2454/2412/2308.*"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import json, urllib.request, urllib.parse\n\nBASE = \"https://www.tradingagentapp.com/api/v1\"\nKEY = \"demo\"  # public demo key: 25 flagship tickers, FULL fields & history, no signup\n             # paid keys unlock every ticker -> https://www.tradingagentapp.com/fundamentals\n\ndef api(path, **params):\n    qs = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})\n    req = urllib.request.Request(f\"{BASE}{path}?{qs}\",\n                                 headers={\"Authorization\": f\"Bearer {KEY}\"})\n    with urllib.request.urlopen(req, timeout=60) as r:\n        return json.loads(r.read().decode())\n\nprint(\"ready — or `pip install pit-fundamentals` for the packaged client\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1 · Pull TSMC"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "out = api(\"/fundamentals\", ticker=\"2330.TW\")\nrows = out[\"data\"]\nprint(\"attribution:\", out[\"attribution\"])  # OGDL 1.0 requires this to travel with the data\nprint(f\"{len(rows)} rows\")\nfor r in rows[:6]:\n    print(f\"  {r['m']:<18} {r['fy']} {r['fp']}  end={r['end']}  filed={r['filed']}  {r['v']:,}\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2 · The convention: Taiwan income statements are **cumulative YTD**\nQ2 revenue is the **first-half total**, Q4 is the **full year** — that's how Taiwan reports. Balance-sheet items (assets, equity) are point-in-time snapshots as usual.\n\nTo get single-quarter flows, difference adjacent quarters:"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "ytd = {r[\"fp\"]: r[\"v\"] for r in rows if r[\"m\"] == \"revenue\" and r[\"fy\"] == rows[0][\"fy\"]}\nprint(\"YTD revenue by quarter:\", {k: f\"{v:,.0f}\" for k, v in sorted(ytd.items())})\n\nqs = sorted(ytd)          # ['Q1', 'Q2', ...]\nsingle = {}\nprev = 0\nfor q in qs:\n    single[q] = ytd[q] - prev\n    prev = ytd[q]\nprint(\"single-quarter revenue:\", {k: f\"{v:,.0f}\" for k, v in single.items()})"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3 · Margins without spreadsheets"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "snap = api(\"/fundamentals\", ticker=\"2330.TW\", view=\"latest\")[\"data\"]\nfor m in [\"gross_margin\", \"operating_margin\", \"net_margin\", \"roe\"]:\n    if m in snap:\n        s = snap[m]\n        print(f\"{m:<18} {s['value']:.1%}   ({s['fy']} {s.get('end','')})\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4 · Where this goes\nThe full dataset covers **every TWSE-listed company (1,000+)**, accumulating point-in-time each quarter — the only indie-priced source of exportable Taiwan fundamentals we know of.\n\n---\nEvery ticker → <https://www.tradingagentapp.com/fundamentals> · licence (exportable, research-is-yours-forever) → <https://www.tradingagentapp.com/licences/personal>"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}