File size: 11,407 Bytes
72c80ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Portfolio Optimizer - Risk-aware allocation engine."""
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from typing import Dict, List, Optional, Tuple
import warnings
warnings.filterwarnings('ignore')


class PortfolioOptimizer:
    """Portfolio optimizer with constraints and robust optimization"""
    
    def __init__(self, 
                 max_weight: float = 0.20,
                 min_weight: float = 0.0,
                 target_return: Optional[float] = None,
                 risk_free_rate: float = 0.04,
                 transaction_cost: float = 0.0003,
                 turnover_penalty: float = 0.001,
                 risk_aversion: float = 1.0):
        self.max_weight = max_weight
        self.min_weight = min_weight
        self.target_return = target_return
        self.risk_free_rate = risk_free_rate
        self.transaction_cost = transaction_cost
        self.turnover_penalty = turnover_penalty
        self.risk_aversion = risk_aversion
        
    def optimize_mean_variance(self, 
                                mu: np.ndarray,
                                Sigma: np.ndarray,
                                current_weights: Optional[np.ndarray] = None,
                                long_only: bool = True) -> Dict:
        """
        Mean-variance optimization with transaction costs
        
        Args:
            mu: Expected returns vector (n_assets,)
            Sigma: Covariance matrix (n_assets, n_assets)
            current_weights: Current portfolio weights (n_assets,)
            long_only: If True, weights must be >= 0
        
        Returns:
            Dict with weights, expected_return, volatility, sharpe
        """
        n_assets = len(mu)
        
        # Objective: maximize utility = return - risk_aversion * variance - transaction_costs
        def objective(w):
            port_return = np.dot(w, mu)
            port_variance = np.dot(w, np.dot(Sigma, w))
            
            # Transaction cost penalty
            if current_weights is not None:
                turnover = np.sum(np.abs(w - current_weights))
                tc_penalty = self.turnover_penalty * turnover
            else:
                tc_penalty = 0
            
            # Negative utility (for minimization)
            return -(port_return - self.risk_aversion * port_variance - tc_penalty)
        
        # Constraints
        constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]  # Fully invested
        
        if self.target_return is not None:
            constraints.append(
                {'type': 'eq', 'fun': lambda w: np.dot(w, mu) - self.target_return}
            )
        
        # Bounds
        if long_only:
            bounds = [(self.min_weight, self.max_weight) for _ in range(n_assets)]
        else:
            bounds = [(-self.max_weight, self.max_weight) for _ in range(n_assets)]
        
        # Initial guess: equal weight
        w0 = np.ones(n_assets) / n_assets
        
        # Optimize
        result = minimize(
            objective,
            w0,
            method='SLSQP',
            bounds=bounds,
            constraints=constraints,
            options={'maxiter': 1000, 'ftol': 1e-9}
        )
        
        if not result.success:
            print(f"Optimization warning: {result.message}")
        
        weights = result.x
        weights = np.maximum(weights, 0)  # Clean small negatives
        weights /= np.sum(weights)  # Renormalize
        
        # Compute portfolio metrics
        port_return = np.dot(weights, mu)
        port_vol = np.sqrt(np.dot(weights, np.dot(Sigma, weights)))
        sharpe = (port_return - self.risk_free_rate) / port_vol if port_vol > 0 else 0
        
        return {
            'weights': weights,
            'expected_return': port_return,
            'volatility': port_vol,
            'sharpe_ratio': sharpe,
            'success': result.success
        }
    
    def optimize_max_sharpe(self,
                            mu: np.ndarray,
                            Sigma: np.ndarray,
                            current_weights: Optional[np.ndarray] = None) -> Dict:
        """Optimize for maximum Sharpe ratio"""
        n_assets = len(mu)
        
        def neg_sharpe(w):
            port_return = np.dot(w, mu)
            port_vol = np.sqrt(np.dot(w, np.dot(Sigma, w)))
            
            if current_weights is not None:
                turnover = np.sum(np.abs(w - current_weights))
                port_return -= self.turnover_penalty * turnover
            
            return -(port_return - self.risk_free_rate) / (port_vol + 1e-8)
        
        constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]
        bounds = [(self.min_weight, self.max_weight) for _ in range(n_assets)]
        w0 = np.ones(n_assets) / n_assets
        
        result = minimize(
            neg_sharpe,
            w0,
            method='SLSQP',
            bounds=bounds,
            constraints=constraints,
            options={'maxiter': 1000}
        )
        
        weights = result.x
        weights = np.maximum(weights, 0)
        weights /= np.sum(weights)
        
        port_return = np.dot(weights, mu)
        port_vol = np.sqrt(np.dot(weights, np.dot(Sigma, weights)))
        sharpe = (port_return - self.risk_free_rate) / port_vol
        
        return {
            'weights': weights,
            'expected_return': port_return,
            'volatility': port_vol,
            'sharpe_ratio': sharpe,
            'success': result.success
        }
    
    def optimize_min_volatility(self,
                                 mu: np.ndarray,
                                 Sigma: np.ndarray,
                                 min_return: Optional[float] = None) -> Dict:
        """Optimize for minimum volatility with optional return constraint"""
        n_assets = len(mu)
        
        def variance(w):
            return np.dot(w, np.dot(Sigma, w))
        
        constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]
        
        if min_return is not None:
            constraints.append(
                {'type': 'ineq', 'fun': lambda w: np.dot(w, mu) - min_return}
            )
        
        bounds = [(self.min_weight, self.max_weight) for _ in range(n_assets)]
        w0 = np.ones(n_assets) / n_assets
        
        result = minimize(
            variance,
            w0,
            method='SLSQP',
            bounds=bounds,
            constraints=constraints,
            options={'maxiter': 1000}
        )
        
        weights = result.x
        weights = np.maximum(weights, 0)
        weights /= np.sum(weights)
        
        port_return = np.dot(weights, mu)
        port_vol = np.sqrt(np.dot(weights, np.dot(Sigma, weights)))
        sharpe = (port_return - self.risk_free_rate) / port_vol if port_vol > 0 else 0
        
        return {
            'weights': weights,
            'expected_return': port_return,
            'volatility': port_vol,
            'sharpe_ratio': sharpe,
            'success': result.success
        }
    
    def robust_optimization(self,
                            mu: np.ndarray,
                            Sigma: np.ndarray,
                            mu_uncertainty: Optional[np.ndarray] = None,
                            Sigma_uncertainty: Optional[float] = None) -> Dict:
        """
        Robust optimization with uncertainty sets
        
        Uses worst-case approach: optimize for worst-case mu within uncertainty ellipsoid
        """
        n_assets = len(mu)
        
        if mu_uncertainty is None:
            # Default: 20% uncertainty on expected returns
            mu_uncertainty = np.abs(mu) * 0.2
        
        # Worst-case return: mu - uncertainty
        mu_worst = mu - mu_uncertainty
        
        # Add covariance uncertainty
        if Sigma_uncertainty is not None:
            Sigma_robust = Sigma + np.eye(n_assets) * Sigma_uncertainty
        else:
            Sigma_robust = Sigma
        
        return self.optimize_mean_variance(mu_worst, Sigma_robust)
    
    def black_litterman(self,
                        market_caps: np.ndarray,
                        Sigma: np.ndarray,
                        risk_aversion: float = 2.5,
                        views: Optional[List[Dict]] = None,
                        view_confidence: float = 0.5) -> Dict:
        """
        Black-Litterman model for incorporating investor views
        
        Args:
            market_caps: Market capitalization weights
            Sigma: Covariance matrix
            risk_aversion: Risk aversion parameter
            views: List of view dicts with 'assets', 'direction', 'magnitude'
            view_confidence: Confidence in views (0-1)
        """
        n_assets = len(market_caps)
        
        # Implied equilibrium returns
        Pi = risk_aversion * np.dot(Sigma, market_caps)
        
        if views is None or len(views) == 0:
            # No views: use market equilibrium
            return self.optimize_mean_variance(Pi, Sigma)
        
        # Build view matrix P and view vector Q
        P = []
        Q = []
        Omega_diag = []
        
        for view in views:
            assets = view['assets']
            direction = view['direction']  # 'overweight' or 'underweight'
            magnitude = view['magnitude']
            
            p_row = np.zeros(n_assets)
            for asset in assets:
                p_row[asset] = 1.0 / len(assets)
            
            P.append(p_row)
            Q.append(magnitude if direction == 'overweight' else -magnitude)
            Omega_diag.append(view_confidence)
        
        P = np.array(P)
        Q = np.array(Q)
        Omega = np.diag(Omega_diag)
        
        # Black-Litterman formula
        tau = 0.05  # Uncertainty scaling
        
        M_inverse = np.linalg.inv(tau * Sigma)
        middle = np.linalg.inv(np.dot(np.dot(P, tau * Sigma), P.T) + Omega)
        
        BL_mu = Pi + np.dot(
            np.dot(tau * Sigma, P.T),
            np.dot(middle, Q - np.dot(P, Pi))
        )
        
        BL_Sigma = Sigma + tau * Sigma - np.dot(
            np.dot(tau * Sigma, P.T),
            np.dot(middle, np.dot(P, tau * Sigma))
        )
        
        return self.optimize_mean_variance(BL_mu, BL_Sigma)
    
    def compute_efficient_frontier(self,
                                    mu: np.ndarray,
                                    Sigma: np.ndarray,
                                    n_points: int = 50) -> pd.DataFrame:
        """Compute efficient frontier points"""
        min_vol_result = self.optimize_min_volatility(mu, Sigma)
        max_ret_result = self.optimize_mean_variance(mu, Sigma, target_return=np.max(mu))
        
        min_ret = min_vol_result['expected_return']
        max_ret = max_ret_result['expected_return']
        
        target_returns = np.linspace(min_ret, max_ret, n_points)
        
        frontier = []
        for target in target_returns:
            result = self.optimize_mean_variance(mu, Sigma, target_return=target)
            frontier.append({
                'target_return': target,
                'volatility': result['volatility'],
                'sharpe': result['sharpe_ratio']
            })
        
        return pd.DataFrame(frontier)