File size: 14,199 Bytes
3e33e2e
 
 
 
 
 
 
 
b277794
 
 
 
 
 
 
 
 
3e33e2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""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"


@dataclass(frozen=True)
class AssetAllocation:
    symbol: str
    sector: str
    weight: float
    volatility: float
    momentum_return: float
    marginal_risk_contribution: float


@dataclass(frozen=True)
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,
        )