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
This commit is contained in:
2026-04-28 15:05:15 -04:00
parent d41fcd0499
commit 47471b7700
184 changed files with 9044 additions and 170 deletions

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.