Provides assistance for quantitative trading strategies, backtesting, and data analysis on the Taiwan stock market.
Install
mkdir -p .claude/skills/finlab && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6779" && unzip -o skill.zip -d .claude/skills/finlab && rm skill.zipInstalls to .claude/skills/finlab
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
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).Key capabilities
- →Backtest quantitative trading strategies
- →Perform factor analysis on stock data
- →Construct stock selection universes
- →Analyze financial statement data
- →Generate HTML backtest reports
How it works
The agent uses the FinLab package to fetch historical market data, apply factor-based conditions to select stocks, and simulate portfolio performance over time.
Inputs & outputs
When to use finlab
- →Developing stock trading strategies
- →Backtesting market hypotheses
- →Analyzing stock selection factors
- →Working with FinLab data structures
About this skill
FinLab Quantitative Trading Package
Prerequisites
Before running any FinLab code, verify these in order:
-
uv is installed (Python package manager):
uv --versionIf uv is not installed, tell the user to install it.
After installing, ensure
uvis on PATH:source $HOME/.local/bin/env 2>/dev/null # Add uv to current shell -
FinLab is installed via uv (requires >= 2.2.15):
uv python install 3.12 # Ensure Python is available (skip if already installed) uv pip install --system "finlab>=2.2.15" 2>/dev/null || uv pip install "finlab>=2.2.15"Or use
uv runfor zero-setup execution (recommended for one-off scripts):uv run --with "finlab" python3 script.pyuv run --withauto-creates a temporary environment with dependencies — no venv management needed.Prefer zero-install? Run notebooks directly in FinLab Studio — a hosted Jupyter environment with
finlabpreinstalled and your account already logged in. -
Logged in to FinLab (finlab >= 2.0; no legacy API token required):
Desktop (has a browser): log in once; credentials are cached locally:
python -m finlab loginimport finlab finlab.login() # reuses cached credentials, or starts browser login if noneHeadless / cron / Docker: on a machine with a browser, log in and run:
python -m finlab token --envSet all three exported variables —
FINLAB_REFRESH_TOKEN,FINLAB_SESSION_ID, andFINLAB_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_TOKENandfinlab.login('<api_token>')are deprecated. Runpython -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; the
2026/08/01date 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 cacheddata.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, 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:
- 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 rawfiling_datecolumn is not the publication date ReportAPI names on US (creturn/daily_creturn/get_stats(); noget_equity())- US backtest defaults for both markets:
USMarket(fee_ratio=0,tax_ratio=0,trade_at_price='close') andUSFundMarketfor ETF/fund backtests - How
data.set_market(...)is the session-scope switch (there is nomarket=kwarg ondata.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
USFundMarketandus_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
Quick Start Example
from finlab import data
from finlab.backtest import sim
# 1. Fetch data
close = data.get("price:收盤價")
vol = data.get("price:成交股數")
pb = data.get("price_earning_ratio:股價淨值比")
# 2. Create conditions
cond1 = close.rise(10) # Rising last 10 days
cond2 = vol.average(20) > 1000*1000 # High liquidity
cond3 = pb.rank(axis=1, pct=True) < 0.3 # Low P/B ratio
# 3. Combine conditions and select stocks
position = cond1 & cond2 & cond3
position = pb[position].is_smallest(10) # Top 10 lowest P/B
# 4. Backtest
report = sim(position, resample="M", upload=False)
# 5. Print metrics - Two equivalent ways:
# Option A: Using metrics object
print(report.metrics.annual_return())
print(report.metrics.sharpe_ratio())
print(report.metrics.max_drawdown())
# Option B: Using get_stats() dictionary (different key names!)
stats = report.get_stats()
print(f"CAGR: {stats['cagr']:.2%}")
print(f"Sharpe: {stats['daily_sharpe']:.2f}")
print(f"MDD: {stats['max_drawdown']:.2%}")
# Benchmark stats (finlab >= 2.0.17): same keys via report.get_benchmark_stats()
# 6. Write the FinLab-generated HTML report (REQUIRED — do not hand-roll your own HTML)
report.to_html("report.html")
print("Open report.html to inspect equity curve, monthly returns, drawdown, and trade list.")
Core Workflow: 5-Step Strategy Development
Step 1: Fetch Data
Use data.get("<TABLE>:<COLUMN>") to retrieve data:
from finlab import data
# Price data
close = data.get("price:收盤價") # TWD
volume = data.get("price:成交股數") # shares
# Financial statements
roe = data.get("fundamental_features:ROE稅後") # %
revenue = data.get("monthly_revenue:當月營收") # thousand TWD, dated when disclosed: the 2026-10-12 row is September
eps = data.get("financial_statement:每股盈餘") # TWD, that quarter alone
# Valuation
pe = data.get("price_earning_ratio:本益比")
pb = data.get("price_earning_ratio:股價淨值比")
# Institutional trading
foreign_buy = data.get("institutional_investors_trading_summary:外陸資買賣超股數(不含外資自營商)") # shares
# Market benchmark
taiex = data.get("taiex_total_index:收盤指數") # TAIEX close
# Technical indicators
rsi = data.indicator("RSI", timeperiod=14)
macd, macd_signal, macd_hist = data.indicator("MACD", fastperiod=12, slowperiod=26, signalperiod=9)
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():
# Limit to specific industry
with data.universe(market='TSE_OTC', category=['水泥工業']):
price = data.get('price:收盤價')
# Set globally
data.set_universe(market='TSE_OTC', category='半導體')
Use data.search('keyword', market='<code>') to discover available datasets; market takes any set_market code from 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. 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:
# Trend
rising = close.rise(10) # Rising vs 10 days ag
---
*Content truncated.*
When not to use it
- →Real-time trade execution
- →Using live-only data for historical backtesting
Prerequisites
Limitations
- →Daily data quota limits apply based on account tier
- →Requires specific market-code settings for different regions
How it compares
It provides a standardized workflow for quantitative research that handles data alignment and backtesting metrics automatically, unlike manual spreadsheet analysis.
Compared to similar skills
finlab side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| finlab (this skill) | 1 | 5mo | Review | Advanced |
| quant-analyst | 103 | 6mo | No flags | Advanced |
| stock-analyzer | 71 | 5mo | Review | Beginner |
| pair-trade-screener | 11 | 4mo | Review | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
You might also like
quant-analyst
zenobi-us
Expert quantitative analyst specializing in financial modeling, algorithmic trading, and risk analytics. Masters statistical methods, derivatives pricing, and high-frequency trading with focus on mathematical rigor, performance optimization, and profitable strategy development.
stock-analyzer
FrancyJGLisboa
Provides comprehensive technical analysis for stocks and ETFs using RSI, MACD, Bollinger Bands, and other indicators. Activates when user requests stock analysis, technical indicators, trading signals, or market data for specific ticker symbols.
pair-trade-screener
tradermonty
Statistical arbitrage tool for identifying and analyzing pair trading opportunities. Detects cointegrated stock pairs within sectors, analyzes spread behavior, calculates z-scores, and provides entry/exit recommendations for market-neutral strategies. Use when user requests pair trading opportunities, statistical arbitrage screening, mean-reversion strategies, or market-neutral portfolio construction. Supports correlation analysis, cointegration testing, and spread backtesting.
risk-metrics-calculation
wshobson
Calculate portfolio risk metrics including VaR, CVaR, Sharpe, Sortino, and drawdown analysis. Use when measuring portfolio risk, implementing risk limits, or building risk monitoring systems.
backtesting-trading-strategies
jeremylongshore
Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".
model-usage
openclaw
Use CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost data from codexbar, or when you need a scriptable per-model summary from codexbar cost JSON.