Metrics package
Market-Specific
Range of metrics to analyze market data.
- pymicrostructure.metrics.market.amihud_illiquidity(market: Market, window: int = 20) DataFrame[source]
Calculate the rolling window Amihud illiquidity measure (lambda) based on trade history.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’, ‘volume’, and ‘time’ keys.
- windowint, optional
The size of the rolling window (in number of periods). Default is 20.
Returns:
- pd.DataFrame
A DataFrame with an ‘amihud_lambda’ column, indexed by time.
- pymicrostructure.metrics.market.effective_spread(market: Market, volume: float, relative: bool = False) DataFrame[source]
Calculate the effective spread of a market for a given order size.
The effective spread is the difference between the execution price of a market order and the midpoint price, multiplied by 2 to account for round-trip costs.
Parameters:
- marketMarket
An object representing the market, which must have an ‘ob_snapshots’ attribute. Each snapshot should be a dictionary with ‘bid’ and ‘ask’ keys, containing lists of price-volume pairs.
- volumefloat
The size of the market order to simulate.
Returns:
- pd.DataFrame
A DataFrame with ‘effective_spread_buy’ and ‘effective_spread_sell’ columns, indexed by snapshot times.
- pymicrostructure.metrics.market.hurst_exponent(market: Market, window: int = 100, max_lag: int = 20) DataFrame[source]
Calculate the rolling Hurst exponent for a price series.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’ and ‘time’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
- max_lagint, optional
The maximum lag to consider in the R/S calculation. Default is 20.
Returns:
- pd.DataFrame
A DataFrame with a ‘hurst_exponent’ column, indexed by time.
- pymicrostructure.metrics.market.kyle_lambda(market: Market, window: int = 20) DataFrame[source]
Calculate the rolling window Kyle’s Lambda based on trade history.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’, ‘volume’, ‘aggressor_side’, and ‘time’ keys.
- windowint, optional
The size of the rolling window (in number of periods). Default is 20.
Returns:
- pd.DataFrame
A DataFrame with a ‘kyle_lambda’ column, indexed by time.
- pymicrostructure.metrics.market.news_goodness(market: Market, window: int = 20) DataFrame[source]
Calculate the rolling window news goodness based on trade history.
The news goodness is the ratio of the number of trades with positive news to the total number of trades.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’, ‘time’, and ‘news’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with a ‘news_goodness’ column, indexed by time.
- pymicrostructure.metrics.market.order_book_depth(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window order book depth based on order book snapshots.
The order book depth is the total volume at the best bid and best ask prices.
Parameters:
- marketMarket
An object representing the market, which must have an ‘ob_snapshots’ attribute. Each snapshot should be a dictionary with ‘bid’ and ‘ask’ keys, containing lists of price-volume pairs.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with ‘bid_depth’ and ‘ask_depth’ columns, indexed by time.
- pymicrostructure.metrics.market.order_book_heatmap(market: Market, frequency: int = 10) DataFrame[source]
Create a heatmap of order book volumes over time.
Parameters:
- marketMarket
An object representing the market, which must have an ‘ob_snapshots’ attribute. Each snapshot should be a dictionary with ‘bid’ and ‘ask’ keys, containing lists of price-volume pairs.
- frequencyint, optional
The frequency of snapshots to include in the heatmap. Default is 10. This parameter can be used to reduce the computation time of the heatmap. At a cost of less resolution.
Returns:
- pd.DataFrame
A DataFrame with order book volumes indexed by time and price level.
- pymicrostructure.metrics.market.order_flow_imbalance(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window order flow imbalance based on trade history.
The order flow imbalance is the ratio of buy volume to total volume.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘volume’ and ‘aggressor_side’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with an ‘order_flow_imbalance’ column, indexed by time.
- pymicrostructure.metrics.market.quoted_spread(market: Market) DataFrame[source]
Calculate the quoted spread of a market.
The quoted spread is the difference between the best bid and best ask prices.
Parameters:
- marketMarket
An object representing the market, which must have an ‘ob_snapshots’ attribute. Each snapshot should be a dictionary with ‘bid’ and ‘ask’ keys.
Returns:
- pd.DataFrame
A DataFrame with a ‘quoted_spread’ column, indexed by snapshot times.
- pymicrostructure.metrics.market.realized_volatility(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window realized volatility based on trade history.
Realized volatility is the standard deviation of price returns over a given window.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’ and ‘time’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with a ‘realized_volatility’ column, indexed by time.
- pymicrostructure.metrics.market.returns_autocorrelation(market: Market, window: int = 20) DataFrame[source]
Calculate the rolling window auto-correlation of returns based on trade history.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’, ‘time’, and ‘aggressor_side’ keys.
- windowint, optional
The size of the rolling window (in number of periods). Default is 20.
Returns:
- pd.DataFrame
A DataFrame with a ‘returns_autocorr’ column, indexed by time.
- pymicrostructure.metrics.market.roll_spread_estimator(market: Market, window_size: int = 100, relative: bool = False) DataFrame[source]
Estimate the rolling spread of a market based on its trade history.
This function calculates the rolling spread using a covariance-based method on the price changes over a specified window size.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’ and ‘time’ keys.
- window_sizeint, optional (default=100)
The size of the rolling window for spread estimation.
- relativebool, optional (default=False)
If True, calculate relative price changes instead of absolute changes.
Returns:
- pd.DataFrame
A DataFrame with a ‘roll_spread’ column, indexed by trade times.
Notes:
The roll spread is estimated as: roll_spread = mult * sqrt(-cov(delta_price_t, delta_price_t-1)) where mult is 200 for relative changes and 2 for absolute changes.
- pymicrostructure.metrics.market.rolling_adf_test(market: Market, window: int = 100, alpha: float = 0.05) DataFrame[source]
Perform a rolling Augmented Dickey-Fuller test on price series.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’ and ‘time’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
- alphafloat, optional
The significance level for the test. Default is 0.05.
Returns:
- pd.DataFrame
A DataFrame with ‘adf_statistic’, ‘p_value’, and ‘is_stationary’ columns, indexed by time.
- pymicrostructure.metrics.market.rolling_cancellation_rate(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window cancellation rate based on order history.
The cancellation rate is the number of canceled orders divided by the total number of orders.
Parameters:
- marketMarket
An object representing the market, which must have a ‘cancellations’ and ‘order_history’ attribute. Each order in the history should be a dictionary with ‘status’ and ‘time’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with a ‘cancellation_rate’ column, indexed by time.
- pymicrostructure.metrics.market.trade_midprice_deviation(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window deviation of trade prices from the midprice based on trade history.
The midprice is the average of the best bid and best ask prices.
Parameters:
- marketMarket
An object representing the market, which must have an ‘ob_snapshots’ and ‘trade_history’ attribute. Each snapshot should be a dictionary with ‘bid’ and ‘ask’ keys, containing lists of price-volume pairs. Each trade in the history should be a dictionary with ‘price’ and ‘time’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with a ‘trade_midprice_deviation’ column, indexed by time.
- pymicrostructure.metrics.market.trade_sign_autocorrelation(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window auto-correlation of trade signs based on trade history.
The trade sign is the sign of the trade price change.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’, ‘time’, and ‘aggressor_side’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with a ‘trade_sign_autocorr’ column, indexed by time.
- pymicrostructure.metrics.market.variance_ratio_test(market: Market, k: int = 5, window: int = 100) DataFrame[source]
Perform a rolling Variance Ratio test on price series.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’ and ‘time’ keys.
- kint, optional
The number of periods to use for the k-period return. Default is 5.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with ‘vr_statistic’ and ‘p_value’ columns, indexed by time.
- pymicrostructure.metrics.market.vwap(market: Market, window: int = 100) DataFrame[source]
Calculate the rolling window volume-weighted average price (VWAP) based on trade history.
Parameters:
- marketMarket
An object representing the market, which must have a ‘trade_history’ attribute. Each trade in the history should be a dictionary with ‘price’, ‘volume’, and ‘time’ keys.
- windowint, optional
The size of the rolling window. Default is 100.
Returns:
- pd.DataFrame
A DataFrame with a ‘vwap’ column, indexed by time.
Trader-Specific
Metric for analyzing trader performance.
- pymicrostructure.metrics.trader.aggressor_ratio(trader: Trader) float[source]
Calculate the ratio of aggressive to total volume.
- pymicrostructure.metrics.trader.average_trade_size(trader: Trader) float[source]
Calculate the average trade size for a trader.
- pymicrostructure.metrics.trader.calculate_trader_metrics(trader: Trader) Dict[str, float][source]
Calculate various performance metrics for a trader.
- Args:
trader (Trader): The trader object.
- Returns:
Dict[str, float]: A dictionary of calculated metrics.
- pymicrostructure.metrics.trader.fill_rate(trader: Trader) float[source]
Calculate the fill rate for a trader.
- pymicrostructure.metrics.trader.final_position(trader: Trader) int[source]
Get the final position of a trader.
- pymicrostructure.metrics.trader.final_profit(trader: Trader) float[source]
Get the final profit of a trader.
- pymicrostructure.metrics.trader.information_ratio(trader: Trader) float[source]
Calculate the information ratio for a trader.
- pymicrostructure.metrics.trader.mean_abs_position(trader: Trader) float[source]
Calculate the mean absolute position of a trader.
- pymicrostructure.metrics.trader.mean_position(trader: Trader) float[source]
Calculate the mean position of a trader.
- pymicrostructure.metrics.trader.participants_report(participants: List[Trader]) DataFrame[source]
Generate a performance report for multiple traders.
- Args:
participants (List[Trader]): A list of trader objects.
- Returns:
pd.DataFrame: A DataFrame containing performance metrics for all traders.
- pymicrostructure.metrics.trader.position_history(trader: Trader) Tuple[List[int], List[int]][source]
Calculate the position history of a trader.
- Args:
trader (Trader): The trader object.
- Returns:
- Tuple[List[int], List[int]]: A tuple containing two lists:
List of timestamps
List of positions at each timestamp
- pymicrostructure.metrics.trader.profit_history(trader: Trader) Tuple[List[int], List[float]][source]
Calculate the profit history of a trader.
- Args:
trader (Trader): The trader object.
- Returns:
- Tuple[List[int], List[float]]: A tuple containing two lists:
List of timestamps
List of cumulative profits at each timestamp
- pymicrostructure.metrics.trader.profit_per_state(trader: Trader) float[source]
Calculate the average profit per state for a trader.
- pymicrostructure.metrics.trader.profit_per_volume(trader: Trader) float[source]
Calculate the profit per unit volume for a trader.
- pymicrostructure.metrics.trader.std_profit_per_state(trader: Trader) float[source]
Calculate the standard deviation of profit per state for a trader.
- pymicrostructure.metrics.trader.time_in_market(trader: Trader) float[source]
Calculate the proportion of time the trader held a non-zero position.
- pymicrostructure.metrics.trader.total_trades(trader: Trader) int[source]
Get the total number of trades for a trader.
- pymicrostructure.metrics.trader.trader_report(trader: Trader) Dict[str, float][source]
Generate a comprehensive report for a single trader.
- pymicrostructure.metrics.trader.volume_as_aggressor(trader: Trader) float[source]
Calculate the volume traded as an aggressor.