-
Notifications
You must be signed in to change notification settings - Fork 10
Build initial beta/regime risk management features #787
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
forstmeier
merged 6 commits into
statistical-arbitrage-phase-two
from
statistical-arbitrage-phase-three
Mar 9, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
924b0d8
Build initial beta/regime risk management features
forstmeier 3e1dcb9
Fix off-by-one guard and dead code in classify_regime; annotate compu…
forstmeier f710475
Address PR #787 review feedback: NaN guard, zero-weight guard, confid…
forstmeier 4968dde
Address PR #787 review feedback: beta guard off-by-one, float equalit…
forstmeier ee568c3
Guard SPY prices against non-positive values before np.log in beta an…
forstmeier 3b38a1f
Update floating-point equality operation
forstmeier File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
76 changes: 76 additions & 0 deletions
76
applications/portfoliomanager/src/portfoliomanager/beta.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import numpy as np | ||
| import polars as pl | ||
| import scipy.stats | ||
|
|
||
| BETA_WINDOW_DAYS = 60 | ||
|
|
||
| _TRADING_DAYS_PER_YEAR = 252 | ||
| _MINIMUM_RETURN_COUNT = 2 | ||
|
|
||
|
|
||
| def compute_market_betas( | ||
| historical_prices: pl.DataFrame, | ||
| spy_prices: pl.DataFrame, | ||
|
forstmeier marked this conversation as resolved.
|
||
| window_days: int = BETA_WINDOW_DAYS, | ||
| ) -> pl.DataFrame: | ||
| spy_close = ( | ||
| spy_prices.sort("timestamp").tail(window_days + 1)["close_price"].to_numpy() | ||
| ) | ||
|
|
||
| if len(spy_close) < _MINIMUM_RETURN_COUNT + 1 or np.any(spy_close <= 0): | ||
| return pl.DataFrame(schema={"ticker": pl.String, "market_beta": pl.Float64}) | ||
|
|
||
| spy_returns = np.diff(np.log(spy_close)) | ||
|
forstmeier marked this conversation as resolved.
|
||
| tickers = historical_prices["ticker"].unique().to_list() | ||
| results = [] | ||
|
|
||
| for ticker in tickers: | ||
| ticker_close = ( | ||
| historical_prices.filter(pl.col("ticker") == ticker) | ||
| .sort("timestamp") | ||
| .tail(window_days + 1)["close_price"] | ||
| .to_numpy() | ||
| ) | ||
| if len(ticker_close) < _MINIMUM_RETURN_COUNT or np.any(ticker_close <= 0): | ||
| continue | ||
|
|
||
| ticker_returns = np.diff(np.log(ticker_close)) | ||
| count = min(len(spy_returns), len(ticker_returns)) | ||
| if count < _MINIMUM_RETURN_COUNT: | ||
| continue | ||
|
|
||
| slope, _, _, _, _ = scipy.stats.linregress( | ||
| spy_returns[-count:], ticker_returns[-count:] | ||
| ) | ||
| results.append({"ticker": ticker, "market_beta": float(slope)}) | ||
|
|
||
| if not results: | ||
| return pl.DataFrame(schema={"ticker": pl.String, "market_beta": pl.Float64}) | ||
|
|
||
| return pl.DataFrame(results) | ||
|
|
||
|
|
||
| # Validates beta neutralization in tests; retained for future beta reporting. | ||
| def compute_portfolio_beta( | ||
| portfolio: pl.DataFrame, | ||
| market_betas: pl.DataFrame, | ||
| ) -> float: | ||
|
forstmeier marked this conversation as resolved.
|
||
| beta_lookup = dict( | ||
| zip( | ||
| market_betas["ticker"].to_list(), | ||
| market_betas["market_beta"].to_list(), | ||
| strict=False, | ||
| ) | ||
| ) | ||
|
|
||
| total_gross = portfolio["dollar_amount"].sum() | ||
| if np.isclose(total_gross, 0.0): | ||
| return 0.0 | ||
|
|
||
| net_beta = 0.0 | ||
| for row in portfolio.iter_rows(named=True): | ||
| beta = beta_lookup.get(row["ticker"], 0.0) | ||
| sign = 1.0 if row["side"] == "LONG" else -1.0 | ||
| net_beta += sign * (row["dollar_amount"] / total_gross) * beta | ||
|
|
||
| return net_beta | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
applications/portfoliomanager/src/portfoliomanager/regime.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| from typing import TypedDict | ||
|
|
||
| import numpy as np | ||
| import polars as pl | ||
|
|
||
|
|
||
| class RegimeResult(TypedDict): | ||
| state: str | ||
| confidence: float | ||
|
|
||
|
|
||
| REGIME_WINDOW_DAYS = 60 | ||
| REGIME_VOLATILITY_THRESHOLD = 0.20 | ||
| REGIME_AUTOCORRELATION_THRESHOLD = 0.0 | ||
|
|
||
| _TRADING_DAYS_PER_YEAR = 252 | ||
| _MINIMUM_RETURN_COUNT = 2 | ||
|
|
||
|
|
||
| def classify_regime( | ||
| spy_prices: pl.DataFrame, | ||
| window_days: int = REGIME_WINDOW_DAYS, | ||
| ) -> RegimeResult: | ||
|
forstmeier marked this conversation as resolved.
|
||
| spy_close = ( | ||
| spy_prices.sort("timestamp").tail(window_days + 1)["close_price"].to_numpy() | ||
| ) | ||
|
|
||
| if np.any(spy_close <= 0): | ||
| return {"state": "trending", "confidence": 0.0} | ||
|
|
||
| returns = np.diff(np.log(spy_close)) | ||
|
|
||
| # Sparse data defaults to trending/0.0, halving exposure in the caller. | ||
| if len(returns) < _MINIMUM_RETURN_COUNT + 1: | ||
| return {"state": "trending", "confidence": 0.0} | ||
|
|
||
| realized_volatility = float( | ||
| np.std(returns, ddof=1) * np.sqrt(_TRADING_DAYS_PER_YEAR) | ||
| ) | ||
|
|
||
| autocorrelation = float(np.corrcoef(returns[:-1], returns[1:])[0, 1]) | ||
|
|
||
| low_volatility = realized_volatility < REGIME_VOLATILITY_THRESHOLD | ||
| mean_reverting_signal = autocorrelation < REGIME_AUTOCORRELATION_THRESHOLD | ||
|
|
||
| if low_volatility and mean_reverting_signal: | ||
| volatility_margin = ( | ||
| REGIME_VOLATILITY_THRESHOLD - realized_volatility | ||
| ) / REGIME_VOLATILITY_THRESHOLD | ||
| autocorrelation_margin = min(1.0, -autocorrelation) | ||
| confidence = float( | ||
| np.clip((volatility_margin + autocorrelation_margin) / 2.0, 0.0, 1.0) | ||
| ) | ||
| return {"state": "mean_reversion", "confidence": confidence} | ||
|
|
||
| excess_volatility = max( | ||
| 0.0, | ||
| (realized_volatility - REGIME_VOLATILITY_THRESHOLD) | ||
| / REGIME_VOLATILITY_THRESHOLD, | ||
| ) | ||
| excess_autocorrelation = max( | ||
| 0.0, autocorrelation - REGIME_AUTOCORRELATION_THRESHOLD | ||
| ) | ||
| confidence = float( | ||
| np.clip((excess_volatility + excess_autocorrelation) / 2.0, 0.0, 1.0) | ||
| ) | ||
| return {"state": "trending", "confidence": confidence} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.