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

View File

@@ -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., 520%) |
| 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.

View File

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

View File

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

View File

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

View File

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