Flow Toxicity Metrics¶
Market microstructure measures for detecting informed trading and quantifying price impact.
Functions¶
vpin ¶
vpin(
trades: DataFrame,
*,
bucket_volume: float | Literal["fit"] | None = None,
n_buckets: int = 50,
sign_method: str | None = None,
quotes: DataFrame | None = None,
) -> VpinResult
Compute the Volume-Synchronized Probability of Informed Trading.
Partitions cumulative trade volume into equal-sized buckets and
measures the normalised buy/sell imbalance within each bucket. The
trailing average of vpin over n_buckets is the headline VPIN
metric.
Works on feeds without a native aggressor side. When the trades frame
has no direction, the buy/sell split is inferred with a trade-sign
classifier (see sign_method), so VPIN runs on L2 / aggregated captures
too.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
DataFrame
|
Trades with at least |
required |
bucket_volume
|
float
|
Total volume per bucket, in the instrument's own units (BTC, shares,
contracts). It means the same amount whether |
None
|
n_buckets
|
int
|
Window length (in buckets) for the trailing VPIN average.
Default is 50, following the original paper. Fewer complete buckets
than this is reported in the result's |
50
|
sign_method
|
str
|
How to obtain the buy/sell split when there is no native
|
None
|
quotes
|
DataFrame
|
Quote frame for |
None
|
Returns:
| Type | Description |
|---|---|
VpinResult
|
The per-bucket
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
If required columns are missing, or the sizes are integer lots and
the frame carries no |
vpin_bucket_volume ¶
vpin_bucket_volume(
trades: DataFrame,
*,
buckets_per_day: int = VPIN_BUCKETS_PER_DAY,
trading_day: str | Timedelta = "24h",
) -> float
Pick a VPIN bucket_volume from the trades: average daily volume ÷ 50.
Average daily volume is the traded volume per unit of time, scaled to one trading_day::
daily volume = total volume × trading_day / (last timestamp − first timestamp)
The same formula covers every session length. A 30-minute capture is
scaled up to a full day at the rate it traded; a week-long one is averaged
down to a day. On a short capture the result is therefore a large bucket,
and VPIN will fill only a few of them, which :func:vpin then
reports in its diagnostics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
DataFrame
|
Trades with at least |
required |
buckets_per_day
|
int
|
How many buckets one average day of volume fills. Default 50. |
VPIN_BUCKETS_PER_DAY
|
trading_day
|
str or Timedelta
|
Length of one trading day, on the same clock as the span between the
first and last trade. Default |
'24h'
|
Returns:
| Type | Description |
|---|---|
float
|
The bucket volume, in the instrument's own units (BTC, shares,
contracts), ready to pass to :func: |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If required columns are missing, or the sizes are integer lots and
the frame carries no |
kyle_lambda ¶
kyle_lambda(
trades: DataFrame,
*,
window: str = "5min",
sign_method: str | None = None,
quotes: DataFrame | None = None,
n_boot: int = 1000,
ci_level: float = 0.95,
seed: int | Generator | None = 0,
) -> KyleLambdaResult
Estimate Kyle's Lambda via OLS regression.
For each time window, computes:
- ΔPrice = last trade price − first trade price
- signed_volume = Σ(buy volume) − Σ(sell volume)
Then regresses ΔPrice on signed_volume across all windows. The slope (λ) measures how much the price moves per unit of net order flow — a proxy for market illiquidity and adverse selection.
λ is in the quote currency per unit of size (for example USD per BTC),
whether the trades hold integer ticks and lots (with tick_size and
lot_size on the frame's attrs, as on a pipeline result) or
display prices and sizes. table is in the same units.
Works on feeds without a native aggressor side. When the trades frame
has no direction, the side is inferred with a trade-sign classifier
(see sign_method), as for :func:vpin and
:func:trade_imbalance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
DataFrame
|
Trades with |
required |
window
|
str
|
Length of each regression window, a fixed duration such as |
'5min'
|
sign_method
|
str
|
How to obtain the buy/sell split when there is no native
|
None
|
quotes
|
DataFrame
|
Quote frame for |
None
|
n_boot
|
int
|
Number of bootstrap resamples for the confidence interval. Default
1000; |
1000
|
ci_level
|
float
|
Coverage of the interval, strictly between 0 and 1. Default 0.95. |
0.95
|
seed
|
int or Generator
|
Seed or generator for the bootstrap. Default |
0
|
Returns:
| Type | Description |
|---|---|
KyleLambdaResult
|
Frozen dataclass with |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If required columns are missing, window is not a fixed duration,
or the prices or sizes are integers and the frame carries no
|
trade_imbalance ¶
trade_imbalance(
trades: DataFrame,
*,
window: str = "1min",
sign_method: str | None = None,
quotes: DataFrame | None = None,
) -> pd.DataFrame
Compute normalised trade imbalance per time window.
For each window:
trade_imbalance = (buy_volume − sell_volume) / (buy_volume + sell_volume)
Values range from −1 (all sells) to +1 (all buys). Zero indicates balanced flow.
Works on feeds without a native aggressor side: when the trades frame
has no direction, it is inferred with a per-trade trade-sign
classifier (see sign_method).
Each window is one time bar of :func:~ob_analytics.bars.bars, so
trade_imbalance is that bar's signed_volume / volume. Windows
count from the Unix epoch, and a window in which nothing traded is left
out. A window whose trades all have zero size is kept, with
trade_imbalance set to NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
DataFrame
|
Trades with |
required |
window
|
str
|
Length of each window, a fixed duration such as |
'1min'
|
sign_method
|
str
|
How to obtain the buy/sell split when there is no native
|
None
|
quotes
|
DataFrame
|
Quote frame for |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If required columns are missing, window is not a fixed duration,
or the sizes are integer lots and the frame carries no |
trade_imbalance_by_window ¶
trade_imbalance_by_window(
trades: DataFrame,
*,
windows: tuple[str, ...] = TRADE_IMBALANCE_WINDOWS,
grid: str = "5s",
sign_method: str | None = None,
quotes: DataFrame | None = None,
) -> pd.DataFrame
Compute trade imbalance over several trailing windows on one grid.
:func:trade_imbalance measures one window at a time. This measures
each of windows at every step of a common time grid, so pressure over short
and long windows can be compared at the same instant. Each value is a
trailing window ending at the grid step, not a block of the grid, so a
long window changes slowly and a short one changes quickly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
DataFrame
|
Trades with |
required |
windows
|
tuple of str
|
Fixed durations, one per window. Each is rounded to a whole number
of grid steps, with a minimum of one. Default
:data: |
TRADE_IMBALANCE_WINDOWS
|
grid
|
str
|
Step of the time grid, a fixed duration. Default |
'5s'
|
sign_method
|
optional
|
How to obtain the buy/sell split, as for :func: |
None
|
quotes
|
optional
|
How to obtain the buy/sell split, as for :func: |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per grid step, with |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If required columns are missing, or grid or a window is not a fixed duration. Also if trades is empty. |
cumulative_signed_volume ¶
cumulative_signed_volume(
trades: DataFrame,
*,
sign_method: str | None = None,
quotes: DataFrame | None = None,
) -> pd.DataFrame
Compute the running sum of buy volume minus sell volume, trade by trade.
Each trade adds its size when the taker bought and subtracts it when the
taker sold, so the running sum rises while buyers take liquidity and
falls while sellers do. It is the cumulative form of the
signed_volume of :func:trade_imbalance, without windows.
Works on feeds without a native aggressor side, as
:func:trade_imbalance does (see sign_method).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trades
|
DataFrame
|
Trades with |
required |
sign_method
|
str
|
How to obtain the buy/sell split, as in :func: |
None
|
quotes
|
DataFrame
|
Quote frame for |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per trade, in time order: |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If required columns are missing, or the sizes are integer lots and
the frame carries no |
Models¶
KyleLambdaResult
dataclass
¶
KyleLambdaResult(
lambda_: float,
t_stat: float,
r_squared: float,
n_windows: int,
table: DataFrame = pd.DataFrame(),
ci_low: float = float("nan"),
ci_high: float = float("nan"),
ci_level: float = 0.95,
)
Result of a Kyle's λ OLS regression.
Attributes:
| Name | Type | Description |
|---|---|---|
lambda_ |
float
|
Slope — price change in the quote currency per unit of signed order flow in the instrument's units (higher = less liquid). |
t_stat |
float
|
t-statistic for |
r_squared |
float
|
Fraction of ΔPrice variance explained by signed order flow. |
n_windows |
int
|
Number of time windows in the regression. |
table |
DataFrame
|
The regression data, one row per window: |
ci_low, ci_high |
float
|
Bounds of a block-bootstrap confidence interval for |
ci_level |
float
|
Coverage of that interval, for example |
diagnostics
property
¶
Reasons lambda_ should not be relied on; empty when there are none.
Checks the fit is defined, that there are at least
:data:KYLE_MIN_WINDOWS windows, and that |t_stat| reaches
:data:KYLE_MIN_T_STAT.
VpinResult
dataclass
¶
Result of :func:vpin: the per-bucket table and how it was computed.
Attributes:
| Name | Type | Description |
|---|---|---|
table |
DataFrame
|
One row per completed bucket. :func: |
bucket_volume |
float
|
The bucket size used, in the instrument's own units. |
bucket_volume_rule |
str
|
How the bucket size was chosen: |
n_buckets |
int
|
The trailing window of |
diagnostics
property
¶
Reasons the result should not be relied on; empty when there are none.
The one check is that there are at least :attr:n_buckets complete
buckets. With fewer, vpin_avg never averages a full trailing
window.
Thresholds¶
vpin refuses a bucket size that would make more than
MAX_VOLUME_BUCKETS
buckets.