金晰數據

Python SDK

Python SDK支援同步與非同步查詢、自動重試、歷史資料分批讀取,也能轉成pandas DataFrame。每個帳戶每小時可請求3,000次。

安裝

bash
pip install 'clarifindata[pandas]'

需要Python 3.9以上,使用httpx。若不需DataFrame,可只安裝clarifindata,不安裝pandas。

快速上手

python
from clarifindata import Client

# Replace with your API key from https://clarifindata.com/dashboard
cfd = Client("YOUR_API_KEY")

# Fetch OHLCV for TSMC (2330)
df = cfd.get("TaiwanStockPrice", stock_id="2330", start="2026-01-01", as_df=True)
print(df.head())
print(df.attrs["attribution"])

get()預設回傳資料列清單。傳入as_df=True取得DataFrame,其attrs['attribution']保留來源資訊;with_meta=True則回傳含data與attribution的字典。

進階範例

批次查詢多支股票

python
# Comma-separated stock_id for batch queries
df = cfd.get(
    "TaiwanStockPrice",
    stock_id="2330,2317,0050",
    start="2026-01-01",
    end="2026-06-11",
    as_df=True,
)
print(df.groupby("stock_id")["close"].last())

查詢單季財報

python
# Use the REST API for dataset-specific options such as period
import httpx

response = httpx.get(
    "https://api.clarifindata.com/v1/data/TaiwanStockFinancialStatement",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    params={"stock_id": "2330", "period": "quarterly"},
    timeout=30,
)
response.raise_for_status()
financials = response.json()
print(financials["data"])
print(financials["attribution"])

分批讀取歷史資料

python
for batch in cfd.iter_history(
    "TaiwanStockInstitutionalInvestorsBuySell",
    stock_id="2330",
    since="2020-01-01",
    until="2026-06-11",
    with_meta=True,
):
    print(len(batch["data"]), "rows")
    print(batch["attribution"])

# Materialize all batches and their combined source notices
history = cfd.history(
    "TaiwanStockPrice", stock_id="2330", since="2020-01-01", with_meta=True,
)
print(history["attribution"])
下載及轉交資料時,請保留attribution。history()會合併各批次來源。DataFrame轉存CSV時不會保存attrs,請另存並提供來源聲明。

設定

python
from clarifindata import Client

cfd = Client(
    api_key="YOUR_API_KEY",
    base_url="https://api.clarifindata.com",  # default
    timeout=30,                                # seconds
    max_retries=3,                             # on 429 / 5xx
)