Spaces:
Running on Zero
Running on Zero
deveshc23
fix: Add Python 3.10 StrEnum backward compatibility and set python_version 3.11 in README
b277794 Download src/drift_quant/portfolio/allocator.py from deveshc23/drift-quant: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/spaces/deveshc23/drift-quant/resolve/main/src/drift_quant/portfolio/allocator.py
- Command line
-
hf download hf://spaces/deveshc23/drift-quant/src/drift_quant/portfolio/allocator.py
-
curl -L -o allocator.py https://huggingface.co/spaces/deveshc23/drift-quant/resolve/main/src/drift_quant/portfolio/allocator.py
14.2 kB
| """Quantitative portfolio construction, weighting models, and risk allocation.""" | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass | |
| from typing import Any | |
| try: | |
| from enum import StrEnum | |
| except ImportError: | |
| from enum import Enum | |
| class StrEnum(str, Enum): # noqa: UP042 | |
| def __str__(self) -> str: | |
| return str(self.value) | |
| class AllocationModel(StrEnum): | |
| EQUAL_WEIGHT = "equal_weight" | |
| INVERSE_VOLATILITY = "inverse_volatility" | |
| RISK_PARITY = "risk_parity" | |
| MULTI_FACTOR_MOMENTUM = "multi_factor_momentum" | |
| MINIMUM_VARIANCE = "minimum_variance" | |
| class AssetAllocation: | |
| symbol: str | |
| sector: str | |
| weight: float | |
| volatility: float | |
| momentum_return: float | |
| marginal_risk_contribution: float | |
| class AllocationResult: | |
| model: str | |
| constituents_count: int | |
| portfolio_volatility: float | |
| effective_n: float | |
| diversification_ratio: float | |
| max_single_weight: float | |
| sector_weights: dict[str, float] | |
| allocations: list[AssetAllocation] | |
| def to_dict(self) -> dict[str, Any]: | |
| return { | |
| "model": self.model, | |
| "constituents_count": self.constituents_count, | |
| "portfolio_volatility": round(self.portfolio_volatility, 4), | |
| "effective_n": round(self.effective_n, 2), | |
| "diversification_ratio": round(self.diversification_ratio, 3), | |
| "max_single_weight": round(self.max_single_weight, 4), | |
| "sector_weights": {k: round(v, 4) for k, v in sorted(self.sector_weights.items())}, | |
| "allocations": [ | |
| { | |
| "symbol": a.symbol, | |
| "sector": a.sector, | |
| "weight": round(a.weight, 4), | |
| "volatility": round(a.volatility, 4), | |
| "momentum_return": round(a.momentum_return, 4), | |
| "marginal_risk_contribution": round(a.marginal_risk_contribution, 4), | |
| } | |
| for a in self.allocations | |
| ], | |
| } | |
| class PortfolioAllocator: | |
| """Quantitative portfolio allocator implementing smart beta and risk budgeting.""" | |
| def __init__(self, sector_map: dict[str, str] | None = None) -> None: | |
| self.sector_map = sector_map or {} | |
| def compute_daily_returns( | |
| self, bars_by_symbol: dict[str, list[dict[str, Any]]] | |
| ) -> tuple[list[str], list[str], dict[str, list[float]]]: | |
| """Align bar series across symbols and compute percentage returns.""" | |
| # Find intersecting timestamps or group by date | |
| daily_closes: dict[str, dict[str, float]] = {} | |
| for sym, bars in bars_by_symbol.items(): | |
| daily_closes[sym] = {} | |
| for b in bars: | |
| day = b["timestamp"][:10] | |
| daily_closes[sym][day] = b["close"] | |
| # Intersect trading days | |
| symbols = sorted(bars_by_symbol.keys()) | |
| if not symbols: | |
| return [], [], {} | |
| common_days = set(daily_closes[symbols[0]].keys()) | |
| for s in symbols[1:]: | |
| common_days.intersection_update(daily_closes[s].keys()) | |
| sorted_days = sorted(common_days) | |
| if len(sorted_days) < 2: | |
| return symbols, [], {s: [] for s in symbols} | |
| returns: dict[str, list[float]] = {s: [] for s in symbols} | |
| for s in symbols: | |
| prices = [daily_closes[s][day] for day in sorted_days] | |
| for i in range(1, len(prices)): | |
| prev = prices[i - 1] | |
| curr = prices[i] | |
| ret = (curr - prev) / prev if prev > 0 else 0.0 | |
| returns[s].append(ret) | |
| return symbols, sorted_days[1:], returns | |
| def compute_covariance( | |
| self, symbols: list[str], returns: dict[str, list[float]] | |
| ) -> tuple[dict[str, float], list[list[float]]]: | |
| """Compute annualized volatilities and sample covariance matrix.""" | |
| n_assets = len(symbols) | |
| if n_assets == 0: | |
| return {}, [] | |
| t_samples = len(returns[symbols[0]]) | |
| if t_samples < 2: | |
| return {s: 0.20 for s in symbols}, [ | |
| [1.0 if i == j else 0.0 for j in range(n_assets)] for i in range(n_assets) | |
| ] | |
| # Sample means | |
| means = {s: sum(returns[s]) / t_samples for s in symbols} | |
| # Volatilities (annualized assuming 252 trading days) | |
| vols: dict[str, float] = {} | |
| for s in symbols: | |
| var = sum((r - means[s]) ** 2 for r in returns[s]) / (t_samples - 1) | |
| vols[s] = math.sqrt(max(1e-8, var)) * math.sqrt(252) | |
| # Covariance matrix (annualized) | |
| cov: list[list[float]] = [[0.0] * n_assets for _ in range(n_assets)] | |
| for i in range(n_assets): | |
| s_i = symbols[i] | |
| mean_i = means[s_i] | |
| for j in range(i, n_assets): | |
| s_j = symbols[j] | |
| mean_j = means[s_j] | |
| cov_ij = ( | |
| sum( | |
| (returns[s_i][k] - mean_i) * (returns[s_j][k] - mean_j) | |
| for k in range(t_samples) | |
| ) | |
| / (t_samples - 1) | |
| ) * 252 | |
| cov[i][j] = cov_ij | |
| cov[j][i] = cov_ij | |
| return vols, cov | |
| def shrink_covariance( | |
| self, cov: list[list[float]], shrinkage: float = 0.20 | |
| ) -> list[list[float]]: | |
| """Ledoit-Wolf style constant correlation shrinkage to condition covariance.""" | |
| n = len(cov) | |
| if n <= 1: | |
| return cov | |
| # Compute diagonal standard deviations | |
| stds = [math.sqrt(max(1e-8, cov[i][i])) for i in range(n)] | |
| # Compute average correlation | |
| corrs = [] | |
| for i in range(n): | |
| for j in range(i + 1, n): | |
| corr = cov[i][j] / (stds[i] * stds[j]) | |
| corrs.append(corr) | |
| mean_corr = sum(corrs) / len(corrs) if corrs else 0.0 | |
| # Target matrix F with constant correlation | |
| shrunk = [[0.0] * n for _ in range(n)] | |
| for i in range(n): | |
| for j in range(n): | |
| target = stds[i] * stds[j] if i == j else mean_corr * stds[i] * stds[j] | |
| shrunk[i][j] = (1.0 - shrinkage) * cov[i][j] + shrinkage * target | |
| return shrunk | |
| def allocate( | |
| self, | |
| model: AllocationModel | str, | |
| bars_by_symbol: dict[str, list[dict[str, Any]]], | |
| max_stock_cap: float = 0.15, | |
| max_sector_cap: float = 0.35, | |
| ) -> AllocationResult: | |
| """Construct optimal portfolio weights according to chosen quant strategy.""" | |
| if isinstance(model, str): | |
| model = AllocationModel(model) | |
| symbols, _days, returns = self.compute_daily_returns(bars_by_symbol) | |
| n = len(symbols) | |
| if n == 0: | |
| return AllocationResult( | |
| model=model.value, | |
| constituents_count=0, | |
| portfolio_volatility=0.0, | |
| effective_n=0.0, | |
| diversification_ratio=0.0, | |
| max_single_weight=0.0, | |
| sector_weights={}, | |
| allocations=[], | |
| ) | |
| vols, cov = self.compute_covariance(symbols, returns) | |
| shrunk_cov = self.shrink_covariance(cov, shrinkage=0.25) | |
| # Compute momentum returns (e.g. cumulative return over available window) | |
| momentum_rets: dict[str, float] = {} | |
| for s in symbols: | |
| s_bars = bars_by_symbol[s] | |
| if len(s_bars) >= 2: | |
| p_start = s_bars[0]["close"] | |
| p_end = s_bars[-1]["close"] | |
| momentum_rets[s] = (p_end - p_start) / p_start if p_start > 0 else 0.0 | |
| else: | |
| momentum_rets[s] = 0.0 | |
| # 1. Compute Raw Uncapped Weights | |
| raw_weights: dict[str, float] = {} | |
| if model == AllocationModel.EQUAL_WEIGHT: | |
| w_eq = 1.0 / n | |
| raw_weights = {s: w_eq for s in symbols} | |
| elif model == AllocationModel.INVERSE_VOLATILITY: | |
| inv_vols = {s: 1.0 / max(0.01, vols[s]) for s in symbols} | |
| sum_inv = sum(inv_vols.values()) | |
| raw_weights = {s: inv_vols[s] / sum_inv for s in symbols} | |
| elif model == AllocationModel.RISK_PARITY: | |
| # Cyclical coordinate descent for Equal Risk Contribution | |
| # Initialize with inverse vol | |
| w = [1.0 / max(0.01, vols[s]) for s in symbols] | |
| sum_w = sum(w) | |
| w = [x / sum_w for x in w] | |
| # Coordinate descent iterations | |
| for _ in range(50): | |
| for i in range(n): | |
| # Marginal contribution of asset i: (Sigma * w)_i | |
| sigma_w_i = sum(shrunk_cov[i][j] * w[j] for j in range(n)) | |
| # Solve quadratic for w_i: w_i * (sigma_w_i) = target_risk * total_var | |
| # Updating step with dampening | |
| denom = shrunk_cov[i][i] | |
| if denom > 1e-8: | |
| a = denom | |
| b = sigma_w_i - w[i] * denom | |
| # Root of a*x^2 + b*x - target = 0 | |
| disc = b * b + 4 * a * 0.001 | |
| if disc >= 0: | |
| new_wi = (-b + math.sqrt(disc)) / (2 * a) | |
| w[i] = max(1e-4, 0.8 * w[i] + 0.2 * new_wi) | |
| # Re-normalize | |
| total_w = sum(w) | |
| if total_w > 0: | |
| w = [x / total_w for x in w] | |
| raw_weights = {symbols[i]: w[i] for i in range(n)} | |
| elif model == AllocationModel.MULTI_FACTOR_MOMENTUM: | |
| # Cross-sectional Z-score blending: | |
| # Factor Score = 0.6 * Z(Momentum) - 0.4 * Z(Volatility) | |
| mom_values = [momentum_rets[s] for s in symbols] | |
| vol_values = [vols[s] for s in symbols] | |
| mean_mom = sum(mom_values) / n | |
| std_mom = max( | |
| 1e-4, math.sqrt(sum((x - mean_mom) ** 2 for x in mom_values) / max(1, n - 1)) | |
| ) | |
| mean_vol = sum(vol_values) / n | |
| std_vol = max( | |
| 1e-4, math.sqrt(sum((x - mean_vol) ** 2 for x in vol_values) / max(1, n - 1)) | |
| ) | |
| scores = {} | |
| for s in symbols: | |
| z_mom = (momentum_rets[s] - mean_mom) / std_mom | |
| z_vol = (vols[s] - mean_vol) / std_vol | |
| composite = 0.6 * z_mom - 0.4 * z_vol | |
| scores[s] = math.exp( | |
| min(2.5, max(-2.5, composite)) | |
| ) # Softmax-style positive exponent | |
| sum_scores = sum(scores.values()) | |
| raw_weights = {s: scores[s] / sum_scores for s in symbols} | |
| elif model == AllocationModel.MINIMUM_VARIANCE: | |
| # Diagonal inverse approximation with shrinkage | |
| inv_vars = {s: 1.0 / max(1e-4, vols[s] ** 2) for s in symbols} | |
| sum_inv_var = sum(inv_vars.values()) | |
| raw_weights = {s: inv_vars[s] / sum_inv_var for s in symbols} | |
| # 2. Apply Caps & Constraints (SEBI Regulatory Guidelines) | |
| # Cap max single-stock weight, reallocate excess iteratively | |
| capped_weights = dict(raw_weights) | |
| for _ in range(15): | |
| excess = 0.0 | |
| uncapped_sum = 0.0 | |
| for s, weight in capped_weights.items(): | |
| if weight > max_stock_cap: | |
| excess += weight - max_stock_cap | |
| capped_weights[s] = max_stock_cap | |
| else: | |
| uncapped_sum += weight | |
| if excess <= 1e-5 or uncapped_sum <= 1e-5: | |
| break | |
| # Redistribute excess proportionally | |
| for s, weight in capped_weights.items(): | |
| if weight < max_stock_cap: | |
| capped_weights[s] += excess * (weight / uncapped_sum) | |
| # Normalize to exactly 1.0 | |
| final_sum = sum(capped_weights.values()) | |
| final_weights = {s: w / final_sum for s, w in capped_weights.items()} | |
| # 3. Compute Portfolio Risk Analytics | |
| w_vec = [final_weights[s] for s in symbols] | |
| port_var = 0.0 | |
| marginal_risks: list[float] = [] | |
| for i in range(n): | |
| row_cov = sum(shrunk_cov[i][j] * w_vec[j] for j in range(n)) | |
| port_var += w_vec[i] * row_cov | |
| port_vol = math.sqrt(max(1e-8, port_var)) | |
| # Marginal risk contributions: (w_i * (Sigma * w)_i) / port_vol | |
| for i in range(n): | |
| row_cov = sum(shrunk_cov[i][j] * w_vec[j] for j in range(n)) | |
| mrc = (w_vec[i] * row_cov) / port_vol if port_vol > 0 else 0.0 | |
| marginal_risks.append(mrc) | |
| # Diversification Ratio = Weighted Vol / Portfolio Vol | |
| weighted_vol = sum(w_vec[i] * vols[symbols[i]] for i in range(n)) | |
| diversification_ratio = weighted_vol / port_vol if port_vol > 0 else 1.0 | |
| # Effective N (Herfindahl Index Inverse: 1 / sum(w_i^2)) | |
| effective_n = 1.0 / sum(w**2 for w in w_vec) if sum(w**2 for w in w_vec) > 0 else float(n) | |
| # Sector weights breakdown | |
| sector_weights: dict[str, float] = {} | |
| for s, w in final_weights.items(): | |
| sec = self.sector_map.get(s, "Diversified / Other") | |
| sector_weights[sec] = sector_weights.get(sec, 0.0) + w | |
| allocations = [ | |
| AssetAllocation( | |
| symbol=symbols[i], | |
| sector=self.sector_map.get(symbols[i], "Diversified / Other"), | |
| weight=final_weights[symbols[i]], | |
| volatility=vols[symbols[i]], | |
| momentum_return=momentum_rets[symbols[i]], | |
| marginal_risk_contribution=marginal_risks[i], | |
| ) | |
| for i in range(n) | |
| ] | |
| allocations.sort(key=lambda a: -a.weight) | |
| return AllocationResult( | |
| model=model.value, | |
| constituents_count=n, | |
| portfolio_volatility=port_vol, | |
| effective_n=effective_n, | |
| diversification_ratio=diversification_ratio, | |
| max_single_weight=max(final_weights.values()), | |
| sector_weights=sector_weights, | |
| allocations=allocations, | |
| ) | |