# Horizon SDK Reference

Version: 0.4.20

Auto-generated from live module introspection. Every signature below is the real API.

## How to Write a Strategy

Every strategy follows this pattern:

```python
import horizon as hz

def fair_value(ctx: hz.Context) -> float:
    price = ctx.feeds["feed_name"].price
    return price

def quoter(ctx: hz.Context, fair: float) -> list[hz.Quote]:
    return hz.quotes(fair=fair, spread=0.04, size=10)

hz.run(
    name="my_strategy",
    markets=["market-slug"],
    feeds={"feed_name": hz.BinanceWS("btcusdt")},
    pipeline=[fair_value, quoter],
    risk=hz.Risk(max_position=100, max_notional=1000),
)
```

**Pipeline rules:**
- Each function takes `ctx: hz.Context` as first arg
- Return value is passed as kwarg to next function (matched by parameter name)
- Last function returns `list[Quote]` to submit orders
- Dict pipeline for per-market logic: `{'market_a': [fn1], '*': [fn2]}`

**Context object:**
- `ctx.feeds` — dict of FeedData snapshots (price, bid, ask, timestamp)
- `ctx.feed` — shortcut for first/default feed
- `ctx.inventory` — InventorySnapshot (positions, net, net_for_market)
- `ctx.market` — current Market object
- `ctx.market_id` — current market ID string
- `ctx.event` — current Event (if multi-outcome)
- `ctx.status` — EngineStatus (PnL, uptime, kill switch)
- `ctx.params` — custom dict from hz.run(params={...})

## Core Entry Points

### `run(name: 'str', exchange: 'Any' = None, exchanges: 'list[Any] | None' = None, markets: 'list[str] | None' = None, events: 'list[Event] | None' = None, feeds: 'dict[str, Any] | None' = None, pipeline: 'list[Callable] | dict[str, list[Callable]] | None' = None, risk: 'Risk | RiskConfig | None' = None, interval: 'float' = 0.5, mode: 'str' = 'paper', dashboard: 'bool' = False, params: 'dict[str, Any] | None' = None, db_path: 'str | None' = Ellipsis, netting_pairs: 'list[tuple[str, str]] | None' = None, api_key: 'str | None' = None) -> 'None'`

Single entry point to run a strategy.

    Args:
        name: Strategy name (shown in dashboard).
        exchange: Exchange config (Polymarket(...), Kalshi(...), or None for paper).
                  For single-exchange mode (backward compatible).
        exchanges: List of exchange configs for mu...

### `backtest(name: 'str' = 'backtest', markets: 'list[str] | None' = None, data: 'Any' = None, feeds: 'dict[str, Any] | None' = None, pipeline: 'list[Callable] | None' = None, risk: 'Risk | RiskConfig | None' = None, params: 'dict[str, Any] | None' = None, paper_fee_rate: 'float' = 0.001, paper_maker_fee_rate: 'float | None' = None, paper_taker_fee_rate: 'float | None' = None, initial_capital: 'float' = 1000.0, outcomes: 'dict[str, float] | None' = None, book_data: 'dict[str, list[dict]] | None' = None, fill_model: 'str' = 'deterministic', fill_model_params: 'dict[str, float] | None' = None, impact_temporary_bps: 'float' = 0.0, impact_permanent_fraction: 'float' = 0.0, latency_ms: 'float' = 0.0, rng_seed: 'int | None' = None) -> 'BacktestResult'`

Run a backtest over historical data using the same pipeline as hz.run().

    Args:
        name: Strategy name (for logging).
        markets: List of market IDs to quote on. Defaults to ["market"].
        data: Historical data - list[dict], CSV path (str), pandas DataFrame,
              or dict[...

### `BacktestResult` (dataclass)
```python
BacktestResult(
    equity_curve: list[tuple[float, float]] = list(),
    trades: list = list(),
    positions: list = list(),
    initial_capital: float = 1000.0,
    outcomes: dict[str, float] | None = None
)
```

Container for backtest results with lazy metric computation.
- `calibration(self, n_bins: 'int' = 10)`
- `log_loss_score(self) -> 'float'`
- `pnl_by_market(self) -> 'dict[str, float]'`
- `summary(self) -> 'str'`
- `tearsheet(self) -> 'Tearsheet'`
- `to_csv(self, path: 'str', what: 'str' = 'equity') -> 'None'`

### `quotes(fair: float, spread: float, size: float = 5.0) -> list[Quote]`

Helper to create a Quote from fair value and spread.

## Core Types

### `Engine` (class)
```python
Engine(risk_config=None, paper_fee_rate=0.001, exchange_type='paper', exchange_key=None, exchange_secret=None, exchange_passphrase=None, clob_url=None, api_url=None, email=None, password=None, private_key=None, paper_partial_fill_ratio=1.0, db_path=None, api_key=None, fill_model=None, fill_lambda=1.0, fill_kappa=1.5, fill_queue_position=0.5, fill_intensity=1.0, impact_temporary_bps=0.0, impact_permanent_fraction=0.0, latency_ticks=0, rng_seed=None, paper_maker_fee_rate=None, paper_taker_fee_rate=None)
```

The core engine: owns risk, orders, positions, exchanges, feeds, and persistence.
Supports multiple exchanges simultaneously for cross-venue trading.
Exposed to Python via PyO3.

Members:
- `activate_kill_switch` — method: `activate_kill_switch(self, /, reason)`
- `add_exchange` — method: `add_exchange(self, /, exchange_type, exchange_key=None, exchange_secret=None, exchange_passphrase=None, clob_url=None, api_url=None, email=None, password=None, private_key=None, paper_fee_rate=0.001, paper_partial_fill_ratio=1.0, paper_maker_fee_rate=None, paper_taker_fee_rate=None)`
- `add_stop_loss` — method: `add_stop_loss(self, /, market_id, side, order_side, size, trigger_price, exchange=None)`
- `add_take_profit` — method: `add_take_profit(self, /, market_id, side, order_side, size, trigger_price, trigger_pnl=None, exchange=None)`
- `all_feed_metrics` — method: `all_feed_metrics(self, /)`
- `all_feed_snapshots` — method: `all_feed_snapshots(self, /)`
- `all_orderbook_snapshots` — method: `all_orderbook_snapshots(self, /)`
- `amend_order` — method: `amend_order(self, /, order_id, new_price=None, new_size=None)`
- `cancel` — method: `cancel(self, /, order_id)`
- `cancel_all` — method: `cancel_all(self, /)`
- `cancel_contingent` — method: `cancel_contingent(self, /, contingent_id)`
- `cancel_market` — method: `cancel_market(self, /, market_id)`
- `check_contingent_triggers` — method: `check_contingent_triggers(self, /, market_id, current_price)`
- `check_lifecycle` — method: `check_lifecycle(self, /)`
- `check_order_scoring` — method: `check_order_scoring(self, /, order_id, exchange=None)`
- `db_open_order_ids` — method: `db_open_order_ids(self, /)`
- `db_run_id` — method: `db_run_id(self, /)`
- `deactivate_kill_switch` — method: `deactivate_kill_switch(self, /)`
- `end_run` — method: `end_run(self, /)`
- `event_exposure` — method: `event_exposure(self, /, event_id)`
- `event_parity_check` — method: `event_parity_check(self, /, event_id, threshold=0.02)`
- `event_positions` — method: `event_positions(self, /, event_id)`
- `evict_stale_orders` — method: `evict_stale_orders(self, /, max_age_secs=300.0)`
- `exchange_count` — method: `exchange_count(self, /)`
- `exchange_name` — method: `exchange_name(self, /)`
- `exchange_names` — method: `exchange_names(self, /)`
- `execute_arbitrage` — method: `execute_arbitrage(self, /, market_id, buy_exchange, sell_exchange, buy_price, sell_price, size, side=None, token_id=None, neg_risk=False)`
- `execute_event_arb` — method: `execute_event_arb(self, /, event_id, direction, size, exchange=None, proportional=True, token_id=None, neg_risk=False)`
- `execute_parity_arb` — method: `execute_parity_arb(self, /, market_id, exchange, yes_price, no_price, size, token_id=None, neg_risk=False)`
- `feed_age` — method: `feed_age(self, /, name)`

### `Market` (class)
```python
Market(id, name='', slug='', exchange='paper', expiry=None, active=True, yes_token_id=None, no_token_id=None, condition_id=None, neg_risk=False, ticker=None, event_id=None, outcome_name=None)
```

A prediction market.

Members:
- `active` — = `<attribute 'active' of 'builtins.Market' objects>`
- `condition_id` — = `<attribute 'condition_id' of 'builtins.Market' objects>`
- `event_id` — = `<attribute 'event_id' of 'builtins.Market' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.Market' objects>`
- `expiry` — = `<attribute 'expiry' of 'builtins.Market' objects>`
- `id` — = `<attribute 'id' of 'builtins.Market' objects>`
- `name` — = `<attribute 'name' of 'builtins.Market' objects>`
- `neg_risk` — = `<attribute 'neg_risk' of 'builtins.Market' objects>`
- `no_token_id` — = `<attribute 'no_token_id' of 'builtins.Market' objects>`
- `outcome_name` — = `<attribute 'outcome_name' of 'builtins.Market' objects>`
- `slug` — = `<attribute 'slug' of 'builtins.Market' objects>`
- `ticker` — = `<attribute 'ticker' of 'builtins.Market' objects>`
- `token_id` — method: `token_id(self, /, side)`
- `yes_token_id` — = `<attribute 'yes_token_id' of 'builtins.Market' objects>`

### `Quote` (class)
```python
Quote(bid, ask, size)
```

A quote (bid + ask at a size).

Members:
- `ask` — = `<attribute 'ask' of 'builtins.Quote' objects>`
- `bid` — = `<attribute 'bid' of 'builtins.Quote' objects>`
- `mid` — method: `mid(self, /)`
- `size` — = `<attribute 'size' of 'builtins.Quote' objects>`
- `spread` — method: `spread(self, /)`

### `OrderRequest` (class)
```python
OrderRequest(market_id, side, order_side, size, price, order_type=Ellipsis, time_in_force=Ellipsis, post_only=True, token_id=None, neg_risk=False)
```

An order request (input to the engine).

Members:
- `market_id` — = `<attribute 'market_id' of 'builtins.OrderRequest' objects>`
- `neg_risk` — = `<attribute 'neg_risk' of 'builtins.OrderRequest' objects>`
- `order_side` — = `<attribute 'order_side' of 'builtins.OrderRequest' objects>`
- `order_type` — = `<attribute 'order_type' of 'builtins.OrderRequest' objects>`
- `post_only` — = `<attribute 'post_only' of 'builtins.OrderRequest' objects>`
- `price` — = `<attribute 'price' of 'builtins.OrderRequest' objects>`
- `side` — = `<attribute 'side' of 'builtins.OrderRequest' objects>`
- `size` — = `<attribute 'size' of 'builtins.OrderRequest' objects>`
- `time_in_force` — = `<attribute 'time_in_force' of 'builtins.OrderRequest' objects>`
- `token_id` — = `<attribute 'token_id' of 'builtins.OrderRequest' objects>`

### `Order` (class)
```python
Order($self, /, *args, **kwargs)
```

An order with current state.

Members:
- `amendment_count` — = `<attribute 'amendment_count' of 'builtins.Order' objects>`
- `created_at` — = `<attribute 'created_at' of 'builtins.Order' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.Order' objects>`
- `filled_size` — = `<attribute 'filled_size' of 'builtins.Order' objects>`
- `id` — = `<attribute 'id' of 'builtins.Order' objects>`
- `is_open` — method: `is_open(self, /)`
- `market_id` — = `<attribute 'market_id' of 'builtins.Order' objects>`
- `neg_risk` — = `<attribute 'neg_risk' of 'builtins.Order' objects>`
- `order_side` — = `<attribute 'order_side' of 'builtins.Order' objects>`
- `order_type` — = `<attribute 'order_type' of 'builtins.Order' objects>`
- `price` — = `<attribute 'price' of 'builtins.Order' objects>`
- `remaining_size` — = `<attribute 'remaining_size' of 'builtins.Order' objects>`
- `side` — = `<attribute 'side' of 'builtins.Order' objects>`
- `size` — = `<attribute 'size' of 'builtins.Order' objects>`
- `status` — = `<attribute 'status' of 'builtins.Order' objects>`
- `status_reason` — = `<attribute 'status_reason' of 'builtins.Order' objects>`
- `time_in_force` — = `<attribute 'time_in_force' of 'builtins.Order' objects>`
- `token_id` — = `<attribute 'token_id' of 'builtins.Order' objects>`

### `Position` (class)
```python
Position($self, /, *args, **kwargs)
```

A position in a market.

Members:
- `avg_entry_price` — = `<attribute 'avg_entry_price' of 'builtins.Position' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.Position' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.Position' objects>`
- `notional` — method: `notional(self, /)`
- `realized_pnl` — = `<attribute 'realized_pnl' of 'builtins.Position' objects>`
- `side` — = `<attribute 'side' of 'builtins.Position' objects>`
- `size` — = `<attribute 'size' of 'builtins.Position' objects>`
- `token_id` — = `<attribute 'token_id' of 'builtins.Position' objects>`
- `total_pnl` — method: `total_pnl(self, /)`
- `unrealized_pnl` — = `<attribute 'unrealized_pnl' of 'builtins.Position' objects>`

### `Fill` (class)
```python
Fill(fill_id, order_id, market_id, side, order_side, price, size, fee=0.0, timestamp=0.0, token_id=None, exchange='', is_maker=False)
```

A fill event.

Members:
- `exchange` — = `<attribute 'exchange' of 'builtins.Fill' objects>`
- `fee` — = `<attribute 'fee' of 'builtins.Fill' objects>`
- `fill_id` — = `<attribute 'fill_id' of 'builtins.Fill' objects>`
- `is_maker` — = `<attribute 'is_maker' of 'builtins.Fill' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.Fill' objects>`
- `order_id` — = `<attribute 'order_id' of 'builtins.Fill' objects>`
- `order_side` — = `<attribute 'order_side' of 'builtins.Fill' objects>`
- `price` — = `<attribute 'price' of 'builtins.Fill' objects>`
- `side` — = `<attribute 'side' of 'builtins.Fill' objects>`
- `size` — = `<attribute 'size' of 'builtins.Fill' objects>`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.Fill' objects>`
- `token_id` — = `<attribute 'token_id' of 'builtins.Fill' objects>`

### `EngineStatus` (class)
```python
EngineStatus($self, /, *args, **kwargs)
```

Engine status snapshot.

Members:
- `active_positions` — = `<attribute 'active_positions' of 'builtins.EngineStatus' objects>`
- `daily_pnl` — = `<attribute 'daily_pnl' of 'builtins.EngineStatus' objects>`
- `kill_switch_active` — = `<attribute 'kill_switch_active' of 'builtins.EngineStatus' objects>`
- `kill_switch_reason` — = `<attribute 'kill_switch_reason' of 'builtins.EngineStatus' objects>`
- `open_orders` — = `<attribute 'open_orders' of 'builtins.EngineStatus' objects>`
- `running` — = `<attribute 'running' of 'builtins.EngineStatus' objects>`
- `total_pnl` — method: `total_pnl(self, /)`
- `total_realized_pnl` — = `<attribute 'total_realized_pnl' of 'builtins.EngineStatus' objects>`
- `total_unrealized_pnl` — = `<attribute 'total_unrealized_pnl' of 'builtins.EngineStatus' objects>`
- `uptime_secs` — = `<attribute 'uptime_secs' of 'builtins.EngineStatus' objects>`

### `FeedSnapshot` (class)
```python
FeedSnapshot(price=0.0, timestamp=0.0, source='', bid=0.0, ask=0.0, volume_24h=0.0, last_trade_size=0.0, last_trade_is_buy=False)
```

Snapshot of a single feed's latest data.

Members:
- `ask` — = `<attribute 'ask' of 'builtins.FeedSnapshot' objects>`
- `bid` — = `<attribute 'bid' of 'builtins.FeedSnapshot' objects>`
- `last_trade_is_buy` — = `<attribute 'last_trade_is_buy' of 'builtins.FeedSnapshot' objects>`
- `last_trade_size` — = `<attribute 'last_trade_size' of 'builtins.FeedSnapshot' objects>`
- `price` — = `<attribute 'price' of 'builtins.FeedSnapshot' objects>`
- `source` — = `<attribute 'source' of 'builtins.FeedSnapshot' objects>`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.FeedSnapshot' objects>`
- `volume_24h` — = `<attribute 'volume_24h' of 'builtins.FeedSnapshot' objects>`

### `RiskConfig` (class)
```python
RiskConfig(max_position_per_market=100.0, max_portfolio_notional=1000.0, max_daily_drawdown_pct=5.0, max_order_size=50.0, rate_limit_sustained=50, rate_limit_burst=300, dedup_window_ms=1000, max_position_per_event=None)
```

Risk configuration for the engine.

Members:
- `dedup_window_ms` — = `<attribute 'dedup_window_ms' of 'builtins.RiskConfig' objects>`
- `max_daily_drawdown_pct` — = `<attribute 'max_daily_drawdown_pct' of 'builtins.RiskConfig' objects>`
- `max_order_size` — = `<attribute 'max_order_size' of 'builtins.RiskConfig' objects>`
- `max_portfolio_notional` — = `<attribute 'max_portfolio_notional' of 'builtins.RiskConfig' objects>`
- `max_position_per_event` — = `<attribute 'max_position_per_event' of 'builtins.RiskConfig' objects>`
- `max_position_per_market` — = `<attribute 'max_position_per_market' of 'builtins.RiskConfig' objects>`
- `rate_limit_burst` — = `<attribute 'rate_limit_burst' of 'builtins.RiskConfig' objects>`
- `rate_limit_sustained` — = `<attribute 'rate_limit_sustained' of 'builtins.RiskConfig' objects>`

### `Context` (dataclass)
```python
Context(
    feeds: dict[str, FeedData] = dict(),
    inventory: InventorySnapshot = InventorySnapshot(),
    market: Market | None = None,
    event: Event | None = None,
    status: EngineStatus | None = None,
    params: dict[str, Any] = dict()
)
```

Context injected into every pipeline function.

    Provides access to feeds, inventory, market info, engine status,
    and arbitrary user parameters.

### `Risk` (class)
```python
Risk(max_position: 'float' = 100.0, max_notional: 'float' = 1000.0, max_drawdown_pct: 'float' = 5.0, max_order_size: 'float' = 50.0, rate_limit: 'int' = 50, rate_burst: 'int' = 300)
```

Declarative risk config builder.

    Usage:
        Risk(max_position=100, max_drawdown_pct=5)

Members:
- `to_config` — method: `to_config(self) -> 'RiskConfig'`

## Enums

### `Side` (class)
```python
Side($self, /, *args, **kwargs)
```

Side of a prediction market outcome.

Members:
- `No` — = `Side.No`
- `Yes` — = `Side.Yes`

### `OrderSide` (class)
```python
OrderSide($self, /, *args, **kwargs)
```

Buy or Sell direction.

Members:
- `Buy` — = `OrderSide.Buy`
- `Sell` — = `OrderSide.Sell`

### `OrderType` (class)
```python
OrderType($self, /, *args, **kwargs)
```

Order type.

Members:
- `Limit` — = `OrderType.Limit`
- `Market` — = `OrderType.Market`

### `TimeInForce` (class)
```python
TimeInForce($self, /, *args, **kwargs)
```

Time in force.

Members:
- `FAK` — = `TimeInForce.FAK`
- `FOK` — = `TimeInForce.FOK`
- `GTC` — = `TimeInForce.GTC`
- `GTD` — = `TimeInForce.GTD`

### `OrderStatus` (class)
```python
OrderStatus($self, /, *args, **kwargs)
```

Order status.

Members:
- `Accepted` — = `OrderStatus.Accepted`
- `Canceled` — = `OrderStatus.Canceled`
- `Filled` — = `OrderStatus.Filled`
- `New` — = `OrderStatus.New`
- `PartiallyFilled` — = `OrderStatus.PartiallyFilled`
- `Rejected` — = `OrderStatus.Rejected`
- `Submitted` — = `OrderStatus.Submitted`

### `AlertLevel` (class)
```python
AlertLevel($self, /, *args, **kwargs)
```

Alert level for risk events.

Members:
- `Critical` — = `AlertLevel.Critical`
- `Info` — = `AlertLevel.Info`
- `Warning` — = `AlertLevel.Warning`

### `TriggerType` (class)
```python
TriggerType($self, /, *args, **kwargs)
```

Type of contingent order trigger.

Members:
- `StopLoss` — = `TriggerType.StopLoss`
- `TakeProfit` — = `TriggerType.TakeProfit`

## Multi-Outcome Events

### `Outcome` (class)
```python
Outcome(name, market_id, yes_token_id=None, no_token_id=None, yes_price=0.0)
```

One named outcome in a multi-outcome event. Each outcome is a binary contract.

Members:
- `market_id` — = `<attribute 'market_id' of 'builtins.Outcome' objects>`
- `name` — = `<attribute 'name' of 'builtins.Outcome' objects>`
- `no_token_id` — = `<attribute 'no_token_id' of 'builtins.Outcome' objects>`
- `token_id` — method: `token_id(self, /, side)`
- `yes_price` — = `<attribute 'yes_price' of 'builtins.Outcome' objects>`
- `yes_token_id` — = `<attribute 'yes_token_id' of 'builtins.Outcome' objects>`

### `Event` (class)
```python
Event(id, name, outcomes, neg_risk=False, exchange='polymarket', condition_id=None, expiry=None)
```

Groups outcomes under a shared condition_id for multi-outcome events.

Members:
- `condition_id` — = `<attribute 'condition_id' of 'builtins.Event' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.Event' objects>`
- `expiry` — = `<attribute 'expiry' of 'builtins.Event' objects>`
- `id` — = `<attribute 'id' of 'builtins.Event' objects>`
- `name` — = `<attribute 'name' of 'builtins.Event' objects>`
- `neg_risk` — = `<attribute 'neg_risk' of 'builtins.Event' objects>`
- `outcome_by_name` — method: `outcome_by_name(self, /, name)`
- `outcome_count` — method: `outcome_count(self, /)`
- `outcome_names` — method: `outcome_names(self, /)`
- `outcomes` — = `<attribute 'outcomes' of 'builtins.Event' objects>`
- `to_markets` — method: `to_markets(self, /)`

## Exchanges

### `Polymarket` (dataclass)
```python
Polymarket(
    private_key: str | None = None,
    clob_url: str = 'https://clob.polymarket.com',
    gamma_url: str = 'https://gamma-api.polymarket.com',
    api_key: str | None = None,
    api_secret: str | None = None,
    api_passphrase: str | None = None
)
```

Polymarket exchange configuration.

    Credentials are resolved in this order:
    1. Explicit constructor arguments
    2. Environment variables (POLYMARKET_PRIVATE_KEY, POLYMARKET_API_KEY, etc.)

    Usage:
        Polymarket(private_key="0x...")  # explicit
        Polymarket()                     # from env vars
- `derive_api_credentials(self) -> 'None'`

### `Kalshi` (dataclass)
```python
Kalshi(
    email: str | None = None,
    password: str | None = None,
    api_key: str | None = None,
    api_url: str = 'https://trading-api.kalshi.com/trade-api/v2'
)
```

Kalshi exchange configuration.

    Credentials are resolved in this order:
    1. Explicit constructor arguments
    2. Environment variables (KALSHI_EMAIL, KALSHI_PASSWORD, KALSHI_API_KEY)

    Usage:
        Kalshi(email="...", password="...")  # explicit
        Kalshi()                             # from env vars

### `Alpaca` (dataclass)
```python
Alpaca(
    api_key: str | None = None,
    api_secret: str | None = None,
    paper: bool = True,
    api_url: str | None = None,
    data_source: str = 'iex'
)
```

Alpaca Markets exchange configuration.

    Credentials are resolved in this order:
    1. Explicit constructor arguments
    2. Environment variables (ALPACA_API_KEY / APCA_API_KEY_ID,
       ALPACA_API_SECRET / APCA_API_SECRET_KEY)

    Usage:
        Alpaca(api_key="...", api_secret="...")  # explicit
        Alpaca()                                  # from env vars
        Alpaca(paper=False)                       # live trading

## Feeds

### `BinanceWS` (dataclass)
```python
BinanceWS(
    symbol: str
)
```

Binance WebSocket price feed.

    Usage: BinanceWS("btcusdt")

### `RESTFeed` (dataclass)
```python
RESTFeed(
    url: str,
    interval: float = 5.0
)
```

Generic REST API price feed.

    Usage: RESTFeed("https://api.example.com/price", interval=5.0)

### `PolymarketBook` (dataclass)
```python
PolymarketBook(
    market_slug: str
)
```

Polymarket orderbook feed.

    Usage: PolymarketBook("will-btc-hit-100k")

### `KalshiBook` (dataclass)
```python
KalshiBook(
    ticker: str
)
```

Kalshi orderbook feed.

    Usage: KalshiBook("KXBTC-25FEB16")

### `PredictItFeed` (dataclass)
```python
PredictItFeed(
    market_id: int,
    contract_id: int | None = None,
    interval: float = 5.0
)
```

PredictIt market price feed.

    Polls the PredictIt API for contract prices.

    Usage: PredictItFeed(market_id=7456, contract_id=28562)

### `ManifoldFeed` (dataclass)
```python
ManifoldFeed(
    slug: str,
    interval: float = 5.0
)
```

Manifold Markets probability feed.

    Polls the Manifold API for market probability.

    Usage: ManifoldFeed("will-btc-hit-100k-by-2026")

### `ESPNFeed` (dataclass)
```python
ESPNFeed(
    sport: str,
    league: str,
    event_id: str | None = None,
    interval: float = 10.0
)
```

ESPN live scoreboard feed.

    Polls ESPN for live game scores.

    Usage: ESPNFeed("basketball", "nba")

### `NWSFeed` (dataclass)
```python
NWSFeed(
    office: str = '',
    grid_x: int = 0,
    grid_y: int = 0,
    state: str = '',
    mode: str = 'forecast',
    user_agent: str = 'Horizon-SDK/0.4.7',
    interval: float = 60.0
)
```

National Weather Service feed.

    Two modes:
      - forecast: temperature, wind, precipitation for a grid point
      - alerts: active weather alerts for a state

    Usage:
        NWSFeed(office="TOP", grid_x=31, grid_y=80)  # forecast
        NWSFeed(state="FL", mode="alerts")             # alerts

### `RESTJsonPathFeed` (dataclass)
```python
RESTJsonPathFeed(
    url: str,
    price_path: str | None = None,
    bid_path: str | None = None,
    ask_path: str | None = None,
    volume_path: str | None = None,
    interval: float = 5.0
)
```

Enhanced REST feed with JSON path extraction.

    Uses dot-notation paths to map any JSON field to price/bid/ask/volume.

    Usage:
        RESTJsonPathFeed(
            url="https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd",
            price_path="bitcoin.usd",
        )

### `ChainlinkFeed` (dataclass)
```python
ChainlinkFeed(
    contract_address: str,
    rpc_url: str,
    decimals: int = 8,
    interval: float = 10.0
)
```

Chainlink on-chain price oracle feed.

    Reads price data from a Chainlink aggregator proxy contract via
    JSON-RPC eth_call. Works with any EVM chain (Ethereum, Arbitrum,
    Polygon, BSC).

    Usage:
        ChainlinkFeed(
            contract_address="0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419",
            rpc_url="https://eth.llamarpc.com",
        )

### `MempoolFeed` (dataclass)
```python
MempoolFeed(
    rpc_url: str = '',
    ctf_addresses: list[str] = <lambda>(),
    interval: float = 2.0
)
```

Polygon mempool watcher feed.

    Monitors pending transactions to Polymarket CTF exchange contracts
    for large order flow visibility.

    Usage:
        MempoolFeed(rpc_url="https://polygon-rpc.com")

### `AlpacaFeed` (dataclass)
```python
AlpacaFeed(
    symbols: list[str] = list(),
    api_key: str | None = None,
    api_secret: str | None = None,
    data_source: str = 'iex'
)
```

Alpaca Markets real-time stock data feed.

    Streams trades and quotes via WebSocket for stock symbols.

    Usage:
        AlpacaFeed(symbols=["AAPL", "SPY"])
        AlpacaFeed(symbols=["TLT"], data_source="sip")

### `CalendarFeed` (dataclass)
```python
CalendarFeed(
    events_json: str = '',
    api_url: str = '',
    interval: float = 300.0
)
```

Calendar/event feed for economic events and earnings.

    Polls bundled or API-provided event data, maps nearest event to
    FeedSnapshot fields (bid=seconds_to_event, ask=event_type_code).

    Usage:
        CalendarFeed()  # uses bundled FOMC/CPI dates
        CalendarFeed(api_url="https://api.example.com/events")

### `TreasuryFeed` (dataclass)
```python
TreasuryFeed(
    api_key: str | None = None,
    series_ids: list[str] = <lambda>(),
    primary_series: str = 'DGS10',
    interval: float = 300.0
)
```

Treasury yield curve feed via FRED API.

    Polls the Federal Reserve Economic Data API for yield curve data.

    Usage:
        TreasuryFeed(api_key="your_fred_api_key")
        TreasuryFeed()  # uses FRED_API_KEY env var

## Kelly Criterion & Sizing

### `edge(prob, market_price)`

Compute the expected edge (expected value per dollar risked).

For buying YES: edge = prob * (1 - price) - (1 - prob) * price = prob - price
Returns the raw edge (can be negative if no edge).

### `kelly(prob, market_price)`

Kelly fraction for buying YES at `market_price` when true probability is `prob`.

Formula: f* = (p - P) / (1 - P)
Returns 0.0 if no edge (prob <= price) or invalid inputs.
Result is the fraction of bankroll to risk.

### `kelly_no(prob, market_price)`

Kelly fraction for the NO side — buying NO at `1 - market_price`.

Formula: f* = (P - p) / P
Use when you believe the market is overpriced (prob < market_price).

### `fractional_kelly(prob, market_price, fraction)`

Fractional Kelly — multiplies raw Kelly by a fraction (typically 0.25–0.5)
to reduce variance at the cost of slightly lower expected growth.

### `kelly_size(prob, market_price, bankroll, fraction, max_size)`

Compute the actual contract size from Kelly fraction.

`bankroll`: total capital available.
`fraction`: Kelly scaling factor (1.0 = full Kelly, 0.5 = half Kelly).
`max_size`: hard cap on position size (from risk config).

Returns number of contracts to buy at `market_price`.

### `multi_kelly(probs, prices, max_total)`

Independent multi-outcome Kelly: compute Kelly fractions for N binary outcomes.

Each outcome is treated independently. If total allocation exceeds 1.0,
fractions are proportionally scaled down to sum to at most `max_total`.

Returns a Vec of Kelly fractions (one per outcome).

### `liquidity_adjusted_kelly(prob, market_price, bankroll, fraction, available_liquidity, max_size)`

Liquidity-adjusted Kelly: reduces sizing when available liquidity is thin.

Uses square-root scaling: as your target size approaches available liquidity,
you face increasing market impact. The sqrt dampens aggressive sizing.

`available_liquidity`: total shares available at or near the target price.

### `kelly_sizer(fraction: 'float' = 0.25, bankroll: 'float' = 1000.0, max_size: 'float' = 100.0) -> 'Callable[[Context, float], float]'`

Create a pipeline function that sizes positions using Kelly criterion.

    The returned function takes (ctx, estimated_prob) and returns the
    optimal contract size.

    Args:
        fraction: Kelly fraction (0.25 = quarter Kelly). Lower = less variance.
        bankroll: Total capital availabl...

### `kelly_sizer_with_liquidity(fraction: 'float' = 0.25, bankroll: 'float' = 1000.0, max_size: 'float' = 100.0) -> 'Callable[[Context, float], float]'`

Like kelly_sizer but adjusts for available liquidity.

    Uses the ask-side depth from feeds to dampen sizing in thin books.

### `yield_adjusted_kelly(prob, price, rfr, duration_days, fraction=1.0)`

Yield-adjusted Kelly fraction.

Adjusts standard Kelly by subtracting the risk-free opportunity cost.
Accounts for the fact that capital locked in a prediction market position
could otherwise earn the risk-free rate.

Formula: max(0, kelly(prob, price) - rfr * duration_days / 365) * fraction

### `opportunity_cost(notional, rfr, duration_days)`

Compute the opportunity cost of locking capital at a given risk-free rate.

Returns the dollar amount of risk-free interest foregone.

### `breakeven_edge(rfr, duration_days)`

Compute the breakeven edge required to justify a position given the risk-free rate.

If your edge is below this threshold, you'd be better off earning risk-free returns.

### `yield_adjusted_kelly_size(prob, price, rfr, duration_days, bankroll, fraction=0.5, max_size=1000.0)`

Yield-adjusted Kelly sizing (contracts).

Combines yield-adjusted Kelly fraction with bankroll sizing.

### `yield_adjusted_sizer(rfr_feed: 'str' = 'treasury', duration_days: 'float' = 30.0, fraction: 'float' = 0.5, bankroll: 'float' = 10000.0, max_size: 'float' = 1000.0) -> 'Callable'`

Size positions using yield-adjusted Kelly criterion.

    Reduces position size when the risk-free rate makes the opportunity
    cost of capital too high relative to the edge.

### `opportunity_cost_filter(rfr_feed: 'str' = 'treasury', duration_days: 'float' = 30.0, min_edge_multiple: 'float' = 2.0) -> 'Callable'`

Filter out trades where edge doesn't justify opportunity cost.

### `collateral_optimizer(rfr_feed: 'str' = 'treasury', max_utilization: 'float' = 0.8) -> 'Callable'`

Optimize capital allocation considering yield curve shape.

## Signals

### `Signal` (dataclass)
```python
Signal(
    name: str,
    fn: Callable[[Context], float],
    weight: float = 1.0
)
```

A named signal with a weight for combination.

### `signal_combiner(signals: 'list[Signal]', method: 'str' = 'weighted_avg', smoothing: 'int' = 0, clip: 'tuple[float, float]' = (0.0, 1.0)) -> 'Callable[[Context], float]'`

Create a pipeline function that combines multiple signals.

    Args:
        signals: List of Signal objects to combine.
        method: "weighted_avg", "rank", or "zscore".
        smoothing: EMA smoothing span (0 = disabled).
        clip: (min, max) range to clamp the output.

    Returns:
     ...

### `price_signal(feed_name: 'str', weight: 'float' = 1.0) -> 'Signal'`

Extract mid price from a feed as a signal (0-1 for prediction markets).

    Args:
        feed_name: Name of the feed to read from.
        weight: Signal weight for combination.

### `imbalance_signal(feed_name: 'str', levels: 'int' = 5, weight: 'float' = 1.0) -> 'Signal'`

Extract orderbook imbalance as a signal (0-1, >0.5 = buy pressure).

    Args:
        feed_name: Name of the orderbook feed.
        levels: Number of levels to compute imbalance over.
        weight: Signal weight.

### `spread_signal(feed_name: 'str', weight: 'float' = 1.0) -> 'Signal'`

Extract bid-ask spread as a signal (0-1, tighter = higher).

    Args:
        feed_name: Name of the feed.
        weight: Signal weight.

### `momentum_signal(feed_name: 'str', lookback: 'int' = 20, weight: 'float' = 1.0) -> 'Signal'`

Extract rolling return as a signal (0-1, >0.5 = uptrend).

    Args:
        feed_name: Name of the feed.
        lookback: Number of ticks for rolling window.
        weight: Signal weight.

### `flow_signal(feed_name: 'str', window: 'int' = 50, weight: 'float' = 1.0) -> 'Signal'`

Extract volume flow direction as a signal (0-1, >0.5 = buy flow).

    Tracks price changes to infer flow direction (tick rule).

    Args:
        feed_name: Name of the feed.
        window: Number of ticks for volume flow window.
        weight: Signal weight.

### `combine_signals(signals, method='weighted_avg')`

Combine multiple (value, weight) signals using the specified method.

Methods:
- "weighted_avg" (default): weighted average of signal values
- "rank": average of rank-normalized values (0..1)
- "zscore": weighted average of z-score normalized values, then sigmoid to [0,1]

Returns 0.0 if no valid si...

### `ema(values, span)`

Exponential moving average of a series.

`span` determines the decay factor: alpha = 2 / (span + 1).
Returns the final EMA value, or 0.0 if input is empty.

### `zscore(value, mean, std)`

Z-score normalization: (value - mean) / std.

Returns 0.0 if std is zero or any input is NaN/Inf.

### `decay_weight(age_secs, half_life_secs)`

Exponential time decay weight.

`age_secs`: how old the observation is (seconds).
`half_life_secs`: time for the weight to decay to 0.5.

Returns weight in (0, 1]. Returns 0.0 for invalid inputs.

## Market Making

### `reservation_price(mid, inventory, gamma, volatility, time_horizon)`

Avellaneda-Stoikov reservation price: inventory-skewed fair value.

Formula: r = mid - inventory * gamma * volatility^2 * time_horizon

- `mid`: current mid price
- `inventory`: net inventory (positive = long, negative = short)
- `gamma`: risk aversion parameter (higher = more aggressive skew)
- `vo...

### `optimal_spread(volatility, inventory, gamma, kappa, time_horizon)`

Optimal bid-ask spread width (Avellaneda-Stoikov).

Formula: spread = gamma * sigma^2 * T + (2/gamma) * ln(1 + gamma/kappa)

- `volatility`: estimated price volatility
- `inventory`: net inventory (used indirectly via gamma)
- `gamma`: risk aversion parameter
- `kappa`: order arrival intensity (high...

### `competitive_spread(base_spread, book_spread, book_imbalance, aggression)`

Competitive spread: blend model spread with observed market spread.

- `base_spread`: model-derived optimal spread
- `book_spread`: observed bid-ask spread from orderbook
- `book_imbalance`: orderbook imbalance in [-1, 1] (>0 = buy pressure)
- `aggression`: 0.0 = use model spread, 1.0 = use book spr...

### `mm_size(base_size, inventory, max_position, fill_rate, skew_factor)`

Inventory-skewed bid/ask sizes.

Returns (bid_size, ask_size) adjusted for inventory.
When long, reduce bid size and increase ask size to reduce inventory.

- `base_size`: starting size for both sides
- `inventory`: net inventory (positive = long)
- `max_position`: maximum allowed position
- `fill_r...

### `estimate_volatility(prices, annualize=False)`

Estimate volatility from a price series using log-return standard deviation.

Returns 0.0 if fewer than 2 prices or all prices are the same.
When `annualize` is true, multiplies by sqrt(365) for prediction market calendar.

### `market_maker(base_spread: 'float' = 0.04, gamma: 'float' = 0.5, kappa: 'float' = 1.5, max_position: 'float' = 100.0, num_levels: 'int' = 1, level_spacing: 'float' = 0.01, aggression: 'float' = 0.5, volatility_window: 'int' = 50, feed_name: 'str | None' = None, size: 'float' = 5.0, skew_factor: 'float' = 0.5, time_horizon: 'float' = 1.0) -> 'Callable[[Context], list[Quote]]'`

Create a pipeline function that generates market making quotes.

    Uses Avellaneda-Stoikov reservation price and optimal spread,
    blended with observed market spread, with inventory-skewed sizing.

    Args:
        base_spread: Fallback spread when model spread unavailable.
        gamma: Risk...

### `inventory_skewer(max_skew: 'float' = 0.03, half_life_secs: 'float' = 300.0, skew_factor: 'float' = 1.0, max_position: 'float' = 100.0) -> 'Callable[[Context, list[Quote]], list[Quote]]'`

Create an inventory skew modifier.

    Shifts bid and ask prices based on current inventory to encourage
    mean reversion of positions. As inventory ages, urgency increases.

    Args:
        max_skew: Maximum price skew (e.g. 0.03 = 3 cents).
        half_life_secs: Position age half-life for u...

### `adaptive_spread(fill_rate_window: 'int' = 100, vol_window: 'int' = 50, fill_rate_target: 'float' = 0.3, vol_sensitivity: 'float' = 2.0, imbalance_sensitivity: 'float' = 0.5, min_multiplier: 'float' = 0.5, max_multiplier: 'float' = 3.0) -> 'Callable[[Context, list[Quote]], list[Quote]]'`

Create an adaptive spread modifier.

    Scales the bid-ask spread based on market conditions:
    - High fill rate → widen spread (adverse selection)
    - High volatility → widen spread (risk)
    - High imbalance → widen spread (one-sided flow)

    Args:
        fill_rate_window: Window for fill...

### `SpreadMetrics` (dataclass)
```python
SpreadMetrics(
    fill_rate: float = 0.0,
    realized_vol: float = 0.0,
    imbalance: float = 0.0,
    spread_multiplier: float = 1.0
)
```

Metrics computed by the adaptive spread modifier.

### `toxicity_adjusted_spread(base_spread, vpin, sensitivity=1.0)`

Adjust spread based on VPIN toxicity signal.

- `base_spread`: baseline spread (0..1)
- `vpin`: VPIN value from VpinDetector (0..1)
- `sensitivity`: how aggressively to widen (0..10, default 1.0)

Returns `base_spread * (1 + sensitivity * vpin)`, clamped to [0, 1].

## Volatility

### `parkinson_vol(highs, lows, annualize=True)`

Parkinson high/low range volatility estimator.

More efficient than close-to-close by using intra-period range.
Returns 0.0 on empty/invalid input.

### `garman_klass_vol(opens, highs, lows, closes, annualize=True)`

Garman-Klass OHLC volatility estimator.

The most efficient standard estimator using open, high, low, close data.
Returns 0.0 on empty/invalid input.

### `yang_zhang_vol(opens, highs, lows, closes, annualize=True)`

Yang-Zhang volatility estimator.

Combines overnight jump, open-to-close, and Rogers-Satchell components.
Handles opening jumps — the most robust OHLC estimator.
Returns 0.0 on insufficient/invalid input (needs >= 2 bars).

### `ewma_vol(prices, span=20, annualize=True)`

Exponentially weighted moving average (EWMA) volatility.

Reactive to recent price changes. Uses RiskMetrics-style EWMA of squared returns.

- `prices`: price series
- `span`: EWMA span (default 20, like a 20-period half-life)
- `annualize`: multiply by sqrt(365) for prediction markets

Returns 0.0 ...

### `rolling_vol(prices, window=20, annualize=True)`

Rolling realized volatility series.

Computes windowed standard deviation of log returns.

- `prices`: price series
- `window`: rolling window size (default 20)
- `annualize`: multiply each value by sqrt(365)

Returns empty vec on insufficient input.

### `VolatilitySnapshot` (dataclass)
```python
VolatilitySnapshot(
    realized: float = 0.0,
    parkinson: float = 0.0,
    garman_klass: float = 0.0,
    yang_zhang: float = 0.0,
    ewma: float = 0.0,
    rolling: float = 0.0
)
```

All volatility estimates for one market at one cycle.
- `as_dict(self) -> 'dict[str, float]'`

### `volatility(feed: 'str', lookback: 'int' = 100, ewma_span: 'int' = 20, rolling_window: 'int' = 20, annualize: 'bool' = True) -> 'Callable[[Context], dict[str, Any]]'`

Create a volatility pipeline function.

    Maintains per-market price history from a feed, computes all vol
    estimators each cycle, and injects VolatilitySnapshot into
    ctx.params["vol"].

    Args:
        feed: Feed name to read prices from.
        lookback: Maximum price history length pe...

## Monte Carlo & Simulation

### `SimPosition` (class)
```python
SimPosition(market_id, side, size, entry_price, current_price)
```

A simulated position for Monte Carlo analysis.

Members:
- `current_price` — = `<attribute 'current_price' of 'builtins.SimPosition' objects>`
- `entry_price` — = `<attribute 'entry_price' of 'builtins.SimPosition' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.SimPosition' objects>`
- `side` — = `<attribute 'side' of 'builtins.SimPosition' objects>`
- `size` — = `<attribute 'size' of 'builtins.SimPosition' objects>`

### `SimulationResult` (class)
```python
SimulationResult($self, /, *args, **kwargs)
```

Results of a Monte Carlo simulation.

Members:
- `cvar_95` — = `<attribute 'cvar_95' of 'builtins.SimulationResult' objects>`
- `max_gain` — = `<attribute 'max_gain' of 'builtins.SimulationResult' objects>`
- `max_loss` — = `<attribute 'max_loss' of 'builtins.SimulationResult' objects>`
- `mean_pnl` — = `<attribute 'mean_pnl' of 'builtins.SimulationResult' objects>`
- `median_pnl` — = `<attribute 'median_pnl' of 'builtins.SimulationResult' objects>`
- `percentiles` — = `<attribute 'percentiles' of 'builtins.SimulationResult' objects>`
- `scenario_pnl` — = `<attribute 'scenario_pnl' of 'builtins.SimulationResult' objects>`
- `std_dev` — = `<attribute 'std_dev' of 'builtins.SimulationResult' objects>`
- `var_95` — = `<attribute 'var_95' of 'builtins.SimulationResult' objects>`
- `var_99` — = `<attribute 'var_99' of 'builtins.SimulationResult' objects>`
- `win_probability` — = `<attribute 'win_probability' of 'builtins.SimulationResult' objects>`

### `monte_carlo(positions, scenarios=10000, correlation_matrix=None, seed=None)`

Run a Monte Carlo simulation over a portfolio of prediction market positions.

Algorithm:
1. For each scenario, draw correlated normal random variables (one per position)
2. Threshold via normal_cdf to get a probability, compare to current_price for Bernoulli outcome
3. Compute PnL: YES side = size ...

### `simulate(engine=None, positions: 'list[SimPosition] | None' = None, scenarios: 'int' = 10000, correlations: 'dict[tuple[str, str], float] | None' = None, prices: 'dict[str, float] | None' = None, seed: 'int | None' = None) -> 'SimulationResult'`

Run a Monte Carlo simulation on a portfolio.

    Can auto-extract positions from an Engine, or accept explicit
    SimPosition objects.

    Args:
        engine: Optional Engine to extract positions and prices from.
        positions: Explicit list of SimPosition (overrides engine).
        scenar...

## Information Theory

### `shannon_entropy(p)`

Binary Shannon entropy: -[p*log2(p) + (1-p)*log2(1-p)].
Returns 0.0 for p outside (0,1).

### `joint_entropy(probs)`

Multi-outcome entropy: -sum(p_i * log2(p_i)).
Skips non-positive probabilities.

### `kl_divergence(p, q)`

KL divergence KL(P||Q) = sum(p_i * log(p_i / q_i)).
Clamps q values to epsilon to avoid division by zero.

### `mutual_information(x, y, n_bins=10)`

Mutual information MI(X;Y) via 2D histogram: H(X) + H(Y) - H(X,Y).

### `transfer_entropy(source, target, lag=1, n_bins=10)`

Transfer entropy TE(X->Y) via 3D histogram.
Measures directed information flow from source to target with given lag.

## Microstructure

### `kyles_lambda(price_changes, signed_volumes)`

Kyle's lambda: OLS price impact coefficient = cov(dp, sv) / var(sv).

### `amihud_ratio(returns, volumes)`

Amihud illiquidity ratio: mean(|r_i| / v_i).
Skips zero-volume observations.

### `roll_spread(returns)`

Roll implicit spread: 2 * sqrt(-cov(r_t, r_{t-1})).
Returns 0 if autocovariance is non-negative.

### `effective_spread(fill_price, mid, is_buy)`

Effective spread: 2 * signed distance from mid.

### `realized_spread(fill_price, mid_after, is_buy)`

Realized spread: 2 * sign * (fill_price - mid_after).
Measures how much spread the liquidity provider actually captures.

### `lob_imbalance(bids, asks, levels=5)`

Multi-level limit order book imbalance: (sum_bid_qty - sum_ask_qty) / (sum_bid_qty + sum_ask_qty).
Uses up to `levels` price levels from each side.

### `weighted_mid(bids, asks)`

Microprice: volume-weighted mid price using best bid/ask.
weighted_mid = (ask_qty * bid_price + bid_qty * ask_price) / (bid_qty + ask_qty)

## Risk Analytics

### `cornish_fisher_var(returns, confidence=0.95)`

Cornish-Fisher VaR: skew/kurtosis-adjusted Value at Risk.

### `cornish_fisher_cvar(returns, confidence=0.95)`

Cornish-Fisher CVaR (Expected Shortfall).
Uses empirical tail average below the CF VaR threshold.

### `prediction_greeks(price, size, is_yes, t_hours=24.0, vol=0.2)`

Prediction market Greeks for a binary outcome contract.

Uses a simple log-normal model: delta, gamma, theta, vega.
- price: current market probability
- size: position size
- is_yes: YES or NO side
- t_hours: hours to expiry
- vol: implied volatility

### `PredictionGreeks` (class)
```python
PredictionGreeks($self, /, *args, **kwargs)
```

Prediction market Greeks result.

Members:
- `delta` — = `<attribute 'delta' of 'builtins.PredictionGreeks' objects>`
- `gamma` — = `<attribute 'gamma' of 'builtins.PredictionGreeks' objects>`
- `theta` — = `<attribute 'theta' of 'builtins.PredictionGreeks' objects>`
- `vega` — = `<attribute 'vega' of 'builtins.PredictionGreeks' objects>`

## Signal Analysis

### `information_coefficient(predictions, outcomes)`

Information Coefficient: Spearman rank correlation between predictions and outcomes.

### `signal_half_life(values)`

Signal half-life from AR(1) fit: -ln(2) / ln(phi).
phi is the AR(1) coefficient from regressing x_t on x_{t-1}.

### `hurst_exponent(series)`

Hurst exponent via rescaled range (R/S) analysis.
H > 0.5: trending, H < 0.5: mean-reverting, H = 0.5: random walk.

### `variance_ratio(returns, period=2)`

Variance ratio test: VR(q) = Var(q-period returns) / (q * Var(1-period returns)).
VR = 1.0 indicates random walk.

## Statistical Testing

### `deflated_sharpe(sharpe, n_obs, n_trials, skew, kurt)`

Deflated Sharpe Ratio p-value (Bailey & Lopez de Prado, 2014).
Tests whether observed Sharpe is significant given multiple trials.

### `bonferroni_threshold(alpha, n_trials)`

Bonferroni correction: alpha / n_trials.

### `benjamini_hochberg(p_values, alpha=0.05)`

Benjamini-Hochberg FDR control.
Returns Vec<bool> — true if the corresponding hypothesis is rejected.

## Streaming Detectors

### `VpinDetector` (class)
```python
VpinDetector(bucket_volume=1000.0, n_buckets=50)
```

VPIN (Volume-synchronized Probability of Informed Trading) detector.

Tracks buy/sell volume in fixed-volume buckets and computes
the fraction of absolute order imbalance.

Members:
- `current_vpin` — method: `current_vpin(self, /)`
- `reset` — method: `reset(self, /)`
- `update` — method: `update(self, /, _price, volume, is_buy)`

### `CusumDetector` (class)
```python
CusumDetector(threshold=5.0, drift=0.0)
```

CUSUM change-point detector with Welford online mean/variance.

Detects structural breaks in a time series using cumulative sum control chart.

Members:
- `lower` — method: `lower(self, /)`
- `reset` — method: `reset(self, /)`
- `update` — method: `update(self, /, value)`
- `upper` — method: `upper(self, /)`

### `OfiTracker` (class)
```python
OfiTracker()
```

Order Flow Imbalance tracker.

Tracks changes in best bid/ask quantities to measure order flow direction.

Members:
- `cumulative` — method: `cumulative(self, /)`
- `reset` — method: `reset(self, /)`
- `update` — method: `update(self, /, best_bid_qty, best_ask_qty)`

### `HawkesProcess` (class)
```python
HawkesProcess(mu=0.1, alpha=0.5, beta=1.0, max_events=1000)
```

Self-exciting Hawkes point process for trade arrival intensity estimation.

Models bursty activity in prediction markets: each event increases the
probability of further events, decaying exponentially over time.
Intensity: lambda(t) = mu + sum_i alpha * exp(-beta * (t - t_i))

Members:
- `add_event` — method: `add_event(self, /, timestamp)`
- `branching_ratio` — method: `branching_ratio(self, /)`
- `event_count` — method: `event_count(self, /)`
- `expected_events` — method: `expected_events(self, /, t, horizon)`
- `intensity` — method: `intensity(self, /, t)`
- `intensity_now` — method: `intensity_now(self, /)`
- `reset` — method: `reset(self, /)`

### `ledoit_wolf_shrinkage(returns)`

Ledoit-Wolf shrinkage estimator for covariance matrices.

Shrinks the sample covariance toward a structured target (scaled identity)
to produce a better-conditioned estimate. Returns (shrunk_cov, shrinkage_intensity).

Args:
    returns: T x N matrix (each inner Vec is one time-step of N assets).

R...

## Arbitrage

### `ArbitrageOpportunity` (class)
```python
ArbitrageOpportunity($self, /, *args, **kwargs)
```

A detected arbitrage opportunity across exchanges.

Members:
- `buy_exchange` — = `<attribute 'buy_exchange' of 'builtins.ArbitrageOpportunity' objects>`
- `buy_price` — = `<attribute 'buy_price' of 'builtins.ArbitrageOpportunity' objects>`
- `is_executable` — = `<attribute 'is_executable' of 'builtins.ArbitrageOpportunity' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.ArbitrageOpportunity' objects>`
- `max_size` — = `<attribute 'max_size' of 'builtins.ArbitrageOpportunity' objects>`
- `net_edge` — = `<attribute 'net_edge' of 'builtins.ArbitrageOpportunity' objects>`
- `raw_edge` — = `<attribute 'raw_edge' of 'builtins.ArbitrageOpportunity' objects>`
- `sell_exchange` — = `<attribute 'sell_exchange' of 'builtins.ArbitrageOpportunity' objects>`
- `sell_price` — = `<attribute 'sell_price' of 'builtins.ArbitrageOpportunity' objects>`

### `ParityArbitrageOpportunity` (class)
```python
ParityArbitrageOpportunity($self, /, *args, **kwargs)
```

A detected parity arbitrage opportunity on a single exchange.
YES_ask + NO_ask < 1.0 means buying both locks in guaranteed profit.

Members:
- `exchange` — = `<attribute 'exchange' of 'builtins.ParityArbitrageOpportunity' objects>`
- `is_executable` — = `<attribute 'is_executable' of 'builtins.ParityArbitrageOpportunity' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.ParityArbitrageOpportunity' objects>`
- `max_size` — = `<attribute 'max_size' of 'builtins.ParityArbitrageOpportunity' objects>`
- `net_edge` — = `<attribute 'net_edge' of 'builtins.ParityArbitrageOpportunity' objects>`
- `no_ask` — = `<attribute 'no_ask' of 'builtins.ParityArbitrageOpportunity' objects>`
- `raw_edge` — = `<attribute 'raw_edge' of 'builtins.ParityArbitrageOpportunity' objects>`
- `total_cost` — = `<attribute 'total_cost' of 'builtins.ParityArbitrageOpportunity' objects>`
- `yes_ask` — = `<attribute 'yes_ask' of 'builtins.ParityArbitrageOpportunity' objects>`

### `LatencyArbOpportunity` (class)
```python
LatencyArbOpportunity($self, /, *args, **kwargs)
```

A detected latency arbitrage opportunity.

Members:
- `direction` — = `<attribute 'direction' of 'builtins.LatencyArbOpportunity' objects>`
- `edge` — = `<attribute 'edge' of 'builtins.LatencyArbOpportunity' objects>`
- `expected_price` — = `<attribute 'expected_price' of 'builtins.LatencyArbOpportunity' objects>`
- `market_price` — = `<attribute 'market_price' of 'builtins.LatencyArbOpportunity' objects>`
- `ref_price_change` — = `<attribute 'ref_price_change' of 'builtins.LatencyArbOpportunity' objects>`
- `staleness_ms` — = `<attribute 'staleness_ms' of 'builtins.LatencyArbOpportunity' objects>`

### `EventArbitrageOpportunity` (class)
```python
EventArbitrageOpportunity($self, /, *args, **kwargs)
```

A detected arbitrage opportunity within a multi-outcome event.

Members:
- `direction` — = `<attribute 'direction' of 'builtins.EventArbitrageOpportunity' objects>`
- `event_id` — = `<attribute 'event_id' of 'builtins.EventArbitrageOpportunity' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.EventArbitrageOpportunity' objects>`
- `is_executable` — = `<attribute 'is_executable' of 'builtins.EventArbitrageOpportunity' objects>`
- `net_edge` — = `<attribute 'net_edge' of 'builtins.EventArbitrageOpportunity' objects>`
- `overround` — = `<attribute 'overround' of 'builtins.EventArbitrageOpportunity' objects>`
- `price_sum` — = `<attribute 'price_sum' of 'builtins.EventArbitrageOpportunity' objects>`

### `ArbResult` (dataclass)
```python
ArbResult(
    market_id: str,
    buy_exchange: str,
    sell_exchange: str,
    buy_price: float,
    sell_price: float,
    size: float,
    raw_edge: float,
    net_edge: float,
    buy_order_id: str = '',
    sell_order_id: str = '',
    timestamp: float = time()
)
```

Result of a cross-exchange arbitrage execution.

### `EventArbResult` (dataclass)
```python
EventArbResult(
    event_id: str,
    direction: str,
    price_sum: float,
    net_edge: float,
    size: float,
    order_ids: list[str] = list(),
    timestamp: float = time()
)
```

Result of a multi-outcome event arbitrage execution.

### `SpreadSignal` (dataclass)
```python
SpreadSignal(
    market_a: str,
    market_b: str,
    spread: float,
    spread_mean: float,
    spread_std: float,
    zscore: float,
    signal: str
)
```

Signal from spread convergence analysis.

### `StatArbResult` (dataclass)
```python
StatArbResult(
    pair: tuple[str, str],
    hedge_ratio: float,
    zscore: float,
    half_life: float,
    adf_stat: float,
    signal: str,
    timestamp: float = time()
)
```

Result of a statistical arbitrage signal.

### `CompositeArbResult` (dataclass)
```python
CompositeArbResult(
    method: str,
    score: float,
    net_edge: float,
    capital_needed: float,
    details: dict = dict(),
    timestamp: float = time()
)
```

Result of composite arbitrage scanner scoring.

### `ParityResult` (class)
```python
ParityResult($self, /, *args, **kwargs)
```

Result of a YES/NO parity check for a single market.

Members:
- `deviation` — = `<attribute 'deviation' of 'builtins.ParityResult' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.ParityResult' objects>`
- `is_violation` — = `<attribute 'is_violation' of 'builtins.ParityResult' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.ParityResult' objects>`
- `no_price` — = `<attribute 'no_price' of 'builtins.ParityResult' objects>`
- `yes_price` — = `<attribute 'yes_price' of 'builtins.ParityResult' objects>`

### `arb_scanner(market_id: 'str', exchanges: 'list[str]', feed_map: 'dict[str, str]', min_edge: 'float' = 0.01, max_size: 'float' = 50.0, fee_rates: 'dict[str, float] | None' = None, auto_execute: 'bool' = False, cooldown: 'float' = 5.0) -> 'Callable[[Context], list[Quote] | None]'`

Create a pipeline function that scans for arbitrage opportunities.

    Args:
        market_id: Market to scan.
        exchanges: List of exchange names to compare.
        feed_map: Mapping of exchange_name -> feed_name.
        min_edge: Minimum net edge to consider actionable.
        max_size:...

### `arb_sweep(engine, market_id: 'str', feed_map: 'dict[str, str]', min_edge: 'float' = 0.01, max_size: 'float' = 50.0, fee_rates: 'dict[str, float] | None' = None) -> 'ArbResult | None'`

One-shot arbitrage sweep: scan and execute the best opportunity.

    Args:
        engine: Horizon Engine instance.
        market_id: Market to scan.
        feed_map: Mapping of exchange_name -> feed_name.
        min_edge: Minimum net edge.
        max_size: Maximum trade size.
        fee_rates...

### `parity_arb_scanner(market_id: 'str', exchange: 'str' = 'paper', feed_name: 'str | None' = None, min_edge: 'float' = 0.005, max_size: 'float' = 50.0, fee_rate: 'float' = 0.002, auto_execute: 'bool' = False, cooldown: 'float' = 5.0) -> 'Callable[[Context], None]'`

Create a pipeline function that scans for parity arbitrage.

    Args:
        market_id: Market to scan.
        exchange: Exchange name.
        feed_name: Feed to read prices from. Defaults to exchange name.
        min_edge: Minimum net edge to consider actionable.
        max_size: Maximum trad...

### `parity_arb_sweep(engine, market_id: 'str', feed_name: 'str | None' = None, exchange: 'str' = 'paper', min_edge: 'float' = 0.005, max_size: 'float' = 50.0, fee_rate: 'float' = 0.002) -> 'ArbResult | None'`

One-shot parity arbitrage sweep.

    Args:
        engine: Horizon Engine instance.
        market_id: Market to scan.
        feed_name: Feed to read prices from.
        exchange: Exchange name.
        min_edge: Minimum net edge.
        max_size: Maximum trade size.
        fee_rate: Fee rate p...

### `event_arb_scanner(event_id: 'str', min_edge: 'float' = 0.01, max_size: 'float' = 50.0, fee_rate: 'float' = 0.002, auto_execute: 'bool' = False, cooldown: 'float' = 10.0, proportional: 'bool' = True) -> 'Callable[[Context], None]'`

Create a pipeline function that scans for multi-outcome event arbitrage.

    Args:
        event_id: Registered event ID.
        min_edge: Minimum net edge to consider actionable.
        max_size: Maximum total trade size.
        fee_rate: Fee rate per outcome trade.
        auto_execute: If Tru...

### `event_arb_sweep(engine, event_id: 'str', min_edge: 'float' = 0.01, max_size: 'float' = 50.0, fee_rate: 'float' = 0.002, proportional: 'bool' = True) -> 'EventArbResult | None'`

One-shot event arbitrage sweep.

    Args:
        engine: Horizon Engine instance.
        event_id: Registered event ID.
        min_edge: Minimum net edge.
        max_size: Maximum total trade size.
        fee_rate: Fee rate per outcome trade.
        proportional: If True, size inversely propo...

### `spread_convergence(market_a: 'str', market_b: 'str', feed_a: 'str', feed_b: 'str', lookback: 'int' = 100, entry_zscore: 'float' = 2.0, exit_zscore: 'float' = 0.5, max_spread: 'float' = 0.2, size: 'float' = 10.0, auto_execute: 'bool' = False, cooldown: 'float' = 30.0) -> 'Callable[[Context], None]'`

Create a pipeline function for spread convergence trading.

    Tracks the price spread between two markets and generates entry/exit
    signals based on z-score deviations from the historical mean.

    Args:
        market_a: First market ID.
        market_b: Second market ID.
        feed_a: Fee...

### `StatArbConfig` (dataclass)
```python
StatArbConfig(
    pair: tuple[str, str],
    feeds: tuple[str, str],
    lookback: int = 200,
    entry_zscore: float = 2.0,
    exit_zscore: float = 0.5,
    stop_zscore: float = 4.0,
    recalibrate_every: int = 50,
    min_half_life: float = 5.0,
    max_half_life: float = 200.0
)
```

Configuration for statistical arbitrage.

### `stat_arb(config: 'StatArbConfig', size: 'float' = 10.0, auto_execute: 'bool' = False, cooldown: 'float' = 30.0) -> 'Callable[[Context], None]'`

Create a pipeline function for cointegration-based stat arb.

    Collects price histories, periodically recalibrates the hedge ratio
    via OLS cointegration test, checks half-life bounds, and generates
    entry/exit/stop signals based on residual z-score.

    Args:
        config: StatArbConfig...

### `MMArbConfig` (dataclass)
```python
MMArbConfig(
    quote_exchange: str,
    hedge_exchange: str,
    quote_feed: str,
    hedge_feed: str,
    base_spread: float = 0.04,
    gamma: float = 0.5,
    max_position: float = 100.0,
    hedge_threshold: float = 10.0,
    hedge_aggression: float = 0.01,
    size: float = 5.0
)
```

Configuration for market-making arbitrage.

### `mm_arb(config: 'MMArbConfig') -> 'Callable[[Context], list[Quote]]'`

Create a pipeline function for market-making arbitrage.

    Generates Avellaneda-Stoikov quotes on the quoting exchange.
    When delta (net position) exceeds the hedge threshold, submits
    aggressive FOK orders on the hedge exchange to neutralize.

    Args:
        config: MMArbConfig with exch...

### `latency_arb(market_id: 'str', ref_feed: 'str', market_feed: 'str', sensitivity: 'float' = 1.0, min_staleness_ms: 'float' = 500.0, min_edge: 'float' = 0.02, max_size: 'float' = 20.0, fee_rate: 'float' = 0.002, auto_execute: 'bool' = False, cooldown: 'float' = 2.0, max_daily_trades: 'int' = 50) -> 'Callable[[Context], None]'`

Create a pipeline function for latency arbitrage.

    Monitors a fast reference feed and the prediction market book.
    When the reference feed shows a significant move and the market
    book is stale, generates a trade signal.

    Args:
        market_id: Market to trade.
        ref_feed: Fast...

### `ArbMethodConfig` (dataclass)
```python
ArbMethodConfig(
    method: str,
    weight: float = 1.0,
    max_capital: float = 500.0,
    enabled: bool = True,
    kwargs: dict = dict()
)
```

Configuration for a single arbitrage method in the composite scanner.

### `composite_arb(methods: 'list[ArbMethodConfig]', total_capital: 'float' = 1000.0, max_concurrent: 'int' = 3, rebalance_interval: 'float' = 60.0, auto_execute: 'bool' = False, cooldown: 'float' = 5.0) -> 'Callable[[Context], None]'`

Create a meta-scanner that runs all configured arb methods.

    Each cycle, the composite scanner checks all enabled methods,
    scores opportunities, and routes capital to the best ones.

    Scoring: score = (net_edge / cost) * confidence * weight * (1 - utilization)

    Args:
        methods: ...

### `implication_arb_scanner(markets: 'list[str]', implications: 'list[tuple[str, str]]', min_edge: 'float' = 0.01) -> 'Callable[[Context], list[dict] | None]'`

Create a pipeline function that scans for implication arbs.

    For each (A, B) where A implies B: price_A must be <= price_B.
    If price_A > price_B + min_edge, there's an arb.

    Args:
        markets: List of market IDs to monitor.
        implications: List of (A, B) tuples where A => B.
  ...

### `contradiction_arb_scanner(markets: 'list[str]', contradictions: 'list[tuple[str, str]]', min_edge: 'float' = 0.01) -> 'Callable[[Context], list[dict] | None]'`

Create a pipeline function that scans for contradiction arbs.

    For each (A, B) that are mutually exclusive: price_A + price_B <= 1.
    If sum > 1 + min_edge, there's an arb.

    Args:
        markets: List of market IDs to monitor.
        contradictions: List of (A, B) tuples that are mutuall...

### `cointegration_test(prices_a, prices_b)`

OLS cointegration test for two price series.

Returns (hedge_ratio, residuals, adf_statistic).
hedge_ratio: OLS beta (cov(a,b)/var(b)).
residuals: a - beta*b.
adf_statistic: ADF test statistic on residuals (more negative = more stationary).

### `spread_zscore(residuals, lookback)`

Compute z-score of the latest residual given a lookback window.

Uses the last `lookback` values of `residuals` to compute rolling mean/std,
then z-scores the final value.

## AFML Bars & Labeling

### `Bar` (class)
```python
Bar($self, /, *args, **kwargs)
```

A single OHLCV bar sampled from tick data.

Members:
- `close` — = `<attribute 'close' of 'builtins.Bar' objects>`
- `high` — = `<attribute 'high' of 'builtins.Bar' objects>`
- `low` — = `<attribute 'low' of 'builtins.Bar' objects>`
- `n_ticks` — = `<attribute 'n_ticks' of 'builtins.Bar' objects>`
- `open` — = `<attribute 'open' of 'builtins.Bar' objects>`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.Bar' objects>`
- `volume` — = `<attribute 'volume' of 'builtins.Bar' objects>`
- `vwap` — = `<attribute 'vwap' of 'builtins.Bar' objects>`

### `tick_bars(timestamps, prices, volumes, threshold)`

Sample a new bar every `threshold` ticks.

Args:
    timestamps: tick timestamps (f64, e.g. unix epoch seconds)
    prices: tick prices
    volumes: tick volumes
    threshold: number of ticks per bar

### `volume_bars(timestamps, prices, volumes, threshold)`

Sample a new bar every time cumulative volume exceeds `threshold`.

Args:
    timestamps: tick timestamps
    prices: tick prices
    volumes: tick volumes
    threshold: cumulative volume threshold per bar

### `dollar_bars(timestamps, prices, volumes, threshold)`

Sample a new bar every time cumulative dollar volume (price * volume) exceeds `threshold`.

Args:
    timestamps: tick timestamps
    prices: tick prices
    volumes: tick volumes
    threshold: cumulative dollar volume threshold per bar

### `tick_imbalance_bars(timestamps, prices, volumes, initial_estimate)`

Tick Imbalance Bars (TIBs) — Chapter 2.3.2.1.

Samples a new bar when the absolute cumulative tick imbalance
exceeds a dynamically estimated threshold.

- b_t = sign(price_t - price_{t-1}), b_0 = 1
- theta_t = sum(b_i) from start of current bar
- New bar when |theta_t| >= expected_T
- expected_T upd...

### `volume_imbalance_bars(timestamps, prices, volumes, initial_estimate)`

Volume Imbalance Bars (VIBs) — Chapter 2.3.2.2.

Same as tick imbalance bars, but weights by volume:
theta_t = sum(b_i * v_i) from start of current bar.

Args:
    timestamps: tick timestamps
    prices: tick prices
    volumes: tick volumes
    initial_estimate: initial expected |volume imbalance| ...

### `tick_run_bars(timestamps, prices, volumes, initial_estimate)`

Tick Run Bars (TRBs) — Chapter 2.3.3.

Counts runs of buy ticks and sell ticks separately.
Samples a new bar when max(buy_run, sell_run) >= expected threshold.

Args:
    timestamps: tick timestamps
    prices: tick prices
    volumes: tick volumes
    initial_estimate: initial expected max run leng...

### `volume_run_bars(timestamps, prices, volumes, initial_estimate)`

Volume Run Bars (VRBs) — Chapter 2.3.3.

Same as tick run bars, but accumulates volume in buy/sell runs
rather than counting ticks.

Args:
    timestamps: tick timestamps
    prices: tick prices
    volumes: tick volumes
    initial_estimate: initial expected max volume run

### `BarrierLabel` (class)
```python
BarrierLabel($self, /, *args, **kwargs)
```

Result of triple barrier labeling for a single event.

Fields:
  event_idx: index in the original price series where the event started
  label: -1 (stop-loss), 0 (vertical barrier / below min_ret), +1 (profit-taking)
  ret: realized return from entry to barrier touch
  barrier: which barrier was touched ("pt", "sl", or "vb")
  touch_idx: index in the price series where the barrier was touched

Members:
- `barrier` — = `<attribute 'barrier' of 'builtins.BarrierLabel' objects>`
- `event_idx` — = `<attribute 'event_idx' of 'builtins.BarrierLabel' objects>`
- `label` — = `<attribute 'label' of 'builtins.BarrierLabel' objects>`
- `ret` — = `<attribute 'ret' of 'builtins.BarrierLabel' objects>`
- `touch_idx` — = `<attribute 'touch_idx' of 'builtins.BarrierLabel' objects>`

### `get_daily_vol(prices, span)`

Compute exponentially weighted daily volatility from a price series.

Computes log returns, then applies EWM standard deviation with the given span.
First `span` entries use an expanding window for stability.

Returns a Vec of length `prices.len()`. The first element is always 0.0
(no return can be ...

### `cusum_filter(prices, threshold)`

Symmetric CUSUM filter for event-driven sampling (Chapter 2.5.2.1).

Tracks cumulative positive and negative sums of price changes.
When either sum exceeds the threshold, records the index and resets both.

This produces a structurally meaningful subsample of the time series,
filtering out noise and...

### `triple_barrier_labels(prices, timestamps, events, pt_sl, min_ret, max_holding, vol_span)`

Triple barrier labeling (Chapter 3.2-3.4).

For each event index, sets three barriers:
- Upper (profit-taking): entry_price * (1 + daily_vol * pt_sl[0])
- Lower (stop-loss):     entry_price * (1 - daily_vol * pt_sl[1])
- Vertical:              max_holding bars forward from entry

Scans forward from ...

### `meta_labels(prices, timestamps, primary_signals, pt_sl, max_holding, vol_span)`

Meta-labeling (Chapter 3.6).

Given a primary model's directional signals, meta-labeling determines
whether acting on each signal is profitable (label=1) or not (label=0).

The primary model provides the side (+1 long, -1 short). The meta-label
indicates if the bet was correct:
- Primary says +1 (lo...

### `drop_labels(labels, min_pct)`

Drop rare labels that don't meet a minimum percentage threshold (Chapter 3.7).

Counts occurrences of each label class (-1, 0, +1). Removes events whose
label class has fewer than `min_pct` fraction of the total.

This prevents classifier training on heavily imbalanced datasets where
rare classes ca...

### `frac_diff_weights(d, threshold=1e-05)`

Compute the fractional differentiation weights for order `d`.

Weights follow the recursion: w_k = -w_{k-1} * (d - k + 1) / k,
starting with w_0 = 1. Generation stops when |w_k| < `threshold`.

This is the core building block for both FFD and expanding-window methods.

### `frac_diff_ffd(series, d, threshold=1e-05)`

Fixed-Width Window Fractional Differentiation (FFD).

Computes weights via `frac_diff_weights(d, threshold)` and applies them as
a convolution over the series.  The output is shorter than the input by
`len(weights) - 1` because the first entries lack enough history.

This is the recommended method f...

### `frac_diff_expanding(series, d)`

Expanding-window (full-memory) fractional differentiation.

At each point `t`, uses all weights from lag 0 to lag `t`.  This preserves
the full information content of the original series but produces a
non-stationary weight structure (earlier points use fewer lags).

Slower than FFD (O(n^2) vs O(n *...

### `adf_statistic(series)`

Simplified Augmented Dickey-Fuller test statistic (no augmenting lags).

Fits the regression: delta_y[t] = alpha + beta * y[t-1] + epsilon[t]
and returns ADF stat = beta / SE(beta).

More negative values indicate stronger stationarity evidence.
Critical values (approximate, n > 100):
  1%: -3.43,  5...

### `min_frac_diff(series, p_threshold=0.05, max_d=1.0, n_steps=20, weight_threshold=1e-05)`

Find the minimum `d` that makes the series stationary (Chapter 5.5).

Searches `d` from 0 to `max_d` in `n_steps` equal increments.  For each `d`,
applies `frac_diff_ffd`, then computes the ADF test statistic.  Returns the
smallest `d` whose ADF stat is below the 5% critical value (-2.862).

Returns...

## Hierarchical Risk Parity

### `HRPResult` (class)
```python
HRPResult($self, /, *args, **kwargs)
```

Result of Hierarchical Risk Parity allocation.

Members:
- `linkage` — = `<attribute 'linkage' of 'builtins.HRPResult' objects>`
- `sorted_indices` — = `<attribute 'sorted_indices' of 'builtins.HRPResult' objects>`
- `weights` — = `<attribute 'weights' of 'builtins.HRPResult' objects>`

### `DenoisedCov` (class)
```python
DenoisedCov($self, /, *args, **kwargs)
```

Result of Marcenko-Pastur covariance denoising.

Members:
- `covariance` — = `<attribute 'covariance' of 'builtins.DenoisedCov' objects>`
- `eigenvalues` — = `<attribute 'eigenvalues' of 'builtins.DenoisedCov' objects>`
- `n_noise` — = `<attribute 'n_noise' of 'builtins.DenoisedCov' objects>`
- `n_signals` — = `<attribute 'n_signals' of 'builtins.DenoisedCov' objects>`

### `hrp_weights(covariance)`

Compute Hierarchical Risk Parity portfolio weights.

Full pipeline:
1. Convert covariance to correlation matrix
2. Compute correlation distance matrix
3. Single-linkage hierarchical clustering
4. Quasi-diagonalization (seriation)
5. Recursive bisection (inverse-variance weighting)

Returns an `HRPRe...

### `denoise_covariance(covariance, n_observations)`

Denoise a covariance matrix using Marcenko-Pastur eigenvalue clipping.

1. Compute eigendecomposition of the covariance matrix.
2. Estimate the Marcenko-Pastur upper bound: lambda_+ = sigma^2 * (1 + sqrt(N/T))^2
3. Replace noise eigenvalues (below lambda_+) with their average.
4. Reconstruct the den...

### `detone_covariance(covariance)`

Remove the market factor (first principal component) from a covariance matrix.

1. Compute eigendecomposition.
2. Zero out the largest eigenvalue's contribution.
3. Reconstruct the covariance without the market mode.

This is useful for removing the dominant market factor that drives all
assets toge...

## Calibration & Analytics

### `CalibrationResult` (class)
```python
CalibrationResult($self, /, *args, **kwargs)
```

Result of calibration curve computation.

Members:
- `bins` — = `<attribute 'bins' of 'builtins.CalibrationResult' objects>`
- `brier_score` — = `<attribute 'brier_score' of 'builtins.CalibrationResult' objects>`
- `ece` — = `<attribute 'ece' of 'builtins.CalibrationResult' objects>`
- `log_loss` — = `<attribute 'log_loss' of 'builtins.CalibrationResult' objects>`

### `EdgeDecayResult` (class)
```python
EdgeDecayResult($self, /, *args, **kwargs)
```

Result of edge decay analysis.

Members:
- `decay_curve` — = `<attribute 'decay_curve' of 'builtins.EdgeDecayResult' objects>`
- `half_life_hours` — = `<attribute 'half_life_hours' of 'builtins.EdgeDecayResult' objects>`

### `FeedMetrics` (class)
```python
FeedMetrics($self, /, *args, **kwargs)
```

Per-feed connection metrics.

Members:
- `error_count` — = `<attribute 'error_count' of 'builtins.FeedMetrics' objects>`
- `is_connected` — = `<attribute 'is_connected' of 'builtins.FeedMetrics' objects>`
- `last_error` — = `<attribute 'last_error' of 'builtins.FeedMetrics' objects>`
- `last_update_time` — = `<attribute 'last_update_time' of 'builtins.FeedMetrics' objects>`
- `reconnect_count` — = `<attribute 'reconnect_count' of 'builtins.FeedMetrics' objects>`
- `update_count` — = `<attribute 'update_count' of 'builtins.FeedMetrics' objects>`

### `calibration_curve(predictions, outcomes, n_bins=10)`

Bin predictions into n_bins buckets, compute actual frequency per bin.
Also computes Brier score, log-loss, and ECE in a single O(N) pass.

Args:
    predictions: predicted probabilities (0-1)
    outcomes: actual outcomes (0.0 or 1.0)
    n_bins: number of calibration bins

### `log_loss(predictions, outcomes)`

Compute log-loss: -1/N * sum(y*ln(p) + (1-y)*ln(1-p)).
Predictions clamped to [1e-15, 1-1e-15] for numerical stability.

### `edge_decay(entry_prices, outcomes, entry_ts, resolution_ts, n_buckets=20)`

Group trades by hours-to-resolution, compute avg edge per bucket.
Edge = outcome - entry_price for each trade.

Args:
    entry_prices: price at trade entry
    outcomes: actual outcomes (0.0 or 1.0)
    entry_ts: UNIX timestamp of each trade entry
    resolution_ts: UNIX timestamp of each market re...

### `CalibrationTracker` (class)
```python
CalibrationTracker(db_path: 'str' = ':memory:') -> 'None'
```

Track probability calibration with SQLite persistence.

    Usage:
        tracker = CalibrationTracker("calibration.db")
        tracker.log_prediction("mkt_1", 0.75)
        # ... later, when market resolves ...
        tracker.resolve_market("mkt_1", True)
        report = tracker.report()
        print(f"Brier: {report.brier_score:.4f}")

Members:
- `brier_score` — method: `brier_score(self) -> 'float'`
- `calibration_curve` — method: `calibration_curve(self, n_bins: 'int' = 10) -> 'list[CalibrationBucket]'`
- `clear` — method: `clear(self) -> 'None'`
- `close` — method: `close(self) -> 'None'`
- `log_loss` — method: `log_loss(self) -> 'float'`
- `log_prediction` — method: `log_prediction(self, market_id: 'str', probability: 'float', timestamp: 'float | None' = None) -> 'None'`
- `report` — method: `report(self, n_bins: 'int' = 10) -> 'CalibrationReport'`
- `resolve_market` — method: `resolve_market(self, market_id: 'str', outcome: 'bool') -> 'None'`
- `suggest_adjustment` — method: `suggest_adjustment(self, probability: 'float', n_bins: 'int' = 10) -> 'float'`

### `Metrics` (dataclass)
```python
Metrics(
    total_return: float = 0.0,
    total_return_pct: float = 0.0,
    cagr: float = 0.0,
    sharpe_ratio: float = 0.0,
    sortino_ratio: float = 0.0,
    calmar_ratio: float = 0.0,
    max_drawdown: float = 0.0,
    max_drawdown_pct: float = 0.0,
    max_drawdown_duration_secs: float = 0.0,
    total_trades: int = 0,
    win_rate: float = 0.0,
    profit_factor: float = 0.0,
    expectancy: float = 0.0,
    avg_win: float = 0.0,
    avg_loss: float = 0.0,
    largest_win: float = 0.0,
    largest_loss: float = 0.0,
    total_fees: float = 0.0,
    brier_score: float | None = None,
    avg_edge: float | None = None,
    log_loss: float | None = None,
    ece: float | None = None
)
```

Computed performance metrics from a backtest.

### `Tearsheet` (dataclass)
```python
Tearsheet(
    monthly_returns: dict[str, float] = dict(),
    rolling_sharpe: list[Tuple[float, float]] = list(),
    rolling_sortino: list[Tuple[float, float]] = list(),
    drawdowns: list[DrawdownRecord] = list(),
    avg_win: float = 0.0,
    avg_loss: float = 0.0,
    largest_win: float = 0.0,
    largest_loss: float = 0.0,
    avg_hold_time: float = 0.0,
    win_streak: int = 0,
    loss_streak: int = 0,
    time_of_day: dict[int, float] = dict(),
    max_consecutive_wins: int = 0,
    max_consecutive_losses: int = 0,
    tail_ratio: float = 0.0
)
```

Comprehensive performance tearsheet.

### `DrawdownRecord` (dataclass)
```python
DrawdownRecord(
    start_ts: float = 0.0,
    end_ts: float = 0.0,
    recovery_ts: float | None = None,
    depth_pct: float = 0.0,
    duration_secs: float = 0.0
)
```

A single drawdown period.

### `compute_metrics(equity_curve: 'list[tuple[float, float]]', trades: 'list', initial_capital: 'float', outcomes: 'dict[str, float] | None' = None) -> 'Metrics'`

Compute all performance metrics from backtest results.

    Args:
        equity_curve: List of (timestamp, equity) tuples.
        trades: List of Fill objects from the engine.
        initial_capital: Starting capital.
        outcomes: Optional dict of market_id -> outcome (1.0 or 0.0) for Brier ...

### `generate_tearsheet(equity_curve: 'list[tuple[float, float]]', trades: 'list', initial_capital: 'float') -> 'Tearsheet'`

Generate a comprehensive performance tearsheet.

    Args:
        equity_curve: List of (timestamp, equity) tuples.
        trades: List of Fill objects from the engine.
        initial_capital: Starting capital.

    Returns:
        Tearsheet dataclass with all computed values.

## Discovery

### `discover_markets(exchange: 'str' = 'polymarket', query: 'str' = '', active: 'bool' = True, limit: 'int' = 20, min_volume: 'float' = 0.0, category: 'str' = '', sort_by: 'str' = 'volume', gamma_url: 'str' = 'https://gamma-api.polymarket.com', kalshi_url: 'str' = 'https://api.elections.kalshi.com/trade-api/v2') -> 'list[Market]'`

Search for markets on the specified exchange.

    Args:
        exchange: "polymarket" or "kalshi".
        query: Search text (market title/slug).
        active: Only return active (open) markets.
        limit: Max number of results.
        min_volume: Minimum 24h volume filter.
        categor...

### `discover_events(exchange: 'str' = 'polymarket', query: 'str' = '', active: 'bool' = True, limit: 'int' = 10, min_volume: 'float' = 0.0, gamma_url: 'str' = 'https://gamma-api.polymarket.com') -> 'list[Event]'`

Discover multi-outcome events from Polymarket.

    Hits the Gamma API /events endpoint and returns Event objects
    with all outcomes populated, including YES/NO token IDs and prices.

    Args:
        exchange: Currently only "polymarket" is supported.
        query: Search text for event title/...

### `top_markets(exchange: 'str' = 'polymarket', limit: 'int' = 10, category: 'str' = '', gamma_url: 'str' = 'https://gamma-api.polymarket.com', kalshi_url: 'str' = 'https://api.elections.kalshi.com/trade-api/v2') -> 'list[Market]'`

Get the top markets by volume.

    Convenience wrapper around discover_markets with sensible defaults.

    Args:
        exchange: "polymarket" or "kalshi".
        limit: Number of markets to return.
        category: Optional category filter.

    Returns:
        Top markets sorted by volume (d...

### `get_market_detail(slug_or_id: 'str', exchange: 'str' = 'polymarket', gamma_url: 'str' = 'https://gamma-api.polymarket.com') -> 'dict'`

Fetch comprehensive info about a single market.

    Returns a dict with sections: market, prices, price_history,
    orderbook, recent_trades, top_holders.

## Historical Data

### `HistoricalTrade` (class)
```python
HistoricalTrade($self, /, *args, **kwargs)
```

A historical trade record.

Members:
- `market_id` — = `<attribute 'market_id' of 'builtins.HistoricalTrade' objects>`
- `price` — = `<attribute 'price' of 'builtins.HistoricalTrade' objects>`
- `side` — = `<attribute 'side' of 'builtins.HistoricalTrade' objects>`
- `size` — = `<attribute 'size' of 'builtins.HistoricalTrade' objects>`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.HistoricalTrade' objects>`

### `OHLCBar` (class)
```python
OHLCBar($self, /, *args, **kwargs)
```

An OHLC bar.

Members:
- `close` — = `<attribute 'close' of 'builtins.OHLCBar' objects>`
- `high` — = `<attribute 'high' of 'builtins.OHLCBar' objects>`
- `low` — = `<attribute 'low' of 'builtins.OHLCBar' objects>`
- `open` — = `<attribute 'open' of 'builtins.OHLCBar' objects>`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.OHLCBar' objects>`
- `volume` — = `<attribute 'volume' of 'builtins.OHLCBar' objects>`

### `fetch_polymarket_prices(token_id, start_ts, end_ts, fidelity=60)`

Fetch Polymarket OHLC price history.

GET https://clob.polymarket.com/prices-history?market={token_id}&startTs={start}&endTs={end}&fidelity={fidelity}

### `fetch_polymarket_trades(token_id, limit=1000)`

Fetch Polymarket trade history.

GET https://clob.polymarket.com/trades?asset_id={token_id}

### `fetch_kalshi_book(ticker)`

Fetch a single Kalshi orderbook snapshot.

GET https://trading-api.kalshi.com/trade-api/v2/markets/{ticker}/orderbook

### `fetch_polymarket_book(token_id)`

Fetch Polymarket orderbook snapshot.

GET https://clob.polymarket.com/book?token_id={token_id}

### `fetch_kalshi_market(ticker)`

Fetch a single Kalshi market metadata.

GET https://trading-api.kalshi.com/trade-api/v2/markets/{ticker}

Returns raw JSON as a string (parse with json.loads in Python).

### `fetch_prices(token_id: 'str', start: 'str | float', end: 'str | float', fidelity: 'int' = 60) -> 'list[dict]'`

Fetch Polymarket OHLC history.

    Args:
        token_id: Polymarket token ID (condition_id or token_id).
        start: Start timestamp (UNIX float or ISO string).
        end: End timestamp (UNIX float or ISO string).
        fidelity: Bar interval in seconds (default 60).

    Returns:
        ...

### `fetch_trades(token_id: 'str', limit: 'int' = 1000) -> 'list[dict]'`

Fetch Polymarket trade history.

    Args:
        token_id: Polymarket token ID.
        limit: Maximum number of trades to fetch.

    Returns:
        List of trade dicts with timestamp, price, size, side, market_id.

### `ohlc_to_ticks(bars: 'list[OHLCBar]') -> 'list[Tick]'`

Convert OHLCBar list to backtest Tick list.

    Uses close as price, min(open, close) as bid, max(open, close) as ask.

## Flow Analytics (Polymarket)

### `Trade` (dataclass)
```python
Trade(
    wallet: str,
    side: str,
    outcome: str,
    size: float,
    price: float,
    usdc_size: float,
    timestamp: int,
    market_slug: str,
    market_title: str,
    condition_id: str,
    token_id: str,
    tx_hash: str | None = None,
    pseudonym: str | None = None
)
```

A single trade on Polymarket.

### `PolymarketPosition` (dataclass)
```python
PolymarketPosition(
    wallet: str,
    market_slug: str,
    market_title: str,
    condition_id: str,
    token_id: str,
    outcome: str,
    size: float,
    avg_price: float,
    current_price: float,
    current_value: float,
    pnl: float,
    pnl_percent: float
)
```

An open position held by a wallet.

### `Holder` (dataclass)
```python
Holder(
    wallet: str,
    amount: float,
    token_id: str,
    outcome_index: int,
    pseudonym: str | None = None,
    name: str | None = None
)
```

A top holder in a market.

### `WalletProfile` (dataclass)
```python
WalletProfile(
    wallet: str,
    pseudonym: str | None = None,
    name: str | None = None,
    bio: str | None = None,
    profile_image: str | None = None,
    x_username: str | None = None,
    created_at: str | None = None
)
```

Public profile for a Polymarket wallet.

### `MarketFlow` (dataclass)
```python
MarketFlow(
    condition_id: str,
    total_trades: int,
    buy_volume: float,
    sell_volume: float,
    net_flow: float,
    unique_wallets: int,
    top_buyers: list[tuple[str, float]] = list(),
    top_sellers: list[tuple[str, float]] = list()
)
```

Aggregated flow analytics for a market.

### `get_market_trades(condition_id: 'str', limit: 'int' = 100, offset: 'int' = 0, side: 'str | None' = None, min_size: 'float' = 0.0, data_api_url: 'str' = 'https://data-api.polymarket.com') -> 'list[Trade]'`

Fetch recent trades for a market.

    Args:
        condition_id: Market condition ID (0x-prefixed hex).
        limit: Max trades to return (max 10000).
        offset: Pagination offset.
        side: Filter by "BUY" or "SELL" (None = both).
        min_size: Minimum trade size in USDC.
        d...

### `get_wallet_trades(address: 'str', limit: 'int' = 100, offset: 'int' = 0, condition_id: 'str | None' = None, data_api_url: 'str' = 'https://data-api.polymarket.com') -> 'list[Trade]'`

Fetch trade history for a wallet.

    Args:
        address: Wallet address (0x...).
        limit: Max trades to return.
        offset: Pagination offset.
        condition_id: Optional market filter.
        data_api_url: Override Data API URL.

    Returns:
        List of Trade objects for thi...

### `get_wallet_positions(address: 'str', limit: 'int' = 100, offset: 'int' = 0, condition_id: 'str | None' = None, sort_by: 'str' = 'TOKENS', data_api_url: 'str' = 'https://data-api.polymarket.com') -> 'list[WalletPosition]'`

Fetch open positions for a wallet.

    Args:
        address: Wallet address (0x...).
        limit: Max positions to return (max 500).
        offset: Pagination offset.
        condition_id: Optional market filter.
        sort_by: Sort field - "TOKENS", "CURRENT", "INITIAL", "CASHPNL",
         ...

### `get_wallet_value(address: 'str', data_api_url: 'str' = 'https://data-api.polymarket.com') -> 'float'`

Get total USD value of a wallet's open positions.

    Args:
        address: Wallet address (0x...).
        data_api_url: Override Data API URL.

    Returns:
        Total position value in USD. Returns 0.0 on error.

### `get_top_holders(condition_id: 'str', limit: 'int' = 20, data_api_url: 'str' = 'https://data-api.polymarket.com') -> 'list[Holder]'`

Get top holders for a market.

    Args:
        condition_id: Market condition ID.
        limit: Max holders (max 20).
        data_api_url: Override Data API URL.

    Returns:
        List of Holder objects sorted by position size.

### `get_wallet_profile(address: 'str', gamma_url: 'str' = 'https://gamma-api.polymarket.com') -> 'WalletProfile | None'`

Fetch public profile for a wallet.

    Args:
        address: Wallet address (0x...).
        gamma_url: Override Gamma API URL.

    Returns:
        WalletProfile or None if not found.

### `analyze_market_flow(condition_id: 'str', trade_limit: 'int' = 500, top_n: 'int' = 10, data_api_url: 'str' = 'https://data-api.polymarket.com') -> 'MarketFlow'`

Analyze trade flow for a market.

    Fetches recent trades and computes buy/sell volume,
    net flow, unique wallets, and top buyers/sellers.

    Args:
        condition_id: Market condition ID.
        trade_limit: Number of recent trades to analyze (max 10000).
        top_n: Number of top buye...

## Logit-Space Pricing

### `LogitGreeks` (class)
```python
LogitGreeks($self, /, *args, **kwargs)
```

Members:
- `belief_vega` — = `<attribute 'belief_vega' of 'builtins.LogitGreeks' objects>`
- `delta` — = `<attribute 'delta' of 'builtins.LogitGreeks' objects>`
- `gamma` — = `<attribute 'gamma' of 'builtins.LogitGreeks' objects>`
- `theta` — = `<attribute 'theta' of 'builtins.LogitGreeks' objects>`

### `LogitPnlAttribution` (class)
```python
LogitPnlAttribution($self, /, *args, **kwargs)
```

Members:
- `belief_vega_pnl` — = `<attribute 'belief_vega_pnl' of 'builtins.LogitPnlAttribution' objects>`
- `correlation_vega_pnl` — = `<attribute 'correlation_vega_pnl' of 'builtins.LogitPnlAttribution' objects>`
- `curvature` — = `<attribute 'curvature' of 'builtins.LogitPnlAttribution' objects>`
- `directional` — = `<attribute 'directional' of 'builtins.LogitPnlAttribution' objects>`
- `residual` — = `<attribute 'residual' of 'builtins.LogitPnlAttribution' objects>`

### `logit(p)`

### `sigmoid(x)`

### `sigmoid_prime(x)`

### `sigmoid_double_prime(x)`

### `logit_reservation_price(mid, inventory, gamma, belief_vol, t)`

### `logit_optimal_spread(belief_vol, inventory, gamma, kappa, t)`

### `logit_greeks(price, size, is_yes, t_hours=24.0, belief_vol=0.2)`

### `logit_pnl_decompose(p_before, p_after, size, is_yes, vol_before, vol_after, corr_before=0.0, corr_after=0.0)`

### `logit_market_maker(base_spread: 'float' = 0.04, gamma: 'float' = 0.5, kappa: 'float' = 1.5, belief_vol: 'float' = 0.2, max_position: 'float' = 100.0, feed_name: 'str | None' = None, size: 'float' = 5.0, time_horizon: 'float' = 1.0, use_vpin: 'bool' = False, vpin_sensitivity: 'float' = 1.0) -> 'Callable[[Context], list[Quote]]'`

Create a logit-space market maker pipeline function.

    Uses logit-space reservation price and optimal spread for proper
    boundary compression near 0 and 1.

    Args:
        base_spread: Fallback spread.
        gamma: Risk aversion.
        kappa: Order arrival intensity.
        belief_vol:...

### `logit_greeks_pipeline(feed_name: 'str | None' = None, belief_vol: 'float' = 0.2, t_hours: 'float' = 24.0) -> 'Callable[[Context], None]'`

Pipeline function that computes logit Greeks per market.

    Injects into ctx.params:
        - "logit_delta", "logit_gamma", "logit_theta", "logit_belief_vega"

    Args:
        feed_name: Feed to read price from.
        belief_vol: Belief volatility parameter.
        t_hours: Hours to resoluti...

### `logit_pnl_attribution_pipeline(belief_vol: 'float' = 0.2) -> 'Callable[[Context], None]'`

Pipeline function that tracks per-market PnL decomposition in logit space.

    Injects into ctx.params:
        - "logit_pnl_attribution": dict with directional, curvature, etc.

    Args:
        belief_vol: Belief volatility parameter.

    Returns:
        Pipeline function: (Context) -> None

## Bootstrap Methods

### `BootstrapResult` (class)
```python
BootstrapResult($self, /, *args, **kwargs)
```

Members:
- `bias` — = `<attribute 'bias' of 'builtins.BootstrapResult' objects>`
- `ci_lower` — = `<attribute 'ci_lower' of 'builtins.BootstrapResult' objects>`
- `ci_upper` — = `<attribute 'ci_upper' of 'builtins.BootstrapResult' objects>`
- `n_resamples` — = `<attribute 'n_resamples' of 'builtins.BootstrapResult' objects>`
- `point_estimate` — = `<attribute 'point_estimate' of 'builtins.BootstrapResult' objects>`
- `std_error` — = `<attribute 'std_error' of 'builtins.BootstrapResult' objects>`

### `BootstrapHypothesisResult` (class)
```python
BootstrapHypothesisResult($self, /, *args, **kwargs)
```

Members:
- `ci_lower` — = `<attribute 'ci_lower' of 'builtins.BootstrapHypothesisResult' objects>`
- `ci_upper` — = `<attribute 'ci_upper' of 'builtins.BootstrapHypothesisResult' objects>`
- `p_value` — = `<attribute 'p_value' of 'builtins.BootstrapHypothesisResult' objects>`
- `reject` — = `<attribute 'reject' of 'builtins.BootstrapHypothesisResult' objects>`
- `test_statistic` — = `<attribute 'test_statistic' of 'builtins.BootstrapHypothesisResult' objects>`

### `JackknifeResult` (class)
```python
JackknifeResult($self, /, *args, **kwargs)
```

Members:
- `bias` — = `<attribute 'bias' of 'builtins.JackknifeResult' objects>`
- `estimate` — = `<attribute 'estimate' of 'builtins.JackknifeResult' objects>`
- `pseudovalues` — = `<attribute 'pseudovalues' of 'builtins.JackknifeResult' objects>`
- `std_error` — = `<attribute 'std_error' of 'builtins.JackknifeResult' objects>`

### `bootstrap_mean(data, n_resamples=10000, confidence=0.95, seed=42)`

### `bootstrap_sharpe(returns, n_resamples=10000, confidence=0.95, seed=42)`

### `bootstrap_var(returns, var_level=0.05, n_resamples=10000, confidence=0.95, seed=42)`

### `bootstrap_correlation(x, y, n_resamples=10000, confidence=0.95, seed=42)`

### `bootstrap_edge(predictions, outcomes, n_resamples=10000, confidence=0.95, seed=42)`

### `block_bootstrap(data, block_size, n_resamples=10000, confidence=0.95, seed=42)`

### `circular_block_bootstrap(data, block_size, n_resamples=10000, confidence=0.95, seed=42)`

### `stationary_bootstrap(data, expected_block_size, n_resamples=10000, confidence=0.95, seed=42)`

### `bootstrap_hypothesis_test(sample_a, sample_b, n_resamples=10000, seed=42)`

### `bootstrap_prediction_interval(residuals, point_forecast, n_resamples=10000, confidence=0.95, seed=42)`

### `jackknife_bias(data, statistic='mean')`

### `bootstrap_edge_tracker(window: 'int' = 100, n_resamples: 'int' = 10000, confidence: 'float' = 0.95, seed: 'int' = 42) -> 'Callable[[Context], dict | None]'`

Create a pipeline function that tracks bootstrap CI for prediction edge.

    Collects (prediction, outcome) pairs per market. When the window fills,
    computes bootstrap confidence interval for edge.

    Injects into ctx.params:
        - "bootstrap_edge": dict with edge, ci_lower, ci_upper, is_...

### `bootstrap_strategy_test(strategy_a_key: 'str' = 'returns_a', strategy_b_key: 'str' = 'returns_b', n_resamples: 'int' = 10000, seed: 'int' = 42) -> 'Callable[[Context], dict | None]'`

Create a pipeline function that tests if two strategies differ significantly.

    Reads return vectors from ctx.params and runs a permutation test.

    Injects into ctx.params:
        - "strategy_test": dict with test_statistic, p_value, reject

    Args:
        strategy_a_key: Key for strategy ...

## Belief-Vol & Breeden-Litzenberger

### `BeliefVolSurface` (class)
```python
BeliefVolSurface(decay=0.99, min_observations=20)
```

Members:
- `current_vol` — method: `current_vol(self, /)`
- `jump_probability` — method: `jump_probability(self, /)`
- `reset` — method: `reset(self, /)`
- `surface_point` — method: `surface_point(self, /, time_to_resolution, logit_moneyness=0.0)`
- `update` — method: `update(self, /, price, timestamp, bid=0.0, ask=0.0, volume=0.0)`

### `belief_vol_tracker(feed_name: 'str | None' = None, decay: 'float' = 0.99, min_observations: 'int' = 20) -> 'Callable[[Context], None]'`

Create a pipeline function that tracks belief volatility per market.

    Injects into ctx.params:
        - "belief_vol": current belief volatility estimate
        - "jump_prob": estimated jump probability

    Args:
        feed_name: Feed to read price/bid/ask from.
        decay: EWMA decay fac...

### `RiskNeutralDensity` (class)
```python
RiskNeutralDensity($self, /, *args, **kwargs)
```

Members:
- `cdf` — = `<attribute 'cdf' of 'builtins.RiskNeutralDensity' objects>`
- `densities` — = `<attribute 'densities' of 'builtins.RiskNeutralDensity' objects>`
- `mean` — = `<attribute 'mean' of 'builtins.RiskNeutralDensity' objects>`
- `strikes` — = `<attribute 'strikes' of 'builtins.RiskNeutralDensity' objects>`
- `variance` — = `<attribute 'variance' of 'builtins.RiskNeutralDensity' objects>`

### `CrossAssetEdge` (class)
```python
CrossAssetEdge($self, /, *args, **kwargs)
```

Members:
- `adjusted_edge` — = `<attribute 'adjusted_edge' of 'builtins.CrossAssetEdge' objects>`
- `confidence` — = `<attribute 'confidence' of 'builtins.CrossAssetEdge' objects>`
- `market_price` — = `<attribute 'market_price' of 'builtins.CrossAssetEdge' objects>`
- `option_implied_prob` — = `<attribute 'option_implied_prob' of 'builtins.CrossAssetEdge' objects>`
- `raw_edge` — = `<attribute 'raw_edge' of 'builtins.CrossAssetEdge' objects>`

### `risk_neutral_density(strikes, call_prices, r=0.0, t=1.0)`

### `implied_probability_above(strikes, call_prices, threshold, r=0.0, t=1.0)`

### `implied_probability_below(strikes, call_prices, threshold, r=0.0, t=1.0)`

### `implied_probability_between(strikes, call_prices, lower, upper, r=0.0, t=1.0)`

### `cross_asset_edge(option_prob, market_price, transaction_cost=0.0)`

### `risk_premium_adjustment(option_prob, market_price, historical_ratio=0.5)`

### `cross_asset_signal(options_data_key: 'str' = 'options_chain', threshold_key: 'str' = 'threshold', fee_rate: 'float' = 0.002) -> 'Callable[[Context], dict | None]'`

Create a pipeline function that computes cross-asset edge signals.

    Reads options chain data from ctx.params and computes implied probability
    vs prediction market price.

    Expects in ctx.params:
        - options_data_key: dict with "strikes" and "call_prices" lists
        - threshold_ke...

## Kalman & Particle Filters

### `KalmanFilter` (class)
```python
KalmanFilter(state_dim, obs_dim)
```

Standard linear Kalman filter with configurable matrices.

State estimation for linear dynamical systems:
  x_{t+1} = F * x_t + w,  w ~ N(0, Q)
  z_t     = H * x_t + v,  v ~ N(0, R)

Pro tier required.

Members:
- `covariance` — method: `covariance(self, /)`
- `log_likelihood` — method: `log_likelihood(self, /, measurement)`
- `predict` — method: `predict(self, /)`
- `set_covariance` — method: `set_covariance(self, /, cov)`
- `set_measurement_noise` — method: `set_measurement_noise(self, /, r)`
- `set_observation` — method: `set_observation(self, /, h_matrix)`
- `set_process_noise` — method: `set_process_noise(self, /, q)`
- `set_state` — method: `set_state(self, /, state)`
- `set_transition` — method: `set_transition(self, /, f_matrix)`
- `state` — method: `state(self, /)`
- `update` — method: `update(self, /, measurement)`

### `UnscentedKF` (class)
```python
UnscentedKF(state_dim, obs_dim, alpha=0.001, beta=2.0, kappa=0.0)
```

Unscented Kalman Filter using the scaled unscented transform.

Handles nonlinear dynamics better than the standard KF by using
deterministic sigma points instead of linearization.

Pro tier required.

Members:
- `covariance` — method: `covariance(self, /)`
- `log_likelihood` — method: `log_likelihood(self, /, measurement)`
- `predict` — method: `predict(self, /)`
- `set_covariance` — method: `set_covariance(self, /, cov)`
- `set_measurement_noise` — method: `set_measurement_noise(self, /, r)`
- `set_observation` — method: `set_observation(self, /, h_matrix)`
- `set_process_noise` — method: `set_process_noise(self, /, q)`
- `set_state` — method: `set_state(self, /, state)`
- `set_transition` — method: `set_transition(self, /, f_matrix)`
- `state` — method: `state(self, /)`
- `update` — method: `update(self, /, measurement)`

### `kalman_tracker(feed: 'str', state_dim: 'int' = 1, obs_dim: 'int' = 1) -> 'Callable[[Context], dict[str, Any]]'`

Create a Kalman filter tracking pipeline function.

    Tracks a latent state variable from noisy feed observations.

    Args:
        feed: Feed name to read price data from.
        state_dim: State vector dimension.
        obs_dim: Observation vector dimension.

    Returns:
        Pipeline fu...

### `kalman_hedge_ratio(feed_a: 'str', feed_b: 'str') -> 'Callable[[Context], dict[str, Any]]'`

Create a dynamic hedge ratio estimator using Kalman filter.

    Models: price_b = beta * price_a + alpha + noise
    Uses a 2-state Kalman filter to track (alpha, beta) dynamically.

    Args:
        feed_a: Feed name for the first asset.
        feed_b: Feed name for the second asset.

    Return...

### `kalman_spread(feed_a: 'str', feed_b: 'str') -> 'Callable[[Context], dict[str, Any]]'`

Create a dynamic spread tracker using Kalman filter.

    Tracks the spread between two assets with time-varying mean.

    Args:
        feed_a: Feed name for the first asset.
        feed_b: Feed name for the second asset.

    Returns:
        Pipeline function: (Context) -> dict with keys:
     ...

### `ParticleFilter` (class)
```python
ParticleFilter(n_particles, initial_state, process_noise, measurement_noise, seed=42)
```

Bootstrap Particle Filter for nonlinear state estimation.

Tracks a latent scalar state using Sequential Monte Carlo:
- State model: x_t = x_{t-1} + w,  w ~ N(0, process_noise^2)
- Obs model:   z_t = x_t + v,      v ~ N(0, measurement_noise^2)

Adaptive systematic resampling triggers when ESS drops below 50%
of the particle count.

Pro tier required.

Members:
- `credible_interval` — method: `credible_interval(self, /, level=0.95)`
- `effective_sample_size` — method: `effective_sample_size(self, /)`
- `n_particles` — method: `n_particles(self, /)`
- `particles` — method: `particles(self, /)`
- `reset` — method: `reset(self, /, initial_state)`
- `state_estimate` — method: `state_estimate(self, /)`
- `state_median` — method: `state_median(self, /)`
- `state_variance` — method: `state_variance(self, /)`
- `update` — method: `update(self, /, observation)`
- `weights` — method: `weights(self, /)`

### `PFState` (class)
```python
PFState($self, /, *args, **kwargs)
```

State returned after each particle filter update step.

Members:
- `ess` — = `<attribute 'ess' of 'builtins.PFState' objects>`
- `estimate` — = `<attribute 'estimate' of 'builtins.PFState' objects>`
- `resampled` — = `<attribute 'resampled' of 'builtins.PFState' objects>`
- `variance` — = `<attribute 'variance' of 'builtins.PFState' objects>`

### `particle_tracker(feed: 'str', n_particles: 'int' = 1000, process_noise: 'float' = 0.01, measurement_noise: 'float' = 0.05) -> 'Callable[[Context], dict[str, Any]]'`

Create a particle filter tracking pipeline function.

    Tracks a latent state variable from noisy feed observations
    using Sequential Monte Carlo methods.

    Args:
        feed: Feed name to read price data from.
        n_particles: Number of particles.
        process_noise: State transitio...

## BOCPD (Change Point Detection)

### `BocpdDetector` (class)
```python
BocpdDetector(hazard_rate=250.0, mu0=0.0, kappa0=1.0, alpha0=1.0, beta0=1.0)
```

Bayesian Online Change Point Detector (Adams & MacKay 2007).

Detects abrupt changes in streaming data by maintaining a distribution
over possible run lengths (time since last change point). Uses a
Normal-Inverse-Gamma conjugate prior for Gaussian data.

Pro tier required.

Members:
- `change_probability` — method: `change_probability(self, /)`
- `expected_run_length` — method: `expected_run_length(self, /)`
- `most_likely_run_length` — method: `most_likely_run_length(self, /)`
- `n_observations` — method: `n_observations(self, /)`
- `reset` — method: `reset(self, /)`
- `run_batch` — method: `run_batch(self, /, observations)`
- `run_length_distribution` — method: `run_length_distribution(self, /)`
- `update` — method: `update(self, /, observation)`

### `BocpdResult` (class)
```python
BocpdResult($self, /, *args, **kwargs)
```

Result of a single BOCPD update step.

Members:
- `change_prob` — = `<attribute 'change_prob' of 'builtins.BocpdResult' objects>`
- `is_changepoint` — = `<attribute 'is_changepoint' of 'builtins.BocpdResult' objects>`
- `most_likely_run_length` — = `<attribute 'most_likely_run_length' of 'builtins.BocpdResult' objects>`

### `bocpd_detector(feed: 'str', hazard_rate: 'float' = 250.0, threshold: 'float' = 0.5) -> 'Callable[[Context], dict[str, Any]]'`

Create a BOCPD change point detection pipeline function.

    Uses Bayesian online change point detection with Normal-Inverse-Gamma
    conjugate priors to detect structural breaks in price series.

    Args:
        feed: Feed name to read price data from.
        hazard_rate: Expected run length (...

## Lead-Lag Detection

### `LeadLagResult` (class)
```python
LeadLagResult($self, /, *args, **kwargs)
```

Result of a lead-lag analysis between two series.

Members:
- `correlation` — = `<attribute 'correlation' of 'builtins.LeadLagResult' objects>`
- `lag_periods` — = `<attribute 'lag_periods' of 'builtins.LeadLagResult' objects>`
- `lagger` — = `<attribute 'lagger' of 'builtins.LeadLagResult' objects>`
- `leader` — = `<attribute 'leader' of 'builtins.LeadLagResult' objects>`
- `p_value` — = `<attribute 'p_value' of 'builtins.LeadLagResult' objects>`

### `GrangerResult` (class)
```python
GrangerResult($self, /, *args, **kwargs)
```

Result of a Granger causality test.

Members:
- `f_statistic` — = `<attribute 'f_statistic' of 'builtins.GrangerResult' objects>`
- `is_significant` — = `<attribute 'is_significant' of 'builtins.GrangerResult' objects>`
- `lag` — = `<attribute 'lag' of 'builtins.GrangerResult' objects>`
- `p_value` — = `<attribute 'p_value' of 'builtins.GrangerResult' objects>`

### `LeadLagNetwork` (class)
```python
LeadLagNetwork($self, /, *args, **kwargs)
```

A network of lead-lag relationships.

Members:
- `edges` — = `<attribute 'edges' of 'builtins.LeadLagNetwork' objects>`
- `laggers` — = `<attribute 'laggers' of 'builtins.LeadLagNetwork' objects>`
- `leaders` — = `<attribute 'leaders' of 'builtins.LeadLagNetwork' objects>`

### `hayashi_yoshida(ts_a, prices_a, ts_b, prices_b)`

Hayashi-Yoshida asynchronous covariance estimator.

Computes the realized covariance between two non-synchronously observed
price series. Unlike standard covariance, this estimator correctly handles
irregularly spaced data by summing products of overlapping return intervals.

Reference: Hayashi & Yo...

### `cross_correlation_lags(x, y, max_lag)`

Compute cross-correlation between two series at multiple lags.

For each lag k in [-max_lag, +max_lag], computes the Pearson correlation
between x[max_lag..n-max_lag] and y shifted by k positions.
Positive lag means y is shifted forward (x leads y).

Args:
    x: First time series.
    y: Second tim...

### `granger_causality(x, y, max_lag)`

Granger causality F-test.

Tests whether past values of x help predict y beyond y's own past values.
Fits two OLS models:
  Restricted:   y_t = c + sum(a_i * y_{t-i}) + e_t
  Unrestricted: y_t = c + sum(a_i * y_{t-i}) + sum(b_i * x_{t-i}) + e_t
and computes the F-statistic for the joint significance...

### `lead_lag_network(series, names, max_lag)`

Build a lead-lag network from pairwise cross-correlation analysis.

For each pair of series, computes cross-correlations at all lags and
identifies the dominant lead-lag relationship. Constructs a directed
network where edges point from leader to lagger.

Args:
    series: List of time series (all s...

### `lead_lag_detector(feeds: 'list[str]', max_lag: 'int' = 10, window: 'int' = 100) -> 'Callable[[Context], dict[str, Any]]'`

Create a lead-lag detection pipeline function.

    Monitors cross-correlations across multiple feeds to identify
    which markets lead and which lag.

    Args:
        feeds: List of feed names to monitor.
        max_lag: Maximum lag to test.
        window: Rolling window for correlation estima...

## Graph & Network Analysis

### `GraphNode` (class)
```python
GraphNode($self, /, *args, **kwargs)
```

A node in the market graph with centrality metrics.

Members:
- `betweenness` — = `<attribute 'betweenness' of 'builtins.GraphNode' objects>`
- `closeness` — = `<attribute 'closeness' of 'builtins.GraphNode' objects>`
- `degree` — = `<attribute 'degree' of 'builtins.GraphNode' objects>`
- `name` — = `<attribute 'name' of 'builtins.GraphNode' objects>`

### `GraphEdge` (class)
```python
GraphEdge($self, /, *args, **kwargs)
```

An edge in the market graph.

Members:
- `source` — = `<attribute 'source' of 'builtins.GraphEdge' objects>`
- `target` — = `<attribute 'target' of 'builtins.GraphEdge' objects>`
- `weight` — = `<attribute 'weight' of 'builtins.GraphEdge' objects>`

### `Community` (class)
```python
Community($self, /, *args, **kwargs)
```

A community detected in the market graph.

Members:
- `id` — = `<attribute 'id' of 'builtins.Community' objects>`
- `members` — = `<attribute 'members' of 'builtins.Community' objects>`
- `modularity` — = `<attribute 'modularity' of 'builtins.Community' objects>`

### `MarketGraph` (class)
```python
MarketGraph($self, /, *args, **kwargs)
```

Full market graph with nodes, edges, communities, and MST.

Members:
- `communities` — = `<attribute 'communities' of 'builtins.MarketGraph' objects>`
- `density` — = `<attribute 'density' of 'builtins.MarketGraph' objects>`
- `edges` — = `<attribute 'edges' of 'builtins.MarketGraph' objects>`
- `mst_edges` — = `<attribute 'mst_edges' of 'builtins.MarketGraph' objects>`
- `nodes` — = `<attribute 'nodes' of 'builtins.MarketGraph' objects>`

### `build_correlation_graph(corr_matrix, names, threshold)`

Build a correlation graph from a correlation matrix.

Creates a graph where nodes are assets/markets and edges represent
correlations above the given threshold. Computes centrality metrics
(degree, betweenness, closeness), detects communities via Louvain,
and finds the minimum spanning tree.

Args:
...

### `minimum_spanning_tree(corr_matrix, names)`

Compute minimum spanning tree from a correlation matrix using Kruskal's algorithm.

Transforms correlations to distances: d(i,j) = sqrt(2 * (1 - corr(i,j)))
and finds the MST using union-find.

Args:
    corr_matrix: NxN correlation matrix.
    names: List of N asset/market names.

Returns:
    List...

### `detect_communities(adj_matrix, names)`

Detect communities in an adjacency matrix using Louvain modularity optimization.

Args:
    adj_matrix: NxN weighted adjacency matrix (non-negative weights).
    names: List of N node names.

Returns:
    List of Community objects with member assignments and modularity.

### `contagion_risk(adj_matrix, names, shock_node, decay)`

Simulate contagion/shock propagation through a network.

Starting from a shocked node, propagates the impact through the network
where each step multiplies the shock by the edge weight times a decay factor.
Uses BFS to model waves of contagion.

Args:
    adj_matrix: NxN weighted adjacency matrix.
 ...

### `market_network(feeds: 'list[str]', window: 'int' = 100, threshold: 'float' = 0.5) -> 'Callable[[Context], dict[str, Any]]'`

Create a market network analysis pipeline function.

    Builds a correlation graph from multiple feeds and analyzes
    network structure including communities and centrality.

    Args:
        feeds: List of feed names to include.
        window: Rolling window for correlation estimation.
       ...

## Optimal Execution

### `GPTrajectory` (class)
```python
GPTrajectory($self, /, *args, **kwargs)
```

Optimal execution trajectory from the Garleanu-Pedersen model.

Members:
- `positions` — = `<attribute 'positions' of 'builtins.GPTrajectory' objects>`
- `rate` — = `<attribute 'rate' of 'builtins.GPTrajectory' objects>`
- `target` — = `<attribute 'target' of 'builtins.GPTrajectory' objects>`
- `times` — = `<attribute 'times' of 'builtins.GPTrajectory' objects>`
- `total_cost` — = `<attribute 'total_cost' of 'builtins.GPTrajectory' objects>`

### `gp_optimal_trajectory(current_position, target_position, alpha_decay_rate, temporary_impact, permanent_impact, risk_aversion, n_steps, dt)`

Compute the Garleanu-Pedersen optimal execution trajectory.

Solves the G-P (2013) optimal trading problem with exponentially decaying
alpha signal. The optimal strategy trades toward an "aim portfolio" at a
rate proportional to the urgency parameter.

The aim portfolio at time t is:
    aim(t) = ta...

### `gp_execution_cost(trajectory, temporary_impact, permanent_impact)`

Compute the execution cost of a given GP trajectory.

Args:
    trajectory: A GPTrajectory object.
    temporary_impact: Temporary market impact coefficient.
    permanent_impact: Permanent market impact coefficient.

Returns:
    Total execution cost.

### `gp_urgency(alpha_decay_rate, temporary_impact, risk_aversion, volatility)`

Compute the Garleanu-Pedersen urgency parameter.

Urgency determines how fast to trade toward the aim portfolio.
Higher urgency means faster trading (alpha decays quickly, so act now).

urgency = sqrt(alpha_decay_rate * risk_aversion * volatility^2 / temporary_impact)

Args:
    alpha_decay_rate: Ra...

### `gp_executor(feed: 'str', target_position: 'float' = 0.0, alpha_decay: 'float' = 0.5, temporary_impact: 'float' = 0.01, permanent_impact: 'float' = 0.001, risk_aversion: 'float' = 1.0, n_steps: 'int' = 20, dt: 'float' = 0.05) -> 'Callable[[Context], dict[str, Any]]'`

Create a Garleanu-Pedersen optimal execution pipeline function.

    Computes optimal trade trajectory with exponentially decaying
    alpha signal and linear market impact.

    Args:
        feed: Feed name for price data.
        target_position: Target position to reach.
        alpha_decay: Alp...

### `ACTrajectory` (class)
```python
ACTrajectory($self, /, *args, **kwargs)
```

Optimal liquidation trajectory from the Almgren-Chriss model.

Members:
- `efficient_frontier` — = `<attribute 'efficient_frontier' of 'builtins.ACTrajectory' objects>`
- `expected_cost` — = `<attribute 'expected_cost' of 'builtins.ACTrajectory' objects>`
- `schedule` — = `<attribute 'schedule' of 'builtins.ACTrajectory' objects>`
- `variance` — = `<attribute 'variance' of 'builtins.ACTrajectory' objects>`

### `ac_optimal_schedule(total_shares, n_steps, volatility, permanent_impact, temporary_impact, risk_aversion)`

Compute the Almgren-Chriss optimal liquidation schedule.

Solves the AC2000 mean-variance optimization to find the trading schedule
that minimizes expected cost + risk_aversion * variance.

The optimal schedule is:
    n_j = total_shares * sinh(kappa * (T - t_j)) / sinh(kappa * T)

Args:
    total_s...

### `ac_efficient_frontier(total_shares, n_steps, volatility, permanent_impact, temporary_impact, n_points)`

Compute the efficient frontier for AC optimal execution.

Traces out the set of (expected_cost, variance) pairs achievable by
varying the risk aversion parameter from very patient to very aggressive.

Args:
    total_shares: Total shares to liquidate.
    n_steps: Number of trading periods.
    vola...

### `ac_kappa(volatility, permanent_impact, temporary_impact, risk_aversion)`

Compute the Almgren-Chriss kappa parameter.

kappa controls the speed of liquidation:
- Large kappa: aggressive (TWAP-like), minimizes variance but higher impact
- Small kappa: patient, minimizes impact but higher variance

kappa = arccosh(1 + risk_aversion * volatility^2 / (2 * temporary_impact * n...

### `ac_liquidator(feed: 'str', total_shares: 'float' = 1000.0, n_steps: 'int' = 20, permanent_impact: 'float' = 0.001, temporary_impact: 'float' = 0.01, risk_aversion: 'float' = 1e-06) -> 'Callable[[Context], dict[str, Any]]'`

Create an Almgren-Chriss liquidation pipeline function.

    Computes optimal liquidation schedule minimizing execution cost
    with risk aversion.

    Args:
        feed: Feed name for price/volatility data.
        total_shares: Total shares to liquidate.
        n_steps: Number of time steps.
 ...

## Queue Modeling

### `QueueModel` (class)
```python
QueueModel(initial_queue, orders_ahead)
```

Queue position model for limit order fill probability estimation.

Tracks the dynamics of a limit order's position in the queue using
Poisson arrivals and exponential cancellations. Updates rate estimates
from orderbook snapshots and computes fill probabilities.

Example:
    model = QueueModel(initial_queue=500.0, orders_ahead=200.0)
    model.update_book(480.0, 10.0, 25.0, 5.0)
    prob = model.fill_probability(60.0)  # prob of fill in 60 seconds

Members:
- `arrival_rate` — method: `arrival_rate(self, /)`
- `cancel_rate` — method: `cancel_rate(self, /)`
- `expected_fill_time` — method: `expected_fill_time(self, /)`
- `fill_prob_result` — method: `fill_prob_result(self, /, time_horizon)`
- `fill_probability` — method: `fill_probability(self, /, time_horizon)`
- `queue_position` — method: `queue_position(self, /)`
- `update_book` — method: `update_book(self, /, queue_size, arrived, cancelled, filled)`

### `FillProbResult` (class)
```python
FillProbResult($self, /, *args, **kwargs)
```

Result of a queue fill probability calculation.

Members:
- `expected_time` — = `<attribute 'expected_time' of 'builtins.FillProbResult' objects>`
- `probability` — = `<attribute 'probability' of 'builtins.FillProbResult' objects>`
- `queue_position` — = `<attribute 'queue_position' of 'builtins.FillProbResult' objects>`

### `queue_fill_prob(queue_size, position, arrival_rate, cancel_rate, time_horizon)`

Compute the fill probability for a limit order given queue parameters.

Standalone function (no stateful model needed). Models the queue as a
Poisson process with given arrival and cancel rates.

Args:
    queue_size: Total orders at this price level.
    position: Number of orders ahead of us.
    ...

### `queue_tracker(feed: 'str', initial_queue: 'float' = 100.0, orders_ahead: 'float' = 50.0) -> 'Callable[[Context], dict[str, Any]]'`

Create a queue position tracking pipeline function.

    Monitors orderbook queue dynamics and estimates fill probability
    for passive limit orders.

    Args:
        feed: Feed name to read book data from.
        initial_queue: Initial queue size estimate.
        orders_ahead: Initial orders ...

## Copulas

### `CopulaFamily` (class)
```python
CopulaFamily($self, /, *args, **kwargs)
```

Copula family for bivariate dependence modeling.

Members:
- `Clayton` — = `CopulaFamily.Clayton`
- `Frank` — = `CopulaFamily.Frank`
- `Gaussian` — = `CopulaFamily.Gaussian`
- `Gumbel` — = `CopulaFamily.Gumbel`
- `StudentT` — = `CopulaFamily.StudentT`

### `CopulaFit` (class)
```python
CopulaFit($self, /, *args, **kwargs)
```

Result of copula fitting: family, estimated parameter, and goodness-of-fit.

Members:
- `aic` — = `<attribute 'aic' of 'builtins.CopulaFit' objects>`
- `family` — = `<attribute 'family' of 'builtins.CopulaFit' objects>`
- `kendall_tau` — = `<attribute 'kendall_tau' of 'builtins.CopulaFit' objects>`
- `log_likelihood` — = `<attribute 'log_likelihood' of 'builtins.CopulaFit' objects>`
- `parameter` — = `<attribute 'parameter' of 'builtins.CopulaFit' objects>`

### `fit_copula(u, v, family)`

Fit a copula of the specified family to pseudo-uniform data.

Parameters
----------
u : list[float]
    First marginal pseudo-observations in (0, 1).
v : list[float]
    Second marginal pseudo-observations in (0, 1).
family : CopulaFamily
    Which copula family to fit.

Returns
-------
CopulaFit

### `best_copula(u, v)`

Fit all 5 copula families and return the one with best AIC.

Parameters
----------
u : list[float]
    First marginal pseudo-observations in (0, 1).
v : list[float]
    Second marginal pseudo-observations in (0, 1).

Returns
-------
CopulaFit

### `copula_sample(family, parameter, n, seed)`

Sample from a bivariate copula.

Parameters
----------
family : CopulaFamily
parameter : float
n : int
seed : int

Returns
-------
list[tuple[float, float]]

### `copula_cdf(family, parameter, u, v)`

Evaluate the copula CDF C(u, v; parameter) for a given family.

Parameters
----------
family : CopulaFamily
parameter : float
u : float
v : float

Returns
-------
float

### `rank_transform(data)`

Transform raw data to pseudo-uniform [0, 1] via rank transform.

Parameters
----------
data : list[float]
    Raw observations.

Returns
-------
list[float]
    Pseudo-uniform values in (0, 1).

### `copula_dependence(feed_a: 'str', feed_b: 'str', window: 'int' = 100) -> 'Callable[[Context], dict[str, Any]]'`

Create a copula dependence monitoring pipeline function.

    Fits copula models to track tail dependence and non-linear
    correlation between two feeds.

    Args:
        feed_a: First feed name.
        feed_b: Second feed name.
        window: Rolling window for fitting.

    Returns:
        ...

### `VineType` (class)
```python
VineType($self, /, *args, **kwargs)
```

Type of vine copula structure.

Members:
- `CVine` — = `VineType.CVine`
- `DVine` — = `VineType.DVine`

### `PairCopula` (class)
```python
PairCopula($self, /, *args, **kwargs)
```

A single pair copula in the vine structure.

Members:
- `conditioning` — = `<attribute 'conditioning' of 'builtins.PairCopula' objects>`
- `family` — = `<attribute 'family' of 'builtins.PairCopula' objects>`
- `parameter` — = `<attribute 'parameter' of 'builtins.PairCopula' objects>`
- `var1` — = `<attribute 'var1' of 'builtins.PairCopula' objects>`
- `var2` — = `<attribute 'var2' of 'builtins.PairCopula' objects>`

### `VineCopulaResult` (class)
```python
VineCopulaResult($self, /, *args, **kwargs)
```

Result of fitting a vine copula model.

Members:
- `log_likelihood` — = `<attribute 'log_likelihood' of 'builtins.VineCopulaResult' objects>`
- `n_variables` — = `<attribute 'n_variables' of 'builtins.VineCopulaResult' objects>`
- `pair_copulas` — = `<attribute 'pair_copulas' of 'builtins.VineCopulaResult' objects>`
- `vine_type` — = `<attribute 'vine_type' of 'builtins.VineCopulaResult' objects>`

### `fit_vine(data, vine_type)`

Fit a vine copula (C-vine or D-vine) to multivariate data.

Parameters
----------
data : list[list[float]]
    Each inner list is one variable's observations (all same length).
vine_type : VineType
    CVine or DVine.

Returns
-------
VineCopulaResult

### `vine_sample(vine, n, seed)`

Sample from a fitted vine copula.

Parameters
----------
vine : VineCopulaResult
    Fitted vine copula model.
n : int
    Number of samples to generate.
seed : int
    Random seed for reproducibility.

Returns
-------
list[list[float]]
    Each inner list is one variable's samples.

### `vine_tail_risk(vine, threshold, n_sim, seed)`

Estimate tail risk (joint exceedance probability) from a vine copula.

Estimates P(all variables exceed their respective thresholds)
via Monte Carlo simulation from the fitted vine.

Parameters
----------
vine : VineCopulaResult
    Fitted vine copula model.
threshold : float
    Uniform threshold i...

### `vine_risk_monitor(feeds: 'list[str]', vine_type: 'str' = 'dvine', window: 'int' = 200, refit_interval: 'int' = 100) -> 'Callable[[Context], dict[str, Any]]'`

Create a vine copula risk monitoring pipeline function.

    Fits vine copulas to multivariate feed data and estimates
    joint tail risk.

    Args:
        feeds: List of feed names to model jointly.
        vine_type: "cvine" or "dvine".
        window: Rolling window for fitting.
        refit_...

## Cross-Impact

### `CrossImpactMatrix` (class)
```python
CrossImpactMatrix($self, /, *args, **kwargs)
```

Estimated cross-impact matrix with eigenvalue analysis.

Members:
- `eigenvalues` — = `<attribute 'eigenvalues' of 'builtins.CrossImpactMatrix' objects>`
- `is_psd` — = `<attribute 'is_psd' of 'builtins.CrossImpactMatrix' objects>`
- `market_names` — = `<attribute 'market_names' of 'builtins.CrossImpactMatrix' objects>`
- `matrix` — = `<attribute 'matrix' of 'builtins.CrossImpactMatrix' objects>`

### `CrossImpactEstimator` (class)
```python
CrossImpactEstimator(n_markets, lookback)
```

Streaming cross-impact estimator with rolling window.

Members:
- `add_observation` — method: `add_observation(self, /, returns, signed_volumes)`
- `estimate` — method: `estimate(self, /)`

### `estimate_cross_impact(returns_matrix, volume_matrix, names)`

Estimate the cross-impact matrix from return and volume matrices.

Parameters
----------
returns_matrix : list[list[float]]
    Each inner list is one market's return series.
volume_matrix : list[list[float]]
    Each inner list is one market's signed volume series.
names : list[str]
    Market name...

### `cross_impact_monitor(feeds: 'list[str]', lookback: 'int' = 100) -> 'Callable[[Context], None]'`

Create a cross-impact monitoring pipeline function.

    Estimates cross-market impact matrix and injects results into ctx.params.

    Args:
        feeds: List of feed names to track.
        lookback: Rolling window for estimation.

    Returns:
        Pipeline function: (Context) -> None (injec...

## Entropy Pooling

### `EntropyPoolResult` (class)
```python
EntropyPoolResult($self, /, *args, **kwargs)
```

Result of entropy pooling optimization.

Members:
- `effective_scenarios` — = `<attribute 'effective_scenarios' of 'builtins.EntropyPoolResult' objects>`
- `posterior_probs` — = `<attribute 'posterior_probs' of 'builtins.EntropyPoolResult' objects>`
- `prior_probs` — = `<attribute 'prior_probs' of 'builtins.EntropyPoolResult' objects>`
- `relative_entropy` — = `<attribute 'relative_entropy' of 'builtins.EntropyPoolResult' objects>`

### `ViewConstraint` (class)
```python
ViewConstraint(coefficients, bound, is_equality=True)
```

A linear view constraint on the scenario set.

For equality: sum_j coefficients[j] * scenarios[j] = bound
For inequality: sum_j coefficients[j] * scenarios[j] <= bound

Members:
- `bound` — = `<attribute 'bound' of 'builtins.ViewConstraint' objects>`
- `coefficients` — = `<attribute 'coefficients' of 'builtins.ViewConstraint' objects>`
- `is_equality` — = `<attribute 'is_equality' of 'builtins.ViewConstraint' objects>`

### `entropy_pool` (module)

### `posterior_mean(probs, scenarios)`

Compute posterior mean from weighted scenarios.

Parameters
----------
probs : list[float]
    Scenario probabilities.
scenarios : list[list[float]]
    Scenario values (n_scenarios x n_variables).

Returns
-------
list[float]
    Posterior mean for each variable.

### `posterior_covariance(probs, scenarios)`

Compute posterior covariance from weighted scenarios.

Parameters
----------
probs : list[float]
    Scenario probabilities.
scenarios : list[list[float]]
    Scenario values (n_scenarios x n_variables).

Returns
-------
list[list[float]]
    Posterior covariance matrix (n_variables x n_variables).

### `entropy_pooling(scenarios: 'list[list[float]]', views: 'list[dict]') -> 'Callable[[Context], dict[str, Any]]'`

Create an entropy pooling pipeline function.

    Applies investor views to scenario probabilities using
    Meucci's entropy pooling (minimum relative entropy).

    Args:
        scenarios: Matrix of scenarios (rows=scenarios, cols=assets).
        views: List of view dicts with keys: coefficients...

## Robust Portfolio

### `RobustPortfolioResult` (class)
```python
RobustPortfolioResult($self, /, *args, **kwargs)
```

Result of robust portfolio optimization.

Members:
- `nominal_return` — = `<attribute 'nominal_return' of 'builtins.RobustPortfolioResult' objects>`
- `uncertainty_budget` — = `<attribute 'uncertainty_budget' of 'builtins.RobustPortfolioResult' objects>`
- `weights` — = `<attribute 'weights' of 'builtins.RobustPortfolioResult' objects>`
- `worst_case_return` — = `<attribute 'worst_case_return' of 'builtins.RobustPortfolioResult' objects>`

### `robust_optimize(expected_returns, covariance, return_uncertainty, uncertainty_budget, max_weight=1.0, min_weight=0.0)`

Solve the robust mean-variance optimization problem.

Parameters
----------
expected_returns : list[float]
    Point estimates of expected returns.
covariance : list[list[float]]
    Covariance matrix (N x N).
return_uncertainty : list[float]
    Uncertainty radius for each asset's expected return.
...

### `worst_case_return(weights, expected_returns, return_uncertainty, budget)`

Compute the worst-case expected return for given weights.

Parameters
----------
weights : list[float]
expected_returns : list[float]
return_uncertainty : list[float]
budget : float

Returns
-------
float

### `robust_efficient_frontier(expected_returns, covariance, return_uncertainty, n_points=20)`

Compute the robust efficient frontier.

Parameters
----------
expected_returns : list[float]
covariance : list[list[float]]
return_uncertainty : list[float]
n_points : int
    Number of points on the frontier.

Returns
-------
list[tuple[float, float]]
    (worst_case_return, portfolio_risk) pairs.

### `robust_allocator(markets: 'list[str]', uncertainty_budget: 'float' = 0.1, max_weight: 'float' = 0.3, min_weight: 'float' = 0.0) -> 'Callable[[Context], dict[str, Any]]'`

Create a robust portfolio allocation pipeline function.

    Computes worst-case optimal portfolio weights accounting for
    estimation uncertainty in expected returns.

    Args:
        markets: List of market/feed names.
        uncertainty_budget: Size of uncertainty set.
        max_weight: Ma...

## Optimal Stopping

### `StopPolicy` (class)
```python
StopPolicy($self, /, *args, **kwargs)
```

Result of Longstaff-Schwartz optimal stopping.

Members:
- `exercise_boundary` — = `<attribute 'exercise_boundary' of 'builtins.StopPolicy' objects>`
- `expected_payoff` — = `<attribute 'expected_payoff' of 'builtins.StopPolicy' objects>`
- `optimal_stop_time` — = `<attribute 'optimal_stop_time' of 'builtins.StopPolicy' objects>`

### `generate_gbm_paths(s0, mu, sigma, dt, n_steps, n_paths, seed)`

Generate Geometric Brownian Motion price paths.

S_{t+1} = S_t * exp((mu - sigma^2/2)*dt + sigma*sqrt(dt)*Z)

Parameters
----------
s0 : float
    Initial price.
mu : float
    Drift (annualized).
sigma : float
    Volatility (annualized).
dt : float
    Time step size (in years, e.g. 1/252 for dail...

### `longstaff_schwartz(paths, strike, n_basis=4)`

Run Longstaff-Schwartz optimal stopping on price paths.

Determines when to optimally exit a position by comparing
intrinsic value (distance from strike) against estimated
continuation value from polynomial regression.

Parameters
----------
paths : list[list[float]]
    Price paths (n_paths x n_ste...

### `should_exit(price, boundary, time_step)`

Check if the current price is above the exercise boundary.

Parameters
----------
price : float
    Current price.
boundary : list[float]
    Exercise boundary from StopPolicy.
time_step : int
    Current time step index.

Returns
-------
bool
    True if position should be exited (price below bound...

### `exit_optimizer(feed: 'str', n_paths: 'int' = 1000, vol: 'float' = 0.3, n_steps: 'int' = 20, strike_offset: 'float' = 0.0) -> 'Callable[[Context], dict[str, Any]]'`

Create an optimal exit timing pipeline function.

    Uses Longstaff-Schwartz backward induction to compute optimal
    exercise boundaries for position exit.

    Args:
        feed: Feed name for price data.
        n_paths: Number of Monte Carlo paths for training.
        vol: Volatility assumpt...

## ACD Duration Models

### `AcdModel` (class)
```python
AcdModel(omega=0.1, alpha=0.1, beta=0.8)
```

Members:
- `expected_duration` — method: `expected_duration(self, /)`
- `hazard_rate` — method: `hazard_rate(self, /, elapsed)`
- `surprise` — method: `surprise(self, /)`
- `update` — method: `update(self, /, event_time)`

### `AcdState` (class)
```python
AcdState($self, /, *args, **kwargs)
```

Members:
- `actual_duration` — = `<attribute 'actual_duration' of 'builtins.AcdState' objects>`
- `expected_duration` — = `<attribute 'expected_duration' of 'builtins.AcdState' objects>`
- `is_unusual` — = `<attribute 'is_unusual' of 'builtins.AcdState' objects>`
- `surprise` — = `<attribute 'surprise' of 'builtins.AcdState' objects>`

### `acd_log_likelihood(durations, omega, alpha, beta)`

Log-likelihood of ACD model given durations.

### `fit_acd(durations)`

Fit ACD model to durations via grid search MLE.

### `duration_monitor(feed: 'str', omega: 'float' = 0.1, alpha: 'float' = 0.1, beta: 'float' = 0.8) -> 'Callable[[Context], dict[str, Any]]'`

Create an ACD duration monitoring pipeline function.

    Tracks inter-trade durations and detects unusual activity patterns
    using autoregressive conditional duration models.

    Args:
        feed: Feed name to read trade data from.
        omega: ACD intercept parameter.
        alpha: ACD AR...

## Elastic Net / LASSO / Ridge

### `ElasticNetResult` (class)
```python
ElasticNetResult($self, /, *args, **kwargs)
```

Members:
- `alpha` — = `<attribute 'alpha' of 'builtins.ElasticNetResult' objects>`
- `coefficients` — = `<attribute 'coefficients' of 'builtins.ElasticNetResult' objects>`
- `intercept` — = `<attribute 'intercept' of 'builtins.ElasticNetResult' objects>`
- `l1_ratio` — = `<attribute 'l1_ratio' of 'builtins.ElasticNetResult' objects>`
- `nonzero_count` — = `<attribute 'nonzero_count' of 'builtins.ElasticNetResult' objects>`
- `r_squared` — = `<attribute 'r_squared' of 'builtins.ElasticNetResult' objects>`

### `elastic_net_fit(x, y, alpha=1.0, l1_ratio=0.5, max_iter=1000, tol=1e-06)`

Fit an elastic net model using coordinate descent.

### `elastic_net_predict(x, result)`

Predict using a fitted elastic net model.

### `lasso_fit(x, y, alpha=1.0)`

Fit LASSO (L1 penalty only, l1_ratio=1.0).

### `ridge_fit(x, y, alpha=1.0)`

Fit Ridge regression (L2 penalty only, l1_ratio=0.0).

### `elastic_net_cv(x, y, alphas=None, l1_ratios=None, n_folds=5)`

Cross-validated elastic net: tries all combos of alphas x l1_ratios.

### `signal_selector(signals: 'list[str]', target: 'str' = 'return', window: 'int' = 100, refit_interval: 'int' = 50, alpha: 'float' = 0.1, l1_ratio: 'float' = 0.7) -> 'Callable[[Context], dict[str, Any]]'`

Create a signal selection pipeline using elastic net regression.

    Automatically selects the most predictive signals from a set of
    candidates using L1/L2 regularization.

    Args:
        signals: List of signal parameter names to use as features.
        target: Target parameter name (defau...

## Microstructure Invariance

### `InvarianceResult` (class)
```python
InvarianceResult($self, /, *args, **kwargs)
```

Members:
- `bet_size` — = `<attribute 'bet_size' of 'builtins.InvarianceResult' objects>`
- `impact_per_bet` — = `<attribute 'impact_per_bet' of 'builtins.InvarianceResult' objects>`
- `market_efficiency_score` — = `<attribute 'market_efficiency_score' of 'builtins.InvarianceResult' objects>`
- `normal_trade_size` — = `<attribute 'normal_trade_size' of 'builtins.InvarianceResult' objects>`
- `trading_activity` — = `<attribute 'trading_activity' of 'builtins.InvarianceResult' objects>`

### `trading_activity(dollar_volume, volatility)`

Trading activity: W = V * sigma^(2/3).
V = dollar volume, sigma = volatility.

### `invariant_bet_size(dollar_volume, volatility, n_trades)`

Invariant bet size: (V * sigma^(2/3) / N)^(2/3).

### `kyle_obizhaeva_impact(trade_size, dollar_volume, volatility)`

Kyle-Obizhaeva price impact estimate.
Impact = sigma * (trade_size / (V * sigma^(2/3)))^(1/2).

### `is_informed_trade(trade_size, dollar_volume, volatility, threshold=2.0)`

Determine if a trade is informed based on invariance framework.
A trade is informed if its size exceeds threshold * invariant_bet_size.

### `invariance_analysis(dollar_volume, volatility, n_trades, avg_trade_size)`

Full invariance analysis.

### `invariance_monitor(feed: 'str', window: 'int' = 100) -> 'Callable[[Context], dict[str, Any]]'`

Create a microstructure invariance monitoring pipeline function.

    Tracks dollar volume and volatility to compute invariance metrics
    in real-time, detecting informed trading activity.

    Args:
        feed: Feed name to read trade data from.
        window: Rolling window for volatility est...

## Volatility Signature

### `SignaturePlot` (class)
```python
SignaturePlot($self, /, *args, **kwargs)
```

Members:
- `frequencies` — = `<attribute 'frequencies' of 'builtins.SignaturePlot' objects>`
- `noise_variance` — = `<attribute 'noise_variance' of 'builtins.SignaturePlot' objects>`
- `optimal_frequency` — = `<attribute 'optimal_frequency' of 'builtins.SignaturePlot' objects>`
- `realized_vols` — = `<attribute 'realized_vols' of 'builtins.SignaturePlot' objects>`
- `two_scale_rv` — = `<attribute 'two_scale_rv' of 'builtins.SignaturePlot' objects>`

### `volatility_signature(prices, max_freq=None, n_points=20)`

Compute the volatility signature plot.

### `two_scale_realized_vol(prices, slow_freq=5)`

Two-Scale Realized Volatility (TSRV).
Corrects for microstructure noise using fast and slow scale estimators.

### `noise_variance_estimate(prices)`

Estimate microstructure noise variance from tick-by-tick returns.
Uses first-order autocovariance: Var(noise) = -Cov(r_t, r_{t-1}).

### `optimal_sampling_frequency(prices)`

Find optimal sampling frequency that minimizes variance.

### `vol_signature_analyzer(feed: 'str', window: 'int' = 500, recompute_interval: 'int' = 100) -> 'Callable[[Context], dict[str, Any]]'`

Create a volatility signature analysis pipeline function.

    Collects prices and periodically computes the volatility signature
    plot to detect optimal sampling frequency and microstructure noise.

    Args:
        feed: Feed name to read price data from.
        window: Number of prices to co...

## Characteristic Function Pricing

### `PricingModel` (class)
```python
PricingModel($self, /, *args, **kwargs)
```

Members:
- `Heston` — = `PricingModel.Heston`
- `MertonJump` — = `PricingModel.MertonJump`
- `VarianceGamma` — = `PricingModel.VarianceGamma`

### `HestonParams` (class)
```python
HestonParams(v0=0.04, kappa=2.0, theta=0.04, sigma_v=0.3, rho=Ellipsis)
```

Members:
- `kappa` — = `<attribute 'kappa' of 'builtins.HestonParams' objects>`
- `rho` — = `<attribute 'rho' of 'builtins.HestonParams' objects>`
- `sigma_v` — = `<attribute 'sigma_v' of 'builtins.HestonParams' objects>`
- `theta` — = `<attribute 'theta' of 'builtins.HestonParams' objects>`
- `v0` — = `<attribute 'v0' of 'builtins.HestonParams' objects>`

### `MertonParams` (class)
```python
MertonParams(jump_intensity=0.1, jump_mean=Ellipsis, jump_vol=0.2)
```

Members:
- `jump_intensity` — = `<attribute 'jump_intensity' of 'builtins.MertonParams' objects>`
- `jump_mean` — = `<attribute 'jump_mean' of 'builtins.MertonParams' objects>`
- `jump_vol` — = `<attribute 'jump_vol' of 'builtins.MertonParams' objects>`

### `VGParams` (class)
```python
VGParams(sigma=0.2, theta=Ellipsis, nu=0.5)
```

Members:
- `nu` — = `<attribute 'nu' of 'builtins.VGParams' objects>`
- `sigma` — = `<attribute 'sigma' of 'builtins.VGParams' objects>`
- `theta` — = `<attribute 'theta' of 'builtins.VGParams' objects>`

### `BinaryPrice` (class)
```python
BinaryPrice($self, /, *args, **kwargs)
```

Members:
- `delta` — = `<attribute 'delta' of 'builtins.BinaryPrice' objects>`
- `model` — = `<attribute 'model' of 'builtins.BinaryPrice' objects>`
- `price` — = `<attribute 'price' of 'builtins.BinaryPrice' objects>`
- `vega` — = `<attribute 'vega' of 'builtins.BinaryPrice' objects>`

### `binary_price_heston(strike, time_to_expiry, params, r=0.0, s0=1.0)`

Price a binary option under the Heston stochastic volatility model.

### `binary_price_merton(strike, time_to_expiry, vol, params, r=0.0, s0=1.0)`

Price a binary option under the Merton jump-diffusion model.

### `binary_price_vg(strike, time_to_expiry, params, r=0.0, s0=1.0)`

Price a binary option under the Variance Gamma model.

### `implied_vol_from_binary(price, strike, time_to_expiry, r=0.0, s0=1.0)`

Implied vol from a binary option price using bisection.

### `pricing_signal(feed: 'str', model: 'str' = 'heston') -> 'Callable[[Context], dict[str, Any]]'`

Create a characteristic function pricing pipeline function.

    Prices binary options under Heston, Merton, or Variance Gamma
    models and compares to market price for edge detection.

    Args:
        feed: Feed name for price/strike data.
        model: Pricing model ("heston", "merton", "vg")...

## HJB Market Making

### `HJBConfig` (class)
```python
HJBConfig(max_inventory=10, n_time_steps=100, gamma=0.1, sigma=0.3, kappa=1.5, alpha=0.01, terminal_time=1.0)
```

Members:
- `alpha` — = `<attribute 'alpha' of 'builtins.HJBConfig' objects>`
- `gamma` — = `<attribute 'gamma' of 'builtins.HJBConfig' objects>`
- `kappa` — = `<attribute 'kappa' of 'builtins.HJBConfig' objects>`
- `max_inventory` — = `<attribute 'max_inventory' of 'builtins.HJBConfig' objects>`
- `n_time_steps` — = `<attribute 'n_time_steps' of 'builtins.HJBConfig' objects>`
- `sigma` — = `<attribute 'sigma' of 'builtins.HJBConfig' objects>`
- `terminal_time` — = `<attribute 'terminal_time' of 'builtins.HJBConfig' objects>`

### `HJBSolution` (class)
```python
HJBSolution($self, /, *args, **kwargs)
```

Members:
- `ask_deltas` — = `<attribute 'ask_deltas' of 'builtins.HJBSolution' objects>`
- `bid_deltas` — = `<attribute 'bid_deltas' of 'builtins.HJBSolution' objects>`
- `value_function` — = `<attribute 'value_function' of 'builtins.HJBSolution' objects>`

### `HJBQuote` (class)
```python
HJBQuote($self, /, *args, **kwargs)
```

Members:
- `ask_delta` — = `<attribute 'ask_delta' of 'builtins.HJBQuote' objects>`
- `bid_delta` — = `<attribute 'bid_delta' of 'builtins.HJBQuote' objects>`
- `spread` — = `<attribute 'spread' of 'builtins.HJBQuote' objects>`
- `value` — = `<attribute 'value' of 'builtins.HJBQuote' objects>`

### `solve_hjb(config)`

Solve the HJB equation for optimal market making via backward induction.

### `hjb_quote(solution, inventory, time_fraction)`

Look up optimal quotes from a pre-solved HJB solution.

### `hjb_arrival_rate(delta, kappa, alpha)`

Compute the arrival rate for a given delta.
Lambda(delta) = alpha * exp(-kappa * delta)

### `hjb_market_maker(feed: 'str', max_inventory: 'int' = 10, gamma: 'float' = 0.1, sigma: 'float' = 0.3, kappa: 'float' = 1.5, alpha: 'float' = 0.01, terminal_time: 'float' = 1.0, n_time_steps: 'int' = 100) -> 'Callable[[Context], list]'`

Create an HJB optimal market making pipeline function.

    Pre-solves the Avellaneda-Stoikov HJB PDE and uses the solution
    to generate optimal bid/ask quotes in real-time.

    Args:
        feed: Feed name for price data.
        max_inventory: Maximum inventory (absolute).
        gamma: Risk...

## Stock Hedging

### `HedgeSensitivities` (class)
```python
HedgeSensitivities($self, /, *args, **kwargs)
```

Greeks-style sensitivities for a hedged position.

Members:
- `beta` — = `<attribute 'beta' of 'builtins.HedgeSensitivities' objects>`
- `cross_gamma` — = `<attribute 'cross_gamma' of 'builtins.HedgeSensitivities' objects>`
- `delta` — = `<attribute 'delta' of 'builtins.HedgeSensitivities' objects>`
- `hedge_decay` — = `<attribute 'hedge_decay' of 'builtins.HedgeSensitivities' objects>`
- `tracking_error` — = `<attribute 'tracking_error' of 'builtins.HedgeSensitivities' objects>`

### `MultiHedgeResult` (class)
```python
MultiHedgeResult($self, /, *args, **kwargs)
```

Multi-ticker hedge optimization result.

Members:
- `hedge_effectiveness` — = `<attribute 'hedge_effectiveness' of 'builtins.MultiHedgeResult' objects>`
- `portfolio_variance` — = `<attribute 'portfolio_variance' of 'builtins.MultiHedgeResult' objects>`
- `tickers` — = `<attribute 'tickers' of 'builtins.MultiHedgeResult' objects>`
- `tracking_error` — = `<attribute 'tracking_error' of 'builtins.MultiHedgeResult' objects>`
- `weights` — = `<attribute 'weights' of 'builtins.MultiHedgeResult' objects>`

### `ScenarioOutcome` (class)
```python
ScenarioOutcome($self, /, *args, **kwargs)
```

Scenario analysis outcome.

Members:
- `hedge_benefit` — = `<attribute 'hedge_benefit' of 'builtins.ScenarioOutcome' objects>`
- `hedge_move_pct` — = `<attribute 'hedge_move_pct' of 'builtins.ScenarioOutcome' objects>`
- `portfolio_pnl` — = `<attribute 'portfolio_pnl' of 'builtins.ScenarioOutcome' objects>`
- `spot_move_pct` — = `<attribute 'spot_move_pct' of 'builtins.ScenarioOutcome' objects>`
- `unhedged_pnl` — = `<attribute 'unhedged_pnl' of 'builtins.ScenarioOutcome' objects>`

### `HedgeCostTracker` (class)
```python
HedgeCostTracker()
```

Tracks cumulative hedge trading costs for rebalancing analysis.

Members:
- `avg_cost_per_rebalance` — method: `avg_cost_per_rebalance(self, /)`
- `cost_as_pct_of_notional` — method: `cost_as_pct_of_notional(self, /)`
- `record_trade` — method: `record_trade(self, /, notional, commission, slippage)`
- `total_cost` — method: `total_cost(self, /)`

### `hedge_ratio_ols(spot_prices, hedge_prices, window=60)`

OLS hedge ratio: h* = Cov(dS, dF) / Var(dF)

Uses rolling returns computed from the last `window` prices.
The minimum-variance hedge ratio minimizes the variance of the hedged portfolio.

### `rolling_correlation(series_a, series_b, window=60)`

Rolling Pearson correlation between two series.

Returns a vector of correlations, one for each point where at least `window` values exist.

### `hedge_effectiveness(spot_returns, hedge_returns, hedge_ratio)`

Hedge effectiveness: HE = 1 - Var(hedged) / Var(unhedged)

Where hedged_return = spot_return - h * hedge_return.
A value close to 1.0 means the hedge explains most of the spot variance.

### `basis_risk(spot_returns, hedge_returns, hedge_ratio)`

Basis risk: Var(spot_return - h * hedge_return)

The residual variance after hedging. Lower is better.

### `optimal_hedge_size(spot_notional, hedge_ratio, max_hedge_notional=Ellipsis)`

Optimal hedge size given spot notional and hedge ratio.

Caps the result at `max_hedge_notional` if provided.

### `compute_hedge_sensitivities(spot_prices, hedge_prices, position_size=1.0, window=60)`

Compute Greeks-style hedge sensitivities from price series.

### `multi_ticker_hedge(spot_returns, hedge_returns_matrix, tickers)`

Multi-ticker hedge optimization via OLS.

Solves w = Sigma_FF^{-1} * Sigma_FS using Cholesky decomposition
for the case of multiple hedge instruments.

### `hedge_scenario(spot_position, spot_price, hedge_position, hedge_price, spot_move_pct, correlation=0.8, hedge_vol=0.2, spot_vol=0.2)`

Run a scenario analysis on a hedged position.

Models the hedge instrument's expected move given a spot move,
accounting for correlation and relative volatilities.

### `HedgeConfig` (dataclass)
```python
HedgeConfig(
    prediction_feed: str = '',
    stock_feed: str = '',
    stock_symbol: str = '',
    window: int = 60,
    rebalance_threshold: float = 0.05,
    max_hedge_notional: float = 100000.0,
    auto_rebalance: bool = False,
    exchange: str = 'alpaca'
)
```

Configuration for stock hedge pipeline functions.

### `hedge_monitor(prediction_feed: 'str', stock_feed: 'str', window: 'int' = 60) -> 'Callable[[Context], dict[str, Any]]'`

Create a hedge monitoring pipeline function.

    Tracks rolling hedge ratio, effectiveness, basis risk, and correlation
    between a prediction market feed and a stock feed.

    Args:
        prediction_feed: Feed name for prediction market prices.
        stock_feed: Feed name for stock/ETF pric...

### `hedge_executor(config: 'HedgeConfig') -> 'Callable[[Context], dict[str, Any]]'`

Create a hedge execution pipeline function.

    Monitors hedge drift and flags when rebalancing is needed.
    If auto_rebalance is True, generates OrderRequests for the stock exchange.

    Args:
        config: HedgeConfig with thresholds and exchange settings.

    Returns:
        Pipeline func...

### `correlation_tracker(feeds: 'list[str]', window: 'int' = 60) -> 'Callable[[Context], dict[str, Any]]'`

Create a correlation tracking pipeline function.

    Tracks pairwise rolling correlations across multiple feeds.

    Args:
        feeds: List of feed names to track.
        window: Rolling window for correlation calculation.

    Returns:
        Pipeline function: (Context) -> dict with keys:
 ...

### `stock_hedge(config: 'HedgeConfig') -> 'Callable[[Context], dict[str, Any]]'`

Create an all-in-one stock hedge pipeline function.

    Combines hedge_monitor + hedge_executor.

    Args:
        config: HedgeConfig with all settings.

    Returns:
        Pipeline function: (Context) -> dict with combined hedge state.

### `compute_hedge_report(spot_prices: 'list[float]', hedge_prices: 'list[float]', window: 'int' = 60, position_size: 'float' = 1.0) -> 'dict[str, Any]'`

Generate a one-shot hedge analysis report.

    Args:
        spot_prices: Historical spot (prediction market) prices.
        hedge_prices: Historical hedge (stock) prices.
        window: Rolling window for calculations.
        position_size: Position size for sensitivity calculations.

    Retur...

### `run_scenario(spot_position: 'float', spot_price: 'float', hedge_position: 'float', hedge_price: 'float', spot_moves: 'list[float]', correlation: 'float' = 0.8, hedge_vol: 'float' = 0.2, spot_vol: 'float' = 0.2) -> 'list[dict[str, float]]'`

Run multiple scenario analyses on a hedged position.

    Args:
        spot_position: Number of spot units held.
        spot_price: Current spot price.
        hedge_position: Number of hedge units held (negative for short).
        hedge_price: Current hedge price.
        spot_moves: List of spo...

## Synthetic Index

### `WeightingMethod` (class)
```python
WeightingMethod($self, /, *args, **kwargs)
```

Weighting method for index construction.

Members:
- `Custom` — = `WeightingMethod.Custom`
- `Equal` — = `WeightingMethod.Equal`
- `InverseVol` — = `WeightingMethod.InverseVol`
- `Liquidity` — = `WeightingMethod.Liquidity`

### `IndexWeight` (class)
```python
IndexWeight(market_id, weight)
```

A single component weight in the index.

Members:
- `market_id` — = `<attribute 'market_id' of 'builtins.IndexWeight' objects>`
- `weight` — = `<attribute 'weight' of 'builtins.IndexWeight' objects>`

### `IndexLevel` (class)
```python
IndexLevel($self, /, *args, **kwargs)
```

Computed index level.

Members:
- `level` — = `<attribute 'level' of 'builtins.IndexLevel' objects>`
- `num_components` — = `<attribute 'num_components' of 'builtins.IndexLevel' objects>`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.IndexLevel' objects>`
- `total_weight` — = `<attribute 'total_weight' of 'builtins.IndexLevel' objects>`

### `IndexRebalanceAction` (class)
```python
IndexRebalanceAction($self, /, *args, **kwargs)
```

Rebalance action for a single component.

Members:
- `current_weight` — = `<attribute 'current_weight' of 'builtins.IndexRebalanceAction' objects>`
- `delta` — = `<attribute 'delta' of 'builtins.IndexRebalanceAction' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.IndexRebalanceAction' objects>`
- `target_weight` — = `<attribute 'target_weight' of 'builtins.IndexRebalanceAction' objects>`

### `IndexArbSignal` (class)
```python
IndexArbSignal($self, /, *args, **kwargs)
```

Arbitrage signal between index level and component prices.

Members:
- `deviation` — = `<attribute 'deviation' of 'builtins.IndexArbSignal' objects>`
- `fair_level` — = `<attribute 'fair_level' of 'builtins.IndexArbSignal' objects>`
- `index_level` — = `<attribute 'index_level' of 'builtins.IndexArbSignal' objects>`
- `signal_strength` — = `<attribute 'signal_strength' of 'builtins.IndexArbSignal' objects>`

### `compute_index_level(prices, weights, base_level=100.0)`

Compute index level as weighted sum of prices.

prices[i] corresponds to weights[i].market_id.
Returns IndexLevel with the computed level.

### `compute_weights_equal(n)`

Compute equal weights for N components.

### `compute_weights_inverse_vol(volatilities)`

Compute inverse-volatility weights.

Components with lower volatility get higher weight.

### `compute_weights_liquidity(volumes)`

Compute liquidity-weighted weights.

Components with higher volume get higher weight.

### `rebalance_weights(market_ids, current_weights, target_weights)`

Compute rebalance actions to move from current to target weights.

### `index_tracking_error(portfolio_returns, index_returns)`

Compute tracking error between portfolio and index returns.

Tracking error = std(portfolio_returns - index_returns)

### `index_arb_signal(index_level, prices, weights, threshold=0.01)`

Detect arbitrage signal between index and components.

Compares a tracked index level to the fair level computed from component prices.

### `IndexConfig` (dataclass)
```python
IndexConfig(
    name: str,
    market_feeds: dict[str, str],
    weighting: str = 'equal',
    custom_weights: dict[str, float] = dict(),
    base_level: float = 100.0,
    rebalance_threshold: float = 0.05
)
```

Configuration for a synthetic index.

### `index_pipeline(config: 'IndexConfig | None' = None, market_feeds: 'dict[str, str] | None' = None, weighting: 'str' = 'equal', base_level: 'float' = 100.0) -> 'Callable'`

Compute and track a synthetic index level.

### `track_index(market_feeds: 'dict[str, str]', target_weights: 'dict[str, float] | None' = None, rebalance_threshold: 'float' = 0.05) -> 'Callable'`

Track an index and signal rebalance actions.

### `index_arb(market_feeds: 'dict[str, str]', index_feed: 'str' = '', threshold: 'float' = 0.02) -> 'Callable'`

Detect index arbitrage opportunities.

### `CRYPTO_PREDICTION_INDEX` (IndexConfig)

### `POLITICS_INDEX` (IndexConfig)

## Correlation Regime

### `CorrelationEntry` (class)
```python
CorrelationEntry(market_a, market_b, correlation, num_observations)
```

A single entry in a correlation matrix.

Members:
- `correlation` — = `<attribute 'correlation' of 'builtins.CorrelationEntry' objects>`
- `market_a` — = `<attribute 'market_a' of 'builtins.CorrelationEntry' objects>`
- `market_b` — = `<attribute 'market_b' of 'builtins.CorrelationEntry' objects>`
- `num_observations` — = `<attribute 'num_observations' of 'builtins.CorrelationEntry' objects>`

### `RegimeShiftResult` (class)
```python
RegimeShiftResult($self, /, *args, **kwargs)
```

Result of a regime shift detection.

Members:
- `change_magnitude` — = `<attribute 'change_magnitude' of 'builtins.RegimeShiftResult' objects>`
- `confidence` — = `<attribute 'confidence' of 'builtins.RegimeShiftResult' objects>`
- `new_mean_corr` — = `<attribute 'new_mean_corr' of 'builtins.RegimeShiftResult' objects>`
- `old_mean_corr` — = `<attribute 'old_mean_corr' of 'builtins.RegimeShiftResult' objects>`
- `shifted` — = `<attribute 'shifted' of 'builtins.RegimeShiftResult' objects>`

### `ContagionAlert` (class)
```python
ContagionAlert($self, /, *args, **kwargs)
```

Contagion alert for correlated market stress.

Members:
- `affected_markets` — = `<attribute 'affected_markets' of 'builtins.ContagionAlert' objects>`
- `avg_correlation` — = `<attribute 'avg_correlation' of 'builtins.ContagionAlert' objects>`
- `contagion_score` — = `<attribute 'contagion_score' of 'builtins.ContagionAlert' objects>`
- `source_market` — = `<attribute 'source_market' of 'builtins.ContagionAlert' objects>`

### `DecorrelationResult` (class)
```python
DecorrelationResult($self, /, *args, **kwargs)
```

Result of decorrelation analysis.

Members:
- `avg_correlation` — = `<attribute 'avg_correlation' of 'builtins.DecorrelationResult' objects>`
- `diversification_score` — = `<attribute 'diversification_score' of 'builtins.DecorrelationResult' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.DecorrelationResult' objects>`
- `max_correlation` — = `<attribute 'max_correlation' of 'builtins.DecorrelationResult' objects>`

### `live_correlation_matrix(market_ids, returns_matrix)`

Compute a live correlation matrix from return series.

Each row of `returns_matrix` is the return series for one market.
Returns vector of CorrelationEntry for all unique pairs.

### `detect_regime_shift(historical_corrs, recent_corrs, threshold=2.0)`

Detect a regime shift by comparing recent vs historical correlation levels.

Uses a simple z-score test on mean correlations.

### `contagion_score(source_market, market_ids, correlations, price_changes, threshold=0.5)`

Compute contagion score for a source market.

Measures how strongly correlated a market is with others,
weighted by the strength of recent price moves.

### `find_decorrelated(market_ids, returns_matrix, top_n=5)`

Find markets with lowest average correlation (best diversifiers).

### `incremental_correlation_update(n, sum_x, sum_y, sum_xy, sum_x2, sum_y2, new_x, new_y)`

Incremental O(1) correlation update using Welford-style running stats.

Given existing stats (n, sum_x, sum_y, sum_xy, sum_x2, sum_y2) and new
data point (x, y), returns updated correlation.

### `correlation_matrix(feed_names: 'list[str]', window: 'int' = 50) -> 'Callable'`

Compute live correlation matrix across feeds.

### `regime_shift(feed_names: 'list[str]', lookback: 'int' = 100, recent_window: 'int' = 20, threshold: 'float' = 2.0) -> 'Callable'`

Detect correlation regime shifts.

### `contagion_alert(feed_names: 'list[str]', correlation_threshold: 'float' = 0.5, window: 'int' = 50) -> 'Callable'`

Monitor for contagion risk across markets.

### `decorrelation_finder(feed_names: 'list[str]', top_n: 'int' = 5, window: 'int' = 50) -> 'Callable'`

Find most decorrelated markets for diversification.

## Portable Alpha

### `FactorExposure` (class)
```python
FactorExposure(factor_name, beta, r_squared, residual_vol)
```

Single factor exposure measurement.

Members:
- `beta` — = `<attribute 'beta' of 'builtins.FactorExposure' objects>`
- `factor_name` — = `<attribute 'factor_name' of 'builtins.FactorExposure' objects>`
- `r_squared` — = `<attribute 'r_squared' of 'builtins.FactorExposure' objects>`
- `residual_vol` — = `<attribute 'residual_vol' of 'builtins.FactorExposure' objects>`

### `AlphaDecomposition` (class)
```python
AlphaDecomposition($self, /, *args, **kwargs)
```

Alpha/beta decomposition result.

Members:
- `alpha` — = `<attribute 'alpha' of 'builtins.AlphaDecomposition' objects>`
- `beta` — = `<attribute 'beta' of 'builtins.AlphaDecomposition' objects>`
- `information_ratio` — = `<attribute 'information_ratio' of 'builtins.AlphaDecomposition' objects>`
- `r_squared` — = `<attribute 'r_squared' of 'builtins.AlphaDecomposition' objects>`
- `residual_returns` — = `<attribute 'residual_returns' of 'builtins.AlphaDecomposition' objects>`
- `tracking_error` — = `<attribute 'tracking_error' of 'builtins.AlphaDecomposition' objects>`

### `NeutralityTarget` (class)
```python
NeutralityTarget(factor_name, target_beta=0.0, tolerance=0.05)
```

Target neutrality specification.

Members:
- `factor_name` — = `<attribute 'factor_name' of 'builtins.NeutralityTarget' objects>`
- `target_beta` — = `<attribute 'target_beta' of 'builtins.NeutralityTarget' objects>`
- `tolerance` — = `<attribute 'tolerance' of 'builtins.NeutralityTarget' objects>`

### `NeutralityAdjustment` (class)
```python
NeutralityAdjustment($self, /, *args, **kwargs)
```

Adjustment needed to achieve neutrality.

Members:
- `current_beta` — = `<attribute 'current_beta' of 'builtins.NeutralityAdjustment' objects>`
- `factor_name` — = `<attribute 'factor_name' of 'builtins.NeutralityAdjustment' objects>`
- `hedge_ratio` — = `<attribute 'hedge_ratio' of 'builtins.NeutralityAdjustment' objects>`
- `is_within_tolerance` — = `<attribute 'is_within_tolerance' of 'builtins.NeutralityAdjustment' objects>`
- `target_beta` — = `<attribute 'target_beta' of 'builtins.NeutralityAdjustment' objects>`

### `beta_decompose(portfolio_returns, factor_returns)`

Decompose portfolio returns into alpha + beta * factor_returns.

Uses OLS regression (Cholesky solve for single factor).

### `compute_factor_exposures(portfolio_returns, factor_names, factor_returns_matrix)`

Compute factor exposures for multiple factors.

### `neutrality_adjustment(current_betas, factor_names, target_betas, tolerances)`

Compute hedge adjustments needed for market neutrality.

### `incremental_beta_update(prev_cov, prev_var, new_port_ret, new_factor_ret, decay=0.94)`

Incremental EWMA beta update: O(1) per new observation.

Returns (new_cov, new_var, new_beta).

### `FactorConfig` (dataclass)
```python
FactorConfig(
    name: str,
    feed_name: str
)
```

Factor definition for portable alpha analysis.

### `PortableAlphaConfig` (dataclass)
```python
PortableAlphaConfig(
    factors: list[FactorConfig] = list(),
    target_beta: float = 0.0,
    tolerance: float = 0.05,
    decay: float = 0.94
)
```

Configuration for portable alpha strategy.

### `beta_decompose_pipeline(portfolio_feed: 'str', factor_feed: 'str', window: 'int' = 50) -> 'Callable'`

Decompose portfolio returns into alpha + beta * factor.

### `market_neutral(portfolio_feed: 'str', factor_feed: 'str', target_beta: 'float' = 0.0, tolerance: 'float' = 0.05, decay: 'float' = 0.94) -> 'Callable'`

Track and adjust for market neutrality.

### `portable_alpha_pipeline(portfolio_feed: 'str', factor_feeds: 'dict[str, str]', target_betas: 'dict[str, float] | None' = None, tolerance: 'float' = 0.05) -> 'Callable'`

Full portable alpha with multi-factor decomposition.

### `factor_model(factor_feeds: 'dict[str, str]', decay: 'float' = 0.94) -> 'Callable'`

Track factor betas incrementally (O(1) per cycle).

## Trigger System

### `TriggerCondition` (class)
```python
TriggerCondition($self, /, *args, **kwargs)
```

Condition type for trigger evaluation.

Members:
- `Above` — = `TriggerCondition.Above`
- `AbsoluteChange` — = `TriggerCondition.AbsoluteChange`
- `Below` — = `TriggerCondition.Below`
- `Between` — = `TriggerCondition.Between`
- `CrossAbove` — = `TriggerCondition.CrossAbove`
- `CrossBelow` — = `TriggerCondition.CrossBelow`
- `Outside` — = `TriggerCondition.Outside`
- `PercentChange` — = `TriggerCondition.PercentChange`

### `TriggerActionType` (class)
```python
TriggerActionType($self, /, *args, **kwargs)
```

Action type when trigger fires.

Members:
- `Alert` — = `TriggerActionType.Alert`
- `Hedge` — = `TriggerActionType.Hedge`
- `KillSwitch` — = `TriggerActionType.KillSwitch`
- `Order` — = `TriggerActionType.Order`
- `Webhook` — = `TriggerActionType.Webhook`

### `TriggerRule` (class)
```python
TriggerRule(name, condition, threshold, action_type, threshold_upper=0.0, cooldown_secs=60.0, hysteresis=0.0)
```

A trigger rule definition.

Members:
- `action_type` — = `<attribute 'action_type' of 'builtins.TriggerRule' objects>`
- `condition` — = `<attribute 'condition' of 'builtins.TriggerRule' objects>`
- `cooldown_secs` — = `<attribute 'cooldown_secs' of 'builtins.TriggerRule' objects>`
- `hysteresis` — = `<attribute 'hysteresis' of 'builtins.TriggerRule' objects>`
- `name` — = `<attribute 'name' of 'builtins.TriggerRule' objects>`
- `threshold` — = `<attribute 'threshold' of 'builtins.TriggerRule' objects>`
- `threshold_upper` — = `<attribute 'threshold_upper' of 'builtins.TriggerRule' objects>`

### `TriggerResult` (class)
```python
TriggerResult($self, /, *args, **kwargs)
```

Result of trigger evaluation.

Members:
- `action_type` — = `<attribute 'action_type' of 'builtins.TriggerResult' objects>`
- `current_value` — = `<attribute 'current_value' of 'builtins.TriggerResult' objects>`
- `fired` — = `<attribute 'fired' of 'builtins.TriggerResult' objects>`
- `reason` — = `<attribute 'reason' of 'builtins.TriggerResult' objects>`
- `rule_name` — = `<attribute 'rule_name' of 'builtins.TriggerResult' objects>`
- `threshold` — = `<attribute 'threshold' of 'builtins.TriggerResult' objects>`

### `evaluate_trigger(rule, current_value, previous_value=0.0, last_fire_time=0.0, now=0.0, armed=True)`

Evaluate a trigger condition (pure, stateless).

`current_value`: the current feed/metric value.
`previous_value`: the previous value (for cross/change conditions).
`last_fire_time`: Unix timestamp of last fire (for cooldown).
`now`: current Unix timestamp.
`armed`: whether the trigger is currently ...

### `create_trigger(name, condition, threshold, action_type, threshold_upper=0.0, cooldown_secs=60.0, hysteresis=0.0)`

Convenience: create a TriggerRule from parameters.

### `TriggerConfig` (dataclass)
```python
TriggerConfig(
    name: str,
    feed_name: str,
    condition: str = 'above',
    threshold: float = 0.5,
    threshold_upper: float = 0.0,
    action: str = 'alert',
    cooldown_secs: float = 60.0,
    hysteresis: float = 0.0,
    webhook_url: str = '',
    order_side: str = 'buy',
    order_size: float = 10.0
)
```

Configuration for a trigger rule.

### `trigger_pipeline(triggers: 'list[TriggerConfig]', alert_manager: 'Any' = None) -> 'Callable'`

Evaluate triggers each cycle and fire actions.

### `conditional_hedge(feed_name: 'str', condition: 'str' = 'below', threshold: 'float' = 0.3, hedge_size: 'float' = 100.0, cooldown_secs: 'float' = 300.0) -> 'Callable'`

Automatically hedge when a condition is met.

### `oracle_pipeline(port: 'int' = 8099) -> 'Callable'`

Start a minimal HTTP server exposing feed prices as JSON.

    GET / returns {"feeds": {"name": price, ...}}.

## Options Overlay

### `SyntheticOption` (class)
```python
SyntheticOption($self, /, *args, **kwargs)
```

A synthetic option derived from prediction market prices.

Members:
- `delta` — = `<attribute 'delta' of 'builtins.SyntheticOption' objects>`
- `expiry_days` — = `<attribute 'expiry_days' of 'builtins.SyntheticOption' objects>`
- `gamma` — = `<attribute 'gamma' of 'builtins.SyntheticOption' objects>`
- `implied_vol` — = `<attribute 'implied_vol' of 'builtins.SyntheticOption' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.SyntheticOption' objects>`
- `price` — = `<attribute 'price' of 'builtins.SyntheticOption' objects>`
- `strike` — = `<attribute 'strike' of 'builtins.SyntheticOption' objects>`
- `theta` — = `<attribute 'theta' of 'builtins.SyntheticOption' objects>`
- `vega` — = `<attribute 'vega' of 'builtins.SyntheticOption' objects>`

### `VolSurfacePoint` (class)
```python
VolSurfacePoint(strike, expiry_days, implied_vol)
```

A point on the volatility surface.

Members:
- `expiry_days` — = `<attribute 'expiry_days' of 'builtins.VolSurfacePoint' objects>`
- `implied_vol` — = `<attribute 'implied_vol' of 'builtins.VolSurfacePoint' objects>`
- `strike` — = `<attribute 'strike' of 'builtins.VolSurfacePoint' objects>`

### `TermStructurePoint` (class)
```python
TermStructurePoint(expiry_days, implied_vol, price)
```

A point on the term structure.

Members:
- `expiry_days` — = `<attribute 'expiry_days' of 'builtins.TermStructurePoint' objects>`
- `implied_vol` — = `<attribute 'implied_vol' of 'builtins.TermStructurePoint' objects>`
- `price` — = `<attribute 'price' of 'builtins.TermStructurePoint' objects>`

### `SpreadStrategy` (class)
```python
SpreadStrategy($self, /, *args, **kwargs)
```

Spread strategy type.

Members:
- `Butterfly` — = `SpreadStrategy.Butterfly`
- `CalendarSpread` — = `SpreadStrategy.CalendarSpread`
- `Straddle` — = `SpreadStrategy.Straddle`

### `build_options_chain(market_ids, prices, expiry_days)`

Build a synthetic options chain from prediction market prices.

Treats each market price as a binary option and computes implied Greeks.

### `vol_surface(strikes, expiry_days, prices)`

Build a volatility surface from prices at different strikes and expiries.

### `term_structure(expiry_days, prices)`

Build a term structure from prices at different expiries.

### `synthetic_butterfly(lower_market, center_market, upper_market, size)`

Build synthetic butterfly spread legs.

Returns (lower_buy, center_sell_2x, upper_buy) as (market_id, side, size) tuples.

### `synthetic_straddle(market_id, size)`

Build synthetic straddle legs.

Returns (yes_buy, no_buy) legs for the same market.

### `calendar_spread_legs(near_market, far_market, size)`

Build calendar spread legs between near and far expiry.

### `options_chain(market_feeds: 'dict[str, str]', expiry_days: 'dict[str, float] | None' = None, default_expiry: 'float' = 30.0) -> 'Callable'`

Build a synthetic options chain from prediction market prices.

### `delta_hedge_continuous(market_feeds: 'dict[str, str]', hedge_threshold: 'float' = 0.1, default_expiry: 'float' = 30.0) -> 'Callable'`

Continuous delta hedging for prediction market positions.

### `vol_surface_monitor(market_feeds: 'dict[str, str]', expiry_days: 'dict[str, float] | None' = None, default_expiry: 'float' = 30.0) -> 'Callable'`

Monitor the volatility surface across prediction markets.

## Liquidity Aggregation

### `AggregatedLevel` (class)
```python
AggregatedLevel(price, size, venue)
```

A single price level in the aggregated book.

Members:
- `price` — = `<attribute 'price' of 'builtins.AggregatedLevel' objects>`
- `size` — = `<attribute 'size' of 'builtins.AggregatedLevel' objects>`
- `venue` — = `<attribute 'venue' of 'builtins.AggregatedLevel' objects>`

### `AggregatedBook` (class)
```python
AggregatedBook($self, /, *args, **kwargs)
```

Aggregated orderbook across venues.

Members:
- `asks` — = `<attribute 'asks' of 'builtins.AggregatedBook' objects>`
- `best_ask` — = `<attribute 'best_ask' of 'builtins.AggregatedBook' objects>`
- `best_bid` — = `<attribute 'best_bid' of 'builtins.AggregatedBook' objects>`
- `bids` — = `<attribute 'bids' of 'builtins.AggregatedBook' objects>`
- `mid_price` — = `<attribute 'mid_price' of 'builtins.AggregatedBook' objects>`
- `spread` — method: `spread(self, /)`
- `total_ask_size` — = `<attribute 'total_ask_size' of 'builtins.AggregatedBook' objects>`
- `total_bid_size` — = `<attribute 'total_bid_size' of 'builtins.AggregatedBook' objects>`

### `SmartRouteDecision` (class)
```python
SmartRouteDecision($self, /, *args, **kwargs)
```

Smart routing decision.

Members:
- `expected_cost` — = `<attribute 'expected_cost' of 'builtins.SmartRouteDecision' objects>`
- `fills_across_venues` — = `<attribute 'fills_across_venues' of 'builtins.SmartRouteDecision' objects>`
- `price` — = `<attribute 'price' of 'builtins.SmartRouteDecision' objects>`
- `size` — = `<attribute 'size' of 'builtins.SmartRouteDecision' objects>`
- `venue` — = `<attribute 'venue' of 'builtins.SmartRouteDecision' objects>`

### `VenueMapping` (class)
```python
VenueMapping(canonical_id, venue_market_ids)
```

Venue mapping for cross-venue equivalence.

Members:
- `canonical_id` — = `<attribute 'canonical_id' of 'builtins.VenueMapping' objects>`
- `venue_market_ids` — = `<attribute 'venue_market_ids' of 'builtins.VenueMapping' objects>`

### `aggregate_books(venue_bids, venue_asks)`

Aggregate orderbooks from multiple venues into a unified book.

`venue_bids` and `venue_asks` are lists of (venue_name, price, size) tuples.
Returns sorted aggregated book (bids descending, asks ascending).

### `smart_route_rust(book, side, size)`

Route an order to the best venue(s) based on aggregated book.

`side`: "buy" or "sell"
`size`: desired order size
Walks the aggregated book to find best execution.

### `best_venue(book, side)`

Find the single best venue for an order.

### `merged_mid_price(venue_bids, venue_asks)`

Compute the merged mid-price from aggregated book.

### `aggregate_book(venue_feeds: 'dict[str, dict[str, str]]') -> 'Callable'`

Aggregate orderbooks from multiple venues.

    venue_feeds: {venue_name: {"bid_feed": feed_name, "ask_feed": feed_name}}

### `smart_route_pipeline(venue_feeds: 'dict[str, dict[str, str]]', default_size: 'float' = 100.0) -> 'Callable'`

Smart order routing across venues.

### `cross_venue_mm(venue_feeds: 'dict[str, dict[str, str]]', spread_markup: 'float' = 0.01, size: 'float' = 50.0) -> 'Callable'`

Cross-venue market making using aggregated book.

## Multi-Leg Execution

### `FillPolicy` (class)
```python
FillPolicy($self, /, *args, **kwargs)
```

Fill policy for multi-leg execution.

Members:
- `AllOrNone` — = `FillPolicy.AllOrNone`
- `BestEffort` — = `FillPolicy.BestEffort`
- `DeltaNeutral` — = `FillPolicy.DeltaNeutral`

### `LegStatus` (class)
```python
LegStatus($self, /, *args, **kwargs)
```

Status of an individual leg.

Members:
- `Canceled` — = `LegStatus.Canceled`
- `Failed` — = `LegStatus.Failed`
- `Filled` — = `LegStatus.Filled`
- `PartiallyFilled` — = `LegStatus.PartiallyFilled`
- `Pending` — = `LegStatus.Pending`
- `Submitted` — = `LegStatus.Submitted`

### `Leg` (class)
```python
Leg(market_id, side, size, price, exchange='paper')
```

A single leg in a multi-leg order.

Members:
- `exchange` — = `<attribute 'exchange' of 'builtins.Leg' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.Leg' objects>`
- `notional` — method: `notional(self, /)`
- `price` — = `<attribute 'price' of 'builtins.Leg' objects>`
- `side` — = `<attribute 'side' of 'builtins.Leg' objects>`
- `size` — = `<attribute 'size' of 'builtins.Leg' objects>`

### `LegResult` (class)
```python
LegResult($self, /, *args, **kwargs)
```

Result of a single leg execution.

Members:
- `error` — = `<attribute 'error' of 'builtins.LegResult' objects>`
- `filled_price` — = `<attribute 'filled_price' of 'builtins.LegResult' objects>`
- `filled_size` — = `<attribute 'filled_size' of 'builtins.LegResult' objects>`
- `leg_index` — = `<attribute 'leg_index' of 'builtins.LegResult' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.LegResult' objects>`
- `order_id` — = `<attribute 'order_id' of 'builtins.LegResult' objects>`
- `status` — = `<attribute 'status' of 'builtins.LegResult' objects>`

### `MultiLegResult` (class)
```python
MultiLegResult($self, /, *args, **kwargs)
```

Result of multi-leg execution.

Members:
- `error` — = `<attribute 'error' of 'builtins.MultiLegResult' objects>`
- `fill_rate` — method: `fill_rate(self, /)`
- `legs` — = `<attribute 'legs' of 'builtins.MultiLegResult' objects>`
- `policy` — = `<attribute 'policy' of 'builtins.MultiLegResult' objects>`
- `success` — = `<attribute 'success' of 'builtins.MultiLegResult' objects>`
- `total_filled` — = `<attribute 'total_filled' of 'builtins.MultiLegResult' objects>`
- `total_legs` — = `<attribute 'total_legs' of 'builtins.MultiLegResult' objects>`
- `total_notional` — = `<attribute 'total_notional' of 'builtins.MultiLegResult' objects>`

### `validate_legs(legs)`

Validate legs before execution. Returns error message or empty string.

### `aggregate_leg_risk(legs)`

Compute aggregate risk metrics for a set of legs.

Returns (total_notional, max_single_leg, num_exchanges).

### `build_mock_result(legs, policy, success)`

Build a mock MultiLegResult (for testing / paper execution).

### `multi_leg(legs_config: 'list[dict[str, Any]] | None' = None, policy: 'str' = 'best_effort') -> 'Callable'`

Execute multiple legs atomically.

    legs_config: list of {"market_id": str, "side": str, "size": float, "price": float, "exchange": str}
    policy: "all_or_none", "best_effort", "delta_neutral"

## Evolution Optimizer

### `EvolutionConfig` (class)
```python
EvolutionConfig(pop_size=50, generations=100, mutation_rate=0.1, crossover_rate=0.7, tournament_size=3, elite_count=2, sigma=0.1)
```

Configuration for evolutionary optimization.

Members:
- `crossover_rate` — = `<attribute 'crossover_rate' of 'builtins.EvolutionConfig' objects>`
- `elite_count` — = `<attribute 'elite_count' of 'builtins.EvolutionConfig' objects>`
- `generations` — = `<attribute 'generations' of 'builtins.EvolutionConfig' objects>`
- `mutation_rate` — = `<attribute 'mutation_rate' of 'builtins.EvolutionConfig' objects>`
- `pop_size` — = `<attribute 'pop_size' of 'builtins.EvolutionConfig' objects>`
- `sigma` — = `<attribute 'sigma' of 'builtins.EvolutionConfig' objects>`
- `tournament_size` — = `<attribute 'tournament_size' of 'builtins.EvolutionConfig' objects>`

### `Individual` (class)
```python
Individual(genome, fitness=Ellipsis)
```

A single individual (genome + fitness).

Members:
- `fitness` — = `<attribute 'fitness' of 'builtins.Individual' objects>`
- `genome` — = `<attribute 'genome' of 'builtins.Individual' objects>`

### `ParamBound` (class)
```python
ParamBound(name, min_val, max_val, is_discrete=False)
```

Bounds for a single parameter.

Members:
- `is_discrete` — = `<attribute 'is_discrete' of 'builtins.ParamBound' objects>`
- `max_val` — = `<attribute 'max_val' of 'builtins.ParamBound' objects>`
- `min_val` — = `<attribute 'min_val' of 'builtins.ParamBound' objects>`
- `name` — = `<attribute 'name' of 'builtins.ParamBound' objects>`

### `EvolutionResult` (class)
```python
EvolutionResult($self, /, *args, **kwargs)
```

Result of evolution optimization.

Members:
- `best_fitness` — = `<attribute 'best_fitness' of 'builtins.EvolutionResult' objects>`
- `best_genome` — = `<attribute 'best_genome' of 'builtins.EvolutionResult' objects>`
- `fitness_history` — = `<attribute 'fitness_history' of 'builtins.EvolutionResult' objects>`
- `generations_run` — = `<attribute 'generations_run' of 'builtins.EvolutionResult' objects>`

### `GenerationStats` (class)
```python
GenerationStats($self, /, *args, **kwargs)
```

Per-generation statistics.

Members:
- `best_fitness` — = `<attribute 'best_fitness' of 'builtins.GenerationStats' objects>`
- `diversity` — = `<attribute 'diversity' of 'builtins.GenerationStats' objects>`
- `generation` — = `<attribute 'generation' of 'builtins.GenerationStats' objects>`
- `mean_fitness` — = `<attribute 'mean_fitness' of 'builtins.GenerationStats' objects>`
- `median_fitness` — = `<attribute 'median_fitness' of 'builtins.GenerationStats' objects>`
- `population_size` — = `<attribute 'population_size' of 'builtins.GenerationStats' objects>`
- `std_fitness` — = `<attribute 'std_fitness' of 'builtins.GenerationStats' objects>`
- `worst_fitness` — = `<attribute 'worst_fitness' of 'builtins.GenerationStats' objects>`

### `ConvergenceState` (class)
```python
ConvergenceState($self, /, *args, **kwargs)
```

Convergence detection state.

Members:
- `best_fitness` — = `<attribute 'best_fitness' of 'builtins.ConvergenceState' objects>`
- `converged` — = `<attribute 'converged' of 'builtins.ConvergenceState' objects>`
- `generations_without_improvement` — = `<attribute 'generations_without_improvement' of 'builtins.ConvergenceState' objects>`
- `reason` — = `<attribute 'reason' of 'builtins.ConvergenceState' objects>`

### `AdaptiveMutationState` (class)
```python
AdaptiveMutationState($self, /, *args, **kwargs)
```

Adaptive mutation state tracking.

Members:
- `sigma` — = `<attribute 'sigma' of 'builtins.AdaptiveMutationState' objects>`
- `success_count` — = `<attribute 'success_count' of 'builtins.AdaptiveMutationState' objects>`
- `success_rate` — = `<attribute 'success_rate' of 'builtins.AdaptiveMutationState' objects>`
- `total_count` — = `<attribute 'total_count' of 'builtins.AdaptiveMutationState' objects>`

### `IslandConfig` (class)
```python
IslandConfig(n_islands=4, migration_interval=5, migration_count=2, topology=Ellipsis)
```

Island model configuration.

Members:
- `migration_count` — = `<attribute 'migration_count' of 'builtins.IslandConfig' objects>`
- `migration_interval` — = `<attribute 'migration_interval' of 'builtins.IslandConfig' objects>`
- `n_islands` — = `<attribute 'n_islands' of 'builtins.IslandConfig' objects>`
- `topology` — = `<attribute 'topology' of 'builtins.IslandConfig' objects>`

### `NsgaIndividual` (class)
```python
NsgaIndividual(index, objectives)
```

NSGA-II individual with multi-objective fitness.

Members:
- `crowding_distance` — = `<attribute 'crowding_distance' of 'builtins.NsgaIndividual' objects>`
- `index` — = `<attribute 'index' of 'builtins.NsgaIndividual' objects>`
- `objectives` — = `<attribute 'objectives' of 'builtins.NsgaIndividual' objects>`
- `rank` — = `<attribute 'rank' of 'builtins.NsgaIndividual' objects>`

### `NsgaResult` (class)
```python
NsgaResult($self, /, *args, **kwargs)
```

Result of NSGA-II selection.

Members:
- `fronts` — = `<attribute 'fronts' of 'builtins.NsgaResult' objects>`
- `pareto_front_indices` — = `<attribute 'pareto_front_indices' of 'builtins.NsgaResult' objects>`
- `selected_indices` — = `<attribute 'selected_indices' of 'builtins.NsgaResult' objects>`

### `SelectionMethod` (class)
```python
SelectionMethod($self, /, *args, **kwargs)
```

Selection method for choosing parents during evolution.

Six methods from uniform exploration to UCB1 exploitation, matching the
selection strategies described in the ProFiT framework (Siper et al.).

Members:
- `EpsilonGreedy` — = `SelectionMethod.EpsilonGreedy`
- `Rank` — = `SelectionMethod.Rank`
- `RouletteWheel` — = `SelectionMethod.RouletteWheel`
- `Tournament` — = `SelectionMethod.Tournament`
- `Ucb1` — = `SelectionMethod.Ucb1`
- `Uniform` — = `SelectionMethod.Uniform`

### `MigrationTopology` (class)
```python
MigrationTopology($self, /, *args, **kwargs)
```

Topology for inter-island migration in the island model.

Members:
- `FullyConnected` — = `MigrationTopology.FullyConnected`
- `Ring` — = `MigrationTopology.Ring`

### `ObjectiveDirection` (class)
```python
ObjectiveDirection($self, /, *args, **kwargs)
```

Whether to maximize or minimize an objective in NSGA-II.

Members:
- `Maximize` — = `ObjectiveDirection.Maximize`
- `Minimize` — = `ObjectiveDirection.Minimize`

### `tournament_select(fitnesses, tournament_size=3, count=1, seed=42)`

Tournament selection: select `count` individuals from population.

### `uniform_select(fitnesses, count=1, seed=42)`

Uniform selection: random with equal probability.

### `roulette_select(fitnesses, count=1, seed=42)`

Roulette wheel selection: probability proportional to fitness.

Fitnesses are shifted so the minimum becomes a small positive value,
ensuring valid probabilities even with negative fitnesses.

### `rank_select(fitnesses, count=1, seed=42)`

Rank-based selection: probability proportional to rank position.

Individuals are sorted by fitness. Rank 1 (worst) gets weight 1,
rank N (best) gets weight N. Higher-ranked individuals are more
likely to be selected.

### `ucb1_select(fitnesses, selection_counts, total_selections, count=1)`

UCB1 selection: Upper Confidence Bound 1.

Balances exploitation (high fitness) with exploration (rarely selected).
Formula: score_i + sqrt(2 * ln(T) / n_i)

From Auer et al., "Finite-time Analysis of the Multiarmed Bandit Problem" (2002).
Used in the ProFiT evolutionary framework (Siper et al.) for...

### `epsilon_greedy_select(fitnesses, epsilon=0.1, count=1, seed=42)`

Epsilon-greedy selection: with probability epsilon pick random, else pick best.

### `gaussian_mutate(genome, bounds_min, bounds_max, is_discrete, sigma=0.1, rate=0.1, seed=42)`

Gaussian mutation: mutate genome values with Gaussian noise.

### `uniform_crossover(parent_a, parent_b, rate=0.5, seed=42)`

Uniform crossover: combine two parent genomes.

### `init_population(bounds_min, bounds_max, is_discrete, pop_size=50, seed=42)`

Initialize a random population within bounds.

### `non_dominated_sort(objectives)`

Fast non-dominated sorting (NSGA-II).

Returns fronts where fronts[0] is the Pareto front (non-dominated set),
fronts[1] is dominated only by front 0, etc.

Based on Deb et al., "A Fast and Elitist Multiobjective Genetic Algorithm: NSGA-II" (2002).

### `crowding_distance_assign(objectives, front_indices)`

Compute crowding distance for individuals in a front.

Returns crowding distances for each individual in the front.
Boundary individuals get infinite distance. Interior individuals get
distance proportional to the objective space around them.

### `nsga2_select(objectives, n_select)`

NSGA-II selection: select N individuals using front rank + crowding distance.

Multi-objective evolutionary optimization. Individuals are sorted by
Pareto dominance rank (lower is better). Within the same rank,
individuals with higher crowding distance are preferred to maintain diversity.

### `pareto_front(objectives)`

Extract the Pareto front (non-dominated set) indices.

### `island_migrate(islands, fitnesses, config)`

Perform island migration: move top genomes between islands.

Each island is a list of (genome, fitness) pairs. Migration copies the
top-K genomes from source islands to destination islands based on the topology.

### `island_selection_methods(n_islands)`

Get the default selection method for each island.

Assigns different selection methods to each island for diversity,
following the ProFiT framework's approach of per-island specialization.
Methods cycle through: RouletteWheel, Rank, UCB1, EpsilonGreedy.

### `check_convergence(best_fitness, diversity, prev_best_fitness, gens_without_improvement, patience=20, min_improvement=0.0001, diversity_threshold=0.01)`

Check if evolution has converged.

Returns convergence state based on:
1. Patience: no improvement for `patience` generations
2. Diversity collapse: population diversity below threshold

### `adapt_mutation_sigma(current_sigma, success_count, total_count, target_success_rate=0.2, adaptation_factor=1.5, sigma_min=0.001, sigma_max=2.0)`

Adapt mutation sigma using Rechenberg's 1/5 success rule.

If the success rate is above the target (default 0.2), increase sigma
to explore more broadly. If below, decrease sigma to fine-tune.

Reference: Rechenberg, I. (1973), "Evolutionsstrategie".
Also used in the Continuous Program Search framew...

### `population_diversity(population)`

Compute population diversity as the mean pairwise distance between genomes.

Uses normalized L2 distance. Returns 0.0 for populations with fewer than
2 individuals. Higher values indicate more diverse populations.

### `compute_generation_stats(generation, fitnesses)`

Compute per-generation statistics from fitness values.

### `evolve(data: 'Any', pipeline_factory: 'Callable', param_bounds: 'list[dict[str, Any]]', pop_size: 'int' = 50, generations: 'int' = 100, mutation_rate: 'float' = 0.1, crossover_rate: 'float' = 0.7, tournament_size: 'int' = 3, elite_count: 'int' = 2, sigma: 'float' = 0.1, fraction_train: 'float' = 0.7, seed: 'int' = 42, fitness_fn: 'Callable | None' = None, selection: 'str | SelectionMethod' = 'tournament', early_stopping: 'bool' = True, patience: 'int' = 20, adaptive_mutation: 'bool' = False, epsilon: 'float' = 0.1) -> 'EvolutionResult'`

Run evolutionary optimization on a strategy.

    Args:
        data: Historical data for backtesting.
        pipeline_factory: Function(params_dict) -> pipeline for hz.backtest().
        param_bounds: List of {"name": str, "min": float, "max": float, "discrete": bool}.
        selection: Selectio...

### `evolve_nsga2(data: 'Any', pipeline_factory: 'Callable', param_bounds: 'list[dict[str, Any]]', objectives: 'list[dict[str, str]]', pop_size: 'int' = 50, generations: 'int' = 100, mutation_rate: 'float' = 0.1, crossover_rate: 'float' = 0.7, sigma: 'float' = 0.1, fraction_train: 'float' = 0.7, seed: 'int' = 42, early_stopping: 'bool' = True, patience: 'int' = 20) -> 'dict[str, Any]'`

Multi-objective evolution using NSGA-II.

    Optimizes multiple objectives simultaneously (e.g., maximize Sharpe AND
    minimize max drawdown). Returns the Pareto front of non-dominated solutions.

    Based on Deb et al., "A Fast and Elitist Multiobjective Genetic Algorithm: NSGA-II" (2002).

   ...

### `evolve_islands(data: 'Any', pipeline_factory: 'Callable', param_bounds: 'list[dict[str, Any]]', pop_size: 'int' = 50, generations: 'int' = 100, mutation_rate: 'float' = 0.1, crossover_rate: 'float' = 0.7, sigma: 'float' = 0.1, fraction_train: 'float' = 0.7, seed: 'int' = 42, fitness_fn: 'Callable | None' = None, n_islands: 'int' = 4, migration_interval: 'int' = 5, migration_count: 'int' = 2, topology: 'str | MigrationTopology' = 'ring', early_stopping: 'bool' = True, patience: 'int' = 20) -> 'dict[str, Any]'`

Island model evolution with parallel populations.

    Multiple populations evolve independently using different selection methods.
    Periodically, top individuals migrate between islands to share genetic material.

    Inspired by the Darwin SDK's island model and the ProFiT framework's approach
...

## Adversarial Simulation

### `AdversaryType` (class)
```python
AdversaryType($self, /, *args, **kwargs)
```

Type of adversarial agent.

Members:
- `FrontRunner` — = `AdversaryType.FrontRunner`
- `LiquidityDrainer` — = `AdversaryType.LiquidityDrainer`
- `Spoofing` — = `AdversaryType.Spoofing`
- `Whale` — = `AdversaryType.Whale`

### `AdversaryConfig` (class)
```python
AdversaryConfig(adversary_type, market_id, intensity=1.0, size_multiplier=5.0)
```

Configuration for an adversary agent.

Members:
- `adversary_type` — = `<attribute 'adversary_type' of 'builtins.AdversaryConfig' objects>`
- `intensity` — = `<attribute 'intensity' of 'builtins.AdversaryConfig' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.AdversaryConfig' objects>`
- `size_multiplier` — = `<attribute 'size_multiplier' of 'builtins.AdversaryConfig' objects>`

### `AdversaryAction` (class)
```python
AdversaryAction($self, /, *args, **kwargs)
```

An action generated by an adversary.

Members:
- `adversary_type` — = `<attribute 'adversary_type' of 'builtins.AdversaryAction' objects>`
- `description` — = `<attribute 'description' of 'builtins.AdversaryAction' objects>`
- `is_cancel` — = `<attribute 'is_cancel' of 'builtins.AdversaryAction' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.AdversaryAction' objects>`
- `price` — = `<attribute 'price' of 'builtins.AdversaryAction' objects>`
- `side` — = `<attribute 'side' of 'builtins.AdversaryAction' objects>`
- `size` — = `<attribute 'size' of 'builtins.AdversaryAction' objects>`

### `SimulationMetrics` (class)
```python
SimulationMetrics(total_pnl=0.0, max_drawdown=0.0, sharpe_ratio=0.0, num_trades=0, win_rate=0.0, avg_slippage=0.0)
```

Metrics from an adversarial simulation run.

Members:
- `avg_slippage` — = `<attribute 'avg_slippage' of 'builtins.SimulationMetrics' objects>`
- `max_drawdown` — = `<attribute 'max_drawdown' of 'builtins.SimulationMetrics' objects>`
- `num_trades` — = `<attribute 'num_trades' of 'builtins.SimulationMetrics' objects>`
- `sharpe_ratio` — = `<attribute 'sharpe_ratio' of 'builtins.SimulationMetrics' objects>`
- `total_pnl` — = `<attribute 'total_pnl' of 'builtins.SimulationMetrics' objects>`
- `win_rate` — = `<attribute 'win_rate' of 'builtins.SimulationMetrics' objects>`

### `AdversarialResult` (class)
```python
AdversarialResult($self, /, *args, **kwargs)
```

Result of adversarial simulation.

Members:
- `adversarial` — = `<attribute 'adversarial' of 'builtins.AdversarialResult' objects>`
- `baseline` — = `<attribute 'baseline' of 'builtins.AdversarialResult' objects>`
- `drawdown_impact` — = `<attribute 'drawdown_impact' of 'builtins.AdversarialResult' objects>`
- `pnl_impact` — = `<attribute 'pnl_impact' of 'builtins.AdversarialResult' objects>`
- `sharpe_impact` — = `<attribute 'sharpe_impact' of 'builtins.AdversarialResult' objects>`
- `vulnerability_score` — = `<attribute 'vulnerability_score' of 'builtins.AdversarialResult' objects>`

### `whale_action(market_id, current_price, avg_size, intensity=1.0, seed=42)`

Generate whale actions: large market-moving orders.

### `front_runner_action(market_id, detected_side, detected_price, detected_size, edge_bps)`

Generate front-runner actions: copy detected order ahead of execution.

### `spoofing_action(market_id, current_price, spoof_size, levels=3)`

Generate spoofing actions: place and cancel large orders to move price.

### `liquidity_drainer_action(market_id, bid_price, ask_price, available_size)`

Generate liquidity drainer actions: aggressively take all resting orders.

### `compute_simulation_metrics(baseline_pnls, adversarial_pnls)`

Compute metrics comparing baseline vs adversarial simulation.

### `vulnerability_score(baseline_sharpe, adversarial_sharpe, baseline_pnl, adversarial_pnl)`

Compute vulnerability score from baseline and adversarial metrics.

### `AdversarialSimConfig` (dataclass)
```python
AdversarialSimConfig(
    adversaries: list[AdversaryConfig] = list(),
    num_cycles: int = 100,
    seed: int = 42
)
```

Configuration for adversarial simulation.

### `adversarial_sim(pipeline_factory: 'Callable', data: 'Any' = None, adversaries: 'list[AdversaryConfig] | None' = None, num_cycles: 'int' = 100, seed: 'int' = 42) -> 'AdversarialResult'`

Run adversarial simulation: baseline vs adversarial.

    Compares strategy performance with and without adversarial agents.

### `anti_fragile(pipeline_factory: 'Callable', param_bounds: 'list[dict[str, Any]]', adversaries: 'list[AdversaryConfig] | None' = None, data: 'Any' = None, pop_size: 'int' = 30, generations: 'int' = 50, seed: 'int' = 42) -> 'dict[str, Any]'`

Evolutionary optimization for adversarial robustness.

    Wraps evolution with adversarial fitness: optimizes for best
    performance UNDER adversarial conditions.

### `WHALE_PRESET` (AdversaryConfig)

### `FRONT_RUNNER_PRESET` (AdversaryConfig)

### `SPOOFING_PRESET` (AdversaryConfig)

### `DRAINER_PRESET` (AdversaryConfig)

## Execution Algorithms

### `ExecAlgo` (class)
```python
ExecAlgo(engine: 'Engine')
```

Base class for execution algorithms.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `TWAP` (class)
```python
TWAP(engine: 'Engine', duration_secs: 'float', num_slices: 'int')
```

Time-Weighted Average Price: splits into equal slices over a duration.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `VWAP` (class)
```python
VWAP(engine: 'Engine', duration_secs: 'float', volume_profile: 'list[float]')
```

Volume-Weighted Average Price: slices proportional to volume profile.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `Iceberg` (class)
```python
Iceberg(engine: 'Engine', show_size: 'float')
```

Iceberg: shows only a visible portion at a time.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `execution_tracker(window: 'int' = 200, slippage_lookback: 'int' = 50) -> 'Callable[[Context], None]'`

Create an execution quality tracker.

    Reads fills from ``ctx.params["_recent_fills"]`` (injected by strategy.py)
    and computes fill rate, slippage, and adverse selection.

    Injects ``ctx.params["exec_quality"]`` with an ExecQuality dataclass.

    Args:
        window: Rolling window for f...

### `ExecQuality` (dataclass)
```python
ExecQuality(
    fill_rate: float = 0.0,
    avg_slippage: float = 0.0,
    adverse_selection: float = 0.0,
    total_fills: int = 0,
    total_quotes: int = 0
)
```

Execution quality metrics.

## Contingent Orders

### `ContingentOrder` (class)
```python
ContingentOrder($self, /, *args, **kwargs)
```

A contingent order (stop-loss or take-profit) that triggers at a price level.

Members:
- `child_order_id` — = `<attribute 'child_order_id' of 'builtins.ContingentOrder' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.ContingentOrder' objects>`
- `id` — = `<attribute 'id' of 'builtins.ContingentOrder' objects>`
- `linked_order_id` — = `<attribute 'linked_order_id' of 'builtins.ContingentOrder' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.ContingentOrder' objects>`
- `neg_risk` — = `<attribute 'neg_risk' of 'builtins.ContingentOrder' objects>`
- `order_side` — = `<attribute 'order_side' of 'builtins.ContingentOrder' objects>`
- `side` — = `<attribute 'side' of 'builtins.ContingentOrder' objects>`
- `size` — = `<attribute 'size' of 'builtins.ContingentOrder' objects>`
- `token_id` — = `<attribute 'token_id' of 'builtins.ContingentOrder' objects>`
- `trigger_pnl` — = `<attribute 'trigger_pnl' of 'builtins.ContingentOrder' objects>`
- `trigger_price` — = `<attribute 'trigger_price' of 'builtins.ContingentOrder' objects>`
- `trigger_type` — = `<attribute 'trigger_type' of 'builtins.ContingentOrder' objects>`
- `triggered` — = `<attribute 'triggered' of 'builtins.ContingentOrder' objects>`

### `TriggerType` (class)
```python
TriggerType($self, /, *args, **kwargs)
```

Type of contingent order trigger.

Members:
- `StopLoss` — = `TriggerType.StopLoss`
- `TakeProfit` — = `TriggerType.TakeProfit`

## Alerts & Monitoring

### `AlertManager` (class)
```python
AlertManager(channels: 'list[Any] | None' = None, max_alerts_per_window: 'int' = 10, window_secs: 'float' = 60.0) -> 'None'
```

Manages alert channels with throttling.

    Usage:
        mgr = AlertManager(channels=[WebhookChannel("https://...")])
        mgr.alert(AlertType.FILL, "Filled 10 @ 0.55", data={"market": "btc"})

Members:
- `alert` — method: `alert(self, alert_type: 'AlertType', message: 'str', data: 'dict[str, Any] | None' = None) -> 'bool'`
- `clear_history` — method: `clear_history(self) -> 'None'`
- `recent_alerts` — property

### `AlertType` (enum)
Variants: `FILL`, `RISK_TRIGGER`, `MARKET_RESOLUTION`, `FEED_STALE`, `ARB_WINDOW`, `PRICE_DEVIATION`, `LIFECYCLE`, `CUSTOM`

### `Alert` (dataclass)
```python
Alert(
    alert_type: AlertType,
    message: str,
    timestamp: float = time(),
    data: dict[str, Any] = dict()
)
```

A single alert event.
- `to_dict(self) -> 'dict[str, Any]'`

### `WebhookChannel` (class)
```python
WebhookChannel(url: 'str', timeout: 'float' = 5.0) -> 'None'
```

Send alerts via HTTP POST to a webhook URL.

Members:
- `send` — method: `send(self, alert: 'Alert') -> 'bool'`

### `TelegramChannel` (class)
```python
TelegramChannel(bot_token: 'str', chat_id: 'str') -> 'None'
```

Send alerts to a Telegram chat via bot API.

Members:
- `send` — method: `send(self, alert: 'Alert') -> 'bool'`

### `DiscordChannel` (class)
```python
DiscordChannel(webhook_url: 'str') -> 'None'
```

Send alerts to a Discord channel via webhook.

Members:
- `send` — method: `send(self, alert: 'Alert') -> 'bool'`

### `LogChannel` (class)
```python
LogChannel()
```

Send alerts to the Python logger (always available, no config needed).

Members:
- `send` — method: `send(self, alert: 'Alert') -> 'bool'`

### `MetricsCollector` (class)
```python
MetricsCollector() -> 'None'
```

Thread-safe metrics collection.

Members:
- `counter` — method: `counter(self, name: 'str') -> '_Counter'`
- `gauge` — method: `gauge(self, name: 'str') -> '_Gauge'`
- `histogram` — method: `histogram(self, name: 'str') -> '_Histogram'`
- `render` — method: `render(self) -> 'str'`

### `MetricsServer` (class)
```python
MetricsServer(collector: 'MetricsCollector', port: 'int' = 9090) -> 'None'
```

HTTP server exposing /metrics in Prometheus text format.

    Usage:
        collector = MetricsCollector()
        server = MetricsServer(collector, port=9090)
        server.start()
        # ... update metrics ...
        collector.counter("orders_submitted").inc()
        collector.gauge("open_orders").set(5)
        # ... later ...
        server.stop()

Members:
- `start` — method: `start(self) -> 'None'`
- `stop` — method: `stop(self) -> 'None'`

### `update_engine_metrics(collector: 'MetricsCollector', engine) -> 'None'`

Update metrics from engine status. Call each tick cycle.

### `PriceAggregator` (class)
```python
PriceAggregator() -> 'None'
```

Aggregates prices across exchanges for the same market/event.

    Usage:
        agg = PriceAggregator()
        agg.add_mapping("btc_election", ["poly_feed", "kalshi_feed"])
        result = agg.aggregate(engine, "btc_election")

Members:
- `add_mapping` — method: `add_mapping(self, market_id: 'str', feed_exchange_pairs: 'list[tuple[str, str]]') -> 'None'`
- `aggregate` — method: `aggregate(self, engine, market_id: 'str') -> 'AggregatedPrice | None'`
- `divergence_alert` — method: `divergence_alert(self, engine, market_id: 'str', threshold: 'float' = 0.02) -> 'bool'`

### `AggregatedPrice` (dataclass)
```python
AggregatedPrice(
    market_id: str,
    best_bid: float,
    best_ask: float,
    best_bid_exchange: str,
    best_ask_exchange: str,
    composite_mid: float,
    divergence: float,
    num_exchanges: int
)
```

Unified price across exchanges for one market.

### `OrderbookSnapshot` (class)
```python
OrderbookSnapshot(timestamp=0.0, source='')
```

Full L2 orderbook snapshot for a single instrument.

Bids sorted descending by price, asks sorted ascending by price.

Members:
- `ask_depth` — method: `ask_depth(self, /, levels=None)`
- `ask_depth_levels` — method: `ask_depth_levels(self, /)`
- `asks` — method: `asks(self, /)`
- `best_ask` — method: `best_ask(self, /)`
- `best_bid` — method: `best_bid(self, /)`
- `bid_depth` — method: `bid_depth(self, /, levels=None)`
- `bid_depth_levels` — method: `bid_depth_levels(self, /)`
- `bids` — method: `bids(self, /)`
- `depth_within` — method: `depth_within(self, /, price_range)`
- `imbalance` — method: `imbalance(self, /, levels=5)`
- `mid` — method: `mid(self, /)`
- `source` — = `<attribute 'source' of 'builtins.OrderbookSnapshot' objects>`
- `spread` — method: `spread(self, /)`
- `timestamp` — = `<attribute 'timestamp' of 'builtins.OrderbookSnapshot' objects>`
- `vwap_mid` — method: `vwap_mid(self, /, levels=5)`

## Feed Health & Guards

### `feed_guard(stale_threshold: 'float' = 30.0, kill_threshold: 'float' = 60.0, critical_feeds: 'list[str] | None' = None) -> 'Callable[[Context], None]'`

Create a feed staleness monitor pipeline function.

    Injects ``ctx.params["feed_health"]`` with a FeedHealthReport each cycle.
    When all critical feeds are stale for longer than ``kill_threshold``,
    sets ``should_kill = True``. When feeds recover after a kill,
    sets ``should_recover = Tr...

### `FeedHealthReport` (dataclass)
```python
FeedHealthReport(
    feeds: dict[str, FeedHealthStatus] = dict(),
    all_stale: bool = False,
    all_stale_duration_secs: float = 0.0,
    should_kill: bool = False,
    should_recover: bool = False
)
```

Aggregated feed health report.

### `FeedHealthStatus` (dataclass)
```python
FeedHealthStatus(
    name: str,
    is_stale: bool = False,
    age_secs: float = 0.0,
    consecutive_stale_cycles: int = 0,
    last_healthy_time: float = 0.0
)
```

Health status for a single feed.

## Regime Detection

### `MarkovRegimeModel` (class)
```python
MarkovRegimeModel(n_states=2)
```

Hidden Markov Model with Gaussian emissions for regime detection.

Each state has its own (mean, variance) emission distribution.
Designed for financial return series: state 0 = low vol, state 1 = high vol, etc.

Members:
- `current_regime` — method: `current_regime(self, /)`
- `decode` — method: `decode(self, /, observations)`
- `emission_params` — method: `emission_params(self, /)`
- `filter_step` — method: `filter_step(self, /, observation)`
- `filtered_probs` — method: `filtered_probs(self, /)`
- `fit` — method: `fit(self, /, observations, max_iters=100, tol=1e-06)`
- `is_trained` — method: `is_trained(self, /)`
- `n_states` — method: `n_states(self, /)`
- `predict` — method: `predict(self, /)`
- `reset_filter` — method: `reset_filter(self, /)`
- `smooth` — method: `smooth(self, /, observations)`
- `transition_matrix` — method: `transition_matrix(self, /)`

### `prices_to_returns(prices)`

Convenience: compute log returns from a price series.

Returns vec of length len(prices)-1.

### `regime_signal(feed_name: 'str', method: 'str' = 'composite', lookback: 'int' = 50, vol_threshold_low: 'float' = 0.005, vol_threshold_high: 'float' = 0.05, momentum_lookback: 'int' = 20, weight: 'float' = 1.0) -> "'Signal'"`

Create a regime detection signal for use in signal_combiner.

    Args:
        feed_name: Name of the feed to read prices from.
        method: "volatility", "trend", or "composite" (0.6*vol + 0.4*trend).
        lookback: Rolling window size for price history.
        vol_threshold_low: Volatility...

### `markov_regime(model: 'MarkovRegimeModel | None' = None, n_states: 'int' = 2, warmup: 'int' = 100, feed: 'str | None' = None, param_name: 'str' = 'regime') -> 'Callable[[Context], None]'`

Create a pipeline function that classifies the current market regime.

    On each tick, computes the log return from the latest price, feeds it
    through the HMM forward filter, and injects regime info into ctx.params.

    Injected params:
        ctx.params[param_name] -> int: most likely state...

## Portfolio Management

### `Portfolio` (class)
```python
Portfolio(name: 'str' = 'portfolio', capital: 'float' = 10000.0) -> 'None'
```

Portfolio of prediction market positions with analytics and optimization.

Members:
- `add_position` — method: `add_position(self, market_id: 'str', side: 'str', size: 'float', entry_price: 'float', current_price: 'float') -> 'None'`
- `concentration` — method: `concentration(self) -> 'float'`
- `from_engine` — method: `from_engine(engine, capital: 'float' = 10000.0) -> 'Portfolio'`
- `metrics` — method: `metrics(self, n_simulations: 'int' = 10000, seed: 'int | None' = None, t_hours: 'float' = 24.0, vol: 'float' = 0.2) -> 'PortfolioMetrics'`
- `needs_rebalance` — method: `needs_rebalance(self, target_weights: 'dict[str, float]', threshold: 'float' = 0.05) -> 'bool'`
- `optimize_equal_weight` — method: `optimize_equal_weight(self) -> 'dict[str, float]'`
- `optimize_kelly` — method: `optimize_kelly(self, probs: 'dict[str, float]', max_total: 'float' = 1.0) -> 'dict[str, float]'`
- `optimize_min_variance` — method: `optimize_min_variance(self, returns_history: 'list[list[float]]') -> 'dict[str, float]'`
- `optimize_risk_parity` — method: `optimize_risk_parity(self, returns_history: 'list[list[float]] | None' = None) -> 'dict[str, float]'`
- `pnl` — method: `pnl(self) -> 'float'`
- `pnl_pct` — method: `pnl_pct(self) -> 'float'`
- `rebalance_orders` — method: `rebalance_orders(self, target_weights: 'dict[str, float]') -> 'list[dict]'`
- `remove_position` — method: `remove_position(self, market_id: 'str') -> 'None'`
- `summary` — method: `summary(self) -> 'str'`
- `update_price` — method: `update_price(self, market_id: 'str', new_price: 'float') -> 'None'`
- `weights` — method: `weights(self) -> 'dict[str, float]'`

### `PortfolioAsset` (dataclass)
```python
PortfolioAsset(
    market_id: str,
    side: str,
    size: float,
    entry_price: float,
    current_price: float,
    weight: float = 0.0,
    target_weight: float = 0.0
)
```

A single position within a portfolio.

### `PortfolioMetrics` (dataclass)
```python
PortfolioMetrics(
    total_value: float,
    total_pnl: float,
    total_pnl_pct: float,
    num_positions: int,
    concentration: float,
    var_95: float,
    cvar_95: float,
    win_probability: float,
    greeks: dict[str, PredictionGreeks] = dict(),
    correlation_matrix: list[list[float]] | None = None,
    shrinkage_intensity: float = 0.0
)
```

Aggregated portfolio analytics.

### `risk_parity_weights(cov_matrix: 'list[list[float]]') -> 'list[float]'`

Inverse-volatility weighting (risk parity approximation).

    Each asset's weight is proportional to 1 / sigma_i. This ensures that
    each asset contributes roughly equal standalone volatility to the portfolio.

### `min_variance_weights(cov_matrix: 'list[list[float]]') -> 'list[float]'`

Minimum variance portfolio via iterative coordinate descent.

    Solves min w^T Sigma w subject to sum(w) = 1, w_i >= 0 using
    projected gradient descent.  No external dependencies required.

## Alpha Decay

### `AlphaDecayTracker` (class)
```python
AlphaDecayTracker(window: 'int' = 100, alert_threshold: 'float' = -0.05) -> 'None'
```

Stateful tracker that accumulates predictions and outcomes over time.

    Computes rolling IC (Spearman rank correlation), estimates half-life
    via AR(1) fit, and detects trend via linear regression on rolling IC.

    Args:
        window: Rolling window size for IC calculation.
        alert_threshold: IC trend slope below which alpha is considered decaying.

Members:
- `report` — method: `report(self) -> 'AlphaDecayReport'`
- `update` — method: `update(self, predictions: 'list[float]', outcomes: 'list[float]', timestamp: 'float | None' = None) -> 'AlphaDecayReport | None'`

### `AlphaDecayReport` (dataclass)
```python
AlphaDecayReport(
    current_ic: float = 0.0,
    rolling_ic: list[tuple[float, float]] = list(),
    half_life: float = 0.0,
    ic_trend: float = 0.0,
    is_decaying: bool = False,
    rolling_sharpe: list[tuple[float, float]] = list(),
    sharpe_trend: float = 0.0,
    time_to_zero: float | None = None
)
```

Report on the current state of alpha decay.

### `alpha_decay_pipeline(window: 'int' = 100, alert_threshold: 'float' = -0.05) -> 'Callable[[Context], None]'`

Pipeline function for hz.run() that tracks alpha decay.

    Uses predictions from ``ctx.params.get("predictions")`` and outcomes
    derived from fills to track alpha decay over time.

    Injects into ctx.params:
        - "alpha_ic": current information coefficient
        - "alpha_half_life": es...

## Feature Importance (AFML)

### `FeatureImportance` (dataclass)
```python
FeatureImportance(
    feature: str,
    importance: float,
    std: float
)
```

Importance score for a single feature.

    Attributes:
        feature: Feature name.
        importance: Mean importance score (higher = more important).
        std: Standard deviation of importance across folds.

### `mda_importance(score_fn: 'callable', X: 'list[list[float]]', y: 'list[float]', feature_names: 'list[str]', n_splits: 'int' = 5, purge_gap: 'int' = 0, seed: 'int | None' = None) -> 'list[FeatureImportance]'`

Mean Decrease Accuracy (permutation importance) with purged CV.

    For each cross-validation fold, computes a baseline score on the test
    set. Then for each feature, shuffles that feature's column in the test
    set and re-scores. The importance of a feature is the mean decrease in
    score c...

### `sfi_importance(score_fn: 'callable', X: 'list[list[float]]', y: 'list[float]', feature_names: 'list[str]', n_splits: 'int' = 5) -> 'list[FeatureImportance]'`

Single Feature Importance (AFML Chapter 8.6).

    Trains the model using each feature *individually* and evaluates via
    cross-validation. The importance of a feature is its cross-validated
    score when used as the sole predictor.

    Args:
        score_fn: Callable ``(X_train, y_train, X_tes...

### `clustered_mda(score_fn: 'callable', X: 'list[list[float]]', y: 'list[float]', feature_names: 'list[str]', n_clusters: 'int' = 3, n_splits: 'int' = 5, seed: 'int | None' = None) -> 'list[FeatureImportance]'`

Clustered feature importance (AFML Chapter 8.7).

    Groups features by correlation into clusters using simple agglomerative
    clustering, then permutes entire clusters at once. This accounts for
    substitution effects between correlated features that standard MDA
    misses.

    When one feat...

## Meta-Labeling

### `MetaLabel` (dataclass)
```python
MetaLabel(
    event_idx: int,
    primary_side: int,
    meta_label: int,
    ret: float,
    confidence: float
)
```

Result of meta-labeling a single primary signal event.

    Attributes:
        event_idx: Index into the price series where the primary signal fired.
        primary_side: Direction of the primary signal (+1 long, -1 short).
        meta_label: 1 if the signal was profitable (act), 0 if not (abstain).
        ret: Realized return from the primary signal's perspective.
        confidence: Confidence score in [0, 1] based on return magnitude
            relative to volatility.

### `compute_meta_labels(prices: 'list[float]', timestamps: 'list[float]', primary_signals: 'list[tuple[int, int]]', pt_sl: 'tuple[float, float]' = (1.0, 1.0), max_holding: 'int' = 100, vol_span: 'int' = 20) -> 'list[MetaLabel]'`

Compute meta-labels from primary model signals using triple barriers.

    For each primary signal, scans forward from the signal index and applies
    three barriers:

    - **Profit-taking (PT)**: Return exceeds ``vol * pt_sl[0]`` in the
      direction of the primary signal. Meta-label = 1 (act)....

### `meta_label_pipeline(primary_signal_key: 'str' = 'primary_signal', window: 'int' = 50) -> 'Callable'`

Create a meta-labeling pipeline function for ``hz.run()``.

    Reads the primary model's signal from ``ctx.params[primary_signal_key]``
    (expected to be +1, -1, or 0). Maintains a rolling buffer of recent
    price observations and meta-label outcomes. Injects the following into
    ``ctx.params...

## Multi-Strategy Book

### `StrategyBook` (class)
```python
StrategyBook(total_capital: 'float' = 100000.0) -> 'None'
```

Multi-strategy book with isolated risk budgets and aggregate analytics.

    Manages multiple Engine references, tracks per-strategy PnL histories,
    computes correlations, and provides rebalancing recommendations.

    The book does NOT own engines -- it holds references and queries them
    via ``engine.status()``. Each strategy is responsible for its own
    execution; the book provides oversight and analytics.

    Thread-safe: no shared mutable state between strategies. Each strategy's
  ...

Members:
- `add_strategy` — method: `add_strategy(self, name: 'str', engine: 'Any', risk_budget: 'float | None' = None) -> 'None'`
- `needs_intervention` — method: `needs_intervention(self, max_drawdown: 'float' = 0.1, min_sharpe: 'float' = 0.0) -> 'list[str]'`
- `rebalance_capital` — method: `rebalance_capital(self, method: 'str' = 'equal') -> 'dict[str, float]'`
- `remove_strategy` — method: `remove_strategy(self, name: 'str') -> 'None'`
- `report` — method: `report(self) -> 'MultiStrategyReport'`
- `strategy_pipeline` — method: `strategy_pipeline(self, strategy_name: 'str') -> 'Callable'`
- `update` — method: `update(self) -> 'None'`

### `StrategySlot` (dataclass)
```python
StrategySlot(
    name: str,
    engine: Any,
    risk_budget: float,
    pnl: float = 0.0,
    sharpe: float = 0.0,
    drawdown: float = 0.0,
    is_active: bool = True
)
```

A single strategy within the multi-strategy book.

    Attributes:
        name: Unique identifier for this strategy.
        engine: Reference to the strategy's Engine instance.
        risk_budget: Fraction of total capital allocated (0.0 to 1.0).
        pnl: Current unrealized + realized PnL.
        sharpe: Rolling Sharpe ratio.
        drawdown: Current drawdown as a fraction of peak equity.
        is_active: Whether the strategy is currently active.

### `StrategyCorrelation` (dataclass)
```python
StrategyCorrelation(
    strategy_a: str,
    strategy_b: str,
    correlation: float,
    n_observations: int
)
```

Pairwise correlation between two strategy PnL streams.

    Attributes:
        strategy_a: Name of the first strategy.
        strategy_b: Name of the second strategy.
        correlation: Pearson correlation of PnL changes.
        n_observations: Number of overlapping observations used.

### `MultiStrategyReport` (dataclass)
```python
MultiStrategyReport(
    strategies: list[StrategySlot],
    total_pnl: float,
    total_drawdown: float,
    portfolio_sharpe: float,
    correlations: list[StrategyCorrelation],
    capital_utilization: float
)
```

Aggregated report across all strategies in the book.

    Attributes:
        strategies: Snapshot of each strategy slot.
        total_pnl: Sum of all strategy PnLs.
        total_drawdown: Portfolio-level drawdown.
        portfolio_sharpe: Sharpe ratio of the combined equity curve.
        correlations: Pairwise correlations between strategies.
        capital_utilization: Fraction of total capital in use.

## PnL Attribution

### `PnLBreakdown` (dataclass)
```python
PnLBreakdown(
    market_id: str,
    pnl: float,
    pnl_pct: float,
    contribution: float
)
```

Per-market PnL breakdown.

### `TimeBreakdown` (dataclass)
```python
TimeBreakdown(
    period: str,
    pnl: float,
    n_trades: int,
    win_rate: float
)
```

PnL breakdown for a time period.

### `FactorBreakdown` (dataclass)
```python
FactorBreakdown(
    factor: str,
    exposure: float,
    pnl_contribution: float,
    r_squared: float
)
```

Factor-based PnL attribution.

### `AttributionReport` (dataclass)
```python
AttributionReport(
    by_market: list[PnLBreakdown] = list(),
    by_time: list[TimeBreakdown] = list(),
    by_factor: list[FactorBreakdown] = list(),
    total_pnl: float = 0.0,
    n_positions: int = 0
)
```

Full attribution report combining market, time, and factor views.

### `GreeksAttribution` (dataclass)
```python
GreeksAttribution(
    market_id: str,
    directional: float,
    curvature: float,
    belief_vega_pnl: float,
    correlation_vega_pnl: float,
    residual: float
)
```

Per-position PnL decomposition using logit Greeks.

### `attribute_pnl(engine: 'Any') -> 'AttributionReport'`

Extract positions and fills from engine, compute per-market PnL breakdown.

    For each position: compute PnL, percentage, and contribution to total.
    Results are sorted by absolute PnL descending.

    Args:
        engine: Horizon Engine instance.

    Returns:
        AttributionReport with b...

### `attribute_by_time(fills: 'list[Any]', period: 'str' = 'daily') -> 'list[TimeBreakdown]'`

Group fills by time period and compute PnL per period.

    Args:
        fills: List of Fill objects (must have ``timestamp`` and ``price``
               attributes, plus ``order_side`` and ``size``).
        period: One of "hourly", "daily", "weekly".

    Returns:
        List of TimeBreakdown s...

### `attribute_by_factor(positions: 'list[Any]', factor_exposures: 'dict[str, dict[str, float]]') -> 'list[FactorBreakdown]'`

Factor-based PnL attribution.

    Args:
        positions: List of Position objects.
        factor_exposures: Mapping of factor_name -> {market_id: exposure_weight}.
            Example: {"crypto": {"btc-100k": 0.8, "eth-5k": 0.9},
                      "politics": {"trump-win": 1.0}}

    Returns...

### `pnl_attribution_pipeline(engine: 'Any' = None) -> 'Callable[[Context], None]'`

Pipeline function for hz.run() that adds attribution data each cycle.

    Injects into ctx.params:
        - "pnl_by_market": list of PnLBreakdown
        - "pnl_top_winner": PnLBreakdown or None
        - "pnl_top_loser": PnLBreakdown or None

    Args:
        engine: Optional engine override. If...

### `greeks_attribution(positions: 'list[Any]', price_before: 'dict[str, float]', price_after: 'dict[str, float]', belief_vol: 'float' = 0.2, vol_after: 'float | None' = None) -> 'list[GreeksAttribution]'`

Decompose per-position PnL using logit-space Greeks.

    Args:
        positions: List of Position objects.
        price_before: {market_id: price} at start of period.
        price_after: {market_id: price} at end of period.
        belief_vol: Belief volatility at start.
        vol_after: Belie...

## Reconciliation

### `PositionBreak` (dataclass)
```python
PositionBreak(
    market_id: str,
    break_type: str,
    engine_size: float | None = None,
    exchange_size: float | None = None,
    engine_side: str | None = None,
    exchange_side: str | None = None,
    severity: str = 'info'
)
```

A single reconciliation discrepancy.

### `ReconciliationReport` (dataclass)
```python
ReconciliationReport(
    breaks: list[PositionBreak] = list(),
    matched: int = 0,
    total_engine: int = 0,
    total_exchange: int = 0,
    is_clean: bool = True,
    timestamp: float = 0.0
)
```

Result of a reconciliation run.

### `reconcile(engine: 'Any', exchange_positions: 'list[dict[str, Any]] | None' = None) -> 'ReconciliationReport'`

Compare engine positions vs exchange.

    If exchange_positions is None, attempts to fetch from engine's exchange
    (if the engine supports it). Otherwise, compares against the provided list.

    Exchange position dicts should have keys:
        - "market_id" (str): market identifier
        - "...

### `auto_reconcile(engine: 'Any' = None, interval: 'float' = 300.0) -> 'Callable[[Context], None]'`

Pipeline function for hz.run() that runs reconciliation periodically.

    Runs reconciliation every ``interval`` seconds and injects results
    into ctx.params:
        - "recon_clean" (bool): True if no breaks found
        - "recon_breaks" (int): Number of breaks found

    Logs warnings for any...

## Copy-Trading

### `CopyTraderConfig` (dataclass)
```python
CopyTraderConfig(
    wallets: list[str] = list(),
    size_scale: float = 1.0,
    max_position_per_market: float = 1000.0,
    min_trade_usdc: float = 1.0,
    poll_interval: float = 30.0,
    inverse: bool = False,
    max_slippage: float = 0.02,
    dry_run: bool = False,
    dedup_capacity: int = 10000
)
```

Configuration for copy-trading.

### `CopyTradeResult` (dataclass)
```python
CopyTradeResult(
    source_wallet: str,
    source_tx_hash: str | None,
    market_slug: str,
    condition_id: str,
    side: str,
    order_side: str,
    size: float,
    price: float,
    order_id: str | None = None,
    error: str | None = None
)
```

Record of a single copied (or attempted) trade.

### `copy_trades(wallet: 'str | list[str] | None' = None, wallets: 'list[str] | None' = None, size_scale: 'float' = 1.0, max_position: 'float' = 1000.0, min_trade_usdc: 'float' = 1.0, poll_interval: 'float' = 30.0, exchange: 'str' = 'paper', inverse: 'bool' = False, max_slippage: 'float' = 0.02, dry_run: 'bool' = False, risk: 'Any' = None, api_key: 'str | None' = None) -> 'None'`

Copy trades from Polymarket whale wallet(s).

    Blocking loop that polls wallet trades and submits mirrored orders.

    Args:
        wallet: Single wallet address or list of addresses.
        wallets: List of wallet addresses (alternative to ``wallet``).
        size_scale: Multiplier for trade...

### `copy_trader(wallet: 'str | list[str] | None' = None, wallets: 'list[str] | None' = None, size_scale: 'float' = 1.0, max_position: 'float' = 1000.0, min_trade_usdc: 'float' = 1.0, inverse: 'bool' = False, max_slippage: 'float' = 0.02, dry_run: 'bool' = False) -> 'Callable[[Context], None]'`

Create a pipeline function that copies trades from tracked wallets.

    Returns a callable for use in ``hz.run(pipeline=[...])``.

    Args:
        wallet: Single wallet address or list of addresses.
        wallets: List of wallet addresses (alternative to ``wallet``).
        size_scale: Multipl...

## Wallet Intelligence

### `WalletScore` (dataclass)
```python
WalletScore(
    wallet: str,
    win_rate: float,
    avg_pnl_pct: float,
    sharpe: float,
    total_pnl: float,
    trade_count: int,
    position_count: int,
    composite_score: float
)
```

Performance score for a wallet.

### `WalletPattern` (dataclass)
```python
WalletPattern(
    name: str,
    description: str,
    value: float,
    exploitable: bool,
    counter_strategy: str
)
```

A detected behavioral pattern in a wallet's trading.

### `WalletAnalysis` (dataclass)
```python
WalletAnalysis(
    wallet: str,
    patterns: list[WalletPattern],
    vulnerability_score: float,
    counter_strategies: list[str],
    trade_count: int,
    analysis_period_hours: int
)
```

Adversarial analysis of a wallet's trading behavior.

### `BotDetection` (dataclass)
```python
BotDetection(
    wallet: str,
    is_bot: bool,
    confidence: float,
    strategy_type: str,
    evidence: list[str],
    trade_count: int,
    avg_interval_seconds: float,
    size_regularity: float
)
```

Bot detection result for a single wallet in a market.

### `score_wallet(address: 'str', limit: 'int' = 500) -> 'WalletScore'`

Score a wallet's trading performance.

    Fetches positions and computes win rate, average PnL, Sharpe estimate,
    and a composite score from -1 (terrible) to +1 (excellent).

    Args:
        address: Wallet address (0x...).
        limit: Max positions to analyze.

    Returns:
        WalletS...

### `analyze_wallet(address: 'str', trade_limit: 'int' = 500) -> 'WalletAnalysis'`

Analyze a wallet for exploitable trading patterns.

    Runs 6 pattern detectors on the wallet's trade history:
    timing regularity, sizing predictability, directional bias,
    reaction speed, market concentration, and stop levels.

    Args:
        address: Wallet address (0x...).
        trade...

### `scan_bots(condition_id: 'str', trade_limit: 'int' = 1000, min_trades: 'int' = 5) -> 'list[BotDetection]'`

Scan a market to detect bot wallets.

    Fetches recent trades, groups by wallet, and classifies each wallet
    as bot or human with strategy type and confidence score.

    Args:
        condition_id: Market condition ID (0x-prefixed hex).
        trade_limit: Max trades to analyze.
        min_t...

### `reverse_copy(wallet: 'str', threshold: 'float' = -0.3, size_scale: 'float' = 0.5, max_position: 'float' = 1000.0, poll_interval: 'float' = 30.0, exchange: 'str' = 'paper', dry_run: 'bool' = False, api_key: 'str | None' = None) -> 'None'`

Auto-fade a bad wallet by reverse-copying its trades.

    Scores the wallet first. If composite_score < threshold, starts
    an inverse copy-trade loop. If the wallet isn't bad enough, logs
    a message and returns.

    Args:
        wallet: Wallet address to evaluate and potentially fade.
     ...

### `reverse_copier(wallet: 'str', threshold: 'float' = -0.3, size_scale: 'float' = 0.5, max_position: 'float' = 1000.0, min_trade_usdc: 'float' = 1.0, max_slippage: 'float' = 0.02, dry_run: 'bool' = False) -> 'Callable[..., None]'`

Create a pipeline function that reverse-copies a bad wallet.

    Scores the wallet on first call. If the score is below threshold,
    wraps copy_trader with inverse=True. Otherwise returns None each cycle.

    Args:
        wallet: Wallet address to evaluate.
        threshold: Composite score th...

### `bot_scanner(min_trades: 'int' = 5) -> 'Callable[..., None]'`

Create a pipeline function that scans markets for bots.

    Scans each market in ctx.market_ids and stores results in
    ctx.params["bot_scan_results"].

    Args:
        min_trades: Min trades per wallet to classify.

    Returns:
        Pipeline function: (Context) -> None

## Wallet Profiler

### `FullWalletProfile` (dataclass)
```python
FullWalletProfile(
    wallet: str,
    score: WalletScore,
    analysis: WalletAnalysis,
    temporal: TemporalProfile,
    market_selection: MarketSelectionProfile,
    order_flow: OrderFlowProfile,
    edge: EdgeDetection,
    strategies: list[ProfitStrategy],
    best_strategy: ProfitStrategy | None,
    data_quality: str
)
```

Complete behavioral profile with actionable strategies.

### `ProfitStrategy` (dataclass)
```python
ProfitStrategy(
    name: str,
    description: str,
    mechanism: str,
    expected_edge: str,
    risk_level: str,
    confidence: float,
    impl_type: str,
    params: dict[str, Any]
)
```

A concrete strategy to profit from a wallet's behavior.

### `TemporalProfile` (dataclass)
```python
TemporalProfile(
    hour_distribution: HourDistribution,
    day_distribution: DayDistribution,
    session: SessionClassification,
    burst: BurstAnalysis,
    active_days_pct: float
)
```

When does the wallet trade?

### `MarketSelectionProfile` (dataclass)
```python
MarketSelectionProfile(
    categories: list[MarketCategory],
    best_category: str,
    worst_category: str,
    herfindahl: float,
    diversity_score: float,
    market_count: int,
    early_entrant_score: float
)
```

What does the wallet trade?

### `OrderFlowProfile` (dataclass)
```python
OrderFlowProfile(
    building_style: PositionBuildingStyle,
    exit_style: ExitStyle,
    avg_hold_hours: float,
    hold_cv: float,
    size_trend: str,
    size_trend_slope: float,
    dip_buyer_score: float,
    rip_seller_score: float
)
```

How does the wallet enter and exit?

### `EdgeDetection` (dataclass)
```python
EdgeDetection(
    information_score: float,
    timing_quality: float,
    win_rate_by_size: dict[str, float],
    streak_type: str,
    streak_autocorrelation: float,
    edge_bps: float,
    confidence: float
)
```

Is the wallet good?

### `profile_wallet(address: 'str', trade_limit: 'int' = 500) -> 'FullWalletProfile'`

Generate a complete behavioral profile for a wallet.

    Args:
        address: Wallet address (0x...).
        trade_limit: Max trades to fetch for analysis.

    Returns:
        FullWalletProfile with all analysis dimensions and strategies.

### `hunt(wallet: 'str', trade_limit: 'int' = 500, size_scale: 'float' = 0.5, max_position: 'float' = 1000.0, poll_interval: 'float' = 30.0, exchange: 'str' = 'paper', dry_run: 'bool' = False, api_key: 'str | None' = None) -> 'None'`

Profile a wallet and auto-execute the best strategy.

    Blocking function: profiles the wallet, picks the best strategy,
    then launches the appropriate copy/fade loop.

    Args:
        wallet: Wallet address (0x...).
        trade_limit: Max trades for profiling.
        size_scale: Base size...

### `hunter(wallet: 'str', trade_limit: 'int' = 500, size_scale: 'float' = 0.5, max_position: 'float' = 1000.0, min_trade_usdc: 'float' = 1.0, max_slippage: 'float' = 0.02, dry_run: 'bool' = False) -> 'Callable[..., None]'`

Create a pipeline function that profiles and hunts a wallet.

    Profiles on first call, then delegates to ``copy_trader()`` each
    cycle with appropriate params based on the best strategy.

    Args:
        wallet: Wallet address (0x...).
        trade_limit: Max trades for profiling.
        s...

## Wallet Tracker

### `TrackerConfig` (dataclass)
```python
TrackerConfig(
    decay_half_life_secs: float = 21600.0,
    ema_alpha: float = 0.3,
    min_signal_strength: float = 0.05,
    min_confidence: float = 0.3,
    min_edge_bps: float = 200.0,
    min_wallets_for_consensus: int = 3,
    min_wallet_quality: float = 0.1,
    momentum_weight: float = 0.2,
    regime_change_threshold: float = 0.4,
    wallet_score_cache_ttl: float = 300.0,
    poll_interval_cycles: int = 20
)
```

Tunable knobs for the wallet tracker.

    Attributes:
        decay_half_life_secs: Half-life for recency decay (seconds).
        ema_alpha: Smoothing factor for EMA between refreshes.
        min_signal_strength: Minimum ``|signal - 0.5|`` to be actionable.
        min_confidence: Minimum confidence to be actionable.
        min_edge_bps: Minimum |edge| vs market price to be actionable.
        min_wallets_for_consensus: Minimum wallets for consensus signal.
        min_wallet_quality: Minimum ``|composite_score|`` to include wallet.
        momentum_weight: Maximum momentum contribution to signal.
        regime_change_threshold: Buy-ratio delta threshold for regime flip.
        wallet_score_cache_ttl: Seconds to cache wallet scores.
        poll_interval_cycles: Pipeline cycles between refreshes.

### `WalletMarketSignal` (dataclass)
```python
WalletMarketSignal(
    wallet: str,
    market_id: str,
    signal: float,
    direction: float,
    conviction: float,
    recency: float,
    momentum: float,
    wallet_quality: float,
    confidence: float,
    confidence_low: float,
    confidence_high: float,
    trade_count: int,
    position_size_usdc: float,
    regime: str,
    edge_bps: float,
    timestamp: float,
    is_actionable: bool
)
```

Directional signal for one wallet in one market.

    Attributes:
        wallet: Wallet address.
        market_id: Market condition ID.
        signal: Composite signal in [0.01, 0.99]; 0.5 = neutral.
        direction: Raw position direction D(w,m).
        conviction: Relative sizing C(w,m).
        recency: Decay weight R(w,m).
        momentum: Recent trade direction shift M(w,m).
        wallet_quality: Composite score from ``score_wallet`` [-1, 1].
        confidence: Signal confidence [0, 1].
        confidence_low: Lower bound of confidence interval.
        confidence_high: Upper bound of confidence interval.
        trade_count: Number of trades in the market.
        position_size_usdc: Total position size in USDC.
        regime: Detected regime (bullish, bearish, neutral, flipping).
        edge_bps: Edge vs market price in basis points.
        timestamp: Unix timestamp.
        is_actionable: Whether signal passes all thresholds.

### `ConsensusSignal` (dataclass)
```python
ConsensusSignal(
    market_id: str,
    signal: float,
    confidence: float,
    confidence_low: float,
    confidence_high: float,
    agreement: float,
    n_wallets: int,
    edge_bps: float,
    wallet_signals: list[WalletMarketSignal],
    best_wallet: str,
    timestamp: float,
    is_actionable: bool
)
```

Aggregated signal across multiple wallets for a single market.

    Attributes:
        market_id: Market condition ID.
        signal: Weighted consensus signal in [0.01, 0.99].
        confidence: Consensus confidence [0, 1].
        confidence_low: Lower bound of confidence interval.
        confidence_high: Upper bound of confidence interval.
        agreement: Wallet agreement measure [0, 1].
        n_wallets: Number of contributing wallets.
        edge_bps: Consensus edge vs market price.
        wallet_signals: Individual wallet signals.
        best_wallet: Address of highest-confidence wallet.
        timestamp: Unix timestamp.
        is_actionable: Whether consensus passes thresholds.

### `WalletRegimeChange` (dataclass)
```python
WalletRegimeChange(
    wallet: str,
    market_id: str,
    old_regime: str,
    new_regime: str,
    confidence: float,
    timestamp: float
)
```

Detected regime change for a wallet in a market.

### `compute_wallet_signal(wallet: 'str', market_id: 'str', config: 'TrackerConfig | None' = None, market_price: 'float' = 0.0, positions: 'list[WalletPosition] | None' = None, trades: 'list[Trade] | None' = None, wallet_quality: 'float | None' = None) -> 'WalletMarketSignal'`

Compute a directional signal for one wallet in one market.

    If *positions*, *trades*, or *wallet_quality* are not provided they are
    fetched via the public API.

    Args:
        wallet: Wallet address (0x...).
        market_id: Condition ID of the target market.
        config: Tracker con...

### `compute_consensus(market_id: 'str', config: 'TrackerConfig | None' = None, market_price: 'float' = 0.0) -> 'ConsensusSignal'`

Aggregate wallet signals into a weighted consensus for a market.

    Discovers top holders, scores each, filters by quality, and computes
    a weighted consensus signal.

    Args:
        market_id: Condition ID of the target market.
        config: Tracker configuration.
        market_price: Cu...

### `track_wallet(wallet: 'str', config: 'TrackerConfig | None' = None, market_price_map: 'dict[str, float] | None' = None) -> 'list[WalletMarketSignal]'`

Compute signals for every market a wallet holds a position in.

    Returns a list sorted by ``|signal - 0.5|`` descending (strongest first).

    Args:
        wallet: Wallet address (0x...).
        config: Tracker configuration.
        market_price_map: Optional mapping of market_id -> current p...

### `scan_wallets(market_id: 'str | None' = None, config: 'TrackerConfig | None' = None, market_price: 'float' = 0.0) -> 'ConsensusSignal'`

Auto-discover wallets and compute consensus for a market.

    If no *market_id* is given, uses the first top market from discovery.

    Args:
        market_id: Optional market condition ID.
        config: Tracker configuration.
        market_price: Current market mid price.

    Returns:
      ...

### `wallet_tracker(wallets: 'list[str] | None' = None, config: 'TrackerConfig | None' = None, poll_interval_cycles: 'int | None' = None) -> 'Callable[[Context], None]'`

Create a pipeline function that tracks wallets and injects signals.

    The returned callable maintains per-market state and refreshes signals
    every *poll_interval_cycles* cycles.  Between refreshes it serves
    EMA-smoothed cached values.

    Injected context parameters:
        ``wallet_tra...

## Whale Galaxy

### `RankedWallet` (dataclass)
```python
RankedWallet(
    address: str,
    score: float,
    win_rate: float,
    pnl: float,
    sharpe: float,
    edge_category: str,
    trade_count: int,
    position_count: int,
    last_active: float
)
```

A wallet ranked by composite score with performance metrics.

### `WalletCluster` (dataclass)
```python
WalletCluster(
    wallets: list[str] = list(),
    co_trade_count: int = 0,
    avg_delay_secs: float = 0.0,
    cluster_type: str = 'coincidence',
    shared_markets: list[str] = list()
)
```

A group of wallets that trade in a correlated manner.

### `WhaleAlert` (dataclass)
```python
WhaleAlert(
    wallet: str,
    pseudonym: str,
    market_id: str,
    market_title: str,
    action: str,
    size_usdc: float,
    significance: float,
    timestamp: float
)
```

Alert when a high-scoring wallet makes a significant move.

### `GalaxySnapshot` (dataclass)
```python
GalaxySnapshot(
    top_wallets: list[RankedWallet],
    bottom_wallets: list[RankedWallet],
    clusters: list[WalletCluster],
    alerts: list[WhaleAlert],
    scan_time: float,
    market_count: int,
    wallet_count: int
)
```

Complete snapshot of a galaxy scan.

### `GalaxyConfig` (dataclass)
```python
GalaxyConfig(
    top_n: int = 20,
    min_trades: int = 10,
    cluster_window_secs: float = 3600.0,
    cluster_min_overlap: int = 3,
    alert_min_score: float = 0.3,
    alert_min_size_usdc: float = 500.0
)
```

Configuration for galaxy scans (mutable).

### `scan_galaxy(markets: 'list[Any] | None' = None, top_n: 'int' = 20, min_trades: 'int' = 10, max_markets: 'int' = 50) -> 'GalaxySnapshot'`

Scan the galaxy of Polymarket wallets and rank them.

    Discovers top markets (or uses the provided list), collects unique
    wallet holders, batch-scores them, detects clusters, and generates
    alerts.

    Args:
        markets: Market objects or condition ID strings. Discovers top
          ...

### `detect_clusters(wallet_trades: 'dict[str, list[Trade]]', window_secs: 'float' = 3600.0, min_overlap: 'int' = 3) -> 'list[WalletCluster]'`

Detect clusters of wallets that trade in coordinated patterns.

    For each pair of wallets, finds shared markets.  If the overlap
    meets ``min_overlap``, computes average trade-time delay and
    classifies: <60s "copy_chain", <300s "coordinated", else
    "coincidence".  Returns up to 50 clust...

### `auto_target(snapshot: 'GalaxySnapshot', strategy: 'str' = 'auto') -> 'dict'`

Select target wallets and mode from a galaxy snapshot.

    Strategies:
        "copy": top wallets with score > 0.5.
        "fade": bottom wallets with score < -0.3.
        "auto": picks the stronger set.

    Args:
        snapshot: A GalaxySnapshot from scan_galaxy().
        strategy: One of "...

### `galaxy_tracker(config: 'GalaxyConfig | None' = None, scan_interval_cycles: 'int' = 100) -> 'Callable[[Context], None]'`

Create a pipeline function that periodically scans the whale galaxy.

    Performs a full scan_galaxy() every ``scan_interval_cycles`` cycles.
    Injects ``galaxy_snapshot`` and ``galaxy_alerts`` into ctx.params.

    Args:
        config: Optional GalaxyConfig (uses defaults if None).
        scan...

### `galaxy_hunt(markets: 'list[Any] | None' = None, top_n: 'int' = 10, size_scale: 'float' = 0.5, max_position: 'float' = 1000.0, exchange: 'str' = 'paper', dry_run: 'bool' = False, api_key: 'str | None' = None) -> 'None'`

Scan the galaxy, auto-target, and launch copy/fade trading.

    Blocking function that scans the galaxy for top/bottom wallets,
    auto-selects the best target mode, and launches copy_trades().
    Handles SIGINT/SIGTERM for clean shutdown.

    Args:
        markets: Market objects or condition I...

## Data Collector

### `Collector` (class)
```python
Collector(config)
```

Market data collector: captures orderbooks, trades, and metadata to SQLite.

Members:
- `purge` — method: `purge(self, /, max_age_secs=86400.0)`
- `query_metadata` — method: `query_metadata(self, /, market_id)`
- `query_orderbooks` — method: `query_orderbooks(self, /, market_id, start_ts=0.0, end_ts=Ellipsis, limit=1000)`
- `query_trades` — method: `query_trades(self, /, market_id, start_ts=0.0, end_ts=Ellipsis, limit=1000)`
- `record_orderbook` — method: `record_orderbook(self, /, market_id, exchange, bids_json, asks_json, best_bid, best_ask, mid_price, spread, timestamp)`
- `record_trades` — method: `record_trades(self, /, trades_json, market_id, exchange)`
- `start` — method: `start(self, /)`
- `status` — method: `status(self, /)`
- `stop` — method: `stop(self, /)`

### `CollectorConfig` (class)
```python
CollectorConfig(market_ids, exchange=Ellipsis, orderbook_interval_secs=5.0, trade_poll_interval_secs=10.0, metadata_interval_secs=300.0, max_book_levels=0, db_path=Ellipsis)
```

Configuration for the market data collector.

Members:
- `db_path` — = `<attribute 'db_path' of 'builtins.CollectorConfig' objects>`
- `exchange` — = `<attribute 'exchange' of 'builtins.CollectorConfig' objects>`
- `market_ids` — = `<attribute 'market_ids' of 'builtins.CollectorConfig' objects>`
- `max_book_levels` — = `<attribute 'max_book_levels' of 'builtins.CollectorConfig' objects>`
- `metadata_interval_secs` — = `<attribute 'metadata_interval_secs' of 'builtins.CollectorConfig' objects>`
- `orderbook_interval_secs` — = `<attribute 'orderbook_interval_secs' of 'builtins.CollectorConfig' objects>`
- `trade_poll_interval_secs` — = `<attribute 'trade_poll_interval_secs' of 'builtins.CollectorConfig' objects>`

### `CollectorStatus` (class)
```python
CollectorStatus($self, /, *args, **kwargs)
```

Runtime status of the collector.

Members:
- `db_size_bytes` — = `<attribute 'db_size_bytes' of 'builtins.CollectorStatus' objects>`
- `errors_total` — = `<attribute 'errors_total' of 'builtins.CollectorStatus' objects>`
- `is_running` — = `<attribute 'is_running' of 'builtins.CollectorStatus' objects>`
- `last_error` — = `<attribute 'last_error' of 'builtins.CollectorStatus' objects>`
- `markets_active` — = `<attribute 'markets_active' of 'builtins.CollectorStatus' objects>`
- `metadata_updates_total` — = `<attribute 'metadata_updates_total' of 'builtins.CollectorStatus' objects>`
- `ob_snapshots_total` — = `<attribute 'ob_snapshots_total' of 'builtins.CollectorStatus' objects>`
- `trades_total` — = `<attribute 'trades_total' of 'builtins.CollectorStatus' objects>`
- `uptime_secs` — = `<attribute 'uptime_secs' of 'builtins.CollectorStatus' objects>`

### `DataCollectorConfig` (dataclass)
```python
DataCollectorConfig(
    markets: list[str] = list(),
    exchange: str = 'polymarket',
    orderbook_interval: float = 5.0,
    trade_poll_interval: float = 10.0,
    metadata_interval: float = 300.0,
    max_book_levels: int = 0,
    db_path: str | None = None,
    parquet_dir: str | None = None,
    parquet_export_interval: float = 3600.0,
    retention_hours: float = 0.0
)
```

Full collector configuration (Python side).

    Extends Rust CollectorConfig with Parquet export and retention settings.
- `to_rust_config(self) -> 'CollectorConfig'`

### `collect(config: 'DataCollectorConfig | None' = None, markets: 'list[str] | None' = None, exchange: 'str' = 'polymarket', db_path: 'str | None' = None, duration: 'float' = 0.0) -> 'None'`

Run the collector as a standalone daemon.

    Args:
        config: Full DataCollectorConfig. If provided, other args are ignored.
        markets: List of market IDs / token IDs to collect.
        exchange: Exchange name (``polymarket`` or ``kalshi``).
        db_path: SQLite database path.
     ...

### `collector(feed: 'str', db_path: 'str | None' = None, orderbook_every_n: 'int' = 1) -> 'Callable'`

Pipeline factory that records orderbook snapshots from a feed.

    Usage in hz.run():
        pipeline=[
            collector("poly_btc", orderbook_every_n=5),
            my_strategy,
        ]

    Args:
        feed: Feed name whose orderbook to record (must match a feed in feeds dict).
       ...

### `export_parquet(db_path: 'str', output_dir: 'str', start_ts: 'float' = 0.0, end_ts: 'float' = 0.0, tables: 'list[str] | None' = None) -> 'list[str]'`

Export collector SQLite tables to Parquet files.

    Requires ``pyarrow`` (optional dependency).

    Args:
        db_path: Path to collector SQLite database.
        output_dir: Directory to write Parquet files.
        start_ts: Start timestamp filter (0 = no filter).
        end_ts: End timesta...

### `query_orderbooks(db_path: 'str', market_id: 'str', start_ts: 'float' = 0.0, end_ts: 'float' = 0.0, limit: 'int' = 1000) -> 'list[dict]'`

Query orderbook snapshots from a collector database.

    Args:
        db_path: Path to SQLite database.
        market_id: Market ID to query.
        start_ts: Start timestamp (0 = beginning).
        end_ts: End timestamp (0 = now).
        limit: Max rows to return.

    Returns:
        List o...

### `query_collected_trades(db_path: 'str', market_id: 'str', start_ts: 'float' = 0.0, end_ts: 'float' = 0.0, limit: 'int' = 1000) -> 'list[dict]'`

Query collected trades from a collector database.

    Args:
        db_path: Path to SQLite database.
        market_id: Market ID to query.
        start_ts: Start timestamp (0 = beginning).
        end_ts: End timestamp (0 = now).
        limit: Max rows to return.

    Returns:
        List of t...

## Stealth Execution

### `ImpactEstimate` (dataclass)
```python
ImpactEstimate(
    market_id: str,
    size: float,
    estimated_slippage_bps: float,
    kyle_lambda: float,
    effective_spread_bps: float,
    volatility: float,
    recommended_strategy: str,
    estimated_duration_secs: float
)
```

Pre-trade market impact estimation.

### `SmartRoute` (dataclass)
```python
SmartRoute(
    exchange: str,
    size_fraction: float,
    limit_price: float,
    estimated_fill_prob: float,
    fee_rate: float,
    estimated_cost_bps: float
)
```

Single venue-level routing decision.

### `ExecutionPlan` (dataclass)
```python
ExecutionPlan(
    strategy: str,
    child_orders: list[dict],
    total_size: float,
    estimated_cost_bps: float,
    estimated_duration_secs: float,
    routes: list[SmartRoute]
)
```

Full execution plan returned by :func:`stealth_execute`.

### `StealthConfig` (dataclass)
```python
StealthConfig(
    randomize: bool = True,
    min_delay_secs: float = 0.5,
    max_delay_secs: float = 5.0,
    max_visible_pct: float = 0.1,
    impact_limit_bps: float = 50.0,
    patience_secs: float = 120.0,
    adaptive_aggression: bool = True
)
```

Mutable configuration for stealth execution algorithms.

### `AdaptiveTWAP` (class)
```python
AdaptiveTWAP(engine: 'Engine', duration_secs: 'float', num_slices: 'int', config: 'StealthConfig | None' = None) -> 'None'
```

Time-sliced execution with adaptive pacing and spread filter.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `IcebergPlus` (class)
```python
IcebergPlus(engine: 'Engine', show_size: 'float', config: 'StealthConfig | None' = None) -> 'None'
```

Iceberg with randomised visible size and jittered refill delay.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `SniperAlgo` (class)
```python
SniperAlgo(engine: 'Engine', target_spread: 'float', config: 'StealthConfig | None' = None) -> 'None'
```

Opportunistic single-shot execution on favourable microstructure.

Members:
- `child_order_ids` — property
- `is_complete` — property
- `on_tick` — method: `on_tick(self, current_price: 'float', timestamp: 'float') -> 'None'`
- `start` — method: `start(self, request: 'OrderRequest') -> 'None'`
- `total_filled` — property

### `estimate_impact(engine: 'Engine', market_id: 'str', size: 'float', feed_name: 'str | None' = None) -> 'ImpactEstimate'`

Estimate market impact of executing *size* contracts.

    Uses Kyle's lambda, effective spread, and volatility.  Falls back
    to conservative defaults when live data is unavailable.

### `smart_route(engine: 'Engine', market_id: 'str', side: 'Side', order_side: 'OrderSide', size: 'float', exchanges: 'list[str] | None' = None) -> 'list[SmartRoute]'`

Compute cost-minimising routing plan across venues.

    Estimates fill probability from spread and total cost (half-spread +
    fees).  Greedily allocates to cheapest venue first.

### `stealth_execute(engine: 'Engine', market_id: 'str', side: 'Side', order_side: 'OrderSide', size: 'float', price: 'float', strategy: 'str' = 'auto', config: 'StealthConfig | None' = None, exchanges: 'list[str] | None' = None) -> 'ExecutionPlan'`

Start stealth execution and return the plan.

    If *strategy* is ``"auto"``, :func:`estimate_impact` picks the best
    algorithm.  The algo is started immediately and registered in the
    module-level ``_active_algos`` dict for pipeline ticking.

### `stealth_executor(config: 'StealthConfig | None' = None) -> 'Callable[[Context], None]'`

Pipeline function that drives stealth execution algorithms.

    Reads ``ctx.params["stealth_requests"]`` (list of request dicts),
    starts algos, ticks active ones each cycle, and cleans up completed.
    Injects ``ctx.params["stealth_active_count"]``.

## Sentinel (Risk Monitor)

### `CorrelationAlert` (dataclass)
```python
CorrelationAlert(
    market_a: str,
    market_b: str,
    current_corr: float,
    baseline_corr: float,
    spike_magnitude: float,
    risk_implication: str
)
```

Alert for a correlation spike between two markets.

### `DrawdownLevel` (dataclass)
```python
DrawdownLevel(
    scope: str,
    scope_id: str,
    current_dd: float,
    peak_value: float,
    current_value: float,
    threshold: float,
    action: str,
    triggered: bool
)
```

Drawdown status for a scope (portfolio or single market).

### `HedgeSuggestion` (dataclass)
```python
HedgeSuggestion(
    market_id: str,
    market_title: str,
    side: str,
    order_side: str,
    size: float,
    price: float,
    risk_reduction_pct: float,
    cost_estimate_usdc: float,
    rationale: str
)
```

Actionable hedge recommendation to reduce portfolio risk.

### `RiskBudget` (dataclass)
```python
RiskBudget(
    total_budget: float,
    used_budget: float,
    usage_pct: float,
    regime: str,
    regime_multiplier: float,
    per_market: dict[str, float] = dict()
)
```

Risk budget status with regime-aware adjustments.

### `SentinelReport` (dataclass)
```python
SentinelReport(
    correlation_alerts: list[CorrelationAlert],
    drawdown_levels: list[DrawdownLevel],
    hedges: list[HedgeSuggestion],
    risk_budget: RiskBudget,
    var_95: float,
    cvar_95: float,
    max_position_pct: float,
    regime: str,
    portfolio_value: float,
    timestamp: float
)
```

Comprehensive portfolio risk report.

### `SentinelConfig` (dataclass)
```python
SentinelConfig(
    drawdown_thresholds: list[tuple[float, str]] = <lambda>(),
    correlation_spike_threshold: float = 0.3,
    auto_hedge: bool = False,
    auto_deleverage: bool = True,
    regime_sensitivity: float = 1.0,
    var_confidence: float = 0.95,
    lookback_returns: int = 100,
    risk_budget_total: float = 10000.0
)
```

Configuration for the sentinel risk monitor (mutable).

### `sentinel_report(engine: 'Engine') -> 'SentinelReport'`

Generate a comprehensive portfolio risk report (standalone).

    Combines correlation analysis, drawdown tracking, VaR/CVaR,
    regime detection, risk budgeting, and hedge suggestions.

    Args:
        engine: The Horizon trading engine instance.

    Returns:
        SentinelReport with all ris...

### `suggest_hedges(engine: 'Engine', max_hedges: 'int' = 5, min_reduction_pct: 'float' = 5.0) -> 'list[HedgeSuggestion]'`

Generate hedge suggestions for the current portfolio.

    Analyzes delta exposure and recommends counter-positions ranked
    by risk reduction percentage.

    Args:
        engine: The Horizon trading engine instance.
        max_hedges: Maximum number of suggestions.
        min_reduction_pct: M...

### `sentinel(config: 'SentinelConfig | None' = None, report_interval_cycles: 'int' = 10) -> 'Callable[[Context], None]'`

Create an always-on portfolio sentinel pipeline function.

    Runs every cycle to track drawdowns and returns. Generates a full
    SentinelReport every ``report_interval_cycles`` cycles.

    Injected params:
        ctx.params["sentinel_report"] -> SentinelReport | None

    Auto-deleverage actio...

## Oracle (Forecasting)

### `SignalReading` (dataclass)
```python
SignalReading(
    name: str,
    raw_value: float,
    normalized_value: float,
    weight: float,
    contribution: float
)
```

A single signal's contribution to the ensemble forecast.

    Attributes:
        name: Human-readable signal identifier (e.g. ``"smart_money_flow"``).
        raw_value: Unprocessed output from the signal extractor.
        normalized_value: Value mapped to the [0, 1] range (0.5 = neutral).
        weight: Weight assigned by ``OracleConfig.signal_weights``.
        contribution: ``normalized_value * weight`` -- the signal's share of
            the weighted sum.

### `MarketForecast` (dataclass)
```python
MarketForecast(
    market_id: str,
    market_title: str,
    ensemble_prob: float,
    confidence_low: float,
    confidence_high: float,
    edge_bps: float,
    signals: list[SignalReading],
    market_price: float,
    timestamp: float
)
```

Ensemble probability forecast for a single market.

    Attributes:
        market_id: Condition ID of the market (0x-prefixed hex).
        market_title: Human-readable market question.
        ensemble_prob: Weighted-average probability from all signals, clamped
            to [0.01, 0.99].
        confidence_low: Lower bound of the forecast confidence interval.
        confidence_high: Upper bound of the forecast confidence interval.
        edge_bps: ``(ensemble_prob - market_price) * 10000`` -- positive means
            the market underprices YES.
        signals: Per-signal breakdown.
        market_price: Most recent market mid price at forecast time.
        timestamp: Unix timestamp when the forecast was generated.

### `EdgeOpportunity` (dataclass)
```python
EdgeOpportunity(
    market_id: str,
    market_title: str,
    forecast_prob: float,
    market_price: float,
    edge_bps: float,
    confidence: float,
    direction: str,
    signal_agreement: float,
    recommended_size: float
)
```

An actionable edge detected between ensemble forecast and market price.

    Attributes:
        market_id: Condition ID of the market.
        market_title: Human-readable market question.
        forecast_prob: Ensemble probability.
        market_price: Current market mid price.
        edge_bps: Signed edge in basis points.
        confidence: Forecast confidence (0-1).
        direction: ``"buy_yes"`` when forecast > market, ``"buy_no"`` otherwise.
        signal_agreement: Fraction of signals agreeing with direction.
        recommended_size: Kelly-fraction suggested position size in USDC.

### `OracleReport` (dataclass)
```python
OracleReport(
    forecasts: list[MarketForecast],
    top_edges: list[EdgeOpportunity],
    model_calibration: float,
    coverage: int,
    avg_confidence: float,
    timestamp: float
)
```

Summary report across multiple markets.

    Attributes:
        forecasts: Individual market forecasts.
        top_edges: Filtered and ranked edge opportunities.
        model_calibration: Log-loss of forecast probabilities vs market prices
            (lower is better); ``0.0`` when insufficient data.
        coverage: Number of markets successfully forecast.
        avg_confidence: Mean confidence across all forecasts.
        timestamp: Unix timestamp of report generation.

### `OracleConfig` (dataclass)
```python
OracleConfig(
    signal_weights: dict[str, float] = <lambda>(),
    min_confidence: float = 0.3,
    edge_threshold_bps: float = 200.0,
    recalibrate_interval: int = 50,
    holder_limit: int = 50,
    trade_limit: int = 200
)
```

Tunable knobs for the oracle ensemble.

    This dataclass is intentionally *not* frozen so users can mutate it
    before passing it to the public API.

    Attributes:
        signal_weights: Mapping from signal name to relative weight.  Weights
            are normalized to sum to 1 internally.
        min_confidence: Minimum forecast confidence to surface an edge.
        edge_threshold_bps: Minimum |edge| in basis points for inclusion in
            ``scan_edges`` and ``oracle_report``.
        recalibrate_interval: Reserved for future online recalibration.
        holder_limit: Max holders to fetch per market.
        trade_limit: Max trades to fetch per market.

### `forecast_market(market_id: 'str', market_title: 'str' = '', market_price: 'float' = 0.0, config: 'OracleConfig | None' = None, exchange: 'str' = 'polymarket', include_wallet_signal: 'bool' = False) -> 'MarketForecast'`

Generate an ensemble probability forecast for a single market.

    Runs all six signal extractors, computes a weighted ensemble, and
    returns a :class:`MarketForecast` with per-signal breakdown and
    edge estimate.

    For Kalshi markets, flow-dependent signals (smart money, microstructure,
 ...

### `scan_edges(markets: 'list[dict[str, Any]] | None' = None, min_edge_bps: 'float' = 200.0, max_markets: 'int' = 30, config: 'OracleConfig | None' = None, exchange: 'str' = 'polymarket') -> 'list[EdgeOpportunity]'`

Scan multiple markets and return those with material edge.

    For each market the ensemble forecast is compared with the current
    price.  Markets whose |edge| exceeds *min_edge_bps* are returned,
    ranked by ``|edge| * confidence``.

    Args:
        markets: List of dicts with at least ``"i...

### `oracle(config: 'OracleConfig | None' = None, forecast_interval_cycles: 'int' = 20, exchange: 'str' = 'polymarket') -> 'Callable[[Context], None]'`

Create a pipeline function that forecasts the current market periodically.

    The returned callable maintains per-market state and refreshes the
    ensemble forecast every *forecast_interval_cycles* cycles.  Between
    refreshes it injects the most recent forecast into ``ctx.params``.

    Injec...

### `oracle_report(markets: 'list[dict[str, Any]] | None' = None, max_markets: 'int' = 20, config: 'OracleConfig | None' = None, exchange: 'str' = 'polymarket') -> 'OracleReport'`

Generate a comprehensive oracle report across multiple markets.

    Forecasts each market, computes model calibration via log-loss, and
    surfaces the top edge opportunities.

    Args:
        markets: List of dicts with ``"id"``, ``"title"``, ``"price"``
            keys.  If ``None``, the func...

## LLM Signal

### `NewsItem` (dataclass)
```python
NewsItem(
    title: str,
    summary: str,
    url: str,
    published: float,
    source: str
)
```

A single news item from an RSS feed or NewsAPI.

    Attributes:
        title: Headline text.
        summary: Brief summary or description.
        url: Source URL.
        published: Unix timestamp of publication.
        source: Origin identifier (``"rss"``, ``"newsapi"``, ``"exa"``,
            ``"tavily"``, ``"user"``).

### `LLMForecast` (dataclass)
```python
LLMForecast(
    market_id: str,
    market_title: str,
    llm_prob: float,
    reasoning: str,
    confidence: float,
    edge_bps: float,
    market_price: float,
    model: str,
    news_sources: list[str],
    timestamp: float
)
```

LLM-generated probability forecast for a prediction market.

    Attributes:
        market_id: Market identifier.
        market_title: Human-readable market question.
        llm_prob: LLM-estimated probability, clamped to [0.01, 0.99].
        reasoning: LLM's reasoning text.
        confidence: Self-reported confidence [0, 1].
        edge_bps: ``(llm_prob - market_price) * 10000``.
        market_price: Market mid price at forecast time.
        model: Model identifier used for the forecast.
        news_sources: URLs of news items used.
        timestamp: Unix timestamp of forecast generation.

### `LLMConfig` (dataclass)
```python
LLMConfig(
    provider: str = 'anthropic',
    model: str = '',
    news_sources: list[str] = list(),
    newsapi_query: str = '',
    exa_query: str = '',
    tavily_query: str = '',
    max_news_items: int = 5,
    cache_ttl: float = 300.0,
    rate_limit_per_minute: int = 10,
    max_tokens: int = 1024,
    temperature: float = 0.2
)
```

Configuration for LLM-based forecasting.

    Attributes:
        provider: LLM provider (``"anthropic"``, ``"openai"``, or any
            litellm-supported provider).
        model: Model name. Empty string uses provider default. Accepts
            litellm-qualified strings like ``"openrouter/meta-llama/..."``.
        news_sources: RSS feed URLs to fetch news from.
        newsapi_query: Optional NewsAPI search query.
        exa_query: Optional Exa.ai semantic search query. Env: ``EXA_API_KEY``.
        tavily_query: Optional Tavily real-time search query. Env: ``TAVILY_API_KEY``.
        max_news_items: Max news items to include in prompt.
        cache_ttl: Cache time-to-live in seconds.
        rate_limit_per_minute: Max LLM calls per minute.
        max_tokens: Max response tokens for LLM call.
        temperature: LLM sampling temperature.

### `llm_forecast(market_id: 'str', market_title: 'str', market_price: 'float', news_context: 'list[NewsItem] | None' = None, config: 'LLMConfig | None' = None) -> 'LLMForecast'`

Generate an LLM-based probability forecast for a single market.

    Fetches news, calls the configured LLM provider, and returns a
    :class:`LLMForecast` with probability estimate, reasoning, and edge.

    Args:
        market_id: Market identifier.
        market_title: Human-readable market qu...

### `llm_scan(markets: 'list[dict[str, Any]]', min_edge_bps: 'float' = 200.0, max_markets: 'int' = 20, config: 'LLMConfig | None' = None) -> 'list[LLMForecast]'`

Scan multiple markets for LLM-detected edges.

    Args:
        markets: List of dicts with ``"id"``, ``"title"``, and ``"price"`` keys.
        min_edge_bps: Minimum absolute edge in basis points to include.
        max_markets: Maximum number of markets to scan.
        config: LLM configuration....

### `llm_signal(config: 'LLMConfig | None' = None, forecast_interval_cycles: 'int' = 20) -> 'Callable[[Context], None]'`

Create a pipeline function that forecasts the current market via LLM.

    The returned callable refreshes the LLM forecast every
    *forecast_interval_cycles* cycles and injects it into ``ctx.params``.

    Injected context parameters:
        ``llm_forecast`` -- the :class:`LLMForecast` object.
 ...

## Resolution Analysis

### `ResolutionCondition` (dataclass)
```python
ResolutionCondition(
    description: str,
    source: str,
    verifiable: bool,
    ambiguity_notes: str
)
```

A single resolution condition for a prediction market.

    Attributes:
        description: What needs to happen for resolution.
        source: Authority that determines resolution (e.g., "AP", "official").
        verifiable: Whether the condition is objectively verifiable.
        ambiguity_notes: Notes on potential ambiguity.

### `ResolutionAnalysis` (dataclass)
```python
ResolutionAnalysis(
    market_id: str,
    market_title: str,
    resolution_source: str,
    conditions: list[ResolutionCondition],
    ambiguity_score: float,
    edge_cases: list[str],
    timing_risks: list[str],
    resolution_type: str,
    estimated_resolution_date: str,
    risk_level: str,
    reasoning: str,
    timestamp: float
)
```

Complete resolution analysis for a prediction market.

    Attributes:
        market_id: Market identifier.
        market_title: Human-readable market question.
        resolution_source: Primary resolution authority.
        conditions: List of resolution conditions.
        ambiguity_score: 0.0 (clear) to 1.0 (highly ambiguous).
        edge_cases: Identified edge cases that could complicate resolution.
        timing_risks: Timing-related resolution risks.
        resolution_type: Type of resolution mechanism.
        estimated_resolution_date: Expected resolution date or "unknown".
        risk_level: Overall risk level ("low", "medium", "high").
        reasoning: LLM reasoning for the analysis.
        timestamp: Unix timestamp of analysis generation.

### `ResolutionConfig` (dataclass)
```python
ResolutionConfig(
    provider: str = 'anthropic',
    model: str = '',
    ambiguity_threshold: float = 0.6,
    cache_ttl: float = 3600.0
)
```

Configuration for resolution analysis.

    Attributes:
        provider: LLM provider (``"anthropic"``, ``"openai"``, or any
            litellm-supported provider).
        model: Model name. Empty string uses provider default. Accepts
            litellm-qualified strings like ``"openrouter/meta-llama/..."``.
        ambiguity_threshold: Score above which a market is flagged.
        cache_ttl: Cache time-to-live in seconds (rules rarely change).

### `analyze_resolution(market_id: 'str', market_title: 'str' = '', market_description: 'str' = '', config: 'ResolutionConfig | None' = None, exchange: 'str' = 'polymarket') -> 'ResolutionAnalysis'`

Analyze resolution conditions and risks for a prediction market.

    Fetches market description (if not provided), calls the configured LLM
    to parse resolution criteria, and returns a :class:`ResolutionAnalysis`.

    Args:
        market_id: Market identifier or slug.
        market_title: Opt...

### `batch_analyze(market_ids: 'list[str]', config: 'ResolutionConfig | None' = None, exchange: 'str' = 'polymarket') -> 'list[ResolutionAnalysis]'`

Analyze resolution conditions for multiple markets.

    Args:
        market_ids: List of market identifiers.
        config: Resolution configuration.
        exchange: Exchange to fetch market details from
            (``"polymarket"`` or ``"kalshi"``).

    Returns:
        List of :class:`Resol...

### `resolution_guard(config: 'ResolutionConfig | None' = None, block_above_ambiguity: 'float' = 0.6, analysis_interval_cycles: 'int' = 100) -> 'Callable[[Context], None]'`

Create a pipeline function that blocks quoting on ambiguous markets.

    On first encounter (and every *analysis_interval_cycles*), analyzes the
    market's resolution conditions. If ``ambiguity_score > block_above_ambiguity``,
    injects ``ctx.params["resolution_blocked"] = True`` so downstream ...

### `ResolutionSignal` (dataclass)
```python
ResolutionSignal(
    market_id: str,
    market_title: str,
    resolved: bool,
    confidence: float,
    resolution_side: str,
    evidence: list[str],
    reasoning: str,
    timestamp: float
)
```

Signal indicating a market has potentially resolved.

    Attributes:
        market_id: Market identifier.
        market_title: Human-readable market question.
        resolved: Whether the LLM believes the event has resolved.
        confidence: Confidence in the resolution detection [0, 1].
        resolution_side: Expected resolution side ("yes" or "no").
        evidence: Headlines or facts triggering the detection.
        reasoning: LLM reasoning text.
        timestamp: Unix timestamp of detection.

### `SniperConfig` (dataclass)
```python
SniperConfig(
    provider: str = 'anthropic',
    model: str = '',
    news_sources: list[str] = list(),
    exa_query: str = '',
    tavily_query: str = '',
    confidence_threshold: float = 0.85,
    max_position_size: float = 50.0,
    price_offset: float = 0.02,
    scan_interval_cycles: int = 5,
    cache_ttl: float = 60.0
)
```

Configuration for resolution sniping.

    Attributes:
        provider: LLM provider (``"anthropic"``, ``"openai"``, or any
            litellm-supported provider).
        model: Model name. Empty string uses provider default. Accepts
            litellm-qualified strings like ``"openrouter/meta-llama/..."``.
        news_sources: RSS feed URLs to monitor for resolution events.
        exa_query: Optional Exa.ai semantic search query. Env: ``EXA_API_KEY``.
        tavily_query: Optional Tavily real-time search query. Env: ``TAVILY_API_KEY``.
        confidence_threshold: Minimum confidence to trigger a snipe.
        max_position_size: Maximum position size in USDC.
        price_offset: Offset from 1.0 for aggressive pricing.
        scan_interval_cycles: Cycles between resolution scans.
        cache_ttl: Cache time-to-live in seconds.

### `scan_resolutions(markets: 'list[dict[str, Any]]', config: 'SniperConfig | None' = None) -> 'list[ResolutionSignal]'`

Scan markets for potential resolution events.

    Fetches news and uses LLM to determine if any markets have resolved.

    Args:
        markets: List of dicts with ``"id"`` and ``"title"`` keys.
        config: Sniper configuration.

    Returns:
        List of :class:`ResolutionSignal` for mark...

### `resolution_sniper(config: 'SniperConfig | None' = None) -> 'Callable[[Context], list[Quote] | None]'`

Create a pipeline function that snipes market resolutions.

    Periodically scans news to detect if the current market has resolved.
    When resolution is detected with sufficient confidence, generates an
    aggressive quote to buy the resolving side at near-parity.

    Args:
        config: Sni...

## Stress Testing

### `StressScenario` (dataclass)
```python
StressScenario(
    name: str,
    correlation_override: float | None = None,
    price_shocks: dict[str, float] = dict()
)
```

A stress test scenario definition.

    Args:
        name: Human-readable scenario label.
        correlation_override: If set, overrides the correlation matrix with
            a uniform correlation at this level (e.g. 0.95 for spike).
        price_shocks: Dict mapping market_id -> shocked current_price.
            Markets not in the dict keep their original price.

### `ScenarioResult` (dataclass)
```python
ScenarioResult(
    scenario: StressScenario,
    sim: SimulationResult
)
```

Result of a single stress scenario.

### `StressTestResult` (dataclass)
```python
StressTestResult(
    scenarios: list[ScenarioResult]
)
```

Aggregated stress test results across all scenarios.
- `summary(self) -> 'dict[str, Any]'`

### `stress_test(positions: 'list[SimPosition]', scenarios: 'list[StressScenario] | None' = None, n_simulations: 'int' = 10000, seed: 'int | None' = None) -> 'StressTestResult'`

Run stress tests across multiple scenarios.

    Args:
        positions: Portfolio positions as SimPosition objects.
        scenarios: List of stress scenarios to test.
            Defaults to [CORRELATION_SPIKE, ALL_RESOLVE_NO, LIQUIDITY_SHOCK, TAIL_RISK].
        n_simulations: Monte Carlo simul...

### `CORRELATION_SPIKE` (StressScenario)

### `ALL_RESOLVE_NO` (StressScenario)

### `LIQUIDITY_SHOCK` (StressScenario)

### `TAIL_RISK` (StressScenario)

## Walk-Forward & Optimization

### `walk_forward(data: 'Any', pipeline_factory: 'Callable[[dict], list[Callable]]', param_grid: 'dict[str, list[Any]]', n_splits: 'int' = 5, train_ratio: 'float' = 0.7, expanding: 'bool' = True, objective: 'str' = 'sharpe_ratio', purge_gap: 'float' = 0.0, markets: 'list[str] | None' = None, risk: 'Any' = None, initial_capital: 'float' = 1000.0, **backtest_kwargs: 'Any') -> 'WalkForwardResult'`

Run walk-forward optimization over historical data.

    Args:
        data: Historical data (same formats as hz.backtest).
        pipeline_factory: Function that takes params dict and returns a pipeline.
        param_grid: Dict of parameter names to lists of values for grid search.
        n_spli...

### `WalkForwardResult` (dataclass)
```python
WalkForwardResult(
    windows: list[WalkForwardWindow] = list(),
    best_params_per_window: list[dict[str, Any]] = list(),
    test_results: list[BacktestResult] = list(),
    aggregate_equity: list[tuple[float, float]] = list(),
    aggregate_metrics: Metrics = Metrics()
)
```

Result of walk-forward optimization.

### `WalkForwardWindow` (dataclass)
```python
WalkForwardWindow(
    train_start: float,
    train_end: float,
    test_start: float,
    test_end: float
)
```

A single train/test window in walk-forward optimization.

### `bayesian_optimize(data: 'Any', pipeline_factory: 'Callable[..., list[Callable]]', search_space: 'dict[str, tuple[float, float]]', objective: 'str' = 'sharpe_ratio', n_trials: 'int' = 50, n_initial: 'int' = 10, markets: 'list[str] | None' = None, risk: 'Any' = None, seed: 'int | None' = None, **backtest_kwargs: 'Any') -> 'BayesianOptResult'`

Run Bayesian optimization over strategy parameters.

    The optimizer first evaluates *n_initial* random parameter samples, then
    uses a Gaussian Process surrogate model with Expected Improvement to
    choose the most promising points for the remaining trials.

    Args:
        data: Historica...

### `BayesianOptResult` (dataclass)
```python
BayesianOptResult(
    best_params: dict[str, float] = dict(),
    best_score: float = -inf,
    all_trials: list[dict[str, Any]] = list(),
    n_trials: int = 0,
    convergence: list[float] = list()
)
```

Result of Bayesian optimization.

    Attributes:
        best_params: Parameter dict that achieved the highest objective score.
        best_score: Best objective value found.
        all_trials: List of dicts, each with ``params`` (dict) and ``score`` (float).
        n_trials: Total number of trials evaluated.
        convergence: Best score seen up to and including each trial index.

### `CPCVResult` (dataclass)
```python
CPCVResult(
    oos_sharpes: list[float] = list(),
    pbo: float = 0.0,
    is_overfit: bool = False,
    n_combinations: int = 0
)
```

Result of CPCV analysis.

    Attributes:
        oos_sharpes: Out-of-sample Sharpe ratios for each combination.
        pbo: Probability of Backtest Overfitting (fraction of combos
             where best in-sample underperforms out-of-sample).
        is_overfit: True if PBO > 0.5.
        n_combinations: Total number of combinatorial splits evaluated.

### `cpcv(data: 'list[float]', pipeline_factory: 'Callable[[dict[str, Any]], Callable[[list[float]], float]]', param_grid: 'list[dict[str, Any]]', n_groups: 'int' = 8, purge_gap: 'float' = 0.0, max_combinations: 'int' = 500) -> 'CPCVResult'`

Run Combinatorial Purged Cross-Validation.

    Splits data into n_groups blocks, selects C(n_groups, n_groups/2)
    combinations of train/test splits, grid-searches params on the train
    half, and evaluates the best on the test half.

    Args:
        data: Time series of returns or prices.
   ...

### `probability_of_overfitting(cpcv_result: 'CPCVResult') -> 'float'`

Extract PBO from a CPCV result.

    Args:
        cpcv_result: Result from cpcv().

    Returns:
        Probability of backtest overfitting (0-1).

## Quant Pipeline Functions

### `toxic_flow(feed: 'str', bucket_volume: 'float' = 1000.0, n_buckets: 'int' = 50, threshold: 'float' = 0.7) -> 'Callable[[Context], dict[str, Any]]'`

Create a VPIN toxic flow pipeline function.

    Per-market VpinDetector instances track volume-synchronized order
    imbalance and inject toxicity metrics into the pipeline.

    Args:
        feed: Feed name to read trade data from.
        bucket_volume: Volume per VPIN bucket.
        n_buckets...

### `microstructure(feed: 'str', lookback: 'int' = 100) -> 'Callable[[Context], dict[str, Any]]'`

Create a microstructure analytics pipeline function.

    Per-market OfiTracker and rolling deques for returns/volumes
    compute real-time microstructure metrics.

    Args:
        feed: Feed name to read data from.
        lookback: Rolling window size for returns/volumes.

    Returns:
        ...

### `change_detector(threshold: 'float' = 5.0, drift: 'float' = 0.0) -> 'Callable[[Context], dict[str, Any]]'`

Create a CUSUM change-point detection pipeline function.

    Per-market CusumDetector instances detect structural breaks
    in price series.

    Args:
        threshold: CUSUM threshold for triggering.
        drift: Allowable drift before accumulation.

    Returns:
        Pipeline function: (C...

### `hawkes_intensity(feed_name: 'str | None' = None, mu: 'float' = 0.1, alpha: 'float' = 0.5, beta: 'float' = 1.0, param_name: 'str' = 'hawkes') -> 'Callable[[Context], None]'`

Create a Hawkes self-exciting process pipeline function.

    Per-market HawkesProcess instances track event arrival intensity.
    Events are triggered by fills and large price jumps (>2%).

    Injected params:
        ctx.params[param_name + "_intensity"] -> float: current intensity
        ctx.p...

### `correlation_estimator(feed_names: 'list[str] | None' = None, window: 'int' = 100, param_name: 'str' = 'correlation') -> 'Callable[[Context], None]'`

Create a Ledoit-Wolf shrinkage correlation estimator pipeline function.

    Collects price returns from multiple feeds and computes a shrunk
    covariance matrix using the Ledoit-Wolf estimator.

    Injected params:
        ctx.params[param_name + "_matrix"] -> list[list[float]]: shrunk covarianc...

### `strategy_significance(result: 'Any', n_trials: 'int', alpha: 'float' = 0.05) -> 'dict[str, Any]'`

Test strategy significance using Deflated Sharpe Ratio.

    Extracts Sharpe/skew/kurtosis from an equity curve or backtest result
    and tests whether the performance is statistically significant.

    Args:
        result: Object with ``equity_curve`` (list[float]) or ``sharpe`` attribute,
      ...

### `signal_diagnostics(predictions: 'list[float]', outcomes: 'list[float]') -> 'dict[str, float]'`

Compute signal quality diagnostics.

    Args:
        predictions: Model predictions.
        outcomes: Actual outcomes.

    Returns:
        dict with: ic, half_life, hurst

### `market_efficiency(prices: 'list[float]') -> 'dict[str, Any]'`

Assess market efficiency from a price series.

    Args:
        prices: Time series of prices.

    Returns:
        dict with: variance_ratio, hurst, is_efficient

## Calendar Events

### `time_decay(calendar_feed: 'str' = 'calendar', max_days: 'float' = 30.0, decay_type: 'str' = 'linear') -> 'Callable'`

Apply time decay sizing based on distance to next event.

    Reduces position size as events approach (risk management).

### `event_countdown(calendar_feed: 'str' = 'calendar') -> 'Callable'`

Expose event countdown data for downstream pipeline use.

### `pre_event_strategy(calendar_feed: 'str' = 'calendar', reduce_hours: 'float' = 24.0, reduce_factor: 'float' = 0.5) -> 'Callable'`

Reduce exposure before major events.

### `bundled_events_json() -> 'str'`

Get bundled FOMC + CPI events as JSON string.

### `FOMC_DATES` = `['2024-01-31', '2024-03-20', '2024-05-01', '2024-06-12', '2024-07-31', '2024-09-18', '2024-11-07', '...`

### `CPI_DATES` = `['2025-01-15', '2025-02-12', '2025-03-12', '2025-04-10', '2025-05-13', '2025-06-11', '2025-07-11', '...`

## Cross-Market Hedging

### `cross_hedger(correlations: 'dict[tuple[str, str], float] | None' = None, max_delta: 'float' = 50.0, hedge_size: 'float' = 5.0, hedge_spread: 'float' = 0.02, event_correlated: 'bool' = True) -> 'Callable[[Context, list[Quote] | None], list[Quote]]'`

Create a cross-market hedging modifier.

    Monitors portfolio delta and appends hedge quotes when exposure
    exceeds ``max_delta``.

    Correlation resolution (priority):
    1. Static: ``correlations`` dict (key or reversed key).
    2. Event-based: outcomes in same ``ctx.event`` → -1.0.
    3...

## Rewards

### `RewardConfig` (class)
```python
RewardConfig($self, /, *args, **kwargs)
```

Reward rate configuration for a single market.

Members:
- `max_spread` — = `<attribute 'max_spread' of 'builtins.RewardConfig' objects>`
- `min_size` — = `<attribute 'min_size' of 'builtins.RewardConfig' objects>`
- `rates` — = `<attribute 'rates' of 'builtins.RewardConfig' objects>`

### `RewardMarket` (class)
```python
RewardMarket($self, /, *args, **kwargs)
```

A market that is eligible for liquidity rewards.

Members:
- `condition_id` — = `<attribute 'condition_id' of 'builtins.RewardMarket' objects>`
- `market_id` — = `<attribute 'market_id' of 'builtins.RewardMarket' objects>`
- `question` — = `<attribute 'question' of 'builtins.RewardMarket' objects>`
- `rewards` — = `<attribute 'rewards' of 'builtins.RewardMarket' objects>`

### `fetch_reward_markets()`

Fetch Polymarket reward-eligible markets.

GET https://clob.polymarket.com/sampling-simplified-markets (unauthenticated)

### `EpochRewards` (dataclass)
```python
EpochRewards(
    market_id: str = '',
    fills_scored: int = 0,
    estimated_usdc: float = 0.0,
    total_notional: float = 0.0
)
```

Per-market reward accumulator for one epoch.
- `as_dict(self) -> 'dict[str, Any]'`

### `RewardsTracker` (class)
```python
RewardsTracker(rebate_rate: 'float' = 0.0002, check_scoring: 'bool' = False) -> 'None'
```

Tracks maker fills and estimates liquidity rebates.

    Args:
        rebate_rate: Rebate rate as fraction of notional (default 0.0002 = 2bps).
        check_scoring: If True, calls engine.check_order_scoring() per fill.

Members:
- `epoch_rewards` — property
- `record_fill` — method: `record_fill(self, market_id: 'str', fill_id: 'str', notional: 'float', is_maker: 'bool' = True, scoring: 'bool' = True) -> 'float'`
- `reset_epoch` — method: `reset_epoch(self) -> 'dict[str, EpochRewards]'`
- `total_usdc` — property

### `rewards_tracker(rebate_rate: 'float' = 0.0002, check_scoring: 'bool' = False) -> 'Callable[[Context], dict[str, Any]]'`

Create a rewards tracker pipeline function.

    Monitors fills from the engine, estimates rebates, and injects
    reward metrics into the pipeline output.

    Args:
        rebate_rate: Rebate rate as fraction of notional (default 2bps).
        check_scoring: If True, check order scoring via Pol...

## Hot Reload

### `ParamReloader` (class)
```python
ParamReloader(path: 'str', poll_interval: 'float' = 1.0) -> 'None'
```

Watches a JSON file for parameter changes using file mtime polling.

    Thread-safe: ``check()`` and ``current()`` can be called from any thread.

    The JSON file must contain a flat object with string keys and numeric
    values, e.g.::

        {"spread": 0.05, "size": 10.0, "threshold": 0.3}

    Non-float values are silently skipped with a warning.

Members:
- `check` — method: `check(self) -> 'dict[str, float] | None'`
- `current` — method: `current(self) -> 'dict[str, float]'`

### `hot_reload(source: 'str | ParamReloader | dict' = 'params.json', prefix: 'str' = '', on_change: 'Callable[[dict[str, float], dict[str, float]], Any] | None' = None) -> 'Callable'`

Pipeline function that injects hot-reloaded parameters into the context.

    Drop this into your ``hz.run()`` pipeline to enable live parameter
    tuning without restarting::

        hz.run(
            ...,
            pipeline=[hot_reload("my_params.json"), my_strategy],
        )

    Args:
  ...

### `write_params(path: 'str', params: 'dict[str, float]') -> 'None'`

Write parameters to a JSON file atomically.

    Uses a temporary file + rename to avoid partial reads by a concurrent
    ``ParamReloader``.

    Args:
        path: File path to write to.
        params: Flat dict of string keys to float values.

## Lifecycle

### `register_expiry(engine, market_id: 'str', expiry: 'str | float | None') -> 'bool'`

Register a market's expiry time with the engine.

    Accepts ISO 8601 string, Unix timestamp float, or None (no-op).
    Returns True if successfully registered.

### `register_market_expiries(engine, markets) -> 'int'`

Register expiries for a list of Market objects.

    Reads the `expiry` field from each Market. Returns count registered.

### `check_lifecycle(engine) -> 'list[str]'`

Run lifecycle check and return list of market IDs acted upon.

    Wraps engine.check_lifecycle() with logging.

### `time_to_expiry(engine, market_id: 'str') -> 'float | None'`

Seconds until market expires. None if no expiry registered.

### `approaching_expiry(engine, market_id: 'str', lead_secs: 'float' = 300.0) -> 'bool'`

Check if a market is within lead_secs of expiry.

## Auth

### `signup(email: 'str', password: 'str', name: 'str' = '') -> 'dict'`

Create a Horizon account via Supabase Auth.

    Returns ``{"status": "ok", "access_token": ..., ...}`` on success.
    If ``session`` is ``None``, email confirmation is required.
    Returns ``{"error": "..."}`` on failure.

### `login(email: 'str', password: 'str') -> 'dict'`

Log into an existing Horizon account.

    Returns ``{"status": "ok", "access_token": ..., ...}`` on success.
    Returns ``{"error": "..."}`` on failure.

### `generate_sdk_key() -> 'str'`

Generate an SDK key: ``hz_sdk_`` + 64 random hex chars.

### `hash_api_key(key: 'str') -> 'str'`

SHA-256 hash of an API key (same algorithm as the deploy platform).

### `create_sdk_key(access_token: 'str', name: 'str' = 'default') -> 'dict'`

Generate an SDK key and insert it into the Supabase ``sdk_keys`` table.

    Returns ``{"key": "hz_sdk_...", "prefix": "hz_sdk_abcdef1"}`` on success.
    The full key is returned here but should NOT be forwarded to tool responses.

### `save_credentials(api_key: 'str') -> 'str'`

Save an SDK key to ``~/.horizon/credentials.json`` (encrypted).

    Returns the path where the credentials were saved.

### `load_credentials() -> 'str | None'`

Load the saved SDK key from ``~/.horizon/credentials.json``.

    Supports both v2 (encrypted) and v1 (plaintext, legacy) formats.
    Returns the key string, or ``None`` if not found or decryption fails.

### `resolve_password(password: 'str | None' = None) -> 'str | None'`

Resolve password from argument or HORIZON_PASSWORD env var.

    Prefers the env var to avoid password exposure in CLI args and logs.
    Returns None if no password is available.

### `auth_setup(email: 'str', password: 'str', name: 'str' = '') -> 'dict'`

Full agentic auth flow: signup/login, generate key, save locally.

    1. Try login first (existing user).
    2. If login fails, try signup.
    3. If email confirmation is needed, return status.
    4. Otherwise generate SDK key, save to disk.

    Returns only the key prefix in the response (neve...

### `current_tier()`

### `require_pro()`

### `require_ultra()`

## Other Exports

- `__version__` (constant_str)
