Stock Liquidity
Alex YangCommunityCreated by Alex Yang
- Skill
- Tool integration
- Data and AI
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive framework for evaluating the liquidity of financial instruments. By leveraging data from Yahoo Finance, it calculates key metrics such as bid-ask spreads, average daily volume, turnover ratios, and the Amihud illiquidity ratio. It also includes an institutional-grade square-root model to estimate market impact and potential slippage for large orders, helping users understand the real-world costs of trading.
What it does
- Calculates bid-ask spreads and relative spread percentages.
- Computes volume metrics including average daily volume and dollar volume.
- Estimates market impact and slippage for large orders using a square-root model.
- Measures turnover ratios to assess trading activity relative to float.
- Determines Amihud illiquidity ratios to quantify price response per dollar traded.
- Generates a liquidity dashboard for quick assessment of one or more tickers.
When to use it
- When assessing how easily a position can be entered or exited.
- When estimating the potential market impact of a large trade.
- When comparing the liquidity of multiple stocks.
- When analyzing thinly traded names, small caps, or penny stocks.
- When evaluating trading costs beyond the quoted price.
Advantages
- Provides actionable estimates for execution costs and slippage.
- Normalizes liquidity comparisons across different price points.
- Uses standardized institutional models for market impact.
- Helps identify potential liquidity risks before trading.
Usage examples
- “How liquid is AAPL compared to TSLA?”
- The agent will generate a side-by-side liquidity dashboard comparing bid-ask spreads, volume, and Amihud illiquidity for both tickers.
- “What is the estimated market impact of a $1M order in AMD?”
- The agent will calculate the expected price slippage in basis points using the square-root market impact model based on recent volume data.
- “Show me the turnover ratio for GME.”
- The agent will return the daily and annualized turnover ratios relative to the stock's float and shares outstanding.
- “What is the bid-ask spread for NVDA options?”
- The agent will provide the current quoted spread and context from near-the-money options data.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/himself65/stock-liquidity/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip stock-liquidity.zip -d .agents/skills
Documentation by Alex Yang
Stock Liquidity Analysis Skill
If your host has not already executed the shell probes below (for example, in Codex), run the commands inside the ! wrappers with its shell tool before choosing a setup path. Use the actual output; if shell access is unavailable, report that limitation.
Analyzes stock liquidity across multiple dimensions — bid-ask spreads, volume patterns, order book depth, estimated market impact, and turnover ratios — using data from Yahoo Finance via yfinance.
Liquidity matters because it determines the real cost of trading. The quoted price is not what you actually pay — spreads, slippage, and market impact all eat into returns, especially for larger positions or less liquid names.
Important: This is for research and educational purposes only. Not financial advice. yfinance is not affiliated with Yahoo, Inc.
Step 1: Ensure Dependencies Are Available
Current environment status:
!`python3 -c "exec('try:\n import yfinance, pandas, numpy\n print(f\'yfinance={yfinance.__version__} pandas={pandas.__version__} numpy={numpy.__version__}\')\nexcept Exception:\n print(\'DEPS_MISSING\')')"`If DEPS_MISSING, install required packages:
import subprocess, sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "yfinance", "pandas", "numpy"])If already installed, skip and proceed.
Step 2: Route to the Correct Sub-Skill
Classify the user's request and jump to the matching section. If the user asks for a general liquidity assessment without specifying a particular metric, run Sub-Skill A (Liquidity Dashboard) which computes all key metrics together.
| User Request | Route To | Examples |
|---|---|---|
| General liquidity check, "how liquid is X" | Sub-Skill A: Liquidity Dashboard | "how liquid is AAPL", "liquidity analysis for TSLA", "is this stock liquid enough" |
| Bid-ask spread, trading costs, effective spread | Sub-Skill B: Spread Analysis | "bid-ask spread for AMD", "what's the spread on NVDA options", "trading cost estimate" |
| Volume, ADTV, dollar volume, volume profile | Sub-Skill C: Volume Analysis | "volume analysis MSFT", "average daily volume", "volume profile for SPY" |
| Order book depth, market depth, level 2 | Sub-Skill D: Order Book Depth | "order book depth for AAPL", "market depth", "show me the book" |
| Market impact, slippage, execution cost for large orders | Sub-Skill E: Market Impact | "how much would 50k shares move the price", "slippage estimate", "market impact of $1M order" |
| Turnover ratio, trading activity relative to float | Sub-Skill F: Turnover Ratio | "turnover ratio for GME", "float turnover", "how actively traded is this" |
| Compare liquidity across multiple stocks | Sub-Skill A (multi-ticker mode) | "compare liquidity AAPL vs TSLA", "which is more liquid AMD or INTC" |
Defaults
| Parameter | Default |
|---|---|
| Lookback period | 3mo (3 months) |
| Data interval | 1d (daily) |
| Market impact model | Square-root model |
| Intraday interval (when needed) | 5m |
Sub-Skill A: Liquidity Dashboard
Goal: Produce a comprehensive liquidity snapshot combining all key metrics for one or more tickers.
A1: Fetch data and compute all metrics
import yfinance as yf
import pandas as pd
import numpy as np
def liquidity_dashboard(ticker_symbol, period="3mo"):
ticker = yf.Ticker(ticker_symbol)
info = ticker.info
hist = ticker.history(period=period)
if hist.empty:
return None
# --- Spread metrics (from current quote) ---
bid = info.get("bid", None)
ask = info.get("ask", None)
current_price = info.get("currentPrice") or info.get("regularMarketPrice") or hist["Close"].iloc[-1]
spread = None
spread_pct = None
if bid and ask and bid > 0 and ask > 0:
spread = round(ask - bid, 4)
midpoint = (ask + bid) / 2
spread_pct = round((spread / midpoint) * 100, 4)
# --- Volume metrics ---
avg_volume = hist["Volume"].mean()
median_volume = hist["Volume"].median()
avg_dollar_volume = (hist["Close"] * hist["Volume"]).mean()
volume_std = hist["Volume"].std()
volume_cv = volume_std / avg_volume if avg_volume > 0 else None # coefficient of variation
# --- Turnover ratio ---
shares_outstanding = info.get("sharesOutstanding", None)
float_shares = info.get("floatShares", None)
base_shares = float_shares or shares_outstanding
turnover_ratio = round(avg_volume / base_shares, 6) if base_shares else None
# --- Amihud illiquidity ratio ---
# Average of |daily return| / daily dollar volume
returns = hist["Close"].pct_change().dropna()
dollar_volume = (hist["Close"] * hist["Volume"]).iloc[1:] # align with returns
amihud_values = returns.abs() / dollar_volume
amihud = amihud_values[amihud_values.replace([np.inf, -np.inf], np.nan).notna()].mean()
# --- Market impact estimate (square-root model) ---
# For a hypothetical order of 1% of ADV
adv = avg_volume
order_size = adv * 0.01
daily_volatility = returns.std()
sigma = daily_volatility
participation_rate = order_size / adv if adv > 0 else 0
impact_bps = sigma * np.sqrt(participation_rate) * 10000 # in basis points
return {
"ticker": ticker_symbol,
"current_price": round(current_price, 2),
"bid": bid,
"ask": ask,
"spread": spread,
"spread_pct": spread_pct,
"avg_daily_volume": int(avg_volume),
"median_daily_volume": int(median_volume),
"avg_dollar_volume": round(avg_dollar_volume, 0),
"volume_cv": round(volume_cv, 3) if volume_cv else None,
"shares_outstanding": shares_outstanding,
"float_shares": float_shares,
"turnover_ratio": turnover_ratio,
"amihud_illiquidity": round(amihud * 1e9, 4) if not np.isnan(amihud) else None,
"daily_volatility": round(daily_volatility * 100, 2),
"impact_1pct_adv_bps": round(impact_bps, 2),
"observations": len(hist),
}A2: Interpret and present
Present as a summary card. For the Amihud illiquidity ratio, multiply by 1e9 for readability (standard convention).
Liquidity grade (use these rough thresholds for US equities):
| Grade | Avg Dollar Volume | Spread (%) | Amihud (×10⁹) |
|---|---|---|---|
| Very High | > $500M/day | < 0.03% | < 0.01 |
| High | $50M–$500M/day | 0.03–0.10% | 0.01–0.1 |
| Moderate | $5M–$50M/day | 0.10–0.50% | 0.1–1.0 |
| Low | $500K–$5M/day | 0.50–2.00% | 1.0–10 |
| Very Low | < $500K/day | > 2.00% | > 10 |
When comparing multiple tickers, show a side-by-side table and highlight which is more liquid and why.
Sub-Skill B: Spread Analysis
Goal: Detailed bid-ask spread analysis including current spread, historical context from options data, and effective spread estimates.
B1: Current spread from quote
import yfinance as yf
def spread_analysis(ticker_symbol):
ticker = yf.Ticker(ticker_symbol)
info = ticker.info
bid = info.get("bid", 0)
ask = info.get("ask", 0)
bid_size = info.get("bidSize", None)
ask_size = info.get("askSize", None)
current_price = info.get("currentPrice") or info.get("regularMarketPrice", 0)
result = {"bid": bid, "ask": ask, "bid_size": bid_size, "ask_size": ask_size}
if bid > 0 and ask > 0:
midpoint = (bid + ask) / 2
result["absolute_spread"] = round(ask - bid, 4)
result["relative_spread_pct"] = round((ask - bid) / midpoint * 100, 4)
result["relative_spread_bps"] = round((ask - bid) / midpoint * 10000, 2)
return resultB2: Options spread context
Options data from yfinance includes bid/ask for each strike, which gives a sense of derivatives liquidity. Use the nearest expiration, extract near-the-money calls and puts, and compute spread and spread percentage for each.
See references/liquidity_reference.md § "Options Spread Analysis" for the full code template.
B3: Present results
Show:
Current quoted spread (absolute, relative %, basis points)
Bid/ask sizes if available
Near-the-money options spreads for context
How the spread compares to typical ranges for this market cap tier
Sub-Skill C: Volume Analysis
Goal: Analyze trading volume patterns — averages, trends, relative volume, and dollar volume.
C1: Compute volume metrics
import yfinance as yf
import pandas as pd
import numpy as np
def volume_analysis(ticker_symbol, period="3mo"):
ticker = yf.Ticker(ticker_symbol)
hist = ticker.history(period=period)
if hist.empty:
return None
vol = hist["Volume"]
close = hist["Close"]
dollar_vol = vol * close
# Relative volume (today vs average)
rvol = vol.iloc[-1] / vol.mean() if vol.mean() > 0 else None
# Volume trend (linear regression slope over the period)
x = np.arange(len(vol))
slope, _ = np.polyfit(x, vol.values, 1) if len(vol) > 1 else (0, 0)
trend_pct = (slope * len(vol)) / vol.mean() * 100 # % change over period
# Volume profile by day of week
hist_copy = hist.copy()
hist_copy["DayOfWeek"] = hist_copy.index.dayofweek
day_names = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri"}
vol_by_day = hist_copy.groupby("DayOfWeek")["Volume"].mean()
vol_by_day.index = vol_by_day.index.map(day_names)
# High/low volume days
high_vol_days = hist.nlargest(5, "Volume")[["Close", "Volume"]]
low_vol_days = hist.nsmallest(5, "Volume")[["Close", "Volume"]]
return {
"avg_volume": int(vol.mean()),
"median_volume": int(vol.median()),
"avg_dollar_volume": round(dollar_vol.mean(), 0),
"current_volume": int(vol.iloc[-1]),
"relative_volume": round(rvol, 2) if rvol else None,
"volume_trend_pct": round(trend_pct, 1),
"volume_by_day": vol_by_day.to_dict(),
"high_vol_days": high_vol_days,
"low_vol_days": low_vol_days,
"max_volume": int(vol.max()),
"min_volume": int(vol.min()),
}C2: Present results
Show:
Average daily volume (shares and dollar) with median for comparison
Relative volume (RVOL) — today's volume vs. the average. RVOL > 1.5 is elevated; RVOL < 0.5 is unusually quiet
Volume trend — is trading activity increasing or declining?
Day-of-week pattern (if meaningful variation exists)
Top 5 highest-volume days with context (earnings? news?)
Sub-Skill D: Order Book Depth
Goal: Estimate order book depth using available bid/ask data from the equity quote and options chain.
Yahoo Finance does not provide full Level 2 / order book data. Be upfront about this limitation. What we can do:
Equity quote: bid, ask, bid size, ask size (top of book only)
Options chain: bid/ask and open interest across strikes give a proxy for derivatives depth
Intraday volume distribution: how volume is distributed within the day suggests how deep the continuous market is
D1: Gather available depth data
Collect three data points:
Top of book — bid, ask, bidSize, askSize from
ticker.infoIntraday volume distribution — 5-min bars over the last 5 days, grouped by time-of-day and normalized to percentage of daily volume
Options open interest — total call/put OI and volume from the nearest expiration as a derivatives depth proxy
See references/liquidity_reference.md § "Order Book Depth Proxy" for the full code template.
D2: Present results
Show:
Top of book: current bid/ask with sizes
Intraday volume shape: where volume concentrates (open/close vs. midday)
Options depth: total open interest and volume as a proxy for derivatives liquidity
Honest limitation: "Yahoo Finance provides top-of-book only. For full Level 2 depth, a direct market data feed (e.g., NYSE OpenBook, NASDAQ TotalView) is needed."
Sub-Skill E: Market Impact
Goal: Estimate how much a given order size would move the price, using the square-root market impact model.
The standard model in practice is: Impact (%) = σ × √(Q / V) where σ is daily volatility, Q is order size in shares, and V is average daily volume. This is a simplified version of the Almgren-Chriss framework used by institutional traders.
E1: Compute market impact estimate
import yfinance as yf
import numpy as np
def market_impact(ticker_symbol, order_shares=None, order_dollars=None, period="3mo"):
ticker = yf.Ticker(ticker_symbol)
hist = ticker.history(period=period)
info = ticker.info
if hist.empty:
return None
current_price = info.get("currentPrice") or hist["Close"].iloc[-1]
avg_volume = hist["Volume"].mean()
daily_volatility = hist["Close"].pct_change().dropna().std()
# Determine order size in shares
if order_dollars and not order_shares:
order_shares = order_dollars / current_price
elif not order_shares:
# Default: estimate for various sizes
order_shares = avg_volume * 0.01 # 1% of ADV
participation_rate = order_shares / avg_volume if avg_volume > 0 else 0
pct_adv = (order_shares / avg_volume * 100) if avg_volume > 0 else 0
# Square-root impact model
impact_pct = daily_volatility * np.sqrt(participation_rate) * 100
impact_bps = impact_pct * 100
impact_dollars = impact_pct / 100 * current_price * order_shares
# Generate impact curve for multiple order sizes
sizes = [0.001, 0.005, 0.01, 0.02, 0.05, 0.10, 0.20, 0.50] # as fraction of ADV
curve = []
for s in sizes:
q = avg_volume * s
imp = daily_volatility * np.sqrt(s) * 100
curve.append({
"pct_adv": round(s * 100, 1),
"shares": int(q),
"dollars": round(q * current_price, 0),
"impact_bps": round(imp * 100, 1),
"impact_dollars_per_share": round(imp / 100 * current_price, 4),
})
return {
"ticker": ticker_symbol,
"current_price": round(current_price, 2),
"avg_daily_volume": int(avg_volume),
"daily_volatility_pct": round(daily_volatility * 100, 2),
"order_shares": int(order_shares),
"order_dollars": round(order_shares * current_price, 0),
"pct_of_adv": round(pct_adv, 2),
"estimated_impact_bps": round(impact_bps, 1),
"estimated_impact_pct": round(impact_pct, 4),
"estimated_impact_total_dollars": round(impact_dollars, 2),
"impact_curve": curve,
}E2: Present results
Show:
The estimated impact for the user's specific order size
An impact curve table showing how cost scales with order size
Context: "This uses the square-root market impact model, a standard institutional estimate. Actual impact depends on execution strategy (VWAP, TWAP, etc.), time of day, and current market conditions."
Above ~25 bps, note that the order is large for the stock's liquidity; above ~50 bps, flag it clearly and suggest the user consider algorithmic execution or splitting the order across days
Sub-Skill F: Turnover Ratio
Goal: Measure how actively a stock trades relative to its shares outstanding and free float.
F1: Compute turnover metrics
import yfinance as yf
import pandas as pd
import numpy as np
def turnover_analysis(ticker_symbol, period="3mo"):
ticker = yf.Ticker(ticker_symbol)
hist = ticker.history(period=period)
info = ticker.info
if hist.empty:
return None
avg_volume = hist["Volume"].mean()
shares_outstanding = info.get("sharesOutstanding")
float_shares = info.get("floatShares")
result = {
"avg_daily_volume": int(avg_volume),
"shares_outstanding": shares_outstanding,
"float_shares": float_shares,
}
if shares_outstanding:
daily_turnover = avg_volume / shares_outstanding
result["daily_turnover_ratio"] = round(daily_turnover, 6)
result["annualized_turnover"] = round(daily_turnover * 252, 2)
result["days_to_trade_float"] = round(
(float_shares or shares_outstanding) / avg_volume, 1
) if avg_volume > 0 else None
if float_shares:
float_turnover = avg_volume / float_shares
result["float_turnover_daily"] = round(float_turnover, 6)
result["float_turnover_annualized"] = round(float_turnover * 252, 2)
# Turnover trend
vol = hist["Volume"]
base = float_shares or shares_outstanding
if base:
hist_copy = hist.copy()
hist_copy["turnover"] = hist_copy["Volume"] / base
recent_turnover = hist_copy["turnover"].tail(20).mean()
older_turnover = hist_copy["turnover"].head(20).mean()
if older_turnover > 0:
result["turnover_trend_pct"] = round(
(recent_turnover - older_turnover) / older_turnover * 100, 1
)
return resultF2: Present results
Show:
Daily and annualized turnover ratios (vs. outstanding and float)
"Days to trade the float" — how many days at average volume to turn over the entire free float
Turnover trend — is the stock becoming more or less actively traded?
Context:
| Turnover (Annualized) | Interpretation |
|---|---|
| > 500% | Extremely active — likely speculative or momentum-driven |
| 100–500% | Actively traded |
| 30–100% | Moderate activity |
| < 30% | Thinly traded — likely institutional buy-and-hold or neglected |
Step 3: Respond to the User
After running the appropriate sub-skill:
Always include
The lookback period used for historical metrics
The data timestamp — spreads and quotes are snapshots, not real-time
Any tickers that returned empty data (invalid symbol, delisted, etc.)
Always caveat
Yahoo Finance quote data has a 15-minute delay for most exchanges — spreads shown may not reflect the current live market
Full order book (Level 2) data is not available through Yahoo Finance
Market impact estimates are models, not guarantees — actual execution costs depend on strategy, timing, and market conditions
Liquidity can change rapidly — a stock that's liquid today may not be tomorrow (especially around events, halts, or during extended hours)
Practical guidance (mention when relevant)
Position sizing: If estimated impact exceeds ~25 bps, the position may be too large for the stock's liquidity (see the thresholds in Sub-Skill E)
Small/micro-cap warning: Stocks with < $1M daily dollar volume require careful execution
Spread costs compound: A 0.10% spread on a round-trip (buy + sell) costs 0.20% — this adds up for active strategies
Illiquidity premium: Less liquid stocks historically earn higher returns as compensation — but the transaction costs can eat this premium
Present liquidity data and let the user make their own decisions; don't recommend specific trades.
Reference Files
references/liquidity_reference.md— Detailed formulas, extended code templates, metric interpretation guides, and academic references for all liquidity measures
Read the reference file when you need exact formulas, edge case handling, or deeper background on liquidity metrics.
Files
- ATTRIBUTION.mdAdded by AutoGineer891 B
- LICENSELicence file added by AutoGineer1.0 KiB
- README.md1.4 KiB
- SKILL.md19.6 KiB
- references/liquidity_reference.md13.4 KiB
references/liquidity_reference.md
Liquidity Metrics Reference
Complete reference for all liquidity metrics, formulas, code templates, and interpretation guidelines.
Table of Contents
Bid-Ask Spread Metrics
Volume Metrics
Amihud Illiquidity Ratio
Square-Root Market Impact Model
Turnover Ratio
Composite Liquidity Score
yfinance Fields Reference
Edge Cases and Gotchas
Bid-Ask Spread Metrics
Quoted Spread
The difference between the best ask and best bid price.
Absolute Spread = Ask - Bid
Relative Spread (%) = (Ask - Bid) / Midpoint × 100
Spread (bps) = (Ask - Bid) / Midpoint × 10,000
Midpoint = (Ask + Bid) / 2Effective Spread (estimated)
The effective spread captures the actual transaction cost, accounting for trades that execute inside the quoted spread. Without tick-level data, estimate as:
Effective Spread ≈ 2 × |Trade Price - Midpoint|Since yfinance doesn't provide tick data, use the quoted spread as an upper bound. The effective spread is typically 60–80% of the quoted spread for liquid stocks.
Spread as a Function of Price Level
Low-priced stocks often have wider percentage spreads due to the minimum tick size ($0.01). A $5 stock with a $0.01 spread has a 0.20% spread, while a $500 stock with a $0.01 spread has a 0.002% spread. Always report relative spread, not just absolute.
Volume Metrics
Average Daily Volume (ADV)
adv = hist["Volume"].mean()Use median for a more robust measure when volume has large spikes (earnings, index rebalancing).
Average Daily Dollar Volume (ADDV)
addv = (hist["Close"] * hist["Volume"]).mean()Dollar volume is more meaningful than share volume for cross-stock comparisons because it normalizes for price differences.
Relative Volume (RVOL)
rvol = current_volume / avg_volume| RVOL | Interpretation |
|---|---|
| > 3.0 | Extreme — likely news, earnings, or event |
| 1.5–3.0 | Elevated — increased interest |
| 0.8–1.2 | Normal |
| 0.5–0.8 | Below average — quiet day |
| < 0.5 | Very low — possible holiday, pre-event calm |
Volume Coefficient of Variation
volume_cv = hist["Volume"].std() / hist["Volume"].mean()High CV (> 1.0) means volume is "spiky" — the stock alternates between very quiet and very active days. This matters for execution: you can't rely on the average volume being available every day.
Intraday Volume Distribution
Volume follows a U-shape pattern in US equities — highest at open and close, lowest midday. Use 5-minute bars to visualize:
intraday = ticker.history(period="5d", interval="5m")
intraday["time"] = intraday.index.time
vol_by_time = intraday.groupby("time")["Volume"].mean()Typical distribution for US equities:
First 30 min (9:30–10:00): ~15–20% of daily volume
Midday (11:00–14:00): ~25–30% of daily volume
Last 30 min (15:30–16:00): ~15–20% of daily volume
Amihud Illiquidity Ratio
Formula
Amihud (2002) illiquidity ratio measures the daily price response per dollar of trading volume:
ILLIQ = (1/D) × Σ |rₜ| / DVOLₜWhere:
D= number of trading days in the periodrₜ= daily return on day tDVOLₜ= daily dollar volume on day t (price × volume)
Code
returns = hist["Close"].pct_change().dropna()
dollar_volume = (hist["Close"] * hist["Volume"]).iloc[1:] # align with returns
amihud_daily = returns.abs() / dollar_volume
# Remove inf values (zero-volume days)
amihud_daily = amihud_daily.replace([np.inf, -np.inf], np.nan).dropna()
amihud = amihud_daily.mean()
# Convention: multiply by 10^9 for readability
amihud_scaled = amihud * 1e9Interpretation
Higher values = less liquid. The ratio captures how much "price bang" you get per dollar of volume.
| Amihud (×10⁹) | Liquidity Level |
|---|---|
| < 0.01 | Mega-cap, extremely liquid (AAPL, MSFT) |
| 0.01–0.1 | Large-cap, highly liquid |
| 0.1–1.0 | Mid-cap, moderately liquid |
| 1.0–10 | Small-cap, less liquid |
| > 10 | Micro-cap, illiquid |
Rolling Amihud
Track how liquidity changes over time:
window = 20 # trading days
rolling_amihud = amihud_daily.rolling(window).mean() * 1e9Square-Root Market Impact Model
Theory
The square-root law of market impact is one of the most robust empirical findings in market microstructure. Price impact scales with the square root of order size:
Impact (%) = σ × √(Q / V)Where:
σ= daily return volatility (standard deviation)Q= order size in sharesV= average daily volume in shares
This means doubling the order size only increases impact by ~41% (√2 ≈ 1.41), not 100%. This concavity arises because large orders are typically split across time.
Extended Model with Participation Rate
For orders executed over multiple periods:
Impact (%) = σ × √(Q / (V × T))Where T is the number of days over which the order is executed.
Total Execution Cost
Total Cost = Spread Cost + Market Impact
Spread Cost = 0.5 × Bid-Ask Spread (one way)
Total Round-Trip = 2 × (Spread Cost + Impact)Code for Impact Curve
def impact_curve(ticker_symbol, period="3mo"):
ticker = yf.Ticker(ticker_symbol)
hist = ticker.history(period=period)
info = ticker.info
price = info.get("currentPrice") or hist["Close"].iloc[-1]
adv = hist["Volume"].mean()
sigma = hist["Close"].pct_change().dropna().std()
sizes_pct_adv = [0.1, 0.5, 1, 2, 5, 10, 20, 50]
results = []
for pct in sizes_pct_adv:
frac = pct / 100
shares = int(adv * frac)
impact_pct = sigma * np.sqrt(frac) * 100
impact_per_share = impact_pct / 100 * price
total_cost = impact_per_share * shares
results.append({
"pct_adv": pct,
"shares": shares,
"notional": round(shares * price),
"impact_bps": round(impact_pct * 100, 1),
"cost_per_share": round(impact_per_share, 4),
"total_cost": round(total_cost, 2),
})
return resultsTurnover Ratio
Formulas
Daily Turnover = Daily Volume / Shares Outstanding
Float Turnover = Daily Volume / Free Float Shares
Annualized Turnover = Daily Turnover × 252
Days to Trade Float = Float Shares / Average Daily Volumeyfinance Fields
info = ticker.info
shares_outstanding = info.get("sharesOutstanding")
float_shares = info.get("floatShares")Float shares excludes restricted stock, insider holdings, and other locked-up shares. Float turnover is generally more informative than total turnover because it measures trading relative to the actually tradable supply.
Interpretation
| Annualized Float Turnover | Interpretation |
|---|---|
| > 1000% | Hyper-active — meme stock, short squeeze, or speculative frenzy |
| 500–1000% | Very active — high retail or momentum interest |
| 100–500% | Actively traded — typical for popular large/mid-caps |
| 30–100% | Moderate — normal institutional holding pattern |
| 10–30% | Low — buy-and-hold investor base, limited trading |
| < 10% | Very low — thinly traded, possibly neglected or closely held |
Composite Liquidity Score
For a quick single-number summary, combine normalized metrics:
def liquidity_score(spread_pct, avg_dollar_volume, amihud_scaled, turnover_annual):
"""Returns 0-100 score. Higher = more liquid."""
import numpy as np
# Spread score (lower spread = higher score)
spread_score = max(0, min(100, 100 - spread_pct * 200))
# Dollar volume score (log scale)
dv_log = np.log10(max(avg_dollar_volume, 1))
dv_score = max(0, min(100, (dv_log - 4) / 6 * 100)) # $10K=0, $10B=100
# Amihud score (lower = better)
ami_score = max(0, min(100, 100 - np.log10(max(amihud_scaled, 0.001)) * 25))
# Turnover score
turn_score = max(0, min(100, turnover_annual / 5)) # 500% annual = 100
# Weighted composite
composite = (
spread_score * 0.30 +
dv_score * 0.35 +
ami_score * 0.20 +
turn_score * 0.15
)
return round(composite, 1)This is a heuristic, not a formal measure. It's useful for quick comparisons but should not replace examining individual metrics.
yfinance Fields Reference
From ticker.info
| Field | Description | Used For |
|---|---|---|
bid | Current best bid price | Spread |
ask | Current best ask price | Spread |
bidSize | Size at best bid (lots) | Book depth |
askSize | Size at best ask (lots) | Book depth |
currentPrice | Last trade price | Impact calc |
regularMarketPrice | Regular session last price | Fallback price |
averageVolume | 3-month avg daily volume | Volume metrics |
averageVolume10days | 10-day avg daily volume | Recent volume |
averageDailyVolume10Day | Same as above (alias) | Recent volume |
volume | Today's volume so far | RVOL |
sharesOutstanding | Total shares outstanding | Turnover |
floatShares | Free float shares | Float turnover |
marketCap | Market capitalization | Context |
From ticker.history()
| Column | Description |
|---|---|
Open | Opening price |
High | Day's high |
Low | Day's low |
Close | Closing price |
Volume | Shares traded |
From ticker.option_chain(expiration)
| Column | Description | Used For |
|---|---|---|
bid | Option bid price | Options spread |
ask | Option ask price | Options spread |
volume | Option contracts traded | Options liquidity |
openInterest | Open contracts | Depth proxy |
Options Spread Analysis
Analyze near-the-money options spreads from the nearest expiration to gauge derivatives liquidity:
def options_spread_analysis(ticker_symbol):
ticker = yf.Ticker(ticker_symbol)
expirations = ticker.options
if not expirations:
return None
# Use nearest expiration
chain = ticker.option_chain(expirations[0])
for label, df in [("Calls", chain.calls), ("Puts", chain.puts)]:
atm = pd.concat([df[df["inTheMoney"]].tail(3), df[~df["inTheMoney"]].head(3)])
atm["spread"] = atm["ask"] - atm["bid"]
atm["spread_pct"] = (atm["spread"] / ((atm["ask"] + atm["bid"]) / 2) * 100).round(2)
return chainOrder Book Depth Proxy
Yahoo Finance does not provide full Level 2 data. Use this function to gather available depth signals:
def order_book_proxy(ticker_symbol):
ticker = yf.Ticker(ticker_symbol)
info = ticker.info
# Top of book
top_of_book = {
"bid": info.get("bid"),
"ask": info.get("ask"),
"bid_size": info.get("bidSize"),
"ask_size": info.get("askSize"),
}
# Intraday volume distribution (5-min bars, last 5 days)
intraday = ticker.history(period="5d", interval="5m")
if not intraday.empty:
intraday_copy = intraday.copy()
intraday_copy["time"] = intraday_copy.index.time
vol_by_time = intraday_copy.groupby("time")["Volume"].mean()
# Normalize to percentage of daily volume
total = vol_by_time.sum()
vol_pct = (vol_by_time / total * 100).round(2) if total > 0 else vol_by_time
# Options open interest as depth proxy
expirations = ticker.options
if expirations:
chain = ticker.option_chain(expirations[0])
total_call_oi = chain.calls["openInterest"].sum()
total_put_oi = chain.puts["openInterest"].sum()
total_call_volume = chain.calls["volume"].sum()
total_put_volume = chain.puts["volume"].sum()
return top_of_book, vol_pct if not intraday.empty else NoneEdge Cases and Gotchas
Zero-Volume Days
Some thinly traded stocks have days with zero volume. Filter these before computing Amihud (division by zero) and volume averages:
# Remove zero-volume days for Amihud
mask = hist["Volume"] > 0
hist_filtered = hist[mask]Pre/Post Market Data
yfinance prepost=True includes extended hours data, which has wider spreads and lower volume. For liquidity analysis, use regular hours only (the default).
Quote Staleness
Yahoo Finance quotes can be delayed 15+ minutes. During market hours, bid/ask may not reflect the current state. Note this in output.
ADRs and Foreign Stocks
American Depositary Receipts (ADRs) may show different liquidity than the underlying foreign-listed stock. The ADR spread can be wider than the home-market spread. When analyzing ADR liquidity, note this distinction.
ETFs vs. Stocks
ETF liquidity is more complex — the ETF may appear illiquid (low volume, wide spread) but the underlying basket is very liquid, meaning authorized participants can create/redeem shares efficiently. The "true" liquidity of an ETF is the liquidity of its underlying holdings. Note this when the user asks about ETF liquidity.
Penny Stocks (< $1)
Minimum tick size ($0.01) creates a floor on absolute spreads. A $0.50 stock can't have less than a 2% spread (at minimum tick). Relative spread metrics are especially important for low-priced securities.
Weekend/Holiday Gaps
Volume averages should use trading days only (yfinance handles this by default). But be careful when computing "days to trade float" — these are trading days, not calendar days.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Alex Yang
- Publisher
- Alex Yang (Community)
- Source
- himself65/finance-skills · plugins/market-analysis/skills/stock-liquidity · commit a085078
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Alex Yang.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download stock-liquidity.zip