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: "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).

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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.13.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 25 (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.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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 310 trading days
- **Middle MA length T_2**: Typically 1021 trading days
- **Long MA length T_3**: Typically 2150 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.

View File

@@ -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 1050 trading days
- **Long MA length T**: Typically 30200 trading days; T' < T required
- **MA type**: SMA or EMA for both
- **Stop-loss threshold Delta**: Typically 13% (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.

View File

@@ -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 16 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 16 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 16 months.
- Book value data lags the market; stale book values can introduce noise.
- Value strategies can suffer extended drawdowns during "growth" regimes.