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

View File

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

View File

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

View File

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

View File

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