From 47471b770035598ce3546530b8bc8cb24cb7ecfc Mon Sep 17 00:00:00 2001 From: Tim Olson Date: Tue, 28 Apr 2026 15:05:15 -0400 Subject: [PATCH] Expand model tag support: add GLM-5.1, simplify Anthropic IDs, scan tags anywhere in message - Flink update_bars debouncing - update_bars subscription idempotency bugfix - Price decimal correction bugfix of previous commit - Add GLM-5.1 model tag alongside renamed GLM-5 - Use short Anthropic model IDs (sonnet/haiku/opus) instead of full version strings - Allow @tags anywhere in message content, not just at start - Return hasOtherContent flag instead of trimmed rest string - Only trigger greeting stream when tag has no other content - Update workspace knowledge base references to platform/workspace and platform/shapes - Hierarchical knowledge base catalog - 151 Trading Strategies knowledge base articles - Shapes knowledge base article - MutateShapes tool instead of workspace patch --- doc/plan.md | 7 +- .../com/dexorder/flink/TradingFlinkApp.java | 2 +- .../flink/publisher/RealtimeBarFunction.java | 71 ++++- .../{indicators => }/indicator-development.md | 10 +- gateway/knowledge/platform/index.md | 4 + gateway/knowledge/platform/shapes.md | 131 ++++++++ gateway/knowledge/platform/workspace.md | 17 +- .../{strategies => }/strategy-development.md | 14 +- gateway/knowledge/trading/index.md | 4 + .../knowledge/trading/signal-combination.md | 121 +++++++ .../strategies/cash/liquidity-management.md | 51 +++ .../trading/strategies/cash/loan-sharking.md | 49 +++ .../cash/money-laundering-dark-side.md | 42 +++ .../trading/strategies/cash/pawnbroking.md | 51 +++ .../knowledge/trading/strategies/cash/repo.md | 53 +++ .../commodities/hedging-pressure.md | 56 ++++ .../commodities/portfolio-diversification.md | 46 +++ .../strategies/commodities/pricing-models.md | 69 ++++ .../strategies/commodities/roll-yields.md | 51 +++ .../commodities/skewness-premium.md | 55 ++++ .../trading/strategies/commodities/value.md | 52 +++ .../convertibles/convertible-arbitrage.md | 44 +++ .../convertibles/convertible-oas.md | 46 +++ .../trading/strategies/crypto/ann-strategy.md | 175 ++++++++++ .../crypto/sentiment-naive-bayes.md | 128 ++++++++ .../active-distressed-investing.md | 50 +++ .../buy-and-hold-distressed-debt.md | 44 +++ .../distressed-assets/distress-risk-puzzle.md | 58 ++++ .../trading/strategies/etfs/alpha-rotation.md | 46 +++ .../trading/strategies/etfs/leveraged-etfs.md | 49 +++ .../trading/strategies/etfs/mean-reversion.md | 57 ++++ .../etfs/multi-asset-trend-following.md | 70 ++++ .../trading/strategies/etfs/r-squared.md | 63 ++++ .../etfs/sector-momentum-rotation.md | 74 +++++ .../strategies/fixed-income/barbells.md | 50 +++ .../fixed-income/bond-immunization.md | 66 ++++ .../strategies/fixed-income/bullets.md | 36 +++ .../strategies/fixed-income/carry-factor.md | 56 ++++ .../fixed-income/cds-basis-arbitrage.md | 55 ++++ .../dollar-duration-neutral-butterfly.md | 44 +++ .../fixed-income/fifty-fifty-butterfly.md | 46 +++ .../strategies/fixed-income/generalities.md | 100 ++++++ .../strategies/fixed-income/ladders.md | 43 +++ .../fixed-income/low-risk-factor.md | 44 +++ .../regression-weighted-butterfly.md | 53 +++ .../fixed-income/rolling-down-yield-curve.md | 52 +++ .../fixed-income/swap-spread-arbitrage.md | 59 ++++ .../strategies/fixed-income/value-factor.md | 66 ++++ .../fixed-income/yield-curve-spread.md | 56 ++++ .../strategies/futures/calendar-spread.md | 48 +++ .../strategies/futures/contrarian-trading.md | 79 +++++ .../strategies/futures/hedging-risk.md | 80 +++++ .../strategies/futures/trend-following.md | 83 +++++ .../trading/strategies/fx/carry-trade.md | 74 +++++ .../strategies/fx/dollar-carry-trade.md | 45 +++ .../strategies/fx/momentum-carry-combo.md | 57 ++++ .../fx/moving-averages-hp-filter.md | 51 +++ .../strategies/fx/triangular-arbitrage.md | 52 +++ .../global-macro/economic-announcements.md | 62 ++++ .../fundamental-macro-momentum.md | 59 ++++ .../global-macro/global-fixed-income.md | 63 ++++ .../global-macro/inflation-hedge.md | 77 +++++ gateway/knowledge/trading/strategies/index.md | 301 ++++++++++++++++++ .../indexes/cash-and-carry-arbitrage.md | 60 ++++ .../strategies/indexes/dispersion-trading.md | 79 +++++ .../strategies/indexes/generalities.md | 35 ++ .../indexes/intraday-etf-arbitrage.md | 49 +++ .../indexes/volatility-targeting.md | 58 ++++ .../infrastructure/infrastructure-overview.md | 80 +++++ .../miscellaneous/energy-spark-spread.md | 61 ++++ .../miscellaneous/inflation-hedging-swaps.md | 56 ++++ .../miscellaneous/tips-treasury-arbitrage.md | 65 ++++ .../miscellaneous/weather-risk-hedging.md | 70 ++++ .../strategies/options/bear-call-ladder.md | 34 ++ .../strategies/options/bear-call-spread.md | 32 ++ .../strategies/options/bear-put-ladder.md | 34 ++ .../strategies/options/bear-put-spread.md | 32 ++ .../options/bearish-long-seagull-spread.md | 38 +++ .../options/bearish-short-seagull-spread.md | 38 +++ .../strategies/options/bull-call-ladder.md | 34 ++ .../strategies/options/bull-call-spread.md | 32 ++ .../strategies/options/bull-put-ladder.md | 34 ++ .../strategies/options/bull-put-spread.md | 32 ++ .../options/bullish-long-seagull-spread.md | 38 +++ .../options/bullish-short-seagull-spread.md | 38 +++ .../options/calendar-call-spread.md | 33 ++ .../strategies/options/calendar-put-spread.md | 33 ++ .../options/call-ratio-backspread.md | 33 ++ .../trading/strategies/options/collar.md | 33 ++ .../strategies/options/covered-call.md | 32 ++ .../trading/strategies/options/covered-put.md | 32 ++ .../options/covered-short-straddle.md | 33 ++ .../options/covered-short-strangle.md | 32 ++ .../options/diagonal-call-spread.md | 33 ++ .../strategies/options/diagonal-put-spread.md | 33 ++ .../trading/strategies/options/long-box.md | 34 ++ .../strategies/options/long-call-butterfly.md | 46 +++ .../strategies/options/long-call-condor.md | 36 +++ .../options/long-call-synthetic-straddle.md | 34 ++ .../trading/strategies/options/long-combo.md | 36 +++ .../trading/strategies/options/long-guts.md | 33 ++ .../strategies/options/long-iron-butterfly.md | 36 +++ .../strategies/options/long-iron-condor.md | 36 +++ .../strategies/options/long-put-butterfly.md | 46 +++ .../strategies/options/long-put-condor.md | 36 +++ .../options/long-put-synthetic-straddle.md | 34 ++ .../strategies/options/long-straddle.md | 33 ++ .../strategies/options/long-strangle.md | 33 ++ .../options/long-synthetic-forward.md | 32 ++ .../strategies/options/protective-call.md | 32 ++ .../strategies/options/protective-put.md | 32 ++ .../options/put-ratio-backspread.md | 33 ++ .../strategies/options/ratio-call-spread.md | 33 ++ .../strategies/options/ratio-put-spread.md | 33 ++ .../options/short-call-butterfly.md | 35 ++ .../strategies/options/short-call-condor.md | 36 +++ .../options/short-call-synthetic-straddle.md | 33 ++ .../trading/strategies/options/short-combo.md | 36 +++ .../trading/strategies/options/short-guts.md | 33 ++ .../options/short-iron-butterfly.md | 36 +++ .../strategies/options/short-iron-condor.md | 36 +++ .../strategies/options/short-put-butterfly.md | 35 ++ .../strategies/options/short-put-condor.md | 36 +++ .../options/short-put-synthetic-straddle.md | 33 ++ .../strategies/options/short-straddle.md | 33 ++ .../strategies/options/short-strangle.md | 33 ++ .../options/short-synthetic-forward.md | 32 ++ .../trading/strategies/options/strap.md | 33 ++ .../trading/strategies/options/strip.md | 33 ++ .../strategies/real-estate/fix-and-flip.md | 54 ++++ .../real-estate/inflation-hedging.md | 53 +++ .../intra-asset-diversification.md | 40 +++ .../mixed-asset-diversification.md | 47 +++ .../real-estate/momentum-regional.md | 42 +++ .../trading/strategies/stocks/alpha-combos.md | 74 +++++ .../trading/strategies/stocks/channel.md | 60 ++++ .../strategies/stocks/earnings-momentum.md | 46 +++ .../strategies/stocks/event-driven-ma.md | 50 +++ .../strategies/stocks/implied-volatility.md | 45 +++ .../stocks/low-volatility-anomaly.md | 42 +++ .../strategies/stocks/market-making.md | 54 ++++ .../stocks/mean-reversion-cluster.md | 97 ++++++ .../mean-reversion-weighted-regression.md | 60 ++++ .../trading/strategies/stocks/ml-knn.md | 85 +++++ .../stocks/multifactor-portfolio.md | 68 ++++ .../strategies/stocks/pairs-trading.md | 61 ++++ .../strategies/stocks/price-momentum.md | 66 ++++ .../strategies/stocks/residual-momentum.md | 68 ++++ .../stocks/single-moving-average.md | 57 ++++ .../statistical-arbitrage-optimization.md | 79 +++++ .../stocks/support-and-resistance.md | 60 ++++ .../stocks/three-moving-averages.md | 51 +++ .../strategies/stocks/two-moving-averages.md | 57 ++++ .../trading/strategies/stocks/value.md | 44 +++ .../structured-assets/carry-cds-hedging.md | 54 ++++ .../structured-assets/carry-equity-tranche.md | 52 +++ .../carry-senior-mezzanine.md | 49 +++ .../carry-tranche-hedging.md | 52 +++ .../structured-assets/cdo-curve-trades.md | 62 ++++ .../structured-assets/cdo-generalities.md | 92 ++++++ .../structured-assets/mbs-trading.md | 60 ++++ .../cross-border-tax-arbitrage.md | 73 +++++ .../tax-arbitrage/muni-bond-tax-arbitrage.md | 50 +++ .../strategies/volatility/generalities.md | 48 +++ .../strategies/volatility/variance-swaps.md | 68 ++++ .../volatility/vix-futures-basis-trading.md | 64 ++++ .../strategies/volatility/volatility-carry.md | 68 ++++ .../volatility/volatility-risk-premium.md | 63 ++++ .../volatility-skew-risk-reversal.md | 53 +++ gateway/prompt/agent-main.md | 20 ++ gateway/prompt/index.md | 4 +- gateway/prompt/tools.md | 5 +- gateway/src/channels/websocket-handler.ts | 58 ++-- gateway/src/clients/zmq-relay-client.ts | 53 +-- gateway/src/harness/spawn/wiki-loader.ts | 91 +++++- gateway/src/llm/model-tags.ts | 35 +- gateway/src/main.ts | 2 +- gateway/src/services/ohlc-service.ts | 48 +-- gateway/src/tools/mcp/mcp-tool-wrapper.ts | 13 + gateway/src/tools/platform/index.ts | 5 + .../src/tools/platform/shapes-mutate.tool.ts | 106 ++++++ gateway/src/tools/tool-registry.ts | 12 + web/src/components/ChatPanel.vue | 8 +- web/src/composables/useTradingViewDatafeed.ts | 32 +- 184 files changed, 9044 insertions(+), 170 deletions(-) rename gateway/knowledge/{indicators => }/indicator-development.md (90%) create mode 100644 gateway/knowledge/platform/index.md create mode 100644 gateway/knowledge/platform/shapes.md rename gateway/knowledge/{strategies => }/strategy-development.md (90%) create mode 100644 gateway/knowledge/trading/index.md create mode 100644 gateway/knowledge/trading/signal-combination.md create mode 100644 gateway/knowledge/trading/strategies/cash/liquidity-management.md create mode 100644 gateway/knowledge/trading/strategies/cash/loan-sharking.md create mode 100644 gateway/knowledge/trading/strategies/cash/money-laundering-dark-side.md create mode 100644 gateway/knowledge/trading/strategies/cash/pawnbroking.md create mode 100644 gateway/knowledge/trading/strategies/cash/repo.md create mode 100644 gateway/knowledge/trading/strategies/commodities/hedging-pressure.md create mode 100644 gateway/knowledge/trading/strategies/commodities/portfolio-diversification.md create mode 100644 gateway/knowledge/trading/strategies/commodities/pricing-models.md create mode 100644 gateway/knowledge/trading/strategies/commodities/roll-yields.md create mode 100644 gateway/knowledge/trading/strategies/commodities/skewness-premium.md create mode 100644 gateway/knowledge/trading/strategies/commodities/value.md create mode 100644 gateway/knowledge/trading/strategies/convertibles/convertible-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/convertibles/convertible-oas.md create mode 100644 gateway/knowledge/trading/strategies/crypto/ann-strategy.md create mode 100644 gateway/knowledge/trading/strategies/crypto/sentiment-naive-bayes.md create mode 100644 gateway/knowledge/trading/strategies/distressed-assets/active-distressed-investing.md create mode 100644 gateway/knowledge/trading/strategies/distressed-assets/buy-and-hold-distressed-debt.md create mode 100644 gateway/knowledge/trading/strategies/distressed-assets/distress-risk-puzzle.md create mode 100644 gateway/knowledge/trading/strategies/etfs/alpha-rotation.md create mode 100644 gateway/knowledge/trading/strategies/etfs/leveraged-etfs.md create mode 100644 gateway/knowledge/trading/strategies/etfs/mean-reversion.md create mode 100644 gateway/knowledge/trading/strategies/etfs/multi-asset-trend-following.md create mode 100644 gateway/knowledge/trading/strategies/etfs/r-squared.md create mode 100644 gateway/knowledge/trading/strategies/etfs/sector-momentum-rotation.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/barbells.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/bond-immunization.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/bullets.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/carry-factor.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/cds-basis-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/dollar-duration-neutral-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/fifty-fifty-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/generalities.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/ladders.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/low-risk-factor.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/regression-weighted-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/rolling-down-yield-curve.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/swap-spread-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/value-factor.md create mode 100644 gateway/knowledge/trading/strategies/fixed-income/yield-curve-spread.md create mode 100644 gateway/knowledge/trading/strategies/futures/calendar-spread.md create mode 100644 gateway/knowledge/trading/strategies/futures/contrarian-trading.md create mode 100644 gateway/knowledge/trading/strategies/futures/hedging-risk.md create mode 100644 gateway/knowledge/trading/strategies/futures/trend-following.md create mode 100644 gateway/knowledge/trading/strategies/fx/carry-trade.md create mode 100644 gateway/knowledge/trading/strategies/fx/dollar-carry-trade.md create mode 100644 gateway/knowledge/trading/strategies/fx/momentum-carry-combo.md create mode 100644 gateway/knowledge/trading/strategies/fx/moving-averages-hp-filter.md create mode 100644 gateway/knowledge/trading/strategies/fx/triangular-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/global-macro/economic-announcements.md create mode 100644 gateway/knowledge/trading/strategies/global-macro/fundamental-macro-momentum.md create mode 100644 gateway/knowledge/trading/strategies/global-macro/global-fixed-income.md create mode 100644 gateway/knowledge/trading/strategies/global-macro/inflation-hedge.md create mode 100644 gateway/knowledge/trading/strategies/index.md create mode 100644 gateway/knowledge/trading/strategies/indexes/cash-and-carry-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/indexes/dispersion-trading.md create mode 100644 gateway/knowledge/trading/strategies/indexes/generalities.md create mode 100644 gateway/knowledge/trading/strategies/indexes/intraday-etf-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/indexes/volatility-targeting.md create mode 100644 gateway/knowledge/trading/strategies/infrastructure/infrastructure-overview.md create mode 100644 gateway/knowledge/trading/strategies/miscellaneous/energy-spark-spread.md create mode 100644 gateway/knowledge/trading/strategies/miscellaneous/inflation-hedging-swaps.md create mode 100644 gateway/knowledge/trading/strategies/miscellaneous/tips-treasury-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/miscellaneous/weather-risk-hedging.md create mode 100644 gateway/knowledge/trading/strategies/options/bear-call-ladder.md create mode 100644 gateway/knowledge/trading/strategies/options/bear-call-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bear-put-ladder.md create mode 100644 gateway/knowledge/trading/strategies/options/bear-put-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bearish-long-seagull-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bearish-short-seagull-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bull-call-ladder.md create mode 100644 gateway/knowledge/trading/strategies/options/bull-call-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bull-put-ladder.md create mode 100644 gateway/knowledge/trading/strategies/options/bull-put-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bullish-long-seagull-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/bullish-short-seagull-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/calendar-call-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/calendar-put-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/call-ratio-backspread.md create mode 100644 gateway/knowledge/trading/strategies/options/collar.md create mode 100644 gateway/knowledge/trading/strategies/options/covered-call.md create mode 100644 gateway/knowledge/trading/strategies/options/covered-put.md create mode 100644 gateway/knowledge/trading/strategies/options/covered-short-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/covered-short-strangle.md create mode 100644 gateway/knowledge/trading/strategies/options/diagonal-call-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/diagonal-put-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/long-box.md create mode 100644 gateway/knowledge/trading/strategies/options/long-call-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/options/long-call-condor.md create mode 100644 gateway/knowledge/trading/strategies/options/long-call-synthetic-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/long-combo.md create mode 100644 gateway/knowledge/trading/strategies/options/long-guts.md create mode 100644 gateway/knowledge/trading/strategies/options/long-iron-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/options/long-iron-condor.md create mode 100644 gateway/knowledge/trading/strategies/options/long-put-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/options/long-put-condor.md create mode 100644 gateway/knowledge/trading/strategies/options/long-put-synthetic-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/long-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/long-strangle.md create mode 100644 gateway/knowledge/trading/strategies/options/long-synthetic-forward.md create mode 100644 gateway/knowledge/trading/strategies/options/protective-call.md create mode 100644 gateway/knowledge/trading/strategies/options/protective-put.md create mode 100644 gateway/knowledge/trading/strategies/options/put-ratio-backspread.md create mode 100644 gateway/knowledge/trading/strategies/options/ratio-call-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/ratio-put-spread.md create mode 100644 gateway/knowledge/trading/strategies/options/short-call-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/options/short-call-condor.md create mode 100644 gateway/knowledge/trading/strategies/options/short-call-synthetic-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/short-combo.md create mode 100644 gateway/knowledge/trading/strategies/options/short-guts.md create mode 100644 gateway/knowledge/trading/strategies/options/short-iron-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/options/short-iron-condor.md create mode 100644 gateway/knowledge/trading/strategies/options/short-put-butterfly.md create mode 100644 gateway/knowledge/trading/strategies/options/short-put-condor.md create mode 100644 gateway/knowledge/trading/strategies/options/short-put-synthetic-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/short-straddle.md create mode 100644 gateway/knowledge/trading/strategies/options/short-strangle.md create mode 100644 gateway/knowledge/trading/strategies/options/short-synthetic-forward.md create mode 100644 gateway/knowledge/trading/strategies/options/strap.md create mode 100644 gateway/knowledge/trading/strategies/options/strip.md create mode 100644 gateway/knowledge/trading/strategies/real-estate/fix-and-flip.md create mode 100644 gateway/knowledge/trading/strategies/real-estate/inflation-hedging.md create mode 100644 gateway/knowledge/trading/strategies/real-estate/intra-asset-diversification.md create mode 100644 gateway/knowledge/trading/strategies/real-estate/mixed-asset-diversification.md create mode 100644 gateway/knowledge/trading/strategies/real-estate/momentum-regional.md create mode 100644 gateway/knowledge/trading/strategies/stocks/alpha-combos.md create mode 100644 gateway/knowledge/trading/strategies/stocks/channel.md create mode 100644 gateway/knowledge/trading/strategies/stocks/earnings-momentum.md create mode 100644 gateway/knowledge/trading/strategies/stocks/event-driven-ma.md create mode 100644 gateway/knowledge/trading/strategies/stocks/implied-volatility.md create mode 100644 gateway/knowledge/trading/strategies/stocks/low-volatility-anomaly.md create mode 100644 gateway/knowledge/trading/strategies/stocks/market-making.md create mode 100644 gateway/knowledge/trading/strategies/stocks/mean-reversion-cluster.md create mode 100644 gateway/knowledge/trading/strategies/stocks/mean-reversion-weighted-regression.md create mode 100644 gateway/knowledge/trading/strategies/stocks/ml-knn.md create mode 100644 gateway/knowledge/trading/strategies/stocks/multifactor-portfolio.md create mode 100644 gateway/knowledge/trading/strategies/stocks/pairs-trading.md create mode 100644 gateway/knowledge/trading/strategies/stocks/price-momentum.md create mode 100644 gateway/knowledge/trading/strategies/stocks/residual-momentum.md create mode 100644 gateway/knowledge/trading/strategies/stocks/single-moving-average.md create mode 100644 gateway/knowledge/trading/strategies/stocks/statistical-arbitrage-optimization.md create mode 100644 gateway/knowledge/trading/strategies/stocks/support-and-resistance.md create mode 100644 gateway/knowledge/trading/strategies/stocks/three-moving-averages.md create mode 100644 gateway/knowledge/trading/strategies/stocks/two-moving-averages.md create mode 100644 gateway/knowledge/trading/strategies/stocks/value.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/carry-cds-hedging.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/carry-equity-tranche.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/carry-senior-mezzanine.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/carry-tranche-hedging.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/cdo-curve-trades.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/cdo-generalities.md create mode 100644 gateway/knowledge/trading/strategies/structured-assets/mbs-trading.md create mode 100644 gateway/knowledge/trading/strategies/tax-arbitrage/cross-border-tax-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/tax-arbitrage/muni-bond-tax-arbitrage.md create mode 100644 gateway/knowledge/trading/strategies/volatility/generalities.md create mode 100644 gateway/knowledge/trading/strategies/volatility/variance-swaps.md create mode 100644 gateway/knowledge/trading/strategies/volatility/vix-futures-basis-trading.md create mode 100644 gateway/knowledge/trading/strategies/volatility/volatility-carry.md create mode 100644 gateway/knowledge/trading/strategies/volatility/volatility-risk-premium.md create mode 100644 gateway/knowledge/trading/strategies/volatility/volatility-skew-risk-reversal.md create mode 100644 gateway/src/tools/platform/shapes-mutate.tool.ts diff --git a/doc/plan.md b/doc/plan.md index 47c22499..fc58836c 100644 --- a/doc/plan.md +++ b/doc/plan.md @@ -1,7 +1,8 @@ # Development Plan -* Daily volume in symbol metadata * Triggers +* Alerts + * Needs Email/Telegram channels * Screeners * Strategy UI * Backtesting TV integration @@ -11,9 +12,13 @@ * Sandbox <=> Dexorder auth * Chat channels * MCP channel (with or without images) + * Telegram cookie binding + * Needs user secrets vault * TradingView indicator import tool * Results persistence: ~~research analysis~~, backtests, strategy performance metrics, etc. * Free tier with token limits and sandbox shutdown + * Registration + * System email * Performance analysis * Custom pre-session scanners / summaries * Saved prompts (Create /presession prompt command for easy re-use) diff --git a/flink/src/main/java/com/dexorder/flink/TradingFlinkApp.java b/flink/src/main/java/com/dexorder/flink/TradingFlinkApp.java index f876de3e..1b493c03 100644 --- a/flink/src/main/java/com/dexorder/flink/TradingFlinkApp.java +++ b/flink/src/main/java/com/dexorder/flink/TradingFlinkApp.java @@ -269,7 +269,7 @@ public class TradingFlinkApp { DataStream barStream = tickStream .keyBy(TickWrapper::getTicker) - .flatMap(new RealtimeBarFunction(periods)) + .process(new RealtimeBarFunction(periods)) .setParallelism(1); barStream.addSink(new RealtimeBarPublisher(notificationEndpoint)) diff --git a/flink/src/main/java/com/dexorder/flink/publisher/RealtimeBarFunction.java b/flink/src/main/java/com/dexorder/flink/publisher/RealtimeBarFunction.java index acd49d3c..1b1d56f3 100644 --- a/flink/src/main/java/com/dexorder/flink/publisher/RealtimeBarFunction.java +++ b/flink/src/main/java/com/dexorder/flink/publisher/RealtimeBarFunction.java @@ -1,11 +1,13 @@ package com.dexorder.flink.publisher; -import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.api.common.state.MapState; import org.apache.flink.api.common.state.MapStateDescriptor; +import org.apache.flink.api.common.state.ValueState; +import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeinfo.PrimitiveArrayTypeInfo; import org.apache.flink.configuration.Configuration; +import org.apache.flink.streaming.api.functions.KeyedProcessFunction; import org.apache.flink.util.Collector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,11 +22,16 @@ import org.slf4j.LoggerFactory; * one tick interval (~10s for realtime polling). * * Emits two types of bars per tick: - * - Open bar (isClosed=false): the current accumulator state, every tick. - * Topic: "{ticker}|ohlc:{period}:open" — consumed by charts for live price display. - * - Closed bar (isClosed=true): emitted once when a window boundary is crossed. + * - Open bar (isClosed=false): current accumulator state, debounced via processing-time + * timer. Multiple ticks within DEBOUNCE_MS share a single emission. Emitted on + * topic "{ticker}|ohlc:{period}:open" — consumed by charts for live price display. + * - Closed bar (isClosed=true): emitted immediately when a window boundary is crossed. * Topic: "{ticker}|ohlc:{period}" — consumed by strategies/triggers. * + * Debouncing: open bars are not emitted per-tick. Instead the first tick in a batch + * registers a processing-time timer (DEBOUNCE_MS in the future). onTimer() emits + * the final accumulated state once, after the Kafka poll queue drains. + * * Replay protection: ticks whose trade timestamp predates a period's current window start * are discarded (prevents Kafka replay from contaminating current bars). Open bars are * additionally suppressed until the first live tick (within LIVE_TICK_THRESHOLD_MS of now) @@ -40,14 +47,19 @@ import org.slf4j.LoggerFactory; * [6] tickCount * [7] valid (1 = seeded or fresh window, 0 = mid-window cold start — open bars suppressed) */ -public class RealtimeBarFunction extends RichFlatMapFunction { +public class RealtimeBarFunction extends KeyedProcessFunction { private static final Logger LOG = LoggerFactory.getLogger(RealtimeBarFunction.class); private static final long serialVersionUID = 1L; + // Ticks within this many ms of wall-clock time are considered live (vs. Kafka catch-up). private static final long LIVE_TICK_THRESHOLD_MS = 30_000L; + // Open bars are debounced: first tick in a batch registers a timer; onTimer emits once. + private static final long DEBOUNCE_MS = 50L; private final int[] periods; private transient MapState accumState; + // Tracks the timestamp of the pending debounce timer (null if none registered). + private transient ValueState pendingTimerTs; // Suppresses open bar emissions during Kafka catch-up; set to true on first live tick. private transient boolean caughtUp = false; @@ -66,10 +78,12 @@ public class RealtimeBarFunction extends RichFlatMapFunction("pendingTimerTs", Long.class)); } @Override - public void flatMap(TickWrapper tick, Collector out) throws Exception { + public void processElement(TickWrapper tick, Context ctx, Collector out) throws Exception { if (tick == null) return; long nowMs = System.currentTimeMillis(); @@ -88,6 +102,8 @@ public class RealtimeBarFunction extends RichFlatMapFunction 0) { out.collect(toBar(tick.getTicker(), period, accum, true)); LOG.debug("Emitted closed bar: ticker={}, period={}s, windowStart={}, ticks={}", @@ -141,7 +156,7 @@ public class RealtimeBarFunction extends RichFlatMapFunction out) throws Exception { + pendingTimerTs.clear(); + if (!caughtUp) return; + + String ticker = ctx.getCurrentKey(); + long nowMs = System.currentTimeMillis(); + + for (int period : periods) { + long[] accum = accumState.get(period); + if (accum == null || accum[7] != 1) continue; + + // Verify accumulator is still in the current window (guard against stale state) + long periodMs = period * 1000L; + long windowStart = (nowMs / periodMs) * periodMs; + if (accum[5] != windowStart) continue; + + out.collect(toBar(ticker, period, accum, false)); + LOG.debug("Debounced open bar emitted: ticker={}, period={}s", ticker, period); + } } private static long[] openWindow(TickWrapper tick, long windowStart, boolean valid) { diff --git a/gateway/knowledge/indicators/indicator-development.md b/gateway/knowledge/indicator-development.md similarity index 90% rename from gateway/knowledge/indicators/indicator-development.md rename to gateway/knowledge/indicator-development.md index 07d6af65..47245203 100644 --- a/gateway/knowledge/indicators/indicator-development.md +++ b/gateway/knowledge/indicator-development.md @@ -6,7 +6,7 @@ description: "API and patterns for writing custom Python indicator scripts that Custom indicators are Python scripts saved in the `indicator` category. They compute values from OHLCV data and are plotted live on the TradingView chart alongside built-in indicators. -See [`../pandas-ta-reference.md`](../pandas-ta-reference.md) for the full catalog of built-in indicators available via `pandas_ta`. +See [`pandas-ta-reference`](pandas-ta-reference.md) for the full catalog of built-in indicators available via `pandas_ta`. --- @@ -109,7 +109,7 @@ To shade between two output series (e.g. upper/lower bands), add a `filled_areas 3. **Add to workspace** with `WorkspacePatch("indicators", ...)` using `pandas_ta_name: "custom_"`. Include `custom_metadata` in the patch value so the web client can render it. -4. **Use in strategies** via `ta.custom_(...)`. See [`../strategies/strategy-development.md`](strategy-development.md) for details. +4. **Use in strategies** via `ta.custom_(...)`. See [`strategy-development`](strategy-development.md) for details. --- @@ -163,6 +163,6 @@ if vw_rsi.isna().all() or len(df) < min_required: ## See Also -- [`../pandas-ta-reference.md`](../pandas-ta-reference.md) — Full catalog of built-in indicators and calling conventions -- [`../api-reference.md`](../api-reference.md) — DataAPI and ChartingAPI for research scripts -- [`../strategies/strategy-development.md`](strategy-development.md) — Using custom indicators in strategies via `ta.custom_*` +- [`pandas-ta-reference`](pandas-ta-reference.md) — Full catalog of built-in indicators and calling conventions +- [`api-reference`](api-reference.md) — DataAPI and ChartingAPI for research scripts +- [`strategy-development`](strategy-development.md) — Using custom indicators in strategies via `ta.custom_*` diff --git a/gateway/knowledge/platform/index.md b/gateway/knowledge/platform/index.md new file mode 100644 index 00000000..5df4474e --- /dev/null +++ b/gateway/knowledge/platform/index.md @@ -0,0 +1,4 @@ +--- +description: "Platform documentation index: workspace API reference, chart shape types, and MCP sandbox lifecycle." +tags: [platform, index] +--- diff --git a/gateway/knowledge/platform/shapes.md b/gateway/knowledge/platform/shapes.md new file mode 100644 index 00000000..d44db7a4 --- /dev/null +++ b/gateway/knowledge/platform/shapes.md @@ -0,0 +1,131 @@ +--- +description: "Chart shape types (trend lines, Fibonacci, rectangles, channels, etc.), point requirements, override properties, and WorkspacePatch patterns for adding/modifying/deleting shapes on the TradingView chart." +--- + +# Chart Shapes + +Shapes are persistent TradingView chart drawings stored in the `shapes` workspace store. Read them with `WorkspaceRead("shapes")` and create/modify/delete them with `ShapesMutate`. Do **not** use `WorkspacePatch` for shapes — it requires knowledge of the internal path structure and is error-prone. + +Always read `chartState` first to get the current `symbol` and visible `start_time`/`end_time` for placing points correctly. + +--- + +## Shape Object + +```json +{ + "id": "string — unique ID you assign (e.g. 'trendline-btc-1')", + "type": "string — see type table below", + "points": [{ "time": 1700000000, "price": 45000.0, "channel": "optional" }], + "color": "#2962FF", + "line_width": 2, + "line_style": "solid", + "properties": {}, + "symbol": "BTC/USDT.BINANCE", + "created_at": 1700000000, + "modified_at": 1700000000 +} +``` + +- `line_style`: `"solid"` | `"dashed"` | `"dotted"` +- `properties`: passed directly as TradingView overrides (see [Drawings Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides)) +- `time` values must be Unix timestamps in **seconds**; they are snapped to the nearest candle boundary automatically + +--- + +## Supported Shape Types + +| `type` | Description | Points | +|---|---|---| +| `trend_line` | Trend line between two price/time points | 2 | +| `horizontal_line` | Horizontal price level across the chart | 1 | +| `vertical_line` | Vertical time marker | 1 | +| `rectangle` | Price/time rectangle (two corners) | 2 | +| `circle` | Circle centered at first point, edge at second | 2 | +| `arrow` | Arrow from point 1 to point 2 | 2 | +| `fib_retracement` | Fibonacci retracement levels between two points | 2 | +| `fib_trend_ext` | Trend-based Fibonacci extension (A→B→C) | 3 | +| `parallel_channel` | Parallel channel (two-line + channel width) | 3 | +| `pitchfork` | Andrews pitchfork (handle + two tines) | 3 | +| `gannbox_fan` | Gann fan from a pivot point | 2 | +| `path` | Free-form polyline through 2+ points | 2+ | +| `text` | Text label anchored at a price/time location | 1 | +| `head_and_shoulders` | Head and shoulders pattern overlay | 7 | + +> For the full TradingView drawing catalog (including Elliott waves, patterns, annotations, etc.) see [Drawings List](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List/) and [CreateShapeOptions](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateShapeOptions/#shape). + +--- + +## ShapesMutate Patterns + +Use `ShapesMutate` — not `WorkspacePatch` — to add, update, or remove shapes. Any combination of operations can be sent in a single call. + +### Add a shape + +``` +ShapesMutate({ + add: [{ + id: "trendline-1", + type: "trend_line", + points: [ + { time: 1700000000, price: 42000 }, + { time: 1700172800, price: 45000 } + ], + color: "#2962FF", + line_width: 2, + line_style: "solid", + symbol: "BTC/USDT.BINANCE" + }] +}) +``` + +### Update a property + +``` +ShapesMutate({ update: [{ id: "trendline-1", color: "#FF5722" }] }) +``` + +### Delete a shape + +``` +ShapesMutate({ remove: ["trendline-1"] }) +``` + +### Combined (add + remove in one call) + +``` +ShapesMutate({ + add: [{ id: "hline-support", type: "horizontal_line", points: [{ time: 0, price: 42000 }], symbol: "BTC/USDT.BINANCE" }], + remove: ["trendline-1"] +}) +``` + +--- + +## Override Properties + +These map to TradingView drawing override keys passed in the `properties` field: + +| Property key | Type | Notes | +|---|---|---| +| `linecolor` | string (hex) | Same as top-level `color` — prefer `color` | +| `linewidth` | number | Same as top-level `line_width` — prefer `line_width` | +| `linestyle` | number | 0 = solid, 1 = dashed, 2 = dotted — prefer `line_style` | +| `fillBackground` | boolean | Fill enclosed areas (rectangles, circles, etc.) | +| `backgroundColor` | string (hex) | Fill color when `fillBackground` is true | +| `transparency` | number | Fill transparency 0–100 | +| `extendLeft` | boolean | Extend line left (rays, horizontal lines) | +| `extendRight` | boolean | Extend line right | +| `showLabel` | boolean | Show price/time label on the shape | + +For the complete per-type override reference, consult [Drawings Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides). + +--- + +## Notes + +- **ID collisions**: read the `shapes` store first to check existing IDs before adding +- **Symbol filter**: the web client only renders shapes where `shape.symbol` matches the current chart symbol — always set it +- **Horizontal lines** only need a `price` in their single point; `time` is ignored +- **Vertical lines** only need a `time` in their single point; `price` is ignored +- **Text shapes**: set `properties.text` to the label string diff --git a/gateway/knowledge/platform/workspace.md b/gateway/knowledge/platform/workspace.md index 7fc4c758..e677beee 100644 --- a/gateway/knowledge/platform/workspace.md +++ b/gateway/knowledge/platform/workspace.md @@ -1,5 +1,5 @@ --- -description: "Workspace store schema, available stores, and WorkspaceRead/WorkspacePatch usage for reading and updating the user's UI state." +description: "Workspace store schema: chartState (symbol/period/time range), indicators, shapes (chart drawings/annotations — see platform/shapes), and WorkspaceRead/WorkspacePatch usage." --- # Workspace @@ -70,20 +70,7 @@ A flat map of `indicator_id → IndicatorInstance`. Each entry represents one st { "shapes": { "": Shape } } ``` -Each `Shape` has: - -| Field | Type | Description | -|---|---|---| -| `id` | string | Unique shape ID | -| `type` | string | Drawing type (e.g. `"trend_line"`, `"horizontal_line"`, `"rectangle"`) | -| `points` | array | Control points: `{ time: unix_ts, price: number, channel?: string }` | -| `color` | string? | Hex color | -| `line_width` | number? | Line thickness | -| `line_style` | string? | `"solid"`, `"dotted"`, `"dashed"` | -| `properties` | object? | Additional type-specific properties | -| `symbol` | string? | Symbol the shape belongs to | -| `created_at` | number? | Unix timestamp | -| `modified_at` | number? | Unix timestamp | +For the complete shapes reference — all supported types, point counts, override properties, and WorkspacePatch examples — see **`platform/shapes`** (`MemoryLookup({page: "platform/shapes"})`). --- diff --git a/gateway/knowledge/strategies/strategy-development.md b/gateway/knowledge/strategy-development.md similarity index 90% rename from gateway/knowledge/strategies/strategy-development.md rename to gateway/knowledge/strategy-development.md index c1869f74..98b1c67e 100644 --- a/gateway/knowledge/strategies/strategy-development.md +++ b/gateway/knowledge/strategy-development.md @@ -6,7 +6,7 @@ description: "PandasStrategy class API, order placement, backtesting, and paper Strategies on Dexorder are `PandasStrategy` subclasses that receive a live stream of OHLCV bars and call `self.buy()` / `self.sell()` / `self.flatten()` to place orders. -See [`../api-reference.md`](../api-reference.md) for the DataAPI and ChartingAPI used in research scripts. For indicator calculations, see [`../pandas-ta-reference.md`](../pandas-ta-reference.md). +See [`api-reference`](api-reference.md) for the DataAPI and ChartingAPI used in research scripts. For indicator calculations, see [`pandas-ta-reference`](pandas-ta-reference.md). --- @@ -78,7 +78,7 @@ ema = ta.ema(df["close"], length=20) atr = ta.atr(df["high"], df["low"], df["close"], length=14) ``` -See [`../pandas-ta-reference.md`](../pandas-ta-reference.md) for the full indicator catalog and multi-output column extraction patterns. +See [`pandas-ta-reference`](pandas-ta-reference.md) for the full indicator catalog and multi-output column extraction patterns. --- @@ -104,7 +104,7 @@ def evaluate(self, dfs): self.sell(0.01) ``` -Custom indicator names follow the pattern `ta.custom_{sanitized_name}`. See [`../indicators/indicator-development.md`](../indicators/indicator-development.md) for naming rules and how to create custom indicators. +Custom indicator names follow the pattern `ta.custom_{sanitized_name}`. See [`indicator-development`](indicator-development.md) for naming rules and how to create custom indicators. --- @@ -260,7 +260,7 @@ A strategy with a lower win rate can still be profitable if winners are larger t ## See Also -- [`../pandas-ta-reference.md`](../pandas-ta-reference.md) — Indicator catalog and usage examples -- [`../indicators/indicator-development.md`](../indicators/indicator-development.md) — Creating custom indicators -- [`../api-reference.md`](../api-reference.md) — DataAPI reference (for research scripts) -- [`../usage-examples.md`](../usage-examples.md) — Research script patterns +- [`pandas-ta-reference`](pandas-ta-reference.md) — Indicator catalog and usage examples +- [`indicator-development`](indicator-development.md) — Creating custom indicators +- [`api-reference`](api-reference.md) — DataAPI reference (for research scripts) +- [`usage-examples`](usage-examples.md) — Research script patterns diff --git a/gateway/knowledge/trading/index.md b/gateway/knowledge/trading/index.md new file mode 100644 index 00000000..83e80b0d --- /dev/null +++ b/gateway/knowledge/trading/index.md @@ -0,0 +1,4 @@ +--- +description: "Trading knowledge index: signal combination theory, technical analysis, and a master catalog of 150+ strategies by asset class." +tags: [trading, index] +--- diff --git a/gateway/knowledge/trading/signal-combination.md b/gateway/knowledge/trading/signal-combination.md new file mode 100644 index 00000000..bf97e544 --- /dev/null +++ b/gateway/knowledge/trading/signal-combination.md @@ -0,0 +1,121 @@ +--- +description: "Institutional alpha combination: how to merge multiple weak signals into a single high-conviction output using the 11-step procedure and the Fundamental Law of Active Management." +tags: [signals, alpha, portfolio, kelly, statistics] +--- + +# Signal Combination — Alpha Stacking + +## Core Law + +Do not search for one perfect signal. Combine many weak, independent signals. + +**Fundamental Law of Active Management:** +``` +IR = IC × √N +``` +- `IR` = Information Ratio of the combined system (risk-adjusted edge) +- `IC` = average Information Coefficient per signal (correlation of prediction to outcome) +- `N` = number of *genuinely independent* signals + +Real institutional signals have IC = 0.05–0.15. A single signal at IC=0.10 is outperformed by 50 signals at IC=0.05 (IR = 0.05 × √50 = 0.354, over 3× better). + +**Critical:** N counts *effective independent signals*, not raw signal count. Fifty correlated signals may yield only 10–15 effective ones. The 11-step procedure below forces honest accounting. + +--- + +## Five Signal Categories + +| Category | What it measures | Why it persists | +|---|---|---| +| **Momentum / Price** | Direction/rate of price movement over lookback `d` | Underreaction causes short-term trend persistence | +| **Mean Reversion** | Deviation from cross-sectional fair value | Related instruments maintain consistent relative pricing | +| **Volatility** | Implied vs. realized volatility gap | Vol risk premium: sellers demand compensation | +| **Factor** | Value, momentum, carry, quality, low-vol premiums | Persistent behavioral/structural inefficiencies | +| **Microstructure** | Order book imbalance, bid-ask spread, VPIN | Informed order flow leads price movement | + +> **Dexorder scope**: Only crypto OHLCV data is available. Factor signals (value, carry, quality) require TradFi data not available here. Momentum, mean reversion, volatility, and microstructure signals are all applicable. + +--- + +## 11-Step Combination Engine + +Given N signals with historical returns R(i,s) over M periods: + +**Step 1.** Collect realized return series R(i,s) for each signal i, each period s. + +**Step 2.** Remove drift — serially demean: +``` +X(i,s) = R(i,s) − mean(R(i,·)) +``` + +**Step 3.** Compute variance per signal: +``` +σ(i)² = (1/M) × Σ X(i,s)² +``` + +**Step 4.** Normalize to common scale: +``` +Y(i,s) = X(i,s) / σ(i) +``` +Makes signals with different magnitudes directly comparable. + +**Step 5.** Drop the most recent observation from Y — use only out-of-sample history. + +**Step 6.** Cross-sectionally demean at each time period: +``` +Λ(i,s) = Y(i,s) − avg_j(Y(j,s)) +``` +Removes any market-wide effect driving all signals simultaneously at that moment. + +**Step 7.** Drop the final period from Λ to eliminate residual look-ahead. + +**Step 8.** Estimate expected forward return per signal using d-day moving average, normalize: +``` +E(i) = (1/d) × Σ R(i,s) over recent d periods +E_normalized(i) = E(i) / σ(i) +``` + +**Step 9. (Critical)** Regress E_normalized over Λ(i,s) without intercept, unit weights. Residuals `ε(i)` are each signal's *independent* forward-looking contribution — the component not explained by any other signal in the stack. + +**Step 10.** Set weights: +``` +w(i) = η × ε(i) / σ(i) +``` +High independent edge + low noise → high weight. No subjective judgment. + +**Step 11.** Normalize: scale η so `Σ|w(i)| = 1`. No unintended leverage. + +**Combined output = Σ w(i) × signal_i_current_value** + +--- + +## Empirical Kelly Sizing + +``` +f_empirical = f_kelly × (1 − CV_edge) + +f_kelly = (p × b − q) / b +``` +- `CV_edge` = coefficient of variation of edge estimates across 10,000 Monte Carlo path simulations of historical returns +- Higher uncertainty → smaller fraction. The formula automatically scales confidence to what is warranted. + +--- + +## Key Failure Mode: Correlation Blindness + +Believing you have 3 independent reasons for a trade when you have 1 reason expressed 3 times, sized as if for 3. This is the mechanism behind most systematic blowups where the trader was directionally correct but over-sized. + +The cross-sectional demeaning (Step 6) and regression residualization (Step 9) structurally prevent this by exposing shared variance before weights are assigned. + +--- + +## Dexorder Application Note + +When combining multiple indicators into a single entry/exit signal: + +1. Each indicator (momentum, RSI divergence, volume profile, spread, etc.) is a signal producing a score or directional estimate. +2. Run the 11-step engine over backtested signal histories to derive weights. +3. Combined score = weighted sum of current signal outputs. +4. Size the resulting position using empirical Kelly with CV_edge from simulation. + +If computing probability estimates (e.g. probability of upward breakout), substitute probability estimates for return estimates at each step — the math is identical. diff --git a/gateway/knowledge/trading/strategies/cash/liquidity-management.md b/gateway/knowledge/trading/strategies/cash/liquidity-management.md new file mode 100644 index 00000000..9b4d3249 --- /dev/null +++ b/gateway/knowledge/trading/strategies/cash/liquidity-management.md @@ -0,0 +1,51 @@ +--- +description: "A portfolio strategy that optimally determines how much cash to hold to meet unforeseen liquidity demands while minimizing the drag from uninvested capital." +tags: [cash, liquidity, risk-management] +--- + +# Liquidity Management + +**Section**: 17.3 | **Asset Class**: Cash | **Type**: Risk management / Portfolio construction + +## Overview + +From a portfolio management perspective, this strategy amounts to optimally defining the amount of cash to be held in the portfolio to meet liquidity demands generated by unforeseen events. Cash provides immediate liquidity, whereas other assets would have to be liquidated first, which can be associated with substantial transaction costs — especially if liquidation is abrupt. From a corporate perspective, holding cash can be a precautionary measure aimed at avoiding cash flow shortfalls that can yield, inter alia, loss of investment opportunities, financial distress, etc. + +## Construction / Mechanics + +The strategy involves three distinct roles for cash as an asset: + +1. **Risk management tool** — Cash held as a buffer mitigates drawdowns and volatility by providing a shock absorber when other assets decline or become illiquid. + +2. **Opportunity management tool** — A cash reserve allows the investor to take advantage of specific or unusual situations (e.g., distressed asset purchases, sudden dislocations) without needing to liquidate existing positions. + +3. **Liquidity management tool** — In unexpected situations requiring liquid funds, cash is the only immediately available resource without liquidation costs. + +Liquid cash equivalents that can be held in a portfolio include: +- U.S. Treasury bills +- Bank deposit certificates (CDs) +- Commercial paper +- Banker's acceptances +- Eurodollars +- Repurchase agreements (repos) + +## Return Profile / Objective + +The direct return on cash is low (near the risk-free rate). The strategy's value lies in its option-like properties: the ability to act quickly when opportunities arise and to avoid forced liquidation at disadvantageous prices. The optimal cash level trades off the opportunity cost of holding cash against the cost of unexpected forced liquidation. + +## Key Parameters / Signals + +- **Liquidity buffer target**: sized to expected maximum drawdown of cash needs over some horizon +- **Opportunity reserve**: discretionary allocation kept available for tactical deployment +- **Kelly-based sizing**: related to Kelly criterion strategies; the cash fraction can be derived from portfolio growth optimization +- **Liquidation cost model**: transaction costs and market impact of rapidly liquidating other assets inform the minimum required cash buffer + +## Variations + +- **Corporate treasury liquidity management**: focused on operating cash flow needs, payroll, and debt service +- **Hedge fund liquidity management**: sized to potential investor redemptions and margin call scenarios +- **Tactical cash allocation**: dynamically increasing cash weight as a defensive signal during high-volatility regimes + +## Notes + +The optimal cash holding is not the same as the rationale behind Kelly strategies. The appropriate cash level depends on the investor's specific liability structure, redemption profile, and the liquidity of the remaining portfolio. Holding too little cash forces costly liquidation; holding too much creates unacceptable opportunity cost drag. The strategy is foundational to virtually all portfolio management frameworks. diff --git a/gateway/knowledge/trading/strategies/cash/loan-sharking.md b/gateway/knowledge/trading/strategies/cash/loan-sharking.md new file mode 100644 index 00000000..2658fcca --- /dev/null +++ b/gateway/knowledge/trading/strategies/cash/loan-sharking.md @@ -0,0 +1,49 @@ +--- +description: "An illegal lending practice involving loans at excessively high interest rates without collateral, enforced through coercion; documented here for educational and awareness purposes only." +tags: [cash, illegal, lending, awareness] +--- + +# Loan Sharking + +**Section**: 17.6 | **Asset Class**: Cash | **Type**: Illegal activity (documented for educational/awareness purposes only) + +## Overview + +Loan sharking consists of offering loans at excessively high — often usurious — interest rates. Unlike pawnbroking, loan sharking in many jurisdictions is illegal, and the loan is not necessarily secured by collateral. This activity is documented here solely for educational and awareness purposes. It is not a legitimate trading strategy and constitutes criminal conduct in most jurisdictions. + +## Construction / Mechanics + +**Loan structure:** +- Cash is lent to a borrower at interest rates far above legal usury limits — rates can be expressed in weekly or daily terms (e.g., "2 for 1" means repay double within a fixed period) +- No formal legal documentation is typically used; the arrangement is informal and unenforceable through normal legal channels +- The loan is typically unsecured — there is no collateral pledge + +**Enforcement:** +- Because the loan cannot be enforced through the legal system, the lender (loan shark) may resort to extralegal means of enforcement +- This can include blackmail, threats, and physical violence to compel repayment +- The borrower has no legal recourse against abusive enforcement methods + +**Relationship to legitimate lending:** +- Loan sharks operate in the same economic niche as payday lenders and pawnbrokers but without legal constraints on rates or enforcement methods +- They typically serve borrowers with no access to formal credit (e.g., due to criminal records, immigration status, or existing debt) + +## Return Profile / Objective + +The stated "return" is the extremely high interest charged. In practice, the loan shark often profits more from the coercive control over the borrower than from pure interest income — borrowers may be exploited for labor or other services. The high nominal returns are offset by significant legal, personal safety, and operational risks. + +## Key Parameters / Signals + +- **Interest rate**: typically far above legal usury limits; often quoted in short-period terms to obscure the true APR +- **Enforcement mechanism**: the primary differentiator from legal lending; ranges from social pressure to physical violence +- **Borrower desperation**: loan sharks target individuals with no alternative credit access +- **Rollover/compound traps**: unpaid interest may compound rapidly, trapping borrowers in escalating debt + +## Variations + +- **Organized crime lending**: loan sharking as a service offered by criminal organizations, often linked to other illegal activities +- **Predatory lending (grey area)**: legal but extremely high-rate lenders (payday loans, rent-to-own) operating at the edge of legality +- **Salary lending / advance-fee lending**: informal arrangements common in some developing markets + +## Notes + +Loan sharking is **illegal** in most jurisdictions. It is documented here exclusively for educational purposes — to illustrate the spectrum of cash-based financial activities, support awareness of predatory lending, and assist in compliance or regulatory analysis. Any actual participation in loan sharking carries severe criminal penalties including imprisonment. The key distinction from legal high-rate lending (e.g., payday loans) is the use of illegal coercion and the absence of legal licensing and rate-cap compliance. diff --git a/gateway/knowledge/trading/strategies/cash/money-laundering-dark-side.md b/gateway/knowledge/trading/strategies/cash/money-laundering-dark-side.md new file mode 100644 index 00000000..b22c1b16 --- /dev/null +++ b/gateway/knowledge/trading/strategies/cash/money-laundering-dark-side.md @@ -0,0 +1,42 @@ +--- +description: "A three-stage process (placement, layering, integration) by which illegal cash is transformed into legitimate-appearing assets; documented here for educational and awareness purposes only." +tags: [cash, illegal, awareness] +--- + +# Money Laundering — The Dark Side of Cash + +**Section**: 17.2 | **Asset Class**: Cash | **Type**: Illegal activity (documented for educational/awareness purposes only) + +## Overview + +Money laundering is an activity wherein cash is used as a vehicle to transform illegal profits into legitimate-appearing assets. It is documented here solely for educational and awareness purposes — this is an illegal activity in virtually all jurisdictions and is not a legitimate trading strategy. Understanding its mechanics is relevant for compliance, AML (anti-money-laundering) system design, and regulatory awareness. + +## Construction / Mechanics + +There are three main steps in a money laundering process: + +1. **Placement** — The first and riskiest step. Illegal funds are introduced into the legal economy via fraudulent means, e.g., by dividing funds into small amounts and depositing them into multiple bank accounts (structuring/smurfing) to avoid detection thresholds. + +2. **Layering** — Moving the money around between different accounts and even countries, thereby creating complexity and separating the money from its source by several degrees. The goal is to obscure the audit trail. + +3. **Integration** — Money launderers recover the funds via legitimate-looking sources, e.g., cash-intensive businesses such as bars, restaurants, car washes, hotels (in some countries), gambling establishments, and parking garages. + +## Return Profile / Objective + +The "return" is the successful conversion of illicit proceeds into spendable, untraceable wealth. The primary risk is detection and prosecution at the placement stage, which is why smurfing and structuring techniques are employed to stay below reporting thresholds. + +## Key Parameters / Signals + +- **Placement risk**: highest at initial deposit stage; mitigated by structuring below reporting thresholds +- **Layering complexity**: number of intermediary accounts, jurisdictions, and transactions used to obscure origin +- **Integration vehicles**: choice of business type affects detectability (high-cash-volume businesses preferred) + +## Variations + +- **Trade-based laundering**: over- or under-invoicing international trade transactions +- **Real estate laundering**: purchasing and reselling property through shell companies +- **Cryptocurrency layering**: use of mixers, privacy coins, and cross-chain swaps to layer funds + +## Notes + +This strategy is **illegal** in all major jurisdictions. It is documented here exclusively for educational purposes, AML awareness, and to support the design of detection and compliance systems. Financial institutions are required by law (e.g., BSA/AML regulations, FATF guidelines) to implement controls to detect and report suspicious activity consistent with these patterns. diff --git a/gateway/knowledge/trading/strategies/cash/pawnbroking.md b/gateway/knowledge/trading/strategies/cash/pawnbroking.md new file mode 100644 index 00000000..5ea1ce30 --- /dev/null +++ b/gateway/knowledge/trading/strategies/cash/pawnbroking.md @@ -0,0 +1,51 @@ +--- +description: "A secured short-term lending strategy where a pawnbroker extends a cash loan against physical collateral, retaining the right to sell the collateral if the loan is not repaid." +tags: [cash, lending, collateral, alternative] +--- + +# Pawnbroking + +**Section**: 17.5 | **Asset Class**: Cash | **Type**: Collateralized lending + +## Overview + +Pawnbroking is conceptually similar to repurchase agreements (REPOs) but operates in retail/consumer markets and has ancient historical roots. A pawnbroker extends a secured cash loan with a pre-agreed interest rate and period (which can sometimes be extended). The loan is secured with a collateral item of value; if the loan is not repaid with interest as agreed, the collateral is forfeited by the borrower and the pawnbroker can keep it or sell it. + +## Construction / Mechanics + +**Loan origination:** +- Borrower presents a physical item of value as collateral (jewelry, electronics, vehicles, rare books, musical instruments, etc.) +- Pawnbroker appraises the item and offers a loan amount at a significant discount to appraised value (e.g., 25–60% of estimated resale value) +- Borrower receives cash; pawnbroker retains physical possession of the item +- A loan ticket is issued specifying the principal, interest rate, fees, and redemption deadline + +**Redemption or forfeiture:** +- If borrower repays principal plus interest within the agreed period, the item is returned +- If borrower fails to repay, the pawnbroker takes full ownership of the collateral and may sell it to recover the loan amount plus a profit margin + +**From an investment perspective:** +- The pawnbroker's strategy profits from: (a) interest income on repaid loans, and (b) resale margin on forfeited collateral +- The deep discount on collateral valuation provides a cushion against mispriced or illiquid items + +## Return Profile / Objective + +Returns come from two sources: interest income on performing loans (typically high, reflecting the high-risk, unbanked borrower profile) and trading profit on forfeited collateral items sold at or above the appraised value. The high interest rates compensate for the non-recourse nature of many pawn loans (the lender's only recourse is the collateral, not the borrower personally). + +## Key Parameters / Signals + +- **Loan-to-value (LTV) ratio**: loan amount as a fraction of collateral's estimated resale value; typically 25–60% +- **Interest rate / fees**: high relative to bank rates; regulated in many jurisdictions with rate caps +- **Loan term**: typically 1–4 months; extensions often available +- **Collateral liquidity**: items with active resale markets (gold jewelry, electronics) command better LTV ratios +- **Forfeiture rate**: the fraction of loans that are not redeemed; drives the resale revenue component + +## Variations + +- **Online pawnbroking**: digital platforms for luxury goods, collectibles, and watches +- **Commodity pawnbroking**: pawnbrokers dealing specifically in precious metals and gems (overlap with commodity trading) +- **Title lending / auto pawn**: loans secured against vehicle titles; borrower retains use of the vehicle while the title is held +- **Jewelry/gold dealers**: effectively pawnbrokers who specialize in precious metals with spot-price-linked valuations + +## Notes + +Pawnbroking is legal and regulated in most jurisdictions, with interest rates and practices governed by consumer lending laws. The pawnbroker trades physical commodities such as silver and gold as a byproduct of forfeited collateral. The strategy is highly local and operationally intensive. It is conceptually the retail analogue of institutional repo markets — both involve a cash loan secured by an asset with a right to liquidate the asset upon default. diff --git a/gateway/knowledge/trading/strategies/cash/repo.md b/gateway/knowledge/trading/strategies/cash/repo.md new file mode 100644 index 00000000..6f6fd3b5 --- /dev/null +++ b/gateway/knowledge/trading/strategies/cash/repo.md @@ -0,0 +1,53 @@ +--- +description: "A repurchase agreement strategy that borrows or lends cash at a preset interest rate for 1 day to 6 months using securities as collateral, providing immediate liquidity." +tags: [cash, fixed-income, collateral, short-term] +--- + +# Repurchase Agreement (REPO) + +**Section**: 17.4 | **Asset Class**: Cash | **Type**: Collateralized lending / Cash equivalent + +## Overview + +A repurchase agreement (REPO) is a cash-equivalent asset that provides immediate liquidity at a preset interest rate for a specific period of time in exchange for another asset used as collateral. A REPO strategy amounts to borrowing (or lending) cash with interest in exchange for securities, with the commitment of repurchasing them from (or reselling them to) the counterparty at the end of the term. This type of transaction typically spans from 1 day to 6 months. + +## Construction / Mechanics + +**From the borrower's perspective (classic repo):** +- The borrower sells securities to the lender at a spot price +- Simultaneously agrees to repurchase those securities at a future date at a higher price +- The difference in prices represents the repo interest (the "repo rate") +- The securities serve as collateral; the lender has recourse to them if the borrower defaults + +**From the lender's perspective (reverse repo):** +- The lender buys securities and simultaneously agrees to resell them at a later date +- Effectively a collateralized cash loan earning the repo rate +- Counterparty credit risk is mitigated by holding the collateral + +**Mechanics summary:** +- Term: overnight (O/N) to 6 months; "open" repos have no fixed term +- Collateral: typically government securities, though agency bonds and other high-grade paper are used +- Haircut: the collateral is valued at a discount to market price to provide a buffer against collateral price declines + +## Return Profile / Objective + +The strategy earns (or pays) the repo rate, which is typically close to but slightly below the risk-free rate (for general collateral) or can be significantly below (even negative) for "special" securities in high demand. The primary objective is efficient short-term cash management — deploying idle cash at near-risk-free rates while maintaining near-immediate liquidity. + +## Key Parameters / Signals + +- **Repo rate**: the annualized interest rate on the transaction; general collateral (GC) rate vs. specific/special rates +- **Haircut**: discount applied to collateral value (e.g., 2% for Treasuries, higher for lower-grade collateral) +- **Term**: overnight, term (fixed date), or open +- **Collateral type**: determines applicable haircut and rate; GC repos use any acceptable security vs. specific repos tied to a named security +- **Margin calls**: triggered if collateral value falls below the required threshold during the term + +## Variations + +- **Reverse repo**: the lender's side; used by central banks as a monetary policy tool and by money market funds as an investment +- **Tri-party repo**: a clearing bank acts as intermediary, handling collateral management for both parties +- **Securities lending**: conceptually similar; the security owner lends it out for a fee, receiving cash or other securities as collateral +- **GC pooling**: centralized clearing of general collateral repos to improve netting and efficiency + +## Notes + +REPOs are a foundational instrument in money markets and are used by banks, broker-dealers, money market funds, and central banks. The 2008 financial crisis revealed the fragility of repo markets when collateral quality deteriorated rapidly (the "run on repo"). Counterparty credit risk, collateral quality, and the potential for "fire-sale" dynamics during stress are the primary risk considerations. REPOs are conceptually similar to pawnbroking but operate in institutional markets at vastly larger scale. diff --git a/gateway/knowledge/trading/strategies/commodities/hedging-pressure.md b/gateway/knowledge/trading/strategies/commodities/hedging-pressure.md new file mode 100644 index 00000000..d463dea0 --- /dev/null +++ b/gateway/knowledge/trading/strategies/commodities/hedging-pressure.md @@ -0,0 +1,56 @@ +--- +description: "Commodity futures strategy that uses CFTC Commitments of Traders (COT) hedging pressure data to identify long/short opportunities based on hedger and speculator positioning." +tags: [commodities, futures, cot, hedging-pressure, positioning] +--- + +# Trading Based on Hedging Pressure + +**Section**: 9.2 | **Asset Class**: Commodities | **Type**: Positioning / Sentiment + +## Overview +Hedgers and speculators have systematically different objectives in commodity futures markets. High hedger long positioning signals contango (excess hedging demand pushes futures prices up); high speculator long positioning signals backwardation. By reading the CFTC Commitments of Traders (COT) report, a trader can construct a zero-cost portfolio that exploits these positioning signals with a 6-month typical holding period. + +## Construction / Mechanics +The "hedging pressure" (HP) for each group is defined as: + +``` +HP = (number of long contracts) / (total contracts: long + short) +``` + +HP lies between 0 and 1. + +**Interpretation:** +- High hedgers' HP → indicative of contango +- Low hedgers' HP → indicative of backwardation +- High speculators' HP → indicative of backwardation +- Low speculators' HP → indicative of contango + +**Portfolio construction:** +1. Rank all commodity futures by speculators' HP; divide the cross-section into upper and lower halves. +2. Within the upper half (higher speculator HP, i.e., backwardation signal): + - **Buy** futures that are in the **bottom quintile** by hedgers' HP (confirming low hedger demand, strong backwardation signal) +3. Within the lower half (lower speculator HP, i.e., contango signal): + - **Sell** futures that are in the **top quintile** by hedgers' HP (confirming high hedger demand, strong contango signal) + +The portfolio is zero-cost and rebalanced with typical formation and holding periods of 6 months. + +## Return Profile +Profits when commodity futures that show strong backwardation signals (low hedger HP, high speculator HP) outperform those with strong contango signals. The strategy earns a risk premium for providing liquidity to hedgers who are willing to pay above-fair-value forward prices. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| HP (hedgers) | Long / (long + short) for commercial hedgers from COT report | +| HP (speculators) | Long / (long + short) for non-commercial speculators from COT | +| Holding period | Typically 6 months | +| Data source | CFTC Commitments of Traders (weekly) | + +## Variations +- Use the net position (long minus short) as the signal rather than the ratio HP. +- Combine COT positioning with the roll-yield signal (Section 9.1) for a multi-factor commodity model. + +## Notes +- COT data is published weekly with a 3-day lag, so the signal has limited use for high-frequency trading. +- The classification of "hedger" vs. "speculator" in COT data is self-reported and can be noisy; large commodity index funds are classified differently across report types (legacy vs. disaggregated COT). +- The 6-month holding period smooths over reporting noise but requires patience through short-term adverse moves. +- Strategy performance can degrade when large commodity index investors distort the COT positioning signals. diff --git a/gateway/knowledge/trading/strategies/commodities/portfolio-diversification.md b/gateway/knowledge/trading/strategies/commodities/portfolio-diversification.md new file mode 100644 index 00000000..d324c003 --- /dev/null +++ b/gateway/knowledge/trading/strategies/commodities/portfolio-diversification.md @@ -0,0 +1,46 @@ +--- +description: "Portfolio diversification strategy that adds commodity exposure to equity portfolios to exploit their historically low cross-asset correlation and improve risk-adjusted returns." +tags: [commodities, diversification, portfolio-construction, asset-allocation] +--- + +# Portfolio Diversification with Commodities + +**Section**: 9.3 | **Asset Class**: Commodities | **Type**: Portfolio Construction / Asset Allocation + +## Overview +Commodity markets typically exhibit low correlation with equity markets. Adding commodity exposure can improve the return-to-risk characteristics of equity-dominant portfolios. Two broad approaches exist: a passive buy-and-hold allocation, and an active tactical allocation that adjusts commodity exposure based on macroeconomic signals such as the Federal Reserve discount rate. + +## Construction / Mechanics + +### Passive Approach +1. Allocate a preset fraction of available capital to commodity futures (or commodity indices). +2. Hold the commodity position and rebalance periodically (e.g., monthly or annually) back to the target weight. +3. No active signal required; the diversification benefit arises purely from low cross-asset correlation. + +### Active (Tactical) Approach +1. Monitor the Federal Reserve discount rate (or a proxy monetary policy indicator). +2. **Increase** commodity exposure when the discount rate decreases (accommodative policy), since commodity returns are empirically positively correlated with monetary easing. +3. **Decrease** commodity exposure when the discount rate increases (tightening policy). +4. The tactical adjustment exploits the empirical link between commodity returns and Fed monetary policy. + +## Return Profile +The passive approach targets improved risk-adjusted returns through diversification without requiring any predictive signal. The active approach additionally aims to capture the positive correlation between commodity returns and accommodative monetary conditions, increasing commodity weights when they are most likely to outperform. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Commodity allocation (passive) | Fixed % of portfolio (e.g., 5–20%) | +| Rebalancing frequency | Monthly or annual for passive; signal-triggered for active | +| Fed discount rate | Primary macro signal for active tactical allocation | +| Cross-asset correlation | Empirically low between commodities and equities; drives diversification benefit | + +## Variations +- Use commodity indices (e.g., GSCI, BCOM) for passive exposure rather than individual futures contracts. +- Active allocation can use other macro signals: inflation expectations, industrial production growth, credit spreads. +- Risk-parity weighting (equalising volatility contribution of commodities and equities) rather than fixed notional allocation. + +## Notes +- The low equity-commodity correlation is not constant; during crisis periods (e.g., 2008), correlations can spike, reducing diversification benefit at exactly the wrong time. +- The empirical link to Fed policy is regime-dependent; the relationship may be weaker during prolonged zero-rate environments. +- Commodity exposure via futures introduces roll costs (see Section 9.1); the net diversification benefit must be assessed after roll costs. +- Inflation-sensitive commodities (energy, metals) may provide additional value as inflation hedges alongside diversification benefits. diff --git a/gateway/knowledge/trading/strategies/commodities/pricing-models.md b/gateway/knowledge/trading/strategies/commodities/pricing-models.md new file mode 100644 index 00000000..911d10af --- /dev/null +++ b/gateway/knowledge/trading/strategies/commodities/pricing-models.md @@ -0,0 +1,69 @@ +--- +description: "Commodity futures pricing strategy that fits a mean-reverting stochastic model to the term structure and trades futures identified as rich or cheap relative to model-implied fair value." +tags: [commodities, futures, stochastic-model, ornstein-uhlenbeck, pricing, term-structure] +--- + +# Trading with Pricing Models + +**Section**: 9.6 | **Asset Class**: Commodities | **Type**: Relative Value / Model-Based + +## Overview +Commodity futures term structures are non-trivial and can be modelled via stochastic processes. Fitting a parametric model (e.g., the Ornstein-Uhlenbeck mean-reverting process) to historical data allows the identification of futures that are rich (sell signal) or cheap (buy signal) relative to the model's predicted fair value. The approach acknowledges that structural mean reversion is a reasonable property for commodity prices. + +## Construction / Mechanics +Let S(t) be the spot price and X(t) = ln(S(t)). Model X(t) as a mean-reverting Brownian motion (Ornstein-Uhlenbeck): + +``` +dX(t) = κ[a - X(t)] dt + σ dW(t) (459) +``` + +Parameters: +- κ: mean-reversion speed +- a: long-run mean of ln(S) +- σ: log-volatility +- W(t): Q-Brownian motion under risk-free measure Q + +Under the standard pricing argument, the futures price F(t,T) is: + +``` +F(t,T) = E_t(S(T)) (460) +ln(F(t,T)) = E_t(X(T)) + (1/2) V_t(X(T)) (461) +``` + +This gives the closed-form futures price: + +``` +ln(F(t,T)) = exp(-κ(T-t)) X(t) + a[1 - exp(-κ(T-t))] + + (σ²/4κ)[1 - exp(-2κ(T-t))] (462) +``` + +**Calibration and trading:** +1. Fit κ, a, σ to historical data (e.g., nonlinear least squares on observed futures prices). +2. Compute the model-implied futures price for each contract. +3. Compare market price to model price: + - Market price > model price: **sell signal** (futures is rich) + - Market price < model price: **buy signal** (futures is cheap) + +Note: as κ → 0, a → ∞ with κa fixed, this model reduces to the Black-Scholes model. + +## Return Profile +Profits when market prices revert toward the model-implied fair values. Returns are driven by mean-reversion in the spread between market and model prices. In-sample fit may be strong but out-of-sample predictive power is model-dependent. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| κ | Mean-reversion speed; higher κ → faster reversion | +| a | Long-run mean of log-spot price | +| σ | Log-volatility of the spot price | +| F(t,T) model vs. market | Rich/cheap signal: sell if market > model, buy if market < model | + +## Variations +- **Multifactor models**: add stochastic convenience yield or stochastic volatility for richer term structure fitting. +- **Black-box / ML models**: fit any model with desirable qualitative properties (e.g., mean reversion) using machine learning, without explicit stochastic dynamics; valid as long as out-of-sample predictive power is demonstrated. +- Combine with roll-yield (Section 9.1) as a complementary signal. + +## Notes +- In-sample fit can be excellent even for models with poor predictive power; out-of-sample backtesting is essential (see Paschke and Prokopczuk, 2012). +- Model mis-specification risk: the true dynamics may not be OU; using a flexible model without theoretical grounding is equally valid if it works out-of-sample. +- Parameter instability: κ, a, σ estimated on historical data may shift during structural changes (supply shocks, geopolitical events). +- "Fancy does not equal better" — complex models do not necessarily outperform simple ones out-of-sample. diff --git a/gateway/knowledge/trading/strategies/commodities/roll-yields.md b/gateway/knowledge/trading/strategies/commodities/roll-yields.md new file mode 100644 index 00000000..8c3ec414 --- /dev/null +++ b/gateway/knowledge/trading/strategies/commodities/roll-yields.md @@ -0,0 +1,51 @@ +--- +description: "Commodity futures roll-yield strategy that goes long backwardated and short contangoed futures based on the ratio of front-month to second-month prices." +tags: [commodities, futures, roll-yield, term-structure, carry] +--- + +# Roll Yields + +**Section**: 9.1 | **Asset Class**: Commodities | **Type**: Carry / Term Structure + +## Overview +When commodity futures are in backwardation (downward-sloping term structure), long futures positions generate positive roll yield because as contracts approach expiry they roll up toward the higher spot price. In contango (upward-sloping term structure), the roll yield is negative. A zero-cost long-short portfolio can be constructed by going long commodities in backwardation and short those in contango. + +## Construction / Mechanics +Define the backwardation/contango ratio for each commodity: + +``` +φ = P₁ / P₂ (454) +``` + +where P₁ is the front-month futures price and P₂ is the second-month futures price. + +- φ > 1: backwardation (front-month > second-month); long futures position earns positive roll yield +- φ < 1: contango (front-month < second-month); short futures position earns positive roll yield + +**Portfolio construction:** +- Rank all N commodity futures by φ +- Buy futures with higher values of φ (stronger backwardation) +- Sell futures with lower values of φ (deeper contango) +- Dollar-neutral (zero-cost) implementation + +Roll yield is realised when the near-expiry contract is sold (covered) and a longer-dated contract is purchased, or vice versa for short positions. + +## Return Profile +Profits from the periodic rolling of positions: as a backwardated contract approaches expiry, its price converges upward to the spot, generating a positive roll return. In contango the opposite holds and short positions benefit. Roll yield is distinct from spot price returns. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| φ = P₁/P₂ | Backwardation ratio; φ > 1 → backwardation, φ < 1 → contango | +| Ranking quantile | Top/bottom quantile cut-off for long/short selection | +| Roll frequency | Determined by contract expiry calendar | + +## Variations +- Extend the ratio beyond the first two contracts to capture the broader term structure slope. +- Combine with hedging pressure (Section 9.2) or momentum signals for a multi-factor commodity strategy. + +## Notes +- Roll yields can be substantial in commodities with high storage costs (energy) or seasonal supply/demand patterns (agricultural). +- The ratio φ is a snapshot measure; persistent backwardation or contango is more reliable than transient conditions. +- Transaction costs from rolling (bid-ask spreads on each roll) must be weighed against the expected roll yield. +- Convenience yield (the benefit of holding physical inventory) is the economic driver of backwardation in many commodity markets. diff --git a/gateway/knowledge/trading/strategies/commodities/skewness-premium.md b/gateway/knowledge/trading/strategies/commodities/skewness-premium.md new file mode 100644 index 00000000..5f8bcf32 --- /dev/null +++ b/gateway/knowledge/trading/strategies/commodities/skewness-premium.md @@ -0,0 +1,55 @@ +--- +description: "Commodity futures strategy that captures the negative skewness premium by buying low-skewness and selling high-skewness commodity futures, exploiting the empirical negative relationship between return skewness and expected returns." +tags: [commodities, futures, skewness, premium, cross-sectional] +--- + +# Skewness Premium + +**Section**: 9.5 | **Asset Class**: Commodities | **Type**: Skewness / Risk Premium + +## Overview +There is an empirically observed negative correlation between the skewness of historical returns and future expected returns across commodity futures. Commodities with highly negatively skewed returns have, on average, higher future expected returns, while those with positively skewed returns have lower expected returns. This mirrors the skewness premium observed in equity options markets and reflects investor preference for positive skewness ("lottery" demand). + +## Construction / Mechanics +The skewness of returns for commodity i (i = 1,...,N) over T observations is: + +``` +S_i = (1 / (σ_i³ T)) Σ [R_is - R̄_i]³ (456) +``` + +where: + +``` +R̄_i = (1/T) Σ R_is (457) + +σ_i² = (1/(T-1)) Σ [R_is - R̄_i]² (458) +``` + +and R_is are the historical return observations. + +**Portfolio construction:** +- Rank all N commodity futures by S_i +- **Buy** futures in the **bottom quintile** by skewness (most negatively skewed, highest expected return) +- **Sell** futures in the **top quintile** by skewness (most positively skewed, lowest expected return) +- Zero-cost portfolio; rebalanced periodically + +## Return Profile +Profits when the negative skewness-expected return relationship holds out-of-sample: low-skewness (left-tail-heavy) commodities outperform high-skewness (right-tail-heavy) ones. The premium compensates investors for bearing left-tail (crash) risk. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| S_i | Third standardised moment of historical returns | +| T | Estimation window length (number of return observations) | +| Quintile cut-offs | Bottom quintile (buy) vs. top quintile (sell) | +| Rebalancing | Periodic (monthly or quarterly) | + +## Variations +- Use option-implied skewness (from commodity options) instead of realised skewness for a forward-looking signal. +- Combine with value (Section 9.4) or roll yield (Section 9.1) in a multi-factor commodity model. + +## Notes +- Realised skewness is estimated with substantial noise, particularly for commodities with short or infrequently traded histories. +- The skewness premium can be concentrated in a small number of time periods; the strategy may have poor risk-adjusted returns in normal markets and large gains during commodity stress events. +- Tail risk is inherent in this strategy: buying low-skewness commodities means accepting left-tail exposure. +- Sufficient sample size T is needed for reliable skewness estimates; skewness estimation requires more data than mean or variance estimation. diff --git a/gateway/knowledge/trading/strategies/commodities/value.md b/gateway/knowledge/trading/strategies/commodities/value.md new file mode 100644 index 00000000..03f5f958 --- /dev/null +++ b/gateway/knowledge/trading/strategies/commodities/value.md @@ -0,0 +1,52 @@ +--- +description: "Commodity value strategy that buys commodities whose current spot price is low relative to their spot price five years ago, and sells those with relatively high current prices." +tags: [commodities, value, mean-reversion, cross-sectional] +--- + +# Value + +**Section**: 9.4 | **Asset Class**: Commodities | **Type**: Value / Mean-Reversion + +## Overview +Analogous to the value strategy in equities (Section 3.3), the commodity value strategy is based on the premise that commodities with currently depressed prices relative to their historical levels are cheap and likely to revert upward, while those at elevated prices are expensive and likely to revert downward. The value ratio uses the 5-year-ago spot price as the benchmark for fair value. + +## Construction / Mechanics +The value signal for each commodity is defined as: + +``` +v = P₅ / P₀ (455) +``` + +where: +- P₅ is the spot price 5 years ago (alternatively, the average spot price between 4.5 and 5.5 years ago) +- P₀ is the current spot price + +A high v means the commodity is currently cheap relative to its 5-year-ago price (good value); a low v means the commodity is currently expensive. + +**Portfolio construction:** +- Rank all N commodity futures by v +- **Buy** futures in the top tercile by v (cheapest relative to 5-year history) +- **Sell** futures in the bottom tercile by v (most expensive relative to 5-year history) +- Rebalance monthly + +## Return Profile +Profits when commodity prices exhibit long-term mean reversion to their historical levels. The strategy is contrarian over a 5-year horizon, expecting that extreme deviations from historical prices will eventually correct. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| v = P₅/P₀ | Value ratio; high v → cheap (buy), low v → expensive (sell) | +| Look-back period | 5 years (or average between 4.5 and 5.5 years ago) | +| Portfolio terciles | Top tercile long, bottom tercile short | +| Rebalancing | Monthly | + +## Variations +- Use different look-back horizons (e.g., 3 years or 7 years) to capture different mean-reversion cycles. +- Combine value with momentum (e.g., buy commodities with high v AND positive recent momentum) to avoid "value traps". +- Apply to commodity sub-sectors (energy, metals, agriculture) separately to account for different structural price cycles. + +## Notes +- Commodity prices are subject to structural breaks (technological change, supply shocks) that can make historical prices poor benchmarks for fair value. +- The 5-year look-back is long enough to smooth business cycle effects but may include obsolete price regimes. +- Unlike equities, commodities have no earnings or book value; the purely price-based value measure has higher model risk. +- Roll costs from maintaining long futures positions in contangoed commodities can erode value-strategy returns. diff --git a/gateway/knowledge/trading/strategies/convertibles/convertible-arbitrage.md b/gateway/knowledge/trading/strategies/convertibles/convertible-arbitrage.md new file mode 100644 index 00000000..49e2d9a7 --- /dev/null +++ b/gateway/knowledge/trading/strategies/convertibles/convertible-arbitrage.md @@ -0,0 +1,44 @@ +--- +description: "Buy an undervalued convertible bond and short the underlying stock using a delta-based hedge ratio to capture the mispricing between the convertible's market price and its fair value." +tags: [convertibles, arbitrage] +--- + +# Convertible Arbitrage + +**Section**: 12.1 | **Asset Class**: Convertibles (Hybrid: Fixed Income + Equity) | **Type**: Arbitrage + +## Overview +A convertible bond is a hybrid security with an embedded option to convert the bond to a preset number of the issuer's shares (the conversion ratio) when the stock price reaches the conversion price. Empirically, convertibles at issuance tend to be undervalued relative to their fair value, creating arbitrage opportunities. The strategy buys the convertible bond and simultaneously shorts the underlying stock to hedge the equity exposure. + +## Construction / Mechanics +The hedge ratio (number of shares to short) is: + +``` +h = Δ × C (492) +Δ = ∂V/∂S (493) +``` + +- `C` = conversion ratio (number of shares per bond) +- `V` = value of the conversion option (model-dependent) +- `S` = underlying stock price +- `Δ` = option delta (model-dependent) + +The position is typically held for 6–12 months starting at the convertible's issuance date. The hedge ratio is updated daily as delta changes with the stock price. + +## Return Profile +Profits when the market price of the convertible converges toward its theoretical fair value. The long convertible position captures the undervaluation premium. The short stock position hedges directional equity risk, leaving exposure primarily to the convergence of the mispricing. + +## Key Parameters / Signals +- **Conversion ratio** `C`: fixed at issuance +- **Delta** `Δ = ∂V/∂S`: requires a model for the conversion option value `V`; changes daily with stock price `S` +- **Gamma hedging**: since delta itself changes with `S`, the option gamma can be used to refine dynamic hedging (see Section 7.4.1) +- **Entry timing**: position typically initiated at issuance when undervaluation is most pronounced + +## Variations +- **Gamma hedging overlay**: use gamma to dynamically adjust the hedge ratio as the stock moves, capturing additional convexity profits + +## Notes +- Hedge ratios are model-dependent; model risk is a key concern +- Nonparametric hedge estimation using historical data (constrained regression of MBS price P w.r.t. swap rate R) is an alternative to model-based delta +- Liquidity risk: convertible bonds are less liquid than the underlying stock +- Crowding risk: convertible arbitrage is a well-known strategy; forced unwinds by other funds can cause losses diff --git a/gateway/knowledge/trading/strategies/convertibles/convertible-oas.md b/gateway/knowledge/trading/strategies/convertibles/convertible-oas.md new file mode 100644 index 00000000..0827e6bf --- /dev/null +++ b/gateway/knowledge/trading/strategies/convertibles/convertible-oas.md @@ -0,0 +1,46 @@ +--- +description: "Simultaneously buy and sell two convertible bonds from the same issuer, long the higher option-adjusted spread and short the lower, profiting when the spreads converge." +tags: [convertibles, arbitrage, fixed-income] +--- + +# Convertible Option-Adjusted Spread (OAS) Arbitrage + +**Section**: 12.2 | **Asset Class**: Convertibles (Hybrid: Fixed Income + Equity) | **Type**: Relative Value / Arbitrage + +## Overview +This strategy simultaneously buys and sells two different convertible bonds issued by the same company. The long position is in the bond with the higher option-adjusted spread (OAS) and the short position is in the bond with the lower OAS. The trade is profitable when the two spreads converge toward each other. + +## Construction / Mechanics +The price of a convertible bond is decomposed as: + +``` +P_C = P_B + V (494) +``` + +- `P_C` = convertible bond price +- `P_B` = straight bond price (the bond without the embedded option), computed via standard discounting of future cash flows +- `V` = value of the conversion option (a call option on the issuer's stock) + +**OAS Calculation Procedure:** +1. At the initial iteration, compute `V^(0)` using a call option pricing model with the zero-coupon government Treasury curve as the risk-free rate +2. Check if `V^(0)` matches the market-implied option value `P_C^mkt - P_B` +3. If not, iteratively parallel-shift the Treasury curve (e.g., using bisection) until the computed `V` equals `P_C^mkt - P_B` +4. The parallel shift obtained is the OAS + +## Return Profile +Profits when the OAS of the long bond decreases (price rises) and/or the OAS of the short bond increases (price falls), i.e., when the two spreads converge. Returns are driven by relative mispricing between the two convertibles of the same issuer, not by the absolute level of spreads or interest rates. + +## Key Parameters / Signals +- **OAS differential**: the spread between the two bonds' OAS values; wider differential implies larger potential profit but also higher risk if divergence continues +- **Same-issuer requirement**: both bonds must be from the same issuer to neutralize credit risk +- **Convergence horizon**: the expected time for OAS convergence to occur + +## Variations +- **Multi-bond basket**: extend to a basket of convertibles from the same issuer, weighting by OAS rank +- **Cross-issuer OAS**: relax the same-issuer constraint and use credit hedges to neutralize issuer-level credit risk + +## Notes +- The OAS computation requires an option pricing model for `V`; model risk affects both legs +- The iterative parallel-shift procedure assumes the Treasury curve shape is fixed; actual curve shape changes can affect the OAS estimate +- Liquidity mismatch between the two convertible bonds can create mark-to-market losses even when the fundamental trade thesis is correct +- This strategy is distinct from straight convertible arbitrage (12.1): there is no stock short; both legs are bonds from the same issuer diff --git a/gateway/knowledge/trading/strategies/crypto/ann-strategy.md b/gateway/knowledge/trading/strategies/crypto/ann-strategy.md new file mode 100644 index 00000000..e21a629a --- /dev/null +++ b/gateway/knowledge/trading/strategies/crypto/ann-strategy.md @@ -0,0 +1,175 @@ +--- +description: "An artificial neural network (ANN) strategy that forecasts short-term BTC price movements using technical indicators (EMA, EMSD, RSI) as inputs and quantile-based classification as output." +tags: [crypto, machine-learning, ann, bitcoin, technical-analysis] +--- + +# Artificial Neural Network (ANN) Strategy + +**Section**: 18.2 | **Asset Class**: Cryptocurrencies | **Type**: Machine learning / Price prediction + +## Overview + +This strategy uses an ANN to forecast short-term movements of BTC price based on input technical indicators. Unlike equities, cryptocurrencies have no evident "fundamentals" on which to build value-based strategies, so cryptocurrency trading strategies tend to rely on trend data mining via machine learning techniques. The ANN classifies the future normalized return into quantile buckets and generates buy/sell signals accordingly. + +## Construction / Mechanics + +### Price and Return Normalization + +Let `P(t)` be the BTC price at time `t`, where `t = 1, 2, ...` is measured in some units (e.g., 15-minute intervals; `t = 1` is the most recent time). + +**Return:** +``` +R(t) = P(t)/P(t+1) - 1 (521) +``` + +**Serial mean return** over T₁ periods: +``` +R_bar(t, T₁) = (1/T₁) * sum_{t'=t+1}^{t+T₁} R(t') (523) +``` + +**Serially demeaned return:** +``` +R_tilde(t, T₁) = R(t) - R_bar(t, T₁) (522) +``` + +**Variance:** +``` +[sigma(t, T₁)]² = (1/(T₁-1)) * sum_{t'=t+1}^{t+T₁} [R_tilde(t', T₁)]² (525) +``` + +**Normalized (serially demeaned) return:** +``` +R_hat(t, T₁) = R_tilde(t, T₁) / sigma(t, T₁) (524) +``` + +For notational simplicity the T₁ parameter is omitted below and `R_hat(t)` denotes the normalized return. T₁ should be chosen long enough to provide a reasonable volatility estimate. + +### Input Layer: Technical Indicators + +**Exponential Moving Average (EMA):** +``` +EMA(t, lambda, tau) = ((1-lambda)/(1-lambda^tau)) * sum_{t'=t+1}^{t+tau} lambda^{t'-t-1} * R_hat(t') (526) +``` + +**Exponential Moving Standard Deviation (EMSD):** +``` +[EMSD(t, lambda, tau)]² = ((1-lambda)/(lambda - lambda^tau)) * sum_{t'=t+1}^{t+tau} lambda^{t'-t-1} * [R_hat(t') - EMA(t, lambda, tau)]² (527) +``` + +**Relative Strength Index (RSI):** +``` +RSI(t, tau) = nu_+(t, tau) / [nu_+(t, tau) + nu_-(t, tau)] (528) + +nu_±(t, tau) = sum_{t'=t+1}^{t+tau} max(±R_hat(t'), 0) (529) +``` + +Where: `tau` is the moving average length; `lambda` is the exponential smoothing parameter (to reduce parameters, one can set `lambda = (tau-1)/(tau+1)`). + +Typically RSI > 0.7 is interpreted as overbought; RSI < 0.3 as oversold. + +### Input Layer Construction + +The input layer consists of: +- `R_hat(t)` — the current normalized return +- `EMA(t, lambda_a, tau_a)` for `a = 1, ..., m` +- `EMSD(t, lambda_a, tau_a)` for `a = 1, ..., m` +- `RSI(t, tau_{a'})` for `a' = 1, ..., m'` + +Example parameter choices (from the literature): +- `tau_a` corresponding to 30 min, 1 hr, 3 hrs, 6 hrs (so `m = 4`) +- `tau_{a'}` corresponding to 3 hrs, 6 hrs, 12 hrs (so `m' = 3`) + +### Output Layer: Quantile Classification + +The objective is to forecast which quantile the future normalized return `R_hat(t)` will belong to. + +Let `K` be the number of quantiles. For training dataset `D_train`, compute the `(K-1)` quantile values `q_alpha`, `alpha = 1, ..., K-1`, of `R_hat(t)`, `t in D_train`. + +Define supervisory K-vectors `S_alpha(t)`, `alpha = 1, ..., K`: +``` +S_1(t) = 1, if R_hat(t) <= q_1 +S_alpha(t) = 1, if q_{alpha-1} <= R_hat(t) < q_alpha, for 1 < alpha < K (530) +S_K(t) = 1, if q_{K-1} <= R_hat(t) +S_alpha(t) = 0, otherwise +``` + +The output layer produces a nonnegative K-vector `p_alpha(t)` of class probabilities: +``` +sum_{alpha=1}^{K} p_alpha(t) = 1 (531) +``` + +### Network Architecture + +The ANN has `L` layers labeled `l = 1, ..., L`: +- `l = 1`: input layer +- `l = L`: output layer +- Intermediate layers: hidden layers + +At each layer `l`, there are `N^(l)` nodes with vectors `X_vec^(l)` having components `X_{i(l)}^(l)`: + +**Forward propagation:** +``` +X_{i(l)}^(l) = h_{i(l)}^(l)(Y_vec^(l)), l = 2, ..., L (532) + +Y_{i(l)}^(l) = sum_{j(l-1)=1}^{N^(l-1)} A_{i(l)j(l-1)}^(l) * X_{j(l-1)}^(l-1) + B_{i(l)}^(l) (533) +``` + +Where: `A_{i(l)j(l-1)}^(l)` are the weights; `B_{i(l)}^(l)` are the biases (both determined via training). + +**Activation functions:** + +Hidden layers use ReLU: +``` +h_{i(l)}^(l)(Y_vec^(l)) = max(Y_{i(l)}^(l), 0), l = 2, ..., L-1 (534) +``` + +Output layer uses softmax (ensuring probabilities sum to 1): +``` +h_{i(L)}^(L)(Y_vec^(L)) = Y_{i(L)}^(L) * [sum_{j(L)=1}^{N(L)} Y_{j(L)}^(L)]^{-1} (535) +``` + +ReLU fires a neuron only if `Y_{i(l)}^(l) > 0`; softmax enforces condition (531). + +### Training: Cross-Entropy Loss + +The error function to minimize is the cross-entropy: +``` +E = - sum_{t in D_train} sum_{alpha=1}^{K} S_alpha(t) * ln(p_alpha(t)) (536) +``` + +Minimized via stochastic gradient descent (SGD), which iterates until convergence. + +### Trading Signal + +``` +Signal = Buy, iff max(p_alpha(t)) = p_K(t) (537) + Sell, iff max(p_alpha(t)) = p_1(t) +``` + +The trader buys BTC if the predicted class is `p_K(t)` (the top quantile) and sells if it is `p_1(t)` (the bottom quantile). This rule can be modified — e.g., buy on top 2 quantiles and sell on bottom 2 quantiles. + +## Return Profile / Objective + +The strategy profits when the ANN correctly classifies the direction and magnitude of short-term BTC price movements. Returns are driven by the quality of the technical indicator signals and the ability of the trained network to generalize out-of-sample. Given BTC's high volatility, even modest directional accuracy can produce significant returns. + +## Key Parameters / Signals + +- `T₁`: lookback for return normalization (volatility estimation window) +- `tau_a`: EMA/EMSD lookback periods (e.g., 30 min, 1 hr, 3 hrs, 6 hrs) +- `tau_{a'}`: RSI lookback periods (e.g., 3 hrs, 6 hrs, 12 hrs) +- `lambda`: exponential smoothing factor; can be set to `(tau-1)/(tau+1)` +- `K`: number of quantile classes (e.g., K=2 for simple up/down) +- `N^(l)`: number of nodes at each hidden layer +- `L`: total number of layers +- `d_1`: number of most-recent time points excluded from training data to ensure all indicators are computed on sufficient data + +## Variations + +- **K=2 binary classification**: simple up/down forecast; buy/sell signal directly +- **K>2 multi-quantile**: more granular signal strength; trade only on extreme quantiles +- **Extended indicator set**: add MACD, Bollinger Bands, volume indicators to the input layer +- **LSTM/RNN variant**: replace feedforward ANN with recurrent architecture to better capture time-series dependencies + +## Notes + +The primary risk is overfitting: many free parameters (`tau_a`, `lambda_a`, `tau_{a'}`, `N^(l)`, `K`) must be chosen and the ever-present danger of overfitting various free parameters necessitates careful out-of-sample backtesting. The training dataset must exclude the most recent `d_1` time points to ensure all EMA, EMSD, and RSI values are computed using the required number of data points. This strategy is conceptually similar to the single-stock KNN trading strategy (Section 3.17) but uses ANN instead of k-nearest neighbors. No fundamental valuation of BTC is implied. diff --git a/gateway/knowledge/trading/strategies/crypto/sentiment-naive-bayes.md b/gateway/knowledge/trading/strategies/crypto/sentiment-naive-bayes.md new file mode 100644 index 00000000..7866a52d --- /dev/null +++ b/gateway/knowledge/trading/strategies/crypto/sentiment-naive-bayes.md @@ -0,0 +1,128 @@ +--- +description: "A naïve Bayes Bernoulli classifier applied to Twitter sentiment data to forecast BTC price direction, generating buy/sell signals from keyword-frequency feature vectors." +tags: [crypto, machine-learning, nlp, sentiment, bitcoin, naive-bayes] +--- + +# Sentiment Analysis — Naïve Bayes Bernoulli + +**Section**: 18.3 | **Asset Class**: Cryptocurrencies | **Type**: Machine learning / NLP sentiment + +## Overview + +This strategy applies a social media sentiment analysis classification scheme to forecast the direction (or quantile) of BTC price movements based on Twitter data. It uses the naïve Bayes Bernoulli model to classify tweets into outcome classes and generate trading signals. The premise is that aggregate social media sentiment contains predictive information about short-term crypto price movements. + +## Construction / Mechanics + +### Data Collection and Preprocessing + +1. Collect all tweets containing at least one keyword from a pertinent learning vocabulary `V` over some timeframe +2. Clean data: remove duplicate tweets from bots, remove stop-words (e.g., "the", "is", "in", "which"), perform stemming (reduce words to base forms, e.g., "investing" and "invested" → "invest") +3. Stemming can be performed using the Porter stemming algorithm + +Let: +- `M = |V|` = number of keywords in the learning vocabulary +- `N` = number of tweets in the dataset +- `i = 1, ..., N` labels tweets +- `a = 1, ..., M` labels words `w_a` in `V` + +### Feature Vector Construction (Bernoulli Model) + +Assign a feature M-vector `X_i` to each tweet `i`: + +**Bernoulli (binary presence/absence):** +``` +X_{ia} = 0 if word w_a not present in tweet T_i +X_{ia} = 1 if word w_a is present in tweet T_i (Bernoulli) +``` + +Alternative (multinomial): `X_{ia} = n_{ia}`, the number of times `w_a` appears in `T_i`. + +The Bernoulli case is the focus of this strategy. + +### Classification Framework + +Define `K` outcome classes `C_alpha`, `alpha = 1, ..., K`: +- Simplest case: `K = 2` (BTC goes up or down) — provides buy/sell signal +- Alternative: `K` quantiles of the normalized return `R_hat(t)` (as in the ANN strategy, Section 18.2) + +**Goal:** given the `N` feature vectors `X_1, ..., X_N`, predict class `C_alpha`. + +### Bayesian Foundation + +By Bayes' theorem: +``` +P(A|B) = P(B|A) * P(A) / P(B) (538) +``` + +The posterior probability of class `C_alpha` given features `X_1, ..., X_N`: +``` +P(C_alpha | X_1, ..., X_N) = P(X_1, ..., X_N | C_alpha) * P(C_alpha) / P(X_1, ..., X_N) (539) +``` + +Note `P(X_1, ..., X_N)` is independent of `C_alpha` and acts only as a normalization constant. + +### Naïve (Conditional Independence) Assumption + +The naïve Bayes simplification assumes that for a given class `C_alpha`, all features `X_i` are conditionally independent: +``` +P(X_i | C_alpha, X_1, ..., X_{i-1}, X_{i+1}, ..., X_N) = P(X_i | C_alpha) (540) +``` + +This gives: +``` +P(C_alpha | X_1, ..., X_N) = gamma * P(C_alpha) * prod_{i=1}^{N} P(X_i | C_alpha) (541) + +gamma = 1 / P(X_1, ..., X_N) (542) +``` + +### Bernoulli Likelihood + +For the Bernoulli model, the conditional probability of feature vector `X_i` given class `C_alpha`: +``` +P(X_i | C_alpha) = prod_{a=1}^{M} Q_{ia alpha} (543) +``` + +Where: +``` +Q_{ia alpha} = P(w_a | C_alpha), if X_{ia} = 1 (544) +Q_{ia alpha} = 1 - P(w_a | C_alpha), if X_{ia} = 0 (545) +``` + +The conditional probabilities `P(w_a | C_alpha)` are estimated from word occurrence frequencies in the training data. Similarly, `P(C_alpha)` is estimated from the training data class frequencies. + +### Prediction Rule + +Set the forecasted class `C_pred` to the one with maximum posterior probability: +``` +C_pred = argmax_{C_alpha in {1,...,K}} P(C_alpha) * prod_{i=1}^{N} prod_{a=1}^{M} [P(w_a | C_alpha)]^{X_{ia}} * [1 - P(w_a | C_alpha)]^{1 - X_{ia}} (546) +``` + +### Trading Signal + +- For `K = 2`: `C_pred = 1` → Sell; `C_pred = 2` → Buy (consistent with ANN signal convention) +- For `K` quantiles: trade on extreme quantile predictions analogously to the ANN strategy + +## Return Profile / Objective + +Returns are driven by the predictive content of Twitter sentiment about short-term BTC price direction. The strategy profits when aggregate social media tone (bullish vs. bearish language in the vocabulary) correlates with subsequent price movements. High crypto volatility means that even modest accuracy gains over random can generate meaningful returns. + +## Key Parameters / Signals + +- **Vocabulary `V`**: the set of keywords relevant to BTC price forecasting; quality of `V` critically affects performance +- **`K`**: number of outcome classes (2 for binary up/down, or quantile-based) +- **`M = |V|`**: vocabulary size; larger vocabulary increases model complexity and overfitting risk +- **Training window**: timeframe for estimating `P(C_alpha)` and `P(w_a | C_alpha)` +- **Stemming algorithm**: Porter or similar; affects effective vocabulary size +- **Stop-word list**: removal of common non-informative words reduces noise + +## Variations + +- **Multinomial naïve Bayes**: uses word count `n_{ia}` instead of binary presence; can better capture emphasis +- **Support vector machine (SVM)**: alternative classifier on the same feature vectors +- **Logistic regression**: another popular alternative to naïve Bayes for text classification +- **Tree boosting**: gradient boosting applied to tweet feature vectors for BTC direction prediction +- **Multi-source sentiment**: extend beyond Twitter to Reddit (r/bitcoin), news feeds, Telegram channels + +## Notes + +The naïve (conditional independence) assumption is rarely exactly true but often works well in practice for text classification. The key challenge is vocabulary construction — the learning vocabulary `V` must be chosen to be informative about BTC price movements specifically, not just generally related to Bitcoin. Laplace smoothing (adding a pseudo-count) is typically applied to avoid zero probabilities for words not observed in a given class. Compared to the ANN strategy, naïve Bayes is more interpretable and computationally cheaper to train. Social media strategies are vulnerable to coordinated manipulation (pumping sentiment with bots) and regime changes in platform usage patterns. diff --git a/gateway/knowledge/trading/strategies/distressed-assets/active-distressed-investing.md b/gateway/knowledge/trading/strategies/distressed-assets/active-distressed-investing.md new file mode 100644 index 00000000..a55711da --- /dev/null +++ b/gateway/knowledge/trading/strategies/distressed-assets/active-distressed-investing.md @@ -0,0 +1,50 @@ +--- +description: "Actively acquire distressed assets with the goal of obtaining management control, then drive reorganization through planning a restructuring, buying outstanding debt for equity conversion, or providing secured loans that convert to equity upon reorganization." +tags: [distressed-assets, credit, active-investing, private-equity] +--- + +# Active Distressed Investing + +**Section**: 15.2 | **Asset Class**: Distressed Assets | **Type**: Active / Control-Oriented + +## Overview +Unlike passive distressed debt buying (Section 15.1), active distressed investing aims to acquire sufficient ownership or control to influence the management and direction of the distressed company. When a company faces financial distress, it can file for Chapter 11 bankruptcy protection to reorganize under U.S. court supervision, or it can work directly with creditors outside of court. Active investors participate in or drive this reorganization process to generate returns. + +## Construction / Mechanics +The active investor accumulates a significant position in the distressed company's debt or equity to obtain standing and leverage in the reorganization process. Larger debt holders tend to submit more competitive reorganization plans. Three primary sub-strategies are described below (as Variations). + +## Return Profile +Returns are driven by the successful increase in the company's enterprise value through the reorganization process. Active investors can extract value through: +- Control of the reorganized entity +- Conversion of debt to equity at favorable terms +- Secured loan conversion to equity with control rights + +Returns can be very large but require significant legal, operational, and financial expertise. The investment horizon is typically multi-year. + +## Key Parameters / Signals +- **Debt claim size**: larger positions give more influence in Court and in out-of-court negotiations +- **Debt seniority**: senior secured creditors have more leverage; subordinated debt holders have less but more upside on equity conversion +- **Chapter 11 vs. out-of-court**: Chapter 11 provides a formal legal framework; out-of-court is faster but requires creditor consensus +- **Enterprise valuation**: ability to assess the reorganized company's value is critical to determine fair exchange ratios + +## Variations + +### 15.2.1 Planning a Reorganization +An investor submits a reorganization plan to Court with the objective of obtaining participation in the management of the company, increasing its value, and generating profits. Plans submitted by significant debt holders tend to be more competitive and are more likely to be approved by the Court and creditors. + +### 15.2.2 Buying Outstanding Debt +The investor buys outstanding debt of the distressed firm at a discount with the view that, after reorganization, part of this debt will be converted into the firm's equity, thereby giving the investor a certain level of control of the reorganized company. The discount at which debt is purchased represents the potential upside if the company's equity value post-reorganization exceeds the implied value in the purchase price. + +### 15.2.3 Loan-to-Own +The investor finances (via secured loans) a distressed firm that is not yet bankrupt, with the view that the firm either: +- (i) overcomes its distress, avoids bankruptcy, and increases its equity value (the secured loan is repaid at a premium), or +- (ii) files for Chapter 11 protection, upon reorganization the secured loan is converted into the firm's equity with control rights + +This strategy is particularly attractive when the investor believes the firm's assets are worth more under new management. + +## Notes +- Requires deep operational, legal, and financial restructuring expertise; typically executed by specialist hedge funds and private equity firms +- Intercreditor conflicts: multiple classes of creditors with competing interests can delay or complicate the reorganization +- Regulatory considerations: acquiring control of a company through debt conversion may trigger regulatory approvals (antitrust, industry-specific) +- Time horizon uncertainty: Chapter 11 cases can last from months to several years; secured loans may be tied up indefinitely if bankruptcy is protracted +- The "loan-to-own" strategy (15.2.3) has attracted regulatory scrutiny in some jurisdictions as potentially predatory toward the distressed borrower diff --git a/gateway/knowledge/trading/strategies/distressed-assets/buy-and-hold-distressed-debt.md b/gateway/knowledge/trading/strategies/distressed-assets/buy-and-hold-distressed-debt.md new file mode 100644 index 00000000..65d12c04 --- /dev/null +++ b/gateway/knowledge/trading/strategies/distressed-assets/buy-and-hold-distressed-debt.md @@ -0,0 +1,44 @@ +--- +description: "Passively buy a diversified portfolio of deeply discounted distressed debt (yield spread >1,000 bps over Treasuries) and hold through reorganization, expecting high returns on the subset of positions that recover." +tags: [distressed-assets, credit, fixed-income, value] +--- + +# Buying and Holding Distressed Debt (Passive) + +**Section**: 15.1 | **Asset Class**: Distressed Assets (Fixed Income / Credit) | **Type**: Value / Passive + +## Overview +Distressed securities are those whose issuers are undergoing financial or operational distress, default, or bankruptcy. A common definition of distressed debt is when the yield spread between the issuer's bonds and Treasury bonds exceeds a preset threshold (e.g., 1,000 basis points). This passive strategy buys distressed debt at a steep discount and holds it, expecting (hoping) the company will repay its debt. The portfolio is diversified across industries, entities, and debt seniority levels. + +## Construction / Mechanics +- **Definition**: distressed debt = yield spread over Treasuries > ~1,000 basis points +- **Diversification**: spread across industries, issuers, and debt seniority levels (senior secured, senior unsecured, subordinated) +- **Entry timing**: two common approaches: + 1. At the end of the default month + 2. At the end of the bankruptcy-filing month + — both aim to exploit overreaction in the distressed debt market at these key dates +- **Hold**: position is held passively through the reorganization/recovery process + +Passive strategies may also use models (see Section 15.3) to pre-screen assets and predict which companies are likely to declare bankruptcy, selecting only those positioned for successful reorganization. + +## Return Profile +Only a small fraction of held assets are expected to have positive returns, but those that do provide high rates of return (e.g., full par recovery from a deeply discounted purchase). Returns are highly skewed and non-normal. The driver of returns is successful company reorganization — either an out-of-court debt restructuring or a Chapter 11 bankruptcy reorganization. + +## Key Parameters / Signals +- **Yield spread threshold**: typically >1,000 bps over comparable-maturity Treasuries as a distress indicator +- **Entry timing**: end of default month or end of bankruptcy-filing month captures the overreaction premium +- **Debt seniority**: senior secured debt has higher recovery rates; subordinated debt offers higher upside if the company fully recovers +- **Industry and issuer diversification**: essential due to high idiosyncratic default risk; a single large default can dominate portfolio returns +- **Bankruptcy prediction models**: logistic regression or similar models on financial ratios to pre-screen for likely successful reorganizations (see Section 15.3) + +## Variations +- **Focus on defaults**: buy at the end of the default month, targeting market overreaction to default events +- **Focus on bankruptcy filings**: buy at the end of the bankruptcy-filing month, targeting overreaction to Chapter 11 filings +- **Seniority-focused**: concentrate in senior secured debt for higher recovery certainty (lower return, lower variance) + +## Notes +- Illiquidity: distressed debt is highly illiquid; exit before resolution may require large price concessions +- Workout timeline: bankruptcy proceedings can take years; capital is tied up for an uncertain duration +- Legal complexity: debt holders in bankruptcy proceedings face complex intercreditor disputes, cram-down risks, and professional fees +- Expected value of total portfolio is positive but heavily dependent on the few positions that recover fully +- This is a passive strategy — the investor does not seek to influence the reorganization process (contrast with Section 15.2) diff --git a/gateway/knowledge/trading/strategies/distressed-assets/distress-risk-puzzle.md b/gateway/knowledge/trading/strategies/distressed-assets/distress-risk-puzzle.md new file mode 100644 index 00000000..7640c252 --- /dev/null +++ b/gateway/knowledge/trading/strategies/distressed-assets/distress-risk-puzzle.md @@ -0,0 +1,58 @@ +--- +description: "Exploit the distress risk puzzle by going long the safest (lowest bankruptcy probability) stocks and short the riskiest, constructing a zero-cost HMD (healthy-minus-distressed) portfolio rebalanced monthly." +tags: [distressed-assets, equities, factor-investing, long-short] +--- + +# Distress Risk Puzzle + +**Section**: 15.3 | **Asset Class**: Distressed Assets (Equities) | **Type**: Factor / Long-Short + +## Overview +Early studies suggested that companies more prone to bankruptcy offer higher returns as a risk premium. However, more recent and robust studies find the opposite: distressed (high bankruptcy probability) companies do not outperform healthier ones, and healthier companies actually offer higher returns. This is the "distress risk puzzle." The strategy exploits it by buying the safest companies and selling the riskiest (a healthy-minus-distressed, or HMD, zero-cost long-short portfolio). + +## Construction / Mechanics +1. **Estimate bankruptcy probability** `P_i` for each stock `i = 1, ..., N` using, e.g., logistic regression on financial variables: + ``` + logit(P_i) = β_0 + β_1 × (leverage) + β_2 × (profitability) + ... + ``` +2. **Sort stocks** into deciles by `P_i` +3. **Construct zero-cost portfolio**: + - **Short** the top decile (highest `P_i` — most distressed) + - **Long** the bottom decile (lowest `P_i` — healthiest) +4. **Rebalance** monthly (annual rebalancing produces similar returns) + +## Return Profile +The HMD portfolio profits when healthy stocks outperform distressed stocks, which empirical evidence suggests happens persistently. Returns are driven by the cross-sectional spread in returns between the safest and riskiest firms. The strategy has equity-like volatility and is exposed to periods of market stress. + +## Key Parameters / Signals +- **Bankruptcy probability `P_i`**: core signal; modeled via logistic regression or other classification methods on financial variables (leverage, profitability, coverage ratios, market-to-book, etc.) +- **Decile cutoffs**: top and bottom decile are standard; tighter cutoffs increase signal strength but reduce breadth +- **Rebalancing frequency**: monthly is standard; annual rebalancing yields similar returns with lower turnover + +## Variations + +### 15.3.1 Distress Risk Puzzle — Risk Management +The standard HMD strategy has a high time-varying market beta that turns significantly negative following market downturns (associated with increased volatility). This can cause large losses when the market rebounds abruptly. To mitigate this, a volatility-scaled version is used: + +``` +HMD* = (σ_target / σ_hat) × HMD (519) +``` + +- `HMD` = standard HMD portfolio return (from Section 15.3) +- `σ_target` = target volatility level, typically 10%–15% (set per trader preferences) +- `σ_hat` = estimated realized volatility over the prior year using daily data + +**Interpretation**: +- If `σ_hat = σ_target`: 100% of the investment is allocated +- If `σ_hat > σ_target`: allocation is reduced below 100% (de-leverage in high-vol regimes) +- If `σ_hat < σ_target`: allocation exceeds 100% (leverage in low-vol regimes) + +Alternatively, the allocation can be capped at 100% (`min(σ_target / σ_hat, 1)`) to avoid leverage entirely. + +## Notes +- The distress risk puzzle is a well-documented anomaly but its persistence is debated; it may partly reflect data-mining or survivorship bias +- The HMD strategy has high time-varying beta to the equity market; risk management via volatility scaling (15.3.1) is essential for production use +- Bankruptcy probability models require regular recalibration; financial ratios used as inputs are sensitive to accounting changes +- Short-selling the most distressed stocks can be expensive (high borrow costs) and difficult (low float, high short interest) +- Regulatory restrictions on short selling may limit implementation in certain markets or during market stress periods +- Similar time-varying beta behavior is observed in other factor-based strategies (momentum, value, etc.), suggesting a common structural risk diff --git a/gateway/knowledge/trading/strategies/etfs/alpha-rotation.md b/gateway/knowledge/trading/strategies/etfs/alpha-rotation.md new file mode 100644 index 00000000..e551177c --- /dev/null +++ b/gateway/knowledge/trading/strategies/etfs/alpha-rotation.md @@ -0,0 +1,46 @@ +--- +description: "Rotates into sector ETFs with the highest Jensen's alpha estimated from a Fama-French factor regression, replacing raw cumulative return momentum with factor-adjusted alpha as the ranking signal." +tags: [etfs, alpha, momentum, fama-french, rotation] +--- + +# Alpha Rotation + +**Section**: 4.2 | **Asset Class**: ETFs | **Type**: Momentum / Factor-Adjusted Rotation + +## Overview +Alpha rotation is structurally the same as the sector momentum rotation strategy (Section 4.1), but replaces cumulative ETF returns `R_i^cum` with ETF alphas `alpha_i`. These alphas are the Jensen's alpha regression coefficients from a serial regression of each ETF's returns on the Fama-French factors, representing the ETF's return unexplained by common risk factors. + +## Construction / Signal +Run a serial regression of ETF returns `R_i(t)` on the 3 Fama-French factors (MKT, SMB, HML): + +``` +R_i(t) = alpha_i + beta_{1,i} MKT(t) + beta_{2,i} SMB(t) + beta_{3,i} HML(t) + epsilon_i(t) (364) +``` + +The regression coefficient `alpha_i` (Jensen's alpha) corresponds to the intercept and measures the ETF's risk-adjusted excess return relative to the Fama-French model. This alpha replaces `R_i^cum` as the ranking criterion. + +ETFs are ranked by `alpha_i` (descending). Buy top-decile ETFs (highest alpha) and optionally short bottom-decile ETFs (lowest/most-negative alpha). + +## Entry / Exit Rules +- **Entry**: At rebalance, estimate alpha for each ETF over the estimation period; rank and enter positions in top-decile (long) and optionally bottom-decile (short). +- **Exit**: Hold for the standard holding period; rebalance at next scheduled interval. +- **Estimation period**: Typically 1 year; returns `R_i(t)` are daily or weekly. + +## Key Parameters +- **Factor model**: 3 Fama-French factors (MKT, SMB, HML); note alpha here is Jensen's alpha for ETF returns, not mutual fund alpha +- **Estimation period**: Typically 1 year +- **Return frequency for regression**: Daily or weekly `R_i(t)` +- **Holding period**: Same as sector momentum rotation (1–3 months) +- **Ranking criterion**: `alpha_i` (intercept of Fama-French regression) + +## Variations +- **4-factor model**: Add Carhart momentum factor MOM(t) to regression for a 4-factor alpha +- **R-squared augmentation**: Combine alpha ranking with R-squared selectivity measure (see Section 4.3) +- **Long-only**: Buy only top-decile ETFs by alpha + +## Notes +- Estimation period is typically 1 year with daily or weekly return data. +- Jensen's alpha here is defined for ETF returns (not mutual fund returns as in Jensen, 1968). +- Alpha rotation is analytically cleaner than raw momentum rotation as it removes systematic factor exposures from the ranking signal. +- The MA filter and dual-momentum variations from Section 4.1.1 and 4.1.2 can also be applied here. +- Can be combined with R-squared (Section 4.3) to further refine ETF selection. diff --git a/gateway/knowledge/trading/strategies/etfs/leveraged-etfs.md b/gateway/knowledge/trading/strategies/etfs/leveraged-etfs.md new file mode 100644 index 00000000..1818583f --- /dev/null +++ b/gateway/knowledge/trading/strategies/etfs/leveraged-etfs.md @@ -0,0 +1,49 @@ +--- +description: "Exploits the negative drift of leveraged ETF pairs by simultaneously shorting both a leveraged ETF and its inverse counterpart tracking the same index, capturing decay from daily rebalancing compounding." +tags: [etfs, leveraged-etf, letf, short-volatility, decay] +--- + +# Leveraged ETFs (LETFs) + +**Section**: 4.5 | **Asset Class**: ETFs | **Type**: Short-Volatility / Structural Decay + +## Overview +A leveraged (or inverse) ETF seeks to deliver a fixed multiple (2x, 3x) or the inverse (-1x, -2x, -3x) of the daily return of its underlying index. To maintain the target daily leverage, LETFs must rebalance every day — buying when the market is up and selling when it is down. This daily rebalancing creates a negative drift (volatility decay) in the long run, which can be exploited by shorting both a leveraged ETF and its corresponding leveraged inverse ETF on the same underlying index. + +## Construction / Signal +A leveraged ETF with leverage factor L rebalances daily to maintain L × (daily index return). This requires: +- **On up days**: Buy more of the underlying index +- **On down days**: Sell the underlying index + +The compounding of daily returns with daily rebalancing creates a path-dependent negative drift over time: + +``` +LETF cumulative return < L × (index cumulative return) [for L > 1 or L < -1] +``` + +**Strategy**: Short both a leveraged ETF (e.g., 2x) and its leveraged inverse ETF (-2x) on the same underlying index. Both positions decay in value over time due to daily rebalancing, generating profit from the combined negative drift. + +Proceeds from both short positions can be invested in an uncorrelated asset (e.g., a Treasury ETF). + +## Entry / Exit Rules +- **Entry**: Simultaneously short a leveraged ETF (e.g., 2x long) and its corresponding inverse leveraged ETF (e.g., 2x inverse) on the same underlying index. +- **Exit**: Positions are held as long as both ETFs continue to decay; may require periodic rebalancing of the short pair as relative prices change. +- **Capital deployment**: Invest the short proceeds into a Treasury ETF or other low-risk asset. + +## Key Parameters +- **Leverage factor**: 2x or 3x (and their -2x or -3x inverses) +- **Underlying index**: Same index for both the leveraged and inverse leveraged ETF +- **Rebalancing of short pair**: Periodically rebalance the short positions to maintain equal dollar exposure +- **Volatility regime**: Decay is larger in high-volatility regimes + +## Variations +- **3x pair**: Short a 3x leveraged ETF and its -3x inverse (higher decay, higher risk) +- **Single-leg short**: Short only the leveraged (not inverse) ETF when directional bias exists +- **Volatility regime filter**: Enter positions only in high-volatility environments where decay is expected to be larger + +## Notes +- The negative drift from daily rebalancing is mathematically guaranteed over time for both the leveraged and inverse ETF, making this a structural (not purely alpha-dependent) source of return. +- **Key risk**: In the short term, if one leg of the short pair (e.g., the inverse ETF) has a large positive return (the market rallies strongly), the short position in the inverse ETF suffers a sizable loss. This short-term risk can be significant even though the long-term drift is negative. +- The strategy can have a significant downside in the short term if one short leg moves sharply against the position. +- Transaction costs (borrow costs for short selling LETFs, bid-ask spreads) must be carefully considered; LETF borrow rates can be elevated. +- Volatility decay is proportional to variance: approximately `L(L-1)/2 × sigma^2` per period for a leverage factor L. diff --git a/gateway/knowledge/trading/strategies/etfs/mean-reversion.md b/gateway/knowledge/trading/strategies/etfs/mean-reversion.md new file mode 100644 index 00000000..28805ebe --- /dev/null +++ b/gateway/knowledge/trading/strategies/etfs/mean-reversion.md @@ -0,0 +1,57 @@ +--- +description: "Constructs a dollar-neutral ETF portfolio by selling ETFs with high Internal Bar Strength (IBS, close near daily high) and buying ETFs with low IBS (close near daily low), exploiting short-term mean-reversion." +tags: [etfs, mean-reversion, ibs, internal-bar-strength] +--- + +# Mean-Reversion (ETFs) + +**Section**: 4.4 | **Asset Class**: ETFs | **Type**: Mean-Reversion + +## Overview +This strategy applies mean-reversion to ETFs using the Internal Bar Strength (IBS) indicator, derived from the previous day's close, high, and low prices. ETFs with a close near their daily high (high IBS) are considered "rich" and likely to revert downward; ETFs with a close near their daily low (low IBS) are "cheap" and likely to revert upward. A dollar-neutral portfolio sells high-IBS ETFs and buys low-IBS ETFs. + +## Construction / Signal +**Internal Bar Strength (IBS)**: +``` +IBS = (P_C - P_L) / (P_H - P_L) (370) +``` + +Where: +- `P_C` = previous day's closing price +- `P_H` = previous day's high price +- `P_L` = previous day's low price + +IBS ranges from 0 to 1: +- IBS close to 1: price closed near the daily high → ETF is "rich" +- IBS close to 0: price closed near the daily low → ETF is "cheap" + +An equivalent symmetric measure: `Y = IBS - 1/2 = (P_C - P_*) / (P_H - P_L)` where `P_* = (P_H + P_L) / 2`; Y ranges from -1/2 to +1/2. + +**Portfolio construction**: +- Sort ETFs cross-sectionally by IBS. +- Sell ETFs in the top decile (high IBS, "rich"). +- Buy ETFs in the bottom decile (low IBS, "cheap"). +- Dollar-neutral construction. + +## Entry / Exit Rules +- **Entry**: Each day after the close, compute IBS for all ETFs, rank, and enter positions for the next day's open or close. +- **Exit**: Typically hold for 1 day (short-term mean-reversion); close at next day's close. +- **Rebalance**: Daily. + +## Key Parameters +- **IBS computation**: Daily, using previous day's high, low, and close +- **Holding period**: Short-term (typically 1 day) +- **Portfolio construction**: Dollar-neutral long/short decile +- **Weights**: Uniform for all long and all short ETFs, or volatility-weighted + +## Variations +- **Volatility-weighted positions**: Weight positions by historical ETF volatility rather than equal-weighting +- **Stock mean-reversion methods**: Mean-reversion strategies from Section 3 (cluster, weighted regression) can also be adapted to ETFs +- **IBS threshold**: Instead of top/bottom decile, use a fixed IBS threshold (e.g., IBS > 0.8 = short, IBS < 0.2 = long) + +## Notes +- IBS is a simple, daily-bar indicator requiring only OHLC (open-high-low-close) data. +- Mean-reversion in ETFs can be stronger than in individual stocks because ETFs represent diversified baskets where idiosyncratic volatility is reduced, and market-maker arbitrage constrains large deviations from NAV. +- Holding period is very short (1 day); transaction costs can be significant for daily rebalancing. +- The strategy can be combined with other signals (e.g., sector momentum) for confirmation. +- All stock-based mean-reversion strategies (clusters, weighted regression) can be adapted for ETF universes. diff --git a/gateway/knowledge/trading/strategies/etfs/multi-asset-trend-following.md b/gateway/knowledge/trading/strategies/etfs/multi-asset-trend-following.md new file mode 100644 index 00000000..98fa1810 --- /dev/null +++ b/gateway/knowledge/trading/strategies/etfs/multi-asset-trend-following.md @@ -0,0 +1,70 @@ +--- +description: "Builds a long-only trend-following portfolio across multiple asset classes using ETFs, allocating weights proportional to cumulative momentum and optionally risk-adjusted by historical volatility, with an optional MA filter." +tags: [etfs, trend-following, multi-asset, momentum, long-only] +--- + +# Multi-Asset Trend Following + +**Section**: 4.6 | **Asset Class**: ETFs | **Type**: Trend-Following / Multi-Asset + +## Overview +ETFs allow efficient diversification across sectors, countries, asset classes, and factors in a relatively small number of instruments. This strategy constructs a long-only trend-following portfolio across multiple ETFs (and thus multiple asset classes) by allocating weights based on cumulative momentum, optionally filtered by a moving average, and weighted by historical volatility to manage risk. + +## Construction / Signal +**Step 1 — Compute cumulative returns** over a T-month formation period (T = 6–12 months): +``` +R_i^cum = P_i(t) / P_i(t+T) - 1 +``` + +**Step 2 — Filter**: Keep only ETFs with positive `R_i^cum` (positive momentum required for long-only). + +**Step 3 — Optional MA filter**: Additionally keep only ETFs whose last closing price P_i exceeds their moving average MA_i(T') (typically T' = 100–200 days): +``` +P_i > MA_i(T') +``` + +**Step 4 — Assign weights** to all surviving ETFs (not just top decile, since the universe is small): + +Option A — proportional to cumulative return: +``` +w_i = gamma_1 * R_i^cum (371) +``` + +Option B — momentum divided by volatility (Sharpe-like weighting): +``` +w_i = gamma_2 * R_i^cum / sigma_i (372) +``` + +Option C — momentum divided by variance (Sharpe ratio optimization for diagonal covariance): +``` +w_i = gamma_3 * R_i^cum / sigma_i^2 (373) +``` + +where `sigma_i` is historical ETF volatility and normalization coefficients `gamma_1`, `gamma_2`, `gamma_3` are computed to satisfy `sum_{i=1}^{N} w_i = 1` (N = number of ETFs with nonzero weights after filtering). + +Option C (Eq. 373) optimizes the Sharpe ratio of the ETF portfolio assuming a diagonal covariance matrix `C_ij = diag(sigma_i^2)` (ignoring cross-ETF correlations). + +## Entry / Exit Rules +- **Entry**: At each rebalance, apply momentum and MA filters, compute weights, and enter long positions in all surviving ETFs. +- **Exit**: Rebalance monthly (or per the formation period schedule); ETFs with negative cumulative momentum or below their MA are dropped (weight set to zero). +- **Position cap**: Bounds `w_i <= w_i^max` can be imposed to prevent overweighting of any single volatile ETF. + +## Key Parameters +- **Formation period T**: 6–12 months +- **MA filter length T'**: 100–200 days (optional; aligns with sector momentum rotation MA filter) +- **Weighting scheme**: Equal (Eq. 371), volatility-adjusted (Eq. 372), or variance-adjusted/Sharpe-optimal (Eq. 373) +- **Position cap**: Maximum weight per ETF (optional; mitigates concentration risk) +- **Holding period**: Monthly rebalancing typical + +## Variations +- **No MA filter**: Use only positive cumulative return filter +- **With position caps**: Add `w_i <= w_i^max` to prevent overweighting high-momentum volatile ETFs +- **Sector rotation overlay**: Combine with sector momentum rotation (Section 4.1) by restricting the universe to top-ranked sectors + +## Notes +- Eq. (371) is the simplest weighting; it overweights volatile ETFs since on average `R_i^cum ∝ sigma_i`. +- Eq. (372) mitigates volatility overweighting by dividing by sigma_i. +- Eq. (373) is the optimal Sharpe ratio solution under the assumption of uncorrelated (diagonal covariance) ETF returns. +- The key advantage of ETFs for multi-asset trend following: a small number of instruments (tens of ETFs) can provide exposure to many asset classes, sectors, geographies, and factors simultaneously. +- Long-only construction avoids shorting complexity; the MA filter prevents buying ETFs in absolute downtrends even if they have relative momentum. +- For some literature on multi-asset portfolios, dynamic asset allocation, and related topics: Bekkers, Doeswijk and Lam (2009), Black and Litterman (1992), Faber (2015, 2016), Mladina (2014). diff --git a/gateway/knowledge/trading/strategies/etfs/r-squared.md b/gateway/knowledge/trading/strategies/etfs/r-squared.md new file mode 100644 index 00000000..d6c0d8a7 --- /dev/null +++ b/gateway/knowledge/trading/strategies/etfs/r-squared.md @@ -0,0 +1,63 @@ +--- +description: "Overweights ETFs with high selectivity (low R-squared against factor model) and high alpha, and underweights ETFs with low selectivity (high R-squared), using a two-dimensional sort on R-squared and alpha." +tags: [etfs, r-squared, alpha, selectivity, factor-model] +--- + +# R-Squared + +**Section**: 4.3 | **Asset Class**: ETFs | **Type**: Factor-Based / Selectivity + +## Overview +Empirical studies suggest that augmenting Jensen's alpha with an indicator based on R-squared from a factor model regression adds predictive value for future ETF returns. R-squared measures how much of an ETF's return variance is explained by common factors; low R-squared (high "selectivity") combined with high alpha predicts strong future performance. High R-squared (low selectivity) combined with low alpha predicts weak future performance. + +## Construction / Signal +Run a serial regression of ETF returns `R_i(t)` on 4 factors (Fama-French 3 + Carhart momentum): + +``` +R_i(t) = alpha_i + beta_{1,i} MKT(t) + beta_{2,i} SMB(t) + beta_{3,i} HML(t) + beta_{4,i} MOM(t) + epsilon_i(t) (365) +``` + +Compute regression R-squared: +``` +R^2 = 1 - SS_res / SS_tot (366) + +SS_res = sum_{i=1}^{N} epsilon_i(t)^2 (367) + +SS_tot = sum_{i=1}^{N} (R_i(t) - R_bar(t))^2 (368) + +R_bar(t) = (1/N) * sum_{i=1}^{N} R_i(t) (369) +``` + +**Selectivity** = `1 - R^2` [Amihud and Goyenko, 2013]. High selectivity = low R-squared = returns less explained by common factors. + +**Two-dimensional sort strategy**: +1. Sort ETFs into quintiles by R-squared (5 groups). +2. Within each R-squared quintile, sort ETFs into sub-quintiles by alpha (5 sub-groups). +3. This creates 25 groups of ETFs. +4. **Buy** ETFs in the group with lowest R-squared quintile and highest alpha sub-quintile. +5. **Sell** ETFs in the group with highest R-squared quintile and lowest alpha sub-quintile. + +## Entry / Exit Rules +- **Entry**: At rebalance, run regression, compute R-squared and alpha for each ETF, perform 5×5 sort, enter long/short positions. +- **Exit**: Hold for estimation period or holding period; rebalance periodically. +- **Estimation period**: Same as alpha rotation (typically 1 year); longer estimation periods can be used, especially for monthly returns. + +## Key Parameters +- **Factor model**: 4-factor (Fama-French 3 + Carhart MOM); 3-factor also usable +- **Estimation period**: Typically 1 year; can be longer for monthly return data +- **Sort dimensions**: R-squared quintiles × alpha sub-quintiles (5×5 = 25 groups) +- **Holding period**: Similar to alpha rotation strategy (1–3 months) +- **Selectivity definition**: `1 - R^2` + +## Variations +- **3-factor model**: Use Fama-French 3 factors without momentum factor MOM +- **Different quintile splits**: Use deciles instead of quintiles for finer grouping +- **R-squared only**: Sort purely by R-squared without the alpha sub-sort +- **Estimation period alignment**: Use same estimation period as alpha rotation strategy (Section 4.2) for consistency + +## Notes +- R-squared as a measure of active management: in Amihud and Goyenko (2013), R-squared is applied to mutual funds; Garyn-Tal (2014a, 2014b) applies it to actively managed ETFs. +- Low R-squared means the ETF has high "active share" — its returns are driven more by the manager's specific bets than by passive factor exposure. +- The estimation period and return frequency for R-squared can be the same as for alpha rotation (see Section 4.2 and fn. 77). +- Longer estimation periods are particularly appropriate if R_i(t) are monthly returns. +- Can be combined with the MA filter (Section 4.1.1) as an additional condition. diff --git a/gateway/knowledge/trading/strategies/etfs/sector-momentum-rotation.md b/gateway/knowledge/trading/strategies/etfs/sector-momentum-rotation.md new file mode 100644 index 00000000..e4fa012b --- /dev/null +++ b/gateway/knowledge/trading/strategies/etfs/sector-momentum-rotation.md @@ -0,0 +1,74 @@ +--- +description: "Overweights ETFs from outperforming sectors and underweights those from underperforming sectors based on T-month cumulative return momentum, with optional MA filter and dual-momentum variants." +tags: [etfs, momentum, sector-rotation] +--- + +# Sector Momentum Rotation + +**Section**: 4.1 / 4.1.1 / 4.1.2 | **Asset Class**: ETFs | **Type**: Momentum / Sector Rotation + +## Overview +Empirical evidence shows that the momentum effect exists not only for individual stocks but also for sectors and industries. The sector momentum rotation strategy overweights ETFs from outperforming sectors and underweights those from underperforming sectors, using ETFs concentrated in specific sectors/industries to implement sector/industry rotation without buying or selling large numbers of underlying stocks. + +## Construction / Signal +Similarly to stock price-momentum (Section 3.1), use each sector ETF's cumulative return as the momentum measure. Let `P_i(t)` be the price of ETF labeled by i: + +``` +R_i^cum(t) = P_i(t) / P_i(t + T) - 1 (361) +``` + +Here `t + T` is T months in the past w.r.t. t. After time t, buy ETFs in the top decile by `R_i^cum(t)` and hold for a holding period (typically 1–3 months). + +**Dollar-neutral construction**: Buy top-decile ETFs and short bottom-decile ETFs (ETFs can be shorted). + +**Long-only construction**: Buy only top-decile ETFs, equal-weight or volatility-weight. + +## Entry / Exit Rules +- **Entry**: At rebalance, rank all sector ETFs by cumulative return `R_i^cum`; buy top-decile, optionally short bottom-decile. +- **Exit**: Hold for 1–3 months; rebalance at the next scheduled interval. +- **Formation period T**: Typically 6–12 months. + +## Key Parameters +- **Formation period T**: 6–12 months +- **Holding period**: 1–3 months +- **Portfolio construction**: Long-only (top decile) or dollar-neutral (top long, bottom short) +- **Weights**: Uniform or volatility-adjusted + +## Variations + +### 4.1.1 — Sector Momentum Rotation with MA Filter + +A refinement that requires an ETF to pass a moving average filter before entering a position, preventing buys in sectors with downward price trends even if they rank high by relative momentum. + +``` +Rule = { Buy top-decile ETFs only if P > MA(T') + { Short bottom-decile ETFs only if P < MA(T') (362) +``` + +- `P` = ETF's current price at transaction time +- `MA(T')` = moving average of ETF's daily prices over T' days (T' can differ from formation period T; typically T' = 100–200 days) + +This ensures the absolute price level (trend) also supports the trade direction. + +### 4.1.2 — Dual-Momentum Sector Rotation + +In long-only strategies, mitigates the risk of buying sector ETFs when the broad market is trending down. Augments relative (cross-sectional) momentum with absolute (time-series) momentum of a broad market index ETF: + +``` +Rule = { Buy top-decile ETFs if broad market P > MA(T') + { Buy an uncorrelated ETF (e.g., gold, Treasury) if broad market P <= MA(T') (363) +``` + +- `P` = broad market index ETF's price at transaction time +- `MA(T')` = moving average of the broad market index ETF's price; typically T' = 100–200 days + +If the broad market is below its moving average (downtrend), capital is rotated into an ETF uncorrelated with the broad market (e.g., gold or Treasury ETF) instead of sector ETFs. + +Reference: Antonacci (2014, 2017). + +## Notes +- ETF-based sector rotation is simpler to implement than stock-level sector rotation: one ETF trade per sector instead of dozens of stock trades. +- The MA filter (4.1.1) reduces the chance of buying momentum in a sector that is in absolute decline. +- Dual-momentum (4.1.2) addresses the long-only strategy's vulnerability to broad market drawdowns. +- Typical formation period: 6–12 months; typical holding period: 1–3 months. +- Dollar-neutral construction removes broad market exposure but requires shorting ETFs (feasible in practice). diff --git a/gateway/knowledge/trading/strategies/fixed-income/barbells.md b/gateway/knowledge/trading/strategies/fixed-income/barbells.md new file mode 100644 index 00000000..5345cbe4 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/barbells.md @@ -0,0 +1,50 @@ +--- +description: "A barbell portfolio holds bonds at two extreme maturities (short and long) to achieve a target duration while gaining higher convexity than an equivalent bullet, providing better protection against parallel yield curve shifts." +tags: [fixed-income, duration, convexity, barbell, yield-curve] +--- + +# Barbells + +**Section**: 5.3 | **Asset Class**: Fixed Income | **Type**: Duration / Convexity + +## Overview +A barbell concentrates holdings at two maturities: a short maturity T_1 and a long maturity T_2. It is a combination of two bullet strategies. For a given modified duration (matching a bullet at intermediate maturity T_*), the barbell achieves higher convexity, providing better protection against parallel yield shifts at the cost of lower overall yield. + +## Construction / Mechanics +For a simple barbell of w_1 dollars in zero-coupon bonds with maturity T_1 and w_2 dollars with maturity T_2 (continuous compounding, constant yield Y), with price-adjusted weights w̃_1 = w_1·exp(-T_1·Y) and w̃_2 = w_2·exp(-T_2·Y): + +**Duration** (equals a bullet at T_*): +``` +D = (w̃_1·T_1 + w̃_2·T_2) / (w̃_1 + w̃_2) (390) +T_* = D_* = D (391) +``` + +**Convexity** (exceeds the equivalent bullet): +``` +C = (w̃_1·T_1² + w̃_2·T_2²) / (w̃_1 + w̃_2) (392) +C_* = T_*² (393) +``` + +The convexity advantage: +``` +C - C_* = (w̃_1·w̃_2 / (w̃_1 + w̃_2)²) · (T_2 - T_1)² > 0 (394) +``` + +## Payoff / Return Profile +- Higher convexity than an equivalent bullet means the barbell outperforms when yields move significantly in either direction (parallel shifts). +- The long-maturity bonds benefit from high yields; the short-maturity bonds provide protection if rates rise (proceeds reinvested at higher rates). +- Flattening of the yield curve (short-term rates rise relative to long-term) has a positive impact; steepening has a negative impact. + +## Key Parameters / Signals +- T_1 (short maturity), T_2 (long maturity): the two maturities defining the barbell +- w_1, w_2: dollar allocations to short and long maturities +- Target duration D: matched to the equivalent bullet at T_* +- Convexity advantage C - C_*: larger the spread T_2 - T_1, the greater the convexity benefit + +## Variations +- Combine with duration matching to an intermediate bullet for controlled rate exposure. + +## Notes +- Higher convexity comes at the expense of lower overall yield (yield curve typically slopes upward, so the mid-point bullet earns more carry). +- Duration scales approximately linearly with maturity; convexity scales quadratically — this is why the barbell's convexity exceeds the equivalent bullet. +- The barbell is more complex to manage than a bullet due to two distinct maturity exposures. diff --git a/gateway/knowledge/trading/strategies/fixed-income/bond-immunization.md b/gateway/knowledge/trading/strategies/fixed-income/bond-immunization.md new file mode 100644 index 00000000..1b797604 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/bond-immunization.md @@ -0,0 +1,66 @@ +--- +description: "Bond immunization constructs a portfolio whose duration matches a future cash obligation's maturity, protecting the portfolio value against parallel yield curve shifts to meet a predetermined liability." +tags: [fixed-income, duration, immunization, liability-matching, convexity] +--- + +# Bond Immunization + +**Section**: 5.5 | **Asset Class**: Fixed Income | **Type**: Duration / Liability Matching + +## Overview +Bond immunization is used to ensure a portfolio can meet a predetermined future cash obligation F at time T_*. A portfolio is constructed so that its duration matches T_*, making its value insensitive to parallel shifts in the yield curve. It extends to matching convexity for additional protection with three bonds. + +## Construction / Mechanics + +**Total investment** P given a future obligation F at time T_*, constant yield Y, periodic compounding with period δ: +``` +P = F / (1 + Yδ)^(T_*/δ) (396) +``` + +**Two-bond immunization** (matches duration only): + +With two bonds of maturities T_1, T_2 and modified durations D_1, D_2, dollar allocations P_1, P_2: +``` +P_1 + P_2 = P (397) +P_1·D_1 + P_2·D_2 = P·D (398) +``` +where the target modified duration: +``` +D = T_* / (1 + Yδ) (399) +``` + +**Three-bond immunization** (matches duration and convexity): + +With three bonds, durations D_1, D_2, D_3 and convexities C_1, C_2, C_3: +``` +P_1 + P_2 + P_3 = P (400) +P_1·D_1 + P_2·D_2 + P_3·D_3 = P·D (401) +P_1·C_1 + P_2·C_2 + P_3·C_3 = P·C (402) +``` +where the target convexity: +``` +C = T_*(T_* + δ) / (1 + Yδ)² (403) +``` + +## Payoff / Return Profile +- Immunized portfolio is protected against parallel yield curve shifts: the gain/loss from price changes offsets the loss/gain from reinvestment rate changes. +- Matching convexity (three-bond) provides additional protection against larger rate moves. +- The portfolio value converges to F at time T_* under parallel shifts. + +## Key Parameters / Signals +- T_*: maturity of the future cash obligation (target duration) +- F: size of the future obligation +- Y: assumed constant yield (all bonds assumed same yield — a simplification) +- D, C: target modified duration and convexity + +## Variations +- **Zero-coupon immunization**: purchase a single zero-coupon bond with maturity T_* — the simplest solution, but may not be available. +- **Two-bond**: matches duration only; sufficient for small parallel shifts. +- **Three-bond**: matches both duration and convexity; handles larger shifts. +- Extension to non-parallel yield curve changes requires additional sophistication. + +## Notes +- The assumption that all bonds have the same yield is a simplification; in practice yields differ across maturities and issuers. +- The portfolio must be periodically rebalanced as the yield curve changes, incurring transaction costs. +- Immunization protects against parallel shifts only; slope and curvature changes can still cause losses. +- Non-parallel shifts, credit spread changes, and transaction costs all introduce complexity in practice. diff --git a/gateway/knowledge/trading/strategies/fixed-income/bullets.md b/gateway/knowledge/trading/strategies/fixed-income/bullets.md new file mode 100644 index 00000000..ed0172fb --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/bullets.md @@ -0,0 +1,36 @@ +--- +description: "A bullet portfolio concentrates all bond holdings at a single target maturity, used to express a directional view on interest rates at a specific point on the yield curve." +tags: [fixed-income, duration, bullet, yield-curve] +--- + +# Bullets + +**Section**: 5.2 | **Asset Class**: Fixed Income | **Type**: Duration / Directional + +## Overview +In a bullet portfolio all bonds share the same maturity date T, targeting a specific segment of the yield curve. The strategy expresses a view on the direction of interest rates at that maturity. Bonds are typically purchased over time to mitigate timing risk from rate fluctuations. + +## Construction / Mechanics +- Select a target maturity T based on the trader's interest rate outlook. +- Purchase bonds of that maturity, potentially accumulating positions over time. +- Hold to maturity or until the rate view is realized. + +Purchasing over time mitigates interest rate risk: if rates rise, later purchases capture higher yields; if rates fall, earlier purchases lock in higher yields. + +## Payoff / Return Profile +- **Rates expected to fall** (bond prices rise): pick a longer maturity — longer bonds gain more in price from a given yield decline (higher duration). +- **Rates expected to rise** (bond prices fall): pick a shorter maturity — shorter bonds lose less. +- **Uncertain outlook**: diversify across maturities (barbell or ladder preferred). + +## Key Parameters / Signals +- Target maturity T: the single maturity determining duration exposure +- Modified duration: scales with T; determines price sensitivity to rate changes +- Interest rate forecast: the primary signal driving maturity selection + +## Variations +- Building the portfolio gradually over time to average in across different rate environments. + +## Notes +- Concentrating at one maturity creates pure duration exposure with no convexity advantage. +- Compared to a barbell with the same duration, a bullet has lower convexity, meaning it is more exposed to parallel yield curve shifts. +- Suitable when the trader has a strong directional view on a specific maturity segment. diff --git a/gateway/knowledge/trading/strategies/fixed-income/carry-factor.md b/gateway/knowledge/trading/strategies/fixed-income/carry-factor.md new file mode 100644 index 00000000..2151e9ad --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/carry-factor.md @@ -0,0 +1,56 @@ +--- +description: "The carry factor strategy buys bonds with the highest carry — the return earned as a bond rolls down the yield curve — combining bond yield income with the roll-down return from the yield curve's slope." +tags: [fixed-income, factor, carry, roll-down, yield-curve] +--- + +# Carry Factor + +**Section**: 5.11 | **Asset Class**: Fixed Income | **Type**: Factor / Carry + +## Overview +Carry in fixed income is the return from holding a bond as it "rolls down" the yield curve toward maturity. If the term structure is upward-sloping and stable, a bond's yield declines as its maturity shortens, causing a price appreciation on top of the coupon income. The carry factor strategy buys bonds in the top decile by carry and sells those in the bottom decile. + +## Construction / Mechanics + +**Carry** over horizon Δt for a bond with current maturity T: + +``` +C(t, t+Δt, T) = [P(t+Δt, T) - P(t, T)] / P(t, T) (413) +``` + +Under the assumption that the yield curve shape is constant (R(t,T) = f(T-t) only), the yield at t+Δt is R(t+Δt, T) = R(t, T-Δt), giving: + +``` +C(t, t+Δt, T) = R(t,T)·Δt + C_roll(t, t+Δt, T) (414) +``` + +Two components: +1. **Yield income**: R(t,T)·Δt — the bond's current yield times the holding period +2. **Roll-down return**: +``` +C_roll(t, t+Δt, T) ≈ -ModD(t,T) · [R(t, T-Δt) - R(t, T)] (415) +``` +This is the price appreciation as the bond shortens in maturity by Δt along a static yield curve, estimated using modified duration. + +**Portfolio construction**: rank all bonds by C(t, t+Δt, T); long top decile, short bottom decile (zero-cost version). + +## Payoff / Return Profile +- Earns yield income plus roll-down return when the yield curve is upward-sloping and stable. +- Roll-down return is greatest in the steepest segments of the yield curve. +- Underperforms or loses when the yield curve flattens, inverts, or shifts upward unexpectedly. + +## Key Parameters / Signals +- R(t,T): current yield (income component) +- ModD(t,T): modified duration (scales the roll-down component) +- R(t, T-Δt) - R(t, T): slope of the yield curve at maturity T (steeper = more roll-down) +- Δt: carry horizon (e.g., 1 month) + +## Variations +- Long-only: buy top decile by carry (no short sales required). +- Cross-asset carry: extend the same framework to other fixed income markets (government bonds, credit, etc.). + +## Notes +- The static yield curve assumption simplifies computation; actual carry will differ if the curve shifts. +- For financed portfolios, R(t,T) is replaced by R(t,T) - r_f (excess yield over the risk-free rate) in the income component, but this does not affect portfolio weights. +- High-carry bonds tend to have longer maturities in an upward-sloping curve environment, so the carry factor has implicit duration exposure. +- Carry and roll-down are sometimes separated as distinct signals; roll-down alone favors bonds in the steepest curve segments regardless of yield level. diff --git a/gateway/knowledge/trading/strategies/fixed-income/cds-basis-arbitrage.md b/gateway/knowledge/trading/strategies/fixed-income/cds-basis-arbitrage.md new file mode 100644 index 00000000..dd2b1ae9 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/cds-basis-arbitrage.md @@ -0,0 +1,55 @@ +--- +description: "CDS basis arbitrage exploits the mispricing between a bond's credit spread and its CDS spread — when the CDS basis is negative (bond spread too high), buy the bond and buy CDS protection to lock in a risk-free profit." +tags: [fixed-income, arbitrage, cds, credit-spread, basis] +--- + +# CDS Basis Arbitrage + +**Section**: 5.14 | **Asset Class**: Fixed Income | **Type**: Arbitrage / Credit + +## Overview +A credit default swap (CDS) provides insurance against default on a bond. In theory, the CDS spread should equal the bond yield spread over the risk-free rate, making the insured bond equivalent to a risk-free instrument. The CDS basis is the difference between these two spreads, and deviations from zero create arbitrage opportunities. + +## Construction / Mechanics + +**CDS basis**: +``` +CDS basis = CDS spread - bond spread (417) +``` + +where bond spread = bond yield - risk-free rate. + +**Arbitrage logic**: +- CDS spread should ≈ bond spread (both represent compensation for default risk) +- If CDS basis ≠ 0 (and |basis| exceeds transaction costs), an arbitrage opportunity exists + +**Negative basis trade** (most common): +- CDS basis < 0: bond spread > CDS spread → bond is relatively cheap +- Trade: **buy the bond** (receive the high spread) + **buy CDS protection** (pay the lower CDS spread) +- Net P&L per dollar of insured debt: bond spread - CDS spread = -basis > 0 +- Result: a nearly risk-free positive carry, since the CDS makes the bond effectively risk-free + +**Positive basis trade** (less common in practice): +- CDS basis > 0: CDS spread > bond spread → CDS protection is expensive relative to bond +- Trade: sell the bond + sell CDS protection (write CDS) +- In practice, this often means unwinding an existing position (already owning both the bond and CDS) + +## Payoff / Return Profile +- Earns the absolute value of the CDS basis as a near-riskless spread. +- Position closed when basis converges back to zero. +- The trade is essentially a carry trade: positive carry from the basis for as long as it persists. + +## Key Parameters / Signals +- CDS basis = CDS spread - bond spread: the primary signal +- Transaction cost threshold: |basis| must exceed bid-ask spreads and financing costs +- Sign of basis: negative → buy bond + buy CDS; positive → sell bond + sell CDS + +## Variations +- **Synthetic bond replication**: CDS + risk-free bond (e.g., Treasury repo) replicates a corporate bond; mispricing between the two creates the arbitrage. + +## Notes +- CDS protection makes the bond synthetically risk-free, but counterparty risk on the CDS remains. +- Negative basis arbitrage requires financing the bond purchase (repo market); the repo rate affects net P&L. +- The CDS basis can persist or widen during stress periods (e.g., 2008 financial crisis) before eventually converging, creating significant mark-to-market losses in the interim. +- Liquidity risk: corporate bonds may be illiquid, making it difficult to close the position at fair value. +- In the positive basis case, selling a corporate bond short is operationally challenging. diff --git a/gateway/knowledge/trading/strategies/fixed-income/dollar-duration-neutral-butterfly.md b/gateway/knowledge/trading/strategies/fixed-income/dollar-duration-neutral-butterfly.md new file mode 100644 index 00000000..f63dc60a --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/dollar-duration-neutral-butterfly.md @@ -0,0 +1,44 @@ +--- +description: "A dollar-duration-neutral butterfly combines a long barbell (short T_1 and long T_3 maturities) with a short bullet (intermediate T_2) at zero net cost, immunizing against parallel yield curve shifts to profit from yield curve curvature changes." +tags: [fixed-income, butterfly, duration-neutral, yield-curve, curvature] +--- + +# Dollar-Duration-Neutral Butterfly + +**Section**: 5.6 | **Asset Class**: Fixed Income | **Type**: Yield Curve / Curvature + +## Overview +The dollar-duration-neutral butterfly is a zero-cost combination of a long barbell (long T_1 and T_3 maturity bonds) and a short bullet (short the T_2 intermediate maturity bond), where T_1 < T_2 < T_3. Both zero cost (dollar neutrality) and dollar-duration neutrality conditions are imposed, immunizing the portfolio against parallel yield curve shifts. The strategy profits from changes in yield curve curvature. + +## Construction / Mechanics +Let P_1, P_2, P_3 be the dollar amounts invested in the three bonds, and D_1, D_2, D_3 their modified durations. + +**Zero-cost** (dollar neutrality): the long barbell finances the short bullet position: +``` +P_1 + P_3 = P_2 (404) +``` + +**Dollar-duration neutrality** (parallel shift immunity): +``` +P_1·D_1 + P_3·D_3 = P_2·D_2 (405) +``` + +These two equations determine P_1 and P_3 given P_2. + +## Payoff / Return Profile +- Profits when the yield curve becomes more curved (humped): the intermediate yield rises relative to the wings, or the wings fall relative to the body. +- Immune to small parallel shifts in the yield curve (both level and dollar-duration matched). +- Exposed to changes in the slope and curvature of the yield curve. + +## Key Parameters / Signals +- T_1 (short wing), T_2 (body), T_3 (long wing): the three maturities; T_1 < T_2 < T_3 +- D_1, D_2, D_3: modified durations of the three bonds +- P_2: the reference position size (determines P_1 and P_3 via the two constraints) + +## Variations +- See also: fifty-fifty butterfly (5.7) and regression-weighted butterfly (5.8), which relax the zero-cost condition. + +## Notes +- Dollar-duration neutrality (Eq. 405) protects against parallel shifts only; non-parallel changes in slope or curvature can still generate losses or gains. +- The zero-cost constraint (Eq. 404) means no initial capital is required, making it attractive as an overlay strategy. +- In practice, bid-ask spreads, financing costs, and liquidity differences across maturities affect profitability. diff --git a/gateway/knowledge/trading/strategies/fixed-income/fifty-fifty-butterfly.md b/gateway/knowledge/trading/strategies/fixed-income/fifty-fifty-butterfly.md new file mode 100644 index 00000000..c87c9cb4 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/fifty-fifty-butterfly.md @@ -0,0 +1,46 @@ +--- +description: "A fifty-fifty butterfly sets equal dollar durations on both wings of the barbell, making it approximately neutral to small yield curve steepening and flattening while remaining dollar-duration neutral, trading zero-cost for curve-neutrality." +tags: [fixed-income, butterfly, duration-neutral, yield-curve, curvature] +--- + +# Fifty-Fifty Butterfly + +**Section**: 5.7 | **Asset Class**: Fixed Income | **Type**: Yield Curve / Curvature + +## Overview +The fifty-fifty butterfly is a variation of the dollar-duration-neutral butterfly that equalizes the dollar durations of the two wings (short-maturity and long-maturity positions). This makes the strategy approximately neutral to small steepening and flattening of the yield curve (not just parallel shifts), at the cost of no longer being dollar-neutral (it is not zero-cost). It is also known as the "neutral curve butterfly." + +## Construction / Mechanics +Using the same notation as the dollar-duration-neutral butterfly (Section 5.6), with modified durations D_1, D_2, D_3 and dollar positions P_1, P_2, P_3: + +**Equal wing dollar durations**: +``` +P_1·D_1 = P_3·D_3 = (1/2)·P_2·D_2 (406) +``` + +This implies dollar-duration neutrality is preserved: +``` +P_1·D_1 + P_3·D_3 = P_2·D_2 +``` + +But the zero-cost condition P_1 + P_3 = P_2 is generally not satisfied. + +## Payoff / Return Profile +- Approximately neutral to small steepening and flattening of the yield curve: the spread change between the body (T_2) and the short wing (T_1) equals the spread change between the body and the long wing (T_3). +- Still immune to parallel shifts (dollar-duration neutral). +- Profits from curvature changes: if the body cheapens relative to both wings, the position gains. + +## Key Parameters / Signals +- P_1·D_1 = P_3·D_3 = (1/2)·P_2·D_2: the defining equal-wing constraint +- T_1 < T_2 < T_3: the three maturities +- Net cost P_2 - P_1 - P_3: non-zero unlike the dollar-duration-neutral butterfly + +## Variations +- Dollar-duration-neutral butterfly (Section 5.6): zero-cost but not curve-neutral. +- Regression-weighted butterfly (Section 5.8): uses empirical β to account for differential yield volatility across the curve. + +## Notes +- The name "fifty-fifty" refers to the equal split of the body's dollar duration between the two wings. +- Curve-neutrality is approximate and holds only for small parallel steepening/flattening moves. +- The non-zero cost means the trader must finance the net position, which has carry implications. +- Short-term rates are empirically more volatile than long-term rates, which limits the curve-neutrality assumption; this motivates the regression-weighted butterfly. diff --git a/gateway/knowledge/trading/strategies/fixed-income/generalities.md b/gateway/knowledge/trading/strategies/fixed-income/generalities.md new file mode 100644 index 00000000..c3549e1e --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/generalities.md @@ -0,0 +1,100 @@ +--- +description: "Background concepts for fixed income instruments: zero-coupon bonds, coupon bonds, floating rate bonds, swaps, duration, and convexity — the foundational mechanics underlying all fixed income strategies." +tags: [fixed-income, background, duration, convexity, swaps] +--- + +# Fixed Income Generalities + +**Section**: 5.1 | **Asset Class**: Fixed Income | **Type**: Background / Reference + +## Overview +Fixed income instruments are promises to pay cash flows at future dates, priced today as the present value of those flows. The yield of a bond summarizes its return as a single annualized rate. Duration and convexity characterize how bond prices respond to interest rate changes, and are the primary risk-management tools for fixed income portfolios. + +## Construction / Mechanics + +### 5.1.1 Zero-Coupon Bonds +A zero-coupon (discount) bond with maturity T pays $1 at time T. Its price at time t is P(t,T), with P(T,T) = 1. The continuously compounded yield is: + +``` +R(t,T) = -ln(P(t,T)) / (T - t) (374) +``` + +### 5.1.2 Coupon Bonds +A coupon bond pays principal $1 at maturity T plus n coupon payments of amount kδ at times T_i = T_0 + iδ (i = 1,...,n), where δ is the payment period. Price at time t: + +``` +P_c(t,T) = P(t,T) + kδ Σ_{i=I(t)}^n P(t,T_i) (375) +``` + +where I(t) = min(i : t < T_i). At issuance (t = T_0), the par coupon rate is: + +``` +k = (1 - P(T_0,T)) / (δ Σ_{i=1}^n P(T_0,T_i)) (377) +``` + +### 5.1.3 Floating Rate Bonds +Coupon payments are based on LIBOR. The LIBOR rate at T_{i-1} for period [T_{i-1}, T_i] is: + +``` +L(T_{i-1}) = (1/δ) [1/P(T_{i-1},T_i) - 1] (378) +``` + +The coupon paid at T_i is X_i = L(T_{i-1})δ = 1/P(T_{i-1},T_i) - 1. The total value at T_0: + +``` +V_0 = 1 - [P(T_0,T_n) - P(T_0,T)] (380) +``` + +If T = T_n then V_0 = 1 (the bond prices at par). + +### 5.1.4 Swaps +An interest rate swap exchanges fixed rate payments for floating (LIBOR) payments. A long swap = long fixed coupon bond + short floating rate bond. The fixed rate giving zero initial value: + +``` +k = (1 - P(T_0,T_n)) / (δ Σ_{i=1}^n P(T_0,T_i)) (383) +``` + +### 5.1.5 Duration and Convexity +**Macaulay duration** is the present-value-weighted average maturity of cash flows: + +``` +MacD(t,T) = (1/P_c(t,T)) [(T-t)P(t,T) + kδ Σ_{i=I(t)}^n (T_i-t)P(t,T_i)] (384) +``` + +**Modified duration** measures relative price sensitivity to parallel yield shifts: + +``` +ModD(t,T) = -∂ln(P_c(t,T)) / ∂R(t,T) (385) +``` + +For constant yield Y with periodic compounding: ModD = MacD / (1 + Yδ). +Approximate price change: ΔP_c/P_c ≈ -ModD · ΔR + +**Dollar duration** measures absolute price sensitivity: + +``` +DD(t,T) = -∂P_c(t,T)/∂R(t,T) = ModD(t,T) · P_c(t,T) (387) +``` + +**Convexity** captures nonlinear (second-order) effects: + +``` +C(t,T) = -(1/P_c(t,T)) · ∂²P_c(t,T)/∂R(t,T)² (388) +``` + +Full second-order approximation: + +``` +ΔP_c/P_c ≈ -ModD·ΔR + (1/2)·C·(ΔR)² (389) +``` + +## Key Parameters / Signals +- **Yield R(t,T)**: inverse of price; drives all valuation +- **Modified duration**: primary interest rate risk metric; scales approximately linearly with maturity +- **Dollar duration**: used for hedging and portfolio construction +- **Convexity**: scales approximately quadratically with maturity; higher convexity = better protection against parallel yield shifts at the cost of lower yield + +## Notes +- Duration and convexity formulas assume parallel shifts in the yield curve; non-parallel shifts require more sophisticated treatment. +- Floating rate bonds priced at par (V_0 = 1) when T = T_n because the variable coupons replicate rolling T-bond investments. +- Periodic vs. continuous compounding: MacD and ModD coincide under continuous compounding; differ under periodic compounding by factor (1 + Yδ). diff --git a/gateway/knowledge/trading/strategies/fixed-income/ladders.md b/gateway/knowledge/trading/strategies/fixed-income/ladders.md new file mode 100644 index 00000000..bc3b5cd1 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/ladders.md @@ -0,0 +1,43 @@ +--- +description: "A ladder portfolio holds bonds spread evenly across n equidistant maturities to diversify interest rate and reinvestment risk while maintaining an approximately constant duration through systematic roll-down." +tags: [fixed-income, duration, ladder, diversification, yield-curve] +--- + +# Ladders + +**Section**: 5.4 | **Asset Class**: Fixed Income | **Type**: Duration-Targeting / Diversification + +## Overview +A ladder holds bonds with (roughly) equal capital allocations across n different maturities T_i (i = 1,...,n), where maturities are equidistant: T_{i+1} = T_i + δ. The strategy maintains an approximately constant duration by selling shorter-maturity bonds as they near maturity and replacing them with new longer-maturity bonds. It diversifies both interest rate risk and reinvestment risk. + +## Construction / Mechanics +- Allocate roughly equal capital to each rung T_i, i = 1,...,n (n is sizable, e.g., n = 10). +- Equidistant maturities: T_{i+1} = T_i + δ. +- Average (effective) maturity of the portfolio: + +``` +T = (1/n) Σ_{i=1}^n T_i (395) +``` + +- As the shortest rung approaches maturity, sell it and purchase a new bond at the longest maturity, maintaining the ladder structure. +- Also generates regular income from coupon payments across all rungs. + +## Payoff / Return Profile +- Higher average maturity T → higher income (upward-sloping yield curve), but also higher interest rate risk. +- Rolling shorter bonds into longer bonds continuously captures roll-down return. +- Diversification across maturities smooths the impact of rate moves: if rates rise, maturing short bonds are reinvested at higher rates; if rates fall, longer bonds appreciate. + +## Key Parameters / Signals +- n: number of rungs (more rungs = more diversification) +- δ: spacing between maturities +- T (average maturity): determines the income/risk trade-off +- Equal capital allocation per rung: ensures no concentration at any maturity + +## Variations +- Unequal allocations tilting toward shorter or longer maturities (incorporating a partial bullet or barbell bias). + +## Notes +- The ladder avoids the concentration risk of bullets and barbells, making it suitable for investors uncertain about the rate environment. +- The constant-duration property is approximate; exact duration changes as bonds age and are replaced. +- Reinvestment risk is diversified: proceeds from maturing bonds are spread across the yield curve over time rather than all reinvested at once. +- Transaction costs from regular rolling must be weighed against the diversification and roll-down benefits. diff --git a/gateway/knowledge/trading/strategies/fixed-income/low-risk-factor.md b/gateway/knowledge/trading/strategies/fixed-income/low-risk-factor.md new file mode 100644 index 00000000..738ba7bd --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/low-risk-factor.md @@ -0,0 +1,44 @@ +--- +description: "The low-risk factor strategy buys bonds with lower risk (shorter maturity and higher credit rating) within a credit tier, exploiting the empirical anomaly that lower-risk bonds outperform higher-risk bonds on a risk-adjusted basis." +tags: [fixed-income, factor, low-risk, credit, anomaly] +--- + +# Low-Risk Factor + +**Section**: 5.9 | **Asset Class**: Fixed Income | **Type**: Factor / Anomaly + +## Overview +Empirical evidence suggests that lower-risk bonds tend to outperform higher-risk bonds on a risk-adjusted basis (the "low-risk anomaly"), mirroring a similar effect in equities. "Riskiness" in fixed income is measured by credit rating and maturity. The strategy builds long portfolios of the lowest-risk bonds within a given credit tier. + +## Construction / Mechanics +Portfolio construction uses two risk dimensions: + +1. **Credit rating**: separates the investment universe into quality tiers. + - Investment Grade (IG): credit ratings AAA through A-. + - High Yield (HY): credit ratings BB+ through B-. + +2. **Maturity (duration)**: within each credit tier, rank bonds by maturity and take the **bottom decile** (shortest maturities = lowest duration risk). + +Example portfolios: +- IG low-risk: Investment Grade bonds (AAA–A-), bottom decile by maturity. +- HY low-risk: High Yield bonds (BB+–B-), bottom decile by maturity. + +## Payoff / Return Profile +- Earns a risk-adjusted premium by being long the lowest-risk bonds in each tier. +- Outperforms the broad credit market on a Sharpe ratio basis due to the low-risk anomaly. +- Returns are driven by credit spread compression and coupon income, with lower sensitivity to interest rate moves (short maturity). + +## Key Parameters / Signals +- Credit rating tier: AAA–A- (IG) or BB+–B- (HY) +- Maturity rank: bottom decile selects shortest-maturity bonds +- Risk-adjusted return (Sharpe ratio): primary evaluation metric + +## Variations +- Can be combined with a short position in the top-risk decile (highest maturity within the tier) to create a long-short low-risk factor. +- Risk metrics beyond credit rating and maturity (e.g., option-adjusted spread, liquidity) can be incorporated. + +## Notes +- The low-risk anomaly in bonds mirrors the similar effect documented in equities but is driven by different mechanisms (credit and duration rather than beta). +- Separating IG and HY tiers is important because the risk-return relationship differs significantly between investment grade and speculative grade. +- Liquidity may be lower for short-maturity high-yield bonds, increasing transaction costs. +- The strategy is typically implemented as a long-only portfolio; short positions in corporate bonds are operationally difficult. diff --git a/gateway/knowledge/trading/strategies/fixed-income/regression-weighted-butterfly.md b/gateway/knowledge/trading/strategies/fixed-income/regression-weighted-butterfly.md new file mode 100644 index 00000000..fa24574f --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/regression-weighted-butterfly.md @@ -0,0 +1,53 @@ +--- +description: "A regression-weighted butterfly uses an empirically estimated β to account for the higher volatility of short-term rates relative to long-term rates, improving yield-curve-neutrality beyond the fifty-fifty butterfly." +tags: [fixed-income, butterfly, duration-neutral, yield-curve, curvature, regression] +--- + +# Regression-Weighted Butterfly + +**Section**: 5.8 | **Asset Class**: Fixed Income | **Type**: Yield Curve / Curvature + +## Overview +Empirically, short-term interest rates are significantly more volatile than long-term rates. The regression-weighted butterfly accounts for this by weighting the short wing's dollar duration by a factor β > 1, estimated from historical data via regression. This produces better curve-neutrality than the fifty-fifty butterfly in practice. + +## Construction / Mechanics +Using positions P_1, P_2, P_3 with modified durations D_1, D_2, D_3 (T_1 < T_2 < T_3): + +**Dollar-duration neutrality** (parallel shift immunity): +``` +P_1·D_1 + P_3·D_3 = P_2·D_2 (407) +``` + +**Regression-weighted curve-neutrality**: +``` +P_1·D_1 = β · P_3·D_3 (408) +``` + +where β > 1 is the regression coefficient from regressing the spread change between the body (T_2) and the short wing (T_1) on the spread change between the body and the long wing (T_3), using historical data. + +## Payoff / Return Profile +- Immune to both parallel shifts (407) and, approximately, to yield curve slope changes in proportion β. +- Profits from yield curve curvature moves: gains when the body yields rise relative to the wings. +- More robust curve-neutrality than the fifty-fifty butterfly in practice due to the empirically calibrated β. + +## Key Parameters / Signals +- β: regression coefficient (typically β > 1, calibrated from historical spread data) +- P_1, P_3: determined by solving (407) and (408) given P_2 +- T_1, T_2, T_3: the three maturity points on the yield curve + +## Variations + +### 5.8.1 Maturity-Weighted Butterfly +Instead of estimating β from historical regressions, it is set analytically from the three bond maturities: + +``` +β = (T_2 - T_1) / (T_3 - T_2) (409) +``` + +This is proportional to the ratio of the short-wing maturity distance to the long-wing maturity distance from the body. It is a simpler, model-based alternative that does not require historical calibration. + +## Notes +- β is empirically greater than 1 because short-term rates fluctuate more than long-term rates; the short wing therefore needs less dollar duration to hedge the same spread move. +- The regression β should be re-estimated periodically as the volatility relationship between short and long rates can change over time. +- The maturity-weighted variant (5.8.1) provides a model-based β that requires no estimation but may not capture the true empirical volatility asymmetry. +- All butterfly strategies share the exposure to transaction costs, financing costs, and bid-ask spreads that can erode theoretical curve-neutrality profits. diff --git a/gateway/knowledge/trading/strategies/fixed-income/rolling-down-yield-curve.md b/gateway/knowledge/trading/strategies/fixed-income/rolling-down-yield-curve.md new file mode 100644 index 00000000..b1b017c1 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/rolling-down-yield-curve.md @@ -0,0 +1,52 @@ +--- +description: "Rolling down the yield curve buys long- or medium-term bonds in the steepest segment of the yield curve and holds them while they appreciate as they shorten in maturity, then reinvests proceeds into new steepest-segment bonds." +tags: [fixed-income, roll-down, yield-curve, carry, duration] +--- + +# Rolling Down the Yield Curve + +**Section**: 5.12 | **Asset Class**: Fixed Income | **Type**: Carry / Roll-Down + +## Overview +The rolling down the yield curve strategy captures the roll-down component C_roll of bond returns by purchasing bonds in the steepest segments of the yield curve and holding them while their maturity shortens, causing price appreciation. Bonds are sold before maturity and the proceeds reinvested in new long/medium-term bonds from the same steep segment. + +## Construction / Mechanics +The roll-down return over horizon Δt: + +``` +C_roll(t, t+Δt, T) ≈ -ModD(t,T) · [R(t, T-Δt) - R(t, T)] (415) +``` + +This is maximized when: +- **ModD(t,T)** is large (longer-maturity bonds have higher duration) +- **R(t, T-Δt) - R(t, T) < 0** (yield declines as maturity shortens — upward-sloping curve) +- The magnitude |R(t, T-Δt) - R(t, T)| is large (steep segment of the curve) + +**Strategy mechanics**: +1. Identify the steepest segment(s) of the yield curve. +2. Buy long- or medium-term bonds from those segments. +3. Hold while they "roll down" the curve (their maturity shrinks and yield declines). +4. Sell before maturity approaches (before they enter a flatter/shorter segment). +5. Reinvest proceeds into new long/medium-term bonds from the steep segment. + +## Payoff / Return Profile +- Earns roll-down return C_roll in addition to yield income R(t,T)·Δt. +- Total carry C(t, t+Δt, T) = R(t,T)·Δt + C_roll(t, t+Δt, T). +- Profits maximized in steeply upward-sloping yield curves. +- Loses money when the yield curve flattens, inverts, or when long-end yields rise (parallel upward shift). + +## Key Parameters / Signals +- Yield curve slope: identifies which segments offer the most roll-down return +- Modified duration: amplifies the roll-down return +- Holding horizon Δt: determines how far down the curve the bond rolls before sale +- Curve stability: strategy depends on curve shape remaining approximately stable + +## Variations +- Pure roll-down: focus exclusively on C_roll, ignoring yield income (selects steepest curve segments regardless of absolute yield level). +- Combined carry + roll: as in the carry factor strategy (5.11), which uses total C as the signal. + +## Notes +- The yield curve must be upward-sloping for roll-down to be positive; in a flat or inverted curve the roll-down may be zero or negative. +- Transaction costs from repeated roll-overs must be weighed against the roll-down income. +- The strategy has implicit duration risk: long/medium bonds lose value in a rising rate environment, which can more than offset the roll-down gain. +- Steepest curve segments often occur at the short to medium end (e.g., 2-10 year part of the Treasury curve) and can shift over time with monetary policy. diff --git a/gateway/knowledge/trading/strategies/fixed-income/swap-spread-arbitrage.md b/gateway/knowledge/trading/strategies/fixed-income/swap-spread-arbitrage.md new file mode 100644 index 00000000..d22736d3 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/swap-spread-arbitrage.md @@ -0,0 +1,59 @@ +--- +description: "Swap spread arbitrage takes a long (short) position in an interest rate swap versus a short (long) position in a Treasury bond of the same maturity, profiting from the difference between the swap rate, Treasury yield, LIBOR, and the repo rate." +tags: [fixed-income, arbitrage, swap, libor, treasury, spread] +--- + +# Swap Spread Arbitrage + +**Section**: 5.15 | **Asset Class**: Fixed Income | **Type**: Arbitrage / Rates + +## Overview +The swap spread arbitrage is a dollar-neutral strategy that combines a long (or short) position in an interest rate swap with an offsetting short (or long) position in a Treasury bond of the same maturity. It profits from the spread between the swap fixed rate and the Treasury yield, net of financing costs (LIBOR vs. repo rate). The strategy is essentially a bet on the direction of LIBOR relative to the repo rate. + +## Construction / Mechanics + +**Instruments**: +- Interest rate swap: receive fixed rate r_swap, pay floating LIBOR L(t) +- Treasury bond: short the bond (financed at repo rate r(t)) + +**Per-dollar-invested P&L rate**: +``` +C(t) = ±[C_1 - C_2(t)] (418) +C_1 = r_swap - Y_Treasury (419) +C_2(t) = L(t) - r(t) (420) +``` + +where: +- C_1: constant spread = swap fixed rate minus Treasury yield (the swap spread) +- C_2(t): floating spread = LIBOR minus repo rate +- Plus sign: long swap strategy (receive fixed, short Treasury) +- Minus sign: short swap strategy (pay fixed, long Treasury) + +**Long swap strategy** (plus sign): +- Receive r_swap (fixed leg of swap) + short Treasury (financed at repo) → pay Y_Treasury + repo rate +- Profitable if C_2(t) = L(t) - r(t) < C_1 + +**Short swap strategy** (minus sign): +- Pay r_swap (fixed leg) + long Treasury (funded at repo) → receive Y_Treasury +- Profitable if C_2(t) = L(t) - r(t) > C_1 + +## Payoff / Return Profile +- The long swap strategy profits if LIBOR falls (C_2 decreases below C_1). +- The short swap strategy profits if LIBOR rises (C_2 increases above C_1). +- This is fundamentally a **LIBOR bet**: the trade profits or loses based on the LIBOR-repo spread relative to the constant swap spread C_1. + +## Key Parameters / Signals +- C_1 = r_swap - Y_Treasury: the swap spread (constant at trade inception) +- C_2(t) = L(t) - r(t): the LIBOR-repo spread (time-varying) +- Net P&L driver: ±(C_1 - C_2(t)); direction depends on long vs. short swap position + +## Variations +- Adjust maturity of the swap and Treasury bond to target different parts of the yield curve. +- Pair with CDS basis trades for multi-leg credit/rates arbitrage. + +## Notes +- The strategy is dollar-neutral (the swap and Treasury position offset each other in notional terms). +- LIBOR risk is the dominant risk: unexpected changes in LIBOR (e.g., central bank policy shifts, bank credit stress) directly affect P&L. +- The repo rate r(t) can vary and introduces additional uncertainty in C_2(t). +- With the transition away from LIBOR to SOFR and other risk-free rates, the mechanics of this strategy are evolving. +- Counterparty risk on the swap and margin requirements must be accounted for in practice. diff --git a/gateway/knowledge/trading/strategies/fixed-income/value-factor.md b/gateway/knowledge/trading/strategies/fixed-income/value-factor.md new file mode 100644 index 00000000..071376ac --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/value-factor.md @@ -0,0 +1,66 @@ +--- +description: "The value factor strategy for bonds selects bonds with the highest actual credit spread relative to a theoretically predicted spread from a cross-sectional regression, going long undervalued bonds in the top decile." +tags: [fixed-income, factor, value, credit-spread, regression] +--- + +# Value Factor + +**Section**: 5.10 | **Asset Class**: Fixed Income | **Type**: Factor / Value + +## Overview +"Value" in fixed income is defined by comparing a bond's observed credit spread to a theoretically predicted (fair value) credit spread. Bonds trading with a spread significantly above their predicted fair value are cheap (high value); those below are expensive. The strategy buys the top-decile bonds by value score. + +## Construction / Mechanics + +**Step 1: Estimate fair value spreads** via a cross-sectional linear regression across N bonds (i = 1,...,N): + +``` +S_i = Σ_{r=1}^K β_r · I_{ir} + γ · T_i + ε_i (410) +``` + +where: +- S_i: observed credit spread of bond i (bond yield minus risk-free rate) +- I_{ir}: dummy variable = 1 if bond i has credit rating r, 0 otherwise (K ≤ 21 ratings) +- T_i: maturity of bond i +- β_r, γ: regression coefficients (note: no separate intercept since Σ_r I_{ir} = 1 for each bond) +- ε_i: regression residual + +The constraint: +``` +Σ_{r=1}^K I_{ir} = 1 for all i (412) +``` +(each bond has exactly one credit rating, so the intercept is absorbed into the rating dummies) + +**Step 2: Compute fair value spread**: +``` +S_i* = S_i - ε_i (411) +``` +(the fitted value from the regression) + +**Step 3: Compute value score** — either: +- V_i = ln(S_i / S_i*), or +- V_i = ε_i / S_i* = S_i / S_i* - 1 + +**Step 4: Select portfolio** — long bonds in the top decile by V_i (most undervalued). + +## Payoff / Return Profile +- Profits when cheap bonds (high V_i) revert toward fair value, compressing their spreads. +- Returns driven by credit spread compression and coupon income. +- The strategy assumes mean-reversion in credit spreads around their rating- and maturity-implied fair value. + +## Key Parameters / Signals +- S_i: observed credit spread (bond yield minus risk-free rate) +- S_i*: fair value credit spread from cross-sectional regression +- V_i = ln(S_i/S_i*) or V_i = S_i/S_i* - 1: value score +- Top decile by V_i: the portfolio selection criterion + +## Variations +- Long-short: long top decile (cheap bonds), short bottom decile (expensive bonds). +- Separate regressions for Investment Grade and High Yield universes. +- Additional cross-sectional controls (e.g., industry, liquidity) can be added as regressors. + +## Notes +- "Value" in fixed income is harder to define than in equities because bonds have finite lifetimes and their spreads are heavily influenced by credit ratings and maturity. +- The cross-sectional regression should be run on bonds within a comparable universe (e.g., only IG or only HY) to ensure meaningful comparisons. +- Credit spread data may be noisy; outliers from bonds near distress can distort the regression. +- Shorting corporate bonds is operationally challenging; the strategy is often implemented long-only. diff --git a/gateway/knowledge/trading/strategies/fixed-income/yield-curve-spread.md b/gateway/knowledge/trading/strategies/fixed-income/yield-curve-spread.md new file mode 100644 index 00000000..e0d8daff --- /dev/null +++ b/gateway/knowledge/trading/strategies/fixed-income/yield-curve-spread.md @@ -0,0 +1,56 @@ +--- +description: "Yield curve spread strategies (flatteners and steepeners) trade the difference in yields between two maturities of the same issuer, going short the spread when rates are expected to rise and long when rates are expected to fall." +tags: [fixed-income, yield-curve, spread, flattener, steepener, duration] +--- + +# Yield Curve Spread (Flatteners & Steepeners) + +**Section**: 5.13 | **Asset Class**: Fixed Income | **Type**: Yield Curve / Spread + +## Overview +Yield curve spread strategies trade the yield spread between two bonds of the same issuer at different maturities. If interest rates are expected to rise, the yield curve is expected to flatten (short end rises more than long end); if rates are expected to fall, the curve steepens. The strategy goes short the spread (flattener) or long the spread (steepener) accordingly. + +## Construction / Mechanics + +**Yield curve spread**: the difference in yields between a longer-maturity bond (back leg) and a shorter-maturity bond (front leg) of the same issuer: +``` +Spread = Y(back leg, long maturity) - Y(front leg, short maturity) +``` + +**Trading rule**: +``` +Rule = { Flattener: Short spread if interest rates expected to rise + { Steepener: Buy spread if interest rates expected to fall (416) +``` + +**Position construction**: +- **Short the spread (flattener)**: sell shorter-maturity bonds (front leg) + buy longer-maturity bonds (back leg). +- **Buy the spread (steepener)**: buy shorter-maturity bonds (front leg) + sell longer-maturity bonds (back leg). + +**Dollar-duration matching**: to immunize against small parallel shifts, match the dollar durations of the front and back legs: +``` +P_front · D_front = P_back · D_back +``` + +Without duration matching, a parallel shift in the yield curve can generate significant losses. + +## Payoff / Return Profile +- **Flattener profits** when the curve flattens: short-end yields rise more than long-end yields (or long-end falls more than short-end). +- **Steepener profits** when the curve steepens: long-end yields rise more than short-end (or short-end falls more than long-end). +- Dollar-duration-neutral construction limits losses from parallel yield curve moves. + +## Key Parameters / Signals +- Yield curve slope: R(long maturity) - R(short maturity) — the key signal +- Front leg maturity T_1, back leg maturity T_2: define the segment being traded +- Modified durations D_1, D_2: used for dollar-duration matching +- Interest rate outlook: the primary driver of direction (flattener vs. steepener) + +## Variations +- **Curve trades across issuers**: trading the slope difference between two issuers (adds credit spread risk). +- **Butterfly trades**: extend the two-leg spread to a three-leg position to trade curvature rather than slope (see Sections 5.6–5.8). + +## Notes +- Parallel yield curve shifts can cause losses if dollar durations are not matched; duration-matching is essential for a pure slope bet. +- Even with duration matching, large parallel moves (exceeding the immunization approximation) can generate losses due to convexity differences between legs. +- The strategy is exposed to idiosyncratic supply-and-demand effects at specific maturities (e.g., Treasury auction effects, central bank purchases). +- Financing costs (repo rates for the short leg) affect the net P&L of the strategy. diff --git a/gateway/knowledge/trading/strategies/futures/calendar-spread.md b/gateway/knowledge/trading/strategies/futures/calendar-spread.md new file mode 100644 index 00000000..7ebe5779 --- /dev/null +++ b/gateway/knowledge/trading/strategies/futures/calendar-spread.md @@ -0,0 +1,48 @@ +--- +description: "Futures calendar spread strategy that takes simultaneous long/short positions in near-month and deferred-month contracts to bet on supply/demand fundamentals while reducing overall market volatility exposure." +tags: [futures, calendar-spread, term-structure, spread-trading] +--- + +# Calendar Spread + +**Section**: 10.2 | **Asset Class**: Futures | **Type**: Spread Trading / Relative Value + +## Overview +A calendar spread (also called a time spread or intra-commodity spread) involves simultaneously buying and selling futures contracts on the same underlying commodity or asset but with different delivery months. By taking offsetting positions, the trader reduces exposure to outright price moves and focuses on the relative pricing of near versus deferred contracts, which reflects supply-and-demand fundamentals and storage costs. + +## Construction / Mechanics +**Bull spread**: Buy a near-month futures contract, sell a deferred-month futures contract. +- P&L = price change of near-month - price change of deferred-month +- Benefits when near-month appreciates relative to deferred (supply tightening, demand surge) + +**Bear spread**: Sell a near-month futures contract, buy a deferred-month futures contract. +- P&L = price change of deferred-month - price change of near-month +- Benefits when deferred-month appreciates relative to near-month (supply glut, weak demand) + +**Economic rationale**: For commodity futures, near-month contracts react more strongly to current supply and demand imbalances than deferred contracts. Therefore: +- Expect low supply + high demand → use a **bull spread** +- Expect high supply + low demand → use a **bear spread** + +## Return Profile +Profits from changes in the spread between near and deferred contract prices. The outright directional market risk is substantially reduced (though not fully eliminated) relative to an outright futures position. The strategy is driven by term structure dynamics, convenience yield changes, storage cost changes, and short-term supply/demand imbalances. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Near-month contract | The shorter-dated futures leg | +| Deferred-month contract | The longer-dated futures leg | +| Spread = near - deferred | Positive → backwardation; negative → contango | +| Bull signal | Expected low supply and high demand (buy spread) | +| Bear signal | Expected high supply and low demand (sell spread) | + +## Variations +- **Skip-month spread**: skip one contract month between the two legs to amplify the spread move. +- **Butterfly spread**: three legs (buy near, sell middle, buy far) to isolate curvature of the term structure. +- **Crack spread** (energy): spread between crude oil and refined product futures (captures refining margin rather than a pure calendar spread). +- **Inter-commodity spread**: similar mechanics but between related but different commodities (e.g., corn vs. wheat). + +## Notes +- While market exposure is reduced relative to outright futures, calendar spreads are not market-neutral; correlation between legs can break down during stress events. +- Margin requirements for calendar spreads are typically lower than for outright futures because exchanges recognise the reduced directional risk. +- Liquidity in deferred contracts is typically lower than in near-month contracts; wide bid-ask spreads on the deferred leg can erode profits. +- For financial futures (equity index, interest rate), the spread is primarily driven by carry (financing cost and dividend/coupon income) rather than physical supply and demand. diff --git a/gateway/knowledge/trading/strategies/futures/contrarian-trading.md b/gateway/knowledge/trading/strategies/futures/contrarian-trading.md new file mode 100644 index 00000000..82aefc7b --- /dev/null +++ b/gateway/knowledge/trading/strategies/futures/contrarian-trading.md @@ -0,0 +1,79 @@ +--- +description: "Futures mean-reversion strategy that buys recent underperformers and sells recent outperformers relative to an equally-weighted futures market index, with an extension using volume and open interest filters." +tags: [futures, mean-reversion, contrarian, market-index, dollar-neutral] +--- + +# Contrarian Trading (Mean-Reversion) + +**Section**: 10.3 | **Asset Class**: Futures | **Type**: Mean-Reversion / Contrarian + +## Overview +Analogous to the equity mean-reversion strategy (Section 3.9), this futures strategy bets that recent losers will rebound and recent winners will give back gains. Returns of individual futures are measured relative to an equally-weighted market index, and capital is allocated inversely to the deviation from that index. The result is a dollar-neutral, automatically constructed contrarian portfolio rebalanced weekly. + +## Construction / Mechanics +Within a universe of N futures labeled i = 1,...,N, define the "market index" return as the equally-weighted average: + +``` +R_m = (1/N) Σ R_i (469) +``` + +where R_i are individual futures returns, typically measured over the last one week. + +The capital allocation weights are: + +``` +w_i = -γ [R_i - R_m] (470) +``` + +where γ > 0 is fixed via the dollar-neutral normalization condition: + +``` +Σ |w_i| = 1 (471) +``` + +- Futures below the market index (R_i < R_m): positive weight (long) +- Futures above the market index (R_i > R_m): negative weight (short) +- The portfolio is automatically dollar-neutral (Σ w_i = 0) +- The strategy buys losers and sells winners relative to the market index + +**Volatility adjustment**: To mitigate overinvestment in volatile futures, suppress w_i by 1/σ_i or 1/σ_i², where σ_i are the historical volatilities. + +## Return Profile +Profits when futures returns mean-revert toward the market index over a one-week horizon. Returns are driven by short-term overreaction and subsequent correction. The strategy is market-neutral at the index level. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| R_i | Individual futures return over the last week | +| R_m | Equally-weighted market index return (Eq. 469) | +| w_i = -γ[R_i - R_m] | Allocation weight; negative for winners, positive for losers | +| γ | Scaling parameter fixed by Eq. (471) | +| σ_i | Historical volatility; used to suppress w_i optionally | +| Rebalancing | Weekly | + +## Variations + +### 10.3.1 Contrarian Trading — Market Activity +Volume and open interest filters can improve the basic mean-reversion signal. Define: + +``` +v_i = ln(V_i / V_i') (472) +u_i = ln(U_i / U_i') (473) +``` + +where V_i is total volume for futures i over the last week, V_i' is total volume over the prior week, and U_i, U_i' are the analogous open interest quantities. + +**Construction:** +1. Take the upper half of futures by volume factor v_i (higher recent volume relative to prior week). +2. Within that subset, take the lower half by open interest factor u_i. +3. Apply the contrarian weights from Eq. (470) to this filtered subset. + +**Rationale:** +- Larger volume changes indicate greater overreaction (a stronger snap-back is expected). +- A decrease in open interest (low u_i) signals hedger withdrawal and suggests a deeper market for the mean-reversion to work. + +## Notes +- The simple weighting scheme (Eq. 470) can overinvest in highly volatile futures; volatility scaling (1/σ_i or 1/σ_i²) is recommended in practice. +- Weekly rebalancing incurs transaction costs; the net alpha must exceed round-trip costs across all positions. +- Contrarian strategies can suffer sustained losses during trending regimes; combining with a trend-following overlay (Section 10.4) may reduce drawdowns. +- The market-index return R_m links this strategy to the broader futures universe; changing the universe composition changes the benchmark and alters all weights. diff --git a/gateway/knowledge/trading/strategies/futures/hedging-risk.md b/gateway/knowledge/trading/strategies/futures/hedging-risk.md new file mode 100644 index 00000000..9db02d53 --- /dev/null +++ b/gateway/knowledge/trading/strategies/futures/hedging-risk.md @@ -0,0 +1,80 @@ +--- +description: "Futures hedging strategy that uses futures contracts to offset price or interest-rate risk on an underlying asset position, with variants for cross-hedging and duration-based interest-rate risk hedging." +tags: [futures, hedging, risk-management, interest-rate, cross-hedge] +--- + +# Hedging Risk with Futures + +**Section**: 10.1 | **Asset Class**: Futures | **Type**: Hedging / Risk Management + +## Overview +Futures contracts allow traders to mitigate exposure to price risk on an underlying asset. A trader who anticipates needing to buy (sell) an asset at a future date can lock in a price today by buying (selling) a futures contract. The strategy eliminates directional price exposure at the cost of potentially missing favourable price moves. Variants address situations where no exact futures contract exists (cross-hedging) and interest-rate risk on fixed-income assets. + +## Construction / Mechanics +**Basic hedge**: A trader expects to buy (sell) X units of an asset at time T. +- To hedge rising prices: buy futures contracts at time t for delivery at T. +- To hedge falling prices: sell futures contracts at time t for delivery at T. + +The futures position offsets the P&L on the underlying physical exposure. + +## Return Profile +The hedge eliminates (or substantially reduces) the P&L variability due to the hedged risk factor. The net position approximates a risk-free return when the hedge ratio is well-calibrated. Basis risk (see cross-hedging) is the residual risk that remains. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Hedge ratio | Number of futures contracts per unit of underlying exposure | +| Delivery date T | Futures expiry chosen to match or exceed the hedging horizon | +| Basis risk | Residual risk when futures price and spot price do not move in perfect lockstep | + +## Variations + +### 10.1.1 Cross-Hedging +When a futures contract for the exact asset to be hedged does not exist, a futures contract on a correlated asset can be used. The payoff at maturity T of the cross-hedged position (short futures, unit hedge ratio) is: + +``` +S(T) - F(t,T) + F(t,T) += [S*(T) - F(t,T)] + [S(T) - S*(T)] + F(t,T) (463) +``` + +where the subscript * denotes the underlying of the futures contract (different from the hedged asset), S(T) is the spot price of the hedged asset, and F(t,T) is the futures price. + +- First term [S*(T) - F(t,T)]: basis risk from the difference between futures price and the futures' underlying spot at delivery. +- Second term [S(T) - S*(T)]: risk from the difference between the two underlying assets. + +In practice the optimal hedge ratio h ≠ 1 and can be estimated via serial regression of the hedged asset's spot return on the futures return, or by other methods. + +### 10.1.2 Interest Rate Risk Hedging +Fixed-income assets are sensitive to interest rate changes. Futures on interest rate instruments (e.g., T-bond futures) can be used to hedge this risk. + +- Long hedge (buy futures): protects against rising asset prices (falling rates) +- Short hedge (sell futures): protects against falling asset prices (rising rates) + +P&L for the long hedge established at t=0 with unit hedge ratio and maturity T: +``` +P_L(t,T) = B(0,T) - B(t,T) (464) +P_S(t,T) = B(t,T) - B(0,T) (465) +``` +where the futures basis is: +``` +B(t,T) = S(t) - F(t,T) (466) +``` + +**Conversion factor model** (for bonds in a futures delivery basket): +``` +h_C = C × (M_B / M_F) (467) +``` +where M_B is bond notional, M_F is futures notional, C is the conversion factor. + +**Modified duration hedge ratio** (applicable to both deliverable and non-deliverable bonds): +``` +h_D = β × (D_B / D_F) (468) +``` +where D_B is the dollar duration of the bond, D_F is the dollar duration of the futures, and β is the sensitivity of bond yield changes to futures yield changes (often set to 1). + +## Notes +- Basis risk is the primary residual risk in any futures hedge; it arises from imperfect correlation between futures and spot prices. +- The conversion factor model applies only to T-bond and T-note futures; the duration model is more general. +- β in Eq. (468) can be estimated from historical regression of bond yield changes on futures yield changes. +- Cross-hedges with dissimilar underlying assets carry additional residual risk that simple regression-based hedge ratios may not fully capture. +- Hedging eliminates upside as well as downside; traders should consider whether they need a full hedge or a partial one. diff --git a/gateway/knowledge/trading/strategies/futures/trend-following.md b/gateway/knowledge/trading/strategies/futures/trend-following.md new file mode 100644 index 00000000..d71332e8 --- /dev/null +++ b/gateway/knowledge/trading/strategies/futures/trend-following.md @@ -0,0 +1,83 @@ +--- +description: "Futures momentum strategy that weights positions proportionally to the sign of recent returns scaled by historical volatility, equivalent to a diagonal-covariance mean-variance optimisation." +tags: [futures, momentum, trend-following, time-series, volatility-scaled] +--- + +# Trend Following (Momentum) + +**Section**: 10.4 | **Asset Class**: Futures | **Type**: Momentum / Trend-Following + +## Overview +Trend-following constructs a futures portfolio by going long instruments with positive recent returns and short those with negative returns, with position sizes inversely proportional to volatility. This is equivalent to a mean-variance optimisation using a diagonal covariance matrix (ignoring cross-futures correlations) and expected returns proportional to the sign of recent performance. It is one of the most widely used and robust strategies in futures markets. + +## Construction / Mechanics +Let R_i be the return of futures i (i = 1,...,N) over a look-back period T. Define the trend signal: + +``` +η_i = sign(R_i) (475) +``` + +The portfolio weights are: + +``` +w_i = γ × (η_i / σ_i) (474) +``` + +where σ_i are the historical volatilities (computed over T or another window) and γ > 0 is fixed via: + +``` +Σ |w_i| = 1 (476) +``` + +**Dollar-neutral version**: demeaning the weights to achieve Σ w_i = 0: + +``` +w_i = γ [η_i/σ_i - (1/N) Σ η_j/σ_j] (477) +``` + +**Balanced long/short version**: when the number of long positions N+ ≈ number of short positions N- (i.e., N+ = |H+| ≈ N- = |H-|), use separate normalisation constants γ+ and γ-: + +``` +w_i = γ+ × η_i/σ_i, i ∈ H+ (η_i > 0) (478) +w_i = γ- × η_i/σ_i, i ∈ H- (η_i < 0) (479) +``` + +satisfying Eq. (476) and the dollar-neutrality condition: + +``` +Σ w_i = 0 (480) +``` + +**Demeaned returns variant**: replace R_i with R̃_i = R_i - R_m (market-adjusted returns, where R_m is Eq. (469)) to remove the common market factor and prevent skewed η_i distribution. + +**Signal smoothing**: to avoid instability when |R_i| is small relative to σ_i (causing η_i to flip on minor changes), replace sign(R_i) with: + +``` +η_i = tanh(R_i / κ) +``` + +where κ is a smoothing parameter (e.g., the cross-sectional standard deviation of R_i). + +## Return Profile +Profits when futures trend: long positions appreciate as upward trends continue, short positions benefit from sustained downward trends. The volatility scaling ensures that each position contributes roughly equal risk regardless of individual futures volatility. The strategy does not profit from mean-reversion. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| T | Look-back period for R_i and σ_i (days, weeks, or months) | +| η_i = sign(R_i) | Trend signal; +1 for uptrend, -1 for downtrend | +| σ_i | Historical volatility; normalises position size | +| γ | Scaling constant fixed by normalisation condition | +| κ | Smoothing parameter for tanh signal variant | + +## Variations +- **Cumulative return signal**: use E_i = R_i directly (rather than sign) for expected returns; more continuous but potentially noisy. +- **Non-diagonal covariance**: use a full covariance matrix C_ij for more accurate portfolio optimisation (see Section 3.18, Eq. 350). +- **Multiple time horizons**: combine short-term (days), medium-term (weeks), and long-term (months) trend signals to diversify across time scales. +- **Exponential moving averages / HP filter**: apply to returns to suppress noise before computing η_i (Sections 3, 8.1). + +## Notes +- The simple sign-based weights are not dollar-neutral by default; demeaning (Eq. 477) or the balanced variant (Eqs. 478-479) is required for dollar neutrality. +- Signal instability: for small |R_i| (compared to σ_i), η_i can flip on minor return changes; tanh smoothing mitigates this. +- Transaction costs are a meaningful drag because the strategy trades weekly or monthly and may have high turnover in trending markets that reverse. +- The strategy is broadly equivalent to standard managed futures / CTA approaches and has shown positive long-run performance across many asset classes and time periods. diff --git a/gateway/knowledge/trading/strategies/fx/carry-trade.md b/gateway/knowledge/trading/strategies/fx/carry-trade.md new file mode 100644 index 00000000..814fdb58 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fx/carry-trade.md @@ -0,0 +1,74 @@ +--- +description: "FX carry trade that exploits the empirical failure of Uncovered Interest Rate Parity by buying high-interest-rate currencies and selling low-interest-rate currencies via forward contracts." +tags: [fx, carry, interest-rate-differential, uirp] +--- + +# Carry Trade + +**Section**: 8.2 | **Asset Class**: FX | **Type**: Carry + +## Overview +Uncovered Interest Rate Parity (UIRP) predicts that the excess return from investing in a high-interest-rate currency should be exactly offset by that currency's depreciation. Empirically the opposite tends to hold: high-interest-rate currencies appreciate on average. The carry trade exploits this "forward premium/discount anomaly" (Fama puzzle) by writing (selling) forwards on currencies at a forward premium and buying forwards on currencies at a forward discount. + +## Construction / Mechanics +The UIRP condition (which does not reliably hold) is: + +``` +(1 + r_d) = [E_t(S(t+T)) / S(t)] × (1 + r_f) (440) +``` + +The no-arbitrage forward FX rate is given by Covered Interest Rate Parity (CIRP): + +``` +F(t,T) = S(t) × (1 + r_d) / (1 + r_f) (441) +``` + +- r_d: domestic risk-free interest rate +- r_f: foreign risk-free interest rate +- S(t): spot FX rate at time t (units of domestic currency per 1 unit of foreign) +- F(t,T): forward FX rate for delivery at T +- E_t(S(t+T)): expected future spot rate at time t + +**Trade logic:** +- If F(t,T) > S(t) (forward premium, i.e., r_d > r_f): **sell** the forward (borrow foreign, invest domestic) +- If F(t,T) < S(t) (forward discount, i.e., r_f > r_d): **buy** the forward (borrow domestic, invest foreign) + +## Return Profile +Profits when the carry differential is not fully offset by spot rate moves — i.e., when UIRP fails (the typical empirical finding). Losses occur if the borrowed currency suddenly appreciates sharply against the invested currency ("carry unwind" or "crash risk"). + +## Key Parameters / Signals +| Signal | Description | +|--------|-------------| +| F(t,T) > S(t) | Sell the forward (currency at forward premium) | +| F(t,T) < S(t) | Buy the forward (currency at forward discount) | +| Typical horizon T | 1 month | + +## Variations + +### 8.2.1 High-Minus-Low (HML) Carry +The carry trade can be applied cross-sectionally across a universe of N foreign currencies. Define the log forward discount for currency i: + +``` +D(t,T) = s(t) - f(t,T) (442) +``` + +where s(t) = ln(S(t)) and f(t,T) = ln(F(t,T)). By CIRP: + +``` +D(t,T) = ln((1 + r_f) / (1 + r_d)) ≈ r_f - r_d (443) +``` + +**Portfolio construction:** +- Positive D(t,T): buy a forward on that currency (higher foreign rate) +- Negative D(t,T): sell a forward on that currency (lower foreign rate) +- Sort all N currencies by D(t,T); go long the top quantile, short the bottom quantile +- Dollar-neutral (zero-cost) implementation by construction +- Forwards are typically one-month tenors; portfolio rebalanced monthly + +The cross-sectional spread captures the "high-minus-low" carry factor, analogous to HML in equity factor models. + +## Notes +- The single-pair carry trade is exposed to large drawdowns during "carry unwind" episodes (e.g., 2008), when risk-off flows reverse the trade sharply. +- Cross-sectional (HML) implementation diversifies idiosyncratic currency risk but retains systematic crash risk. +- Transaction costs (bid-ask spreads on forwards) are a meaningful drag, particularly for less-liquid currency pairs. +- The trade is equivalent to borrowing the low-rate currency and lending the high-rate currency when transaction costs and FX hedging costs are ignored. diff --git a/gateway/knowledge/trading/strategies/fx/dollar-carry-trade.md b/gateway/knowledge/trading/strategies/fx/dollar-carry-trade.md new file mode 100644 index 00000000..d27c0f71 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fx/dollar-carry-trade.md @@ -0,0 +1,45 @@ +--- +description: "Dollar carry trade that goes long or short all foreign currency forwards simultaneously based on the average cross-sectional forward discount relative to the USD." +tags: [fx, carry, dollar-risk, cross-sectional] +--- + +# Dollar Carry Trade + +**Section**: 8.3 | **Asset Class**: FX | **Type**: Carry / Macro + +## Overview +Rather than sorting currencies into long and short buckets based on individual forward discounts, the dollar carry trade takes a uniform long or short position in a basket of N foreign currencies relative to the USD. The signal is the average forward discount across all currencies. When this average is positive, the dollar is expensive on a carry basis and all foreign currency forwards are bought; when negative, all are sold. This trade is related to the broad strength or weakness of the U.S. economy. + +## Construction / Mechanics +Compute the average cross-sectional forward discount for a basket of N currencies: + +``` +D_bar(t,T) = (1/N) Σ D_i(t,T) (444) +``` + +where D_i(t,T) is the forward discount for currency i (see Eq. 442 in carry-trade.md). + +**Trade logic:** +- D_bar(t,T) > 0: go **long** all N foreign currency forwards with equal weights +- D_bar(t,T) < 0: go **short** all N foreign currency forwards with equal weights +- T can be 1, 2, 3, 6, or 12 months + +## Return Profile +Profits when the average forward discount correctly predicts the net direction of the USD against the foreign currency basket. Empirical evidence links positive average forward discounts to weak U.S. economic conditions, so the strategy also provides indirect macro exposure. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| N | Number of foreign currencies in the basket | +| T | Forward contract tenor (1, 2, 3, 6, or 12 months) | +| D_bar(t,T) | Average forward discount; positive = go long all forwards, negative = go short | + +## Variations +- The equal-weight long/short rule can be replaced by a weight proportional to each currency's individual D_i to incorporate cross-sectional dispersion. +- The basket can be restricted to G10 currencies or expanded to include EM currencies. + +## Notes +- The strategy is not dollar-neutral; it is an explicit bet on the direction of the USD versus a broad basket. +- Unlike the HML carry trade (Section 8.2.1), this strategy does not hedge out the common dollar factor and thus carries more systemic risk. +- Performance is empirically linked to U.S. business cycle conditions: when the U.S. economy is weak, the average forward discount tends to be positive, making the trade profitable in a carry sense. +- Correlations across currencies in the basket can be high during crisis periods, reducing the diversification benefit. diff --git a/gateway/knowledge/trading/strategies/fx/momentum-carry-combo.md b/gateway/knowledge/trading/strategies/fx/momentum-carry-combo.md new file mode 100644 index 00000000..ffbb30d7 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fx/momentum-carry-combo.md @@ -0,0 +1,57 @@ +--- +description: "FX combined strategy that blends the HP-filter moving-average momentum signal with the carry trade using minimum-variance portfolio weights to reduce overall volatility." +tags: [fx, carry, momentum, combination, minimum-variance] +--- + +# Momentum & Carry Combo + +**Section**: 8.4 | **Asset Class**: FX | **Type**: Combination (Momentum + Carry) + +## Overview +Both the FX momentum strategy (Section 8.1) and the carry trade (Section 8.2) capture distinct but complementary sources of FX returns. Combining them in an optimally weighted portfolio can reduce overall variance relative to either strategy alone. The weights are derived by minimising the historical variance of the combined return given the sample variances and correlation of the two strategy return series. + +## Construction / Mechanics +Let R₁(t_s) and R₂(t_s) be the historical return series of the momentum and carry strategies respectively. Define their sample statistics: + +``` +σ₁² = Var(R₁(t_s)) (445) +σ₂² = Var(R₂(t_s)) (446) +ρ = Cor(R₁(t_s), R₂(t_s)) (447) +``` + +The combined portfolio return is: + +``` +R(t_s) = w₁ R₁(t_s) + w₂ R₂(t_s) (448) +w₁ + w₂ = 1 (449) +Var(R(t_s)) → min (450) +``` + +Solving the constrained minimisation yields the minimum-variance weights: + +``` +w₁ = (σ₂² - σ₁σ₂ρ) / (σ₁² + σ₂² - 2σ₁σ₂ρ) (451) +w₂ = (σ₁² - σ₁σ₂ρ) / (σ₁² + σ₂² - 2σ₁σ₂ρ) (452) +``` + +## Return Profile +Profits from both the trend-following component (momentum captures trending FX moves) and the carry component (interest rate differential). The minimum-variance weighting reduces drawdowns when one strategy temporarily underperforms, particularly during carry unwinds when momentum may be positive. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| σ₁, σ₂ | Historical volatilities of momentum and carry strategy returns | +| ρ | Historical correlation between the two strategy returns | +| w₁, w₂ | Optimal weights (sum to 1); derived from sample covariance matrix | +| Estimation window | Rolling historical window for σ₁, σ₂, ρ | + +## Variations +- **Equal-weighted combo**: w₁ = w₂ = 0.5; simpler but ignores relative volatilities. +- **Risk-parity combo**: weight each strategy inversely to its volatility (σ₂/(σ₁+σ₂) and σ₁/(σ₁+σ₂)). +- **Extended combo**: include additional FX strategies (e.g., dollar carry, value) using the full sample covariance matrix (see Sections 3.6 and 4.6 for the general multi-strategy framework). + +## Notes +- The minimum-variance weights are sensitive to the estimation window; rolling windows introduce parameter instability. +- If ρ is close to 1, both strategies move together and diversification benefits are limited; if ρ is close to -1, the combo can nearly eliminate variance but requires large offsetting positions. +- The combo does not necessarily improve the Sharpe ratio compared with each individual strategy; it primarily targets variance reduction. +- Constraints (e.g., w₁, w₂ ≥ 0) may be applied to avoid short-selling a strategy that has negative expected return. diff --git a/gateway/knowledge/trading/strategies/fx/moving-averages-hp-filter.md b/gateway/knowledge/trading/strategies/fx/moving-averages-hp-filter.md new file mode 100644 index 00000000..bb930c0e --- /dev/null +++ b/gateway/knowledge/trading/strategies/fx/moving-averages-hp-filter.md @@ -0,0 +1,51 @@ +--- +description: "FX moving-average crossover strategy that first applies the Hodrick-Prescott filter to remove high-frequency noise from spot rates before computing the MA signals." +tags: [fx, momentum, moving-averages, trend-following] +--- + +# Moving Averages with HP Filter + +**Section**: 8.1 | **Asset Class**: FX | **Type**: Momentum / Trend-Following + +## Overview +FX spot rate time series are noisier than equity prices, which leads to false signals when raw rates are used in standard moving-average crossover strategies. The Hodrick-Prescott (HP) filter first decomposes the spot rate into a smooth lower-frequency trend component S*(t) and a higher-frequency noise component ν(t). Moving averages are then computed on S*(t) rather than the raw rate, substantially reducing whipsaws. + +## Construction / Mechanics +The HP filter minimises a penalised objective that trades off fit against smoothness: + +``` +S(t) = S*(t) + ν(t) (437) + +g = Σ[S(t) - S*(t)]² + λ Σ[S*(t+1) - 2S*(t) + S*(t-1)]² (438) +g → min (439) +``` + +- S(t): raw FX spot rate at time t +- S*(t): smooth ("regular") lower-frequency component +- ν(t): higher-frequency ("irregular") noise, treated as noise +- λ: smoothing parameter (penalises variation in the second discrete derivative of S*(t)) +- Common convention: λ = 100 × n², where n is the data frequency in years (e.g., n = 12 for monthly data gives λ = 14,400) + +Once S*(t) is obtained, two moving averages MA(T₁) and MA(T₂) with T₁ < T₂ are calculated on S*(t): +- MA(T₁) > MA(T₂): **buy signal** (go long the foreign currency) +- MA(T₁) < MA(T₂): **sell signal** (go short the foreign currency) + +## Return Profile +Profits when FX trends persist long enough for the shorter MA to remain above (below) the longer MA. The HP filter reduces false crossovers caused by transient noise, improving the signal-to-noise ratio versus raw-rate MAs. + +## Key Parameters / Signals +| Parameter | Typical Value | Description | +|-----------|--------------|-------------| +| λ | 100 × n² | Smoothing parameter; n = data frequency in years | +| T₁ | shorter window | Fast MA period (computed on S*(t)) | +| T₂ | longer window | Slow MA period (computed on S*(t)); T₁ < T₂ | +| Estimation period | Several years of monthly data | Used to fit S*(t) | + +## Variations +- The HP filter can be replaced by other smoothing techniques (Kalman filter, exponential moving averages) to extract the trend component before computing MAs. +- The underlying MA crossover logic is identical to the equity version (Section 3.12); only the input series differs. + +## Notes +- λ has no universally optimal value; the common heuristic λ = 100n² may not be best for all currency pairs or market regimes. +- The HP filter is backward-looking and non-causal in real time (two-sided filter); practitioners often use the one-sided (real-time) variant to avoid look-ahead bias. +- FX markets are highly liquid but subject to central-bank interventions that can abruptly break trends. diff --git a/gateway/knowledge/trading/strategies/fx/triangular-arbitrage.md b/gateway/knowledge/trading/strategies/fx/triangular-arbitrage.md new file mode 100644 index 00000000..71992d38 --- /dev/null +++ b/gateway/knowledge/trading/strategies/fx/triangular-arbitrage.md @@ -0,0 +1,52 @@ +--- +description: "FX triangular arbitrage that exploits momentary mispricing across three currency pairs by executing a circular chain of exchanges to lock in a riskless profit." +tags: [fx, arbitrage, triangular, market-microstructure] +--- + +# FX Triangular Arbitrage + +**Section**: 8.5 | **Asset Class**: FX | **Type**: Arbitrage + +## Overview +Triangular arbitrage involves three currencies (A, B, C) and three currency pairs. If the cross-rate implied by trading A→B→C→A differs from the direct rate, a riskless profit exists. Such mispricings are extremely short-lived and require fast market data feeds and execution systems. + +## Construction / Mechanics +Given three currencies A, B, C and their bid/ask prices, there are two chains: +1. A → B → C → A +2. A → C → B → A (equivalent to swapping B and C in chain 1) + +Focus on chain 1. The relevant rates are: +- Bid(A→B): rate at which A is exchanged into B +- Bid(B→C): rate at which B is exchanged into C +- Ask(C→A): rate at which C is exchanged back into A (cost = 1/Ask(C→A)) + +Note: Bid(B→A) = 1/Ask(B→A) and Ask(A→B) = 1/Bid(A→B). + +The overall round-trip exchange rate for chain 1 is: + +``` +R(A→B→C→A) = Bid(A→B) × Bid(B→C) × (1 / Ask(C→A)) (453) +``` + +**Profit condition:** If R(A→B→C→A) > 1, the trader profits by executing all three legs simultaneously. Starting with 1 unit of A, the trader ends with R > 1 units of A. + +## Return Profile +The P&L per unit of A is R - 1 when R > 1. Profits are typically very small per trade (fractions of a pip) but can be accumulated at high frequency. The strategy is notionally riskless if all three legs are executed simultaneously; execution lag introduces market risk. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| R(A→B→C→A) | Round-trip rate; > 1 signals a profitable arbitrage | +| Bid(A→B), Bid(B→C) | Bid rates for the two intermediate legs | +| Ask(C→A) | Ask rate for the closing leg | +| Execution speed | Critical: mispricings disappear in milliseconds | + +## Variations +- **Multi-currency arbitrage**: extend to more than 3 currency pairs (N-currency chains); computational complexity increases but can uncover deeper mispricings. +- **Chain 2** (A→C→B→A): identical logic with B and C swapped; both chains should be monitored simultaneously. + +## Notes +- Opportunities are ephemeral; the strategy is effectively a latency arbitrage and is dominated by high-frequency traders with co-located infrastructure. +- Bid-ask spreads are the primary cost; even small spreads can eliminate the theoretical profit, so only very tight markets are viable. +- Unlike statistical arbitrage, this is a near-deterministic arbitrage: no model risk, but significant execution/technology risk. +- Applicable to crypto exchanges where cross-exchange and cross-pair mispricings can be larger and more persistent than in professional FX markets. diff --git a/gateway/knowledge/trading/strategies/global-macro/economic-announcements.md b/gateway/knowledge/trading/strategies/global-macro/economic-announcements.md new file mode 100644 index 00000000..8c3863d0 --- /dev/null +++ b/gateway/knowledge/trading/strategies/global-macro/economic-announcements.md @@ -0,0 +1,62 @@ +--- +description: "A macro strategy that holds equities exclusively on important economic announcement days (FOMC, etc.) and switches to risk-free assets on all other days, exploiting the empirical announcement premium." +tags: [global-macro, event-driven, fomc, announcement, equities] +--- + +# Trading on Economic Announcements + +**Section**: 19.5 | **Asset Class**: Global Macro | **Type**: Event-driven / Calendar-based + +## Overview + +Empirical evidence suggests that stocks tend to yield higher returns on important announcement dates — such as Federal Open Market Committee (FOMC) announcement days — than on other trading days. A simple macro trading strategy exploits this "announcement premium" by holding equities (via ETFs or futures) only on announcement days (ADs) and switching to risk-free assets (e.g., Treasuries) during all non-announcement days (NDAs). The strategy rotates 100% between equity exposure and Treasury exposure based solely on the calendar of scheduled announcements. + +## Construction / Mechanics + +### Signal Construction + +1. Identify a set of important economic announcement dates (ADs). The primary example is FOMC announcement days, but other relevant announcements may include: + - Non-Farm Payrolls (NFP) + - CPI/inflation releases + - GDP advance estimates + - Other major central bank decisions (ECB, BoE, etc.) + +2. For each trading day `t`: + - If `t` is an announcement day (AD): hold equity ETFs/futures + - If `t` is a non-announcement day (NDA): hold risk-free assets (e.g., T-bills or short-term Treasuries) + +### Execution + +- Implemented via ETFs (e.g., SPY for U.S. equities, SHY/BIL for short-term Treasuries) or futures (e.g., E-mini S&P 500 futures + T-bond futures) +- Positions are switched at the open or close on the day before/day of each announcement +- The strategy moves from 100% equities on ADs to 100% Treasuries on NDAs (binary switching) +- Individual stocks are not used — the strategy operates at the index/ETF level + +### Optional Technical Filters + +The basic binary strategy can be augmented with various technical filters (e.g., momentum filters on the equity index) to further refine the signal and potentially improve the risk-adjusted return profile. + +## Return Profile / Objective + +The strategy captures the empirically documented "announcement premium" — the excess return accruing to equity holders on announcement days relative to non-announcement days. By being fully invested in equities only on ADs and earning the risk-free rate otherwise, the strategy aims to achieve equity-like returns with substantially reduced time-in-market and potentially lower overall risk. Returns are driven by the persistence of the announcement premium rather than by market direction. + +## Key Parameters / Signals + +- **Announcement calendar**: the set of ADs used (FOMC dates are the primary source; typically 8 per year for FOMC) +- **Equity instrument**: broad index ETF or futures (e.g., S&P 500) +- **Risk-free instrument**: T-bills, overnight repo, or short-term Treasury ETF +- **Switching timing**: day-before close vs. announcement-day open; affects transaction costs +- **Technical filter (optional)**: momentum or trend filter applied to the equity index to gate the switch +- **Announcement types included**: FOMC only vs. broader macro announcement set + +## Variations + +- **Multi-announcement strategy**: include NFP, CPI, GDP, and other macro releases in addition to FOMC +- **International extension**: apply to other central bank announcements (ECB, BoJ, BoE) for non-U.S. equity indexes +- **Sector rotation on announcements**: hold rate-sensitive sectors on specific announcement types +- **Options-based implementation**: use straddles around announcement dates to capture realized volatility premium +- **Partial allocation**: hold a fixed fraction (e.g., 50%) in equities always, and increase to 100% only on ADs + +## Notes + +The existence and persistence of the FOMC announcement premium is well-documented in the academic literature (Savor and Wilson, 2013; Lucca and Moench, 2012). The premium is thought to reflect compensation for macroeconomic uncertainty resolved at announcement events. Transaction costs are relatively low given the infrequent switching (8 FOMC dates per year). The strategy's main risk is that the announcement premium may attenuate or disappear if it becomes widely exploited. Technical filters can help adapt to changing regimes. Because the strategy uses ETFs rather than individual stocks, execution is straightforward and liquidity is not a constraint for most portfolio sizes. diff --git a/gateway/knowledge/trading/strategies/global-macro/fundamental-macro-momentum.md b/gateway/knowledge/trading/strategies/global-macro/fundamental-macro-momentum.md new file mode 100644 index 00000000..44c469be --- /dev/null +++ b/gateway/knowledge/trading/strategies/global-macro/fundamental-macro-momentum.md @@ -0,0 +1,59 @@ +--- +description: "A systematic macro momentum strategy that buys assets favored by incoming macroeconomic trends and sells adversely affected assets, using four state variables to rank global equity indexes, currencies, and bonds." +tags: [global-macro, momentum, systematic, multi-asset] +--- + +# Fundamental Macro Momentum + +**Section**: 19.2 | **Asset Class**: Global Macro | **Type**: Systematic momentum / Cross-sectional ranking + +## Overview + +This strategy aims to capture returns from the market's underreaction to changes in macroeconomic trends by buying assets favored by incoming macroeconomic trends and selling (shorting) assets adversely affected by them. It is a systematic (non-discretionary) strategy that can be applied across different asset classes — global equity indexes, currencies, government bonds, commodities, etc. — and exploits the tendency of prices to lag macroeconomic fundamentals. + +## Construction / Mechanics + +### State Variables + +Four macroeconomic state variables are used to characterize conditions in each country: + +1. **Business cycle trend**: estimated using 1-year changes in real GDP growth and CPI inflation forecast, each contributing with a 50% weight +2. **International trade trend**: estimated using 1-year changes in spot FX rates against an export-weighted basket +3. **Monetary policy trend**: estimated using 1-year changes in short-term interest rates +4. **Risk sentiment trend**: estimated using 1-year equity market excess returns + +Note: different asset classes are affected by macroeconomic trends differently. For example, increasing growth is positive for equities and currencies but negative for bonds. + +### Portfolio Construction + +1. For a given asset class (e.g., global equity indexes), rank each country's asset using the values of the four state variables +2. Construct a zero-cost long-short portfolio by going long the assets in the top decile and shorting those in the bottom decile +3. Portfolios for various asset classes can be combined, e.g., with equal weights +4. Holding period typically ranges from three to six months + +Multiple ranking and portfolio construction methods are available (see also Subsection 3.6 for multifactor portfolio construction approaches). + +## Return Profile / Objective + +Returns are driven by the market's systematic underreaction to macroeconomic trends: as trends gradually become recognized by market participants, prices adjust and the long positions appreciate while short positions decline. The strategy is fundamentally a momentum strategy but grounded in macroeconomic state variables rather than pure price momentum. Typical holding periods of 3–6 months mean lower turnover and transaction costs compared to short-term momentum. + +## Key Parameters / Signals + +- **Business cycle signal**: 1-year change in real GDP growth + CPI inflation forecast (50/50 weight) +- **International trade signal**: 1-year change in spot FX rate vs. export-weighted basket +- **Monetary policy signal**: 1-year change in short-term rates +- **Risk sentiment signal**: 1-year equity market excess return +- **Decile cutoffs**: top/bottom decile thresholds for portfolio construction +- **Asset class weighting**: equal weight across combined asset class portfolios +- **Holding period**: 3–6 months typical + +## Variations + +- **Single asset class**: apply the strategy only to equity indexes, only to currencies, or only to government bonds +- **Broader factor set**: add additional state variables (e.g., current account balance, credit conditions) +- **Discretionary overlay**: combine the systematic signal with analyst judgment +- **CTA/managed futures extension**: apply the framework to futures contracts on equity indexes, bonds, and currencies + +## Notes + +Macro trading strategies constitute an investment style, not an asset class — they are not limited to any particular asset class or geographic region. The strategy can be classified as directional, long-short, or relative value depending on implementation. The three broad categories of macro strategies are discretionary macro, systematic macro, and CTA/managed futures. This strategy falls in the systematic macro category. Transaction costs are relatively modest given the 3–6 month holding period, but liquidity varies significantly across country assets. Care must be taken when applying this strategy to emerging markets where data quality and market access can be constraints. diff --git a/gateway/knowledge/trading/strategies/global-macro/global-fixed-income.md b/gateway/knowledge/trading/strategies/global-macro/global-fixed-income.md new file mode 100644 index 00000000..69403c32 --- /dev/null +++ b/gateway/knowledge/trading/strategies/global-macro/global-fixed-income.md @@ -0,0 +1,63 @@ +--- +description: "A systematic macro strategy that ranks government bonds from multiple countries using fundamental factors (GDP, inflation, sovereign risk, real interest rate, momentum, term spread, Cochrane-Piazzesi) to construct a zero-cost long-short bond portfolio." +tags: [global-macro, fixed-income, bonds, systematic, factor-investing] +--- + +# Global Fixed-Income Strategy + +**Section**: 19.4 | **Asset Class**: Global Macro | **Type**: Systematic / Cross-sectional factor investing + +## Overview + +This systematic macro trading strategy is based on a cross-sectional analysis of government bonds from various countries. Bonds are ranked using a set of fundamental and quantitative factors, and a zero-cost long-short portfolio is constructed by buying top-ranked bonds and selling bottom-ranked bonds. Country-bond ETFs are typically used as the investment vehicle. + +## Construction / Mechanics + +### Factor Set + +Government bonds are evaluated and ranked using the following variables: + +1. **GDP**: economic growth expectations; stronger GDP growth typically is negative for bonds (higher rates expected) +2. **Inflation**: higher inflation erodes bond values; used as a negative signal for bonds +3. **Sovereign risk**: credit quality of the government issuer; higher sovereign risk is negative for bonds +4. **Real interest rate**: nominal rate minus inflation; higher real rates may indicate better bond valuations +5. **Output gap**: difference between actual and potential GDP; affects future inflation and monetary policy expectations +6. **Value**: valuation metric for bonds (e.g., yield relative to historical norms) +7. **Momentum**: recent price/return trend of the bond +8. **Term spread**: difference between long-term and short-term yields; an indicator of the yield curve shape and expected monetary policy +9. **Cochrane-Piazzesi predictor**: a combination of forward rates that predicts excess bond returns (from Cochrane and Piazzesi, 2005) + +### Portfolio Construction + +1. For each country, compute the factor scores for its government bond +2. Rank bonds across all countries based on the combined factor scores +3. Construct a zero-cost portfolio: buy bonds in the top quantile, sell bonds in the bottom quantile +4. Multifactor portfolios can also be constructed (analogous to Subsection 3.6) +5. Investment vehicle: typically country-bond ETFs + +## Return Profile / Objective + +Returns are driven by systematic differences in bond valuations and expected returns across countries, as captured by the factor set. The strategy captures value, momentum, carry, and macro-fundamental signals simultaneously. Because it is long-short and zero-cost, returns are driven purely by relative differences rather than by the overall level of bond markets. The Cochrane-Piazzesi predictor specifically targets excess return predictability from the term structure of interest rates. + +## Key Parameters / Signals + +- **GDP growth**: typically 1-year change; positive for equities, negative for bonds +- **Inflation**: YoY CPI; negative for nominal bonds +- **Sovereign risk**: credit rating or CDS spread; negative signal for bonds +- **Real interest rate**: nominal yield minus breakeven inflation +- **Output gap**: estimated as deviation of GDP from potential (HP filter or similar) +- **Value**: yield spread vs. historical average or fair-value model +- **Momentum**: 12-month (or other lookback) return of the bond/ETF +- **Term spread**: 10Y-2Y yield spread or similar +- **Cochrane-Piazzesi (CP) predictor**: `cp_t = a + b * (y^5_t - (1/5)*sum_{n=1}^{5} f^n_t)` — a linear combination of forward rates that predicts excess returns on bonds + +## Variations + +- **Single-factor strategies**: pure momentum, pure value, or pure carry in government bonds +- **Equity + bond combined macro**: extend the fundamental macro momentum framework (Section 19.2) to include bond rankings alongside equity index rankings +- **Emerging market bonds**: apply the framework to EM sovereign debt, with additional currency risk considerations +- **Corporate bond extension**: apply analogous factors to cross-sectional corporate bond strategies + +## Notes + +Cross-sectional government bond strategies require careful attention to currency risk — unless currency-hedged, returns are affected by both bond prices and exchange rate movements. Country-bond ETFs provide liquid access but may introduce tracking error relative to the underlying bond indexes. The Cochrane-Piazzesi predictor has been widely studied and validated in the academic literature for predicting U.S. Treasury excess returns, and has been extended internationally. Factor construction requires consistent data across countries, which can be challenging for some emerging market sovereign bonds. diff --git a/gateway/knowledge/trading/strategies/global-macro/inflation-hedge.md b/gateway/knowledge/trading/strategies/global-macro/inflation-hedge.md new file mode 100644 index 00000000..94f8a006 --- /dev/null +++ b/gateway/knowledge/trading/strategies/global-macro/inflation-hedge.md @@ -0,0 +1,77 @@ +--- +description: "A global macro inflation hedging strategy that allocates to commodities based on the spread between headline and core inflation, using ETFs or futures to execute the hedge." +tags: [global-macro, inflation, commodities, hedging] +--- + +# Global Macro Inflation Hedge + +**Section**: 19.3 | **Asset Class**: Global Macro | **Type**: Inflation hedging / Commodity allocation + +## Overview + +Exogenous shocks — such as political or geopolitical events — can cause commodity prices (e.g., oil) to rise, leading to increased prices in oil-dependent economies. This strategy uses the spread between headline inflation (HI) and core inflation (CI) as a signal to determine the appropriate commodity allocation within a portfolio as an inflation hedge. The hedge is executed via ETFs, futures, or direct commodity exposure. + +## Construction / Mechanics + +### Inflation Pass-Through Mechanism + +There are two steps in the inflation transmission process: + +1. **Pass-through from commodity prices to headline inflation (HI)**: commodity price shocks quickly reflect in the headline Consumer Price Index (CPI), which covers a broad basket of goods and services +2. **Pass-through from HI to core inflation (CI)**: core inflation excludes commodities (and other volatile components like food) and adjusts more slowly + +**HI** is the raw inflation measured by indices such as the Consumer Price Index (CPI) based on prices of goods and services in a broad basket. +**CI** excludes some products such as commodities, which are highly volatile and add noise to the index. + +HI quickly reflects exogenous shocks around the world, while CI lags. + +### Commodity Allocation Formula + +The commodity allocation percentage (CA) within the portfolio is: + +``` +CA = max(0, min(HI_YoY - CI_YoY / HI_YoY, 1)) (547) +``` + +More precisely: +``` +CA = max(0, min((HI_YoY - CI_YoY) / HI_YoY, 1)) +``` + +Where "YoY" stands for "year-on-year" change in the respective inflation measure. + +**Interpretation:** +- When `HI_YoY > CI_YoY`: the commodity-driven component of inflation is elevated; increase commodity allocation +- When `HI_YoY <= CI_YoY`: no commodity-driven inflation premium; commodity allocation goes to zero +- The formula is capped at 1 (100%) to prevent over-allocation +- The floor at 0 prevents negative (short) commodity allocation + +### Execution + +The commodity exposure can be implemented by buying a basket of various commodities through: +- ETFs (e.g., broad commodity ETFs, energy ETFs) +- Futures contracts on commodity indexes or individual commodities +- Direct commodity positions + +## Return Profile / Objective + +The strategy profits when commodity prices rise and the portfolio's commodity allocation benefits from this appreciation, offsetting inflationary erosion of the rest of the portfolio. The return profile is asymmetric: the allocation increases when the inflation signal is elevated and goes to zero when it is absent. This is a hedging strategy, so the primary objective is inflation protection rather than alpha generation. + +## Key Parameters / Signals + +- **HI_YoY**: year-on-year headline inflation rate (e.g., CPI) +- **CI_YoY**: year-on-year core inflation rate (CPI excluding volatile components) +- **Spread (HI - CI)**: the commodity-driven inflation component; the hedge signal +- **CA**: resulting commodity allocation percentage, bounded in [0, 1] +- **Commodity basket composition**: choice of ETFs or futures instruments used to implement the allocation + +## Variations + +- **Sector-specific commodity hedge**: allocate specifically to energy, metals, or agricultural commodities depending on the shock source +- **Gold-only hedge**: use gold as the sole inflation hedge instrument (simpler but less diversified) +- **TIPS overlay**: complement commodity allocation with Treasury Inflation-Protected Securities (TIPS) +- **Dynamic basket rebalancing**: adjust the commodity basket weights based on which commodity categories are driving HI above CI + +## Notes + +Infrastructure assets (Chapter 20) can also serve as an inflation hedge, albeit with some heterogeneity. The two-step pass-through mechanism (commodity prices → HI → CI) means CI is a lagging indicator, providing a systematic signal with some temporal stability. The strategy is inherently defensive — it reduces underperformance during inflationary episodes without requiring a directional forecast on commodity prices per se. The formula naturally results in zero allocation during stable, non-commodity-driven inflation environments, which is appropriate since unneeded commodity exposure introduces unnecessary volatility. diff --git a/gateway/knowledge/trading/strategies/index.md b/gateway/knowledge/trading/strategies/index.md new file mode 100644 index 00000000..0709decb --- /dev/null +++ b/gateway/knowledge/trading/strategies/index.md @@ -0,0 +1,301 @@ +--- +description: "Master catalog of 150+ trading strategies organized by asset class. Load this page first, then use MemoryLookup with a specific page name to drill into any strategy's full details, formulas, and mechanics." +tags: [trading, strategies, index, catalog] +--- + +# Trading Strategies — Master Index + +Source: *151 Trading Strategies* (Kakushadze & Serur, 2018). Each strategy has a dedicated knowledge page. + +**Usage:** `MemoryLookup({page: "trading/strategies//"})` — e.g. `MemoryLookup({page: "trading/strategies/options/covered-call"})` + +--- + +## Options (Chapter 2) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 2.2 | Covered call | Buy stock + sell call; income strategy capping upside | `options/covered-call` | +| 2.3 | Covered put | Short stock + sell put; income with neutral-to-bearish bias | `options/covered-put` | +| 2.4 | Protective put | Long stock + long put; hedges downside, preserves upside | `options/protective-put` | +| 2.5 | Protective call | Short stock + long call; hedges upside risk on short position | `options/protective-call` | +| 2.6 | Bull call spread | Buy near-ATM call, sell OTM call; capped bullish bet | `options/bull-call-spread` | +| 2.7 | Bull put spread | Sell higher put, buy lower put; credit-based bullish bet | `options/bull-put-spread` | +| 2.8 | Bear call spread | Sell lower call, buy higher call; credit-based bearish bet | `options/bear-call-spread` | +| 2.9 | Bear put spread | Buy near-ATM put, sell OTM put; capped bearish bet | `options/bear-put-spread` | +| 2.10 | Long synthetic forward | Long call + short put at same strike; replicates long forward | `options/long-synthetic-forward` | +| 2.11 | Short synthetic forward | Long put + short call at same strike; replicates short forward | `options/short-synthetic-forward` | +| 2.12 | Long combo | Buy OTM call + sell OTM put; bullish risk reversal | `options/long-combo` | +| 2.13 | Short combo | Buy OTM put + sell OTM call; bearish risk reversal | `options/short-combo` | +| 2.14 | Bull call ladder | Bull call spread + sell higher OTM call; limited upside, unlimited risk above K3 | `options/bull-call-ladder` | +| 2.15 | Bull put ladder | Short near-ATM put + buy two lower OTM puts; bearish adjustment | `options/bull-put-ladder` | +| 2.16 | Bear call ladder | Short near-ATM call + buy two higher OTM calls; bullish adjustment | `options/bear-call-ladder` | +| 2.17 | Bear put ladder | Bear put spread + sell lower OTM put; unlimited downside risk | `options/bear-put-ladder` | +| 2.18 | Calendar call spread | Long far-dated call, short near-dated call at same strike; exploits time decay | `options/calendar-call-spread` | +| 2.19 | Calendar put spread | Long far-dated put, short near-dated put at same strike; exploits time decay | `options/calendar-put-spread` | +| 2.20 | Diagonal call spread | Long deep ITM far-dated call, short OTM near-dated call; combines direction + decay | `options/diagonal-call-spread` | +| 2.21 | Diagonal put spread | Long deep ITM far-dated put, short OTM near-dated put; combines direction + decay | `options/diagonal-put-spread` | +| 2.22 | Long straddle | Buy ATM call + put; profits from large move either direction | `options/long-straddle` | +| 2.23 | Long strangle | Buy OTM call + OTM put; cheaper volatility play than straddle | `options/long-strangle` | +| 2.24 | Long guts | Buy ITM call + ITM put; pricier volatility play than straddle | `options/long-guts` | +| 2.25 | Short straddle | Sell ATM call + put; income when stock stays near strike | `options/short-straddle` | +| 2.26 | Short strangle | Sell OTM call + OTM put; wider profit zone than short straddle | `options/short-strangle` | +| 2.27 | Short guts | Sell ITM call + ITM put; higher credit, narrower profit zone | `options/short-guts` | +| 2.28 | Long call synthetic straddle | Short stock + buy 2 ATM calls; replicates long straddle | `options/long-call-synthetic-straddle` | +| 2.29 | Long put synthetic straddle | Long stock + buy 2 ATM puts; replicates long straddle | `options/long-put-synthetic-straddle` | +| 2.30 | Short call synthetic straddle | Long stock + sell 2 ATM calls; replicates short straddle | `options/short-call-synthetic-straddle` | +| 2.31 | Short put synthetic straddle | Short stock + sell 2 ATM puts; replicates short straddle | `options/short-put-synthetic-straddle` | +| 2.32 | Covered short straddle | Covered call + short ATM put; higher income, more downside risk | `options/covered-short-straddle` | +| 2.33 | Covered short strangle | Covered call + short OTM put; wider profit zone | `options/covered-short-strangle` | +| 2.34 | Strap | Buy 2 ATM calls + 1 ATM put; bullish volatility bias | `options/strap` | +| 2.35 | Strip | Buy 1 ATM call + 2 ATM puts; bearish volatility bias | `options/strip` | +| 2.36 | Call ratio backspread | Sell fewer near-ATM calls, buy more OTM calls; strongly bullish | `options/call-ratio-backspread` | +| 2.37 | Put ratio backspread | Sell fewer near-ATM puts, buy more OTM puts; strongly bearish | `options/put-ratio-backspread` | +| 2.38 | Ratio call spread | Buy fewer ITM calls, sell more near-ATM calls; income with unlimited upside risk | `options/ratio-call-spread` | +| 2.39 | Ratio put spread | Buy fewer ITM puts, sell more near-ATM puts; income with unlimited downside risk | `options/ratio-put-spread` | +| 2.40 | Long call butterfly | Buy ITM + OTM calls, sell 2 ATM calls; profits if stock stays near middle strike | `options/long-call-butterfly` | +| 2.41 | Long put butterfly | Buy ITM + OTM puts, sell 2 ATM puts; profits if stock stays near middle strike | `options/long-put-butterfly` | +| 2.42 | Short call butterfly | Sell ITM + OTM calls, buy 2 ATM calls; profits from large move | `options/short-call-butterfly` | +| 2.43 | Short put butterfly | Sell ITM + OTM puts, buy 2 ATM puts; profits from large move | `options/short-put-butterfly` | +| 2.44 | Long iron butterfly | Bull put spread + bear call spread around ATM; income near center | `options/long-iron-butterfly` | +| 2.45 | Short iron butterfly | Bear put spread + bull call spread around ATM; profits from large move | `options/short-iron-butterfly` | +| 2.46 | Long call condor | 4-leg call spread; profits if stock stays between inner strikes | `options/long-call-condor` | +| 2.47 | Long put condor | 4-leg put spread; profits if stock stays between inner strikes | `options/long-put-condor` | +| 2.48 | Short call condor | Inverse 4-leg call spread; profits from large move | `options/short-call-condor` | +| 2.49 | Short put condor | Inverse 4-leg put spread; profits from large move | `options/short-put-condor` | +| 2.50 | Long iron condor | OTM bull put spread + OTM bear call spread; income in wide range | `options/long-iron-condor` | +| 2.51 | Short iron condor | OTM bear put spread + OTM bull call spread; profits from large move | `options/short-iron-condor` | +| 2.52 | Long box | Long + short synthetic forward at different strikes; locks in fixed arbitrage payoff | `options/long-box` | +| 2.53 | Collar | Long stock + long OTM put + short OTM call; defined risk/reward range | `options/collar` | +| 2.54 | Bullish short seagull spread | Bull call spread financed by short OTM put; zero-cost bullish structure | `options/bullish-short-seagull-spread` | +| 2.55 | Bearish long seagull spread | Short combo hedged by long OTM call; zero-cost bearish structure | `options/bearish-long-seagull-spread` | +| 2.56 | Bearish short seagull spread | Bear put spread financed by short OTM call; zero-cost bearish structure | `options/bearish-short-seagull-spread` | +| 2.57 | Bullish long seagull spread | Long combo hedged by long OTM put; zero-cost bullish structure | `options/bullish-long-seagull-spread` | + +--- + +## Stocks (Chapter 3) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 3.1 | Price-momentum | Buy past winners, short past losers based on 12-month cumulative return | `stocks/price-momentum` | +| 3.2 | Earnings-momentum | Buy high-SUE stocks, short low-SUE; captures post-earnings drift | `stocks/earnings-momentum` | +| 3.3 | Value | Buy high Book-to-Price stocks, short low B/P; exploits value premium | `stocks/value` | +| 3.4 | Low-volatility anomaly | Buy low-vol stocks, short high-vol; low risk = higher risk-adjusted return | `stocks/low-volatility-anomaly` | +| 3.5 | Implied volatility | Buy stocks with rising call IV, short those with rising put IV | `stocks/implied-volatility` | +| 3.6 | Multifactor portfolio | Blend multiple ranking factors (value + momentum etc.) by averaging ranks | `stocks/multifactor-portfolio` | +| 3.7 | Residual momentum | Momentum on Fama-French regression residuals, stripping common factors | `stocks/residual-momentum` | +| 3.8 | Pairs trading | Long cheap stock, short rich stock in correlated pair when spread deviates | `stocks/pairs-trading` | +| 3.9 | Mean-reversion – cluster | Generalize pairs to N-stock cluster; buy underperformers, short outperformers | `stocks/mean-reversion-cluster` | +| 3.10 | Mean-reversion – weighted regression | Continuous loadings matrix extension of cluster mean-reversion | `stocks/mean-reversion-weighted-regression` | +| 3.11 | Single moving average | Long/short when price crosses a single MA | `stocks/single-moving-average` | +| 3.12 | Two moving averages | Long/short on MA crossover (short vs. long window) | `stocks/two-moving-averages` | +| 3.13 | Three moving averages | Require all three MAs to align before entering | `stocks/three-moving-averages` | +| 3.14 | Support and resistance | Trade pivot-point-derived support/resistance levels | `stocks/support-and-resistance` | +| 3.15 | Channel | Donchian channel mean-reversion or breakout | `stocks/channel` | +| 3.16 | Event-driven – M&A | Merger arbitrage: long target, short acquirer in stock deals | `stocks/event-driven-ma` | +| 3.17 | Machine learning – KNN | KNN regression on price/volume features to predict forward returns | `stocks/ml-knn` | +| 3.18 | Statistical arbitrage – optimization | Maximize Sharpe via covariance matrix optimization; dollar-neutral variant | `stocks/statistical-arbitrage-optimization` | +| 3.19 | Market-making | Earn bid-ask spread via passive limit orders with directional signal filter | `stocks/market-making` | +| 3.20 | Alpha combos | Combine many weak alpha signals into a mega-alpha via structured optimization | `stocks/alpha-combos` | + +--- + +## ETFs (Chapter 4) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 4.1 | Sector momentum rotation | Overweight top-momentum sector ETFs; with MA filter and dual-momentum variants | `etfs/sector-momentum-rotation` | +| 4.2 | Alpha rotation | Rotate into sector ETFs with highest Jensen's alpha from factor regression | `etfs/alpha-rotation` | +| 4.3 | R-squared | Overweight low-R² (high selectivity) high-alpha ETFs | `etfs/r-squared` | +| 4.4 | Mean-reversion | Long low-IBS ETFs, short high-IBS ETFs (daily mean-reversion) | `etfs/mean-reversion` | +| 4.5 | Leveraged ETFs | Short both leveraged ETF and its inverse to harvest daily decay | `etfs/leveraged-etfs` | +| 4.6 | Multi-asset trend following | Long-only momentum across asset-class ETFs, volatility-weighted | `etfs/multi-asset-trend-following` | + +--- + +## Fixed Income (Chapter 5) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 5.1 | Generalities | Bond mechanics: zero-coupon, coupon, floaters, swaps, duration, convexity | `fixed-income/generalities` | +| 5.2 | Bullets | Hold bonds at a single target maturity to express a rate view | `fixed-income/bullets` | +| 5.3 | Barbells | Hold two maturity extremes; higher convexity than equivalent bullet | `fixed-income/barbells` | +| 5.4 | Ladders | Equal-capital allocation across n equidistant maturities | `fixed-income/ladders` | +| 5.5 | Bond immunization | Match portfolio duration to liability maturity to hedge rate risk | `fixed-income/bond-immunization` | +| 5.6 | Dollar-duration-neutral butterfly | Long barbell + short bullet; neutral to parallel shifts, bets on curvature | `fixed-income/dollar-duration-neutral-butterfly` | +| 5.7 | Fifty-fifty butterfly | Butterfly with equal wing dollar durations | `fixed-income/fifty-fifty-butterfly` | +| 5.8 | Regression-weighted butterfly | Butterfly with empirically estimated wing weights; maturity-weighted variant | `fixed-income/regression-weighted-butterfly` | +| 5.9 | Low-risk factor | Buy lowest-maturity bonds within IG/HY tier; exploits low-risk anomaly | `fixed-income/low-risk-factor` | +| 5.10 | Value factor | Buy bonds with spread above regression-implied fair value | `fixed-income/value-factor` | +| 5.11 | Carry factor | Long top-decile bonds by total carry (yield + roll-down) | `fixed-income/carry-factor` | +| 5.12 | Rolling down the yield curve | Buy bonds in steepest curve segments and hold through roll-down appreciation | `fixed-income/rolling-down-yield-curve` | +| 5.13 | Yield curve spread | Flattener or steepener trade between two maturities, duration-matched | `fixed-income/yield-curve-spread` | +| 5.14 | CDS basis arbitrage | Buy bond + buy CDS protection when negative basis creates near-riskless carry | `fixed-income/cds-basis-arbitrage` | +| 5.15 | Swap-spread arbitrage | Long/short IRS vs. Treasury at same maturity; captures LIBOR-repo spread | `fixed-income/swap-spread-arbitrage` | + +--- + +## Indexes (Chapter 6) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 6.1 | Generalities | Index construction, futures/ETF vehicles, spot-futures pricing, basis | `indexes/generalities` | +| 6.2 | Cash-and-carry arbitrage | Trade basis when index futures deviate from fair value F* = (S-D)·exp(r·T) | `indexes/cash-and-carry-arbitrage` | +| 6.3 | Dispersion trading | Long single-stock straddles, short index straddle; exploits IV correlation premium | `indexes/dispersion-trading` | +| 6.4 | Intraday ETF arbitrage | Exploit short-lived bid-ask mispricings between two ETFs on same index | `indexes/intraday-etf-arbitrage` | +| 6.5 | Index volatility targeting | Dynamically allocate w = σ*/σ to index and (1-w) to T-bills | `indexes/volatility-targeting` | + +--- + +## Volatility (Chapter 7) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 7.1 | Generalities | Historical vs. implied vol, VIX, volatility instruments (futures, ETNs, swaps) | `volatility/generalities` | +| 7.2 | VIX futures basis trading | Short VIX futures in contango, long in backwardation based on basis threshold | `volatility/vix-futures-basis-trading` | +| 7.3 | Volatility carry | Short VXX + long VXZ; harvest contango roll differential between maturities | `volatility/volatility-carry` | +| 7.4 | Volatility risk premium | Sell ATM straddles when implied > realized vol; gamma-hedged variant | `volatility/volatility-risk-premium` | +| 7.5 | Volatility skew – long risk reversal | Buy OTM call + sell OTM put; exploit put IV > call IV skew | `volatility/volatility-skew-risk-reversal` | +| 7.6 | Variance swaps | Trade realized vs. implied variance directly; no delta-hedging needed | `volatility/variance-swaps` | + +--- + +## Foreign Exchange (Chapter 8) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 8.1 | Moving averages with HP filter | HP-filter FX series, then apply MA crossover signals | `fx/moving-averages-hp-filter` | +| 8.2 | Carry trade | Buy high-rate currencies, sell low-rate currencies via forwards | `fx/carry-trade` | +| 8.3 | Dollar carry trade | Long/short all currencies vs. USD based on average forward discount | `fx/dollar-carry-trade` | +| 8.4 | Momentum & carry combo | Blend HP-MA momentum with carry using minimum-variance weights | `fx/momentum-carry-combo` | +| 8.5 | FX triangular arbitrage | Exploit circular mispricing across three currency pairs for riskless profit | `fx/triangular-arbitrage` | + +--- + +## Commodities (Chapter 9) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 9.1 | Roll yields | Long backwardated, short contangoed futures based on front/second-month ratio | `commodities/roll-yields` | +| 9.2 | Hedging pressure | Use COT positioning data to identify long/short commodity opportunities | `commodities/hedging-pressure` | +| 9.3 | Portfolio diversification | Add commodities to equity portfolio for low cross-asset correlation benefit | `commodities/portfolio-diversification` | +| 9.4 | Value | Buy commodities cheap vs. 5-year-ago spot; sell those expensive | `commodities/value` | +| 9.5 | Skewness premium | Buy low-skewness, sell high-skewness commodity futures | `commodities/skewness-premium` | +| 9.6 | Trading with pricing models | Fit stochastic term-structure model; trade rich/cheap vs. model fair value | `commodities/pricing-models` | + +--- + +## Futures (Chapter 10) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 10.1 | Hedging risk | Offset price/rate risk with futures; cross-hedging and IR hedging variants | `futures/hedging-risk` | +| 10.2 | Calendar spread | Long near-month, short deferred-month (or vice versa); bet on supply/demand | `futures/calendar-spread` | +| 10.3 | Contrarian trading | Buy recent underperforming futures, short outperforming; volume/OI filter variant | `futures/contrarian-trading` | +| 10.4 | Trend following | Weight positions by sign of recent returns scaled by historical volatility | `futures/trend-following` | + +--- + +## Structured Assets (Chapter 11) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 11.1 | CDO generalities | CDO mechanics, tranche structure, valuation, spread pricing, risky duration | `structured-assets/cdo-generalities` | +| 11.2 | Carry – equity tranche | Buy equity tranche + delta-hedge with CDS index; earn tranche/index spread diff | `structured-assets/carry-equity-tranche` | +| 11.3 | Carry – senior/mezzanine | Sell senior/mezz tranche + buy CDS index; earn index premium over tranche | `structured-assets/carry-senior-mezzanine` | +| 11.4 | Carry – tranche hedging | Buy low-quality tranche + sell high-quality tranche; earn spread differential | `structured-assets/carry-tranche-hedging` | +| 11.5 | Carry – CDS hedging | Buy low-quality tranche + hedge with single-name CDS | `structured-assets/carry-cds-hedging` | +| 11.6 | CDOs – curve trades | Long/short CDO tranches of different maturities; bet on spread curve shape | `structured-assets/cdo-curve-trades` | +| 11.7 | MBS trading | Buy MBS passthrough + hedge duration with IRS; primary exposure = prepayment risk | `structured-assets/mbs-trading` | + +--- + +## Convertibles (Chapter 12) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 12.1 | Convertible arbitrage | Buy convertible bond + short underlying stock via delta hedge ratio h = Δ·C | `convertibles/convertible-arbitrage` | +| 12.2 | Convertible OAS | Long high-OAS convertible, short low-OAS from same issuer; profit on convergence | `convertibles/convertible-oas` | + +--- + +## Tax Arbitrage (Chapter 13) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 13.1 | Municipal bond tax arbitrage | Borrow at taxable rates, invest in tax-exempt munis; capture after-tax spread | `tax-arbitrage/muni-bond-tax-arbitrage` | +| 13.2 | Cross-border tax arbitrage | Exploit dividend imputation tax credits via stock loan or deep ITM puts | `tax-arbitrage/cross-border-tax-arbitrage` | + +--- + +## Miscellaneous Assets (Chapter 14) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 14.1 | Inflation hedging – inflation swaps | Buy/sell zero-coupon or year-on-year CPI swaps to hedge or trade inflation | `miscellaneous/inflation-hedging-swaps` | +| 14.2 | TIPS-Treasury arbitrage | Short Treasury, replicate with TIPS + inflation swaps + STRIPS; lock in spread | `miscellaneous/tips-treasury-arbitrage` | +| 14.3 | Weather risk – demand hedging | Hedge weather-driven demand using CDD/HDD futures/options | `miscellaneous/weather-risk-hedging` | +| 14.4 | Energy – spark spread | Trade power plant gross margin via electricity/gas futures ratio hedge | `miscellaneous/energy-spark-spread` | + +--- + +## Distressed Assets (Chapter 15) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 15.1 | Buy and hold distressed debt | Passively hold diversified distressed debt portfolio through reorganization | `distressed-assets/buy-and-hold-distressed-debt` | +| 15.2 | Active distressed investing | Acquire control; three sub-strategies: court reorganization, debt purchase, loan-to-own | `distressed-assets/active-distressed-investing` | +| 15.3 | Distress risk puzzle | Long healthy stocks, short distressed stocks (HMD portfolio) with vol-scaling | `distressed-assets/distress-risk-puzzle` | + +--- + +## Real Estate (Chapter 16) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 16.2 | Mixed-asset diversification | Add real estate to stock/bond portfolio via MVO; low correlation benefit | `real-estate/mixed-asset-diversification` | +| 16.3 | Intra-asset diversification | Diversify within real estate: property type, economic region, and combined | `real-estate/intra-asset-diversification` | +| 16.4 | Real estate momentum | Buy high-momentum MSAs, short low-momentum MSAs via REITs/housing futures | `real-estate/momentum-regional` | +| 16.5 | Inflation hedging | Hold commercial real estate as inflation hedge (strong empirical relationship) | `real-estate/inflation-hedging` | +| 16.6 | Fix-and-flip | Buy distressed property, renovate, resell; short-term value-add strategy | `real-estate/fix-and-flip` | + +--- + +## Cash (Chapter 17) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 17.2 | Money laundering (dark side) | Three-stage illegal process; documented for AML/educational awareness only | `cash/money-laundering-dark-side` | +| 17.3 | Liquidity management | Optimize cash holdings to meet liquidity demands while minimizing drag | `cash/liquidity-management` | +| 17.4 | REPO | Borrow/lend cash at preset rate using securities as collateral | `cash/repo` | +| 17.5 | Pawnbroking | Secured short-term lending against physical collateral with right of sale | `cash/pawnbroking` | +| 17.6 | Loan sharking | Illegal high-rate uncollateralized lending; documented for educational awareness only | `cash/loan-sharking` | + +--- + +## Cryptocurrencies (Chapter 18) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 18.2 | ANN strategy | EMA/EMSD/RSI features → softmax classifier → BTC buy/sell signals | `crypto/ann-strategy` | +| 18.3 | Sentiment – naïve Bayes | Twitter keyword features → Bernoulli naïve Bayes → BTC direction forecast | `crypto/sentiment-naive-bayes` | + +--- + +## Global Macro (Chapter 19) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 19.2 | Fundamental macro momentum | Rank assets on 4 state variables (business cycle, trade, monetary, risk sentiment) | `global-macro/fundamental-macro-momentum` | +| 19.3 | Global macro inflation hedge | Commodity allocation driven by headline vs. core inflation spread | `global-macro/inflation-hedge` | +| 19.4 | Global fixed-income strategy | Rank government bonds on 9 macro/value/momentum factors; long-short | `global-macro/global-fixed-income` | +| 19.5 | Trading on economic announcements | Hold equities on FOMC/announcement days only; T-bills otherwise | `global-macro/economic-announcements` | + +--- + +## Infrastructure (Chapter 20) + +| # | Strategy | Summary | Page | +|---|---|---|---| +| 20 | Infrastructure overview | Asset class overview: transport, utilities, energy; ETFs, listed/unlisted funds, munis | `infrastructure/infrastructure-overview` | diff --git a/gateway/knowledge/trading/strategies/indexes/cash-and-carry-arbitrage.md b/gateway/knowledge/trading/strategies/indexes/cash-and-carry-arbitrage.md new file mode 100644 index 00000000..dd8d65e6 --- /dev/null +++ b/gateway/knowledge/trading/strategies/indexes/cash-and-carry-arbitrage.md @@ -0,0 +1,60 @@ +--- +description: "Cash-and-carry (index) arbitrage exploits price inefficiencies between an index spot price and its futures price, trading the basis when futures are mispriced relative to their theoretical fair value." +tags: [indexes, arbitrage, futures, basis, cash-and-carry] +--- + +# Cash-and-Carry Arbitrage + +**Section**: 6.2 | **Asset Class**: Indexes | **Type**: Arbitrage + +## Overview +Cash-and-carry arbitrage (also called "index arbitrage") exploits discrepancies between the spot value of an index and the price of index futures. Theoretically, the futures price must equal the spot price compounded at the risk-free rate minus the present value of dividends. When the actual futures price deviates from this fair value beyond transaction costs, an arbitrage trade exists. + +## Construction / Mechanics + +**Theoretical (fair) futures price**: +``` +F*(t,T) = [S(t) - D(t,T)] · exp(r(T-t)) (421) +``` + +where: +- F*(t,T): theoretical futures price with delivery T at time t +- S(t): current spot value of the index +- D(t,T): present value (as of t) of dividends paid by index constituents between t and T +- r: risk-free rate (assumed constant) + +**Basis** (normalized deviation from fair value): +``` +B(t,T) = [F(t,T) - F*(t,T)] / S(t) (422) +``` + +where F(t,T) is the actual futures price. + +**Trading rule**: +- If B(t,T) > 0 (futures rich relative to spot): **sell futures + buy cash** (index basket) +- If B(t,T) < 0 (futures cheap relative to spot): **buy futures + sell cash** (index basket) +- Only trade when |B(t,T)| exceeds pertinent transaction costs +- Close the position when the basis converges to zero (futures price converges to fair value at delivery) + +## Payoff / Return Profile +- Earns the basis B(t,T) as a riskless profit (if perfectly hedged) when the position is held to delivery. +- The basis converges to zero at expiry: futures price → spot price at delivery. +- Return per dollar of notional ≈ |B(t,T)| minus transaction costs. + +## Key Parameters / Signals +- B(t,T): the basis — primary signal; trade when |B| > transaction cost threshold +- S(t): index spot level +- D(t,T): expected dividends over the futures lifetime +- r: risk-free rate +- Transaction cost threshold: determines minimum |B| required to trade profitably + +## Variations +- **Incomplete basket**: use a subset of index constituents to reduce transaction costs; introduces tracking error. +- **ETF arbitrage**: similar logic applied to ETF mispricing (see Section 6.4). + +## Notes +- Arbitrage opportunities are short-lived and require extremely fast execution; this is a domain of high-frequency trading. +- Selling the cash index (short-selling constituent stocks) is operationally complex: hard-to-borrow stocks, short-sale restrictions, etc. +- Dollar-neutral long cash / short futures book helps manage execution but requires continuous monitoring. +- Slippage from large orders moving the market can be prohibitive. +- Incomplete baskets (omitting illiquid or low-cap stocks) reduce transaction costs but introduce residual tracking risk. diff --git a/gateway/knowledge/trading/strategies/indexes/dispersion-trading.md b/gateway/knowledge/trading/strategies/indexes/dispersion-trading.md new file mode 100644 index 00000000..35fa7f39 --- /dev/null +++ b/gateway/knowledge/trading/strategies/indexes/dispersion-trading.md @@ -0,0 +1,79 @@ +--- +description: "Dispersion trading goes long single-stock option straddles on index constituents and short the index option straddle, exploiting the empirical tendency for index implied volatility to exceed the theoretical volatility implied by constituent volatilities and correlations." +tags: [indexes, volatility, dispersion, options, straddle, correlation] +--- + +# Dispersion Trading in Equity Indexes + +**Section**: 6.3 | **Asset Class**: Indexes | **Type**: Volatility / Arbitrage + +## Overview +Dispersion trading exploits the empirical observation that the implied volatility of index options is typically higher than the theoretical index volatility implied by constituent implied volatilities and their correlations. The strategy goes long single-stock volatility (via straddles on each constituent) and short index volatility (via a short index straddle), profiting when realized correlations are lower than the correlation implied by index options pricing. + +## Construction / Mechanics + +**Theoretical index variance** from constituent volatilities and correlation matrix: +``` +σ_I² = Σ_{i,j=1}^N w_i·w_j·σ_i·σ_j·ρ_ij (423) +``` + +where: +- w_i: index weights (assumed market-cap weighted) +- σ_i: implied volatility of stock i (from single-stock options) +- ρ_ij: sample (historical) correlation matrix (ρ_ii = 1) + +Empirically, the implied index volatility ̃σ_I > σ_I, i.e., index options are priced at a premium to theoretical constituent volatility. + +**Position construction** (near-ATM straddles, ~1 month to expiry): +- For each stock i in the index: **long n_i straddles** on stock i (near-ATM) +- **Short 1 index straddle** (near-ATM, index level P_I) + +**Sizing** n_i (for market-cap-weighted index): +``` +n_i = S_i · P_I / Σ_{k=1}^N S_k·P_k (424) +``` + +where S_i is shares outstanding for stock i. With this sizing, P_I = Σ_i n_i·P_i, so the index straddle payoff matches the sum of individual straddle payoffs as closely as possible. + +All positions held until expiry (~1 month). + +## Payoff / Return Profile +- Profits when constituent volatilities are high relative to index volatility (low realized correlation). +- Loses when correlation spikes (e.g., broad market selloff where all stocks fall together), causing the index to move as much as the constituents. +- The strategy can also be viewed as short the average pairwise correlation ρ_ij. + +## Key Parameters / Signals +- ̃σ_I: implied index volatility (from index options) +- σ_I: theoretical index volatility from Eq. (423) using constituent implied vols + historical correlations +- Spread ̃σ_I - σ_I: the basis to be monetized +- Realized vs. implied correlation: the key P&L driver + +## Variations + +### 6.3.1 Dispersion Trading — Subset Portfolio +For large indexes (e.g., S&P 500), some constituent stocks may lack liquid single-stock options (typically smaller-cap stocks). These must be excluded from the bought portfolio. Additional reasons to use a subset: +- Reducing the number of single-stock positions lowers transaction costs. +- The sample correlation matrix ρ_ij is singular for typical lookback periods (e.g., 1 year of daily returns with N=500 stocks), making Eq. (423) unreliable. + +**Stabilized correlation matrix** using a statistical risk model (PCA-based): +``` +ψ_ij = ξ_i²·δ_ij + Σ_{A=1}^K λ^(A)·V_i^(A)·V_j^(A) (425) +ξ_i² = 1 - Σ_{A=1}^K λ^(A)·[V_i^(A)]² (426) +``` + +where K < r (r = rank of ρ_ij) principal components explain systematic risk; ξ_i is the idiosyncratic (specific) risk of stock i. K is chosen via eRank. + +Using ψ_ij instead of ρ_ij, the theoretical variance becomes: +``` +σ_I² = Σ_{i,j=1}^N w_i·w_j·σ_i·σ_j·ψ_ij + = Σ_i w_i²σ_i²ξ_i² + Σ_{A=1}^K λ^(A)·[Σ_i λ^(A)·V_i^(A)·w_i·σ_i]² (427) +``` + +The subset long portfolio contains only the N_* stocks with the lowest w_i²σ_i²ξ_i² values (e.g., N_* = 100 for S&P 500), which are the stocks contributing least specific risk to the index. + +## Notes +- This strategy sits at the boundary of index and volatility strategies; it can also be viewed as correlation trading. +- The strategy loses badly during market crises when correlations spike toward 1 (e.g., 2008), as the index moves almost as much as the individual stocks. +- The pairwise correlations ρ_ij are unstable out-of-sample; using a PCA-based risk model (subset variation) mitigates this. +- ATM options may not be available for all stocks; OTM options close to ATM can substitute. +- The strategy is typically implemented with options expiring in about 1 month, and all positions held to expiration. diff --git a/gateway/knowledge/trading/strategies/indexes/generalities.md b/gateway/knowledge/trading/strategies/indexes/generalities.md new file mode 100644 index 00000000..0e7c0792 --- /dev/null +++ b/gateway/knowledge/trading/strategies/indexes/generalities.md @@ -0,0 +1,35 @@ +--- +description: "Background on index investing: an index is a diversified portfolio of assets with defined weights, and investment vehicles such as futures and ETFs allow efficient, single-trade exposure to broad indexes." +tags: [indexes, background, etf, futures, index-arbitrage] +--- + +# Index Generalities + +**Section**: 6.1 | **Asset Class**: Indexes | **Type**: Background / Reference + +## Overview +An index is a diversified portfolio of assets combined according to specified weights. The underlying assets are typically stocks (e.g., DJIA, S&P 500, Russell 3000). Index weights are determined by price (DJIA) or market capitalization (S&P 500, Russell 3000). Investment vehicles such as index futures and index-based ETFs allow a trader to gain broad market exposure through a single trade. + +## Construction / Mechanics + +**Index types by weighting scheme**: +- **Price-weighted**: DJIA — each stock's weight proportional to its price; a high-priced stock has disproportionate influence. +- **Market-cap-weighted**: S&P 500, Russell 3000 — each stock's weight proportional to its market capitalization (shares × price); larger companies dominate. +- **Equal-weighted**: each constituent receives the same weight; requires frequent rebalancing. + +**Investment vehicles**: +- **Index futures**: standardized contracts to buy/sell the index at a future date; require no upfront payment of the full notional (margin only); settled in cash. +- **Index ETFs**: exchange-traded funds that hold (or replicate) the index constituents; trade intraday like stocks; e.g., SPY (S&P 500), IVV (iShares S&P 500). +- Both instruments allow leveraged or hedged exposure to the index. + +## Key Concepts +- **Spot price S(t)**: current value of the index based on constituent prices. +- **Futures price F(t,T)**: price of the futures contract with delivery at T; theoretically F*(t,T) = [S(t) - D(t,T)] · exp(r(T-t)) where D(t,T) is the present value of dividends and r is the risk-free rate. +- **Basis B(t,T)**: normalized difference between futures price and theoretical fair value; basis trading exploits deviations of B from zero. +- **Tracking error**: difference between an ETF's NAV return and the index return; minimizing tracking error is a key ETF management objective. + +## Notes +- Index futures and ETFs are highly liquid, making index strategies generally easier to implement than single-stock strategies. +- Market-cap-weighted indexes concentrate exposure in the largest stocks; this can create significant single-name risk. +- ETF arbitrage (Section 6.4) exploits intraday mispricings between different ETFs tracking the same index. +- Dispersion trading (Section 6.3) exploits the difference between index implied volatility and constituent implied volatilities. diff --git a/gateway/knowledge/trading/strategies/indexes/intraday-etf-arbitrage.md b/gateway/knowledge/trading/strategies/indexes/intraday-etf-arbitrage.md new file mode 100644 index 00000000..f4937a3e --- /dev/null +++ b/gateway/knowledge/trading/strategies/indexes/intraday-etf-arbitrage.md @@ -0,0 +1,49 @@ +--- +description: "Intraday ETF arbitrage exploits short-term mispricings between two ETFs tracking the same underlying index by buying the cheaper ETF and shorting the more expensive one when their bid-ask prices diverge beyond a threshold." +tags: [indexes, arbitrage, etf, intraday, high-frequency] +--- + +# Intraday Arbitrage Between Index ETFs + +**Section**: 6.4 | **Asset Class**: Indexes | **Type**: Arbitrage / High-Frequency + +## Overview +When two ETFs track the same underlying index, their prices should be nearly identical. Short-lived intraday mispricings arise due to order flow imbalances, liquidity differences, or market microstructure effects. The strategy exploits these mispricings by simultaneously buying the cheaper ETF and shorting the more expensive one, closing the position when prices converge. + +## Construction / Mechanics + +Let ETF1 and ETF2 track the same index. Let P_1^Bid, P_1^Ask be the bid and ask prices for ETF1, and P_2^Bid, P_2^Ask for ETF2. Let κ be a predefined price threshold (κ close to 1, e.g., κ = 1.002). + +**Trading rule**: +``` +Rule = { Buy ETF2, short ETF1 if P_1^Bid ≥ P_2^Ask × κ + { Liquidate position if P_2^Bid ≥ P_1^Ask + { Buy ETF1, short ETF2 if P_2^Bid ≥ P_1^Ask × κ + { Liquidate position if P_1^Bid ≥ P_2^Ask (428) +``` + +- **Enter**: when one ETF's bid exceeds the other's ask by at least factor κ (i.e., the spread exceeds transaction costs by a sufficient margin). +- **Exit**: when the spread collapses (the two bid-ask ranges overlap), meaning convergence has occurred. +- Orders are placed as marketable **"fill or kill"** limit orders to ensure immediate execution. + +## Payoff / Return Profile +- Earns the price differential (P_1^Bid - P_2^Ask or P_2^Bid - P_1^Ask) when the ETFs revert to parity. +- Profit per trade ≈ (P_i^Bid/P_j^Ask - 1) - transaction costs, which is small (basis points level) but high frequency. +- Cumulative return from many small, fast trades. + +## Key Parameters / Signals +- κ: minimum price threshold to trigger trade (e.g., 1.002 = 0.2% premium) +- P_i^Bid, P_i^Ask: real-time bid and ask prices for each ETF +- Entry condition: P_1^Bid ≥ P_2^Ask × κ (or vice versa) +- Exit condition: bid-ask ranges overlap (spread collapses to zero) + +## Variations +- Apply the same logic to an ETF and its underlying index futures (similar to cash-and-carry arbitrage, Section 6.2). +- Multi-ETF: trade mispricings across three or more ETFs on related (but not identical) indexes. + +## Notes +- Arbitrage opportunities are ephemeral and require a fast order execution system; slippage will eat away profits at slow execution speeds. +- "Fill or kill" limit orders are critical: partial fills create unhedged residual risk. +- The threshold κ must exceed the effective transaction cost (bid-ask spread + commissions + market impact) to ensure profitability. +- E.g., for S&P 500 ETFs: SPY (SPDR Trust) and IVV (iShares) are the main candidates. +- This strategy is firmly in the domain of high-frequency / algorithmic trading. diff --git a/gateway/knowledge/trading/strategies/indexes/volatility-targeting.md b/gateway/knowledge/trading/strategies/indexes/volatility-targeting.md new file mode 100644 index 00000000..a15ae629 --- /dev/null +++ b/gateway/knowledge/trading/strategies/indexes/volatility-targeting.md @@ -0,0 +1,58 @@ +--- +description: "Index volatility targeting maintains a constant portfolio volatility level by dynamically rebalancing between a risky index and a risk-free asset, scaling the index allocation inversely with current volatility." +tags: [indexes, volatility-targeting, risk-management, rebalancing, allocation] +--- + +# Index Volatility Targeting with Risk-Free Asset + +**Section**: 6.5 | **Asset Class**: Indexes | **Type**: Risk Management / Volatility Targeting + +## Overview +A volatility targeting strategy maintains a constant target volatility σ_* for a portfolio by periodically rebalancing between a risky asset (an index) and a riskless asset (e.g., U.S. Treasury bills). The allocation to the risky asset is scaled inversely with the current (estimated) volatility of the index, so the portfolio's realized volatility stays close to σ_*. + +## Construction / Mechanics + +**Risky asset weight** (allocation to the index): +``` +w = σ_* / σ +``` + +where: +- σ_*: target volatility (constant, set by the investor) +- σ: current estimated volatility of the index (e.g., realized or implied) + +**Risk-free asset weight**: 1 - w + +If a maximum leverage constraint L is imposed: w is capped at L. + +**Rebalancing to avoid overtrading**: instead of rebalancing on a fixed schedule (weekly, monthly), rebalance only when the allocation has drifted significantly: +``` +Rebalance only if |Δw| / w > κ +``` +where Δw is the change in w since the last rebalance and κ is a preset threshold (e.g., 5–10%). This reduces transaction costs while maintaining approximately constant volatility. + +**Net portfolio**: a fraction w in the index + a fraction (1-w) in T-bills. + +## Payoff / Return Profile +- Targets a constant realized volatility close to σ_*. +- When market volatility rises, the index allocation is reduced, limiting drawdowns. +- When market volatility is low, the index allocation increases (potentially with leverage), improving returns. +- The strategy does not make a directional bet on the market; it is a risk management overlay. + +## Key Parameters / Signals +- σ_*: volatility target (investor-specified, e.g., 10% annualized) +- σ: current volatility estimate (realized vol from recent returns, or implied vol from options) +- w = σ_*/σ: dynamic allocation weight +- κ: rebalancing threshold (avoids unnecessary turnover) +- Maximum leverage L: caps w if set + +## Variations +- Apply to other asset classes (bonds, commodities) using the same framework. +- Combine volatility targeting with a trend-following signal: only hold the index when its trend is positive, otherwise hold the risk-free asset. +- Use implied volatility (e.g., VIX) as σ for a forward-looking allocation rather than backward-looking realized vol. + +## Notes +- Volatility targeting implicitly creates momentum-like behavior: reduces risk when volatility spikes (which often accompanies market selloffs) and adds risk when volatility is low (often in trending markets). +- The strategy does not protect against sudden gap moves (e.g., flash crashes) where volatility spikes before rebalancing can occur. +- Transaction costs from rebalancing must be weighed against the volatility-stabilization benefit; the threshold κ controls this trade-off. +- The choice of σ (historical lookback window vs. implied vol) significantly affects performance and responsiveness. diff --git a/gateway/knowledge/trading/strategies/infrastructure/infrastructure-overview.md b/gateway/knowledge/trading/strategies/infrastructure/infrastructure-overview.md new file mode 100644 index 00000000..f3e0a880 --- /dev/null +++ b/gateway/knowledge/trading/strategies/infrastructure/infrastructure-overview.md @@ -0,0 +1,80 @@ +--- +description: "An overview of infrastructure as an asset class, covering direct and indirect investment vehicles, and three core strategies: portfolio diversification, inflation hedging, and stable cash flow generation from brownfield projects." +tags: [infrastructure, real-assets, inflation-hedge, diversification, long-term] +--- + +# Infrastructure — Investment Overview + +**Section**: 20 | **Asset Class**: Infrastructure | **Type**: Real assets / Long-term buy-and-hold + +## Overview + +Infrastructure investing encompasses long-term investments in essential physical assets and systems that underpin economic activity. It is a distinct asset class characterized by long-lived assets, predictable (often inflation-linked) cash flows, and low correlation with traditional financial assets. Infrastructure is inherently a long-term, buy-and-hold asset class, and the three main investment strategies are: improving risk-adjusted portfolio returns through diversification, hedging inflation, and generating stable cash flows — with brownfield projects being best suited for the latter. + +## Construction / Mechanics + +### Infrastructure Asset Categories + +Infrastructure spans a wide range of asset types: + +- **Transportation**: roads, bridges, tunnels, railways, ports, airports +- **Telecommunications**: transmission cables, satellites, towers +- **Utilities**: electricity generation, gas or electricity transmission/distribution, water supply, sewage, waste management +- **Energy**: conventional and renewable energy infrastructure (pipelines, wind farms, solar facilities) +- **Healthcare**: hospitals, clinics, senior homes +- **Education**: schools, universities, research institutes +- **Social infrastructure**: various government-mandated facilities + +### Investment Vehicles + +Investors can gain exposure to infrastructure assets through: + +1. **Private equity-type investments**: unlisted/private infrastructure funds (direct ownership stakes in infrastructure projects or companies) +2. **Listed infrastructure funds**: closed-end or open-end funds traded on exchanges +3. **Publicly traded infrastructure companies**: stocks of companies that own and operate infrastructure assets +4. **Municipal bonds**: bonds earmarked to fund infrastructure projects +5. **Tracking ETFs**: ETFs that track global infrastructure fund indexes +6. **Unlisted infrastructure funds**: provide direct economic exposure without exchange listing + +### Project Types + +- **Brownfield projects**: associated with established, existing assets in need of improvement or maintenance. More appropriate for stable cash flow generation because assets are already operational with known revenue streams. +- **Greenfield projects**: associated with assets yet to be constructed. Higher risk during construction phase; revenue streams are uncertain until operational. + +## Return Profile / Objective + +Infrastructure investments pursue three primary objectives: + +### 1. Portfolio Diversification (Risk-Adjusted Return Enhancement) +Infrastructure assets typically have low correlation with equities and bonds, providing diversification benefits. Exposure via tracking ETFs, global infrastructure funds, or unlisted funds improves the risk-adjusted return of a well-diversified portfolio. + +### 2. Inflation Hedging +Infrastructure assets, like real estate, can be inflation-hedging investments. Many infrastructure contracts include explicit inflation escalators (e.g., toll road revenues linked to CPI). The inflation-hedging properties can be heterogeneous across infrastructure sub-sectors — regulated utilities and toll roads tend to have stronger inflation linkage than, e.g., merchant power plants. Related strategy: the Global Macro Inflation Hedge (Section 19.3) uses a similar concept applied to commodities. + +### 3. Stable Cash Flow Generation +Infrastructure investments can generate predictable, stable cash flows from long-term concession agreements, regulated rate structures, or monopoly-like market positions. For this objective: +- **Brownfield projects are preferred** over greenfield because existing operational assets have known revenues, established customer bases, and lower execution risk +- **Sector diversification** across transportation, utilities, energy, and social infrastructure can smooth cash flow volatility + +## Key Parameters / Signals + +- **Asset type**: transportation vs. utilities vs. energy vs. social — affects inflation linkage, regulatory environment, and cash flow stability +- **Project stage**: brownfield (operational) vs. greenfield (development) — determines risk/return profile and suitability for cash flow strategies +- **Investment vehicle**: listed (liquid, mark-to-market) vs. unlisted (illiquid, appraisal-based) — affects portfolio construction and liquidity management +- **Regulatory framework**: regulated vs. merchant — regulated assets have more predictable revenue; merchant assets have commodity/market price exposure +- **Concession length**: duration of operating rights; longer concessions provide longer cash flow visibility +- **Inflation linkage**: explicit CPI escalators vs. implicit pass-through + +## Variations + +- **Core infrastructure**: large, stabilized brownfield assets (airports, toll roads, regulated utilities) with the most predictable cash flows and lowest risk +- **Core-plus infrastructure**: slightly higher risk, some development or operational improvement component +- **Value-add / opportunistic infrastructure**: significant operational improvements or greenfield development; higher risk/return +- **Infrastructure debt**: senior secured lending to infrastructure projects; lower return but higher in the capital structure +- **Renewable energy infrastructure**: wind, solar, storage projects; inflation-linked revenues (often via power purchase agreements) with greenfield construction risk + +## Notes + +Infrastructure as an asset class has grown substantially in institutional portfolios (pension funds, sovereign wealth funds, endowments) due to its long-duration, inflation-linked cash flow characteristics that match long-dated liabilities. The illiquidity premium in unlisted infrastructure can be significant, but requires patient capital and robust governance. Diversification across sectors mitigates the risk that any single regulatory regime or commodity market adversely impacts the portfolio. Key risks include regulatory/political risk (government changes to concession terms or rate structures), construction risk (greenfield), and interest rate risk (infrastructure assets are long-duration and sensitive to discount rate changes). + +**Source**: Kakushadze and Serur, "151 Trading Strategies" (2018), Chapter 20. diff --git a/gateway/knowledge/trading/strategies/miscellaneous/energy-spark-spread.md b/gateway/knowledge/trading/strategies/miscellaneous/energy-spark-spread.md new file mode 100644 index 00000000..c59bb4b3 --- /dev/null +++ b/gateway/knowledge/trading/strategies/miscellaneous/energy-spark-spread.md @@ -0,0 +1,61 @@ +--- +description: "Capture or hedge the gross margin of a gas-fired power plant by trading the spread between wholesale electricity prices and natural gas fuel costs, using electricity and gas futures in the ratio determined by the plant's heat rate." +tags: [miscellaneous, energy, spread-trading, hedging, commodities] +--- + +# Energy — Spark Spread + +**Section**: 14.4 | **Asset Class**: Miscellaneous (Energy Commodities) | **Type**: Spread Trading / Hedging + +## Overview +The spark spread is the difference between the wholesale price of electricity and the price of natural gas required to produce it. It measures the gross margin of a gas-fired power plant (excluding all other costs: operation, maintenance, capital, etc.). A spark spread position is built by taking a short position in electricity futures and a long position in natural gas futures, in the ratio determined by the plant's heat rate. + +## Construction / Mechanics + +**Heat rate** (fuel efficiency of the power plant): +``` +H = Q_F / Q_E (516) +``` +- `Q_F` = amount of fuel (natural gas) used, measured in MMBtu +- `Q_E` = electricity produced, measured in MWh +- `H` measured in MMBtu/MWh +- MMBtu = 1,000,000 Btu; Btu ≈ 1,055 Joules + +**Spark spread** (in $/MWh): +``` +S = P_E - H × P_F (517) +``` +- `P_E` = price of electricity ($/MWh) +- `P_F` = price of natural gas ($/MMBtu) + +**Hedge ratio** for futures contracts: +``` +h = H × F_E / F_F (518) +``` +- `F_E = 736 MWh` (standard electricity futures contract size) +- `F_F = 10,000 MMBtu` (standard natural gas futures contract size) + +Since `h` is generally not a whole number, it is approximated as the ratio `h ≈ N_F / N_E` with the lowest possible whole-number denominator `N_E`. The hedge consists of buying `N_F` gas futures contracts for every `N_E` sold electricity futures contracts. + +## Return Profile +- **Electricity producer (natural hedge)**: short electricity futures + long gas futures locks in a fixed spark spread, hedging against a compression of the gross margin +- **Speculator / spread trader**: profits if the spark spread widens (electricity prices rise relative to gas prices) on a long spread position, or if it narrows on a short spread position +- The strategy has no directional energy price exposure — only exposure to the relative price of electricity vs. natural gas + +## Key Parameters / Signals +- **Heat rate `H`**: plant-specific efficiency; lower `H` = more efficient plant = higher spark spread for the same fuel cost +- **Spark spread `S`**: core signal; compare to historical average or fair value based on plant operating costs +- **Contract sizes `F_E`, `F_F`**: determine the achievable hedge ratio granularity +- **Seasonal patterns**: electricity demand (and spark spread) exhibits strong seasonality driven by heating/cooling demand + +## Variations +- **Dark spread**: same concept for coal-fired power plants (replaces natural gas with coal prices) +- **Quark spread**: same concept for nuclear power plants +- **Clean spark spread**: adjusts for carbon emission costs (CO2 allowance prices) in addition to fuel costs + +## Notes +- The spark spread measures gross margin only; it does not account for fixed operating costs, maintenance, or capital expenditures +- Basis risk exists between the price indexes referenced in futures contracts and the actual spot prices at the delivery location +- Liquidity is concentrated in front-month contracts; longer-dated spark spread trades may have wide bid-ask spreads +- Heat rates vary with plant load and ambient temperature; a single fixed `H` is an approximation +- Regulatory risk: electricity markets are often heavily regulated; price caps and dispatch rules can affect realized spreads diff --git a/gateway/knowledge/trading/strategies/miscellaneous/inflation-hedging-swaps.md b/gateway/knowledge/trading/strategies/miscellaneous/inflation-hedging-swaps.md new file mode 100644 index 00000000..200b8a65 --- /dev/null +++ b/gateway/knowledge/trading/strategies/miscellaneous/inflation-hedging-swaps.md @@ -0,0 +1,56 @@ +--- +description: "Buy or sell inflation swaps to exchange fixed and floating (CPI-linked) cash flows, hedging against unexpected inflation or speculating on inflation relative to the breakeven rate." +tags: [miscellaneous, inflation, derivatives, swaps, fixed-income] +--- + +# Inflation Hedging — Inflation Swaps + +**Section**: 14.1 | **Asset Class**: Miscellaneous (Inflation Derivatives) | **Type**: Hedging / Macro + +## Overview +Inflation swaps allow parties to exchange a fixed rate of inflation for a floating (CPI-linked) rate, analogous to interest rate swaps. A buyer of an inflation swap is long inflation: they receive the floating CPI-linked rate and pay the fixed rate ("breakeven rate"). The buyer profits if realized inflation exceeds expected inflation (i.e., the fixed swap rate). The fixed rate is typically calculated as the spread between Treasury notes/bonds and TIPS with the same maturity. + +## Construction / Mechanics + +### Zero-Coupon Inflation Swap (ZC) +The most common type. Only one cash flow at maturity `T` (in years). Cash flows per $1 notional: + +``` +C_fixed = (1 + K)^T - 1 (500) +C_floating = I(T)/I(0) - 1 (501) +``` + +- `K` = fixed rate (the "breakeven rate") +- `I(t)` = CPI value at time `t`; `t = 0` is when the swap is entered into + +### Year-on-Year Inflation Swap (YoY) +References annual inflation rather than cumulative. Assuming annual payments (`t = 1, ..., T`): + +``` +C_fixed(t) = K (502) +C_floating(t) = I(t)/I(t-1) - 1 (503) +``` + +The buyer pays `C_fixed` and receives `C_floating` at each period. + +## Return Profile +- **Buyer (long inflation)**: profits when realized CPI exceeds the breakeven rate `K`; losses when inflation is lower than expected +- **Seller (short inflation)**: profits when realized inflation is below `K` +- Returns are driven by the difference between realized inflation and the fixed swap rate; there is no equity or credit risk in a plain vanilla inflation swap + +## Key Parameters / Signals +- **Breakeven rate** `K`: the fixed rate embedded in the swap; derived from the Treasury/TIPS spread for the same maturity +- **CPI index** `I(t)`: typically the Consumer Price Index; contract specifies which index and lag +- **Maturity** `T`: ZC swaps concentrate all cash flow at maturity; YoY swaps distribute annual payments +- **Notional**: scales all cash flows linearly + +## Variations +- **Zero-Coupon vs. Year-on-Year**: ZC is simpler with one cash flow; YoY resets annually and is less sensitive to base-period CPI distortions +- **Real rate swaps**: swap fixed real rate for floating real rate; related but distinct instrument +- **Inflation caps/floors**: options on inflation; cap protects buyer if inflation exceeds a ceiling rate + +## Notes +- Liquidity in inflation swap markets is concentrated in major currencies (USD, EUR, GBP) +- Counterparty risk: OTC instruments; cleared versions available on some CCPs +- Basis risk between the CPI index in the swap and the actual inflation exposure being hedged +- The fixed rate `K` is model-independent (observed from market), but fair value of the floating leg requires CPI forecasting diff --git a/gateway/knowledge/trading/strategies/miscellaneous/tips-treasury-arbitrage.md b/gateway/knowledge/trading/strategies/miscellaneous/tips-treasury-arbitrage.md new file mode 100644 index 00000000..46eb7aae --- /dev/null +++ b/gateway/knowledge/trading/strategies/miscellaneous/tips-treasury-arbitrage.md @@ -0,0 +1,65 @@ +--- +description: "Short an overvalued Treasury bond and offset it with a synthetic replicating portfolio of TIPS plus zero-coupon inflation swaps, capturing the empirically persistent positive cash flow at inception." +tags: [miscellaneous, arbitrage, fixed-income, TIPS, Treasuries] +--- + +# TIPS-Treasury Arbitrage + +**Section**: 14.2 | **Asset Class**: Miscellaneous (Fixed Income) | **Type**: Arbitrage + +## Overview +Based on the empirical observation that Treasury bonds are almost persistently overvalued relative to TIPS (Treasury Inflation-Protected Securities). The strategy shorts a Treasury bond and offsets the position with a synthetic portfolio that precisely replicates all Treasury bond cash flows using TIPS and zero-coupon inflation swaps. Because the synthetic portfolio costs less than the Treasury bond, the net cash flow at inception is positive, representing the arbitrage profit. + +## Construction / Mechanics +**Short leg**: Sell Treasury bond with price `P_Treasury`, fixed coupon rate `r_Treasury`, maturity `T`. + +**Synthetic replicating portfolio** (long legs): +- Buy TIPS with price `P_TIPS`, maturity `T`, fixed coupon rate `r`, and `n` coupon payments at times `t_i` (`i = 1, ..., n`, with `t_n = T`) +- Simultaneously sell `n` zero-coupon inflation swaps with maturities `t_i`, fixed rate `K`, and notionals: + ``` + N_i = r + δ_{t_i, T} per $1 of TIPS principal + ``` + where `δ_{t_i, T} = 1` if `i = n` (maturity), 0 otherwise (to match principal repayment) + +**TIPS cash flows** (per $1 notional; `I(t)` = CPI at time `t`): +``` +C_TIPS(t_i) = N_i × I(t_i)/I(0) (504) +C_swap(t_i) = N_i × [(1 + K)^t_i - I(t_i)/I(0)] (505) +C_total(t_i) = C_swap(t_i) + C_TIPS(t_i) = N_i(1 + K)^t_i (506) +``` + +The total cash flow replicates fixed coupon payments with effective coupon rates `r_eff(t_i) = r(1 + K)^t_i`. + +**STRIPS positions** to match Treasury coupons exactly (small long or short positions in zero-coupon discount bonds): +``` +S(t_i) = D(t_i) × {[r_Treasury - r_eff(t_i)] + δ_{t_i,T} × [1 - (1+K)^t_i]} (507) +``` +where `D(τ)` is the discount factor (STRIPS value) with maturity `τ`. + +**Net cash flow at inception**: +``` +C(0) = P_Treasury - P_TIPS - Σ S(t_i) (508) + i=1 +``` + +Empirically, `C(0) > 0` even after transaction costs — hence arbitrage. + +## Return Profile +The profit is locked in at trade inception as a positive `C(0)`. All subsequent cash flows net to zero by construction (the synthetic portfolio precisely replicates the Treasury). Returns are model-independent and driven purely by the persistent Treasury overvaluation relative to TIPS. + +## Key Parameters / Signals +- **`C(0)`**: the net cash flow at inception; must be positive (and cover transaction costs) for the trade to be worthwhile +- **STRIPS prices** `D(t_i)`: discount factors; observable from market +- **Fixed rate** `K` on inflation swaps: the breakeven inflation rate +- **TIPS coupon rate** `r` and Treasury coupon rate `r_Treasury`: the gap drives the size of STRIPS adjustments + +## Variations +- **Duration-neutral overlay**: combine with duration hedges to isolate the mispricing from interest rate directionality +- **Partial replication**: use a subset of STRIPS to approximately replicate, reducing transaction costs at the expense of perfect replication + +## Notes +- Transaction costs (bid-ask spreads on TIPS, inflation swaps, STRIPS) can erode `C(0)`; the trade is only viable when mispricing is large enough +- STRIPS = "Separate Trading of Registered Interest and Principal of Securities" — zero-coupon discount bonds +- The persistent Treasury overvaluation has been documented empirically but can narrow or temporarily reverse +- Short selling Treasuries requires repo market access; repo rates affect the total cost of carry +- Regulatory constraints on short positions in government securities may limit implementation diff --git a/gateway/knowledge/trading/strategies/miscellaneous/weather-risk-hedging.md b/gateway/knowledge/trading/strategies/miscellaneous/weather-risk-hedging.md new file mode 100644 index 00000000..b4e4b427 --- /dev/null +++ b/gateway/knowledge/trading/strategies/miscellaneous/weather-risk-hedging.md @@ -0,0 +1,70 @@ +--- +description: "Hedge weather-driven demand risk using weather derivatives (futures or options on temperature indices) with hedge ratios calibrated to the covariance between demand and the relevant temperature index." +tags: [miscellaneous, hedging, weather-derivatives, energy] +--- + +# Weather Risk — Demand Hedging + +**Section**: 14.3 | **Asset Class**: Miscellaneous (Weather Derivatives) | **Type**: Hedging + +## Overview +Many businesses and economic sectors are affected by weather conditions both directly (e.g., energy consumption) and indirectly. Weather risk is hedged using weather derivatives, which reference synthetic temperature indexes since no tradable weather indexes exist. The two most common indexes are based on temperature: Cooling-Degree-Days (CDD) for extreme heat and Heating-Degree-Days (HDD) for extreme cold. + +## Construction / Mechanics + +**Temperature indexes** (over a contract life of `n` days): +``` +I_CDD = Σ max(0, T_i - T_base) (509) + i=1 + +I_HDD = Σ max(0, T_base - T_i) (510) + i=1 + +T_i = (T_i^min + T_i^max) / 2 (511) +``` + +- `T_i` = average daily temperature on day `i` +- `T_i^min`, `T_i^max` = minimum and maximum temperatures on day `i` +- `T_base = 65°F` + +**Hedging demand risk for heating (HDD)**: + +Using a short futures position or a long put option: +``` +h_futures^HDD = Cov(q_w, I_HDD) / Var(I_HDD) (512) +h_put^HDD = -Cov(q_w, max(K - I_HDD, 0)) / Var(max(K - I_HDD, 0)) (513) +``` + +**Hedging demand risk for cooling (CDD)**: + +Using a long futures position or a long call option: +``` +h_futures^CDD = Cov(q_w, I_CDD) / Var(I_CDD) (514) +h_call^CDD = Cov(q_w, max(I_CDD - K, 0)) / Var(max(I_CDD - K, 0)) (515) +``` + +- `q_w` = the portion of demand affected by weather conditions (excluding other exogenous, non-weather components) +- `K` = strike price of the option +- Cov and Var are serial (co)variances + +## Return Profile +The hedge reduces weather-driven demand volatility. The futures hedge provides linear protection against temperature deviations from average; the options hedge provides asymmetric protection (puts for heating risk, calls for cooling risk). In non-extreme weather years the hedge has negative carry (cost of options, or futures mark-to-market losses when weather is mild). + +## Key Parameters / Signals +- **`q_w`**: weather-sensitive component of demand; must be isolated from non-weather demand drivers +- **Hedge ratios** `h_futures` and `h_put/h_call`: computed from historical Cov/Var of demand vs. temperature index +- **Contract life `n`**: weekly, monthly, or seasonal contracts available +- **Base temperature `T_base = 65°F`**: standard for U.S. CME weather contracts +- **Strike `K`**: for option-based hedges; determines payoff profile + +## Variations +- **Futures-only hedge**: simpler, linear; appropriate when demand has approximately linear sensitivity to temperature +- **Options hedge**: asymmetric protection; appropriate when the cost of extreme weather is highly nonlinear +- **Combination**: futures for expected temperature deviation plus options for tail risk + +## Notes +- No "tradable" weather indexes exist; all weather derivatives reference synthetic indexes based on temperature data from specified weather stations +- Basis risk between the specific weather station used in the contract and the firm's actual geographic exposure +- Liquidity is concentrated in CME weather futures for major U.S. cities; OTC markets cover more locations but with less liquidity +- Weather derivatives are used primarily by energy companies, agriculture, retail, and travel industries +- Historical Cov/Var estimates may not be stable across climate regimes; model recalibration is needed periodically diff --git a/gateway/knowledge/trading/strategies/options/bear-call-ladder.md b/gateway/knowledge/trading/strategies/options/bear-call-ladder.md new file mode 100644 index 00000000..39ec78a7 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bear-call-ladder.md @@ -0,0 +1,34 @@ +--- +description: "A bullish-adjusted strategy selling a near-ATM call at K1 and buying two higher OTM calls at K2 and K3, arising when a bear call spread is adjusted for a stock that trades higher." +tags: [options, hedging, bullish, ladder] +--- + +# Bear Call Ladder + +**Section**: 2.16 | **Asset Class**: Options | **Type**: Hedging + +## Overview +The bear call ladder is a vertical spread consisting of a short call at K1 (near ATM), a long call at K2 (OTM), and a long call at K3 (further OTM, K3 > K2 > K1). A bear call ladder typically arises when a bear call spread goes wrong (the stock trades higher), so the trader buys another OTM call at K3 to adjust the position to bullish. + +## Construction +- Sell 1 call option at strike K1 (near ATM) +- Buy 1 call option at strike K2 (OTM, K2 > K1) +- Buy 1 call option at strike K3 (further OTM, K3 > K2), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = (S_T - K3)+ + (S_T - K2)+ - (S_T - K1)+ - H + +- Lower breakeven: S*_down = K1 - H (if H < 0, net credit) +- Upper breakeven: S*_up = K3 + K2 - K1 + H +- Max profit: P_max = unlimited (above S*_up) +- Max loss: L_max = K2 - K1 + H (in zone [K1, K2]) + +## Key Conditions / Signals +- Bullish adjustment to a bear call spread that has moved against the trader +- Profits if the stock continues to rise significantly above K3 +- Low volatility near K1 environment after adjustment is undesirable + +## Notes +The bear call ladder converts a bearish income strategy into a bullish capital gain strategy. The additional long call at K3 limits the maximum loss zone and creates profit on a sharp rally. diff --git a/gateway/knowledge/trading/strategies/options/bear-call-spread.md b/gateway/knowledge/trading/strategies/options/bear-call-spread.md new file mode 100644 index 00000000..2eef1ef0 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bear-call-spread.md @@ -0,0 +1,32 @@ +--- +description: "A bearish vertical spread selling a lower-strike OTM call at K2 and buying a higher-strike OTM call at K1 for a net credit, profiting if the stock stays below K2." +tags: [options, income, bearish, vertical-spread] +--- + +# Bear Call Spread + +**Section**: 2.8 | **Asset Class**: Options | **Type**: Income + +## Overview +The bear call spread is a vertical spread consisting of a long position in an OTM call option with strike K1, and a short position in another OTM call option with a lower strike K2 (K2 < K1). This is a net credit trade. The trader's outlook is bearish. This is an income strategy. + +## Construction +- Buy 1 call option at strike K1 (higher OTM), same expiry +- Sell 1 call option at strike K2 (lower OTM, K2 < K1) + +Net credit: C = premium received for K2 call - premium paid for K1 call + +## Payoff Profile +f_T = (S_T - K1)+ - (S_T - K2)+ + C + +- Breakeven: S* = K2 + C +- Max profit: P_max = C (if S_T <= K2 at expiry; both calls expire worthless) +- Max loss: L_max = K1 - K2 - C (if S_T >= K1 at expiry) + +## Key Conditions / Signals +- Bearish to neutral outlook; expects stock to remain below K2 by expiry +- Prefer when implied volatility is elevated (larger credit received) +- Income generation with defined upside risk + +## Notes +The bear call spread is a credit spread. Maximum profit is limited to the net credit received. Maximum loss is the spread width minus the credit. The long call at K1 caps the loss relative to a naked short call. diff --git a/gateway/knowledge/trading/strategies/options/bear-put-ladder.md b/gateway/knowledge/trading/strategies/options/bear-put-ladder.md new file mode 100644 index 00000000..2682ed9c --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bear-put-ladder.md @@ -0,0 +1,34 @@ +--- +description: "A bear put spread extended by selling an additional lower OTM put at K3, financing the spread while capping downside profit and creating unlimited risk below K3." +tags: [options, income, bearish, ladder] +--- + +# Bear Put Ladder + +**Section**: 2.17 | **Asset Class**: Options | **Type**: Income + +## Overview +The bear put ladder is a vertical spread consisting of a long put at K1 (near ATM), a short put at K2 (OTM, K2 < K1), and a short put at K3 (further OTM, K3 < K2). It is a bear put spread financed by selling an additional OTM put at K3. This adjusts the outlook from bearish (bear put spread) to conservatively bearish or even non-directional with an expectation of low volatility. + +## Construction +- Buy 1 put option at strike K1 (near ATM) +- Sell 1 put option at strike K2 (OTM, K2 < K1) +- Sell 1 put option at strike K3 (further OTM, K3 < K2), same expiry + +Net debit or credit H (assuming K3 + K2 - K1 + H > max(H, 0)) + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ - (K3 - S_T)+ - H + +- Upper breakeven: S*_up = K1 - H (if H > 0) +- Lower breakeven: S*_down = K3 + K2 - K1 + H +- Max profit: P_max = K1 - K2 - H (achieved in zone [K3, K2]) +- Max loss: L_max = K3 + K2 - K1 + H (unlimited as S_T -> 0) + +## Key Conditions / Signals +- Conservatively bearish; expects stock to fall toward K2 but not collapse through K3 +- Low implied volatility environment expected after entry +- The additional short put at K3 reduces cost but creates unlimited downside risk + +## Notes +This is an income strategy in the sense that selling the K3 put finances the spread. However, unlimited loss exposure arises if the stock collapses well below K3. Risk management requires a stop-loss below K3. diff --git a/gateway/knowledge/trading/strategies/options/bear-put-spread.md b/gateway/knowledge/trading/strategies/options/bear-put-spread.md new file mode 100644 index 00000000..ec3144c4 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bear-put-spread.md @@ -0,0 +1,32 @@ +--- +description: "A bearish vertical spread buying a near-ATM put at K1 and selling a lower-strike OTM put at K2 < K1 for a net debit, profiting if the stock falls toward K2." +tags: [options, speculation, bearish, vertical-spread] +--- + +# Bear Put Spread + +**Section**: 2.9 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The bear put spread is a vertical spread consisting of a long position in a close to ATM put option with strike K1, and a short position in an OTM put option with a lower strike K2 (K2 < K1). This is a net debit trade. The trader's outlook is bearish: the strategy profits if the stock price falls. This is a capital gain strategy. + +## Construction +- Buy 1 put option at strike K1 (near ATM), paying debit D +- Sell 1 put option at strike K2 (OTM lower, K2 < K1), same expiry + +Net debit: D = premium paid for K1 put - premium received for K2 put + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ - D + +- Breakeven: S* = K1 - D +- Max profit: P_max = K1 - K2 - D (achieved when S_T <= K2) +- Max loss: L_max = D (if S_T >= K1 at expiry) + +## Key Conditions / Signals +- Moderately bearish outlook; expects stock to fall toward or below K2 by expiry +- Prefer when implied volatility is low (cheaper debit to enter) +- Lower cost and lower risk than buying a naked put; downside profit is capped at K2 + +## Notes +Both profit and loss are limited. The maximum gain equals the spread width minus the net debit. Appropriate when the trader has a bearish view but wants to reduce the premium outlay compared to a simple long put. diff --git a/gateway/knowledge/trading/strategies/options/bearish-long-seagull-spread.md b/gateway/knowledge/trading/strategies/options/bearish-long-seagull-spread.md new file mode 100644 index 00000000..0537565e --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bearish-long-seagull-spread.md @@ -0,0 +1,38 @@ +--- +description: "A bearish capital-gain strategy (short combo hedged by a long OTM call) buying an OTM put at K1, selling an ATM call at K2, and buying an OTM call at K3, ideally structured at zero cost." +tags: [options, speculation, bearish, seagull] +--- + +# Bearish Long Seagull Spread + +**Section**: 2.55 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The bearish long seagull spread is a short combo (short risk reversal) hedged against the stock price rising by buying an OTM call option. It amounts to a long position in an OTM put at K1, a short position in an ATM call at K2, and a long position in an OTM call at K3 (K1 < K2 < K3). Ideally, the trade is structured to have zero cost. The trader's outlook is bearish. This is a capital gain strategy. + +## Construction +- Buy 1 OTM put option at strike K1 (lowest) +- Sell 1 ATM call option at strike K2 (middle) +- Buy 1 OTM call option at strike K3 (highest, K3 > K2 > K1) +- All same expiry; ideally zero net premium (H = 0) + +Net debit or credit H + +## Payoff Profile +f_T = (K1 - S_T)+ - (S_T - K2)+ + (S_T - K3)+ - H + +Breakeven depends on sign of H: +- S* = K1 - H (if H > 0) +- S* = K2 - H (if H < 0) +- K1 <= S* <= K2 (if H = 0) + +- Max profit: P_max = K1 - H (if stock goes to zero; long put at full value) +- Max loss: L_max = K3 - K2 + H (if stock rises above K3; net short call capped at K3) + +## Key Conditions / Signals +- Bearish outlook; expects stock to fall below K1 +- Ideally zero-cost (H = 0): the short call premium finances the long put +- Long call at K3 caps the upside loss from the short call at K2 + +## Notes +The bearish long seagull is the mirror of the bullish short seagull spread. The long call at K3 hedges the unlimited upside risk of the short call at K2, capping maximum loss at K3 - K2 + H. The maximum profit is limited to K1 - H (stock to zero). diff --git a/gateway/knowledge/trading/strategies/options/bearish-short-seagull-spread.md b/gateway/knowledge/trading/strategies/options/bearish-short-seagull-spread.md new file mode 100644 index 00000000..78550df3 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bearish-short-seagull-spread.md @@ -0,0 +1,38 @@ +--- +description: "A bearish capital-gain strategy (bear put spread financed by a short OTM call) selling an OTM call at K3, buying an ATM put at K2, and selling an OTM put at K1, ideally structured at zero cost." +tags: [options, speculation, bearish, seagull] +--- + +# Bearish Short Seagull Spread + +**Section**: 2.56 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The bearish short seagull spread is a bear put spread financed with a sale of an OTM call option. It amounts to a short position in an OTM put at K1, a long position in an ATM put at K2, and a short position in an OTM call at K3 (K1 < K2 < K3). Ideally, the trade is structured to have zero cost. The trader's outlook is bearish. This is a capital gain strategy. + +## Construction +- Sell 1 OTM put option at strike K1 (lowest) +- Buy 1 ATM put option at strike K2 (middle) +- Sell 1 OTM call option at strike K3 (highest, K3 > K2 > K1) +- All same expiry; ideally zero net premium (H = 0) + +Net debit or credit H + +## Payoff Profile +f_T = -(K1 - S_T)+ + (K2 - S_T)+ - (S_T - K3)+ - H + +Breakeven depends on sign of H: +- S* = K2 - H (if H > 0) +- S* = K3 - H (if H < 0) +- K2 <= S* <= K3 (if H = 0) + +- Max profit: P_max = K2 - K1 - H (if S_T <= K1; bear put spread at max, put not needed) +- Max loss: L_max = unlimited (stock rises without bound above K3; short call exposed) + +## Key Conditions / Signals +- Bearish outlook; expects stock to fall below K2 toward K1 +- Ideally zero-cost (H = 0): the short call premium finances the bear put spread +- Short call at K3 creates unlimited upside risk above K3 + +## Notes +Unlike the bearish long seagull (which buys a call to cap upside), the bearish short seagull sells a call at K3 to finance the bear put spread, resulting in unlimited upside loss. The short put at K1 caps the downside profit. Requires careful stop-loss management above K3. diff --git a/gateway/knowledge/trading/strategies/options/bull-call-ladder.md b/gateway/knowledge/trading/strategies/options/bull-call-ladder.md new file mode 100644 index 00000000..4abf926d --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bull-call-ladder.md @@ -0,0 +1,34 @@ +--- +description: "A bullish vertical spread extended by selling a second OTM call at K3 > K2, financing a bull call spread while capping upside and creating unlimited risk above K3." +tags: [options, income, bullish, ladder] +--- + +# Bull Call Ladder + +**Section**: 2.14 | **Asset Class**: Options | **Type**: Income + +## Overview +The bull call ladder is a vertical spread consisting of a long call at K1 (near ATM), a short call at K2 (OTM), and a short call at K3 (further OTM, K3 > K2 > K1). It is a bull call spread financed by selling an additional OTM call at K3. This adjusts the outlook from bullish (bull call spread) to conservatively bullish or even non-directional with an expectation of low volatility. + +## Construction +- Buy 1 call option at strike K1 (near ATM) +- Sell 1 call option at strike K2 (OTM) +- Sell 1 call option at strike K3 (further OTM, K3 > K2 > K1), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = (S_T - K1)+ - (S_T - K2)+ - (S_T - K3)+ - H + +- Lower breakeven: S*_down = K1 + H (if H > 0) +- Upper breakeven: S*_up = K3 + K2 - K1 - H +- Max profit: P_max = K2 - K1 - H (achieved in zone [K2, K3]) +- Max loss: L_max = unlimited (if S_T >> K3) + +## Key Conditions / Signals +- Conservatively bullish; expects stock to rise to around K2 but not blow through K3 +- Low implied volatility environment expected after entry +- The additional short call at K3 reduces cost but creates unlimited upside risk + +## Notes +This is an income strategy in the sense that selling the K3 call finances the spread. However, unlimited loss exposure arises if the stock surges well above K3. Risk management requires a stop-loss above K3. diff --git a/gateway/knowledge/trading/strategies/options/bull-call-spread.md b/gateway/knowledge/trading/strategies/options/bull-call-spread.md new file mode 100644 index 00000000..60f98e15 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bull-call-spread.md @@ -0,0 +1,32 @@ +--- +description: "A bullish vertical spread buying a near-ATM call at K1 and selling an OTM call at K2 > K1 for a net debit, capping both profit and loss." +tags: [options, speculation, bullish, vertical-spread] +--- + +# Bull Call Spread + +**Section**: 2.6 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The bull call spread is a vertical spread consisting of a long position in a close to ATM call option with strike K1, and a short position in an OTM call option with a higher strike K2. This is a net debit trade. The trader's outlook is bullish: the strategy profits if the stock price rises. This is a capital gain strategy. + +## Construction +- Buy 1 call option at strike K1 (near ATM), paying debit D +- Sell 1 call option at strike K2 (OTM, K2 > K1), same expiry + +Net debit: D = premium paid for K1 call - premium received for K2 call + +## Payoff Profile +f_T = (S_T - K1)+ - (S_T - K2)+ - D + +- Breakeven: S* = K1 + D +- Max profit: P_max = K2 - K1 - D (achieved when S_T >= K2) +- Max loss: L_max = D (if S_T <= K1 at expiry) + +## Key Conditions / Signals +- Moderately bullish outlook; expects stock to rise toward or above K2 by expiry +- Prefer when implied volatility is low (cheaper debit to enter) +- Lower cost and lower risk than buying a naked call; upside is capped at K2 + +## Notes +Both profit and loss are limited. The maximum gain equals the spread width minus the net debit. This strategy is appropriate when the trader has a directional view but wants to reduce the premium outlay compared to a simple long call. diff --git a/gateway/knowledge/trading/strategies/options/bull-put-ladder.md b/gateway/knowledge/trading/strategies/options/bull-put-ladder.md new file mode 100644 index 00000000..5cab95a6 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bull-put-ladder.md @@ -0,0 +1,34 @@ +--- +description: "A bearish-adjusted strategy selling a near-ATM put at K1 and buying two lower OTM puts at K2 and K3, arising when a bull put spread is adjusted for a stock that trades lower." +tags: [options, hedging, bearish, ladder] +--- + +# Bull Put Ladder + +**Section**: 2.15 | **Asset Class**: Options | **Type**: Hedging + +## Overview +The bull put ladder is a vertical spread consisting of a short put at K1 (near ATM), a long put at K2 (OTM), and a long put at K3 (further OTM, K3 < K2 < K1). A bull put ladder typically arises when a bull put spread goes wrong (the stock trades lower), so the trader buys another OTM put at K3 to adjust the position to bearish. + +## Construction +- Sell 1 put option at strike K1 (near ATM) +- Buy 1 put option at strike K2 (OTM, K2 < K1) +- Buy 1 put option at strike K3 (further OTM, K3 < K2), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = (K3 - S_T)+ + (K2 - S_T)+ - (K1 - S_T)+ - H + +- Upper breakeven: S*_up = K1 + H (if H < 0, net credit) +- Lower breakeven: S*_down = K3 + K2 - K1 - H +- Max profit: P_max = K3 + K2 - K1 - H (if S_T -> 0) +- Max loss: L_max = K1 - K2 + H (in zone [K2, K1]) + +## Key Conditions / Signals +- Bearish adjustment to a bull put spread that has moved against the trader +- Profits if the stock continues to fall significantly below K3 +- Low volatility near K1 environment after adjustment is undesirable + +## Notes +The bull put ladder converts a bullish income strategy into a bearish capital gain strategy. The additional long put at K3 limits the maximum loss zone and creates profit on a sharp decline. diff --git a/gateway/knowledge/trading/strategies/options/bull-put-spread.md b/gateway/knowledge/trading/strategies/options/bull-put-spread.md new file mode 100644 index 00000000..8d31a563 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bull-put-spread.md @@ -0,0 +1,32 @@ +--- +description: "A bullish vertical spread selling a higher-strike OTM put at K2 and buying a lower-strike OTM put at K1 for a net credit, profiting if the stock stays above K2." +tags: [options, income, bullish, vertical-spread] +--- + +# Bull Put Spread + +**Section**: 2.7 | **Asset Class**: Options | **Type**: Income + +## Overview +The bull put spread is a vertical spread consisting of a long position in an OTM put option with strike K1, and a short position in another OTM put option with a higher strike K2 (K2 > K1). This is a net credit trade. The trader's outlook is bullish. This is an income strategy. + +## Construction +- Buy 1 put option at strike K1 (lower OTM), same expiry +- Sell 1 put option at strike K2 (higher OTM, K2 > K1) + +Net credit: C = premium received for K2 put - premium paid for K1 put + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ + C + +- Breakeven: S* = K2 - C +- Max profit: P_max = C (if S_T >= K2 at expiry; both puts expire worthless) +- Max loss: L_max = K2 - K1 - C (if S_T <= K1 at expiry) + +## Key Conditions / Signals +- Bullish to neutral outlook; expects stock to remain above K2 by expiry +- Prefer when implied volatility is elevated (larger credit received) +- Income generation with defined downside risk + +## Notes +The bull put spread is a credit spread. Maximum profit is limited to the net credit received. Maximum loss is the spread width minus the credit. The long put at K1 provides downside protection relative to a naked short put. diff --git a/gateway/knowledge/trading/strategies/options/bullish-long-seagull-spread.md b/gateway/knowledge/trading/strategies/options/bullish-long-seagull-spread.md new file mode 100644 index 00000000..b6bf41b6 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bullish-long-seagull-spread.md @@ -0,0 +1,38 @@ +--- +description: "A bullish capital-gain strategy (long combo hedged by a long OTM put) buying an OTM put at K1, selling an ATM put at K2, and buying an OTM call at K3, ideally structured at zero cost." +tags: [options, speculation, bullish, seagull] +--- + +# Bullish Long Seagull Spread + +**Section**: 2.57 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The bullish long seagull spread is a long combo (long risk reversal) hedged against the stock price falling by buying an OTM put option. It amounts to a long position in an OTM put at K1, a short position in an ATM put at K2, and a long position in an OTM call at K3 (K1 < K2 < K3). Ideally, the trade is structured to have zero cost. The trader's outlook is bullish. This is a capital gain strategy. + +## Construction +- Buy 1 OTM put option at strike K1 (lowest) +- Sell 1 ATM put option at strike K2 (middle) +- Buy 1 OTM call option at strike K3 (highest, K3 > K2 > K1) +- All same expiry; ideally zero net premium (H = 0) + +Net debit or credit H + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ + (S_T - K3)+ - H + +Breakeven depends on sign of H: +- S* = K3 + H (if H > 0) +- S* = K2 + H (if H < 0) +- K2 <= S* <= K3 (if H = 0) + +- Max profit: P_max = unlimited (stock rises above K3; long call gains without bound) +- Max loss: L_max = K2 - K1 + H (if stock falls below K1; bear put spread at max loss) + +## Key Conditions / Signals +- Bullish outlook; expects stock to rise above K3 +- Ideally zero-cost (H = 0): the short put premium finances the long call +- Long put at K1 caps the downside loss from the short put at K2 + +## Notes +The bullish long seagull is the mirror of the bearish short seagull spread. The long put at K1 hedges the downside risk of the short put at K2, capping maximum loss at K2 - K1 + H. The maximum profit is unlimited on the upside via the long call at K3. diff --git a/gateway/knowledge/trading/strategies/options/bullish-short-seagull-spread.md b/gateway/knowledge/trading/strategies/options/bullish-short-seagull-spread.md new file mode 100644 index 00000000..bf5a2284 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/bullish-short-seagull-spread.md @@ -0,0 +1,38 @@ +--- +description: "A bullish capital-gain strategy (bull call spread financed by a short OTM put) selling an OTM put at K1, buying an ATM call at K2, and selling an OTM call at K3, ideally structured at zero cost." +tags: [options, speculation, bullish, seagull] +--- + +# Bullish Short Seagull Spread + +**Section**: 2.54 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The bullish short seagull spread is a bull call spread financed with a sale of an OTM put option. It amounts to a short position in an OTM put at K1, a long position in an ATM call at K2, and a short position in an OTM call at K3 (K1 < K2 < K3). Ideally, the trade is structured to have zero cost. The trader's outlook is bullish. This is a capital gain strategy. + +## Construction +- Sell 1 OTM put option at strike K1 (lowest) +- Buy 1 ATM call option at strike K2 (middle) +- Sell 1 OTM call option at strike K3 (highest, K3 > K2 > K1) +- All same expiry; ideally zero net premium (H = 0) + +Net debit or credit H + +## Payoff Profile +f_T = -(K1 - S_T)+ + (S_T - K2)+ - (S_T - K3)+ - H + +Breakeven depends on sign of H: +- S* = K2 + H (if H > 0) +- S* = K1 + H (if H < 0) +- K1 <= S* <= K2 (if H = 0) + +- Max profit: P_max = K3 - K2 - H (if S_T >= K3; bull call spread at max) +- Max loss: L_max = K1 + H (if stock goes to zero; full loss on short put) + +## Key Conditions / Signals +- Bullish outlook; expects stock to rise above K2 toward K3 +- Ideally zero-cost (H = 0): the short put premium finances the bull call spread +- Short put at K1 creates downside exposure below K1 + +## Notes +The seagull spread's name comes from its payoff diagram shape. The upside is capped at K3 - K2 - H. The short put at K1 adds risk if the stock falls sharply, but at zero cost it provides a funded bullish position. Unlike the long combo, there is a defined maximum profit. diff --git a/gateway/knowledge/trading/strategies/options/calendar-call-spread.md b/gateway/knowledge/trading/strategies/options/calendar-call-spread.md new file mode 100644 index 00000000..84a89324 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/calendar-call-spread.md @@ -0,0 +1,33 @@ +--- +description: "A horizontal spread buying a longer-dated ATM call at TTM T' and selling a shorter-dated ATM call at the same strike K with TTM T < T', profiting from time decay when stock stays near K." +tags: [options, income, neutral, calendar-spread] +--- + +# Calendar Call Spread + +**Section**: 2.18 | **Asset Class**: Options | **Type**: Income + +## Overview +The calendar call spread (horizontal spread) consists of a long position in a near-ATM call option with TTM T' and a short position in a call option with the same strike K but shorter TTM T < T'. This is a net debit trade. The trader's outlook is neutral to bullish. The best case at expiration of the short call (t = T) is if the stock price is right at the strike (S_T = K), maximizing the remaining value V of the long call. + +## Construction +- Buy 1 call option at strike K, TTM T' (longer expiry) +- Sell 1 call option at strike K, TTM T < T' (shorter expiry), same strike + +Net debit: D + +## Payoff Profile +At t = T (expiry of short call), let V = value of the long call (expiring at T') assuming S_T = K: + +- P_max = V - D (if S_T = K at short expiry) +- L_max = D (net debit paid) + +If S_stop-loss <= S_T <= K, the trader can roll by writing another call with strike K and TTM T1 < T'. + +## Key Conditions / Signals +- Neutral to mildly bullish; expects stock to remain near K through T +- Low volatility environment after entry is ideal (long vega on net position) +- Best suited for income generation by repeatedly selling shorter-dated calls against the long call + +## Notes +This strategy resembles the covered call strategy in structure. While maintaining the long call, the trader can generate income by periodically selling call options with shorter maturities. The stop-loss price S_stop-loss defines the level below which the entire position is unwound. diff --git a/gateway/knowledge/trading/strategies/options/calendar-put-spread.md b/gateway/knowledge/trading/strategies/options/calendar-put-spread.md new file mode 100644 index 00000000..b009d7af --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/calendar-put-spread.md @@ -0,0 +1,33 @@ +--- +description: "A horizontal spread buying a longer-dated ATM put at TTM T' and selling a shorter-dated ATM put at the same strike K with TTM T < T', profiting from time decay when stock stays near K." +tags: [options, income, neutral, calendar-spread] +--- + +# Calendar Put Spread + +**Section**: 2.19 | **Asset Class**: Options | **Type**: Income + +## Overview +The calendar put spread (horizontal spread) consists of a long position in a near-ATM put option with TTM T' and a short position in a put option with the same strike K but shorter TTM T < T'. This is a net debit trade. The trader's outlook is neutral to bearish. The best case at expiration of the short put (t = T) is if the stock price is right at the strike (S_T = K), maximizing the remaining value V of the long put. + +## Construction +- Buy 1 put option at strike K, TTM T' (longer expiry) +- Sell 1 put option at strike K, TTM T < T' (shorter expiry), same strike + +Net debit: D + +## Payoff Profile +At t = T (expiry of short put), let V = value of the long put (expiring at T') assuming S_T = K: + +- P_max = V - D (if S_T = K at short expiry) +- L_max = D (net debit paid) + +If K <= S_T <= S_stop-loss, the trader can roll by writing another put with strike K and TTM T1 < T'. + +## Key Conditions / Signals +- Neutral to mildly bearish; expects stock to remain near K through T +- Low volatility environment after entry is ideal +- Best suited for income generation by repeatedly selling shorter-dated puts against the long put + +## Notes +This strategy resembles the covered put strategy in structure. While maintaining the long put, the trader can generate income by periodically selling put options with shorter maturities. The stop-loss price S_stop-loss defines the level above which the entire position is unwound. diff --git a/gateway/knowledge/trading/strategies/options/call-ratio-backspread.md b/gateway/knowledge/trading/strategies/options/call-ratio-backspread.md new file mode 100644 index 00000000..f16251bc --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/call-ratio-backspread.md @@ -0,0 +1,33 @@ +--- +description: "A strongly bullish volatility strategy selling fewer near-ATM calls at K1 and buying more OTM calls at K2, with unlimited profit on a strong rally and limited loss in between." +tags: [options, volatility, bullish, backspread] +--- + +# Call Ratio Backspread + +**Section**: 2.36 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The call ratio backspread consists of a short position in N_S close to ATM call options with strike K1, and a long position in N_L OTM call options with strike K2 (K2 > K1), where N_L > N_S. Typically N_L = 2, N_S = 1 or N_L = 3, N_S = 2. The trader's outlook is strongly bullish. This is a capital gain strategy. + +## Construction +- Sell N_S call options at strike K1 (near ATM) +- Buy N_L call options at strike K2 (OTM, K2 > K1, N_L > N_S), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = N_L × (S_T - K2)+ - N_S × (S_T - K1)+ - H + +- Lower breakeven (if H < 0, net credit): S*_down = K1 - H/N_S +- Upper breakeven: S*_up = (N_L × K2 - N_S × K1 + H) / (N_L - N_S) +- Max profit: P_max = unlimited (above the upper breakeven) +- Max loss: L_max = N_S × (K2 - K1) + H (in the zone near K2 where long calls are OTM but short calls are ITM) + +## Key Conditions / Signals +- Strongly bullish; expects a significant rally above K2 +- Ideally entered as a credit (H < 0) so that profit is also made if stock stays below K1 +- Loss zone is bounded between the two breakevens + +## Notes +The difference between call ratio backspread and ratio call spread: here N_L > N_S (more longs than shorts). The maximum loss occurs near K2 at expiry. If H < 0, the position profits if the stock stays well below K1 or surges well above the upper breakeven. diff --git a/gateway/knowledge/trading/strategies/options/collar.md b/gateway/knowledge/trading/strategies/options/collar.md new file mode 100644 index 00000000..1188c3f8 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/collar.md @@ -0,0 +1,33 @@ +--- +description: "A hedging strategy (fence) buying stock, buying an OTM put at K1, and selling an OTM call at K2 > K1, capping both upside and downside within a defined range." +tags: [options, hedging, bullish, collar] +--- + +# Collar + +**Section**: 2.53 | **Asset Class**: Options | **Type**: Hedging + +## Overview +The collar (a.k.a. "fence") is a covered call augmented by a long put option as insurance against the stock price falling. It amounts to buying stock, buying an OTM put at K1, and selling an OTM call at K2 (K2 > K1). The trader's outlook is moderately bullish. This is a capital gain strategy. Note: a short collar is a covered put augmented by a long call option. + +## Construction +- Buy 1 share of stock at S0 +- Buy 1 OTM put option at strike K1 (K1 < S0), paying put premium +- Sell 1 OTM call option at strike K2 (K2 > S0 > K1), receiving call premium + +Net debit or credit H (= D if net debit, = -C if net credit) + +## Payoff Profile +f_T = S_T - S0 + (K1 - S_T)+ - (S_T - K2)+ - H + +- Breakeven: S* = S0 + H +- Max profit: P_max = K2 - S0 - H (if S_T >= K2; upside capped by short call) +- Max loss: L_max = S0 - K1 + H (if S_T <= K1; downside protected by long put) + +## Key Conditions / Signals +- Moderately bullish; willing to cap upside in exchange for downside protection +- Ideal when trader has existing long stock position and wants to protect gains +- Often structured as zero-cost (H = 0) by choosing K1 and K2 such that premiums offset + +## Notes +The collar sacrifices unlimited upside potential (capped at K2) in exchange for limiting downside loss (floored at K1). It is one of the most common hedging strategies for long equity holders. A zero-cost collar is popular for protecting unrealized gains. diff --git a/gateway/knowledge/trading/strategies/options/covered-call.md b/gateway/knowledge/trading/strategies/options/covered-call.md new file mode 100644 index 00000000..4fc06e3d --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/covered-call.md @@ -0,0 +1,32 @@ +--- +description: "A buy-write strategy combining long stock with a short call at strike K, generating income by capping upside in exchange for premium collected." +tags: [options, income, covered, bullish] +--- + +# Covered Call + +**Section**: 2.2 | **Asset Class**: Options | **Type**: Income + +## Overview +The covered call (a.k.a. "buy-write") strategy amounts to buying stock and writing a call option with strike K against the long stock position. The trader's outlook is neutral to bullish. It has the same payoff as writing a naked put and allows the trader to generate income by periodically selling OTM call options while maintaining the long stock position. + +## Construction +- Buy 1 share of stock at price S0 +- Sell 1 call option at strike K, receiving net credit C + +Net position: long stock + short call + +## Payoff Profile +f_T = S_T - S_0 - (S_T - K)+ + C = K - S_0 - (K - S_T)+ + C + +- Breakeven: S* = S0 - C +- Max profit: P_max = K - S0 + C (achieved when S_T >= K) +- Max loss: L_max = S0 - C (if stock goes to zero) + +## Key Conditions / Signals +- Neutral to mildly bullish outlook on the underlying +- Elevated implied volatility makes collected premium more attractive +- Suitable for income generation when the trader is comfortable capping upside at K + +## Notes +The covered call strategy is equivalent to writing a put option (short/naked put) in terms of payoff. Upside is capped at K; downside risk is the full cost of the stock minus premium received. diff --git a/gateway/knowledge/trading/strategies/options/covered-put.md b/gateway/knowledge/trading/strategies/options/covered-put.md new file mode 100644 index 00000000..1c718c8f --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/covered-put.md @@ -0,0 +1,32 @@ +--- +description: "A sell-write strategy combining short stock with a short put at strike K, generating income while maintaining a neutral-to-bearish position." +tags: [options, income, covered, bearish] +--- + +# Covered Put + +**Section**: 2.3 | **Asset Class**: Options | **Type**: Income + +## Overview +The covered put (a.k.a. "sell-write") strategy amounts to shorting stock and writing a put option with strike K against the short stock position. The trader's outlook is neutral to bearish. It has the same payoff as writing a naked call and allows the trader to generate income by periodically selling OTM put options while maintaining the short stock position. + +## Construction +- Short 1 share of stock at price S0 +- Sell 1 put option at strike K, receiving net credit C + +Net position: short stock + short put + +## Payoff Profile +f_T = S0 - S_T - (K - S_T)+ + C = S0 - K - (S_T - K)+ + C + +- Breakeven: S* = S0 + C +- Max profit: P_max = S0 - K + C (achieved when S_T <= K) +- Max loss: L_max = unlimited (stock can rise without bound) + +## Key Conditions / Signals +- Neutral to mildly bearish outlook on the underlying +- Elevated implied volatility makes collected premium more attractive +- Suitable for income generation when the trader is comfortable with unlimited upside risk + +## Notes +The covered put strategy is symmetrical to the covered call strategy. The short stock position carries unlimited loss potential if the stock rises; the collected put premium provides only limited cushion. diff --git a/gateway/knowledge/trading/strategies/options/covered-short-straddle.md b/gateway/knowledge/trading/strategies/options/covered-short-straddle.md new file mode 100644 index 00000000..414b0d76 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/covered-short-straddle.md @@ -0,0 +1,33 @@ +--- +description: "A bullish income strategy augmenting a covered call by also writing an ATM put at the same strike K, increasing income at the cost of additional downside exposure." +tags: [options, income, bullish, covered, straddle] +--- + +# Covered Short Straddle + +**Section**: 2.32 | **Asset Class**: Options | **Type**: Income + +## Overview +The covered short straddle amounts to augmenting a covered call by writing a put option with the same strike K and TTM as the sold call option, thereby increasing the income. The trader's outlook is bullish. This is a combination of: long stock + short call at K + short put at K. + +## Construction +- Buy 1 share of stock at S0 +- Sell 1 call option at strike K, receiving credit +- Sell 1 put option at strike K (same strike and expiry), receiving additional credit + +Net credit: C (total premium from both short options) + +## Payoff Profile +f_T = S_T - S0 - (S_T - K)+ - (K - S_T)+ + C + +- Breakeven: S* = (1/2)(S0 + K - C) +- Max profit: P_max = K - S0 + C (if S_T = K at expiry) +- Max loss: L_max = S0 + K - C (if stock goes to zero; put assignment + stock loss) + +## Key Conditions / Signals +- Bullish to neutral; expects stock to remain near or above K +- High implied volatility; writing both options collects more premium +- The additional short put increases income but also increases downside risk significantly + +## Notes +The downside risk is substantially higher than a plain covered call because the short put adds to the loss if the stock falls below K. The maximum loss occurs if the stock goes to zero (stock loss + put assignment at K). diff --git a/gateway/knowledge/trading/strategies/options/covered-short-strangle.md b/gateway/knowledge/trading/strategies/options/covered-short-strangle.md new file mode 100644 index 00000000..62e9ecef --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/covered-short-strangle.md @@ -0,0 +1,32 @@ +--- +description: "A bullish income strategy augmenting a covered call (short call at K) by also writing an OTM put at strike K' < K, increasing income with a wider profit zone than a covered short straddle." +tags: [options, income, bullish, covered, strangle] +--- + +# Covered Short Strangle + +**Section**: 2.33 | **Asset Class**: Options | **Type**: Income + +## Overview +The covered short strangle amounts to augmenting a covered call by writing an OTM put option with strike K' (K' < K) and the same TTM as the sold call option (whose strike is K), thereby increasing the income. The trader's outlook is bullish. + +## Construction +- Buy 1 share of stock at S0 +- Sell 1 call option at strike K +- Sell 1 OTM put option at strike K' (K' < K, same expiry) + +Net credit: C (total premium from both short options) + +## Payoff Profile +f_T = S_T - S0 - (S_T - K)+ - (K' - S_T)+ + C + +- Max profit: P_max = K - S0 + C (if S_T >= K at expiry; call in money, put expires worthless) +- Max loss: L_max = S0 + K' - C (if stock goes to zero; put assigned at K', full stock loss) + +## Key Conditions / Signals +- Bullish to neutral; expects stock to remain above K' and ideally above K +- Lower downside risk than covered short straddle (OTM put vs. ATM put) +- The OTM put provides a wider profit zone on the downside at the cost of lower premium collected + +## Notes +The short OTM put at K' creates downside risk below K', but less immediate than in the covered short straddle (where the put is ATM). The maximum loss is reduced compared to the covered short straddle because K' < K. diff --git a/gateway/knowledge/trading/strategies/options/diagonal-call-spread.md b/gateway/knowledge/trading/strategies/options/diagonal-call-spread.md new file mode 100644 index 00000000..6b03b4fb --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/diagonal-call-spread.md @@ -0,0 +1,33 @@ +--- +description: "A diagonal spread buying a deep ITM call at K1 with TTM T' and selling an OTM call at K2 with shorter TTM T < T', combining directional and time decay benefits." +tags: [options, income, bullish, diagonal-spread] +--- + +# Diagonal Call Spread + +**Section**: 2.20 | **Asset Class**: Options | **Type**: Income + +## Overview +The diagonal call spread consists of a long position in a deep ITM call option with strike K1 and TTM T', and a short position in an OTM call option with strike K2 and shorter TTM T < T' (K2 > K1). This is a net debit trade. The trader's outlook is bullish. At t = T let V be the value of the long call (expiring at T') assuming S_T = K2. + +## Construction +- Buy 1 deep ITM call option at strike K1, TTM T' (longer expiry) +- Sell 1 OTM call option at strike K2, TTM T < T' (shorter expiry, K2 > K1) + +Net debit: D + +## Payoff Profile +At t = T (expiry of short call), let V = value of the long call (expiring at T') assuming S_T = K2: + +- P_max = V - D (if S_T = K2 at short expiry) +- L_max = D (net debit paid) + +If S_stop-loss <= S_T <= K2, the trader can write another OTM call with TTM T1 < T'. + +## Key Conditions / Signals +- Bullish outlook; expects stock to rise toward K2 by the short expiry +- Low volatility environment after entry is ideal for maximizing time decay income +- The deep ITM long call more closely mimics the underlying stock than an ATM call + +## Notes +Similar to the calendar call spread but the deep ITM long call (unlike the close to ATM call in the calendar spread) more closely mimics the underlying stock, providing better protection against a sharp rise in the stock price. The trader can generate income by periodically selling OTM call options with shorter maturities. diff --git a/gateway/knowledge/trading/strategies/options/diagonal-put-spread.md b/gateway/knowledge/trading/strategies/options/diagonal-put-spread.md new file mode 100644 index 00000000..93c7428b --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/diagonal-put-spread.md @@ -0,0 +1,33 @@ +--- +description: "A diagonal spread buying a deep ITM put at K1 with TTM T' and selling an OTM put at K2 with shorter TTM T < T', combining directional and time decay benefits." +tags: [options, income, bearish, diagonal-spread] +--- + +# Diagonal Put Spread + +**Section**: 2.21 | **Asset Class**: Options | **Type**: Income + +## Overview +The diagonal put spread consists of a long position in a deep ITM put option with strike K1 and TTM T', and a short position in an OTM put option with strike K2 and shorter TTM T < T' (K2 < K1). This is a net debit trade. The trader's outlook is bearish. At t = T let V be the value of the long put (expiring at T') assuming S_T = K2. + +## Construction +- Buy 1 deep ITM put option at strike K1, TTM T' (longer expiry) +- Sell 1 OTM put option at strike K2, TTM T < T' (shorter expiry, K2 < K1) + +Net debit: D + +## Payoff Profile +At t = T (expiry of short put), let V = value of the long put (expiring at T') assuming S_T = K2: + +- P_max = V - D (if S_T = K2 at short expiry) +- L_max = D (net debit paid) + +If K2 <= S_T <= S_stop-loss, the trader can write another OTM put with TTM T1 < T'. + +## Key Conditions / Signals +- Bearish outlook; expects stock to fall toward K2 by the short expiry +- Low volatility environment after entry is ideal for maximizing time decay income +- The deep ITM long put more closely mimics the underlying short stock than an ATM put + +## Notes +Similar to the calendar put spread but the deep ITM long put (unlike the close to ATM put in the calendar spread) more closely mimics the underlying stock, providing better protection against a sharp drop in the stock price. The trader can generate income by periodically selling OTM put options with shorter maturities. diff --git a/gateway/knowledge/trading/strategies/options/long-box.md b/gateway/knowledge/trading/strategies/options/long-box.md new file mode 100644 index 00000000..15967026 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-box.md @@ -0,0 +1,34 @@ +--- +description: "An arbitrage/volatility strategy combining a long synthetic forward and a short synthetic forward (or bull call spread and bear put spread) at two strikes, locking in a fixed payoff of K1 - K2." +tags: [options, arbitrage, neutral, box] +--- + +# Long Box + +**Section**: 2.52 | **Asset Class**: Options | **Type**: Arbitrage + +## Overview +The long box strategy can be viewed as a combination of a long synthetic forward and a short synthetic forward, or as a combination of a bull call spread and a bear put spread. It consists of: a long ITM put at K1, a short OTM put at K2 (lower), a long ITM call at K2, and a short OTM call at K1. The trader's outlook is neutral. This is a capital gain strategy. We assume K1 >= K2 + D. + +## Construction +- Buy 1 ITM put option at strike K1 (higher) +- Sell 1 OTM put option at strike K2 (lower, K2 < K1) +- Buy 1 ITM call option at strike K2 (same as short put strike) +- Sell 1 OTM call option at strike K1 (same as long put strike) +- All same expiry + +Net debit: D (assumed K1 >= K2 + D) + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ + (S_T - K2)+ - (S_T - K1)+ - D + = K1 - K2 - D (constant, regardless of S_T) + +- P_max = (K1 - K2) - D (fixed payoff at all stock prices) + +## Key Conditions / Signals +- Used primarily as an arbitrage strategy when the market price of the box (D) is less than the theoretical value (K1 - K2) +- Also used as a tax strategy in some jurisdictions (see footnote 31 in the source) +- No directional risk: the payoff is fixed regardless of stock price at expiry + +## Notes +The long box has a deterministic payoff of K1 - K2 - D at expiry. If D < K1 - K2 (mispricing), this is a risk-free profit. In practice, transaction costs and bid-ask spreads must be considered. Can also be used as a synthetic loan. diff --git a/gateway/knowledge/trading/strategies/options/long-call-butterfly.md b/gateway/knowledge/trading/strategies/options/long-call-butterfly.md new file mode 100644 index 00000000..899d3cb5 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-call-butterfly.md @@ -0,0 +1,46 @@ +--- +description: "A neutral low-cost debit strategy buying an OTM call at K1, selling two ATM calls at K2, and buying an ITM call at K3 with equidistant strikes, profiting if stock stays near K2." +tags: [options, income, neutral, butterfly] +--- + +# Long Call Butterfly + +**Section**: 2.40 | **Asset Class**: Options | **Type**: Income + +## Overview +The long call butterfly is a sideways strategy consisting of a long OTM call at K1, a short position in two ATM calls at K2, and a long ITM call at K3. The strikes are equidistant: K2 - K3 = K1 - K2 = kappa. This is a relatively low cost net debit trade. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Buy 1 call option at strike K1 (OTM, upper wing) +- Sell 2 call options at strike K2 (ATM, body) +- Buy 1 call option at strike K3 (ITM, lower wing, K3 < K2 < K1) +- All same expiry; K2 - K3 = K1 - K2 = kappa (equidistant) + +Net debit: D + +## Payoff Profile +f_T = (S_T - K1)+ + (S_T - K3)+ - 2 × (S_T - K2)+ - D + +- Lower breakeven: S*_down = K3 + D +- Upper breakeven: S*_up = K1 - D +- Max profit: P_max = kappa - D (achieved at S_T = K2) +- Max loss: L_max = D (if S_T <= K3 or S_T >= K1) + +## Key Conditions / Signals +- Neutral; expects stock to pin near K2 at expiry +- Low implied volatility after entry reduces theta bleed on short options +- Low cost structure makes it an efficient way to bet on stability + +## Variations + +### 2.40.1 Modified Call Butterfly +A variation where the strikes are no longer equidistant; instead K1 - K2 < K2 - K3. This results in a sideways strategy with a bullish bias. We have: + +f_T = (S_T - K1)+ + (S_T - K3)+ - 2 × (S_T - K2)+ - D + +- Breakeven: S* = K3 + D (single breakeven on the lower side) +- Max profit: P_max = K2 - K3 - D (at S_T = K2) +- Max loss: L_max = D + +## Notes +The equidistant butterfly has two breakevens symmetric around K2. The maximum profit is the wing width kappa minus the debit. Low-cost entry makes the risk/reward ratio attractive for neutral views. diff --git a/gateway/knowledge/trading/strategies/options/long-call-condor.md b/gateway/knowledge/trading/strategies/options/long-call-condor.md new file mode 100644 index 00000000..24c74605 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-call-condor.md @@ -0,0 +1,36 @@ +--- +description: "A neutral low-cost debit strategy using four calls with equidistant strikes K1 < K2 < K3 < K4, profiting if the stock stays between K2 and K3 at expiry." +tags: [options, income, neutral, condor] +--- + +# Long Call Condor + +**Section**: 2.46 | **Asset Class**: Options | **Type**: Income + +## Overview +The long call condor is a sideways strategy consisting of a long ITM call at K1, a short ITM call at K2 (higher), a short OTM call at K3, and a long OTM call at K4 (higher). All strikes are equidistant: K4 - K3 = K3 - K2 = K2 - K1 = kappa. This is a relatively low cost net debit trade. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Buy 1 call option at strike K1 (ITM, lowest) +- Sell 1 call option at strike K2 (ITM, K2 > K1) +- Sell 1 call option at strike K3 (OTM, K3 > K2) +- Buy 1 call option at strike K4 (OTM, highest, K4 > K3) +- All same expiry; K2 - K1 = K3 - K2 = K4 - K3 = kappa (equidistant) + +Net debit: D + +## Payoff Profile +f_T = (S_T - K1)+ - (S_T - K2)+ - (S_T - K3)+ + (S_T - K4)+ - D + +- Upper breakeven: S*_up = K4 - D +- Lower breakeven: S*_down = K1 + D +- Max profit: P_max = kappa - D (if K2 <= S_T <= K3 at expiry) +- Max loss: L_max = D (if S_T <= K1 or S_T >= K4) + +## Key Conditions / Signals +- Neutral; expects stock to remain in the middle zone [K2, K3] at expiry +- Low implied volatility after entry; wider profit zone than a butterfly +- Low cost entry makes it efficient for betting on a range-bound stock + +## Notes +The condor is a wider version of the butterfly: it has a flat profit plateau between K2 and K3 instead of a single peak. The tradeoff is that the maximum profit (kappa - D) is the same as the butterfly but requires K2 != K3 (four distinct strikes). diff --git a/gateway/knowledge/trading/strategies/options/long-call-synthetic-straddle.md b/gateway/knowledge/trading/strategies/options/long-call-synthetic-straddle.md new file mode 100644 index 00000000..a99ed371 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-call-synthetic-straddle.md @@ -0,0 +1,34 @@ +--- +description: "A volatility strategy shorting stock and buying two ATM calls at strike K, replicating a long straddle by replacing the long put with a synthetic put." +tags: [options, volatility, neutral, synthetic, straddle] +--- + +# Long Call Synthetic Straddle + +**Section**: 2.28 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The long call synthetic straddle (the same as a long straddle with the put replaced by a synthetic put) amounts to shorting stock and buying two ATM (or nearest ITM) call options with strike K. The trader's outlook is neutral. This is a capital gain strategy. We assume S0 >= K and D > S0 - K. + +## Construction +- Short 1 share of stock at S0 +- Buy 2 ATM call options at strike K, same expiry + +Net debit: D (assumed D > S0 - K) + +## Payoff Profile +f_T = S0 - S_T + 2 × (S_T - K)+ - D + +- Upper breakeven: S*_up = 2K - S0 + D +- Lower breakeven: S*_down = S0 - D +- Max profit: P_max = unlimited (large move in either direction) +- Max loss: L_max = D - (S0 - K) (at S_T = K; intrinsic offset reduces loss) + +## Key Conditions / Signals +- Neutral view; expects a large move in either direction +- S0 >= K (stock at or above the call strike) +- D > S0 - K prevents arbitrage +- Useful when puts are expensive relative to calls (use calls to synthesize the straddle) + +## Notes +The short stock position combined with two long calls replicates a straddle by put-call parity. The maximum loss is reduced by the amount S0 - K (intrinsic value of the synthetic put component). diff --git a/gateway/knowledge/trading/strategies/options/long-combo.md b/gateway/knowledge/trading/strategies/options/long-combo.md new file mode 100644 index 00000000..fbf54a6d --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-combo.md @@ -0,0 +1,36 @@ +--- +description: "A bullish capital-gain strategy (long risk reversal) buying an OTM call at K1 and selling an OTM put at K2 < K1, profiting from a strong upward move." +tags: [options, speculation, bullish, risk-reversal] +--- + +# Long Combo + +**Section**: 2.12 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The long combo (a.k.a. "long risk reversal") amounts to buying an OTM call option with strike K1 and selling an OTM put option with strike K2, where K1 > K2. The trader's outlook is bullish. This is a capital gain strategy. + +## Construction +- Buy 1 OTM call option at strike K1 +- Sell 1 OTM put option at strike K2 (K2 < K1), same expiry + +Net debit or credit H (H = D if net debit, H = -C if net credit; K1 > K2) + +## Payoff Profile +f_T = (S_T - K1)+ - (K2 - S_T)+ - H + +Breakeven depends on sign of H: +- S* = K1 + H (if H > 0, net debit) +- S* = K2 + H (if H < 0, net credit) +- K2 <= S* <= K1 (if H = 0, zero-cost) + +- Max profit: P_max = unlimited +- Max loss: L_max = K2 + H + +## Key Conditions / Signals +- Strongly bullish outlook +- Traders often structure as zero-cost (H = 0) by selecting K1 and K2 such that premiums offset +- Profits from a large upward move; loses if stock falls below K2 + +## Notes +Unlike the long synthetic forward (where K1 = K2 = S0), the long combo uses out-of-the-money strikes on both legs, creating a gap zone [K2, K1] where the payoff is flat (equal to -H). Downside is limited to K2 + H if S_T goes to zero. diff --git a/gateway/knowledge/trading/strategies/options/long-guts.md b/gateway/knowledge/trading/strategies/options/long-guts.md new file mode 100644 index 00000000..89ee1a1f --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-guts.md @@ -0,0 +1,33 @@ +--- +description: "A volatility strategy buying an ITM call at K1 and an ITM put at K2 > K1, profiting from a large move in either direction at higher cost than a straddle." +tags: [options, volatility, neutral, guts] +--- + +# Long Guts + +**Section**: 2.24 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The long guts is a volatility strategy consisting of a long position in an ITM call option with strike K1 and a long position in an ITM put option with strike K2 (K2 > K1). This is a net debit trade. Because both options are ITM, this strategy is more costly to establish than a long straddle position. The trader's outlook is neutral. This is a capital gain strategy. We assume D > K2 - K1. + +## Construction +- Buy 1 ITM call option at strike K1 +- Buy 1 ITM put option at strike K2 (K2 > K1), same expiry + +Net debit: D (assumed D > K2 - K1) + +## Payoff Profile +f_T = (S_T - K1)+ + (K2 - S_T)+ - D + +- Upper breakeven: S*_up = K1 + D +- Lower breakeven: S*_down = K2 - D +- Max profit: P_max = unlimited (stock can move far in either direction) +- Max loss: L_max = D - (K2 - K1) (if K1 <= S_T <= K2; intrinsic value offsets some debit) + +## Key Conditions / Signals +- Neutral directional view; expects a very large move but uncertain of direction +- More expensive than a straddle but the ITM options provide intrinsic value floor +- Max loss is reduced by the intrinsic spread K2 - K1 relative to the full debit + +## Notes +The assumption D > K2 - K1 prevents risk-free arbitrage. The intrinsic value of the ITM options (K2 - K1) offsets part of the debit, making the maximum loss smaller than for a straddle with the same debit D. Both options have positive delta at entry. diff --git a/gateway/knowledge/trading/strategies/options/long-iron-butterfly.md b/gateway/knowledge/trading/strategies/options/long-iron-butterfly.md new file mode 100644 index 00000000..a800ee48 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-iron-butterfly.md @@ -0,0 +1,36 @@ +--- +description: "A neutral income strategy combining a bull put spread and a bear call spread around a central ATM strike K2, collecting net credit when stock stays near K2." +tags: [options, income, neutral, butterfly, iron] +--- + +# Long Iron Butterfly + +**Section**: 2.44 | **Asset Class**: Options | **Type**: Income + +## Overview +The "long" iron butterfly is a sideways strategy combining a bull put spread and a bear call spread. It consists of a long OTM put at K1, short ATM put and ATM call at K2, and long OTM call at K3. The strikes are equidistant: K2 - K1 = K3 - K2 = kappa. This is a net credit trade. The trader's outlook is neutral. This is an income strategy. + +## Construction +- Buy 1 OTM put option at strike K1 (lower wing) +- Sell 1 ATM put option at strike K2 (body) +- Sell 1 ATM call option at strike K2 (body, same strike as put) +- Buy 1 OTM call option at strike K3 (upper wing) +- All same expiry; K2 - K1 = K3 - K2 = kappa (equidistant) + +Net credit: C + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ - (S_T - K2)+ + (S_T - K3)+ + C + +- Upper breakeven: S*_up = K2 + C +- Lower breakeven: S*_down = K2 - C +- Max profit: P_max = C (if K1 <= S_T <= K3; both spreads expire worthless) +- Max loss: L_max = kappa - C (if S_T <= K1 or S_T >= K3) + +## Key Conditions / Signals +- Neutral; expects stock to remain close to K2 through expiry +- High implied volatility environment makes the collected credit larger +- Defined risk on both sides unlike a short straddle + +## Notes +The long iron butterfly achieves the same payoff as the short call butterfly or short put butterfly but is constructed using four legs across two spreads. The maximum loss is limited (kappa - C) unlike in a naked short straddle. diff --git a/gateway/knowledge/trading/strategies/options/long-iron-condor.md b/gateway/knowledge/trading/strategies/options/long-iron-condor.md new file mode 100644 index 00000000..ed7d916a --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-iron-condor.md @@ -0,0 +1,36 @@ +--- +description: "A neutral income strategy combining a bull put spread and a bear call spread with four equidistant OTM/ITM strikes, collecting net credit when stock stays between the inner strikes." +tags: [options, income, neutral, condor, iron] +--- + +# Long Iron Condor + +**Section**: 2.50 | **Asset Class**: Options | **Type**: Income + +## Overview +The long iron condor is a sideways strategy combining a bull put spread and a bear call spread. It consists of a long OTM put at K1, a short OTM put at K2, a short OTM call at K3, and a long OTM call at K4. All strikes are equidistant: K4 - K3 = K3 - K2 = K2 - K1 = kappa. This is a net credit trade. The trader's outlook is neutral. This is an income strategy. + +## Construction +- Buy 1 OTM put option at strike K1 (lowest) +- Sell 1 OTM put option at strike K2 (K2 > K1) +- Sell 1 OTM call option at strike K3 (K3 > K2) +- Buy 1 OTM call option at strike K4 (highest, K4 > K3) +- All same expiry; K2 - K1 = K3 - K2 = K4 - K3 = kappa (equidistant) + +Net credit: C + +## Payoff Profile +f_T = (K1 - S_T)+ + (S_T - K4)+ - (K2 - S_T)+ - (S_T - K3)+ + C + +- Upper breakeven: S*_up = K3 + C +- Lower breakeven: S*_down = K2 - C +- Max profit: P_max = C (if K2 <= S_T <= K3 at expiry; all options expire worthless) +- Max loss: L_max = kappa - C (if S_T <= K1 or S_T >= K4) + +## Key Conditions / Signals +- Neutral; expects stock to remain between K2 and K3 through expiry +- High implied volatility makes the collected credit larger +- Defined risk on both sides; popular for structured income trading + +## Notes +The long iron condor is the most widely traded condor variant. It provides a wider profit zone than the iron butterfly (K2 to K3 instead of a single point) with the same defined-risk structure. Maximum loss is limited to kappa - C on either side. diff --git a/gateway/knowledge/trading/strategies/options/long-put-butterfly.md b/gateway/knowledge/trading/strategies/options/long-put-butterfly.md new file mode 100644 index 00000000..1d095c07 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-put-butterfly.md @@ -0,0 +1,46 @@ +--- +description: "A neutral low-cost debit strategy buying an OTM put at K1, selling two ATM puts at K2, and buying an ITM put at K3 with equidistant strikes, profiting if stock stays near K2." +tags: [options, income, neutral, butterfly] +--- + +# Long Put Butterfly + +**Section**: 2.41 | **Asset Class**: Options | **Type**: Income + +## Overview +The long put butterfly is a sideways strategy consisting of a long OTM put at K1, a short position in two ATM puts at K2, and a long ITM put at K3. The strikes are equidistant: K3 - K2 = K2 - K1 = kappa. This is a relatively low cost net debit trade. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Buy 1 put option at strike K1 (OTM, lower wing) +- Sell 2 put options at strike K2 (ATM, body) +- Buy 1 put option at strike K3 (ITM, upper wing, K3 > K2 > K1) +- All same expiry; K3 - K2 = K2 - K1 = kappa (equidistant) + +Net debit: D + +## Payoff Profile +f_T = (K1 - S_T)+ + (K3 - S_T)+ - 2 × (K2 - S_T)+ - D + +- Upper breakeven: S*_up = K3 - D +- Lower breakeven: S*_down = K1 + D +- Max profit: P_max = kappa - D (achieved at S_T = K2) +- Max loss: L_max = D (if S_T >= K3 or S_T <= K1) + +## Key Conditions / Signals +- Neutral; expects stock to pin near K2 at expiry +- Low implied volatility after entry reduces theta bleed on short options +- Low cost structure makes it an efficient way to bet on stability + +## Variations + +### 2.41.1 Modified Put Butterfly +A variation where the strikes are no longer equidistant; instead K3 - K2 < K2 - K1. This results in a sideways strategy with a bullish bias. For H > 0 there is also S*_up = K3 - H. We have: + +f_T = (K1 - S_T)+ + (K3 - S_T)+ - 2 × (K2 - S_T)+ - H + +- Lower breakeven: S*_down = 2 × K2 - K3 + H +- Max profit: P_max = K3 - K2 - H (at S_T = K2) +- Max loss: L_max = 2 × K2 - K1 - K3 + H + +## Notes +The equidistant butterfly has two breakevens symmetric around K2. The maximum profit is the wing width kappa minus the debit. Low-cost entry makes the risk/reward ratio attractive for neutral views. diff --git a/gateway/knowledge/trading/strategies/options/long-put-condor.md b/gateway/knowledge/trading/strategies/options/long-put-condor.md new file mode 100644 index 00000000..5b4da1e0 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-put-condor.md @@ -0,0 +1,36 @@ +--- +description: "A neutral low-cost debit strategy using four puts with equidistant strikes K1 < K2 < K3 < K4, profiting if the stock stays between K2 and K3 at expiry." +tags: [options, income, neutral, condor] +--- + +# Long Put Condor + +**Section**: 2.47 | **Asset Class**: Options | **Type**: Income + +## Overview +The long put condor is a sideways strategy consisting of a long OTM put at K1, a short OTM put at K2 (higher), a short ITM put at K3, and a long ITM put at K4 (highest). All strikes are equidistant: K4 - K3 = K3 - K2 = K2 - K1 = kappa. This is a relatively low cost net debit trade. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Buy 1 put option at strike K1 (OTM, lowest) +- Sell 1 put option at strike K2 (OTM, K2 > K1) +- Sell 1 put option at strike K3 (ITM, K3 > K2) +- Buy 1 put option at strike K4 (ITM, highest, K4 > K3) +- All same expiry; K2 - K1 = K3 - K2 = K4 - K3 = kappa (equidistant) + +Net debit: D + +## Payoff Profile +f_T = (K1 - S_T)+ - (K2 - S_T)+ - (K3 - S_T)+ + (K4 - S_T)+ - D + +- Upper breakeven: S*_up = K4 - D +- Lower breakeven: S*_down = K1 + D +- Max profit: P_max = kappa - D (if K2 <= S_T <= K3 at expiry) +- Max loss: L_max = D (if S_T <= K1 or S_T >= K4) + +## Key Conditions / Signals +- Neutral; expects stock to remain in the middle zone [K2, K3] at expiry +- Low implied volatility after entry; wider profit zone than a butterfly +- Low cost entry makes it efficient for betting on a range-bound stock + +## Notes +The put condor has the same payoff structure as the call condor (by put-call parity). The flat profit plateau between K2 and K3 provides a wider target zone for pinning compared to a butterfly. Four distinct equidistant strikes are required. diff --git a/gateway/knowledge/trading/strategies/options/long-put-synthetic-straddle.md b/gateway/knowledge/trading/strategies/options/long-put-synthetic-straddle.md new file mode 100644 index 00000000..9d1d4d86 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-put-synthetic-straddle.md @@ -0,0 +1,34 @@ +--- +description: "A volatility strategy buying stock and buying two ATM puts at strike K, replicating a long straddle by replacing the long call with a synthetic call." +tags: [options, volatility, neutral, synthetic, straddle] +--- + +# Long Put Synthetic Straddle + +**Section**: 2.29 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The long put synthetic straddle (the same as a long straddle with the call replaced by a synthetic call) amounts to buying stock and buying two ATM (or nearest ITM) put options with strike K. The trader's outlook is neutral. This is a capital gain strategy. We assume S0 <= K and D > K - S0. + +## Construction +- Buy 1 share of stock at S0 +- Buy 2 ATM put options at strike K, same expiry + +Net debit: D (assumed D > K - S0) + +## Payoff Profile +f_T = S_T - S0 + 2 × (K - S_T)+ - D + +- Upper breakeven: S*_up = S0 + D +- Lower breakeven: S*_down = 2K - S0 - D +- Max profit: P_max = unlimited (large move in either direction) +- Max loss: L_max = D - (K - S0) (at S_T = K; intrinsic offset reduces loss) + +## Key Conditions / Signals +- Neutral view; expects a large move in either direction +- S0 <= K (stock at or below the put strike) +- D > K - S0 prevents arbitrage +- Useful when calls are expensive relative to puts (use puts to synthesize the straddle) + +## Notes +The long stock combined with two long puts replicates a straddle by put-call parity. The maximum loss is reduced by the amount K - S0 (intrinsic value of the synthetic call component). diff --git a/gateway/knowledge/trading/strategies/options/long-straddle.md b/gateway/knowledge/trading/strategies/options/long-straddle.md new file mode 100644 index 00000000..35b670b2 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-straddle.md @@ -0,0 +1,33 @@ +--- +description: "A volatility strategy buying an ATM call and an ATM put at the same strike K, profiting from a large move in either direction." +tags: [options, volatility, neutral, straddle] +--- + +# Long Straddle + +**Section**: 2.22 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The long straddle is a volatility strategy consisting of a long position in an ATM call option and a long position in an ATM put option with the same strike K. This is a net debit trade. The trader's outlook is neutral (non-directional). This is a capital gain strategy that profits from a large move in either direction. + +## Construction +- Buy 1 ATM call option at strike K +- Buy 1 ATM put option at strike K, same expiry + +Net debit: D + +## Payoff Profile +f_T = (S_T - K)+ + (K - S_T)+ - D + +- Upper breakeven: S*_up = K + D +- Lower breakeven: S*_down = K - D +- Max profit: P_max = unlimited (stock can move far in either direction) +- Max loss: L_max = D (if S_T = K exactly at expiry; both options expire worthless) + +## Key Conditions / Signals +- Neutral directional view; expects a large move but uncertain of direction +- Low implied volatility environment makes the debit cheaper to enter +- Ideal before high-impact events (earnings, central bank announcements) + +## Notes +The maximum loss is limited to the net debit paid. The position benefits from a rise in implied volatility (long vega). Time decay (theta) works against the position; the stock must move enough to overcome the debit paid. diff --git a/gateway/knowledge/trading/strategies/options/long-strangle.md b/gateway/knowledge/trading/strategies/options/long-strangle.md new file mode 100644 index 00000000..467a2b47 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-strangle.md @@ -0,0 +1,33 @@ +--- +description: "A volatility strategy buying an OTM call at K1 and an OTM put at K2 < K1, profiting from a large move in either direction at lower cost than a straddle." +tags: [options, volatility, neutral, strangle] +--- + +# Long Strangle + +**Section**: 2.23 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The long strangle is a volatility strategy consisting of a long position in an OTM call option with strike K1 and a long position in an OTM put option with strike K2 (K2 < K1). This is a net debit trade. Because both options are OTM, this strategy is less costly to establish than a long straddle. The flipside is that the move required to reach a breakeven point is more significant. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Buy 1 OTM call option at strike K1 +- Buy 1 OTM put option at strike K2 (K2 < K1), same expiry + +Net debit: D + +## Payoff Profile +f_T = (S_T - K1)+ + (K2 - S_T)+ - D + +- Upper breakeven: S*_up = K1 + D +- Lower breakeven: S*_down = K2 - D +- Max profit: P_max = unlimited (stock can move far in either direction) +- Max loss: L_max = D (if K2 <= S_T <= K1 at expiry; both options expire worthless) + +## Key Conditions / Signals +- Neutral directional view; expects a very large move but uncertain of direction +- Cheaper than a straddle but requires a larger price movement to profit +- Ideal before high-impact events where an extreme move is anticipated + +## Notes +The maximum loss zone is the range [K2, K1] where both options expire worthless. The position is long vega and short theta. Compared to a straddle, the strangle is cheaper to enter but needs a bigger move to profit. diff --git a/gateway/knowledge/trading/strategies/options/long-synthetic-forward.md b/gateway/knowledge/trading/strategies/options/long-synthetic-forward.md new file mode 100644 index 00000000..a36079c0 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/long-synthetic-forward.md @@ -0,0 +1,32 @@ +--- +description: "A bullish capital-gain strategy buying an ATM call and selling an ATM put at the same strike K = S0, replicating a long forward contract on the underlying." +tags: [options, speculation, bullish, synthetic] +--- + +# Long Synthetic Forward + +**Section**: 2.10 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The long synthetic forward amounts to buying an ATM call option and selling an ATM put option with the same strike K = S0. This can be a net debit or net credit trade; typically |H| << S0. The trader's outlook is bullish: this strategy mimics a long stock or futures position and replicates a long forward contract with delivery price K and the same maturity as the options. This is a capital gain strategy. + +## Construction +- Buy 1 ATM call option at strike K = S0 +- Sell 1 ATM put option at strike K = S0, same expiry + +Net debit or credit H (H = D for net debit trade, H = -C for net credit trade) + +## Payoff Profile +f_T = (S_T - K)+ - (K - S_T)+ - H = S_T - K - H + +- Breakeven: S* = K + H +- Max profit: P_max = unlimited (stock can rise without bound) +- Max loss: L_max = K + H (if stock goes to zero) + +## Key Conditions / Signals +- Strongly bullish outlook seeking full participation in upside +- Useful when the cost of direct stock purchase is prohibitive +- Typically near-zero net premium (H is small relative to S0) + +## Notes +The payoff is linear in S_T — identical to holding the stock (minus K + H). The downside is not limited; the position loses as the stock falls below K, just like a long stock position. diff --git a/gateway/knowledge/trading/strategies/options/protective-call.md b/gateway/knowledge/trading/strategies/options/protective-call.md new file mode 100644 index 00000000..cb99bc5e --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/protective-call.md @@ -0,0 +1,32 @@ +--- +description: "A hedging strategy combining short stock with a long call at strike K >= S0, limiting upside loss on a short position while preserving downside profit." +tags: [options, hedging, protective, bearish] +--- + +# Protective Call + +**Section**: 2.5 | **Asset Class**: Options | **Type**: Hedging + +## Overview +The protective call (a.k.a. "married call" or "synthetic put") amounts to shorting stock and buying an ATM or OTM call option with strike K >= S0. The trader's outlook is bearish. The call option hedges the risk of the stock price rising, acting as insurance on the short stock position. + +## Construction +- Short 1 share of stock at price S0 +- Buy 1 call option at strike K (K >= S0), paying net debit D + +Net position: short stock + long call + +## Payoff Profile +f_T = S0 - S_T + (S_T - K)+ - D = S0 - K + (K - S_T)+ - D + +- Breakeven: S* = S0 - D +- Max profit: P_max = S0 - D (if stock goes to zero) +- Max loss: L_max = K - S0 + D (capped by the long call at strike K) + +## Key Conditions / Signals +- Bearish on the underlying but seeking upside protection on the short +- Elevated uncertainty or event risk where a sharp rise in the stock is possible +- Useful when the trader wants to retain short stock exposure but limit loss from a rally + +## Notes +The protective call is symmetrical to the protective put strategy. Academic literature on protective calls appears scarce. The debit paid for the call reduces the effective profit from stock depreciation. diff --git a/gateway/knowledge/trading/strategies/options/protective-put.md b/gateway/knowledge/trading/strategies/options/protective-put.md new file mode 100644 index 00000000..662f2e62 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/protective-put.md @@ -0,0 +1,32 @@ +--- +description: "A hedging strategy combining long stock with a long put at strike K <= S0, limiting downside loss while preserving unlimited upside." +tags: [options, hedging, protective, bullish] +--- + +# Protective Put + +**Section**: 2.4 | **Asset Class**: Options | **Type**: Hedging + +## Overview +The protective put (a.k.a. "married put" or "synthetic call") amounts to buying stock and buying an ATM or OTM put option with strike K <= S0. The trader's outlook is bullish. The put option hedges the risk of the stock price falling, acting as insurance on the long stock position. + +## Construction +- Buy 1 share of stock at price S0 +- Buy 1 put option at strike K (K <= S0), paying net debit D + +Net position: long stock + long put + +## Payoff Profile +f_T = S_T - S0 + (K - S_T)+ - D = K - S0 + (S_T - K)+ - D + +- Breakeven: S* = S0 + D +- Max profit: P_max = unlimited (stock can rise without bound) +- Max loss: L_max = S0 - K + D (floor established at strike K) + +## Key Conditions / Signals +- Bullish on the underlying but seeking downside protection +- Elevated uncertainty or event risk (earnings, macro) where a sharp drop is possible +- Useful when the trader wants to retain long stock exposure but limit catastrophic loss + +## Notes +The protective put is the put-call parity complement to the covered call. The debit paid for the put reduces the effective profit from stock appreciation. The maximum loss is capped at S0 - K + D regardless of how far the stock falls. diff --git a/gateway/knowledge/trading/strategies/options/put-ratio-backspread.md b/gateway/knowledge/trading/strategies/options/put-ratio-backspread.md new file mode 100644 index 00000000..18ce5c8a --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/put-ratio-backspread.md @@ -0,0 +1,33 @@ +--- +description: "A strongly bearish volatility strategy selling fewer near-ATM puts at K1 and buying more OTM puts at K2 < K1, with unlimited profit on a sharp decline and limited loss in between." +tags: [options, volatility, bearish, backspread] +--- + +# Put Ratio Backspread + +**Section**: 2.37 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The put ratio backspread consists of a short position in N_S close to ATM put options with strike K1, and a long position in N_L OTM put options with strike K2 (K2 < K1), where N_L > N_S. Typically N_L = 2, N_S = 1 or N_L = 3, N_S = 2. The trader's outlook is strongly bearish. This is a capital gain strategy. + +## Construction +- Sell N_S put options at strike K1 (near ATM) +- Buy N_L put options at strike K2 (OTM lower, K2 < K1, N_L > N_S), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = N_L × (K2 - S_T)+ - N_S × (K1 - S_T)+ - H + +- Upper breakeven (if H < 0): S*_up = K1 + H/N_S +- Lower breakeven: S*_down = (N_L × K2 - N_S × K1 - H) / (N_L - N_S) +- Max profit: P_max = N_L × K2 - N_S × K1 - H (if stock goes to zero) +- Max loss: L_max = N_S × (K1 - K2) + H (in the zone near K2 where long puts are OTM but short puts are ITM) + +## Key Conditions / Signals +- Strongly bearish; expects a significant decline below K2 +- Ideally entered as a credit (H < 0) so that profit is also made if stock stays above K1 +- Loss zone is bounded between the two breakevens + +## Notes +The difference between put ratio backspread and ratio put spread: here N_L > N_S (more longs than shorts). The maximum loss occurs near K2 at expiry. If H < 0, the position profits if the stock stays well above K1 or collapses well below the lower breakeven. diff --git a/gateway/knowledge/trading/strategies/options/ratio-call-spread.md b/gateway/knowledge/trading/strategies/options/ratio-call-spread.md new file mode 100644 index 00000000..fc9b6a06 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/ratio-call-spread.md @@ -0,0 +1,33 @@ +--- +description: "A neutral-to-bearish income strategy selling more near-ATM calls at K1 than ITM calls bought at K2 < K1, collecting premium with unlimited upside risk above the upper breakeven." +tags: [options, income, neutral, ratio-spread] +--- + +# Ratio Call Spread + +**Section**: 2.38 | **Asset Class**: Options | **Type**: Income + +## Overview +The ratio call spread consists of a short position in N_S close to ATM call options with strike K1, and a long position in N_L ITM call options with strike K2 (K2 < K1), where N_L < N_S. Typically N_L = 1, N_S = 2 or N_L = 2, N_S = 3. This is an income strategy if structured as a net credit trade. The trader's outlook is neutral to bearish. + +## Construction +- Sell N_S call options at strike K1 (near ATM) +- Buy N_L call options at strike K2 (ITM, K2 < K1, N_L < N_S), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = N_L × (S_T - K2)+ - N_S × (S_T - K1)+ - H + +- Lower breakeven (if H > 0): S*_down = K2 + H/N_L +- Upper breakeven: S*_up = (N_S × K1 - N_L × K2 - H) / (N_S - N_L) +- Max profit: P_max = N_L × (K1 - K2) - H (in zone [K2, K1] range) +- Max loss: L_max = unlimited (above the upper breakeven; net short calls) + +## Key Conditions / Signals +- Neutral to mildly bearish; expects stock to remain below K1 +- Structured as a net credit when possible (income strategy) +- High implied volatility makes the collected premium from extra short calls larger + +## Notes +Unlike the call ratio backspread (where N_L > N_S), here N_L < N_S, so there is net short call exposure above K1 creating unlimited upside risk. The maximum profit is achieved if the stock stays in the [K2, K1] zone at expiry. diff --git a/gateway/knowledge/trading/strategies/options/ratio-put-spread.md b/gateway/knowledge/trading/strategies/options/ratio-put-spread.md new file mode 100644 index 00000000..ae10e088 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/ratio-put-spread.md @@ -0,0 +1,33 @@ +--- +description: "A neutral-to-bullish income strategy selling more near-ATM puts at K1 than ITM puts bought at K2 > K1, collecting premium with unlimited downside risk below the lower breakeven." +tags: [options, income, neutral, ratio-spread] +--- + +# Ratio Put Spread + +**Section**: 2.39 | **Asset Class**: Options | **Type**: Income + +## Overview +The ratio put spread consists of a short position in N_S close to ATM put options with strike K1, and a long position in N_L ITM put options with strike K2 (K2 > K1), where N_L < N_S. Typically N_L = 1, N_S = 2 or N_L = 2, N_S = 3. This is an income strategy if structured as a net credit trade. The trader's outlook is neutral to bullish. + +## Construction +- Sell N_S put options at strike K1 (near ATM) +- Buy N_L put options at strike K2 (ITM, K2 > K1, N_L < N_S), same expiry + +Net debit or credit H + +## Payoff Profile +f_T = N_L × (K2 - S_T)+ - N_S × (K1 - S_T)+ - H + +- Upper breakeven (if H > 0): S*_up = K2 - H/N_L +- Lower breakeven: S*_down = (N_S × K1 - N_L × K2 + H) / (N_S - N_L) +- Max profit: P_max = N_L × (K2 - K1) - H (in zone [K1, K2]) +- Max loss: L_max = N_S × K1 - N_L × K2 + H (if stock goes to zero; unlimited downside) + +## Key Conditions / Signals +- Neutral to mildly bullish; expects stock to remain above K1 +- Structured as a net credit when possible (income strategy) +- High implied volatility makes the collected premium from extra short puts larger + +## Notes +Unlike the put ratio backspread (where N_L > N_S), here N_L < N_S, so there is net short put exposure below K1 creating unlimited downside risk. The maximum profit is achieved if the stock stays in the [K1, K2] zone at expiry. diff --git a/gateway/knowledge/trading/strategies/options/short-call-butterfly.md b/gateway/knowledge/trading/strategies/options/short-call-butterfly.md new file mode 100644 index 00000000..bec03848 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-call-butterfly.md @@ -0,0 +1,35 @@ +--- +description: "A neutral net credit strategy selling an ITM call at K1, buying two ATM calls at K2, and selling an OTM call at K3, profiting from a large move away from K2." +tags: [options, volatility, neutral, butterfly] +--- + +# Short Call Butterfly + +**Section**: 2.42 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The short call butterfly is a volatility strategy consisting of a short ITM call at K1, a long position in two ATM calls at K2, and a short OTM call at K3. The strikes are equidistant: K3 - K2 = K2 - K1 = kappa. This is a net credit trade. In this sense it is an income strategy. However, the potential reward is sizably smaller than with a short straddle or short strangle (albeit with lower risk). The trader's outlook is neutral. + +## Construction +- Sell 1 call option at strike K1 (ITM, lower wing) +- Buy 2 call options at strike K2 (ATM, body) +- Sell 1 call option at strike K3 (OTM, upper wing, K3 > K2 > K1) +- All same expiry; K3 - K2 = K2 - K1 = kappa (equidistant) + +Net credit: C + +## Payoff Profile +f_T = 2 × (S_T - K2)+ - (S_T - K1)+ - (S_T - K3)+ + C + +- Upper breakeven: S*_up = K3 - C +- Lower breakeven: S*_down = K1 + C +- Max profit: P_max = C (if S_T <= K1 or S_T >= K3; all options at their extremes) +- Max loss: L_max = kappa - C (if S_T = K2 at expiry) + +## Key Conditions / Signals +- Neutral; expects stock to move significantly away from K2 by expiry +- High implied volatility environment; collect larger credit upfront +- Lower risk than a short straddle or strangle but also lower reward + +## Notes +The short call butterfly is the reverse of the long call butterfly. Credit is collected upfront and profit is achieved if the stock moves far enough from K2. The maximum loss is bounded by the wing width kappa minus the credit received. diff --git a/gateway/knowledge/trading/strategies/options/short-call-condor.md b/gateway/knowledge/trading/strategies/options/short-call-condor.md new file mode 100644 index 00000000..f479d096 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-call-condor.md @@ -0,0 +1,36 @@ +--- +description: "A neutral volatility strategy selling an ITM call at K1 and OTM call at K4 while buying calls at K2 and K3, collecting credit and profiting from a large move outside [K1, K4]." +tags: [options, volatility, neutral, condor] +--- + +# Short Call Condor + +**Section**: 2.48 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The short call condor is a volatility strategy consisting of a short ITM call at K1, a long ITM call at K2, a long OTM call at K3, and a short OTM call at K4. All strikes are equidistant: K4 - K3 = K3 - K2 = K2 - K1 = kappa. This is a relatively low net credit trade. As with a short call butterfly, the potential reward is sizably smaller than with a short straddle or short strangle (albeit with lower risk). So this is a capital gain (rather than income) strategy. The trader's outlook is neutral. + +## Construction +- Sell 1 call option at strike K1 (ITM, lowest) +- Buy 1 call option at strike K2 (ITM, K2 > K1) +- Buy 1 call option at strike K3 (OTM, K3 > K2) +- Sell 1 call option at strike K4 (OTM, highest, K4 > K3) +- All same expiry; K2 - K1 = K3 - K2 = K4 - K3 = kappa (equidistant) + +Net credit: C + +## Payoff Profile +f_T = (S_T - K2)+ + (S_T - K3)+ - (S_T - K1)+ - (S_T - K4)+ + C + +- Upper breakeven: S*_up = K4 - C +- Lower breakeven: S*_down = K1 + C +- Max profit: P_max = C (if S_T <= K1 or S_T >= K4) +- Max loss: L_max = kappa - C (if K2 <= S_T <= K3 at expiry) + +## Key Conditions / Signals +- Neutral; expects stock to move significantly outside the [K1, K4] range +- High implied volatility environment; collect larger credit upfront +- Defined risk on both sides, making it safer than a short straddle + +## Notes +The short call condor is the reverse of the long call condor. Net credit is collected and the strategy profits from large moves in either direction. Maximum loss is kappa - C, occurring if the stock stays in the middle zone [K2, K3]. diff --git a/gateway/knowledge/trading/strategies/options/short-call-synthetic-straddle.md b/gateway/knowledge/trading/strategies/options/short-call-synthetic-straddle.md new file mode 100644 index 00000000..5da75247 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-call-synthetic-straddle.md @@ -0,0 +1,33 @@ +--- +description: "A sideways strategy buying stock and selling two ATM calls at strike K, replicating a short straddle by replacing the short put with a synthetic short put." +tags: [options, income, neutral, synthetic, straddle] +--- + +# Short Call Synthetic Straddle + +**Section**: 2.30 | **Asset Class**: Options | **Type**: Income + +## Overview +The short call synthetic straddle (the same as a short straddle with the put replaced by a synthetic put) amounts to buying stock and selling two ATM (or nearest OTM) call options with strike K. The trader's outlook is neutral. This is a capital gain strategy. We assume S0 <= K. + +## Construction +- Buy 1 share of stock at S0 +- Sell 2 ATM call options at strike K, same expiry + +Net credit: C + +## Payoff Profile +f_T = S_T - S0 - 2 × (S_T - K)+ + C + +- Upper breakeven: S*_up = 2K - S0 + C +- Lower breakeven: S*_down = S0 - C +- Max profit: P_max = K - S0 + C (at S_T = K) +- Max loss: L_max = unlimited (stock can rise without bound; short 2 calls) + +## Key Conditions / Signals +- Neutral view; expects stock to stay near K through expiry +- S0 <= K (stock at or below the call strike) +- High implied volatility makes the collected credit from the two short calls larger + +## Notes +Unlimited loss on the upside due to the two short calls. The long stock provides partial offset against rising prices but is insufficient beyond the breakeven. Active management or stop-losses are essential. diff --git a/gateway/knowledge/trading/strategies/options/short-combo.md b/gateway/knowledge/trading/strategies/options/short-combo.md new file mode 100644 index 00000000..e6be7fb8 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-combo.md @@ -0,0 +1,36 @@ +--- +description: "A bearish capital-gain strategy (short risk reversal) buying an OTM put at K1 and selling an OTM call at K2 > K1, profiting from a strong downward move." +tags: [options, speculation, bearish, risk-reversal] +--- + +# Short Combo + +**Section**: 2.13 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The short combo (a.k.a. "short risk reversal") amounts to buying an OTM put option with strike K1 and selling an OTM call option with strike K2, where K2 > K1. The trader's outlook is bearish. This is a capital gain strategy. + +## Construction +- Buy 1 OTM put option at strike K1 +- Sell 1 OTM call option at strike K2 (K2 > K1), same expiry + +Net debit or credit H (H = D if net debit, H = -C if net credit; K2 > K1) + +## Payoff Profile +f_T = (K1 - S_T)+ - (S_T - K2)+ - H + +Breakeven depends on sign of H: +- S* = K1 - H (if H > 0, net debit) +- S* = K2 - H (if H < 0, net credit) +- K1 <= S* <= K2 (if H = 0, zero-cost) + +- Max profit: P_max = K1 - H (if stock goes to zero) +- Max loss: L_max = unlimited (stock can rise without bound) + +## Key Conditions / Signals +- Strongly bearish outlook +- Traders often structure as zero-cost (H = 0) by selecting K1 and K2 such that premiums offset +- Profits from a large downward move; loses if stock rises above K2 + +## Notes +The short combo creates a flat zone [K1, K2] where the payoff equals -H. Unlike the short synthetic forward (where K1 = K2 = S0), both strikes are OTM. Unlimited loss potential on the upside due to the short call. diff --git a/gateway/knowledge/trading/strategies/options/short-guts.md b/gateway/knowledge/trading/strategies/options/short-guts.md new file mode 100644 index 00000000..512cd6b1 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-guts.md @@ -0,0 +1,33 @@ +--- +description: "A sideways income strategy selling an ITM call at K1 and an ITM put at K2 > K1, collecting a higher premium than a short straddle but with higher risk and a narrower profit zone." +tags: [options, income, neutral, guts] +--- + +# Short Guts + +**Section**: 2.27 | **Asset Class**: Options | **Type**: Income + +## Overview +The short guts is a sideways strategy consisting of a short position in an ITM call option with strike K1 and a short position in an ITM put option with strike K2 (K2 > K1). This is a net credit trade. Since both options are ITM, the initial credit is higher than in a short straddle position; the flipside is that the risk is also higher. The trader's outlook is neutral. This is an income strategy. We assume C > K2 - K1. + +## Construction +- Sell 1 ITM call option at strike K1 +- Sell 1 ITM put option at strike K2 (K2 > K1), same expiry + +Net credit: C (assumed C > K2 - K1) + +## Payoff Profile +f_T = -(S_T - K1)+ - (K2 - S_T)+ + C + +- Upper breakeven: S*_up = K1 + C +- Lower breakeven: S*_down = K2 - C +- Max profit: P_max = C - (K2 - K1) (if K1 <= S_T <= K2; intrinsic value reduces profit) +- Max loss: L_max = unlimited (stock can move far in either direction) + +## Key Conditions / Signals +- Neutral view; expects stock to stay in the range [K1, K2] through expiry +- The higher credit offsets the reduced maximum profit zone relative to a short straddle +- High implied volatility environment is ideal for collecting large premium + +## Notes +The assumption C > K2 - K1 prevents risk-free arbitrage. Maximum profit is reduced by the intrinsic spread K2 - K1. The position is short vega and long theta with unlimited directional risk. diff --git a/gateway/knowledge/trading/strategies/options/short-iron-butterfly.md b/gateway/knowledge/trading/strategies/options/short-iron-butterfly.md new file mode 100644 index 00000000..932ca605 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-iron-butterfly.md @@ -0,0 +1,36 @@ +--- +description: "A neutral volatility strategy combining a bear put spread and a bull call spread around a central ATM strike K2, paying a net debit to profit from a large move away from K2." +tags: [options, volatility, neutral, butterfly, iron] +--- + +# Short Iron Butterfly + +**Section**: 2.45 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The "short" iron butterfly is a volatility strategy combining a bear put spread and a bull call spread. It consists of a short OTM put at K1, long ATM put and ATM call at K2, and short OTM call at K3. The strikes are equidistant: K2 - K1 = K3 - K2 = kappa. This is a net debit trade. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Sell 1 OTM put option at strike K1 (lower wing) +- Buy 1 ATM put option at strike K2 (body) +- Buy 1 ATM call option at strike K2 (body, same strike as put) +- Sell 1 OTM call option at strike K3 (upper wing) +- All same expiry; K2 - K1 = K3 - K2 = kappa (equidistant) + +Net debit: D + +## Payoff Profile +f_T = (K2 - S_T)+ + (S_T - K2)+ - (K1 - S_T)+ - (S_T - K3)+ - D + +- Upper breakeven: S*_up = K2 + D +- Lower breakeven: S*_down = K2 - D +- Max profit: P_max = kappa - D (if S_T <= K1 or S_T >= K3) +- Max loss: L_max = D (if S_T = K2; long straddle at center expires at minimum) + +## Key Conditions / Signals +- Neutral; expects a large move away from K2 in either direction +- Low implied volatility environment makes the debit cheaper to enter +- Defined risk on both sides unlike a naked long straddle + +## Notes +The short iron butterfly achieves the same payoff as the long call butterfly or long put butterfly but uses four legs spanning two spreads. The maximum loss is the net debit D, occurring when the stock pins at K2 at expiry. diff --git a/gateway/knowledge/trading/strategies/options/short-iron-condor.md b/gateway/knowledge/trading/strategies/options/short-iron-condor.md new file mode 100644 index 00000000..391737ee --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-iron-condor.md @@ -0,0 +1,36 @@ +--- +description: "A neutral volatility strategy combining a bear put spread and a bull call spread with four equidistant strikes, paying a net debit to profit from a large move outside the inner strikes." +tags: [options, volatility, neutral, condor, iron] +--- + +# Short Iron Condor + +**Section**: 2.51 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The short iron condor is a volatility strategy combining a bear put spread and a bull call spread. It consists of a short OTM put at K1, a long OTM put at K2, a long OTM call at K3, and a short OTM call at K4. All strikes are equidistant: K4 - K3 = K3 - K2 = K2 - K1 = kappa. This is a net debit trade. The trader's outlook is neutral. This is a capital gain strategy. + +## Construction +- Sell 1 OTM put option at strike K1 (lowest) +- Buy 1 OTM put option at strike K2 (K2 > K1) +- Buy 1 OTM call option at strike K3 (K3 > K2) +- Sell 1 OTM call option at strike K4 (highest, K4 > K3) +- All same expiry; K2 - K1 = K3 - K2 = K4 - K3 = kappa (equidistant) + +Net debit: D + +## Payoff Profile +f_T = (K2 - S_T)+ + (S_T - K3)+ - (K1 - S_T)+ - (S_T - K4)+ - D + +- Upper breakeven: S*_up = K3 + D +- Lower breakeven: S*_down = K2 - D +- Max profit: P_max = kappa - D (if S_T <= K1 or S_T >= K4) +- Max loss: L_max = D (if K2 <= S_T <= K3; inner spreads expire worthless) + +## Key Conditions / Signals +- Neutral; expects stock to move significantly outside the [K2, K3] range +- Low implied volatility makes the net debit cheaper to enter +- Defined risk on both sides with defined maximum profit + +## Notes +The short iron condor is the reverse of the long iron condor. A net debit is paid and the strategy profits from large moves in either direction. The maximum loss D occurs if the stock stays between K2 and K3; maximum profit kappa - D is achieved outside [K1, K4]. diff --git a/gateway/knowledge/trading/strategies/options/short-put-butterfly.md b/gateway/knowledge/trading/strategies/options/short-put-butterfly.md new file mode 100644 index 00000000..611b1829 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-put-butterfly.md @@ -0,0 +1,35 @@ +--- +description: "A neutral net credit strategy selling an ITM put at K1, buying two ATM puts at K2, and selling an OTM put at K3, profiting from a large move away from K2." +tags: [options, volatility, neutral, butterfly] +--- + +# Short Put Butterfly + +**Section**: 2.43 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The short put butterfly is a volatility strategy consisting of a short ITM put at K1, a long position in two ATM puts at K2, and a short OTM put at K3. The strikes are equidistant: K2 - K3 = K1 - K2 = kappa. This is a net credit trade. In this sense it is an income strategy. However, the potential reward is sizably smaller than with a short straddle or short strangle (albeit with lower risk). The trader's outlook is neutral. + +## Construction +- Sell 1 put option at strike K1 (ITM, upper wing, K1 > K2) +- Buy 2 put options at strike K2 (ATM, body) +- Sell 1 put option at strike K3 (OTM, lower wing, K3 < K2) +- All same expiry; K1 - K2 = K2 - K3 = kappa (equidistant) + +Net credit: C + +## Payoff Profile +f_T = 2 × (K2 - S_T)+ - (K1 - S_T)+ - (K3 - S_T)+ + C + +- Lower breakeven: S*_down = K3 + C +- Upper breakeven: S*_up = K1 - C +- Max profit: P_max = C (if S_T >= K1 or S_T <= K3) +- Max loss: L_max = kappa - C (if S_T = K2 at expiry) + +## Key Conditions / Signals +- Neutral; expects stock to move significantly away from K2 by expiry +- High implied volatility environment; collect larger credit upfront +- Lower risk than a short straddle or strangle but also lower reward + +## Notes +The short put butterfly is the reverse of the long put butterfly. Credit is collected upfront and profit is achieved if the stock moves far enough from K2. The maximum loss is bounded by the wing width kappa minus the credit received. diff --git a/gateway/knowledge/trading/strategies/options/short-put-condor.md b/gateway/knowledge/trading/strategies/options/short-put-condor.md new file mode 100644 index 00000000..65bf5dbe --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-put-condor.md @@ -0,0 +1,36 @@ +--- +description: "A neutral volatility strategy selling an OTM put at K1 and ITM put at K4 while buying puts at K2 and K3, collecting credit and profiting from a large move outside [K1, K4]." +tags: [options, volatility, neutral, condor] +--- + +# Short Put Condor + +**Section**: 2.49 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The short put condor is a volatility strategy consisting of a short OTM put at K1, a long OTM put at K2, a long ITM put at K3, and a short ITM put at K4. All strikes are equidistant: K4 - K3 = K3 - K2 = K2 - K1 = kappa. This is a relatively low net credit trade. As with a short put butterfly, the potential reward is sizably smaller than with a short straddle or short strangle (albeit with lower risk). So this is a capital gain (rather than income) strategy. The trader's outlook is neutral. + +## Construction +- Sell 1 put option at strike K1 (OTM, lowest) +- Buy 1 put option at strike K2 (OTM, K2 > K1) +- Buy 1 put option at strike K3 (ITM, K3 > K2) +- Sell 1 put option at strike K4 (ITM, highest, K4 > K3) +- All same expiry; K2 - K1 = K3 - K2 = K4 - K3 = kappa (equidistant) + +Net credit: C + +## Payoff Profile +f_T = (K2 - S_T)+ + (K3 - S_T)+ - (K1 - S_T)+ - (K4 - S_T)+ + C + +- Upper breakeven: S*_up = K4 - C +- Lower breakeven: S*_down = K1 + C +- Max profit: P_max = C (if S_T <= K1 or S_T >= K4) +- Max loss: L_max = kappa - C (if K2 <= S_T <= K3 at expiry) + +## Key Conditions / Signals +- Neutral; expects stock to move significantly outside the [K1, K4] range +- High implied volatility environment; collect larger credit upfront +- Defined risk on both sides, making it safer than a short straddle + +## Notes +The short put condor has the same payoff as the short call condor (by put-call parity). Net credit is collected and the strategy profits from large moves in either direction. Maximum loss kappa - C occurs if the stock stays in the middle zone [K2, K3]. diff --git a/gateway/knowledge/trading/strategies/options/short-put-synthetic-straddle.md b/gateway/knowledge/trading/strategies/options/short-put-synthetic-straddle.md new file mode 100644 index 00000000..618f3ceb --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-put-synthetic-straddle.md @@ -0,0 +1,33 @@ +--- +description: "A sideways strategy shorting stock and selling two ATM puts at strike K, replicating a short straddle by replacing the short call with a synthetic short call." +tags: [options, income, neutral, synthetic, straddle] +--- + +# Short Put Synthetic Straddle + +**Section**: 2.31 | **Asset Class**: Options | **Type**: Income + +## Overview +The short put synthetic straddle (the same as a short straddle with the call replaced by a synthetic call) amounts to shorting stock and selling two ATM (or nearest OTM) put options with strike K. The trader's outlook is neutral. This is a capital gain strategy. We assume S0 >= K. + +## Construction +- Short 1 share of stock at S0 +- Sell 2 ATM put options at strike K, same expiry + +Net credit: C + +## Payoff Profile +f_T = S0 - S_T - 2 × (K - S_T)+ + C + +- Upper breakeven: S*_up = S0 + C +- Lower breakeven: S*_down = 2K - S0 - C +- Max profit: P_max = S0 - K + C (at S_T = K) +- Max loss: L_max = unlimited (stock can fall without bound; short 2 puts + short stock) + +## Key Conditions / Signals +- Neutral view; expects stock to stay near K through expiry +- S0 >= K (stock at or above the put strike) +- High implied volatility makes the collected credit from the two short puts larger + +## Notes +Unlimited loss on the downside due to the two short puts combined with the short stock position. The short stock provides partial offset against falling prices but is insufficient beyond the breakeven. Active management or stop-losses are essential. diff --git a/gateway/knowledge/trading/strategies/options/short-straddle.md b/gateway/knowledge/trading/strategies/options/short-straddle.md new file mode 100644 index 00000000..9bf0d56a --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-straddle.md @@ -0,0 +1,33 @@ +--- +description: "A sideways income strategy selling an ATM call and an ATM put at the same strike K, collecting premium when the stock stays near K." +tags: [options, income, neutral, straddle] +--- + +# Short Straddle + +**Section**: 2.25 | **Asset Class**: Options | **Type**: Income + +## Overview +The short straddle is a sideways strategy consisting of a short position in an ATM call option and a short position in an ATM put option with the same strike K. This is a net credit trade. The trader's outlook is neutral. This is an income strategy that profits if the stock remains near K until expiry. + +## Construction +- Sell 1 ATM call option at strike K +- Sell 1 ATM put option at strike K, same expiry + +Net credit: C + +## Payoff Profile +f_T = -(S_T - K)+ - (K - S_T)+ + C + +- Upper breakeven: S*_up = K + C +- Lower breakeven: S*_down = K - C +- Max profit: P_max = C (if S_T = K at expiry; both options expire worthless) +- Max loss: L_max = unlimited (stock can move far in either direction) + +## Key Conditions / Signals +- Neutral view; expects stock to remain very close to K through expiry +- High implied volatility environment makes the collected credit larger +- Ideal when volatility is expected to contract (sell elevated IV, profit from IV crush) + +## Notes +Unlimited risk in both directions. The position is short vega and long theta. A sharp move in either direction can result in catastrophic losses. Active management (delta hedging or stop-losses) is essential. diff --git a/gateway/knowledge/trading/strategies/options/short-strangle.md b/gateway/knowledge/trading/strategies/options/short-strangle.md new file mode 100644 index 00000000..ec72f2ea --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-strangle.md @@ -0,0 +1,33 @@ +--- +description: "A sideways income strategy selling an OTM call at K1 and an OTM put at K2 < K1, collecting premium with a wider profit zone than a short straddle but lower credit." +tags: [options, income, neutral, strangle] +--- + +# Short Strangle + +**Section**: 2.26 | **Asset Class**: Options | **Type**: Income + +## Overview +The short strangle is a sideways strategy consisting of a short position in an OTM call option with strike K1 and a short position in an OTM put option with strike K2 (K2 < K1). This is a net credit trade. Since both options are OTM, this strategy is less risky than a short straddle position; the flipside is that the initial credit is also lower. The trader's outlook is neutral. This is an income strategy. + +## Construction +- Sell 1 OTM call option at strike K1 +- Sell 1 OTM put option at strike K2 (K2 < K1), same expiry + +Net credit: C + +## Payoff Profile +f_T = -(S_T - K1)+ - (K2 - S_T)+ + C + +- Upper breakeven: S*_up = K1 + C +- Lower breakeven: S*_down = K2 - C +- Max profit: P_max = C (if K2 <= S_T <= K1 at expiry; both options expire worthless) +- Max loss: L_max = unlimited (stock can move far in either direction) + +## Key Conditions / Signals +- Neutral view; expects stock to remain between K2 and K1 through expiry +- High implied volatility environment makes the collected credit larger +- Wider profit zone than a short straddle, but smaller credit collected + +## Notes +Unlimited risk in both directions once the stock moves outside [K2, K1]. The position is short vega and long theta. Less risky than the short straddle but still requires active management for large moves. diff --git a/gateway/knowledge/trading/strategies/options/short-synthetic-forward.md b/gateway/knowledge/trading/strategies/options/short-synthetic-forward.md new file mode 100644 index 00000000..0a4c71be --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/short-synthetic-forward.md @@ -0,0 +1,32 @@ +--- +description: "A bearish capital-gain strategy buying an ATM put and selling an ATM call at the same strike K = S0, replicating a short forward contract on the underlying." +tags: [options, speculation, bearish, synthetic] +--- + +# Short Synthetic Forward + +**Section**: 2.11 | **Asset Class**: Options | **Type**: Speculation + +## Overview +The short synthetic forward amounts to buying an ATM put option and selling an ATM call option with the same strike K = S0. This can be a net debit or net credit trade; typically |H| << S0. The trader's outlook is bearish: this strategy mimics a short stock or futures position and replicates a short forward contract with delivery price K and the same maturity as the options. This is a capital gain strategy. + +## Construction +- Buy 1 ATM put option at strike K = S0 +- Sell 1 ATM call option at strike K = S0, same expiry + +Net debit or credit H (H = D for net debit trade, H = -C for net credit trade) + +## Payoff Profile +f_T = (K - S_T)+ - (S_T - K)+ - H = K - S_T - H + +- Breakeven: S* = K - H +- Max profit: P_max = K - H (if stock goes to zero) +- Max loss: L_max = unlimited (stock can rise without bound) + +## Key Conditions / Signals +- Strongly bearish outlook seeking full participation in downside +- Useful when short-selling the stock directly is restricted or costly +- Typically near-zero net premium (H is small relative to S0) + +## Notes +The payoff is linear in S_T — identical to short stock (minus K - H). The upside is not limited; the position loses as the stock rises above K, just like a short stock position. diff --git a/gateway/knowledge/trading/strategies/options/strap.md b/gateway/knowledge/trading/strategies/options/strap.md new file mode 100644 index 00000000..b3a451ff --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/strap.md @@ -0,0 +1,33 @@ +--- +description: "A bullish volatility strategy buying two ATM calls and one ATM put at strike K, profiting more from an upward move than a downward move of equal magnitude." +tags: [options, volatility, bullish, strap] +--- + +# Strap + +**Section**: 2.34 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The strap is a volatility strategy consisting of a long position in two ATM call options and a long position in one ATM put option with strike K. This is a net debit trade. The trader's outlook is bullish (skewed toward upside). This is a capital gain strategy that profits from a large move in either direction but gains more from an upward move. + +## Construction +- Buy 2 ATM call options at strike K +- Buy 1 ATM put option at strike K, same expiry + +Net debit: D + +## Payoff Profile +f_T = 2 × (S_T - K)+ + (K - S_T)+ - D + +- Upper breakeven: S*_up = K + D/2 +- Lower breakeven: S*_down = K - D +- Max profit: P_max = unlimited (especially strong on upside due to 2 calls) +- Max loss: L_max = D (if S_T = K at expiry) + +## Key Conditions / Signals +- Bullish but uncertain of direction; expects a large move with upside bias +- Low implied volatility environment is ideal (cheaper debit to enter) +- The upper breakeven (D/2 above K) is closer to K than the lower breakeven (D below K) + +## Notes +The strap is a modified straddle with bullish skew: two calls vs. one put. The upside potential is doubled relative to the downside (per unit of move). Maximum loss is capped at the net debit D. diff --git a/gateway/knowledge/trading/strategies/options/strip.md b/gateway/knowledge/trading/strategies/options/strip.md new file mode 100644 index 00000000..b29f24b3 --- /dev/null +++ b/gateway/knowledge/trading/strategies/options/strip.md @@ -0,0 +1,33 @@ +--- +description: "A bearish volatility strategy buying one ATM call and two ATM puts at strike K, profiting more from a downward move than an upward move of equal magnitude." +tags: [options, volatility, bearish, strip] +--- + +# Strip + +**Section**: 2.35 | **Asset Class**: Options | **Type**: Volatility + +## Overview +The strip is a volatility strategy consisting of a long position in one ATM call option and a long position in two ATM put options with strike K. This is a net debit trade. The trader's outlook is bearish (skewed toward downside). This is a capital gain strategy that profits from a large move in either direction but gains more from a downward move. + +## Construction +- Buy 1 ATM call option at strike K +- Buy 2 ATM put options at strike K, same expiry + +Net debit: D + +## Payoff Profile +f_T = (S_T - K)+ + 2 × (K - S_T)+ - D + +- Upper breakeven: S*_up = K + D +- Lower breakeven: S*_down = K - D/2 +- Max profit: P_max = unlimited (especially strong on downside due to 2 puts) +- Max loss: L_max = D (if S_T = K at expiry) + +## Key Conditions / Signals +- Bearish but uncertain of direction; expects a large move with downside bias +- Low implied volatility environment is ideal (cheaper debit to enter) +- The lower breakeven (D/2 below K) is closer to K than the upper breakeven (D above K) + +## Notes +The strip is a modified straddle with bearish skew: two puts vs. one call. The downside potential is doubled relative to the upside (per unit of move). Maximum loss is capped at the net debit D. diff --git a/gateway/knowledge/trading/strategies/real-estate/fix-and-flip.md b/gateway/knowledge/trading/strategies/real-estate/fix-and-flip.md new file mode 100644 index 00000000..10bbd5c0 --- /dev/null +++ b/gateway/knowledge/trading/strategies/real-estate/fix-and-flip.md @@ -0,0 +1,54 @@ +--- +description: "Purchase a distressed property at a substantial discount below market value, renovate it, and resell at a price sufficient to cover renovation costs and generate a profit." +tags: [real-estate, value, short-term] +--- + +# Fix-and-Flip + +**Section**: 16.6 | **Asset Class**: Real Estate | **Type**: Value / Short-Term + +## Overview +A short-term real estate investment strategy. The investor purchases a property that is typically in a distressed condition and requires renovations, at a substantial discount below market prices. After renovating the property, the investor resells it at a price high enough to cover the renovation costs and make a profit. Unlike most real estate strategies, this is explicitly short-term and transactional rather than buy-and-hold. + +## Construction / Mechanics +The basic P&L structure is: + +``` +Profit = P_sell - P_buy - C_renovation - C_carry - C_transaction +``` + +- `P_buy` = purchase price (substantially below market value; property is in distressed condition) +- `C_renovation` = total cost of renovations (labor, materials, permits) +- `C_carry` = holding costs during renovation (financing costs, property taxes, insurance, utilities) +- `C_transaction` = transaction costs on both buy and sell (agent commissions, closing costs, transfer taxes) +- `P_sell` = resale price (must exceed all costs for the trade to be profitable) + +Key requirement: `P_buy` must be sufficiently discounted relative to `P_sell` (post-renovation market value) to cover all renovation and carry costs with margin for profit. + +## Return Profile +Returns are driven by three sources: +1. **Discount at acquisition**: buying below market value due to the distressed condition +2. **Value-add from renovation**: the increase in market value attributable to improvements exceeding renovation costs +3. **Market appreciation**: any general price appreciation in the local market during the renovation period (this is incidental and uncontrolled) + +The strategy is short-term (typically 3–12 months per project) and highly transactional. Returns per project can be high in percentage terms but are concentrated in execution risk. + +## Key Parameters / Signals +- **After-repair value (ARV)**: estimated market value of the property after renovation; the primary target price signal +- **Acquisition discount**: the percentage below estimated ARV at which the property is purchased; must be large enough to cover all costs plus profit margin +- **Renovation cost estimate**: accuracy is critical; cost overruns are a primary risk; experienced contractors and detailed scope-of-work essential +- **Days on market / local market conditions**: the resale market must have sufficient demand to sell within the planned timeline; holding period overruns increase carry cost +- **Financing cost**: if leveraged, the interest rate and origination fees on the bridge/hard-money loan directly impact profitability + +## Variations +- **Wholesale flip**: assign the purchase contract to another investor for a fee without performing the renovation (lower return, zero renovation risk) +- **BRRRR (Buy, Rehab, Rent, Refinance, Repeat)**: renovate and then hold as a rental property rather than selling; transition to a buy-and-hold strategy post-renovation +- **Commercial fix-and-flip**: apply the same concept to commercial properties (offices, retail, industrial); higher deal sizes, longer timelines, more complex renovations + +## Notes +- Execution risk is the primary risk: renovation cost overruns, contractor delays, and permitting issues can eliminate the profit margin +- Market timing risk: if the local market declines during the renovation period, `P_sell` may be insufficient to recover costs +- Liquidity risk: if the renovated property does not sell quickly, carry costs accumulate and erode returns; a forced discount sale may be needed +- Financing: fix-and-flip projects typically use hard money loans or bridge loans at high interest rates (8–12%+); cost of capital is a significant factor +- Requires local market expertise, contractor relationships, and permit/code knowledge; not scalable without operational infrastructure +- Tax treatment: profits from fix-and-flip are typically taxed as ordinary income (not capital gains) if the property is held for less than one year diff --git a/gateway/knowledge/trading/strategies/real-estate/inflation-hedging.md b/gateway/knowledge/trading/strategies/real-estate/inflation-hedging.md new file mode 100644 index 00000000..a5f08f33 --- /dev/null +++ b/gateway/knowledge/trading/strategies/real-estate/inflation-hedging.md @@ -0,0 +1,53 @@ +--- +description: "Hold real estate assets as an inflation hedge, exploiting the empirically strong relationship between real estate returns and inflation, with commercial real estate providing a faster and more effective hedge than residential." +tags: [real-estate, inflation, hedging] +--- + +# Inflation Hedging with Real Estate + +**Section**: 16.5 | **Asset Class**: Real Estate | **Type**: Hedging / Inflation Protection + +## Overview +Empirical studies suggest a strong positive relationship between real estate returns and the inflation rate, making real estate a natural hedge against inflation. The intuition is that rising prices inflate both property values and rental income, preserving real wealth. Commercial real estate tends to adjust faster to inflationary price increases than residential real estate and therefore provides a better inflation hedge, though this can depend on the sample, market, and time period studied. + +## Construction / Mechanics +The strategy holds real estate assets (direct property or via REITs) as a component of a broader portfolio with the explicit goal of hedging inflation exposure. Return is measured as: + +``` +R(t_1, t_2) = [P(t_2) + C(t_1, t_2)] / P(t_1) - 1 (520) +``` + +The inflation-hedging effectiveness is measured empirically by regressing real estate returns against realized inflation: + +``` +R_RE = α + β × π + ε +``` + +A higher `β` (beta to inflation) indicates a better inflation hedge. Commercial real estate tends to have a higher `β` than residential real estate. + +**Implementation vehicles** (in order of increasing liquidity): +1. Direct property ownership (commercial or residential) +2. Private real estate funds / unlisted REITs +3. Listed REITs (exchange-traded) +4. Real estate futures and options + +## Return Profile +Returns track inflation over the medium-to-long term. In high-inflation periods, property values and rents rise, generating capital gains and higher income. In low-inflation or deflationary environments, the strategy may underperform relative to nominal bonds. The hedge is imperfect in the short term but strengthens over longer holding periods. + +## Key Parameters / Signals +- **Inflation beta `β`**: the core measure of hedging effectiveness; estimated from historical return series; higher for commercial property than residential in most studies +- **Property type**: commercial real estate (offices, shopping centers, industrial) adjusts faster to inflation than residential +- **Holding period**: the inflation hedge improves at longer horizons; short-term real estate returns can be dominated by idiosyncratic or financial-cycle factors +- **Allocation size**: larger real estate allocation provides stronger inflation protection but increases illiquidity and concentration risk + +## Variations +- **Commercial-focused portfolio**: overweight commercial real estate for stronger inflation sensitivity +- **REIT-based inflation hedge**: use listed REITs for liquid, exchange-traded inflation exposure; note that short-term REIT returns are more correlated with equity markets and may not hedge inflation as effectively as direct property +- **Combined with TIPS**: use real estate alongside TIPS (see Section 14.2) for a comprehensive inflation-protection portfolio + +## Notes +- The inflation-hedging property of real estate is empirically documented but varies across time periods, markets, and property types; it should not be assumed to be constant +- Short-term real estate returns can be negatively correlated with inflation during monetary tightening cycles (rising interest rates hurt property valuations) +- Leverage (common in real estate) amplifies both the inflation hedge and the interest rate sensitivity; rising rates in inflationary environments can partially offset the inflation benefit +- REITs traded on exchanges exhibit higher short-term equity market correlation; the inflation hedge is stronger for direct property +- Commercial real estate leases often include CPI escalation clauses, making the cash flow component of returns directly inflation-linked diff --git a/gateway/knowledge/trading/strategies/real-estate/intra-asset-diversification.md b/gateway/knowledge/trading/strategies/real-estate/intra-asset-diversification.md new file mode 100644 index 00000000..99bebd82 --- /dev/null +++ b/gateway/knowledge/trading/strategies/real-estate/intra-asset-diversification.md @@ -0,0 +1,40 @@ +--- +description: "Diversify a real estate portfolio across property types, economic regions, and geographic areas to reduce non-systematic risk, using standard portfolio construction techniques to determine allocations." +tags: [real-estate, diversification, portfolio-construction] +--- + +# Intra-Asset Diversification within Real Estate + +**Section**: 16.3 | **Asset Class**: Real Estate | **Type**: Diversification / Portfolio Construction + +## Overview +While Section 16.2 addresses diversifying a multi-asset portfolio by adding real estate, this strategy addresses diversification within the real estate allocation itself. Real estate holdings can be diversified by geographic area, property type, property size, proximity to a metropolitan area, economic region, and other characteristics. Standard portfolio construction techniques determine the optimal allocation across these dimensions. + +## Construction / Mechanics +Standard portfolio construction techniques (mean-variance optimization, VAR models — as described in Section 16.2) are applied within the real estate asset class to determine allocations across the dimensions below. + +## Return Profile +By diversifying across property types and economic regions, non-systematic (idiosyncratic) risks specific to a single property type or local economy are reduced. Systematic (market-wide) real estate risk cannot be diversified away within the asset class. Returns come from the same two sources as any real estate investment: income (rental yield) and price appreciation, but are smoothed across multiple sub-segments. + +## Key Parameters / Signals +- **Correlation matrix across property types and regions**: the primary input for MVO; diversification benefit is higher when correlations are lower +- **Transaction costs**: diversification across many property types and regions increases transaction costs; empirical studies show benefits after taking these into account +- **Number of segments**: with four property types × four U.S. regions = 16 groups (property-type-and-geographic diversification variant) + +## Variations + +### 16.3.1 Property Type Diversification +Invest in real estate assets of different types: apartments, offices, industrial properties (manufacturing buildings and property), shopping centers, etc. Empirical studies suggest that property type diversification can be beneficial for non-systematic risk reduction even after accounting for transaction costs. + +### 16.3.2 Economic Diversification +Diversify real estate investments by economic regions defined by characteristics such as the main economic activity, employment statistics, and average income. Regions with different economic drivers have lower return correlations. Empirical studies suggest this can reduce non-systematic risk and transaction costs relative to a naive geographic split. + +### 16.3.3 Property Type and Geographic Diversification +Combine diversification by both property type and geographic region. For example, with four property types (office, retail, industrial, residential) and four U.S. regions (East, Midwest, South, West), there are 16 groups across which to diversify. This combined approach captures both property-type and regional diversification benefits simultaneously. + +## Notes +- Intra-real-estate diversification still leaves the portfolio exposed to the systematic real estate cycle (house price bubbles, credit cycles, etc.) +- Minimum lot sizes for direct real estate investment limit how finely diversification can be achieved; REITs reduce this constraint +- Transaction costs in real estate are high; over-diversification into too many small positions can destroy returns through transaction costs alone +- Economic region classification can be dynamic; regions that were economically distinct may converge over time, reducing diversification benefit +- Property type correlations are not stable; they increase significantly during real estate downturns diff --git a/gateway/knowledge/trading/strategies/real-estate/mixed-asset-diversification.md b/gateway/knowledge/trading/strategies/real-estate/mixed-asset-diversification.md new file mode 100644 index 00000000..8a86aa33 --- /dev/null +++ b/gateway/knowledge/trading/strategies/real-estate/mixed-asset-diversification.md @@ -0,0 +1,47 @@ +--- +description: "Add real estate assets to a traditional portfolio of stocks and bonds to improve risk-adjusted returns, exploiting real estate's persistently low and stable correlation with traditional asset classes." +tags: [real-estate, diversification, portfolio-construction, multi-asset] +--- + +# Mixed-Asset Diversification with Real Estate + +**Section**: 16.2 | **Asset Class**: Real Estate | **Type**: Diversification / Portfolio Construction + +## Overview +Real estate assets are attractive diversification tools because their correlation with traditional assets (bonds and stocks) is low and remains low even through extreme market events such as financial crises. This low correlation is persistent even at long time horizons (where correlations between traditional assets tend to increase). Long-term investors can improve portfolio risk-adjusted returns by including real estate assets alongside equities and fixed income. + +## Construction / Mechanics +The strategy buys and holds real estate assets (directly or via REITs) within a traditional portfolio containing bonds and equities. Return measurement: + +``` +R(t_1, t_2) = [P(t_2) + C(t_1, t_2)] / P(t_1) - 1 (520) +``` + +- `R(t_1, t_2)` = return from beginning `t_1` to end `t_2` of the holding period +- `P(t_1)`, `P(t_2)` = market values of the property at `t_1` and `t_2` +- `C(t_1, t_2)` = net cash flows received (rents, etc.) over the holding period, net of costs + +**Optimal allocation techniques**: +- **Mean-variance optimization (MVO)**: classic Markowitz framework; solve for allocation conditional on time horizon and risk/return preferences +- **Vector autoregressive model (VAR)**: models dynamic relationships between asset class returns over time; computes optimal allocation conditional on the horizon and desired performance characteristics + +## Return Profile +Returns from real estate have two components: price appreciation (`P(t_2)/P(t_1) - 1`) and income return (`C(t_1, t_2)/P(t_1)`). The income return (rental yield) provides steady cash flows; price appreciation is cyclical and tied to macroeconomic conditions. The diversification benefit means adding real estate can reduce total portfolio volatility while maintaining or improving expected return. + +## Key Parameters / Signals +- **Correlation with equities and bonds**: the core diversification driver; should be estimated on the relevant time horizon +- **Investment horizon**: the diversification benefit is larger at longer horizons; short-term correlations can spike in crises +- **Optimal allocation weight**: varies with investor preferences (risk aversion, return target) and the horizon; determined via MVO or VAR +- **Real estate vehicle**: direct property vs. REITs (liquid, exchange-traded, but may have higher short-term correlation with equities) + +## Variations +- **Direct property**: lower liquidity, lower short-term correlation with equities; appropriate for long-term institutional investors +- **REIT-based**: liquid, exchange-traded; provides real estate exposure with equity-like tradability but higher short-term equity correlation +- **Global real estate**: extend diversification internationally; additional currency and geopolitical risk + +## Notes +- Real estate is illiquid (for direct ownership); transaction costs (brokerage, taxes, closing costs) are high relative to financial assets +- Appraisal-based indexes for direct real estate are smoothed and understate true volatility; REIT-based returns are more representative of market volatility +- REITs tend to trade on exchanges and may exhibit higher correlation with the broader equity market, especially in the short term, reducing the diversification benefit +- Leverage is common in real estate; the return formula (520) applies to unlevered returns; levered returns amplify both gains and losses +- The VAR approach requires a sufficiently long time series for reliable parameter estimation diff --git a/gateway/knowledge/trading/strategies/real-estate/momentum-regional.md b/gateway/knowledge/trading/strategies/real-estate/momentum-regional.md new file mode 100644 index 00000000..1a3ef6f6 --- /dev/null +++ b/gateway/knowledge/trading/strategies/real-estate/momentum-regional.md @@ -0,0 +1,42 @@ +--- +description: "Buy real estate properties or REITs in metropolitan statistical areas (MSAs) with high past returns and sell those with low past returns, exploiting empirical momentum effects across U.S. regional real estate markets." +tags: [real-estate, momentum, regional] +--- + +# Real Estate Momentum — Regional Approach + +**Section**: 16.4 | **Asset Class**: Real Estate | **Type**: Momentum + +## Overview +This strategy exploits empirical evidence that there is a momentum effect across U.S. metropolitan statistical areas (MSAs): areas with higher past returns tend to continue delivering higher returns in the future, and areas with lower past returns tend to continue delivering lower returns. The strategy buys real estate in high-momentum MSAs and sells (or avoids / shorts via REITs) in low-momentum MSAs. + +## Construction / Mechanics +1. **Measure past returns** for each MSA over a lookback period +2. **Rank MSAs** by past return (momentum signal) +3. **Long** top-ranked MSAs (buy real estate or REITs/futures on housing indexes for those regions) +4. **Short** bottom-ranked MSAs (sell/short REITs or futures on U.S. housing indexes for those regions) + +For a **zero-cost strategy**, use alternative real estate investment vehicles: +- REITs (exchange-traded, geographic focus) +- Futures and options on U.S. housing indexes (e.g., CME S&P/Case-Shiller Home Price Index futures) based on different geographical areas + +## Return Profile +Profits when the return spread between high-momentum and low-momentum MSAs persists into the future. The strategy captures the serial autocorrelation in regional real estate returns. Returns are driven by macroeconomic factors (local employment, population growth, housing supply constraints) that tend to persist over medium-term horizons. + +## Key Parameters / Signals +- **Lookback period**: the historical window for measuring past returns (typically 1–3 years for real estate, given its lower turnover and slower price discovery) +- **MSA selection**: number of MSAs in the long and short legs; broader MSA coverage increases diversification +- **Implementation vehicle**: direct property (illiquid, high transaction costs), REITs (liquid, but less geographically precise), or housing index futures/options (liquid, zero-cost portfolio feasible) +- **Rebalancing frequency**: determined by liquidity of the implementation vehicle; REITs allow more frequent rebalancing than direct property + +## Variations +- **REIT-based momentum**: use geographically focused REITs as proxies for MSA-level real estate; allows exchange-traded implementation and short selling +- **Housing index futures**: use CME futures on S&P/Case-Shiller Home Price Indexes for specific U.S. cities/regions to construct a zero-cost momentum portfolio +- **Combined property-type and regional momentum**: apply momentum within each property type × region segment + +## Notes +- Real estate momentum is slower-moving than equity momentum; the lookback and holding periods are typically longer +- Transaction costs for direct real estate are prohibitive for frequent rebalancing; vehicle selection (REIT, futures) is critical for practical implementation +- Momentum in real estate is partly driven by supply rigidity (permitting lags, construction time) and demand inertia (migration, employment trends) +- Reversal risk: overheated MSAs can experience sharp price corrections; the strategy has exposure to regional housing bubbles +- Correlation between regional REITs and local housing markets is imperfect; basis risk exists between the REIT price and the underlying physical real estate prices diff --git a/gateway/knowledge/trading/strategies/stocks/alpha-combos.md b/gateway/knowledge/trading/strategies/stocks/alpha-combos.md new file mode 100644 index 00000000..5eec1705 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/alpha-combos.md @@ -0,0 +1,74 @@ +--- +description: "Combines hundreds of thousands of weak individual alpha signals into a single tradeable mega-alpha by optimizing combination weights using a structured 11-step procedure based on demeaned returns and regression residuals." +tags: [stocks, machine-learning, alpha-combination, quantitative] +--- + +# Alpha Combos + +**Section**: 3.20 | **Asset Class**: Stocks | **Type**: Machine Learning / Quantitative / Alpha Combination + +## Overview +Alpha combo strategies combine a large number of weak quantitative trading signals ("alphas") into a single tradeable "mega-alpha" portfolio. Each individual alpha is too faint to trade profitably on its own after costs, but a sufficiently large combination can generate a viable signal. The combination weights are optimized using a structured procedure that handles serial correlation, cross-sectional demeaning, and risk normalization. + +## Construction / Signal +Assume N alphas (possibly hundreds of thousands), all trading the same universe of ~2,500 liquid U.S. stocks. Each alpha produces desired stock holdings at a sequence of times t_1, t_2, .... The procedure for fixing combination weights w_i [Kakushadze and Yu, 2017b]: + +1. Start with time series of realized alpha returns `R_is`, i=1,...,N, s=1,...,M+1. +2. Calculate serially demeaned returns: + ``` + X_is = R_is - (1/(M+1)) * sum_{s=1}^{M+1} R_is + ``` +3. Calculate sample variances of alpha returns: + ``` + sigma_i^2 = (1/M) * sum_{s=1}^{M+1} X_is^2 + ``` +4. Calculate normalized demeaned returns: + ``` + Y_is = X_is / sigma_i + ``` +5. Keep only the first M columns: Y_is, s=1,...,M. +6. Cross-sectionally demean Y_is: + ``` + Lambda_is = Y_is - (1/N) * sum_{j=1}^{N} Y_js + ``` +7. Keep only the first M-1 columns: Lambda_is, s=1,...,M-1. +8. Compute expected alpha returns E_i and normalize: + ``` + E_i = (1/d) * sum_{s=1}^{d} R_is (360) + E_tilde_i = E_i / sigma_i + ``` + (d-day moving average; d need not equal T) +9. Calculate residuals `epsilon_tilde_i` of regression (no intercept, unit weights) of `E_tilde_i` over `Lambda_is`. +10. Set alpha portfolio weights: + ``` + w_i = eta * epsilon_tilde_i / sigma_i + ``` +11. Set normalization coefficient eta such that: + ``` + sum_{i=1}^{N} |w_i| = 1 + ``` + +## Entry / Exit Rules +- **Entry**: At each rebalance time, recompute combination weights w_i using the 11-step procedure and establish positions accordingly. +- **Exit**: Positions are updated at each rebalance; individual alpha positions change according to the alpha's own signals, and the overall mega-alpha weight adjusts. +- **Holding period**: Determined by individual alpha holding periods (typically daily, from close to close). + +## Key Parameters +- **Number of alphas N**: Can be hundreds of thousands or millions +- **Return history M+1**: Number of time periods used for variance estimation +- **Expected return window d**: Number of days for moving average of alpha returns (Eq. 360; d need not equal M) +- **Universe**: Typically ~2,500 most liquid U.S. stocks +- **Alpha returns R_is**: Daily alpha returns from close to close + +## Variations +- **Fewer alphas**: The procedure scales from a few dozen to millions of alphas +- **Different expected return estimator**: Instead of d-day moving average, other estimators for E_i can be used +- **Multiple universes**: Extend to different stock universes or asset classes + +## Notes +- Individual alphas are "ubiquitous, faint, and ephemeral" — their signal is too weak to trade profitably alone due to transaction costs. +- The 11-step procedure handles: serial correlation (steps 1-2), scale normalization (steps 3-4), cross-sectional neutrality (steps 5-7), expected return estimation (step 8), residualization (step 9), and final weight normalization (steps 10-11). +- "Alpha" here follows the practitioner definition: any reasonable expected return signal, not necessarily Jensen's alpha. +- 101 explicit examples of such quantitative alphas are given in Kakushadze (2016). +- This is a cross-sectional multi-stock strategy requiring significant data infrastructure. +- Typical holding period: daily (overnight or close-to-close). diff --git a/gateway/knowledge/trading/strategies/stocks/channel.md b/gateway/knowledge/trading/strategies/stocks/channel.md new file mode 100644 index 00000000..32ce2b4a --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/channel.md @@ -0,0 +1,60 @@ +--- +description: "Buys at the channel floor and shorts at the ceiling (mean-reversion), or follows breakouts through channel boundaries (trend-following), using a Donchian Channel defined by T-period price extremes." +tags: [stocks, technical-analysis, channel, donchian, trend-following, mean-reversion] +--- + +# Channel + +**Section**: 3.15 | **Asset Class**: Stocks | **Type**: Technical Analysis (Mean-Reversion or Trend-Following) + +## Overview +A channel (band) strategy uses a price range bounded by a ceiling and a floor within which the stock price fluctuates. The most common definition is the Donchian Channel, where the ceiling is the T-period maximum price and the floor is the T-period minimum price. The trader can either fade moves to the channel extremes (mean-reversion) or follow breakouts through channel boundaries (trend-following). + +## Construction / Signal +**Donchian Channel** (Donchian, 1960): + +``` +B_up = max(P(1), P(2), ..., P(T)) (329) +B_down = min(P(1), P(2), ..., P(T)) (330) +``` + +where P(t) is the stock price, t=1 is the most recent day, and T is the channel lookback period. + +**Mean-reversion signal** (fade the extremes): +``` +Signal = { Establish long / liquidate short if P = B_down + { Establish short / liquidate long if P = B_up (331) +``` + +The expectation is that if the price touches the floor or ceiling, it will bounce back toward the center of the channel. + +**Trend-following variant**: If the price breaks through B_up (ceiling), the trader may interpret this as the start of a new uptrend and go long instead of shorting; if it breaks through B_down, go short. + +## Entry / Exit Rules +**Mean-reversion mode**: +- **Long entry**: Price reaches channel floor B_down. +- **Short entry**: Price reaches channel ceiling B_up. +- **Exit**: Close when price moves toward the center, or at a fixed time horizon. + +**Trend-following mode (breakout)**: +- **Long entry**: Price breaks above B_up (new trend upward). +- **Short entry**: Price breaks below B_down (new trend downward). +- **Exit**: Wait for channel break in the opposite direction. + +## Key Parameters +- **Channel period T**: Number of trading days for computing the min/max (typically 10–55 days) +- **Channel width**: Wider channels (longer T) reflect higher volatility; narrower channels = tighter bands +- **Mode**: Mean-reversion (fade) vs. trend-following (breakout) +- **Volume confirmation**: Signal robustness improves when price extremes coincide with increased traded volume + +## Variations +- **With volume filter**: Signal is more robust when a price reversal or breakout occurs alongside increased traded volume +- **Bollinger Bands**: Channel defined by moving average ± N standard deviations (alternative to fixed min/max) +- **Keltner Channels**: MA ± N * ATR (average true range) + +## Notes +- The wider the channel, the higher the implied volatility of the underlying stock. +- The channel indicator is typically used together with other signals (e.g., volume) rather than in isolation. +- Mean-reversion mode assumes the price will bounce off extremes; trend-following mode assumes a breakout signals a new trend. +- The strategy can be applied single-stock or across a universe; with a large universe, near-dollar-neutral portfolios are possible. +- Donchian Channels are a classic component of the "Turtle Trading" trend-following system. diff --git a/gateway/knowledge/trading/strategies/stocks/earnings-momentum.md b/gateway/knowledge/trading/strategies/stocks/earnings-momentum.md new file mode 100644 index 00000000..0c02eb5e --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/earnings-momentum.md @@ -0,0 +1,46 @@ +--- +description: "Ranks stocks by standardized unexpected earnings (SUE) and buys high-SUE winners while shorting low-SUE losers, capturing post-earnings announcement drift." +tags: [stocks, momentum, earnings] +--- + +# Earnings-Momentum + +**Section**: 3.2 | **Asset Class**: Stocks | **Type**: Momentum + +## Overview +Earnings-momentum is structurally the same as price-momentum — buying winners and selling losers — but the selection criterion is based on earnings surprises rather than price returns. Stocks that beat earnings expectations tend to continue outperforming, while those that miss tend to continue underperforming (post-earnings announcement drift, PEAD). + +## Construction / Signal +The primary signal is the Standardized Unexpected Earnings (SUE) [Chan, Jegadeesh and Lakonishok, 1996]: + +``` +SUE_i = (E_i - E_i') / sigma_i (274) +``` + +Where: +- `E_i` = most recently announced quarterly earnings per share for stock `i` +- `E_i'` = earnings per share announced 4 quarters ago (same-quarter prior year) +- `sigma_i` = standard deviation of the unexpected earnings `(E_i - E_i')` over the last 8 quarters + +Stocks are sorted by `SUE_i` in descending order. + +## Entry / Exit Rules +- **Entry**: Buy stocks in the top decile by SUE; short stocks in the bottom decile by SUE. Construct as a dollar-neutral portfolio. +- **Exit**: Typically hold for 6 months (holding period typically 1–6 months); diminishing returns beyond 6 months. +- **Rebalance**: Quarterly, coinciding with earnings announcement cycles. + +## Key Parameters +- **SUE lookback for sigma**: 8 quarters +- **Comparison period**: 4 quarters prior (same-season comparison) +- **Holding period**: Typically 6 months +- **Portfolio construction**: Dollar-neutral long/short decile portfolio + +## Variations +- Alternative unexpected earnings definitions (analyst consensus vs. same-quarter-prior-year) +- Combining SUE with price-momentum for a blended signal + +## Notes +- Typical holding period is 6 months; diminishing returns for longer holds. +- PEAD is one of the most robust anomalies in the literature but can be reduced by trading costs given earnings are released quarterly. +- The strategy is exposed to earnings announcement timing and may require frequent universe refreshes. +- Can be combined with price-momentum strategies (see Section 3.6 Multifactor Portfolio). diff --git a/gateway/knowledge/trading/strategies/stocks/event-driven-ma.md b/gateway/knowledge/trading/strategies/stocks/event-driven-ma.md new file mode 100644 index 00000000..89e12ece --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/event-driven-ma.md @@ -0,0 +1,50 @@ +--- +description: "Captures excess returns from merger arbitrage (M&A) by taking long positions in target company stock and, for stock mergers, short positions in the acquirer, exploiting the spread between current and deal prices." +tags: [stocks, event-driven, merger-arbitrage, risk-arbitrage] +--- + +# Event-Driven — M&A + +**Section**: 3.16 | **Asset Class**: Stocks | **Type**: Event-Driven / Arbitrage + +## Overview +This strategy, also known as "merger arbitrage" or "risk arbitrage", attempts to capture excess returns generated via corporate actions such as mergers and acquisitions (M&A). When one publicly traded company announces the acquisition of another, a spread typically exists between the target's current market price and the proposed deal price. The trader seeks to profit from this spread closing at deal completion. + +## Construction / Signal +A merger arbitrage opportunity arises when a publicly traded acquirer announces intent to buy a publicly traded target at a price differing from the target's current market price. Two main transaction types: + +**Cash merger**: +- Trader establishes a **long position in the target company stock** only. +- Profit = (deal price − current target price) if the deal closes. + +**Stock merger**: +- Acquirer offers N_B shares of acquirer stock B for each share of target stock A. +- Trader **buys 1 share of target A** and **shorts N_B shares of acquirer B**. +- Example: Current price of A = $67, current price of B = $35, exchange ratio = 2 shares of B per share of A. + - Initial net credit = 2 × $35 − $67 = $3 per share of A bought. + - This $3 is the profit if the deal closes. + - If the deal falls through, the trader will likely lose money. + +## Entry / Exit Rules +- **Entry**: After public announcement of a merger/acquisition deal, establish the arbitrage position (long target, short acquirer for stock mergers). +- **Exit — deal closes**: Positions are settled at deal terms; long position in target delivers the deal price; the profit is locked in. +- **Exit — deal breaks**: Close positions at market prices; the spread typically widens sharply on deal failure, resulting in a loss. +- **Stop-loss**: Discretionary; deal-break risk is the primary risk. + +## Key Parameters +- **Deal spread**: Difference between current target price and proposed deal price (or equivalent in stock merger terms) +- **Exchange ratio (stock mergers)**: Number of acquirer shares per target share +- **Merger type**: Cash vs. stock merger (determines position structure) +- **Holding period**: Duration from announcement to deal close (weeks to months) + +## Variations +- **Long-only (cash merger)**: Buy target only; no short leg. +- **Dollar-neutral (stock merger)**: Long target, short acquirer in ratio given by deal terms. +- **Index of deals**: Construct a diversified portfolio across multiple live merger situations simultaneously to reduce single-deal risk. + +## Notes +- The primary risk is "deal break risk": if the merger falls through (regulatory rejection, board change, financing failure), the trader typically suffers a loss as the target price drops back toward pre-announcement levels. +- Expected return = (spread × probability of deal close) − (loss on deal break × probability of break). +- Transaction costs and financing costs for short positions reduce profitability. +- Holding period depends on deal timeline: typically weeks to several months. +- This strategy requires monitoring deal-specific news (regulatory filings, shareholder votes, competing bids). diff --git a/gateway/knowledge/trading/strategies/stocks/implied-volatility.md b/gateway/knowledge/trading/strategies/stocks/implied-volatility.md new file mode 100644 index 00000000..7113964a --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/implied-volatility.md @@ -0,0 +1,45 @@ +--- +description: "Buys stocks with the largest monthly increases in call implied volatility and shorts stocks with the largest increases in put implied volatility, exploiting the options market's directional information." +tags: [stocks, implied-volatility, options-based] +--- + +# Implied Volatility + +**Section**: 3.5 | **Asset Class**: Stocks | **Type**: Options-Based / Signal + +## Overview +This strategy is based on the empirical observation that stocks with larger increases in call implied volatilities over the previous month have higher average future returns, while stocks with larger increases in put implied volatilities over the previous month have lower average future returns. The options market contains forward-looking information about stock direction that can be exploited cross-sectionally. + +## Construction / Signal +The signal is the monthly change in implied volatility for calls and puts separately: + +- **Call IV change**: `Delta_call_IV_i` = change in call implied volatility for stock `i` over the previous month +- **Put IV change**: `Delta_put_IV_i` = change in put implied volatility for stock `i` over the previous month + +**Primary portfolio construction**: +- Buy stocks in the **top decile** by increase in call implied volatility (large call IV increases → bullish signal) +- Short stocks in the **top decile** by increase in put implied volatility (large put IV increases → bearish signal) +- Dollar-neutral construction. + +## Entry / Exit Rules +- **Entry**: At monthly rebalance, rank stocks by their respective IV change signals and enter positions as described. +- **Exit**: Hold for approximately 1 month before rebalancing. + +## Key Parameters +- **Lookback**: 1 month for IV change computation +- **Holding period**: Typically 1 month +- **Portfolio construction**: Dollar-neutral long/short + +## Variations +- **Difference signal**: Instead of two separate portfolios (long high-call-IV, short high-put-IV), construct a single signal based on the *difference* between the change in call implied volatility and the change in put implied volatility: + ``` + Signal_i = Delta_call_IV_i - Delta_put_IV_i + ``` + Buy top-decile by this difference, short bottom-decile. + +## Notes +- Requires options market data (implied volatility surfaces or at-the-money IV for calls and puts). +- The empirical evidence suggests options markets reflect informed trading that leads equity prices. +- Transaction costs in options markets can be high; the strategy operates on stock positions, not option positions. +- Monthly rebalancing is typical given the 1-month signal horizon. +- Can be combined with other momentum or factor signals in a multifactor framework. diff --git a/gateway/knowledge/trading/strategies/stocks/low-volatility-anomaly.md b/gateway/knowledge/trading/strategies/stocks/low-volatility-anomaly.md new file mode 100644 index 00000000..21030f7f --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/low-volatility-anomaly.md @@ -0,0 +1,42 @@ +--- +description: "Buys low-historical-volatility stocks and shorts high-historical-volatility stocks, exploiting the empirical anomaly that lower-risk stocks deliver higher risk-adjusted returns." +tags: [stocks, low-volatility, anomaly] +--- + +# Low-Volatility Anomaly + +**Section**: 3.4 | **Asset Class**: Stocks | **Type**: Anomaly / Low-Volatility + +## Overview +The low-volatility anomaly is based on the empirical observation that future returns of previously low-return-volatility portfolios outperform those of previously high-return-volatility portfolios. This contradicts the naive expectation that higher-risk assets should yield proportionately higher returns, and is one of the most robust anomalies in empirical finance. + +## Construction / Signal +Historical volatility `sigma_i` is computed from the time series of historical returns (as in the price-momentum formula): + +``` +sigma_i^2 = 1/(T-1) * sum_{t=S}^{S+T-1} (R_i(t) - R_i^mean)^2 (270) +``` + +Stocks are sorted by `sigma_i` in ascending order. A dollar-neutral portfolio is constructed by buying stocks in the **bottom decile** (low volatility) and shorting stocks in the **top decile** (high volatility). + +## Entry / Exit Rules +- **Entry**: Buy bottom-decile stocks by `sigma_i`; short top-decile stocks by `sigma_i`. +- **Exit**: Hold for the defined holding period (similar duration to the lookback window, typically 6–12 months). +- **No skip period required**: Unlike momentum, no skip period is needed. + +## Key Parameters +- **Lookback window**: 6 months (126 trading days) to 1 year (252 trading days) +- **Holding period**: Similar to the lookback window, typically 6 months to 1 year +- **Volatility measure**: Historical realized volatility `sigma_i` (annualized or monthly) +- **Portfolio construction**: Dollar-neutral (long low-vol, short high-vol) + +## Variations +- **Long-only minimum variance**: Buy low-volatility stocks only; used in minimum variance portfolio construction +- **Beta-sorted portfolios**: Sort by market beta instead of (or in addition to) realized volatility + +## Notes +- This anomaly goes counter to standard asset pricing theory (CAPM) which predicts higher risk = higher return. +- Potential explanations include leverage constraints, benchmark hugging by institutional investors, and lottery preference among retail investors. +- The lookback and holding periods are similar in duration (no skip period needed, unlike price-momentum). +- Strategy can be combined with value or momentum factors in a multifactor portfolio (see Section 3.6). +- Low-volatility stocks may cluster in defensive sectors (utilities, consumer staples), creating sector concentration risk. diff --git a/gateway/knowledge/trading/strategies/stocks/market-making.md b/gateway/knowledge/trading/strategies/stocks/market-making.md new file mode 100644 index 00000000..985cab5f --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/market-making.md @@ -0,0 +1,54 @@ +--- +description: "Captures the bid-ask spread by posting passive limit orders at the bid and ask, using short-horizon directional signals to stay on the correct side and avoid adverse selection from informed order flow." +tags: [stocks, market-making, high-frequency, bid-ask-spread] +--- + +# Market-Making + +**Section**: 3.19 | **Asset Class**: Stocks | **Type**: Market-Making / High-Frequency Trading + +## Overview +Market-making captures the bid-ask spread by simultaneously quoting to buy at the bid and sell at the ask. The strategy profits when order flow is uninformed ("dumb"); it loses money when order flow is "smart" (informed/toxic) due to adverse selection. Practical implementations use short-horizon directional signals to stay on the correct side of the market, often augmented by longer-horizon signals to handle adverse selection on individual fills. + +## Construction / Signal +**Simplified rule**: +``` +Rule = { Buy at the bid + { Sell at the ask (359) +``` + +**Practical refinement — short-horizon signal**: Maintain a signal indicating the likely near-term price direction. Place limit orders such that: +- If signal indicates price increase: buy at the bid (stay long side) +- If signal indicates price decrease: sell at the ask (stay short side) + +**Combined short- and long-horizon signal approach**: +- Short-horizon signal: indicates near-term direction; used to route passive vs. aggressive orders. +- Long-horizon signal: provides directional conviction; can justify accepting adverse selection on individual trades if the trade is based on positive expected return from the longer signal. +- If both signals agree: consider aggressive (marketable) order instead of passive limit order to ensure fill. + +## Entry / Exit Rules +- **Entry**: Post limit orders at bid (to buy) or ask (to sell), sized to the desired position. +- **Exit**: The opposite-side limit order fills (completing the round-trip), or a signal change triggers cancellation and replacement of orders. +- **Position limits**: Must be defined; the strategy should not accumulate large directional inventory. +- **Queue priority**: Must be #1 (or near front) in the limit order queue at each price level to ensure fills; this is what makes speed/infrastructure critical. + +## Key Parameters +- **Bid-ask spread**: The primary source of profit per round-trip +- **Signal horizon (short)**: Milliseconds to seconds; used for order placement direction +- **Signal horizon (long)**: Minutes to hours; used to tolerate adverse selection +- **Cents-per-share target**: Realized P&L in cents per total share traded (including both establishing and liquidating trades) +- **Inventory limit**: Maximum tolerated directional position before reducing quotes +- **Speed/latency**: Infrastructure speed is critical for queue position in high-frequency market-making + +## Variations +- **Pure passive**: Only post limit orders; profit entirely from spread capture; maximally exposed to adverse selection +- **Mixed passive + aggressive**: Use longer-horizon signal to occasionally place aggressive (market) orders when signal strength justifies paying the spread +- **Multi-level quoting**: Quote at multiple price levels across the order book + +## Notes +- In a market with mostly uninformed ("dumb") order flow, pure market-making is highly profitable; in a market dominated by informed ("smart") flow, adverse selection erodes all profits. +- Adverse selection: smart order flow tends to arrive when the market is moving against the market-maker's position (e.g., buys come when the price is declining through the bid). +- The "cents-per-share" metric (realized P&L in cents / total shares traded, counting both establishing and liquidating trades) is the standard performance measure. +- High-frequency trading (HFT) infrastructure is key: speed determines queue priority for limit orders, which determines fill probability. +- Long-horizon signal typically has lower Sharpe ratio but higher cents-per-share than the short-horizon signal. +- This strategy is primarily relevant for professional trading operations with direct market access and co-location infrastructure. diff --git a/gateway/knowledge/trading/strategies/stocks/mean-reversion-cluster.md b/gateway/knowledge/trading/strategies/stocks/mean-reversion-cluster.md new file mode 100644 index 00000000..88282845 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/mean-reversion-cluster.md @@ -0,0 +1,97 @@ +--- +description: "Generalizes pairs trading to N>2 historically correlated stocks within a cluster (e.g., an industry), buying underperformers and shorting overperformers relative to the cluster mean." +tags: [stocks, mean-reversion, cluster, statistical-arbitrage] +--- + +# Mean-Reversion — Single Cluster (and Multiple Clusters) + +**Section**: 3.9 / 3.9.1 | **Asset Class**: Stocks | **Type**: Mean-Reversion / Statistical Arbitrage + +## Overview +This strategy generalizes pairs trading to N > 2 stocks that are historically highly correlated — for example, stocks belonging to the same industry or sector. Each stock's return is demeaned relative to the cluster mean, and positions are taken proportional to negative demeaned returns: buy stocks that underperformed the cluster and short stocks that outperformed it. + +## Construction / Signal +Let `R_i = ln(P_i(t_2) / P_i(t_1))` be the log return for stock i in the cluster of N stocks. + +Cluster mean return and demeaned returns: + +``` +R_bar = (1/N) * sum_{i=1}^{N} R_i (293) +R_tilde_i = R_i - R_bar (294) +``` + +Short stocks with positive `R_tilde_i` (outperformers), buy stocks with negative `R_tilde_i` (underperformers). + +**Dollar-neutrality constraints**: + +``` +sum_{i=1}^{N} P_i |Q_i| = I (295) +sum_{i=1}^{N} P_i Q_i = 0 (296) +``` + +A simple prescription for dollar positions `D_i = P_i Q_i` proportional to demeaned returns: + +``` +D_i = -gamma * R_tilde_i (297) +``` + +where `gamma > 0` (short outperformers, buy underperformers). Eq. (296) is automatically satisfied; Eq. (295) fixes gamma: + +``` +gamma = I / sum_{i=1}^{N} |R_tilde_i| (298) +``` + +## Entry / Exit Rules +- **Entry**: Compute demeaned returns over a short measurement window; enter positions D_i = -gamma * R_tilde_i. +- **Exit**: Close when demeaned returns converge back toward zero, or at a predefined time horizon. + +## Key Parameters +- **Cluster definition**: Industry group, sector, or any set of historically correlated stocks +- **Measurement window**: Short-term (days to weeks) for mean-reversion +- **Position sizing**: Dollar-neutral via gamma normalization (Eq. 298) +- **Weights**: Uniform modulus, or non-uniform (e.g., suppressed by volatility) + +## Variations + +### 3.9.1 — Mean-Reversion: Multiple Clusters + +Generalize to K > 1 clusters, where stocks within each cluster are historically highly correlated. Treat clusters independently and combine via linear regression (unified approach). + +Let `Lambda_{iA}` be the N×K binary loadings matrix: `Lambda_{iA} = 1` if stock i belongs to cluster A, else 0. Cluster sizes: `N_A = sum_{i=1}^{N} Lambda_{iA} > 0`, `N = sum_{A=1}^{K} N_A`. + +Run a linear regression of stock returns R_i on Lambda_{iA} (no intercept, unit weights): + +``` +R_i = sum_{A=1}^{K} Lambda_{iA} f_A + epsilon_i (303) +``` + +Regression coefficients (cluster mean returns): + +``` +f = Q^{-1} Lambda^T R, Q = Lambda^T Lambda (304, 305) +Q_{AB} = N_A delta_{AB} (307) +R_bar_A = (1/N_A) sum_{j in J_A} R_j (308) +``` + +Demeaned return (residual) for stock i: + +``` +epsilon_i = R_i - R_bar_{G(i)} = R_tilde_i (309) +``` + +where G(i) is the cluster to which stock i belongs. These residuals are cluster-neutral: + +``` +sum_{i=1}^{N} R_tilde_i Lambda_{iA} = 0, A = 1,...,K (310) +``` + +Also automatically: `sum_{i=1}^{N} R_tilde_i = 0` (dollar-neutral). + +Investments can be allocated uniformly across the K independent cluster strategies. + +## Notes +- The single-cluster strategy (3.9) is the natural generalization of pairs trading to N stocks. +- The multiple-cluster (3.9.1) formulation uses linear regression to compute all cluster means simultaneously in a unified framework. +- The binary loadings matrix Lambda_{iA} ensures each stock belongs to exactly one cluster (no overlap assumed). +- The intercept is automatically included via the constraint that each stock belongs to one cluster (sum_A Lambda_{iA} = 1). +- Mean-reversion strategies work best when stocks are truly co-integrated or highly correlated; sector/industry groupings provide natural clusters. diff --git a/gateway/knowledge/trading/strategies/stocks/mean-reversion-weighted-regression.md b/gateway/knowledge/trading/strategies/stocks/mean-reversion-weighted-regression.md new file mode 100644 index 00000000..e2dec4c6 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/mean-reversion-weighted-regression.md @@ -0,0 +1,60 @@ +--- +description: "Extends cluster mean-reversion to a general loadings matrix with non-binary (continuous) risk factor exposures and regression weights, enabling neutrality to arbitrary factor sets." +tags: [stocks, mean-reversion, weighted-regression, statistical-arbitrage] +--- + +# Mean-Reversion — Weighted Regression + +**Section**: 3.10 | **Asset Class**: Stocks | **Type**: Mean-Reversion / Statistical Arbitrage + +## Overview +This strategy generalizes the cluster mean-reversion approach (Section 3.9) by replacing the binary loadings matrix with a general (possibly non-binary) loadings matrix `Omega_{iA}`. The resulting demeaned returns are orthogonal to all K loadings vectors, providing neutrality to the corresponding risk factors. Non-binary columns can represent industry-neutral, style factor, or principal component exposures. + +## Construction / Signal +The orthogonality condition for the twiddled (demeaned) returns `R_tilde_i` to a general loadings matrix `Omega_{iA}`: + +``` +sum_{i=1}^{N} R_tilde_i Omega_{iA} = 0, A = 1,...,K (313) +``` + +The twiddled returns are the residuals `epsilon_i` of the regression of `R_i` on `Omega_{iA}` with regression weights `z_i`: + +``` +R_tilde = Z epsilon (314) +epsilon = R - Omega Q^{-1} Omega^T Z R (315) +Z = diag(z_i) (316) +Q = Omega^T Z Omega (317) +``` + +When the intercept is included in `Omega_{iA}` (i.e., a linear combination of columns equals the unit N-vector nu), then automatically: + +``` +sum_{i=1}^{N} R_tilde_i = 0 (318) +``` + +(dollar-neutrality is automatic). + +Weights `z_i` can be taken as `z_i = 1/sigma_i^2` where `sigma_i` are historical volatilities (inverse-variance weighting). + +## Entry / Exit Rules +- **Entry**: Compute residuals from the weighted regression; enter positions proportional to `-R_tilde_i` (buy underperformers relative to factor model, short outperformers). +- **Exit**: Close when residuals converge; or at a fixed holding horizon. +- **Dollar-neutrality**: Automatically satisfied if intercept is included in Omega. + +## Key Parameters +- **Loadings matrix Omega_{iA}**: Binary (industry/sector) or non-binary (continuous risk factors, PCA components) +- **Regression weights z_i**: Often `1/sigma_i^2` (inverse variance) or uniform +- **Number of factors K**: At least 1; more factors remove more systematic risk exposures +- **Holding period**: Short-term, matching the mean-reversion horizon + +## Variations +- **Binary Omega (reduces to Section 3.9)**: When Omega is a binary cluster membership matrix, recovers the single-cluster or multi-cluster mean-reversion formula exactly +- **PCA-based Omega**: Use principal components of the return covariance matrix as non-binary columns +- **Style factor neutrality**: Add style factor exposures (value, momentum, size, liquidity, volatility) as columns in Omega + +## Notes +- This is the most general form of the cluster mean-reversion strategy family. +- Non-binary columns in Omega (e.g., industry-based continuous risk factors, or PCA-derived factors) allow neutralization of more complex systematic risks. +- In the zero specific-risk limit (all variance is factor-driven), optimization reduces to weighted regression. +- The choice of Omega and z_i is the key design decision; binary industry/sector classifications are stable out-of-sample; continuous factor exposures require more frequent recalibration. +- Building a reliable loadings matrix Omega is closely related to constructing a risk model (see Kakushadze and Yu references). diff --git a/gateway/knowledge/trading/strategies/stocks/ml-knn.md b/gateway/knowledge/trading/strategies/stocks/ml-knn.md new file mode 100644 index 00000000..a1758c0a --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/ml-knn.md @@ -0,0 +1,85 @@ +--- +description: "Predicts a stock's future T-day cumulative return using the K-nearest-neighbor algorithm on normalized price and volume features, then trades based on the predicted return signal." +tags: [stocks, machine-learning, knn, prediction] +--- + +# Machine Learning — Single-Stock KNN + +**Section**: 3.17 | **Asset Class**: Stocks | **Type**: Machine Learning / Prediction + +## Overview +This single-stock strategy uses the k-nearest-neighbor (KNN) algorithm to predict future cumulative stock returns based on a set of predictor (feature) variables derived from the stock's own price and volume history. For each stock, the model is trained independently using only that stock's data (no cross-sectional information). The predicted return is then used to generate long/short signals. + +## Construction / Signal +**Target variable** — cumulative return over the next T trading days: +``` +Y(t) = P(t-T) / P(t) - 1 (332) +``` +(t ascending corresponds to going back in time; t=0 is today) + +**Predictor variables** (moving averages of volume and price over varying windows T_1, T_2, T_3, ...): +``` +X_1(t) = (1/T_1) * sum_{s=1}^{T_1} V(t+s) (333) [volume MA] +X_2(t) = (1/T_2) * sum_{s=1}^{T_2} P(t+s) (334) [price MA 1] +X_3(t) = (1/T_3) * sum_{s=1}^{T_3} P(t+s) (335) [price MA 2] +... (336) +``` + +Predictor variables are normalized to [0, 1] using the training period's min/max: +``` +X_tilde_a(t) = (X_a(t) - X_a^-) / (X_a^+ - X_a^-) (337) +``` +where `X_a^+` and `X_a^-` are the max and min of `X_a(t)` over the training period. + +**KNN prediction** — for a given t, find the k nearest neighbors of `X_tilde_a(t)` among training points `t' = t+1, t+2, ..., t+T_*` using Euclidean distance: +``` +[D(t, t')]^2 = sum_{a=1}^{m} (X_tilde_a(t) - X_tilde_a(t'))^2 (338) +``` + +**Predicted return** (simple average): +``` +Y(t) = (1/k) * sum_{alpha=1}^{k} Y(t'_alpha(t)) (339) +``` + +Alternatively, fit a linear model with weights w_alpha and intercept v: +``` +Y(t) = sum_{alpha=1}^{k} Y(t'_alpha(t)) w_alpha + v (340) +``` +trained by regressing Y(t) on the k neighbor returns over M values of t. + +**Trading signal** (z_1, z_2 are trader-defined thresholds): +``` +Signal = { Establish long position if Y > z_1 + { Liquidate long position if Y <= z_2 + { Establish short position if Y < -z_1 + { Liquidate short position if Y >= -z_2 (341) +``` + +## Entry / Exit Rules +- **Long entry**: Predicted cumulative return `Y = Y(0) > z_1` +- **Long exit**: Predicted return `Y <= z_2` (where z_2 <= z_1) +- **Short entry**: Predicted return `Y < -z_1` +- **Short exit**: Predicted return `Y >= -z_2` +- All thresholds must be backtested out-of-sample. + +## Key Parameters +- **Number of neighbors k**: Typically `k = floor(sqrt(T_*))` or `k = ceiling(sqrt(T_*))` (T_* = training sample size) +- **Training sample size T_***: Number of historical time points used for training +- **Prediction horizon T**: Number of trading days for the target return +- **Feature set m**: Number and type of predictor variables (volume MAs, price MAs) +- **Thresholds z_1, z_2**: Entry and exit thresholds for signals (backtested) +- **Train/validation split**: E.g., 60% training, 40% cross-validation +- **Distance metric**: Euclidean (Eq. 338) or Manhattan distance + +## Variations +- **Weighted KNN**: Use distance-based weights for the k neighbors instead of uniform averaging (Eq. 340) +- **Cross-sectional extension**: Compute expected returns Y_i for N stocks and use as inputs to cross-sectional mean-reversion or other multi-stock strategies +- **Alternative features**: Fundamental data, earnings surprises, sentiment indicators in addition to price/volume + +## Notes +- This is a single-stock strategy: each stock's model is trained on that stock's own price/volume data only. +- The strategy must be backtested strictly out-of-sample; data leakage is a critical risk. +- Simple uniform KNN (Eq. 339) has no parameters to train; the linear model (Eq. 340) requires cross-validation and is prone to out-of-sample instability. +- k can be optimized via backtesting; common heuristic: `k = floor(sqrt(T_*))`. +- Typical holding period: T trading days (matching the prediction horizon). +- Training/cross-validation split: e.g., 60%/40%. diff --git a/gateway/knowledge/trading/strategies/stocks/multifactor-portfolio.md b/gateway/knowledge/trading/strategies/stocks/multifactor-portfolio.md new file mode 100644 index 00000000..206920b8 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/multifactor-portfolio.md @@ -0,0 +1,68 @@ +--- +description: "Combines multiple stock-selection factors (e.g., value and momentum) by blending factor rankings or allocating capital across factor sub-portfolios, reducing single-factor risk." +tags: [stocks, multifactor, momentum, value] +--- + +# Multifactor Portfolio + +**Section**: 3.6 | **Asset Class**: Stocks | **Type**: Multifactor + +## Overview +A multifactor portfolio buys and shorts stocks based on multiple factors simultaneously — such as value and momentum — which are often negatively correlated with each other, providing diversification benefits. Combining factors can add value relative to any single-factor strategy. The holding period depends on which factors are combined. + +## Construction / Signal +Two primary approaches to combining F factors: + +**Approach 1 — Capital allocation across sub-portfolios** + +Each of F factor portfolios is built independently (as in Sections 3.1–3.5). Capital is allocated with weights `w_A` (A = 1,...,F): + +``` +sum_{A=1}^{F} w_A = 1 (275) +``` + +Investment level for factor A: `I_A = w_A * I` + +Simple uniform weights: `w_A = 1/F` + +Volatility-weighted: `w_A ∝ 1/sigma_A` or `w_A ∝ 1/sigma_A^2`, where `sigma_A` is the historical volatility of factor portfolio A (uniformly normalized per dollar invested). + +Alternatively, optimize weights using an invertible F×F covariance matrix of the F factor portfolio returns. + +**Approach 2 — Blended ranking scores** + +Define demeaned ranks for factor A across N stocks: + +``` +s_{Ai} = rank(f_{Ai}) - (1/N) * sum_{j=1}^{N} rank(f_{Aj}) (276) +``` + +where `f_{Ai}` is the numeric value of factor A for stock i. Average the ranks across factors: + +``` +s_i = (1/F) * sum_{A=1}^{F} s_{Ai} (277) +``` + +Sort stocks by the combined score `s_i` and construct a long/short portfolio (top decile long, bottom decile short). + +## Entry / Exit Rules +- **Entry**: At rebalance date, compute factor scores, blend them (via capital allocation or rank averaging), and enter long/short positions. +- **Exit**: Hold for the relevant factor horizon; rebalance monthly (or per factor schedule). +- **Tie-breaking**: If ambiguity exists at decile boundaries (e.g., tied combined scores), resolve by preferring one factor's ranking. + +## Key Parameters +- **Number of factors F**: Typically 2–5 (e.g., value + momentum; or value + momentum + low-vol) +- **Factor weights w_A**: Uniform (1/F) or volatility-suppressed +- **Combining method**: Capital allocation vs. rank averaging +- **Holding period**: Depends on the factors combined + +## Variations +- **Two-factor momentum + value**: Sort top/bottom quintiles by momentum, then split by value (or vice versa), creating 4 sub-portfolios +- **Weighted rank averaging**: Non-uniform weights in Eq. (277) using Manhattan or Euclidean distance minimization +- **Portfolio optimization**: Fix weights w_A by optimizing expected returns using an invertible F×F covariance matrix + +## Notes +- Value and momentum are empirically negatively correlated, making them natural complements that reduce portfolio volatility. +- Uniform rank averaging (Eq. 277) minimizes the sum of squared Euclidean distances between the combined N-vector s_i and the K individual N-vectors s_{Ai}. +- Holding period depends on the slowest factor; mixing monthly and annual factors requires careful rebalancing scheduling. +- Transaction costs increase with the number of factors if rebalancing frequencies differ. diff --git a/gateway/knowledge/trading/strategies/stocks/pairs-trading.md b/gateway/knowledge/trading/strategies/stocks/pairs-trading.md new file mode 100644 index 00000000..c7857405 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/pairs-trading.md @@ -0,0 +1,61 @@ +--- +description: "Identifies pairs of historically correlated stocks and trades the spread by shorting the outperformer and buying the underperformer when a mispricing deviation occurs." +tags: [stocks, mean-reversion, pairs-trading, arbitrage] +--- + +# Pairs Trading + +**Section**: 3.8 | **Asset Class**: Stocks | **Type**: Mean-Reversion / Statistical Arbitrage + +## Overview +Pairs trading is a dollar-neutral mean-reversion strategy that identifies two historically highly correlated stocks (stock A and stock B). When a mispricing occurs — a deviation from their high historical correlation — the trader shorts the "rich" stock and buys the "cheap" stock, expecting convergence. This is a classic statistical arbitrage strategy. + +## Construction / Signal +Let `P_A(t_1)`, `P_B(t_1)` be prices at entry time and `P_A(t_2)`, `P_B(t_2)` at a later time. Returns (log approximation preferred for small returns): + +``` +R_A = ln(P_A(t_2) / P_A(t_1)) (285) +R_B = ln(P_B(t_2) / P_B(t_1)) (286) +``` + +Mean return and demeaned returns: + +``` +R_bar = (1/2) * (R_A + R_B) (287) +R_tilde_A = R_A - R_bar (288) +R_tilde_B = R_B - R_bar (289) +``` + +A stock is "rich" if its demeaned return `R_tilde > 0`, and "cheap" if `R_tilde < 0`. + +**Dollar-neutrality constraints** for share quantities Q_A, Q_B (at time t_*): + +``` +P_A |Q_A| + P_B |Q_B| = I (290) +P_A Q_A + P_B Q_B = 0 (291) +``` + +where I is the total desired dollar investment. + +## Entry / Exit Rules +- **Entry**: When the spread between the two stocks deviates significantly from its historical mean (mispricing), short the rich stock (positive demeaned return) and buy the cheap stock (negative demeaned return). Satisfy dollar-neutrality via Eqs. (290)-(291). +- **Exit**: Close positions when the spread converges back to historical norm, or at a predefined stop-loss if the spread widens further. +- **Pair selection**: Choose pairs with historically high correlation (e.g., same sector/industry). + +## Key Parameters +- **Pair selection criterion**: Historical correlation coefficient (typically over 6–12 months) +- **Entry threshold**: Deviation from historical spread mean (typically z-score of spread) +- **Exit threshold**: Convergence back toward mean, or stop-loss if spread widens beyond limit +- **Total investment I**: Split equally between long and short legs + +## Variations +- **Multi-stock generalization**: See Section 3.9 (Mean-reversion — single cluster) for N > 2 stocks +- **Cointegration-based pairs**: Use cointegration tests (Engle-Granger) instead of correlation to identify pairs +- **Distance method**: Sort all possible pairs by sum-of-squared-differences of normalized price series + +## Notes +- Pairs trading is dollar-neutral by construction, removing market beta exposure. +- Risk: if the pair "breaks" (fundamental divergence rather than temporary mispricing), the trade can lose indefinitely — this is a key risk with no natural stop other than a manual stop-loss. +- Prices should be fully adjusted for splits and dividends. +- The log-return approximation (Eqs. 285-286) is preferred over simple returns (Eqs. 283-284) as it is more accurate for small returns. +- Typical holding period: short-term (days to weeks) until spread convergence. diff --git a/gateway/knowledge/trading/strategies/stocks/price-momentum.md b/gateway/knowledge/trading/strategies/stocks/price-momentum.md new file mode 100644 index 00000000..1bfcee3c --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/price-momentum.md @@ -0,0 +1,66 @@ +--- +description: "Ranks stocks by past cumulative or risk-adjusted returns and buys winners while selling losers, exploiting the empirical momentum effect in cross-sectional equity returns." +tags: [stocks, momentum] +--- + +# Price-Momentum + +**Section**: 3.1 | **Asset Class**: Stocks | **Type**: Momentum + +## Overview +The momentum effect describes the empirical tendency for future stock returns to be positively correlated with past returns. Stocks are ranked by a performance criterion computed over a formation period and a portfolio is constructed by buying the top-ranked stocks (winners) and shorting the bottom-ranked stocks (losers). The portfolio is then held for a predefined holding period before being reconstituted. + +## Construction / Signal +Let `P_i(t)` be the fully split- and dividend-adjusted price for stock `i`, with `t` measured in months and `t=0` the most recent time. The monthly return is: + +``` +R_i(t) = P_i(t) / P_i(t+1) - 1 (266) +``` + +Cumulative return over the T-month formation period starting S months ago: + +``` +R_i^cum = P_i(S) / P_i(S+T) - 1 (267) +``` + +Mean monthly return over the formation period: + +``` +R_i^mean = (1/T) * sum_{t=S}^{S+T-1} R_i(t) (268) +``` + +Risk-adjusted mean return (Sharpe-like): + +``` +R_i^risk.adj = R_i^mean / sigma_i (269) + +sigma_i^2 = 1/(T-1) * sum_{t=S}^{S+T-1} (R_i(t) - R_i^mean)^2 (270) +``` + +Stocks are sorted by `R_i^cum`, `R_i^mean`, or `R_i^risk.adj` (descending). The trader buys stocks in the top decile (winners) and shorts stocks in the bottom decile (losers). + +## Entry / Exit Rules +- **Entry**: At rebalance, buy top-decile stocks and short bottom-decile stocks according to the chosen ranking criterion. +- **Exit**: Hold for the predefined holding period (typically 1 month, but can be longer). Liquidate before end of holding period if unforeseen events occur (e.g., market crash). +- **Skip period**: Typically skip the most recent S=1 month to avoid short-term mean-reversion / microstructure effects. + +## Key Parameters +- **Formation period T**: Typically 12 months +- **Skip period S**: Typically 1 month +- **Holding period**: 1 month (longer periods show diminishing returns as momentum fades) +- **Ranking criterion**: `R_i^cum`, `R_i^mean`, or `R_i^risk.adj` +- **Portfolio construction**: Long-only (sum w_i = 1) or dollar-neutral (sum |w_i| = 1, sum w_i = 0) +- **Weights**: Uniform (1/N), or volatility-suppressed (w_i ∝ 1/sigma_i or 1/sigma_i^2) + +## Variations +- **Long-only**: Buy top-decile only; weights w_i ≥ 0, sum w_i = 1. +- **Dollar-neutral (long/short)**: Buy winners, short losers; sum |w_i| = 1, sum w_i = 0. Modulus-uniform weights: w_i = 1/(2*N_L) for longs, w_i = -1/(2*N_S) for shorts. +- **Overlapping portfolios**: Multi-month holding via overlapping 1-month-holding portfolios (Jegadeesh and Titman, 1993). +- **Nonuniform weights**: w_i ∝ 1/sigma_i or w_i ∝ 1/sigma_i^2 to suppress volatile stocks. + +## Notes +- The momentum effect is well-documented but fades over longer horizons; holding periods beyond 12 months tend to reverse (value effect). +- Transaction costs can be significant, especially for high-turnover monthly rebalancing. +- The 1-month skip period is empirically motivated by microstructure/liquidity mean-reversion observed at the 1-month horizon. +- Dollar-neutral construction removes broad market beta exposure. +- Typical holding period: 1 month; diminishing returns for longer holds before trading costs. diff --git a/gateway/knowledge/trading/strategies/stocks/residual-momentum.md b/gateway/knowledge/trading/strategies/stocks/residual-momentum.md new file mode 100644 index 00000000..14ccbacd --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/residual-momentum.md @@ -0,0 +1,68 @@ +--- +description: "Applies price-momentum to the residuals of a Fama-French factor regression rather than raw returns, isolating stock-specific momentum from common factor exposures." +tags: [stocks, momentum, residual, fama-french] +--- + +# Residual Momentum + +**Section**: 3.7 | **Asset Class**: Stocks | **Type**: Momentum + +## Overview +Residual momentum replaces raw stock returns in the price-momentum strategy with the residuals of a serial regression of stock returns on common risk factors (e.g., the 3 Fama-French factors). This isolates the stock-specific component of momentum, removing the influence of market, size, and value factor exposures. The approach is attributed to Blitz, Huij and Martens (2011). + +## Construction / Signal +**Step 1 — Factor regression** (36-month estimation period, with 1-month skip): + +``` +R_i(t) = alpha_i + beta_{1,i} MKT(t) + beta_{2,i} SMB(t) + beta_{3,i} HML(t) + epsilon_i(t) (278) +``` + +where: +- `MKT(t)` = excess market return (market portfolio minus risk-free rate) +- `SMB(t)` = Small Minus Big (size factor) +- `HML(t)` = High Minus Low (book-to-market factor) + +Estimated over a 36-month period to get coefficients `alpha_i`, `beta_{1,i}`, `beta_{2,i}`, `beta_{3,i}`. + +**Step 2 — Compute residuals** for the 12-month formation period (S=1 skip): + +``` +epsilon_i(t) = R_i(t) - beta_{1,i} MKT(t) - beta_{2,i} SMB(t) - beta_{3,i} HML(t) (279) +``` + +Note: `alpha_i` is excluded from this computation (it was estimated over the 36-month period, not the 12-month formation period). + +**Step 3 — Risk-adjusted residual return**: + +``` +epsilon_i^mean = (1/T) * sum_{t=S}^{S+T-1} epsilon_i(t) (280) + +R_tilde_i^risk.adj = epsilon_i^mean / sigma_tilde_i (281) + +sigma_tilde_i^2 = 1/(T-1) * sum_{t=S}^{S+T-1} (epsilon_i(t) - epsilon_i^mean)^2 (282) +``` + +Construct a dollar-neutral portfolio by buying stocks in the top decile by `R_tilde_i^risk.adj` and shorting stocks in the bottom decile. + +## Entry / Exit Rules +- **Entry**: At rebalance, buy top-decile stocks by risk-adjusted residual return; short bottom-decile stocks. +- **Exit**: Hold for typically 1 month (can be longer). +- **Skip period**: S=1 month. + +## Key Parameters +- **Factor model**: 3 Fama-French factors (MKT, SMB, HML); Carhart 4-factor model (adding MOM) is an alternative +- **Regression estimation period**: 36 months +- **Formation period T**: 12 months +- **Skip period S**: 1 month +- **Holding period**: Typically 1 month +- **Portfolio construction**: Dollar-neutral long/short decile + +## Variations +- **4-factor model**: Add Carhart momentum factor MOM(t) to regression +- **Alternative factor models**: Industry factors, principal components, other risk models + +## Notes +- Alpha_i is deliberately excluded from the residual computation for the formation period, as it was estimated over the longer 36-month window. +- Typical holding period is 1 month but can be extended. +- The strategy removes common factor momentum (e.g., sector momentum) and isolates idiosyncratic stock momentum. +- Risk: residual momentum can be sensitive to the choice of factor model and estimation period. diff --git a/gateway/knowledge/trading/strategies/stocks/single-moving-average.md b/gateway/knowledge/trading/strategies/stocks/single-moving-average.md new file mode 100644 index 00000000..8bbd9715 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/single-moving-average.md @@ -0,0 +1,57 @@ +--- +description: "Generates long/short signals for a stock when its current price crosses above or below a single moving average, used as a trend-following entry and exit rule." +tags: [stocks, trend-following, moving-average, technical-analysis] +--- + +# Single Moving Average + +**Section**: 3.11 | **Asset Class**: Stocks | **Type**: Trend-Following / Technical Analysis + +## Overview +This strategy generates buy and sell signals based on whether the current stock price is above or below a single moving average (MA). If the price is above the MA, the stock is in an uptrend and a long position is established; if below, a downtrend is indicated and a short position is established. It can be applied on a single-stock basis or across a universe of stocks simultaneously. + +## Construction / Signal +Two types of moving averages: + +**Simple Moving Average (SMA)**: +``` +SMA(T) = (1/T) * sum_{t=1}^{T} P(t) (319) +``` + +**Exponential Moving Average (EMA)**: +``` +EMA(T, lambda) = (sum_{t=1}^{T} lambda^{t-1} P(t)) / (sum_{t=1}^{T} lambda^{t-1}) + = ((1-lambda)/(1-lambda^T)) * sum_{t=1}^{T} lambda^{t-1} P(t) (320) +``` + +where `t=1` is the most recent day, `T` is the MA length (in trading days), and `lambda < 1` suppresses past contributions. For T >> 1: `EMA(T, lambda) ≈ (1-lambda) P(1) + lambda EMA(T-1, lambda)`. + +**Trading signal** (P is the current price at t=0): +``` +Signal = { Establish long / liquidate short position if P > MA(T) + { Establish short / liquidate long position if P < MA(T) (321) +``` + +## Entry / Exit Rules +- **Long entry**: Current price P crosses above MA(T) → establish long position. +- **Long exit**: Current price P crosses below MA(T) → liquidate long position. +- **Short entry**: Current price P crosses below MA(T) → establish short position. +- **Short exit**: Current price P crosses above MA(T) → liquidate short position. + +## Key Parameters +- **MA type**: SMA or EMA +- **MA length T**: Typically 50, 100, or 200 trading days (longer = slower, fewer signals) +- **Lambda (EMA only)**: Decay factor, 0 < lambda < 1; smaller lambda = faster decay +- **Run mode**: Long-only, short-only, or both long and short + +## Variations +- **Multi-stock application**: Apply to a large universe of stocks on a single-stock basis; with many stocks, (near-)dollar-neutral portfolios can be constructed +- **Two moving averages**: See Section 3.12 (replace price P with a shorter MA) +- **Three moving averages**: See Section 3.13 + +## Notes +- Single-stock technical analysis strategies are considered "unscientific" by many academics, as there is no fundamental reason why a price crossing a moving average should have forecasting power. +- However, trend-following/momentum strategies (which use MAs to compute expected returns) are broadly used and empirically validated. +- Applicable on a single-stock basis with no cross-sectional interaction between stocks. +- With a large universe, near-dollar-neutral portfolios are achievable. +- The strategy can be run as long-only, short-only, or long-short. diff --git a/gateway/knowledge/trading/strategies/stocks/statistical-arbitrage-optimization.md b/gateway/knowledge/trading/strategies/stocks/statistical-arbitrage-optimization.md new file mode 100644 index 00000000..41ed4aa6 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/statistical-arbitrage-optimization.md @@ -0,0 +1,79 @@ +--- +description: "Optimizes portfolio weights by maximizing the Sharpe ratio given expected stock returns and a covariance matrix, with an optional dollar-neutrality constraint enforced via a Lagrange multiplier." +tags: [stocks, statistical-arbitrage, optimization, portfolio-construction, sharpe-ratio] +--- + +# Statistical Arbitrage — Optimization + +**Section**: 3.18 / 3.18.1 | **Asset Class**: Stocks | **Type**: Statistical Arbitrage / Portfolio Optimization + +## Overview +This strategy determines optimal portfolio weights by maximizing the Sharpe ratio given expected returns E_i and a covariance matrix C_ij for N stocks. The unconstrained solution gives a closed-form inverse-covariance-weighted portfolio. A dollar-neutrality constraint can be imposed via a Lagrange multiplier, yielding a modified allocation that suppresses positions by stock volatilities. + +## Construction / Signal +Let `C_ij` be the N×N covariance matrix of stock returns, `D_i` the dollar holdings, `I` the total investment, and `w_i = D_i / I` the dimensionless weights. + +**Portfolio P&L, volatility, and Sharpe ratio**: +``` +P = sum_{i=1}^{N} E_i D_i (342) +V^2 = sum_{i,j=1}^{N} C_ij D_i D_j (343) +S = P / V (344) +``` + +Normalized: `P = I * P_tilde`, `V = I * V_tilde`, `S = P_tilde / V_tilde` where: +``` +P_tilde = sum_{i=1}^{N} E_i w_i (347) +V_tilde^2 = sum_{i,j=1}^{N} C_ij w_i w_j (348) +``` + +with constraint `sum_{i=1}^{N} |w_i| = 1`. + +**Unconstrained Sharpe maximization** (maximize S → max): + +Solution: +``` +w_i = gamma * sum_{j=1}^{N} C_ij^{-1} E_j (350) +``` +where gamma is fixed by the normalization `sum |w_i| = 1`. These weights are not dollar-neutral in general. + +## Entry / Exit Rules +- **Entry**: At each rebalance, solve for optimal weights w_i using expected returns E_i and covariance matrix C_ij; establish long positions for w_i > 0 and short positions for w_i < 0. +- **Exit**: Rebalance periodically (daily or at the signal horizon); close positions that change sign or fall below a threshold. + +## Key Parameters +- **Expected returns E_i**: Can come from mean-reversion, momentum, ML signals, or other alpha sources +- **Covariance matrix C_ij**: Typically a multifactor risk model covariance (sample covariance is singular if T ≤ N+1) +- **Total investment I**: Scales all positions +- **Rebalance frequency**: Depends on signal horizon + +## Variations + +### 3.18.1 — Dollar-Neutrality + +To enforce dollar-neutrality (`sum w_i = 0`), use the Sharpe ratio's scale invariance to reformulate as a quadratic minimization with a Lagrange multiplier mu: + +``` +g(w, lambda) = (lambda/2) * sum_{i,j} C_ij w_i w_j - sum_i E_i w_i - mu * sum_i w_i (354) +g(w, mu, lambda) -> min (355) +``` + +Minimization w.r.t. w_i and mu gives: +``` +lambda * sum_j C_ij w_j = E_i + mu (356) +sum_i w_i = 0 (357) +``` + +Dollar-neutral solution: +``` +w_i = (1/lambda) * [sum_j C_ij^{-1} E_j - C_ij^{-1} * (sum_{k,l} C_kl^{-1} E_l) / (sum_{k,l} C_kl^{-1})] (358) +``` + +Lambda is fixed by the normalization `sum |w_i| = 1`. The weights w_i are approximately suppressed by stock volatilities sigma_i (since C_ii = sigma_i^2 and typically |E_i| ~ sigma_i), providing built-in risk management. + +## Notes +- The sample covariance matrix is singular if T ≤ N+1 (T = number of time observations); in practice a model covariance matrix (positive-definite, stable out-of-sample) is required. +- Eq. (350) is the unconstrained mean-variance (Markowitz, 1952) optimal portfolio. +- The dollar-neutrality solution (Eq. 358) removes market beta and is equivalent to imposing the constraint as a linear homogeneous condition on the quadratic objective. +- Expected returns E_i can be any alpha signal: mean-reversion residuals, momentum scores, ML predictions, etc. +- With a multifactor model C_ij, positions are approximately neutral to factor exposures; exact neutrality is achieved in the zero specific-risk limit (which reduces to weighted regression, see Section 3.10). +- In practice, trading costs, position/trading bounds, and nonlinear constraints are added; this generally breaks the equivalence between Sharpe maximization and quadratic minimization. diff --git a/gateway/knowledge/trading/strategies/stocks/support-and-resistance.md b/gateway/knowledge/trading/strategies/stocks/support-and-resistance.md new file mode 100644 index 00000000..9c370a9c --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/support-and-resistance.md @@ -0,0 +1,60 @@ +--- +description: "Derives support and resistance levels from the previous day's pivot point and trades breakouts or reversals relative to these computed price levels." +tags: [stocks, technical-analysis, support-resistance, pivot-point] +--- + +# Support and Resistance + +**Section**: 3.14 | **Asset Class**: Stocks | **Type**: Technical Analysis + +## Overview +This strategy uses "support" (S) and "resistance" (R) levels computed from the previous day's high, low, and closing prices via a "pivot point" (center) C. The trader establishes or liquidates positions based on whether the current price crosses the center, reaches the resistance, or falls to the support level. + +## Construction / Signal +Using the previous day's high `P_H`, low `P_L`, and closing `P_C` prices: + +**Pivot point (center)**: +``` +C = (P_H + P_L + P_C) / 3 (325) +``` + +**Resistance level**: +``` +R = 2 * C - P_L (326) +``` + +**Support level**: +``` +S = 2 * C - P_H (327) +``` + +**Trading signal** (P is the current price): +``` +Signal = { Establish long position if P > C + { Liquidate long position if P >= R + { Establish short position if P < C + { Liquidate short position if P <= S (328) +``` + +## Entry / Exit Rules +- **Long entry**: Current price P crosses above the pivot center C. +- **Long exit**: Current price P reaches or exceeds the resistance level R (take profit at resistance). +- **Short entry**: Current price P crosses below the pivot center C. +- **Short exit**: Current price P falls to or below the support level S (take profit at support). + +## Key Parameters +- **Price inputs**: Previous day's High (P_H), Low (P_L), Close (P_C) +- **Pivot definition**: Standard: `C = (P_H + P_L + P_C) / 3` (other definitions exist) +- **Holding period**: Very short-term (intraday to 1 day); pivot levels are reset daily + +## Variations +- **Open-price pivot**: Some definitions use the current day's open price instead of the prior close P_C +- **Higher/lower support-resistance levels**: Extended pivot systems define multiple support/resistance levels (S2, S3, R2, R3) +- **Breakout mode**: Instead of reverting at S/R, treat a break through R as a new long entry (trend-following variant) + +## Notes +- Support and resistance levels are reset daily using the previous day's OHLC data. +- The strategy is primarily intraday or very short-term (daily bar). +- There is substantial literature on support/resistance strategies but academic evidence for profitability is mixed. +- Can be combined with volume confirmation: signals are more reliable when price breaks through S/R levels with increased volume. +- The pivot point methodology has many variants (using open price, weekly pivots, Fibonacci ratios, etc.). diff --git a/gateway/knowledge/trading/strategies/stocks/three-moving-averages.md b/gateway/knowledge/trading/strategies/stocks/three-moving-averages.md new file mode 100644 index 00000000..dd67da86 --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/three-moving-averages.md @@ -0,0 +1,51 @@ +--- +description: "Uses three moving averages of ascending length to filter false signals, requiring full alignment of all three MAs before establishing or liquidating long or short positions." +tags: [stocks, trend-following, moving-average, technical-analysis] +--- + +# Three Moving Averages + +**Section**: 3.13 | **Asset Class**: Stocks | **Type**: Trend-Following / Technical Analysis + +## Overview +Adding a third moving average helps filter false signals that arise in the two-MA strategy. A long position is established only when all three MAs are in descending order by length (shortest on top), confirming a strong uptrend. Liquidation occurs as soon as the shortest MA drops below the middle MA — an earlier warning than waiting for a full cross of the two outer MAs. + +## Construction / Signal +Three MAs with lengths T_1 < T_2 < T_3 (e.g., T_1 = 3, T_2 = 10, T_3 = 21): + +``` +Signal = { Establish long position if MA(T_1) > MA(T_2) > MA(T_3) + { Liquidate long position if MA(T_1) <= MA(T_2) + { Establish short position if MA(T_1) < MA(T_2) < MA(T_3) + { Liquidate short position if MA(T_1) >= MA(T_2) (324) +``` + +- **Long trigger**: All three MAs are in bullish alignment (T_1 > T_2 > T_3 in value). +- **Long liquidation**: Early warning — the short MA drops back below the middle MA (even if still above the long MA). +- **Short trigger**: All three MAs are in bearish alignment (T_1 < T_2 < T_3 in value). +- **Short liquidation**: Early warning — the short MA rises back above the middle MA. + +## Entry / Exit Rules +- **Long entry**: MA(T_1) > MA(T_2) > MA(T_3) +- **Long exit**: MA(T_1) <= MA(T_2) +- **Short entry**: MA(T_1) < MA(T_2) < MA(T_3) +- **Short exit**: MA(T_1) >= MA(T_2) + +## Key Parameters +- **Short MA length T_1**: Typically 3–10 trading days +- **Middle MA length T_2**: Typically 10–21 trading days +- **Long MA length T_3**: Typically 21–50 trading days; must have T_1 < T_2 < T_3 +- **Example**: T_1 = 3, T_2 = 10, T_3 = 21 +- **MA type**: SMA or EMA + +## Variations +- **Different exit rule**: Liquidate when T_1 falls below T_3 (slower exit) instead of T_2 +- **Combined with stop-loss**: Add price-based stop-loss as in the two-MA strategy (Section 3.12) +- **Four or more MAs**: Further extension possible but increases complexity and reduces signal frequency + +## Notes +- The three-MA strategy generates fewer signals than the two-MA strategy, filtering out some false crossovers. +- The early liquidation rule (based on T_1 vs T_2 only) provides faster exit than waiting for full reversal. +- Like all MA-based strategies, considered "unscientific" by academics but widely used by practitioners. +- Best applied in trending markets; whipsaw losses occur in range-bound (mean-reverting) markets. +- Applicable single-stock or across a universe; parameter selection should be done via backtesting. diff --git a/gateway/knowledge/trading/strategies/stocks/two-moving-averages.md b/gateway/knowledge/trading/strategies/stocks/two-moving-averages.md new file mode 100644 index 00000000..1af9dd2f --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/two-moving-averages.md @@ -0,0 +1,57 @@ +--- +description: "Signals long/short entries when a shorter moving average crosses above or below a longer moving average, optionally augmented with stop-loss rules based on price thresholds." +tags: [stocks, trend-following, moving-average, technical-analysis] +--- + +# Two Moving Averages + +**Section**: 3.12 | **Asset Class**: Stocks | **Type**: Trend-Following / Technical Analysis + +## Overview +The two-moving-averages strategy replaces the current stock price in the single-MA signal with a shorter moving average. When the shorter MA crosses above the longer MA, a long position is established (bullish signal); when the shorter MA crosses below, a short position is established (bearish signal). This reduces sensitivity to single-day price noise relative to the single-MA strategy. + +## Construction / Signal +Two MAs with lengths T' < T (e.g., T' = 10 days, T = 30 days): + +**Basic signal**: +``` +Signal = { Establish long / liquidate short if MA(T') > MA(T) + { Establish short / liquidate long if MA(T') < MA(T) (322) +``` + +**With stop-loss rules** (Delta is a predefined percentage threshold, e.g., Delta = 2%): + +Let P_1 be the previous day's closing price: +``` +Signal = { Establish long position if MA(T') > MA(T) + { Liquidate long position if P < (1 - Delta) * P_1 + { Establish short position if MA(T') < MA(T) + { Liquidate short position if P > (1 + Delta) * P_1 (323) +``` + +A long position is liquidated if the current price P falls more than Delta below the previous day's price P_1 (even if the shorter MA has not yet crossed the longer MA). Similarly, a short position is liquidated if P rises more than Delta above P_1. + +## Entry / Exit Rules +- **Long entry**: MA(T') crosses above MA(T). +- **Long exit**: MA(T') crosses below MA(T), or price falls Delta% below prior day's close (stop-loss). +- **Short entry**: MA(T') crosses below MA(T). +- **Short exit**: MA(T') crosses above MA(T), or price rises Delta% above prior day's close (stop-loss). + +## Key Parameters +- **Short MA length T'**: Typically 10–50 trading days +- **Long MA length T**: Typically 30–200 trading days; T' < T required +- **MA type**: SMA or EMA for both +- **Stop-loss threshold Delta**: Typically 1–3% (e.g., 2%) +- **Example**: T' = 10, T = 30; or classic "golden cross" T' = 50, T = 200 + +## Variations +- **No stop-loss**: Use basic signal (Eq. 322) only +- **EMA crossover**: Use exponential MAs instead of simple MAs for both T' and T +- **Three moving averages**: See Section 3.13 for additional false-signal filtering + +## Notes +- The two-MA crossover is a classic technical analysis signal (e.g., "golden cross": 50-day MA crosses 200-day MA bullishly). +- Stop-loss rules protect realized profits but can trigger premature exits if the shorter MA has not yet crossed. +- Like all single-stock technical analysis strategies, this is considered "unscientific" by many academics but is widely used in practice. +- Applicable on a single-stock or multi-stock basis. +- Delta must be calibrated via backtesting; too tight a stop causes excessive whipsaw, too loose provides little protection. diff --git a/gateway/knowledge/trading/strategies/stocks/value.md b/gateway/knowledge/trading/strategies/stocks/value.md new file mode 100644 index 00000000..d27e922b --- /dev/null +++ b/gateway/knowledge/trading/strategies/stocks/value.md @@ -0,0 +1,44 @@ +--- +description: "Buys stocks with high Book-to-Price ratios (cheap) and shorts stocks with low Book-to-Price ratios (expensive), exploiting the empirical value premium." +tags: [stocks, value] +--- + +# Value + +**Section**: 3.3 | **Asset Class**: Stocks | **Type**: Value + +## Overview +The value strategy follows the same long-winner/short-loser structure as momentum strategies, but the selection criterion is a value metric rather than past returns. The most common value metric is the Book-to-Price (B/P) ratio. Stocks with high B/P are considered "cheap" (value stocks) and tend to outperform; stocks with low B/P are "expensive" (growth stocks) and tend to underperform. + +## Construction / Signal +The primary signal is the Book-to-Price ratio: + +``` +B/P = Book value per share outstanding / Current stock price +``` + +Note: the B/P ratio is equivalent to the Book-to-Market ratio where "Market" is market capitalization (price × shares outstanding) rather than total book value. + +Stocks are sorted by B/P in descending order. A zero-cost (dollar-neutral) portfolio is constructed by buying top-decile stocks (high B/P, cheap) and shorting bottom-decile stocks (low B/P, expensive). + +## Entry / Exit Rules +- **Entry**: Buy top-decile stocks by B/P; short bottom-decile stocks by B/P. +- **Exit**: Hold for 1–6 months; rebalance periodically as book values are updated (typically quarterly with earnings releases). +- **Portfolio**: Dollar-neutral long/short construction. + +## Key Parameters +- **Value metric**: B/P ratio (Book-to-Price = Book-to-Market) +- **Holding period**: Typically 1–6 months +- **Price definition**: Asness, Moskowitz and Pedersen (2013) use current (most up-to-date) prices; Fama and French (1992) use prices contemporaneous with the book value + +## Variations +- **Alternative value metrics**: Earnings-to-Price (E/P), Sales-to-Price, Cash Flow-to-Price, Dividend Yield +- **Price timing**: Current price vs. price at book value date changes the B/P ratio and can affect performance +- **Long-only**: Buy only top-decile value stocks + +## Notes +- The value premium is a well-documented anomaly (Fama and French three-factor model). +- Value and momentum are empirically negatively correlated, making them natural complements in a multifactor portfolio (see Section 3.6). +- Holding period is typically 1–6 months. +- Book value data lags the market; stale book values can introduce noise. +- Value strategies can suffer extended drawdowns during "growth" regimes. diff --git a/gateway/knowledge/trading/strategies/structured-assets/carry-cds-hedging.md b/gateway/knowledge/trading/strategies/structured-assets/carry-cds-hedging.md new file mode 100644 index 00000000..a2619e20 --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/carry-cds-hedging.md @@ -0,0 +1,54 @@ +--- +description: "CDO carry strategy that buys a low-quality tranche and delta-hedges with a single-name CDS, using the CDS risky duration as the hedge ratio denominator rather than the index." +tags: [structured-assets, cdo, carry, cds-hedge, single-name, delta-hedge] +--- + +# Carry — CDS Hedging + +**Section**: 11.5 | **Asset Class**: Structured Assets | **Type**: Carry / Delta-Hedged + +## Overview +Instead of hedging a long low-quality tranche position with the CDS index (Section 11.2) or a high-quality tranche (Section 11.4), this strategy uses a single-name CDS as the hedging instrument. The single-name CDS typically pays a lower premium than the long tranche, generating positive carry. The hedge ratio uses the risky duration of the CDS as the denominator. + +## Construction / Mechanics +**Position:** +- Long a low-quality tranche: receive high spread S_tranche +- Short a single-name CDS (protection buyer): pay lower spread S_CDS + +**Hedge ratio:** + +``` +Δ_CDS = D / D_CDS (489) +``` + +where: +- D = risky duration of the low-quality tranche (Eq. 486) +- D_CDS = risky duration of the single-name CDS + +Note: Eq. (489) is Eq. (487) with D_ix replaced by D_CDS. + +**Economics:** +- Premium received on the long tranche > premium paid on the short single-name CDS +- Net carry = S_tranche - Δ_CDS × S_CDS + +## Return Profile +Earns positive carry from the spread differential between the tranche and the CDS. The hedge approximately neutralises single-name credit spread sensitivity. Residual risks include basis risk between the tranche and the CDS (they do not move in perfect lockstep), default event risk (the CDS may not pay out at the same time or magnitude as tranche losses), and gamma risk. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Δ_CDS = D / D_CDS | Hedge ratio: tranche risky duration / CDS risky duration | +| S_tranche | Spread received on long tranche | +| S_CDS | Spread paid on short single-name CDS | +| Net carry | S_tranche - Δ_CDS × S_CDS | +| D_CDS | Risky duration of the CDS instrument | + +## Variations +- Use multiple single-name CDS (one per reference entity or a basket) for more precise hedging across the reference pool. +- Combine with an index hedge (Section 11.2) to address both systematic and idiosyncratic credit spread risk. + +## Notes +- Single-name CDS has more precise default coverage for specific reference entities than the index, but may not be available for all names in the pool. +- Basis risk between the tranche and the single-name CDS is a key risk: the tranche spread reflects pool-wide correlation dynamics, while the CDS spread reflects individual credit risk. +- Liquidity of single-name CDS varies widely; less-liquid names may have wide bid-ask spreads that erode carry. +- The tranche remains exposed to correlated defaults (systemic events) even when individual names are hedged. diff --git a/gateway/knowledge/trading/strategies/structured-assets/carry-equity-tranche.md b/gateway/knowledge/trading/strategies/structured-assets/carry-equity-tranche.md new file mode 100644 index 00000000..6bcf9f03 --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/carry-equity-tranche.md @@ -0,0 +1,52 @@ +--- +description: "CDO carry strategy that buys the equity (lowest quality) tranche and delta-hedges credit spread risk by selling the CDS index, earning the spread differential between tranche premium and index cost." +tags: [structured-assets, cdo, carry, equity-tranche, delta-hedge, cds-index] +--- + +# Carry — Equity Tranche with Index Hedging + +**Section**: 11.2 | **Asset Class**: Structured Assets | **Type**: Carry / Delta-Hedged + +## Overview +The equity tranche (e.g., 0–3%) of a CDO pays the highest periodic premium of all tranches because it absorbs the first losses in the reference portfolio. By buying this tranche and delta-hedging the credit spread exposure through a short position in the CDS index, the trader earns the premium differential between the equity tranche and the index hedge cost while neutralising systematic spread movements. + +## Construction / Mechanics +**Position:** +- Long the equity (0–3%) tranche (protection seller): receive spread S_equity +- Short the CDS index (protection buyer): pay spread S_index + +**Delta (hedge ratio):** The number of index units to short per unit of equity tranche is: + +``` +Δ_ix = D / D_ix (487) +``` + +where: +- D = risky duration of the equity tranche (Eq. 486 from Section 11.1) +- D_ix = risky duration of the CDS index + +**Economics:** +- Premium received from the equity tranche > premium paid on the short index position +- The net carry = S_equity × M_tr - S_index × Δ_ix × M_index (per unit time, before defaults) + +## Return Profile +The trade earns positive carry (net spread income) as long as defaults do not erode the equity tranche beyond its detachment point. The hedged position is approximately spread-neutral to small parallel moves in credit spreads. The primary remaining risk is convexity: large spread moves change Δ_ix and require rehedging. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Δ_ix = D / D_ix | Hedge ratio: equity tranche risky duration / index risky duration | +| S_equity | Spread on the equity tranche (higher premium) | +| S_index | Spread on the CDS index (lower premium) | +| Net carry | S_equity - Δ_ix × S_index (approximately) | +| Rehedging frequency | Required as spreads move (risky durations change) | + +## Variations +- Leave the position partially unhedged to maintain more credit spread exposure (higher carry but more market risk). +- Use individual CDS names in the reference pool instead of the index for more precise hedging. + +## Notes +- The equity tranche has the highest spread income but is the first to lose principal if defaults occur in the reference pool; this is the primary tail risk. +- Δ_ix changes as spreads widen or tighten, requiring dynamic rehedging; gamma (convexity) cost reduces net carry. +- During credit crises, equity tranche spreads can blow out dramatically; the hedge may not keep pace if the index and tranche spreads move non-proportionally. +- The strategy is exposed to correlation risk: if default correlations in the reference pool increase (systemic stress), equity tranche losses occur faster than priced. diff --git a/gateway/knowledge/trading/strategies/structured-assets/carry-senior-mezzanine.md b/gateway/knowledge/trading/strategies/structured-assets/carry-senior-mezzanine.md new file mode 100644 index 00000000..9556597b --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/carry-senior-mezzanine.md @@ -0,0 +1,49 @@ +--- +description: "CDO carry strategy that sells a senior or mezzanine tranche and delta-hedges by buying the CDS index, earning the index spread premium over the tranche cost." +tags: [structured-assets, cdo, carry, senior-tranche, mezzanine, delta-hedge, cds-index] +--- + +# Carry — Senior/Mezzanine Tranche with Index Hedging + +**Section**: 11.3 | **Asset Class**: Structured Assets | **Type**: Carry / Delta-Hedged + +## Overview +This is the mirror image of the equity tranche carry trade (Section 11.2). Instead of buying a low-quality tranche and hedging with a short index position, the trader sells a high-quality (senior or mezzanine) tranche and delta-hedges by buying the CDS index. The premiums received from the index exceed the premiums paid on the short senior/mezzanine tranche, generating positive net carry. + +## Construction / Mechanics +**Position:** +- Short the senior/mezzanine tranche (protection buyer): pay spread S_senior +- Long the CDS index (protection seller): receive spread S_index + +**Delta (hedge ratio):** Same formula as Eq. (487): + +``` +Δ_ix = D / D_ix (487) +``` + +where D is the risky duration of the senior/mezzanine tranche and D_ix is the risky duration of the CDS index. + +**Economics:** +- Premium received from the long index position > premium paid on the short senior/mezzanine tranche +- This trade is the opposite of the equity tranche strategy: the index premiums fund the tranche premium cost + +## Return Profile +Earns positive carry as long as defaults do not trigger payouts on the index position that exceed the spread income. The hedged position is approximately spread-neutral to small parallel credit spread moves. The long index position compensates for portfolio-level default losses; the short senior tranche position profits from non-extreme loss scenarios. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Δ_ix = D / D_ix | Hedge ratio: senior/mezzanine tranche risky duration / index risky duration | +| S_index | Spread received on long CDS index position | +| S_senior | Spread paid on short senior/mezzanine tranche | +| Net carry | Δ_ix × S_index - S_senior (approximately) | + +## Variations +- Adjust the quality of the tranche sold (from mezzanine to super-senior) to tune the risk/carry trade-off. +- Use multiple tranches at different quality levels to diversify the credit curve exposure. + +## Notes +- This strategy is "opposite" to the equity tranche carry trade: the long CDS index position exposes the trader to portfolio-level defaults, while the short senior tranche benefits from low-to-moderate loss scenarios. +- The net carry is typically lower than the equity tranche trade because senior tranche spreads are lower. +- Correlation risk applies here as well: if correlation decreases (idiosyncratic defaults increase), the index position is hit harder than a diversified senior tranche. +- The CDS index is a liquid instrument; basis risk between the index and individual tranche spreads is a key residual risk. diff --git a/gateway/knowledge/trading/strategies/structured-assets/carry-tranche-hedging.md b/gateway/knowledge/trading/strategies/structured-assets/carry-tranche-hedging.md new file mode 100644 index 00000000..30fa2b08 --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/carry-tranche-hedging.md @@ -0,0 +1,52 @@ +--- +description: "CDO carry strategy that buys a low-quality tranche and delta-hedges by selling a high-quality tranche, earning the spread differential between the two tranches while hedging credit spread exposure." +tags: [structured-assets, cdo, carry, tranche-hedging, delta-hedge, spread-differential] +--- + +# Carry — Tranche Hedging + +**Section**: 11.4 | **Asset Class**: Structured Assets | **Type**: Carry / Delta-Hedged + +## Overview +Rather than using the CDS index as the hedge vehicle, this strategy hedges a long position in a low-quality tranche by selling a high-quality tranche. The hedge ratio is calibrated to equate the risky durations of the two positions, and the trader earns the spread differential between the high-yield low-quality tranche and the low-yield high-quality tranche. + +## Construction / Mechanics +**Position:** +- Long a low-quality tranche (e.g., equity 0–3%): receive high spread S_low +- Short a high-quality tranche (e.g., senior): pay lower spread S_high + +**Hedge ratio:** The number of high-quality tranche units to short per unit of low-quality tranche is: + +``` +Δ_high = D_low / D_high (488) +``` + +where: +- D_low = risky duration of the low-quality tranche +- D_high = risky duration of the high-quality tranche + +**Economics:** +- Net carry = S_low - Δ_high × S_high (per unit time, before defaults) +- Since S_low >> S_high, the trade generates positive net carry when spread-neutral + +## Return Profile +Profits from the spread differential between the low and high-quality tranches. The delta-hedge neutralises small parallel credit spread moves. Residual exposure includes the correlation between the two tranche spreads, curvature (gamma) as spreads shift, and the risk that defaults breach the low-quality tranche while leaving the high-quality tranche intact. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Δ_high = D_low / D_high | Hedge ratio: risky durations of low vs. high quality tranches | +| S_low | Spread on low-quality (long) tranche | +| S_high | Spread on high-quality (short) tranche | +| Net carry | S_low - Δ_high × S_high | +| Rehedging | Required as risky durations change with spread moves | + +## Variations +- Use mezzanine as the hedge instead of senior to change the risk profile. +- Stack multiple tranche pairs (e.g., equity vs. mezzanine and mezzanine vs. senior) in a ladder structure. + +## Notes +- The correlation between the two tranche spreads is the key residual risk: if the low-quality tranche widens while the high-quality tranche tightens (de-correlation of credit curves), the hedge becomes less effective. +- Unlike the index-hedged strategies (Sections 11.2 and 11.3), there is no single liquid instrument representing the hedge; both legs may have limited secondary market liquidity. +- The hedge ratio Δ_high changes dynamically; frequent rebalancing is required in volatile credit markets. +- This trade is sensitive to the shape of the loss distribution: a bi-modal loss distribution (either very few or very many defaults) affects the two tranches differently. diff --git a/gateway/knowledge/trading/strategies/structured-assets/cdo-curve-trades.md b/gateway/knowledge/trading/strategies/structured-assets/cdo-curve-trades.md new file mode 100644 index 00000000..7a4c0de4 --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/cdo-curve-trades.md @@ -0,0 +1,62 @@ +--- +description: "CDO curve flattener/steepener strategy that takes simultaneous long and short positions in CDO tranches of different maturities, betting on changes in the shape of the CDO spread curve." +tags: [structured-assets, cdo, curve-trade, flattener, steepener, term-structure] +--- + +# CDO Curve Trades + +**Section**: 11.6 | **Asset Class**: Structured Assets | **Type**: Relative Value / Curve + +## Overview +Analogous to curve trades in bonds (Section 5.13), CDO curve trades involve simultaneous long and short positions in CDO tranches of different maturities. A flattener (steepener) bets that the spread curve will flatten (steepen), meaning the differential between long-term and short-term tranche spreads will decrease (increase). The trade can be structured to be dollar-neutral, risky-duration-neutral, or carry-neutral. + +## Construction / Mechanics +**Flattener**: Sell (buy protection on) a short-term tranche + Buy (sell protection on) a long-term tranche. +- Profits if long-term spreads fall relative to short-term spreads (curve flattening). +- In a flattener with S_long > S_short: the trade has positive carry. + +**Steepener**: Buy (sell protection on) a short-term tranche + Sell (buy protection on) a long-term tranche. +- Profits if long-term spreads rise relative to short-term spreads (curve steepening). + +**Carry over period [t, t+Δt]:** + +``` +C(t, t+Δt) = (M_long × S_long - M_short × S_short) × Δt (490) +``` + +where M_long, M_short are the long and short tranche notionals, and S_long, S_short are their spreads. + +**P&L:** The MTM P&L of the strategy is: + +``` +P&L = M_long - M_short (491) +``` + +where M_long and M_short are the long and short tranche MTM values (Eq. 485 from Section 11.1). + +**Structuring options:** +- **Dollar-neutral**: M_long = M_short (equal notionals) +- **Risky-duration-neutral**: D_long = D_short (Eq. 486); equal risky duration exposure +- **Carry-neutral**: M_long × S_long = M_short × S_short (zero net carry at inception) + +## Return Profile +Profits from the anticipated change in the shape of the CDO spread curve (flattening or steepening). The trade eliminates much of the outright credit spread level exposure when structured as duration-neutral. For an upward-sloping curve (S_long > S_short), a flattener has positive carry (favourable in stable conditions). + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| S_long, S_short | Spreads on long and short maturity tranches | +| M_long, M_short | Tranche notionals | +| C(t, t+Δt) | Carry over the holding period (Eq. 490) | +| Structuring method | Dollar-neutral / duration-neutral / carry-neutral | +| P&L = M_long - M_short | Mark-to-market gain/loss (Eq. 491) | + +## Variations +- **Index curve trade**: implement with CDS index tranches of different tenors (e.g., 5-year vs. 10-year CDX). +- **Cross-tranche curve trade**: combine different tranche quality (e.g., equity 5yr vs. senior 10yr) for a combined curve and quality bet. + +## Notes +- Upward-sloping CDO spread curves give positive carry on flattener trades (sell short-term protection, buy long-term protection when S_long > S_short). +- Duration-neutral structuring ensures that small parallel shifts in the spread curve do not generate P&L; the trade is a pure curve bet. +- The risky duration changes as spreads move, requiring periodic rebalancing to maintain duration neutrality. +- Liquidity at the long end of the CDO curve is typically lower than at the standard 5-year tenor; transaction costs may be significant. diff --git a/gateway/knowledge/trading/strategies/structured-assets/cdo-generalities.md b/gateway/knowledge/trading/strategies/structured-assets/cdo-generalities.md new file mode 100644 index 00000000..3979d499 --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/cdo-generalities.md @@ -0,0 +1,92 @@ +--- +description: "Reference overview of Collateralized Debt Obligation (CDO) mechanics, tranche structure, mark-to-market valuation, spread pricing, and risky duration — the foundational concepts for all CDO trading strategies." +tags: [structured-assets, cdo, credit, tranche, abs, cds] +--- + +# CDO Generalities: Collateralized Debt Obligations + +**Section**: 11.1 | **Asset Class**: Structured Assets | **Type**: Reference / Foundational + +## Overview +A CDO is an asset-backed security consisting of a basket of assets (bonds, loans, credit default swaps, etc.) divided into tranches with different credit ratings and interest rates. Each tranche has an attachment point a and a detachment point d. When cumulative portfolio losses exceed a, the tranche begins to lose value; when losses exceed d, the tranche is completely wiped out. Understanding CDO valuation is the foundation for all CDO carry and curve trading strategies (Sections 11.2–11.7). + +## Construction / Mechanics + +### Tranche Structure +- **Attachment point a**: portfolio loss level at which the tranche begins to absorb losses +- **Detachment point d**: portfolio loss level at which the tranche is fully wiped out +- Example: a 3–8% tranche loses value when portfolio losses exceed 3% and is fully wiped at 8% +- Typical tranche hierarchy (decreasing default risk, decreasing premium rate): + - Equity: 0–3% + - Junior mezzanine: 3–7% + - Senior mezzanine: 7–10% + - Senior: 10–15% + - Super senior: 15–30% + +### Buyer/Seller Roles +- **Buyer (long tranche, protection seller)**: receives periodic premium payments; obligated to cover defaults up to the tranche size in the event of a default. +- **Seller (short tranche, protection buyer)**: makes periodic premium payments; receives a payment in the event of a default. + +### Synthetic CDOs +Synthetic CDOs are constructed using credit default swaps (CDS) on a reference pool. Exchange-traded single-tranche CDOs reference CDS indexes such as CDX or iTraxx. + +### Expected Loss Computation +Let t_i (i = 1,...,n) be the periodic premium payment dates. Let H(t) be the set of possible default scenarios ℓ_α (α = 1,...,K) with probabilities p_α(t). The expected loss is: + +``` +L(t) = Σ p_α(t) × max(min(ℓ_α, L_d) - L_a, 0) (481) +``` + +where L_a = a × M_CDO and L_d = d × M_CDO, and M_CDO is the CDO notional in dollars. + +### Mark-to-Market (MTM) Valuation +The MTM value M of the tranche (from the long investor's perspective) is: + +``` +M = P - C (482) +``` + +The premium leg (what the long investor receives): +``` +P = S × Σ D_i Δ_i [M_tr - L(t_i)] (483) +``` + +The contingent (default) leg (what the long investor pays): +``` +C = Σ D_i [L(t_i) - L(t_{i-1})] (484) +``` + +where: +- S = spread (annual premium rate) +- D_i = risk-free discount factor for payment date t_i +- Δ_i = t_i - t_{i-1} (time between payment dates) +- M_tr = L_d - L_a (tranche notional) +- L(t_0) = 0 + +### Fair Spread and Risky Duration +Setting M = 0 fixes the fair spread S = S*. The risky duration D of the tranche is the first derivative of M w.r.t. the spread: + +``` +M(S) = (S - S*) × Σ D_i Δ_i [M_tr - L(t_i)] (485) +D = ∂M/∂S = Σ D_i Δ_i [M_tr - L(t_i)] (486) +``` + +The risky duration D_ix can also be defined analogously for a CDS index. + +## Return Profile +The long tranche position earns carry (spread income) when no defaults occur. The contingent leg represents the tail-risk cost: large losses materialise only when portfolio losses exceed the attachment point. Junior tranches have higher spreads but greater default exposure; senior tranches have lower spreads but protection from defaults up to the attachment point. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| a, d | Attachment and detachment points (%) | +| M_CDO | CDO notional in dollars | +| S | Tranche spread (annual premium rate) | +| D (risky duration) | Sensitivity of MTM to spread change; Eq. (486) | +| L(t) | Expected loss at time t; Eq. (481) | + +## Notes +- The expected loss L(t) and the probabilities p_α(t) are model-dependent; different models (Gaussian copula, etc.) give different valuations. +- Risky duration is the primary hedging metric for CDO tranche positions (used in Sections 11.2–11.5). +- CDS indexes (CDX, iTraxx) provide liquid reference points for both outright hedging and relative-value trades. +- Convexity of tranche value w.r.t. spread means that hedging ratios change as spreads move; dynamic rehedging is required. diff --git a/gateway/knowledge/trading/strategies/structured-assets/mbs-trading.md b/gateway/knowledge/trading/strategies/structured-assets/mbs-trading.md new file mode 100644 index 00000000..5ff3e652 --- /dev/null +++ b/gateway/knowledge/trading/strategies/structured-assets/mbs-trading.md @@ -0,0 +1,60 @@ +--- +description: "Mortgage-backed security (MBS) passthrough trading strategy that buys MBS and hedges interest rate duration with interest rate swaps, leaving prepayment risk as the primary exposure and profit driver." +tags: [structured-assets, mbs, mortgage, prepayment, duration-hedge, interest-rate-swap] +--- + +# Mortgage-Backed Security (MBS) Trading + +**Section**: 11.7 | **Asset Class**: Structured Assets | **Type**: Carry / Relative Value / Duration-Hedged + +## Overview +MBS passthrough securities pool mortgage cash flows and pass them through to investors. The primary risk specific to MBS (beyond general interest rate risk) is prepayment risk: homeowners can prepay their mortgages when interest rates fall, refinancing at lower rates. This creates negative convexity in MBS prices. The core trading strategy buys MBS passthroughs and hedges the interest rate duration exposure with interest rate swaps, isolating prepayment risk as the residual P&L driver. + +## Construction / Mechanics +**Position:** +- Long MBS passthrough (receive mortgage cash flows) +- Short interest rate swap notional calibrated to hedge the MBS duration (pay fixed, receive floating; or receive fixed, pay floating depending on direction) + +**Prepayment mechanics:** +- When interest rates fall, homeowners refinance (prepay mortgages early) +- The MBS investor receives principal early (at par) but loses the above-market coupon stream +- This creates **negative convexity**: the MBS price rises less than a comparable bond when rates fall, and falls similarly when rates rise +- The 5-year swap rate is the key reference benchmark for prepayment behaviour + +**Hedge ratio determination:** +The hedge ratios are model-dependent and require prepayment models. Two approaches: + +1. **Model-based**: use a prepayment model to compute duration, then size the swap position to match the MBS dollar duration. + +2. **Non-parametric / empirical**: using historical data, estimate the first derivative of MBS price P with respect to the 5-year swap rate R: + - Constrain P to be a non-increasing function of R (reflecting negative convexity) + - Estimate via constrained regression (e.g., Ait-Sahalia and Duarte, 2003; Duarte, Longstaff and Yu, 2006) + +## Return Profile +Profits from: +1. **Carry**: MBS passthroughs typically offer a spread over Treasuries and swaps as compensation for prepayment risk. +2. **Prepayment mispricing**: if the market overprices prepayment risk (i.e., the MBS is cheap relative to the modelled value), the hedged position profits as spreads tighten. + +The primary risk is prepayment model error and the negative convexity of MBS when rates decline sharply. + +## Key Parameters / Signals +| Parameter | Description | +|-----------|-------------| +| Prepayment rate (CPR) | Conditional prepayment rate; key driver of MBS cash flows | +| Duration | Interest rate sensitivity of MBS; hedge-determining quantity | +| Hedge instrument | Interest rate swaps (typically 5-year or 10-year) | +| OAS (option-adjusted spread) | Spread over swap curve after adjusting for the embedded prepayment option; buy high OAS | +| Negative convexity | MBS price appreciation is capped when rates fall (prepayments accelerate) | +| Hedge ratio ∂P/∂R | First derivative of MBS price w.r.t. 5-year swap rate; model or regression estimated | + +## Variations +- **TBA (to-be-announced) trading**: most liquid MBS market; trade generic pools before specific pools are specified. +- **Specified pool trading**: target pools with lower prepayment characteristics (e.g., low-loan-balance, geographic concentrations) that command a premium. +- **IO/PO strips**: trade interest-only or principal-only strips to isolate specific prepayment exposures. +- **Agency vs. non-agency MBS**: agency MBS (Fannie/Freddie/Ginnie) carry implicit government guarantee; non-agency MBS add credit risk. + +## Notes +- Prepayment modelling is complex; the standard PSA (Public Securities Association) benchmark model and its descendants require significant calibration. +- Negative convexity is the key distinguishing risk vs. standard fixed income: as rates fall, the effective duration of MBS shortens (prepayments accelerate), creating re-hedging costs. +- The non-parametric hedge approach avoids model specification risk but requires substantial historical data and may be slow to adapt to regime changes in prepayment behaviour. +- The 2008 financial crisis demonstrated that non-agency MBS carries substantial credit risk in addition to prepayment risk; agency MBS largely avoided credit losses but still suffered spread widening. diff --git a/gateway/knowledge/trading/strategies/tax-arbitrage/cross-border-tax-arbitrage.md b/gateway/knowledge/trading/strategies/tax-arbitrage/cross-border-tax-arbitrage.md new file mode 100644 index 00000000..108dbe70 --- /dev/null +++ b/gateway/knowledge/trading/strategies/tax-arbitrage/cross-border-tax-arbitrage.md @@ -0,0 +1,73 @@ +--- +description: "Exploit differences in dividend taxation across jurisdictions by selling stock cum-dividend and repurchasing ex-dividend (or loaning stock to a domestic investor) to capture tax credits unavailable to foreign holders." +tags: [tax-arbitrage, equities, cross-border, dividends] +--- + +# Cross-Border Tax Arbitrage + +**Section**: 13.2 | **Asset Class**: Equities (Cross-Border) | **Type**: Tax Arbitrage + +## Overview +The U.S. double-taxes corporate income: once at the corporate level and again when dividends are received by shareholders. Some countries (e.g., Australia, Singapore) use imputation systems that relieve this burden by attaching tax credits to dividend payments. Foreign investors in such markets generally do not receive these tax credits, creating an arbitrage opportunity around dividend dates. + +## Construction / Mechanics +Under a full dividend imputation system, the tax mechanics per dollar of corporate income `P` are: + +``` +Corporate tax rate = τ_c +Cash dividend paid = D +Dividend tax credit = C = D × τ_c / (1 - τ_c) +Taxable income = I_t = D + C = D / (1 - τ_c) (496) +Personal tax rate = τ_p +Personal income tax = T = I_t × τ_p +Dividend income after credit = I = D + C - T = D × (1 - τ_p) / (1 - τ_c) +``` + +When `D = P(1 - τ_c)` and `I = P(1 - τ_p)` there is no double-taxation. The price drop from cum-dividend to ex-dividend, in the presence of tax credits, is expected to be `D(1 + κ)`, where `κ` is the tax credit rate (`1 + κ = 1/(1 + τ_c)`). + +A foreign investor who holds the stock is penalized relative to a domestic investor. **Arbitrage strategies:** + +1. **Stock sale/repurchase**: Foreign investor sells the stock cum-dividend at `S_0` and buys it back ex-dividend +2. **Stock loan**: Foreign investor loans the stock to a domestic investor cum-dividend and receives the stock back ex-dividend along with a preset portion of the tax credit + +## Return Profile +Profits are realized around dividend dates. The P&L from either approach approximates the value of the tax credit that the domestic investor can claim. Returns are event-driven and concentrated at dividend announcements. + +## Key Parameters / Signals +- **Tax credit rate** `κ`: defined by the local corporate tax rate; `1 + κ = 1/(1 + τ_c)` +- **Cum-/ex-dividend dates**: the arbitrage window is narrow; execution must occur between these dates +- **Transaction costs**: must be below the value of the tax credit for the strategy to be profitable +- **Jurisdiction restrictions**: some markets restrict cross-border tax arbitrage; legal/regulatory due diligence required + +## Variations + +### 13.2.1 Cross-Border Tax Arbitrage with Options +In the absence of a tax credit, there is a theoretical upper bound on American put option value: + +``` +V_put(K, T) ≤ V_call(K, T) - S_0 + K + D (497) +``` + +With a tax credit, put prices are expected to be higher (reflecting the credit). A foreign investor can: +- Sell the stock cum-dividend at `S_0` +- Write a deep ITM put option + +Near expiration, the put value is approximately: + +``` +V_put(K, T) = K - [S_0 - D(1 + κ)] (498) +``` + +The P&L once the put is exercised ex-dividend at strike `K`: + +``` +P&L = S_0 + V_put(K, T) - K = D(1 + κ) (499) +``` + +This achieves the same economic result as the stock loan/swap approach, monetizing the full dividend plus tax credit. + +## Notes +- A swap agreement between foreign and domestic investors can also achieve the same result as the stock loan +- Regulatory risk is significant: many jurisdictions have enacted rules specifically to prevent cross-border dividend tax arbitrage (e.g., anti-avoidance provisions, minimum holding period requirements) +- The options-based variation (13.2.1) requires liquid options markets with deep ITM puts available at reasonable bid-ask spreads +- Legal and tax counsel is essential before implementing; what is permissible varies substantially by jurisdiction pair diff --git a/gateway/knowledge/trading/strategies/tax-arbitrage/muni-bond-tax-arbitrage.md b/gateway/knowledge/trading/strategies/tax-arbitrage/muni-bond-tax-arbitrage.md new file mode 100644 index 00000000..57104449 --- /dev/null +++ b/gateway/knowledge/trading/strategies/tax-arbitrage/muni-bond-tax-arbitrage.md @@ -0,0 +1,50 @@ +--- +description: "Borrow at short-term taxable rates and buy tax-exempt municipal bonds, capturing the after-tax spread where tax deductibility of interest expense creates a net positive return." +tags: [tax-arbitrage, fixed-income, municipal-bonds] +--- + +# Municipal Bond Tax Arbitrage + +**Section**: 13.1 | **Asset Class**: Fixed Income (Municipal Bonds) | **Type**: Tax Arbitrage + +## Overview +One of the most common and simple forms of tax arbitrage. The strategy borrows money (short-term loan) and uses the proceeds to buy tax-exempt municipal bonds. It is attractive to companies in jurisdictions where tax rules allow both buying tax-exempt muni bonds and deducting interest expenses from taxable income (the "tax shield"), creating a positive after-tax spread. + +## Construction / Mechanics +- **Long**: tax-exempt municipal bonds earning interest rate `r_long` +- **Short (borrowed funding)**: corporate loan at interest rate `r_short` + +The strategy return is: + +``` +R = r_long - r_short × (1 - τ) (495) +``` + +- `r_long` = interest rate on the purchased municipal bonds +- `r_short` = interest rate on the loan +- `τ` = corporate tax rate + +The loan interest is tax-deductible, so the effective borrowing cost is `r_short × (1 - τ)`. For `R > 0` (profitable), we need: + +``` +r_long > r_short × (1 - τ) +``` + +## Return Profile +The strategy profits as long as the municipal bond yield exceeds the after-tax borrowing cost. Returns are stable and bond-like in normal markets but exposed to credit events on the muni bonds and to changes in tax law. The tax shield on borrowing is the core structural advantage. + +## Key Parameters / Signals +- **Corporate tax rate** `τ`: higher tax rates make the strategy more attractive (lower effective borrowing cost) +- **Muni yield** `r_long`: tax-exempt; higher quality munis yield less +- **Borrowing rate** `r_short`: short-term rates affect the after-tax funding cost +- **Jurisdiction**: only viable where tax rules permit both the tax-exempt income and the interest deduction simultaneously + +## Variations +- **Leveraged muni carry**: increase leverage to amplify the spread, at the cost of higher interest rate and credit risk +- **Duration-matched**: match the duration of muni bonds and the borrowing to reduce interest rate risk + +## Notes +- Regulatory and tax law risk: changes in tax law can eliminate the tax shield or the tax-exempt status of munis +- Credit risk: municipal bonds can default, though historically at low rates +- Liquidity risk: municipal bonds are less liquid than Treasuries +- Only practically accessible to corporate entities (not individuals) with sufficient tax liability and access to cheap funding diff --git a/gateway/knowledge/trading/strategies/volatility/generalities.md b/gateway/knowledge/trading/strategies/volatility/generalities.md new file mode 100644 index 00000000..68bb738b --- /dev/null +++ b/gateway/knowledge/trading/strategies/volatility/generalities.md @@ -0,0 +1,48 @@ +--- +description: "Background on volatility as an asset class: historical vs. implied volatility, VIX as the market's fear gauge, and the spectrum of instruments (options, futures, ETNs) used for volatility trading." +tags: [volatility, background, vix, implied-volatility, options] +--- + +# Volatility Generalities + +**Section**: 7.1 | **Asset Class**: Volatility | **Type**: Background / Reference + +## Overview +Volatility can be viewed as an asset class in its own right. Volatility strategies make bets on whether future realized volatility will be higher or lower, or on the relationship between implied and realized volatility. Volatility is measured historically (from past returns) or implied (extracted from option prices, forward-looking). VIX is the dominant index-level volatility measure and its derivatives provide direct trading vehicles. + +## Construction / Mechanics + +### Historical (Realized) Volatility +Based on a time series of past returns. For daily log-returns R(t) = ln[S(t)/S(t-1)] over a window of T days: +``` +σ_realized = sqrt(F/T · Σ_{t=1}^T R(t)²) +``` +where F = 252 (annualization factor for daily data). Note: mean is not subtracted (consistent with variance swap conventions). + +### Implied Volatility +Extracted from option prices via the Black-Scholes formula or model-free methods. Implied volatility is forward-looking: it represents the market's expectation of future volatility over the option's lifetime. + +### VIX +The CBOE Volatility Index (VIX), the "fear gauge" or "uncertainty index," measures the market's expectation of 30-day volatility of the S&P 500 as implied by a range of S&P 500 options. Related indexes include: +- **RVX**: CBOE Russell 2000 Volatility Index +- **VXEEM**: CBOE Emerging Markets ETF Volatility Index +- **TYVIX**: CBOE/CBOT 10-year U.S. Treasury Note Volatility Index +- **GVZ**: CBOE Gold ETF Volatility Index +- **EUVIX**: CBOE/CME FX Euro Volatility Index + +### Volatility Trading Instruments +- **Options**: direct vol exposure, but require Delta-hedging to isolate volatility (see Section 7.4.1) +- **VIX futures (UX1, UX2, ...)**: UX1 ≈ 1 month to maturity; allow direct trading of forward implied vol +- **Volatility ETNs**: VXX tracks short-maturity VIX futures (months 1-2); VXZ tracks medium-maturity (months 4-7); subject to roll/contango losses +- **Variance swaps**: payoff proportional to realized variance minus strike; no Delta-hedging required (see Section 7.6) + +## Key Concepts +- **Volatility risk premium**: implied vol > realized vol most of the time; selling volatility is structurally profitable on average but with crash risk +- **Contango**: VIX futures curve upward-sloping (most common); VXX loses value via roll loss +- **Backwardation**: VIX futures curve downward-sloping (during stress); VXX gains from roll +- **VIX and equities are anti-correlated**: VIX typically spikes during equity market selloffs + +## Notes +- Options-based volatility strategies (straddles, etc.) are covered in Section 2 of the book; this chapter focuses on VIX derivatives and variance swaps. +- Long volatility positions profit in crises (natural hedge) but are expensive to maintain due to roll/theta decay. +- Short volatility positions earn the volatility risk premium in normal markets but suffer catastrophic losses during sudden vol spikes. diff --git a/gateway/knowledge/trading/strategies/volatility/variance-swaps.md b/gateway/knowledge/trading/strategies/volatility/variance-swaps.md new file mode 100644 index 00000000..5829a642 --- /dev/null +++ b/gateway/knowledge/trading/strategies/volatility/variance-swaps.md @@ -0,0 +1,68 @@ +--- +description: "Variance swaps are derivative contracts whose payoff is proportional to the difference between realized variance and a preset variance strike, allowing pure volatility bets without the need for continuous Delta-hedging." +tags: [volatility, variance-swap, realized-variance, delta-neutral, derivatives] +--- + +# Volatility Trading with Variance Swaps + +**Section**: 7.6 | **Asset Class**: Volatility | **Type**: Volatility / Derivatives + +## Overview +Variance swaps allow traders to bet on future realized variance without the operational burden of continuous Delta-hedging required by options-based volatility strategies. The payoff at maturity is proportional to the difference between the realized variance of the underlying and a preset variance strike K, scaled by a variance notional N. + +## Construction / Mechanics + +**Payoff at maturity T** (for the long side): +``` +P(T) = N × (v(T) - K) (434) +``` + +**Realized variance** over the period: +``` +v(T) = (F/T) Σ_{t=1}^T R(t)² (435) +``` + +**Log-return** at time t: +``` +R(t) = ln[S(t) / S(t-1)] (436) +``` + +where: +- t = 0, 1, ..., T: sample points (e.g., trading days) +- S(t): underlying price at time t +- F: annualization factor (F = 252 for daily data) +- N: variance notional (preset, in dollar terms) +- K: variance strike (preset at contract inception; determines the fair value entry price) +- Note: the mean return is NOT subtracted in v(T), so the denominator is T (not T-1) + +**Long variance swap**: benefits when realized variance v(T) > K (realized vol was higher than expected). +**Short variance swap**: benefits when realized variance v(T) < K (realized vol was lower than expected). + +**Fair value of K**: at inception, K is set such that the swap has zero initial value; it equals the market's expected future variance (often proxied by the square of the VIX for equity index variance swaps). + +## Payoff / Return Profile +- **Long variance swap** profits when realized variance exceeds the variance strike K: v(T) > K. + - Typical use: hedge against a volatility spike; gains are convex in the volatility move (since variance is the square of vol). +- **Short variance swap** profits when realized variance is below K: v(T) < K. + - Typical use: harvest the volatility risk premium (implied vol > realized vol on average); earns N × (K - v(T)) in normal markets. +- The payoff is in units of variance (not volatility); a move from 10% to 20% vol generates 4× the payoff of a move from 10% to 15% vol. + +## Key Parameters / Signals +- K: variance strike (the break-even point) +- N: variance notional (dollar value per unit of variance) +- v(T): realized variance (the key realized outcome) +- F: annualization factor (252 for daily, 52 for weekly, etc.) +- T: number of observation periods +- v(T) - K: the net P&L per unit of notional + +## Variations +- **Volatility swap**: payoff based on sqrt(v(T)) - K_vol (realized volatility minus vol strike); less convex than variance swap; harder to replicate. +- **Conditional variance swap**: accumulates variance only on days when the underlying is within a specified range. +- **Corridor variance swap**: similar, accumulates variance only when the underlying is above (or below) a barrier. + +## Notes +- The key advantage over options-based volatility strategies: no Delta-hedging required, so the trader takes pure variance exposure with no directional risk (assuming no P&L drift from Delta). +- The convexity of the variance payoff (variance = vol²) means long variance swaps gain more from large vol spikes than short options positions gain from vol increases. +- Short variance swaps capture the volatility risk premium (K > expected realized variance) but have unlimited downside: if realized variance is very high (e.g., a market crash), N × (v(T) - K) can be very large. +- Variance swaps on equity indexes are liquid OTC instruments; single-stock variance swaps are less common. +- The mean is not subtracted in v(T) (Eq. 435), which is standard market convention; subtracting the mean would change the denominator to T-1. diff --git a/gateway/knowledge/trading/strategies/volatility/vix-futures-basis-trading.md b/gateway/knowledge/trading/strategies/volatility/vix-futures-basis-trading.md new file mode 100644 index 00000000..63ef6980 --- /dev/null +++ b/gateway/knowledge/trading/strategies/volatility/vix-futures-basis-trading.md @@ -0,0 +1,64 @@ +--- +description: "VIX futures basis trading is a mean-reversion strategy that shorts VIX futures when the basis is positive (contango) and buys when the basis is negative (backwardation), based on the empirical finding that the basis predicts subsequent VIX futures price changes." +tags: [volatility, vix, futures, basis, mean-reversion] +--- + +# VIX Futures Basis Trading + +**Section**: 7.2 | **Asset Class**: Volatility | **Type**: Mean-Reversion + +## Overview +The VIX futures basis is the difference between the first-month VIX futures price and the VIX spot price. Empirically, the basis has no forecasting power for subsequent VIX changes, but does forecast VIX futures price changes (mean-reversion). When the curve is in contango (positive basis), futures prices tend to fall; when in backwardation (negative basis), futures prices tend to rise. The strategy trades this mean-reversion. + +## Construction / Mechanics + +**VIX futures basis**: +``` +B_VIX = P_UX1 - P_VIX (429) +``` + +**Daily roll value** (normalized by days to settlement T): +``` +D = B_VIX / T (430) +``` + +where: +- P_UX1: price of the first-month (UX1) VIX futures contract +- P_VIX: VIX spot price +- T: number of business days until settlement (assumed ≥ 10) +- D: daily roll value (basis per business day remaining) + +**Trading rule** (based on D): +``` +Rule = { Open long UX1 position if D < -0.10 + { Close long UX1 position if D > -0.05 + { Open short UX1 position if D > 0.10 + { Close short UX1 position if D < 0.05 (431) +``` + +- **Short UX1**: when the curve is in contango (D > 0.10); futures price tends to converge down toward VIX. +- **Long UX1**: when the curve is in backwardation (D < -0.10); futures price tends to converge up toward VIX. + +**Optional hedge**: short UX1 position can be hedged by shorting mini-S&P 500 futures (since VIX and equity markets are anti-correlated; a VIX spike usually accompanies an equity selloff). + +## Payoff / Return Profile +- Profits when VIX futures prices revert toward the VIX spot (as they do at settlement). +- In contango: short position earns the roll-down as futures price falls toward VIX. +- In backwardation: long position earns the roll-up as futures price rises toward VIX. +- Loses when VIX spikes suddenly (short position) or crashes (long position) before mean-reversion occurs. + +## Key Parameters / Signals +- D = B_VIX / T: the daily roll value — primary signal +- Entry thresholds: |D| > 0.10 to open; |D| < 0.05 to close +- T: days to settlement (must be ≥ 10 for the strategy to be viable) +- Hedge ratio: estimated from serial regression of VIX futures price changes on mini-S&P 500 futures returns + +## Variations +- Use a basket of VIX futures (UX1, UX2, etc.) rather than just UX1 for more stable exposure. +- Combine with VIX ETN strategies (VXX/VXZ carry, Section 7.3). + +## Notes +- A short UX1 position is exposed to the risk of a sudden VIX spike (equity market selloff), which typically requires the mini-S&P hedge. +- The hedge ratio for the mini-S&P position should be estimated from historical regression of VIX futures price changes on S&P 500 futures returns. +- The empirical basis for this strategy rests on the mean-reverting property of the VIX futures basis, documented in Mixon (2007), Nossman & Wilhelmsson (2009), Simon & Campasano (2014). +- Settlement date proximity (small T) makes D volatile and the signal unreliable; hence the T ≥ 10 minimum requirement. diff --git a/gateway/knowledge/trading/strategies/volatility/volatility-carry.md b/gateway/knowledge/trading/strategies/volatility/volatility-carry.md new file mode 100644 index 00000000..8109a89f --- /dev/null +++ b/gateway/knowledge/trading/strategies/volatility/volatility-carry.md @@ -0,0 +1,68 @@ +--- +description: "Volatility carry with two ETNs shorts VXX (short-maturity VIX futures ETN) and buys VXZ (medium-maturity VIX futures ETN) to harvest the contango roll loss differential, with the hedge ratio determined by serial regression." +tags: [volatility, carry, vxx, vxz, etn, contango, roll] +--- + +# Volatility Carry with Two ETNs + +**Section**: 7.3 | **Asset Class**: Volatility | **Type**: Carry + +## Overview +VXX and VXZ are exchange-traded notes (ETNs) tracking VIX futures. VXX tracks short-maturity (months 1-2) futures and suffers greater roll/contango losses than VXZ (months 4-7), because the VIX futures curve is steepest at the short end in contango. The strategy shorts VXX (captures the larger roll loss as profit) and buys VXZ as a hedge (offsets some exposure to VIX spikes), earning the contango roll differential. + +## Construction / Mechanics + +**VXX**: tracks a constant-maturity position in months 1-2 VIX futures. Each day, a fraction of the front-month futures is sold and replaced with the next-month futures. In contango, the next-month is more expensive → daily roll loss → VXX decays over time. + +**VXZ**: tracks months 4-7 VIX futures. Same roll mechanism but in a less steep part of the contango curve → lower roll loss than VXX. + +**Basic strategy**: short VXX, long VXZ. + +**Hedge ratio** h (number of VXZ units per VXX shorted): +``` +h = β = ρ · σ_X / σ_Z +``` +where: +- ρ: historical pairwise correlation between VXX and VXZ returns +- σ_X: historical volatility of VXX +- σ_Z: historical volatility of VXZ +- β: slope of serial regression of VXX returns on VXZ returns (with intercept) + +The position: short 1 unit of VXX, long h units of VXZ. + +## Payoff / Return Profile +- Earns the differential roll loss between VXX and VXZ: the strategy benefits because VXX decays faster than VXZ in contango. +- The VXZ long position partially hedges against VIX spikes (which cause VXX to spike more sharply than VXZ). +- Profitable in normal, low-volatility, contango environments. +- Experiences sharp drawdowns during sudden VIX spikes (equity market selloffs), as VXX spikes more violently than VXZ in the short term. + +## Key Parameters / Signals +- Contango in VIX futures curve: the necessary condition for the strategy to profit +- h = ρ · σ_X / σ_Z: hedge ratio (number of VXZ units per 1 unit of VXX shorted) +- Roll loss differential between VXX and VXZ: the carry being harvested +- VIX level and slope of futures curve: risk indicators + +## Variations + +### 7.3.1 Hedging Short VXX with VIX Futures +Instead of using VXZ to hedge, use a basket of N medium-maturity VIX futures (e.g., months 4-7) directly. The optimal weights w_i for the N futures: + +``` +w_i = σ_X Σ_{j=1}^N C_{ij}^{-1} σ_j ρ_j (432) +``` + +where: +- ρ_j: historical correlation between futures j and VXX returns +- C_{ij}: N×N sample covariance matrix of the N futures returns (C_{ii} = σ_i²) +- σ_X: historical volatility of VXX + +Dollar-neutral constraint (optional): Σ_i w_i = 1 (Eq. 433). Some w_i may be negative; can impose w_i ≥ 0 if short futures is undesirable. + +Portfolio can be rebalanced monthly or more frequently. This variation allows finer control over the hedge than using VXZ alone. + +## Notes +- VXX spikes (which occur during equity market selloffs) can be large and sudden, causing substantial short-term P&L drawdowns even if the strategy is profitable overall. +- The hedge ratio h should be recalibrated periodically using updated historical data. +- The corresponding VXZ spikes are typically smaller, providing only partial protection during stress. +- Transaction costs (bid-ask spread on VXX/VXZ) and ETN management fees must be accounted for in return estimates. +- In sustained backwardation periods, both VXX and VXZ can rise; the strategy may lose money if VXX rises faster than VXZ. diff --git a/gateway/knowledge/trading/strategies/volatility/volatility-risk-premium.md b/gateway/knowledge/trading/strategies/volatility/volatility-risk-premium.md new file mode 100644 index 00000000..bd1bc3c9 --- /dev/null +++ b/gateway/knowledge/trading/strategies/volatility/volatility-risk-premium.md @@ -0,0 +1,63 @@ +--- +description: "Volatility risk premium strategy sells S&P 500 ATM straddles when implied volatility (VIX) exceeds recent realized volatility, capturing the persistent premium that implied vol commands over realized vol in normal markets." +tags: [volatility, risk-premium, straddle, vix, implied-volatility, realized-volatility] +--- + +# Volatility Risk Premium + +**Section**: 7.4 | **Asset Class**: Volatility | **Type**: Carry / Short Volatility + +## Overview +Implied volatility is empirically higher than realized volatility most of the time — the volatility risk premium. This means options are, on average, overpriced relative to their Black-Scholes fair value based on realized volatility. The strategy sells options (ATM straddles on S&P 500) when the premium is positive, earning the excess implied vol over realized vol. It is profitable in sideways markets but loses money during sharp volatility spikes. + +## Construction / Mechanics + +**Volatility risk premium proxy signal**: at the start of each month, compare: +- VIX (implied volatility of S&P 500, in %) at the beginning of the current month +- Realized volatility of S&P 500 daily returns (in %) since the beginning of the current month + +If the spread (VIX - realized vol) is positive → **sell the ATM straddle** on S&P 500 options. + +**Position**: short 1 near-ATM straddle (1 short ATM call + 1 short ATM put) on S&P 500 index options, held for approximately 1 month. + +The straddle is ATM at inception, hence approximately Delta-neutral at entry. However, as the underlying moves, the straddle becomes Delta-nonzero. + +## Payoff / Return Profile +- Earns the net option premium (implied vol minus realized vol differential) when the market moves less than implied by VIX. +- Profitable in low-volatility, sideways markets. +- Loses money when the S&P 500 moves sharply (volatility spike), which typically accompanies equity market selloffs. +- The "short vega" position loses immediately when implied volatility rises, even before expiry. + +## Key Parameters / Signals +- VIX at month start: measure of implied volatility +- Realized vol of S&P 500 since month start: backward-looking volatility +- Spread = VIX - realized vol: entry signal (sell when positive) +- Strike selection: near-ATM (at-the-money) straddle +- Holding period: approximately 1 month (to option expiry) + +## Variations + +### 7.4.1 Volatility Risk Premium with Gamma Hedging +The ATM straddle is initially Delta-neutral but becomes Delta-nonzero as the S&P 500 moves. This variation adds Gamma hedging to maintain near-Delta-neutrality: + +- **Gamma (Γ = ∂²V/∂S²)**: measures the rate of change of Delta with the underlying price. +- As the underlying moves up (down), the short straddle develops positive (negative) Delta. +- **Gamma hedge**: buy (sell) the underlying S&P 500 to offset the Delta change; i.e., trade the underlying in the direction opposite to the move. + +Effect of Gamma hedging: +- The strategy becomes a "Theta play": profits from Theta (Θ = ∂V/∂t) decay — the time value of the short options erodes daily. +- The cost of Gamma hedging is the bid-ask spread and transaction costs of continuously rebalancing. +- As the underlying moves further from the strike, Gamma hedging becomes more expensive (the underlying positions become larger) and can eventually exceed the collected option premium, at which point the strategy loses money. +- This is also known as "Gamma scalping" (but from the short side — the hedger is short Gamma). + +**Option Greeks for reference**: +- Θ = ∂V/∂t (Theta): time decay +- Δ = ∂V/∂S (Delta): sensitivity to underlying price +- Γ = ∂²V/∂S² (Gamma): sensitivity of Delta to underlying price +- ν = ∂V/∂σ (Vega): sensitivity to implied volatility + +## Notes +- Index options (S&P 500) are better suited than single-stock options for this strategy because index options typically have higher volatility risk premia (see Section 6.3 on dispersion trading). +- A volatility spike (e.g., during a market selloff) causes both realized vol to rise and VIX to jump, producing large losses on both the Vega and Delta dimensions simultaneously. +- The strategy is sometimes described as "selling tail risk" — the premium earned in normal times compensates for large, infrequent losses. +- Gamma hedging reduces directional risk but cannot eliminate it for large moves; it also introduces transaction costs that reduce the effective premium earned. diff --git a/gateway/knowledge/trading/strategies/volatility/volatility-skew-risk-reversal.md b/gateway/knowledge/trading/strategies/volatility/volatility-skew-risk-reversal.md new file mode 100644 index 00000000..5f2572c2 --- /dev/null +++ b/gateway/knowledge/trading/strategies/volatility/volatility-skew-risk-reversal.md @@ -0,0 +1,53 @@ +--- +description: "Volatility skew risk reversal strategy buys an OTM call and sells an OTM put to exploit the empirical skew where put implied volatility exceeds call implied volatility, capturing a directional upside bias at reduced net premium cost." +tags: [volatility, skew, risk-reversal, options, put, call] +--- + +# Volatility Skew — Long Risk Reversal + +**Section**: 7.5 | **Asset Class**: Volatility | **Type**: Volatility Skew / Directional + +## Overview +OTM put options are empirically priced with higher implied volatility than OTM call options at the same distance from the current spot price. This volatility skew (puts more expensive than calls) reflects market demand for downside protection. The long risk reversal — buy an OTM call, sell an OTM put — captures this skew by selling the expensive put and buying the cheaper call, resulting in a net credit or reduced debit. However, the strategy has a directional component: it loses money if the underlying falls below the put strike. + +## Construction / Mechanics + +**Volatility skew setup**: with underlying S_0 = K (at-the-money), and OTM options at distance κ > 0: +- OTM put: strike K_put = K - κ; implied vol σ_put (higher) +- OTM call: strike K_call = K + κ; implied vol σ_call (lower) +- Skew: σ_put > σ_call (puts priced richer than calls at the same moneyness) + +**Long risk reversal position**: +- **Buy** OTM call (strike K + κ): pays premium C_call +- **Sell** OTM put (strike K - κ): receives premium C_put > C_call +- Net premium received: C = C_put - C_call > 0 (net credit due to the skew) + +Reference: see Section 2.12 of the book for the basic risk reversal option strategy. + +## Payoff / Return Profile +- **If S_T > K + κ** (underlying rallies above call strike): call expires ITM; gain = S_T - (K+κ) + C +- **If K - κ < S_T < K + κ** (underlying stays between strikes): both options expire worthless; gain = C (the net premium received) +- **If S_T < K_put** (underlying falls below put strike): put expires ITM; loss = K_put - S_T - C; maximum loss when S_T → 0 is K_put - C +- Break-even on the downside: S_T = K_put - C + +The strategy profits when the underlying rises or stays stable, and loses when the underlying falls. + +## Key Parameters / Signals +- K_put = K - κ: put strike (sold) +- K_call = K + κ: call strike (bought) +- κ: distance from ATM (moneyness) +- C = C_put - C_call: net premium received (positive due to skew) +- σ_put - σ_call: implied volatility skew — the size of the mispricing being exploited +- K_put - C: downside break-even level + +## Variations +- **Short risk reversal**: sell OTM call, buy OTM put — a bearish, downside bet; profits if underlying falls below the put strike. +- **Skew trade without directional bias**: combine the risk reversal with a Delta hedge to isolate the pure skew component. +- **Different distances**: use asymmetric κ_put ≠ κ_call to fine-tune the net premium and directional exposure. + +## Notes +- This is a directional strategy: it loses money if the price drops below K_put - C; the skew-capture is bundled with an implicit bullish bet. +- The strategy profits most clearly in a stable or rallying market with sustained volatility skew. +- The skew is typically larger for equity indexes than individual stocks (reflecting systematic put-buying for portfolio hedging). +- To isolate the pure skew trade (without directional exposure), the position should be Delta-hedged dynamically, which introduces transaction costs and complexity. +- Risk reversals are commonly used by FX traders where the skew direction can differ from equities (e.g., EURUSD calls can be more expensive than puts in certain regimes). diff --git a/gateway/prompt/agent-main.md b/gateway/prompt/agent-main.md index 15320f66..d06e18b9 100644 --- a/gateway/prompt/agent-main.md +++ b/gateway/prompt/agent-main.md @@ -89,6 +89,26 @@ To switch symbol and period (period is in seconds: 60=1m, 300=5m, 900=15m, 3600= After patching, confirm the change to the user. +## Drawing Shapes on the Chart + +To add or modify chart drawings (trend lines, Fibonacci retracements, rectangles, etc.), use `WorkspacePatch` directly on the `shapes` store. Use `MemoryLookup({page: "platform/shapes"})` for the full type reference including point counts and override properties. + +Read `chartState` first to get the current symbol and visible time range for placing points accurately. + +**Pattern for adding a shape:** +```json +[{ + "op": "add", + "path": "/shapes/", + "value": { } +}] +``` + +The shape object structure and all type-specific details are in `platform/shapes`. + +To delete: `[{ "op": "remove", "path": "/shapes/" }]` +To update a property: `[{ "op": "replace", "path": "/shapes//color", "value": "#FF0000" }]` + ## Symbol Resolution Always use `SymbolLookup` to resolve tickers before passing them to research or chart tools. Symbols must be in `SYMBOL.EXCHANGE` format (e.g., `BTC/USDT.BINANCE`). If the user says "ETHUSDT", "ETH", or any ambiguous ticker, resolve it first. `SymbolLookup` results are sorted by 24h volume descending — pick the top result when the user hasn't specified an exchange. diff --git a/gateway/prompt/index.md b/gateway/prompt/index.md index 2546ea13..4918887b 100644 --- a/gateway/prompt/index.md +++ b/gateway/prompt/index.md @@ -27,11 +27,11 @@ If the user asks for a capability not provided by Dexorder, decline and explain ## Knowledge Base -Use `MemoryLookup` to read detailed documentation about any tool, API, or platform topic. Call it with a page name, e.g. `MemoryLookup({page: "api-reference"})` or `MemoryLookup({page: "workspace"})`. +Use `MemoryLookup` to read detailed documentation about any tool, API, or platform topic. Call it with a page name from the Knowledge Base table below, e.g. `MemoryLookup({page: "platform/workspace"})` or `MemoryLookup({page: "platform/shapes"})`. ## Workspace -The **Workspace** is the user's current UI context — what they are looking at and what is selected. It includes the active chart symbol and timeframe, any indicators and drawings on the chart, and the user's saved scripts. When the user refers to "the chart", "what's selected", or "the current indicator", they mean the Workspace. You can read it with `WorkspaceRead` and update it with `WorkspacePatch`. Detailed descriptions of every Workspace store and field are in the `workspace` knowledge page. +The **Workspace** is the user's current UI context — what they are looking at and what is selected. It includes the active chart symbol and timeframe, any indicators and drawings on the chart, and the user's saved scripts. When the user refers to "the chart", "what's selected", or "the current indicator", they mean the Workspace. You can read it with `WorkspaceRead` and update it with `WorkspacePatch`. Detailed descriptions of every Workspace store and field are in the `platform/workspace` knowledge page. ## Investment Advice diff --git a/gateway/prompt/tools.md b/gateway/prompt/tools.md index 07192548..8455cb14 100644 --- a/gateway/prompt/tools.md +++ b/gateway/prompt/tools.md @@ -17,8 +17,9 @@ Available to all agents: | Tool | Purpose | |------|---------| -| `WorkspacePatch` | Apply a JSON patch to a workspace store | +| `WorkspacePatch` | Apply a JSON patch to a workspace store (use `ShapesMutate` for chart shapes) | | `WorkspaceRead` | Read the current state of a workspace store | +| `ShapesMutate` | Add, update, or remove chart drawings (trend lines, Fibonacci, rectangles, etc.) | | `PythonList` | List existing scripts by category (`strategy`, `indicator`, or `research`) | | `SymbolLookup` | Resolve a ticker to the correct `SYMBOL.EXCHANGE` format | | `GetChartData` | Fetch raw OHLC data (casual retrieval only — use `Spawn` research for analysis) | @@ -29,7 +30,7 @@ Available to all agents: ## MCP Tools (user sandbox) -Available to all agents. These run in the user's per-session sandbox container: +Available to all agents. These run in the user's sandbox container: | Tool | Purpose | |------|---------| diff --git a/gateway/src/channels/websocket-handler.ts b/gateway/src/channels/websocket-handler.ts index ca51b1af..9cb14e33 100644 --- a/gateway/src/channels/websocket-handler.ts +++ b/gateway/src/channels/websocket-handler.ts @@ -76,7 +76,6 @@ export interface WebSocketHandlerConfig { interface BarSubscription { ticker: string; periodSeconds: number; - callback: BarUpdateCallback; openBars: boolean; } @@ -338,20 +337,24 @@ export class WebSocketHandler { return; } - // Check for @ModelTag at the start of the message + // Check for @ModelTag anywhere in the message const parsedTag = parseModelTag(payload.content ?? ''); - let messageContent: string = payload.content ?? ''; + const messageContent: string = payload.content ?? ''; let modelOverride: { modelId: string; provider?: LLMProvider } | undefined; if (parsedTag) { await harness.clearHistory(); - socket.send(JSON.stringify({ type: 'model_switched', tag: parsedTag.tag, modelId: parsedTag.modelId, rest: parsedTag.rest })); - messageContent = parsedTag.rest; + socket.send(JSON.stringify({ + type: 'model_switched', + tag: parsedTag.tag, + modelId: parsedTag.modelId, + hasOtherContent: parsedTag.hasOtherContent, + })); modelOverride = { modelId: parsedTag.modelId, provider: parsedTag.provider }; - logger.info({ tag: parsedTag.tag, modelId: parsedTag.modelId }, 'Model tag switch'); + logger.info({ tag: parsedTag.tag, modelId: parsedTag.modelId, hasOtherContent: parsedTag.hasOtherContent }, 'Model tag switch'); } - // Chat message - send to agent harness with streaming + // Pass the full original message content to the harness (tag included — harmless for the LLM) const inboundMessage: InboundMessage = { messageId: randomUUID(), userId: authContext.userId, @@ -370,7 +373,9 @@ export class WebSocketHandler { const msgDebouncer = makeChunkDebouncer(content => socket.send(JSON.stringify({ type: 'agent_chunk', content, done: false })) ); - const stream = (parsedTag && !messageContent) + const useGreeting = parsedTag && !parsedTag.hasOtherContent; + logger.info({ useGreeting, hasOtherContent: parsedTag?.hasOtherContent }, 'Stream path'); + const stream = useGreeting ? harness.streamGreeting(modelOverride) : harness.streamMessage(inboundMessage, { modelOverride }); for await (const event of stream) { @@ -564,8 +569,8 @@ export class WebSocketHandler { const sessionId = authContext.sessionId; const subs = this.barSubscriptions.get(sessionId); if (subs && this.config.ohlcService) { - for (const { ticker, periodSeconds, callback, openBars } of subs) { - this.config.ohlcService.unsubscribeFromTicker(ticker, periodSeconds, callback, openBars); + for (const { ticker, periodSeconds, openBars } of subs) { + this.config.ohlcService.unsubscribeFromTicker(ticker, periodSeconds, sessionId, openBars); } this.barSubscriptions.delete(sessionId); logger.info({ sessionId, count: subs.length }, 'Cleaned up realtime bar subscriptions'); @@ -790,13 +795,6 @@ export class WebSocketHandler { // Create a per-subscription callback that forwards bars to this socket const barCallback: BarUpdateCallback = (bar) => { if (socket.readyState !== 1 /* OPEN */) return; - const symbolMeta = symbolIndexService?.getSymbolByTicker(bar.ticker); - const priceDivisor = (symbolMeta?.price_precision ?? 0) > 0 - ? Math.pow(10, symbolMeta!.price_precision!) - : 1; - const sizeDivisor = (symbolMeta?.size_precision ?? 0) > 0 - ? Math.pow(10, symbolMeta!.size_precision!) - : 1; socket.send(JSON.stringify({ type: 'bar_update', subscription_id: payload.subscription_id, @@ -806,27 +804,25 @@ export class WebSocketHandler { bar: { // Convert nanoseconds → seconds for client compatibility time: Number(bar.timestamp / 1_000_000_000n), - open: bar.open / priceDivisor, - high: bar.high / priceDivisor, - low: bar.low / priceDivisor, - close: bar.close / priceDivisor, - volume: bar.volume / sizeDivisor, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, }, })); }; - ohlcService.subscribeToTicker(subTicker, subPeriod, barCallback, openBars); + ohlcService.subscribeToTicker(subTicker, subPeriod, sessionId, barCallback, openBars); - // Track for cleanup on disconnect + // Track for cleanup on disconnect (dedup: relay handles the callback, we just need to know what to clean up) if (!this.barSubscriptions.has(sessionId)) { this.barSubscriptions.set(sessionId, []); } - this.barSubscriptions.get(sessionId)!.push({ - ticker: subTicker, - periodSeconds: subPeriod, - callback: barCallback, - openBars, - }); + const sessionSubs = this.barSubscriptions.get(sessionId)!; + if (!sessionSubs.some(s => s.ticker === subTicker && s.periodSeconds === subPeriod && s.openBars === openBars)) { + sessionSubs.push({ ticker: subTicker, periodSeconds: subPeriod, openBars }); + } logger.info({ sessionId, ticker: subTicker, period: subPeriod }, 'Subscribed to realtime bars'); @@ -853,7 +849,7 @@ export class WebSocketHandler { ); if (idx >= 0) { const [removed] = subs.splice(idx, 1); - ohlcService.unsubscribeFromTicker(unsubTicker, unsubPeriod, removed.callback, removed.openBars); + ohlcService.unsubscribeFromTicker(unsubTicker, unsubPeriod, sessionId, removed.openBars); logger.info({ sessionId, ticker: unsubTicker, period: unsubPeriod }, 'Unsubscribed from realtime bars'); } } diff --git a/gateway/src/clients/zmq-relay-client.ts b/gateway/src/clients/zmq-relay-client.ts index 49e9984c..ef006120 100644 --- a/gateway/src/clients/zmq-relay-client.ts +++ b/gateway/src/clients/zmq-relay-client.ts @@ -71,8 +71,8 @@ export class ZMQRelayClient { /** Ref count per ZMQ topic (gateway-level dedup before ZMQ subscribe/unsubscribe) */ private topicRefs: Map = new Map(); - /** Callbacks registered by WebSocket sessions for realtime bar updates */ - private barCallbacks: Map> = new Map(); + /** Callbacks registered by WebSocket sessions for realtime bar updates, keyed by clientId */ + private barCallbacks: Map> = new Map(); private connected = false; private notificationListenerRunning = false; @@ -298,7 +298,7 @@ export class ZMQRelayClient { if (bar) { const callbacks = this.barCallbacks.get(topic); if (callbacks) { - for (const cb of callbacks) { + for (const cb of callbacks.values()) { try { cb(bar); } catch (e) { /* ignore callback errors */ } } } @@ -353,43 +353,48 @@ export class ZMQRelayClient { * Subscribe to realtime OHLC bars for a ticker+period. * * ZMQ subscribe is only called on the 0→1 transition (first subscriber). - * This triggers the relay XPUB → Flink subscription detection → ingestor activation. + * Re-subscribing with the same clientId replaces the existing callback (idempotent). * + * @param clientId Unique identifier for the downstream subscriber (e.g. WebSocket sessionId) * @param callback Called whenever a new bar arrives for this topic * @param openBars If true, subscribe to the ":open" topic (live in-progress bar updates * for charts). If false (default), subscribe to closed bars only * (completed candles for strategies/triggers). */ - subscribeToTicker(ticker: string, periodSeconds: number, callback: BarUpdateCallback, openBars = false): void { + subscribeToTicker(ticker: string, periodSeconds: number, clientId: string, callback: BarUpdateCallback, openBars = false): void { const topic = `${ticker}|ohlc:${periodSeconds}${openBars ? ':open' : ''}`; - // Register callback if (!this.barCallbacks.has(topic)) { - this.barCallbacks.set(topic, new Set()); + this.barCallbacks.set(topic, new Map()); } - this.barCallbacks.get(topic)!.add(callback); + const clientMap = this.barCallbacks.get(topic)!; + const isNew = !clientMap.has(clientId); + clientMap.set(clientId, callback); - // ZMQ subscribe on first ref - const prev = this.topicRefs.get(topic) ?? 0; - this.topicRefs.set(topic, prev + 1); - if (prev === 0 && this.subSocket) { - this.subSocket.subscribe(topic); - this.logger.info({ topic }, 'ZMQ subscribed to realtime topic'); + // ZMQ subscribe on 0→1 transition only; re-subscribes don't add new refs + if (isNew) { + const prev = this.topicRefs.get(topic) ?? 0; + this.topicRefs.set(topic, prev + 1); + if (prev === 0 && this.subSocket) { + this.subSocket.subscribe(topic); + this.logger.info({ topic }, 'ZMQ subscribed to realtime topic'); + } } } /** - * Unsubscribe a callback from realtime OHLC bars. + * Unsubscribe a client from realtime OHLC bars. * ZMQ unsubscribe is only called on the 1→0 transition (last subscriber). + * @param clientId Must match the value used in the corresponding subscribeToTicker call. * @param openBars Must match the value used in the corresponding subscribeToTicker call. */ - unsubscribeFromTicker(ticker: string, periodSeconds: number, callback: BarUpdateCallback, openBars = false): void { + unsubscribeFromTicker(ticker: string, periodSeconds: number, clientId: string, openBars = false): void { const topic = `${ticker}|ohlc:${periodSeconds}${openBars ? ':open' : ''}`; - const callbacks = this.barCallbacks.get(topic); - if (callbacks) { - callbacks.delete(callback); - if (callbacks.size === 0) { + const clientMap = this.barCallbacks.get(topic); + if (clientMap) { + clientMap.delete(clientId); + if (clientMap.size === 0) { this.barCallbacks.delete(topic); } } @@ -419,12 +424,12 @@ export class ZMQRelayClient { } /** - * Remove all subscriptions for a set of (topic, callback) pairs. + * Remove all subscriptions for a set of (topic, clientId) pairs. * Convenience method for WebSocket disconnect cleanup. */ - cleanupSubscriptions(subscriptions: Array<{ ticker: string; periodSeconds: number; callback: BarUpdateCallback; openBars?: boolean }>): void { - for (const { ticker, periodSeconds, callback, openBars } of subscriptions) { - this.unsubscribeFromTicker(ticker, periodSeconds, callback, openBars ?? false); + cleanupSubscriptions(subscriptions: Array<{ ticker: string; periodSeconds: number; clientId: string; openBars?: boolean }>): void { + for (const { ticker, periodSeconds, clientId, openBars } of subscriptions) { + this.unsubscribeFromTicker(ticker, periodSeconds, clientId, openBars ?? false); } } diff --git a/gateway/src/harness/spawn/wiki-loader.ts b/gateway/src/harness/spawn/wiki-loader.ts index 5fb0af54..39f050c9 100644 --- a/gateway/src/harness/spawn/wiki-loader.ts +++ b/gateway/src/harness/spawn/wiki-loader.ts @@ -1,4 +1,5 @@ import { readFile, readdir } from 'fs/promises'; +import type { Dirent } from 'fs'; import { join, dirname, relative } from 'path'; import { fileURLToPath } from 'url'; import yaml from 'js-yaml'; @@ -206,17 +207,91 @@ export class WikiLoader { } /** - * Build a markdown catalog table of all KB pages with their descriptions. - * Used by getBasePrompt() to inject into the cached system prompt. + * Build a markdown table listing all articles in a single subdirectory. + * For .md files: adds a row with the page name and its description. + * For subdirectories that have an index.md: adds a row for "subdir/index". + * Skips index.md and README.md. + */ + private async buildSubdirCatalog(dirName: string): Promise { + const dirPath = join(KNOWLEDGE_DIR, dirName); + let entries; + try { + entries = await readdir(dirPath, { withFileTypes: true }); + } catch { + return ''; + } + + entries.sort((a, b) => a.name.localeCompare(b.name)); + + const rows: string[] = []; + for (const entry of entries) { + if (entry.isFile() && entry.name.endsWith('.md') && entry.name !== 'index.md' && entry.name !== 'README.md') { + const pageName = `${dirName}/${entry.name.slice(0, -3)}`; + const page = await this.loadPage(pageName); + const desc = page?.frontmatter.description ?? ''; + rows.push(`| ${pageName} | ${desc} |`); + } else if (entry.isDirectory()) { + const indexName = `${dirName}/${entry.name}/index`; + const indexPage = await this.loadPage(indexName); + if (indexPage) { + const desc = indexPage.frontmatter.description ?? ''; + rows.push(`| ${indexName} | ${desc} |`); + } + } + } + + if (rows.length === 0) return ''; + return [ + '## Articles in this Category', + '', + '| Page | Description |', + '|------|-------------|', + ...rows, + ].join('\n'); + } + + /** + * Build a tiered markdown catalog for the system prompt. + * + * Includes only: + * - Top-level .md files directly under KNOWLEDGE_DIR (skips README.md) + * - One row per subdirectory that has an index.md (shown as "subdir/index") + * + * For subdirectory index pages with an empty body, eagerly generates and caches + * the full article listing so MemoryLookup calls hit the cache instantly. */ async getKBCatalog(): Promise { - const pages = await this.listPages(); - const rows: string[] = []; - for (const name of pages) { - const page = await this.loadPage(name); - const desc = page?.frontmatter.description ?? ''; - rows.push(`| ${name} | ${desc} |`); + let entries: Dirent[]; + try { + entries = await readdir(KNOWLEDGE_DIR, { withFileTypes: true }); + } catch { + entries = []; } + entries.sort((a, b) => a.name.localeCompare(b.name)); + + const rows: string[] = []; + for (const entry of entries) { + if (entry.isFile() && entry.name.endsWith('.md') && entry.name !== 'README.md') { + const name = entry.name.slice(0, -3); + const page = await this.loadPage(name); + const desc = page?.frontmatter.description ?? ''; + rows.push(`| ${name} | ${desc} |`); + } else if (entry.isDirectory()) { + const indexName = `${entry.name}/index`; + const page = await this.loadPage(indexName); + if (page) { + // Eagerly build and cache the subdir catalog if the file body is empty. + // The KB does not change during operation; all index expansion happens at startup. + if (!page.body.trim()) { + const generatedBody = await this.buildSubdirCatalog(entry.name); + this.pageCache.set(indexName, { frontmatter: page.frontmatter, body: generatedBody }); + } + const desc = page.frontmatter.description ?? ''; + rows.push(`| ${indexName} | ${desc} |`); + } + } + } + return [ '## Knowledge Base', '', diff --git a/gateway/src/llm/model-tags.ts b/gateway/src/llm/model-tags.ts index 3b2fa6f8..c6d73691 100644 --- a/gateway/src/llm/model-tags.ts +++ b/gateway/src/llm/model-tags.ts @@ -10,21 +10,30 @@ export const MODEL_TAGS: ModelTag[] = [ { tag: 'DeepSeek-Flash', modelId: 'deepseek-ai/DeepSeek-V4-Flash' }, { tag: 'DeepSeek-Pro', modelId: 'deepseek-ai/DeepSeek-V4-Pro' }, { tag: 'Kimi', modelId: 'moonshotai/Kimi-K2.6' }, - { tag: 'GLM', modelId: 'zai-org/GLM-5' }, + { tag: 'GLM-5', modelId: 'zai-org/GLM-5' }, + { tag: 'GLM-5.1', modelId: 'zai-org/GLM-5.1' }, { tag: 'Qwen', modelId: 'Qwen/Qwen3.5-27B' }, { tag: 'MiniMax', modelId: 'MiniMaxAI/MiniMax-M2.5' }, - { tag: 'Sonnet', modelId: 'claude-sonnet-4-6', provider: LLMProvider.ANTHROPIC }, - { tag: 'Haiku', modelId: 'claude-haiku-4-5-20251001', provider: LLMProvider.ANTHROPIC }, - { tag: 'Opus', modelId: 'claude-opus-4-7', provider: LLMProvider.ANTHROPIC }, + { tag: 'Sonnet', modelId: 'sonnet', provider: LLMProvider.ANTHROPIC }, + { tag: 'Haiku', modelId: 'haiku', provider: LLMProvider.ANTHROPIC }, + { tag: 'Opus', modelId: 'opus', provider: LLMProvider.ANTHROPIC }, ]; -/** Parse a leading @Tag from message content. Case-insensitive. Returns null if not a known tag. */ -export function parseModelTag(content: string): (ModelTag & { rest: string }) | null { - const trimmed = content.trimStart(); - if (!trimmed.startsWith('@')) return null; - const spaceIdx = trimmed.indexOf(' '); - const tagName = spaceIdx === -1 ? trimmed.slice(1) : trimmed.slice(1, spaceIdx); - const rest = spaceIdx === -1 ? '' : trimmed.slice(spaceIdx + 1).trim(); - const found = MODEL_TAGS.find(m => m.tag.toLowerCase() === tagName.toLowerCase()); - return found ? { ...found, rest } : null; +/** + * Scan content for any known model @Tag (anywhere in the message, case-insensitive). + * Returns the matched tag plus whether any non-tag content is present. + * Returns null if no known model tag is found. + */ +export function parseModelTag(content: string): (ModelTag & { hasOtherContent: boolean }) | null { + const regex = /@([A-Za-z0-9._-]+)/g; + let match; + while ((match = regex.exec(content)) !== null) { + const tagName = match[1]; + const found = MODEL_TAGS.find(m => m.tag.toLowerCase() === tagName.toLowerCase()); + if (found) { + const withoutTag = (content.slice(0, match.index) + content.slice(match.index + match[0].length)).trim(); + return { ...found, hasOtherContent: withoutTag.length > 0 }; + } + } + return null; } diff --git a/gateway/src/main.ts b/gateway/src/main.ts index b0945bb3..0420e24a 100644 --- a/gateway/src/main.ts +++ b/gateway/src/main.ts @@ -540,7 +540,7 @@ try { // Main agent: platform tools + user's general MCP tools toolRegistry.registerAgentTools({ agentName: 'main', - platformTools: ['SymbolLookup', 'GetChartData', 'GetTicker24h'], + platformTools: ['SymbolLookup', 'GetChartData', 'GetTicker24h', 'ShapesMutate'], mcpTools: ['PythonList', 'PythonDelete', 'BacktestStrategy', 'ListActiveStrategies'], }); diff --git a/gateway/src/services/ohlc-service.ts b/gateway/src/services/ohlc-service.ts index 20c97514..9f84bad5 100644 --- a/gateway/src/services/ohlc-service.ts +++ b/gateway/src/services/ohlc-service.ts @@ -47,34 +47,34 @@ export class OHLCService { private icebergClient: IcebergClient; private relayClient: ZMQRelayClient; private logger: FastifyBaseLogger; - private getSymbolIndex?: () => SymbolIndexService | undefined; constructor(config: OHLCServiceConfig) { this.icebergClient = config.icebergClient; this.relayClient = config.relayClient; this.logger = config.logger; - this.getSymbolIndex = config.getSymbolIndex; } /** * Subscribe to realtime OHLC bar updates for a ticker+period. - * ZMQ subscribe is issued on the first call for a given topic; subsequent calls - * for the same topic only add the callback (no extra ZMQ events). + * ZMQ subscribe is issued on the first call for a given topic; re-subscribing with + * the same clientId replaces the existing callback (idempotent). * + * @param clientId Unique downstream subscriber identifier (e.g. WebSocket sessionId) * @param openBars If true, subscribe to in-progress bar snapshots (every tick, for charts). * If false (default), subscribe to closed bars only (for strategies/triggers). */ - subscribeToTicker(ticker: string, periodSeconds: number, callback: BarUpdateCallback, openBars = false): void { - this.relayClient.subscribeToTicker(ticker, periodSeconds, callback, openBars); + subscribeToTicker(ticker: string, periodSeconds: number, clientId: string, callback: BarUpdateCallback, openBars = false): void { + this.relayClient.subscribeToTicker(ticker, periodSeconds, clientId, callback, openBars); } /** - * Unsubscribe a callback from realtime OHLC bar updates. - * ZMQ unsubscribe is issued when the last callback for a topic is removed. + * Unsubscribe a client from realtime OHLC bar updates. + * ZMQ unsubscribe is issued when the last client for a topic is removed. + * @param clientId Must match the value used in the corresponding subscribeToTicker call. * @param openBars Must match the value used in the corresponding subscribeToTicker call. */ - unsubscribeFromTicker(ticker: string, periodSeconds: number, callback: BarUpdateCallback, openBars = false): void { - this.relayClient.unsubscribeFromTicker(ticker, periodSeconds, callback, openBars); + unsubscribeFromTicker(ticker: string, periodSeconds: number, clientId: string, openBars = false): void { + this.relayClient.unsubscribeFromTicker(ticker, periodSeconds, clientId, openBars); } /** @@ -184,11 +184,9 @@ export class OHLCService { * rows from Iceberg. Edge gaps (data not yet ingested, in-progress candles) are * simply absent rows. Both are returned as-is; clients fill as appropriate. * - * Applies decimal correction: Nautilus stores prices/volumes as integers; - * divide by 10^price_precision and 10^size_precision to recover float values. */ private formatHistoryResult( - ticker: string, + _ticker: string, data: any[], // @ts-ignore start_time: bigint, @@ -208,30 +206,6 @@ export class OHLCService { // Convert to TradingView format (also converts BigInt fields to Number). let bars: TradingViewBar[] = data.map(backendToTradingView); - // Apply decimal correction using symbol metadata. - const symbolMeta = this.getSymbolIndex?.()?.getSymbolByTicker(ticker); - if (symbolMeta) { - const pricePrecision = symbolMeta.price_precision; - const sizePrecision = symbolMeta.size_precision; - if (pricePrecision != null && pricePrecision > 0) { - const priceDivisor = Math.pow(10, pricePrecision); - bars = bars.map(bar => ({ - ...bar, - open: bar.open / priceDivisor, - high: bar.high / priceDivisor, - low: bar.low / priceDivisor, - close: bar.close / priceDivisor, - })); - } - if (sizePrecision != null && sizePrecision > 0) { - const sizeDivisor = Math.pow(10, sizePrecision); - bars = bars.map(bar => ({ - ...bar, - volume: bar.volume != null ? bar.volume / sizeDivisor : bar.volume, - })); - } - } - bars.sort((a, b) => a.time - b.time); if (countback && bars.length > countback) { diff --git a/gateway/src/tools/mcp/mcp-tool-wrapper.ts b/gateway/src/tools/mcp/mcp-tool-wrapper.ts index 002d7b24..7d28c85d 100644 --- a/gateway/src/tools/mcp/mcp-tool-wrapper.ts +++ b/gateway/src/tools/mcp/mcp-tool-wrapper.ts @@ -58,6 +58,19 @@ export function createMCPToolWrapper( parsed?.success && parsed?.data !== undefined ) { const storeName = (input as any).store_name as string; + // Validate shapes store structure before applying — guards against + // agent-generated patches that corrupt the { shapes: {} } wrapper + if (storeName === 'shapes') { + const s = parsed.data as any; + if (!s || typeof s !== 'object' || !('shapes' in s) || + typeof s.shapes !== 'object' || Array.isArray(s.shapes)) { + logger.error( + { storeName, data: parsed.data }, + 'WorkspacePatch returned malformed shapes state — skipping sync' + ); + continue; + } + } onWorkspaceMutation(storeName, parsed.data); } // PythonWrite / PythonEdit / PythonDelete / PythonRevert: diff --git a/gateway/src/tools/platform/index.ts b/gateway/src/tools/platform/index.ts index da53845b..c4f7a9d7 100644 --- a/gateway/src/tools/platform/index.ts +++ b/gateway/src/tools/platform/index.ts @@ -19,3 +19,8 @@ export { createMemoryLookupTool, type MemoryLookupToolConfig, } from './memory-lookup.tool.js'; + +export { + createShapesMutateTool, + type ShapesMutateToolConfig, +} from './shapes-mutate.tool.js'; diff --git a/gateway/src/tools/platform/shapes-mutate.tool.ts b/gateway/src/tools/platform/shapes-mutate.tool.ts new file mode 100644 index 00000000..3d04c3bb --- /dev/null +++ b/gateway/src/tools/platform/shapes-mutate.tool.ts @@ -0,0 +1,106 @@ +import { DynamicStructuredTool } from '@langchain/core/tools'; +import { z } from 'zod'; +import type { FastifyBaseLogger } from 'fastify'; +import type { WorkspaceManager } from '../../workspace/workspace-manager.js'; +import type { Shape, ShapesStore } from '../../workspace/types.js'; + +export interface ShapesMutateToolConfig { + workspaceManager: WorkspaceManager; + logger: FastifyBaseLogger; +} + +const pointSchema = z.object({ + time: z.number().describe('Unix timestamp in seconds'), + price: z.number(), + channel: z.string().optional(), +}); + +const shapeTypeEnum = z.enum([ + 'trend_line', 'horizontal_line', 'vertical_line', 'rectangle', + 'circle', 'arrow', 'fib_retracement', 'fib_trend_ext', + 'parallel_channel', 'pitchfork', 'gannbox_fan', 'path', + 'text', 'head_and_shoulders', +]); + +export function createShapesMutateTool(config: ShapesMutateToolConfig): DynamicStructuredTool { + const { workspaceManager, logger } = config; + + return new DynamicStructuredTool({ + name: 'ShapesMutate', + description: `Add, update, or remove chart drawings (trend lines, horizontal lines, Fibonacci retracements, rectangles, etc.) on the TradingView chart. + +Always read chartState first to get the current symbol and visible time range before placing points. + +Each call may mix add, update, and remove operations. At least one array must be non-empty. + +**Point timestamps** must be Unix seconds aligned to candle boundaries — the chart snaps them automatically. +**symbol** should match chartState.symbol (shapes only render for the matching symbol).`, + schema: z.object({ + add: z.array(z.object({ + id: z.string().describe('Unique ID you assign (e.g. "trendline-btc-1")'), + type: shapeTypeEnum.describe('Shape type'), + points: z.array(pointSchema).describe('Control points (count depends on type — trend_line needs 2, horizontal_line needs 1, etc.)'), + color: z.string().optional().describe('Hex color, e.g. "#2962FF"'), + line_width: z.number().optional().describe('Line width in pixels'), + line_style: z.enum(['solid', 'dashed', 'dotted']).optional(), + symbol: z.string().optional().describe('Trading pair in SYMBOL.EXCHANGE format'), + properties: z.record(z.any()).optional().describe('TradingView drawing override properties'), + })).optional().describe('Shapes to add'), + update: z.array(z.object({ + id: z.string().describe('ID of shape to update'), + color: z.string().optional(), + line_width: z.number().optional(), + line_style: z.enum(['solid', 'dashed', 'dotted']).optional(), + points: z.array(pointSchema).optional().describe('Replace all control points'), + properties: z.record(z.any()).optional(), + })).optional().describe('Shapes to update (partial — only provided fields are changed)'), + remove: z.array(z.string()).optional().describe('IDs of shapes to remove'), + }), + func: async ({ add, update, remove }) => { + const hasOps = (add?.length ?? 0) + (update?.length ?? 0) + (remove?.length ?? 0) > 0; + if (!hasOps) { + return 'Error: at least one of add, update, or remove must be non-empty'; + } + + try { + const state = workspaceManager.getState('shapes'); + const shapes: Record = { ...(state?.shapes ?? {}) }; + const now = Math.floor(Date.now() / 1000); + + for (const id of (remove ?? [])) { + delete shapes[id]; + } + + for (const upd of (update ?? [])) { + if (shapes[upd.id]) { + shapes[upd.id] = { ...shapes[upd.id], ...upd, modified_at: now }; + } else { + logger.warn({ id: upd.id }, 'ShapesMutate: update target not found'); + } + } + + for (const shape of (add ?? [])) { + shapes[shape.id] = { created_at: now, modified_at: now, ...shape }; + } + + await workspaceManager.setState('shapes', { shapes }); + + logger.info( + { added: add?.length ?? 0, updated: update?.length ?? 0, removed: remove?.length ?? 0 }, + 'ShapesMutate applied' + ); + + return JSON.stringify({ + added: add?.length ?? 0, + updated: update?.length ?? 0, + removed: remove?.length ?? 0, + shape_ids: Object.keys(shapes), + }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + logger.error({ err }, 'ShapesMutate failed'); + return `Error: ${msg}`; + } + }, + }); +} diff --git a/gateway/src/tools/tool-registry.ts b/gateway/src/tools/tool-registry.ts index 2f5670fc..cb85e63c 100644 --- a/gateway/src/tools/tool-registry.ts +++ b/gateway/src/tools/tool-registry.ts @@ -11,6 +11,7 @@ import { createGetTicker24hTool } from './platform/get-ticker24h.tool.js'; import { createWebSearchTool } from './platform/web-search.tool.js'; import { createFetchPageTool } from './platform/fetch-page.tool.js'; import { createArxivSearchTool } from './platform/arxiv-search.tool.js'; +import { createShapesMutateTool } from './platform/shapes-mutate.tool.js'; import { createMCPToolWrappers, type MCPToolInfo } from './mcp/mcp-tool-wrapper.js'; /** @@ -219,6 +220,17 @@ export class ToolRegistry { break; } + case 'ShapesMutate': { + const workspaceManager = sessionWorkspaceManager || + this.resolveService(this.platformServices.workspaceManager); + if (workspaceManager) { + tool = createShapesMutateTool({ workspaceManager, logger: this.logger }); + } else { + this.logger.warn('WorkspaceManager not available for ShapesMutate tool'); + } + break; + } + default: this.logger.warn({ tool: toolName }, 'Unknown platform tool'); return null; diff --git a/web/src/components/ChatPanel.vue b/web/src/components/ChatPanel.vue index bd833f2e..d3db57a2 100644 --- a/web/src/components/ChatPanel.vue +++ b/web/src/components/ChatPanel.vue @@ -191,8 +191,8 @@ const handleMessage = (data: WebSocketMessage) => { const newMessages: any[] = [systemMsg] - // Re-add the user's first message (content after the @Tag) - const userContent: string = pendingModelSwitchContent || data.rest || '' + // Re-add the user's first message if there was content beyond the @Tag + const userContent: string = (data.hasOtherContent && pendingModelSwitchContent) ? pendingModelSwitchContent : '' if (userContent) { const userMsgId = generateMessageId() lastSentMessageId = userMsgId @@ -494,9 +494,9 @@ const sendMessage = async (event: any) => { } if (modelSwitchUser) { - // Model switch: store content-after-tag for model_switched handler to re-insert. + // Model switch: store full message content for model_switched handler to re-insert as user bubble. // Don't add a user message bubble now — model_switched will set up the full initial state. - pendingModelSwitchContent = content.replace(`@${modelSwitchUser.username}`, '').trim() + pendingModelSwitchContent = content wsManager.send(wsMessage) isAgentProcessing.value = true return diff --git a/web/src/composables/useTradingViewDatafeed.ts b/web/src/composables/useTradingViewDatafeed.ts index 804fd472..cb04ad32 100644 --- a/web/src/composables/useTradingViewDatafeed.ts +++ b/web/src/composables/useTradingViewDatafeed.ts @@ -83,15 +83,29 @@ export class WebSocketDatafeed implements IBasicDataFeed { } private handleMessage(message: any): void { - // On reconnect the server sends a fresh 'connected' message. - // Any pending requests were sent on the old socket and will never be answered, - // so reject them immediately so TradingView can retry on the new connection. - if (message.type === 'connected' && this.pendingRequests.size > 0) { - console.warn('[TradingView Datafeed] WebSocket reconnected — rejecting', this.pendingRequests.size, 'stale pending request(s)') - for (const [requestId, pending] of this.pendingRequests) { - clearTimeout(pending.timeout) - pending.reject(new Error('WebSocket reconnected')) - this.pendingRequests.delete(requestId) + // On reconnect (or initial connect) the server sends a 'connected' message. + // Reject any stale pending requests from the old socket, then re-subscribe all + // active bar subscriptions so the server has the correct state. + if (message.type === 'connected') { + if (this.pendingRequests.size > 0) { + console.warn('[TradingView Datafeed] WebSocket reconnected — rejecting', this.pendingRequests.size, 'stale pending request(s)') + for (const [requestId, pending] of this.pendingRequests) { + clearTimeout(pending.timeout) + pending.reject(new Error('WebSocket reconnected')) + this.pendingRequests.delete(requestId) + } + } + if (this.subscriptions.size > 0) { + console.log('[TradingView Datafeed] Reconnected — re-subscribing', this.subscriptions.size, 'active bar subscription(s)') + for (const [guid, sub] of this.subscriptions) { + this.sendRequest({ + type: 'subscribe_bars', + symbol: sub.symbolInfo.ticker || sub.symbolInfo.name, + period_seconds: intervalToSeconds(sub.resolution), + subscription_id: guid, + bar_type: 'open', + }).catch(() => {}) + } } return }