market-microstructure
This Claude Code skill implements market microstructure analysis tools for quantitative trading, including bid-ask spread decomposition (quoted, effective, realized), order-flow toxicity detection via VPIN and Kyle lambda, liquidity measurement through Amihud and Roll metrics, price-impact modeling, and limit-order-book analysis. Use it when designing execution algorithms, estimating realistic transaction costs, identifying periods of informed trading activity, assessing liquidity risk, or analyzing China A-share market structures like call auctions and block trades.
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading /tmp/market-microstructure && cp -r /tmp/market-microstructure/agent/src/skills/market-microstructure ~/.claude/skills/market-microstructureSKILL.md
# Market Microstructure
## Overview
Study the micro-level mechanisms of price formation: who is trading, how they are trading, and how trades affect prices. For quantitative strategies, this matters because it improves transaction-cost estimation, identifies informed trading, and optimizes execution.
Applicable scenarios:
- Precise estimation of strategy trading costs (instead of simply assuming a flat 0.1% fee)
- Designing large-order execution strategies (`TWAP / VWAP / IS`)
- Detecting order-flow toxicity (avoid time windows dominated by informed traders)
- Quantifying liquidity risk (flash-crash warning)
- Capturing China A-share-specific microstructure features (call auction / closing auction / block trades)
## Core Concepts
### Bid-Ask Spread
**Three measurements:**
| Metric | Formula | Meaning |
|------|------|------|
| Quoted spread | `Ask - Bid` | Best spread shown in the limit order book |
| Effective spread | `2 × |trade price - mid price|` | Actual spread paid by the trader |
| Realized spread | `2 × direction × (trade price - mid price 5min later)` | True market-maker profit |
```
China A-share example:
Instrument: 600519.SH Kweichow Moutai
Best bid: 1680.00 Best ask: 1680.50
Quoted spread: 0.50 RMB = 0.03%
Instrument: 000001.SZ Ping An Bank
Best bid: 11.05 Best ask: 11.06
Quoted spread: 0.01 RMB = 0.09%
Spread decomposition (Roll):
Spread = adverse-selection cost + inventory cost + order-processing cost
In China A-shares: adverse selection accounts for 60-70% (mixture of retail and informed traders)
Spread drivers:
- Larger market cap -> smaller spread (Moutai 0.03% vs small-cap 0.5%)
- Higher volatility -> wider spread (market-maker risk premium)
- Higher volume -> narrower spread (greater competition)
- Higher information asymmetry -> wider spread (adverse selection)
```
### Order-Flow Toxicity Metrics
**VPIN (Volume-Synchronized Probability of Informed Trading):**
```
Principle: replace clock time with volume time to measure the probability of informed trading
Calculation steps:
1. Bucket trades by fixed volume (Volume Bucket)
Bucket size V = average daily volume / 50 (about 5-10 minutes per bucket)
2. Classify buy and sell volume in each bucket (Bulk Volume Classification):
buy_volume = V × Φ(ΔP / σ) (standard normal CDF)
sell_volume = V - buy_volume
3. Compute order-flow imbalance:
OI_i = |buy_volume_i - sell_volume_i|
4. VPIN = Σ(OI_i) / (n × V) (n=50-bucket rolling window)
Interpretation:
VPIN < 0.3 -> normal, low informed-trading share
VPIN 0.3-0.5 -> caution, informed trading rising
VPIN > 0.5 -> dangerous, high probability that major information is about to be released
China A-share usage:
A sudden VPIN spike in a stock may foreshadow:
- insider trading ahead of a major announcement
- institutional position building / distribution
Before the 2015 China A-share flash crashes, VPIN stayed above 0.6 for a prolonged period
```
**Kyle's Lambda (price impact coefficient)**:
```
Model: ΔP = λ × OrderFlow + ε
where OrderFlow = buy volume - sell volume
Estimation method:
1. Compute ΔP and OrderFlow in 5-minute windows
2. Regress ΔP = α + λ × OrderFlow
3. λ = price change caused by one unit of order flow
Interpretation:
Large λ -> poor liquidity, high impact
Small λ -> good liquidity, large orders can be executed cheaply
Typical China A-share values:
Large cap (CSI 300): λ ≈ 0.001-0.005
Mid cap (CSI 500): λ ≈ 0.005-0.02
Small cap (CSI 1000): λ ≈ 0.02-0.1
```
### Liquidity Measures
| Metric | Formula | Advantages | Disadvantages |
|------|------|------|------|
| Amihud illiquidity | `|R_t| / Volume_t` | Requires only daily data | Sensitive to extreme returns |
| Roll implied spread | `2√(-Cov(R_t, R_{t-1}))` | Requires only daily data | Fails when covariance is positive |
| LOT zero-return ratio | zero-return days / total days | Intuitive | Too coarse |
| Turnover ratio | volume / free float | Simple and intuitive | Does not reflect price impact |
| Traded value | average daily notional | Absolute liquidity | Does not reflect relative impact |
```
Amihud calculation (China A-shares):
ILLIQ = (1/D) × Σ(|R_d| / VOL_d) (D=trading days, monthly)
Normalization: ILLIQ × 10^6 (for readability)
Screening rules:
ILLIQ < 0.5 -> high liquidity (large-cap blue chips)
ILLIQ 0.5-5 -> medium liquidity
ILLIQ > 5 -> low liquidity (trade cautiously)
Strategy application:
- Liquidity factor: low-liquidity stocks tend to earn long-run excess return (liquidity premium)
- Liquidity monitor: sudden rise in ILLIQ -> warning of liquidity drying up
```
## Analysis Framework
### 1. Price-Impact Models
**Linear impact (Almgren-Chriss)**:
```
Model: impact = η × σ × (Q / V)^0.6
η: impact coefficient, about 0.5-1.5 for China A-shares
σ: daily volatility
Q: traded quantity (shares)
V: average daily volume (shares)
Example:
Sell 100,000 shares of Kweichow Moutai
Average daily volume 5,000,000 shares, daily volatility 1.8%
impact = 1.0 × 0.018 × (100000/5000000)^0.6
= 0.018 × 0.0085
= 0.015% (1.5bp, acceptable)
Sell 100,000 shares of a small-cap stock
Average daily volume 500,000 shares, daily volatility 3.0%
impact = 1.0 × 0.03 × (100000/500000)^0.6
= 0.03 × 0.076
= 0.23% (23bp, should be executed in slices)
Execution-splitting methods:
TWAP: uniform in clock time -> simple but ignores market state
VWAP: volume-profile execution -> better matches market rhythm
IS: minimize Implementation Shortfall -> optimal but requires real-time optimization
```
**Nonlinear impact (square-root model)**:
```
impact = σ × √(Q / (ADV × T))
σ: daily volatility
Q: total trade size
ADV: average daily traded value
T: execution days
Applicable to: large trades (Q/ADV > 5%)
```
### 2. Limit Order Book Analysis
```
Depth metrics:
Level 1 depth: queue size at the best bid and best ask
Level 5 depth: totalProfessional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).
ADR/H-share/A-share cross-listing premium analysis — track pricing gaps between US-listed ADRs, HK-listed H-shares, and A-shares for arbitrage signals, dual-listing valuation, and delisting risk assessment.
AKShare financial data aggregator (18k+ stars). Free, no API key. Covers A-shares, US, HK, futures, macro, forex. Primary fallback for tushare and yfinance.
Browse and bench the bundled alpha zoos — prebuilt cross-sectional factor libraries (Kakushadze 101, GTJA 191, Qlib 158, Fama-French / Carhart). Use when the user asks "which alphas exist", wants metadata on a named alpha, or wants to run IC/IR on a whole zoo over a universe.
A 股 ST/*ST 风险预测框架 — 基于最新中报/三季报或业绩预告/快报,预测下一财年是否会因营收、利润、净资产、分红不达标而被风险警示,并将新浪监管处罚记录作为独立证据面纳入风险等级。仅适用于 A 股,不预测财务造假。
Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 4 optimizers and rebalancing rules.
Diagnose failed or underperforming backtests, locate the root cause, and fix the issue
Behavioral finance applications: theories of overreaction and underreaction, behavioral explanations for momentum and reversal, investor sentiment cycles, cognitive-bias checklists, and debiasing quantitative strategies.