npx skills add ...
npx skills add koreal6803/finlab-ai --skill finlab
Comprehensive guide for FinLab quantitative trading package across global stock markets (TW, US, KR, JP, HK; both single-name equities and ETFs/funds). Use when working with trading strategies, backtesting, stock data, FinLabDataFrame, factor analysis, stock selection, or when the user mentions FinLab, trading, quant trading, US equity, S&P 500 / NASDAQ 100, SPY / QQQ, sector or leveraged ETFs, ETF rotation, 美股, or stock market analysis. Includes data access, strategy development, backtesting workflows, best practices, and US-market specifics (data availability map, filing-date-aligned quarterly fundamentals, US universe construction, USMarket vs. USFundMarket defaults, and ETF backtesting).
npx skills add koreal6803/finlab-ai --skill finlab
Before running any FinLab code, verify these in order:
uv is installed (Python package manager):
If uv is not installed, tell the user to install it.
After installing, ensure uv is on PATH:
FinLab is installed via uv (requires >= 2.0.0):
Or use uv run for zero-setup execution (recommended for one-off scripts):
uv run --with auto-creates a temporary environment with dependencies — no venv management needed.
Prefer zero-install? Run notebooks directly in FinLab Studio — a hosted Jupyter environment with finlab preinstalled and your API token already wired up.
API Token is set (required - finlab will fail without it):
If no token, use finlab's built-in login (available in >= 1.5.9, improved Firebase flow in v1.5.11):
This handles the full OAuth flow (browser login, token retrieval, .env storage) automatically. Tokens are bound to a FinLab account at finlab.finance — finlab.login() provisions one on first use.
Respond in the user's language. If user writes in Chinese, respond in Chinese. If in English, respond in English.
FinLab supports TW (default), US, KR, JP, HK, plus Taiwan emerging (rotc) and Taiwan convertible bonds (tw_cb). Pick the market once per session with data.set_market(<code>); generic dataset names like price:收盤價 or monthly_revenue:當月營收 resolve to the active market's tables, so strategy code is written the same way across markets. data.set_market('rotc') (v2.0.9) enables 興櫃 (TW emerging) — use it when you need pre-listing price action or revenue factors that don't exist in the main TSE/OTC catalog.
The rest of this file plus dataframe-reference.md, backtesting-reference.md, best-practices.md, factor-analysis-reference.md, and machine-learning-reference.md are market-agnostic — the APIs behave the same across markets.
For US-market work — whether single-name equities (data.set_market('us')) or ETFs/funds (data.set_market('us_fund')) — read us-market.md first. Queries that should trigger it include: US equity, S&P 500, NASDAQ 100, 美股, SPY / QQQ, sector SPDRs, leveraged / inverse ETFs, ETF rotation, us_price:*, us_fund_price:*, data.us_universe(...), or us_income_statement:* / us_cash_flow:* / us_balance_sheet:*. It documents:
key_date == filing_date) — no .shift() workaround neededReport API names on US (creturn / daily_creturn / get_stats(); no get_equity())USMarket (fee_ratio=0, tax_ratio=0, trade_at_price='close') and USFundMarket for ETF/fund backtestsdata.set_market(...) is the session-scope switch (there is no market= kwarg on data.get())data.us_universe(index='S&P 500' | 'NASDAQ 100') with its 2022-11 history-start caveat, quality gates, and sector-exclusion rationaleUSFundMarket and us_fund_price:*Other-market queries can skip that file.
| Tier | Daily Limit | Token Pattern |
|---|---|---|
| Free | 500 MB | ends with #free |
| VIP | 5000 MB | no suffix |
Use data.get("<TABLE>:<COLUMN>") to retrieve data:
Filter by market/category using data.universe():
Use data.search('keyword', market='<market>') to discover available datasets. Supported markets: tw, us, kr, jp, hk. Use keywords in the dataset's native language (e.g. data.search('營收', market='tw'), data.search('revenue', market='us')).
Use FinLabDataFrame methods to create boolean conditions:
See dataframe-reference.md for all FinLabDataFrame methods.
Combine conditions with & (AND), | (OR), ~ (NOT):
Important: Position DataFrame should have:
See backtesting-reference.md for complete sim() API.
Follow each backtest the user will review with one HTML file — the one FinLab generates:
The canonical deliverable is the file generated by report.to_html() — do not hand-roll a separate report (custom HTML pages, Plotly summaries, dashboards, markdown files) unless the user explicitly asks. To summarize results, print a short terminal summary and point to the FinLab report. Exception: in batch runs (parameter sweeps, screening many variants), skip per-run HTML and write it only for the final strategy the user will review.
Pick a descriptive filename when running more than one strategy in the same session (e.g. momentum_top10.html, value_lowpb.html) so the user can compare without overwriting. After writing, tell the user the path so they can open it. Use report.to_terminal() only as a supplement for non-GUI terminals; it does not replace the HTML.
See the "report.to_html() — the canonical deliverable" section of backtesting-reference.md for details on what the file contains.
Convert backtest results to live trading:
See trading-reference.md for complete broker setup and OrderExecutor API.
| File | Content |
|---|---|
| backtesting-reference.md | sim() 參數、stop-loss、rebalancing |
| trading-reference.md | 券商設定、OrderExecutor、Position |
| factor-examples.md | 60+ 策略範例 |
| dataframe-reference.md | FinLabDataFrame 方法 |
| factor-analysis-reference.md | IC、Shapley、因子分析 |
| best-practices.md | 常見錯誤、lookahead bias |
| machine-learning-reference.md | ML 特徵工程 |
| us-market.md | US market specifics: data map, quarterly alignment, defaults, universe construction |
Short version pointers for features added in recent releases. Each reference file tags the exact API with (vX.Y.Z).
v2.0.15 (2026-07-18)
df.sector(by=...): sector accessor now accepts a custom classification — dict / pd.Series (stock_id → group) or a time-varying pd.DataFrame; unlisted stocks are excluded. Works with all sector.* methods — see dataframe-reference.mddf.sector.map(mapping): broadcast group-level scalars (e.g. sector weights) to full DataFrame shape for factor composition — see dataframe-reference.mddf.weight.by_group(weights, by, default): allocate capital across sectors/groups — normalize holdings so each group's total equals its share; under-allocation stays in cash — see dataframe-reference.mdv2.0.12 (2026-06-01)
sim() / hold_until(): trail_stop_activation — require a minimum unrealized gain before trail_stop arms. See backtesting-reference.md and dataframe-reference.mdreport.to_html(path, title=...): standalone HTML now sets browser-tab title + FinLab favicon; pass title to disambiguate multi-strategy report folders — see backtesting-reference.mdv2.0.9 (2026-05-27)
data.set_market("rotc"): 興櫃 is now a first-class market code; price:收盤價 / monthly_revenue:* / etc. resolve to the rotc_ catalog and sim() uses ROTCMarket defaultsdata.search(market="rotc"): scoped to the emerging-market catalog onlyv2.0.1 (2026-04-26)
python -m finlab cloud (CLI): deploy strategies to the finlab-auto-update Cloud Functions runtime with daily Asia/Taipei scheduling — deploy, get, list, run, logs, schedule set/delete, delete, status. See trading-reference.mdsim() peak RSS ~800 MB lower on full-market monthly strategies (was ~2.0–2.2 GiB → ~1.29 GiB); enables s-tier cloud workers that previously OOM'dv2.0.0 (2026-04-04) — major release
finlab.exceptions: structured error hierarchy (FinlabError, DataError, BacktestError, ...) — see backtesting-reference.mddata.get(lazy=True) / data.gets(..., lazy=True): batch fetch + deferred compute; data.override() / DataContext for scoped global statedf.cs / df.sector / df.weight accessors; rolling().std/var/skew/kurt/median — see dataframe-reference.mdPositionStreamMixin for realtime position streaming — see trading-reference.mdfrom finlab import FinlabDataFrame top-level exportbacktest.sim() refactored into 5 testable stages; eval() removed from optimize.combinationsv1.5.13 (2026-03-22)
universe(index=...) / us_universe(index=...): filter US stocks by S&P 500 / NASDAQ 100TW_CB (TW convertible bonds)v1.5.11 (2026-03-11)
data.get_role() / data.is_vip(): query user quota tierv1.5.9
finlab.schemas: typed PositionEntry, OrderEntry, PortfolioData contractsOrderExecutor.generate_orders(as_entries, quantity_type) and generate_order_entries()PortfolioSyncManager.get_data_typed() / set_data_typed()data.get() 80% quota usage warningsim() uses market-specific default fee_ratio / tax_ratio (no longer hardcoded TW values)v1.5.8 (baseline)
verify_strategy(): automated lookahead-bias detectorreport.to_terminal(): ASCII report for non-Jupyter runsCritical: Avoid using future data to make past decisions:
See best-practices.md for more anti-patterns.
Pass lazy=True by default; drop to eager pandas only when debugging. data.get(..., lazy=True) and data.gets(..., lazy=True) (v2.0.0) return lazy FinlabDataFrames that defer the compute graph until a terminal call materializes it — chained ops avoid redundant passes (single-CPU). Omit lazy=True when you need to print/inspect intermediate values interactively.
Direct users to open an issue on GitHub: https://github.com/koreal6803/finlab-ai/issues
data.get() callssim(..., upload=False) for experiments, upload=True only for final production strategies