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 FinL
By koreal6803 · 1,789 installs
npx skills add koreal6803/finlab-ai --skill finlab
Source repository · Upstream listing
FinLab Quantitative Trading Package
Prerequisites
Before running any FinLab code, verify these in order:
1. uv is installed (Python package manager):
If uv is not installed, tell the user to install it.
After installing, ensure uv is on PATH:
2. FinLab is installed via uv (requires = 2.2.15):
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](https://studio.finlab.finance) — a hosted Jupyter environment with finlab preinstalled and your account already logged in.
3. Logged in to FinLab (finlab = 2.0; no legacy API token required):
Desktop (has a browser): log in once; credentials are cached locally:
Headless / cron / Docker: on a machine with a browser, log in and run:
Set all three exported variables — FINLAB REFRESH TOKEN , FINLAB SESSION ID , and FINLAB API KEY — in the headless environment. FinLab uses them automatically. Treat the output as credentials: use your platform's secret storage and do not paste it into chat or commit it.
Google Colab: run finlab.login() in a cell and follow the login link.
Migrating from legacy tokens: FINLAB API TOKEN and finlab.login('<api token ') are deprecated. Run python m finlab migrate , set up browser login or the three environment variables above, then remove the old token from your configuration.
Legacy token status: No removal version or date is publicly confirmed in the [official authentication guide](https://finlab.finance/docs/reference/finlab/); the 2026/08/01 date in client warning text is not a removal announcement. Dropping the client side fallback and rejecting legacy tokens server side are separate changes, and a cached data.get() call does not test server authentication — use the supported login flow above.
Language
Respond in the user's language. If user writes in Chinese, respond in Chinese. If in English, respond in English.
Market Support
FinLab supports tw (default), us , kr , jp , hk , uk , us fund (US ETFs/funds), rotc (Taiwan emerging) and tw cb (Taiwan convertible bonds). Pick the market once per session with data.set market(<code ) ; an unprefixed dataset name resolves to the active market's table ( price:close → us price:close under us ). A name the active market lacks silently falls back to the TW table : Chinese keys ( price:收盤價 , monthly revenue:當月營收 ) exist only for TW and rotc , so under us , data.get('price:收盤價') returns Taiwan prices. Outside TW, use English keys ( price:close ) or prefixed names ( us price:adj close ). 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. tw cb is not a set market code (it raises ValueError ): read cb price: and pass sim(position, market=TWCBMarket()) ( from finlab.markets.tw cb import TWCBMarket ).
The rest of this file plus [dataframe reference.md](dataframe reference.md), [backtesting reference.md](backtesting reference.md), [best practices.md](best practices.md), [factor analysis reference.md](factor analysis reference.md), and [machine learning reference.md](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](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:
Which US data tables are safe for backtesting versus current snapshot only (analyst consensus, ratios, DCF are live only — do not use them historically)
Quarterly fundamentals aligned on key date — no .shift() workaround needed; the raw filing date column is not the publication date
Report API names on US ( creturn / daily creturn / get stats() ; no get equity() )
US backtest defaults for both markets: USMarket ( fee ratio=0 , tax ratio=0 , trade at price='close' ) and USFundMarket for ETF/fund backtests
How data.set market(...) is the session scope switch (there is no market= kwarg on data.get() )
Dollar volume top N universe construction, point in time S&P 500 / NASDAQ 100 membership via us index constituents: ( data.us universe(index=...) is not point in time), quality gates, and sector exclusion rationale
Lookahead bias checklist specific to US data (rolling window universe filters, survivorship avoidance)
ETF / sector rotation backtesting via USFundMarket and us fund price:
Other market queries can skip that file.
Account Tiers & Usage
Tiers
Tier Daily Limit
Free 500 MB
VIP 5000 MB
Check the current plan and quota with python m finlab status .
Usage Reset
Resets daily at 8:00 AM UTC+8
When limit exceeded, user must wait for reset or upgrade to VIP at [finlab.finance](https://finlab.finance)
Quick Start Example
Core Workflow: 5 Step Strategy Development
Step 1: Fetch Data
Use data.get("<TABLE :<COLUMN ") to retrieve data:
Taiwan tables keep the exchange's units. Money in monthly revenue: and financial statement: is thousand TWD (千元): a monthly revenue of 214,752,761 is NT$214.75 billion. Prices and per share figures are TWD; volumes and institutional net buys are shares. Income statement fields of financial statement: , EPS included, cover that quarter alone, not the year to date. Monthly revenue is dated when it is disclosed , by the 10th of the following month: the row dated 2026 10 12 is September's revenue, so name the month it covers, not the month of its date. data.describe("<TABLE :<COLUMN ") returns a field's catalog description.
Filter by market/category using data.universe() :
Use data.search('keyword', market='<code ') to discover available datasets; market takes any set market code from [Market Support]( market support), or 'all' to search every market. Use keywords in the dataset's native language (e.g. data.search('營收', market='tw') , data.search('revenue', market='us') ).
For retained publication versions ( data.versions , as of , version= ), complete data.snapshot recording/replay, and per stock/per quarter date coverage checks before offline research, read [data reproducibility.md](data reproducibility.md). A historical read of one table does not pin later date conversion or backtest dependencies.
Step 2: Create Factors & Conditions
Use FinLabDataFrame methods to create boolean conditions:
See [dataframe reference.md](dataframe reference.md) for all FinLabDataFrame methods.
Step 3: Construct Position DataFrame
Combine conditions with & (AND), (OR), ~ (NOT):
Important: Position DataFrame should have:
Index : DatetimeIndex (dates)
Columns : Stock IDs (e.g., '2330', '1101')
Values : Boolean (True = hold) or numeric (position size)
Step 4: Backtest
See [backtesting reference.md](backtesting reference.md) for complete sim() API.
Step 4.5: Deliver the FinLab HTML Report (REQUIRED)
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](backtesting reference.md) for details on what the file contains.
Step 5: Execute Orders (Optional)
Convert backtest results to live trading:
See [trading reference.md](trading reference.md) for complete broker setup and OrderExecutor API.
Reference Files
File Content
[backtesting reference.md](backtesting reference.md) sim() 參數、stop loss、rebalancing
[trading reference.md](trading reference.md) 券商設定、OrderExecutor、Position
[factor examples.md](factor examples.md) 60+ 策略範例
[dataframe reference.md](dataframe reference.md) FinLabDataFrame 方法
[factor analysis reference.md](factor analysis reference.md) IC、Shapley、因子分析
[best practices.md](best practices.md) 常見錯誤、lookahead bias
[data reproducibility.md](data reproducibility.md) Historical publications, snapshot replay, quarterly date coverage
[machine learning reference.md](machine learning reference.md) ML 特徵工程
[us market.md](us market.md) US market specifics: data map, quarterly alignment, defaults, universe construction
What's New (since v1.5.8)
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.md](dataframe reference.md)
df.sector.map(mapping) : broadcast group level scalars (e.g. sector weights) to full DataFrame shape for factor composition — see [dataframe reference.md](dataframe reference.md)
df.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.md](dataframe reference.md)
v2.0.12 (2026 06 01)
sim() / hold until() : trail stop activation — require a minimum unrealized gain before trail stop arms. See [backtesting reference.md](backtesting reference.md) and [dataframe reference.md](dataframe reference.md)
report.to html(path, title=...) : standalone HTML now sets browser tab title + FinLab favicon; pass title to disambiguate multi strategy report folders — see [backtesting reference.md](backtesting reference.md)
Dashboard settings modal: language / light dark theme / candle color scheme (default, east red, west green) consolidated into one panel
v2.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 defaults
data.search(market="rotc") : scoped to the emerging market catalog only
v2.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.md](trading reference.md cloud strategy deployment python m finlab cloud v201)