> ## Documentation Index
> Fetch the complete documentation index at: https://mathematicalcompany.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Stock Hedge Strategy

> Complete example: hedging a Fed rate prediction with TLT bond ETF.

<Warning>
  **Ultra Feature.** Requires an Ultra subscription. [Get started at api.mathematicalcompany.com](https://api.mathematicalcompany.com)
</Warning>

Market-make "Will the Fed cut rates in 2026?" on Polymarket while hedging with TLT (iShares 20+ Year Treasury Bond ETF) on Alpaca. If rates are cut, bond prices rise, so the TLT position offsets losses on the prediction market side.

## Full Code

```python theme={null}
"""Hedged prediction market strategy: Fed rate cut + TLT bond hedge."""

import horizon as hz


# 1. Define markets
fed_market = hz.Market(id="will-fed-cut-rates-2026", name="Fed Rate Cut 2026")

# 2. Configure exchanges
polymarket = hz.Polymarket()                # prediction market
alpaca = hz.Alpaca(paper=True)              # stock hedge (paper)

# 3. Configure feeds
feeds = {
    "fed_rate": hz.PolymarketBook("will-fed-cut-rates-2026"),
    "tlt": hz.AlpacaFeed(symbols=["TLT"]),
}

# 4. Hedge configuration
hedge_config = hz.HedgeConfig(
    prediction_feed="fed_rate",
    stock_feed="tlt",
    stock_symbol="TLT",
    window=60,
    rebalance_threshold=0.05,      # rebalance when ratio drifts > 5%
    max_hedge_notional=50_000.0,   # cap hedge size
    auto_rebalance=False,          # manual mode (set True to auto-trade)
)


# 5. Strategy pipeline
def my_strategy(ctx):
    """Simple MM strategy on the prediction market."""
    if ctx.feeds.get("fed_rate") is None:
        return []

    fair = ctx.feeds["fed_rate"].price
    if fair <= 0:
        return []

    return hz.quotes(fair=fair, spread=0.04, size=10)


# 6. Run
hz.run(
    name="fed_rate_hedged",
    exchange=[polymarket, alpaca],
    markets=[fed_market],
    feeds=feeds,
    pipeline=[
        hz.stock_hedge(hedge_config),  # monitor + flag rebalancing
        my_strategy,
    ],
    risk=hz.Risk(max_position=100, max_drawdown_pct=5),
    interval=1.0,
    mode="paper",
)
```

## How It Works

1. **Two exchanges**: Polymarket for prediction market orders, Alpaca for stock hedge orders
2. **Two feeds**: `PolymarketBook` streams Yes/No prices, `AlpacaFeed` streams TLT quotes
3. **`stock_hedge()`** runs each cycle:

* Computes the rolling hedge ratio between the prediction market and TLT
* Tracks effectiveness, basis risk, and correlation
* Flags rebalancing when the ratio drifts past the 5% threshold
* With `auto_rebalance=True`, sends Alpaca orders to adjust the hedge

4. **`my_strategy()`** quotes the prediction market around the live fair value

## Pre-Trade Analysis

Before going live, check the hedge relationship:

```python theme={null}
import horizon as hz

# Historical data (you'd fetch these from your data source)
fed_prices = [0.55, 0.56, 0.57, 0.58, 0.57, 0.59, 0.60, 0.61, 0.62]
tlt_prices = [95.0, 95.5, 96.0, 96.5, 96.2, 97.0, 97.5, 98.0, 98.5]

# One-shot report
report = hz.compute_hedge_report(fed_prices, tlt_prices, window=8)
print(f"Hedge ratio: {report['hedge_ratio']:.4f}")
print(f"Effectiveness: {report['hedge_effectiveness']:.4f}")
print(f"Tracking error: {report['sensitivities']['tracking_error']:.4f}")

# Scenario analysis
scenarios = hz.run_scenario(
    spot_position=1000,      # 1000 contracts on Polymarket
    spot_price=0.60,         # current YES price
    hedge_position=-50,      # short 50 shares TLT
    hedge_price=96.0,        # current TLT price
    spot_moves=[-0.20, -0.10, -0.05, 0.0, 0.05, 0.10, 0.20],
    correlation=0.75,
)

print("\nScenario Analysis:")
for s in scenarios:
    print(f"  Spot {s['spot_move_pct']:+.0%}: "
          f"Portfolio ${s['portfolio_pnl']:+.2f}, "
          f"Unhedged ${s['unhedged_pnl']:+.2f}, "
          f"Benefit ${s['hedge_benefit']:+.2f}")
```

## Run It

```bash theme={null}
# Paper mode
python examples/stock_hedge_strategy.py

# Live mode with dashboard
python -m horizon run examples/stock_hedge_strategy.py --mode=live --dashboard

# Auto-rebalance mode (set auto_rebalance=True in config)
python examples/stock_hedge_strategy.py --mode=live
```

## Extending

### Multi-Ticker Hedge

Hedge with multiple instruments instead of just one:

```python theme={null}
import horizon as hz

result = hz.multi_ticker_hedge(
    spot_returns=fed_returns,
    hedge_returns_matrix=[tlt_returns, spy_returns, gld_returns],
    tickers=["TLT", "SPY", "GLD"],
)

print(f"Optimal weights: {dict(zip(result.tickers, result.weights))}")
print(f"Hedge effectiveness: {result.hedge_effectiveness:.4f}")
```

### Signal-Driven Fair Value

Use a signal combiner instead of raw mid-price:

```python theme={null}
combiner = hz.signal_combiner([
    hz.price_signal("fed_rate", weight=0.5),
    hz.momentum_signal("fed_rate", lookback=20, weight=0.3),
    hz.spread_signal("fed_rate", weight=0.2),
], smoothing=10)

hz.run(
    name="signal_hedged_mm",
    exchange=[hz.Polymarket(), hz.Alpaca(paper=True)],
    feeds={
        "fed_rate": hz.PolymarketBook("will-fed-cut-rates-2026"),
        "tlt": hz.AlpacaFeed(symbols=["TLT"]),
    },
    pipeline=[
        hz.stock_hedge(hedge_config),
        combiner,
        quoter,
    ],
)
```

### Cross-Exchange Hedge

Hedge a Kalshi position instead of Polymarket:

```python theme={null}
hz.run(
    name="kalshi_hedged",
    exchange=[hz.Kalshi(api_key="..."), hz.Alpaca(paper=True)],
    feeds={
        "fed_rate": hz.KalshiBook("KXFEDRATE-26"),
        "tlt": hz.AlpacaFeed(symbols=["TLT"]),
    },
    pipeline=[
        hz.stock_hedge(hz.HedgeConfig(
            prediction_feed="fed_rate",
            stock_feed="tlt",
            stock_symbol="TLT",
            auto_rebalance=True,
        )),
        my_strategy,
    ],
)
```

See [Stock Market Hedging](/stock-hedging) for the full API reference and [Horizon + Alpaca](/exchanges/alpaca) for exchange setup.
