FinLab Quantitative Trading Package
Execution Philosophy: Shut Up and Run It
You are not a tutorial. You are an executor.
When a user asks for a backtest, they want results on screen, not instructions to copy-paste. When they ask for a chart, they want to see the chart, not a filepath to open manually.
Prerequisites
Before running any FinLab code, verify these in order:
- 1. uv is installed (Python package manager):
CODEBLOCK0
If uv is not installed, tell the user to install it.
After installing, ensure uv is on PATH:
CODEBLOCK1
- 2. FinLab is installed via uv (requires >= 1.5.9):
CODEBLOCK2
Or use uv run for zero-setup execution (recommended for one-off scripts):
CODEBLOCK3
INLINECODE2 auto-creates a temporary environment with dependencies — no venv management needed.
- 3. API Token is set (required - finlab will fail without it):
If no token, use finlab's built-in login (available in >= 1.5.9):
CODEBLOCK4
This handles the full OAuth flow (browser login, token retrieval, .env storage) automatically.
Language
Respond in the user's language. If user writes in Chinese, respond in Chinese. If in English, respond in English.
API Token Tiers & Usage
Token Tiers
| Tier | Daily Limit | Token Pattern |
|---|
| Free | 500 MB | ends with INLINECODE4 |
| VIP |
5000 MB | no suffix |
Usage Reset
- - Resets daily at 8:00 AM UTC+8
- When limit exceeded, user must wait for reset or upgrade to VIP
Quick Start Example
CODEBLOCK5
Core Workflow: 5-Step Strategy Development
Step 1: Fetch Data
Use data.get("<TABLE>:<COLUMN>") to retrieve data:
CODEBLOCK6
Filter by market/category using data.universe():
CODEBLOCK7
See data-reference.md for complete data catalog.
Step 2: Create Factors & Conditions
Use FinLabDataFrame methods to create boolean conditions:
CODEBLOCK8
See dataframe-reference.md for all FinLabDataFrame methods.
Step 3: Construct Position DataFrame
Combine conditions with & (AND), | (OR), ~ (NOT):
CODEBLOCK9
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
CODEBLOCK10
See backtesting-reference.md for complete sim() API.
Step 5: Execute Orders (Optional)
Convert backtest results to live trading:
CODEBLOCK11
See trading-reference.md for complete broker setup and OrderExecutor API.
Reference Files
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 特徵工程 |
Prevent Lookahead Bias
Critical: Avoid using future data to make past decisions:
CODEBLOCK12
See best-practices.md for more anti-patterns.
Feedback
Direct users to open an issue on GitHub: https://github.com/koreal6803/finlab-ai/issues
Notes
- - Some data columns use Chinese names — this is expected, use them as-is in
data.get() calls - Data frequency varies: daily (price), monthly (revenue), quarterly (financial statements)
- Always use
sim(..., upload=False) for experiments, upload=True only for final production strategies
FinLab 量化交易套件
執行哲學:閉嘴,執行就對了
你不是教學手冊。你是執行者。
當用戶要求回測時,他們要的是螢幕上的結果,而不是複製貼上的指令。當他們要求圖表時,他們要的是看到圖表,而不是手動開啟的檔案路徑。
前置需求
在執行任何 FinLab 程式碼之前,請依序確認以下項目:
- 1. 已安裝 uv(Python 套件管理器):
bash
uv --version
如果未安裝 uv,請告知用戶進行安裝。
安裝完成後,確保 uv 已加入 PATH:
bash
source $HOME/.local/bin/env 2>/dev/null # 將 uv 加入當前 shell
- 2. 已透過 uv 安裝 FinLab(需 >= 1.5.9):
bash
uv python install 3.12 # 確保 Python 可用(若已安裝可略過)
uv pip install --system finlab>=1.5.9 2>/dev/null || uv pip install finlab>=1.5.9
或使用 uv run 進行零設定執行(建議用於一次性腳本):
bash
uv run --with finlab python3 script.py
uv run --with 會自動建立臨時環境並安裝相依套件 — 無需管理虛擬環境。
- 3. 已設定 API Token(必要 - 若無則 finlab 會失敗):
若無 token,請使用 finlab 內建登入功能(1.5.9 以上版本可用):
python
import finlab
finlab.login() # 開啟瀏覽器進行 Google OAuth 驗證,自動儲存 token
這會自動處理完整的 OAuth 流程(瀏覽器登入、token 獲取、.env 儲存)。
語言
使用用戶的語言回覆。 若用戶使用中文書寫,請以中文回覆。若使用英文,則以英文回覆。
API Token 等級與使用方式
Token 等級
| 等級 | 每日限制 | Token 格式 |
|---|
| 免費 | 500 MB | 結尾為 #free |
| VIP |
5000 MB | 無後綴 |
使用量重置
- - 每日 UTC+8 上午 8:00 重置
- 超過限制時,用戶需等待重置或升級至 VIP
快速入門範例
python
from finlab import data
from finlab.backtest import sim
1. 獲取資料
close = data.get(price:收盤價)
vol = data.get(price:成交股數)
pb = data.get(price
earningratio:股價淨值比)
2. 建立條件
cond1 = close.rise(10) # 近 10 日上漲
cond2 = vol.average(20) > 1000*1000 # 高流動性
cond3 = pb.rank(axis=1, pct=True) < 0.3 # 低股價淨值比
3. 組合條件並選股
position = cond1 & cond2 & cond3
position = pb[position].is_smallest(10) # 選取股價淨值比最低的 10 檔
4. 回測
report = sim(position, resample=M, upload=False)
5. 列印指標 - 兩種等效方式:
方式 A:使用 metrics 物件
print(report.metrics.annual_return())
print(report.metrics.sharpe_ratio())
print(report.metrics.max_drawdown())
方式 B:使用 get_stats() 字典(注意鍵名不同!)
stats = report.get_stats()
print(f年化報酬率:{stats[cagr]:.2%})
print(f夏普比率:{stats[monthly_sharpe]:.2f})
print(f最大回撤:{stats[max_drawdown]:.2%})
report
核心工作流程:5 步驟策略開發
步驟 1:獲取資料
使用 data.get(<資料表>:<欄位>) 來取得資料:
python
from finlab import data
價格資料
close = data.get(price:收盤價)
volume = data.get(price:成交股數)
財務報表
roe = data.get(fundamental_features:ROE稅後)
revenue = data.get(monthly_revenue:當月營收)
估值
pe = data.get(price
earningratio:本益比)
pb = data.get(price
earningratio:股價淨值比)
法人交易
foreign
buy = data.get(institutionalinvestors
tradingsummary:外陸資買賣超股數(不含外資自營商))
技術指標
rsi = data.indicator(RSI, timeperiod=14)
macd, macd
signal, macdhist = data.indicator(MACD, fastperiod=12, slowperiod=26, signalperiod=9)
使用 data.universe() 依市場/類別篩選:
python
限制特定產業
with data.universe(market=TSE_OTC, category=[水泥工業]):
price = data.get(price:收盤價)
全域設定
data.set
universe(market=TSEOTC, category=半導體)
完整資料目錄請參閱 data-reference.md。
步驟 2:建立因子與條件
使用 FinLabDataFrame 方法建立布林條件:
python
趨勢
rising = close.rise(10) # 相較 10 日前上漲
sustained_rise = rising.sustain(3) # 連續 3 日上漲
移動平均
sma60 = close.average(60)
above_sma = close > sma60
排名
top
marketvalue = data.get(etl:market
value).islargest(50)
low_pe = pe.rank(axis=1, pct=True) < 0.2 # 本益比最低的 20%
產業排名
industry
top = roe.industryrank() > 0.8 # 產業內前 20%
所有 FinLabDataFrame 方法請參閱 dataframe-reference.md。
步驟 3:建立持倉 DataFrame
使用 &(AND)、|(OR)、~(NOT)組合條件:
python
簡單持倉:持有符合所有條件的股票
position = cond1 & cond2 & cond3
限制股票數量
position = factor[condition].is_smallest(10) # 持有前 10 名
進出場訊號搭配 hold_until
entries = close > close.average(20)
exits = close < close.average(60)
position = entries.hold
until(exits, nstockslimit=10, rank=-pb)
重要: 持倉 DataFrame 應具備:
- - 索引:DatetimeIndex(日期)
- 欄位:股票代碼(例如 2330、1101)
- 數值:布林值(True = 持有)或數值(持倉比例)
步驟 4:回測
python
from finlab.backtest import sim
基本回測
report = sim(position, resample=M)
含風險管理
report = sim(
position,
resample=M,
stop_loss=0.08,
take_profit=0.15,
trail_stop=0.05,
position_limit=1/3,
fee_ratio=1.425/1000/3,
tax_ratio=3/1000,
trade
atprice=open,
upload=False
)
提取指標 - 兩種方式:
方式 A:使用 metrics 物件
print(f年化報酬率:{report.metrics.annual_return():.2%})
print(f夏普比率:{report.metrics.sharpe_ratio():.2f})
print(f最大回撤:{report.metrics.max_drawdown():.2%})
方式 B:使用 get_stats() 字典(注意鍵名不同!)
stats = report.get_stats()
print(f年化報酬率:{stats[cagr]:.2%}) # cagr 而非 annual_return
print(f夏普