Skip to content

Optimization API

PortfolioOptimizer

Portfolio optimization using various strategies.

Supports Maximum Sharpe Ratio, Minimum Volatility, Risk Parity, and Target Return optimization strategies.

Parameters:

Name Type Description Default
data DataFrame

Historical price data with datetime index

required
risk_free_rate float

Annual risk-free rate

0.02

Examples:

>>> optimizer = PortfolioOptimizer(data, risk_free_rate=0.02)
>>> optimal = optimizer.optimize_max_sharpe()
>>> print(f"Optimal weights: {optimal['weights']}")
>>> optimizer.plot_efficient_frontier()
Source code in portfolio_analysis/analysis/optimization.py
 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
class PortfolioOptimizer:
    """
    Portfolio optimization using various strategies.

    Supports Maximum Sharpe Ratio, Minimum Volatility, Risk Parity,
    and Target Return optimization strategies.

    Parameters
    ----------
    data : pd.DataFrame
        Historical price data with datetime index
    risk_free_rate : float, default 0.02
        Annual risk-free rate

    Examples
    --------
    >>> optimizer = PortfolioOptimizer(data, risk_free_rate=0.02)
    >>> optimal = optimizer.optimize_max_sharpe()
    >>> print(f"Optimal weights: {optimal['weights']}")
    >>> optimizer.plot_efficient_frontier()
    """

    TRADING_DAYS = TRADING_DAYS_PER_YEAR

    def __init__(
        self, data: pd.DataFrame, risk_free_rate: float = DEFAULT_RISK_FREE_RATE
    ):
        self.data = data
        self.risk_free_rate = risk_free_rate
        self.n_assets = len(data.columns)
        self.tickers = list(data.columns)

        # Calculate returns and covariance
        self.returns = data.pct_change().dropna()
        self.mean_returns = self.returns.mean() * self.TRADING_DAYS
        self.cov_matrix = self.returns.cov() * self.TRADING_DAYS

    def _portfolio_return(self, weights: np.ndarray) -> float:
        """Calculate portfolio expected return."""
        return np.dot(weights, self.mean_returns)

    def _portfolio_volatility(self, weights: np.ndarray) -> float:
        """Calculate portfolio volatility."""
        return np.sqrt(np.dot(weights.T, np.dot(self.cov_matrix, weights)))

    def _portfolio_sharpe(self, weights: np.ndarray) -> float:
        """Calculate portfolio Sharpe ratio."""
        ret = self._portfolio_return(weights)
        vol = self._portfolio_volatility(weights)
        return (ret - self.risk_free_rate) / vol

    def _neg_sharpe(self, weights: np.ndarray) -> float:
        """Negative Sharpe for minimization."""
        return -self._portfolio_sharpe(weights)

    def optimize_max_sharpe(self, weight_bounds: tuple[float, float] = (0, 1)) -> dict:
        """
        Find the portfolio with maximum Sharpe ratio.

        Parameters
        ----------
        weight_bounds : tuple, default (0, 1)
            Min and max weight for each asset

        Returns
        -------
        dict
            Optimal weights, return, volatility, and Sharpe ratio
        """
        constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
        bounds = tuple(weight_bounds for _ in range(self.n_assets))
        initial_weights = np.array([1 / self.n_assets] * self.n_assets)

        result = minimize(
            self._neg_sharpe,
            initial_weights,
            method="SLSQP",
            bounds=bounds,
            constraints=constraints,
        )

        optimal_weights = result.x
        return {
            "weights": dict(zip(self.tickers, optimal_weights)),
            "return": self._portfolio_return(optimal_weights),
            "volatility": self._portfolio_volatility(optimal_weights),
            "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
        }

    def optimize_min_volatility(
        self, weight_bounds: tuple[float, float] = (0, 1)
    ) -> dict:
        """
        Find the minimum volatility portfolio.

        Parameters
        ----------
        weight_bounds : tuple, default (0, 1)
            Min and max weight for each asset

        Returns
        -------
        dict
            Optimal weights, return, volatility, and Sharpe ratio
        """
        constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
        bounds = tuple(weight_bounds for _ in range(self.n_assets))
        initial_weights = np.array([1 / self.n_assets] * self.n_assets)

        result = minimize(
            self._portfolio_volatility,
            initial_weights,
            method="SLSQP",
            bounds=bounds,
            constraints=constraints,
        )

        optimal_weights = result.x
        return {
            "weights": dict(zip(self.tickers, optimal_weights)),
            "return": self._portfolio_return(optimal_weights),
            "volatility": self._portfolio_volatility(optimal_weights),
            "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
        }

    def optimize_target_return(
        self, target_return: float, weight_bounds: tuple[float, float] = (0, 1)
    ) -> dict:
        """
        Find minimum volatility portfolio for a target return.

        Parameters
        ----------
        target_return : float
            Target annual return
        weight_bounds : tuple, default (0, 1)
            Min and max weight for each asset

        Returns
        -------
        dict
            Optimal weights, return, volatility, and Sharpe ratio
        """
        constraints = [
            {"type": "eq", "fun": lambda x: np.sum(x) - 1},
            {"type": "eq", "fun": lambda x: self._portfolio_return(x) - target_return},
        ]
        bounds = tuple(weight_bounds for _ in range(self.n_assets))
        initial_weights = np.array([1 / self.n_assets] * self.n_assets)

        result = minimize(
            self._portfolio_volatility,
            initial_weights,
            method="SLSQP",
            bounds=bounds,
            constraints=constraints,
        )

        optimal_weights = result.x
        return {
            "weights": dict(zip(self.tickers, optimal_weights)),
            "return": self._portfolio_return(optimal_weights),
            "volatility": self._portfolio_volatility(optimal_weights),
            "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
        }

    def optimize_risk_parity(self) -> dict:
        """
        Find the risk parity portfolio (equal risk contribution).

        Each asset contributes equally to total portfolio risk.

        Returns
        -------
        dict
            Optimal weights, return, volatility, and Sharpe ratio
        """

        def risk_contribution(weights):
            """Calculate risk contribution of each asset."""
            port_vol = self._portfolio_volatility(weights)
            marginal_contrib = np.dot(self.cov_matrix, weights)
            risk_contrib = weights * marginal_contrib / port_vol
            return risk_contrib

        def risk_parity_objective(weights):
            """Objective: minimize deviation from equal risk contribution."""
            rc = risk_contribution(weights)
            target_rc = np.mean(rc)
            return np.sum((rc - target_rc) ** 2)

        constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
        bounds = tuple((0.01, 1) for _ in range(self.n_assets))  # Min 1% per asset
        initial_weights = np.array([1 / self.n_assets] * self.n_assets)

        result = minimize(
            risk_parity_objective,
            initial_weights,
            method="SLSQP",
            bounds=bounds,
            constraints=constraints,
        )

        optimal_weights = result.x
        return {
            "weights": dict(zip(self.tickers, optimal_weights)),
            "return": self._portfolio_return(optimal_weights),
            "volatility": self._portfolio_volatility(optimal_weights),
            "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
            "risk_contributions": dict(
                zip(self.tickers, risk_contribution(optimal_weights))
            ),
        }

    def generate_efficient_frontier(
        self, n_points: int = 50, weight_bounds: tuple[float, float] = (0, 1)
    ) -> pd.DataFrame:
        """
        Generate points on the efficient frontier.

        Parameters
        ----------
        n_points : int, default 50
            Number of points to generate
        weight_bounds : tuple, default (0, 1)
            Min and max weight for each asset

        Returns
        -------
        pd.DataFrame
            DataFrame with return, volatility, and Sharpe for each point
        """
        # Find return range
        min_vol = self.optimize_min_volatility(weight_bounds)
        _max_sharpe = self.optimize_max_sharpe(weight_bounds)  # noqa: F841

        min_ret = min_vol["return"]
        max_ret = max(self.mean_returns)

        target_returns = np.linspace(min_ret, max_ret, n_points)

        frontier = []
        failed_count = 0
        for target in target_returns:
            try:
                portfolio = self.optimize_target_return(target, weight_bounds)
                frontier.append(
                    {
                        "return": portfolio["return"],
                        "volatility": portfolio["volatility"],
                        "sharpe_ratio": portfolio["sharpe_ratio"],
                    }
                )
            except (ValueError, RuntimeError) as e:
                # Optimization may fail for extreme target returns
                failed_count += 1
                logger.debug(f"Optimization failed for target return {target:.4f}: {e}")
                continue

        if failed_count > 0:
            warnings.warn(
                f"Optimization failed for {failed_count}/{n_points} target returns. "
                "This is normal for extreme values at the frontier edges.",
                stacklevel=2,
            )

        if len(frontier) == 0:
            raise OptimizationError(
                "Failed to generate any points on the efficient frontier. "
                "Check that your data is valid and has sufficient history."
            )

        return pd.DataFrame(frontier)

    def plot_efficient_frontier(
        self,
        n_points: int = 50,
        show_assets: bool = True,
        show_optimal: bool = True,
        weight_bounds: tuple[float, float] = (0, 1),
        show: bool = True,
    ) -> plt.Figure:
        """
        Plot the efficient frontier with optimal portfolios marked.

        Parameters
        ----------
        n_points : int, default 50
            Number of points on the frontier
        show_assets : bool, default True
            Show individual assets
        show_optimal : bool, default True
            Mark optimal portfolios (max Sharpe, min vol)
        weight_bounds : tuple, default (0, 1)
            Min and max weight for each asset
        show : bool, default True
            Whether to display the plot. Set to False for automated/server contexts.

        Returns
        -------
        plt.Figure
            The matplotlib figure object
        """
        frontier = self.generate_efficient_frontier(n_points, weight_bounds)

        fig, ax = plt.subplots(figsize=(12, 8))

        # Plot efficient frontier
        ax.plot(
            frontier["volatility"] * 100,
            frontier["return"] * 100,
            "b-",
            linewidth=2,
            label="Efficient Frontier",
        )

        if show_assets:
            # Plot individual assets
            for i, ticker in enumerate(self.tickers):
                ax.scatter(
                    np.sqrt(self.cov_matrix.iloc[i, i]) * 100,
                    self.mean_returns.iloc[i] * 100,
                    s=100,
                    marker="o",
                    label=ticker,
                )

        if show_optimal:
            # Mark max Sharpe portfolio
            max_sharpe = self.optimize_max_sharpe(weight_bounds)
            ax.scatter(
                max_sharpe["volatility"] * 100,
                max_sharpe["return"] * 100,
                s=200,
                marker="*",
                c="red",
                label="Max Sharpe",
            )

            # Mark min volatility portfolio
            min_vol = self.optimize_min_volatility(weight_bounds)
            ax.scatter(
                min_vol["volatility"] * 100,
                min_vol["return"] * 100,
                s=200,
                marker="*",
                c="green",
                label="Min Volatility",
            )

        ax.set_xlabel("Volatility (%)")
        ax.set_ylabel("Expected Return (%)")
        ax.set_title("Efficient Frontier")
        ax.legend()
        ax.grid(True, alpha=0.3)
        fig.tight_layout()

        if show:
            plt.show()

        return fig

    def print_comparison(self, weight_bounds: tuple[float, float] = (0, 1)) -> None:
        """Print comparison of optimization strategies."""
        equal_weight = np.array([1 / self.n_assets] * self.n_assets)
        max_sharpe = self.optimize_max_sharpe(weight_bounds)
        min_vol = self.optimize_min_volatility(weight_bounds)
        risk_parity = self.optimize_risk_parity()

        print("\n" + "=" * 70)
        print("PORTFOLIO OPTIMIZATION COMPARISON")
        print("=" * 70)
        print(f"{'Strategy':<20} {'Return':>12} {'Volatility':>12} {'Sharpe':>10}")
        print("-" * 70)

        # Equal weight
        print(
            f"{'Equal Weight':<20} "
            f"{self._portfolio_return(equal_weight)*100:>11.2f}% "
            f"{self._portfolio_volatility(equal_weight)*100:>11.2f}% "
            f"{self._portfolio_sharpe(equal_weight):>10.2f}"
        )

        # Max Sharpe
        print(
            f"{'Max Sharpe':<20} "
            f"{max_sharpe['return']*100:>11.2f}% "
            f"{max_sharpe['volatility']*100:>11.2f}% "
            f"{max_sharpe['sharpe_ratio']:>10.2f}"
        )

        # Min Volatility
        print(
            f"{'Min Volatility':<20} "
            f"{min_vol['return']*100:>11.2f}% "
            f"{min_vol['volatility']*100:>11.2f}% "
            f"{min_vol['sharpe_ratio']:>10.2f}"
        )

        # Risk Parity
        print(
            f"{'Risk Parity':<20} "
            f"{risk_parity['return']*100:>11.2f}% "
            f"{risk_parity['volatility']*100:>11.2f}% "
            f"{risk_parity['sharpe_ratio']:>10.2f}"
        )

        print("=" * 70)

        print("\nOptimal Weights (Max Sharpe):")
        for ticker, weight in max_sharpe["weights"].items():
            if weight > 0.01:
                print(f"  {ticker}: {weight*100:.1f}%")

optimize_max_sharpe(weight_bounds=(0, 1))

Find the portfolio with maximum Sharpe ratio.

Parameters:

Name Type Description Default
weight_bounds tuple

Min and max weight for each asset

(0, 1)

Returns:

Type Description
dict

Optimal weights, return, volatility, and Sharpe ratio

Source code in portfolio_analysis/analysis/optimization.py
def optimize_max_sharpe(self, weight_bounds: tuple[float, float] = (0, 1)) -> dict:
    """
    Find the portfolio with maximum Sharpe ratio.

    Parameters
    ----------
    weight_bounds : tuple, default (0, 1)
        Min and max weight for each asset

    Returns
    -------
    dict
        Optimal weights, return, volatility, and Sharpe ratio
    """
    constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
    bounds = tuple(weight_bounds for _ in range(self.n_assets))
    initial_weights = np.array([1 / self.n_assets] * self.n_assets)

    result = minimize(
        self._neg_sharpe,
        initial_weights,
        method="SLSQP",
        bounds=bounds,
        constraints=constraints,
    )

    optimal_weights = result.x
    return {
        "weights": dict(zip(self.tickers, optimal_weights)),
        "return": self._portfolio_return(optimal_weights),
        "volatility": self._portfolio_volatility(optimal_weights),
        "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
    }

optimize_min_volatility(weight_bounds=(0, 1))

Find the minimum volatility portfolio.

Parameters:

Name Type Description Default
weight_bounds tuple

Min and max weight for each asset

(0, 1)

Returns:

Type Description
dict

Optimal weights, return, volatility, and Sharpe ratio

Source code in portfolio_analysis/analysis/optimization.py
def optimize_min_volatility(
    self, weight_bounds: tuple[float, float] = (0, 1)
) -> dict:
    """
    Find the minimum volatility portfolio.

    Parameters
    ----------
    weight_bounds : tuple, default (0, 1)
        Min and max weight for each asset

    Returns
    -------
    dict
        Optimal weights, return, volatility, and Sharpe ratio
    """
    constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
    bounds = tuple(weight_bounds for _ in range(self.n_assets))
    initial_weights = np.array([1 / self.n_assets] * self.n_assets)

    result = minimize(
        self._portfolio_volatility,
        initial_weights,
        method="SLSQP",
        bounds=bounds,
        constraints=constraints,
    )

    optimal_weights = result.x
    return {
        "weights": dict(zip(self.tickers, optimal_weights)),
        "return": self._portfolio_return(optimal_weights),
        "volatility": self._portfolio_volatility(optimal_weights),
        "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
    }

optimize_target_return(target_return, weight_bounds=(0, 1))

Find minimum volatility portfolio for a target return.

Parameters:

Name Type Description Default
target_return float

Target annual return

required
weight_bounds tuple

Min and max weight for each asset

(0, 1)

Returns:

Type Description
dict

Optimal weights, return, volatility, and Sharpe ratio

Source code in portfolio_analysis/analysis/optimization.py
def optimize_target_return(
    self, target_return: float, weight_bounds: tuple[float, float] = (0, 1)
) -> dict:
    """
    Find minimum volatility portfolio for a target return.

    Parameters
    ----------
    target_return : float
        Target annual return
    weight_bounds : tuple, default (0, 1)
        Min and max weight for each asset

    Returns
    -------
    dict
        Optimal weights, return, volatility, and Sharpe ratio
    """
    constraints = [
        {"type": "eq", "fun": lambda x: np.sum(x) - 1},
        {"type": "eq", "fun": lambda x: self._portfolio_return(x) - target_return},
    ]
    bounds = tuple(weight_bounds for _ in range(self.n_assets))
    initial_weights = np.array([1 / self.n_assets] * self.n_assets)

    result = minimize(
        self._portfolio_volatility,
        initial_weights,
        method="SLSQP",
        bounds=bounds,
        constraints=constraints,
    )

    optimal_weights = result.x
    return {
        "weights": dict(zip(self.tickers, optimal_weights)),
        "return": self._portfolio_return(optimal_weights),
        "volatility": self._portfolio_volatility(optimal_weights),
        "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
    }

optimize_risk_parity()

Find the risk parity portfolio (equal risk contribution).

Each asset contributes equally to total portfolio risk.

Returns:

Type Description
dict

Optimal weights, return, volatility, and Sharpe ratio

Source code in portfolio_analysis/analysis/optimization.py
def optimize_risk_parity(self) -> dict:
    """
    Find the risk parity portfolio (equal risk contribution).

    Each asset contributes equally to total portfolio risk.

    Returns
    -------
    dict
        Optimal weights, return, volatility, and Sharpe ratio
    """

    def risk_contribution(weights):
        """Calculate risk contribution of each asset."""
        port_vol = self._portfolio_volatility(weights)
        marginal_contrib = np.dot(self.cov_matrix, weights)
        risk_contrib = weights * marginal_contrib / port_vol
        return risk_contrib

    def risk_parity_objective(weights):
        """Objective: minimize deviation from equal risk contribution."""
        rc = risk_contribution(weights)
        target_rc = np.mean(rc)
        return np.sum((rc - target_rc) ** 2)

    constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
    bounds = tuple((0.01, 1) for _ in range(self.n_assets))  # Min 1% per asset
    initial_weights = np.array([1 / self.n_assets] * self.n_assets)

    result = minimize(
        risk_parity_objective,
        initial_weights,
        method="SLSQP",
        bounds=bounds,
        constraints=constraints,
    )

    optimal_weights = result.x
    return {
        "weights": dict(zip(self.tickers, optimal_weights)),
        "return": self._portfolio_return(optimal_weights),
        "volatility": self._portfolio_volatility(optimal_weights),
        "sharpe_ratio": self._portfolio_sharpe(optimal_weights),
        "risk_contributions": dict(
            zip(self.tickers, risk_contribution(optimal_weights))
        ),
    }

generate_efficient_frontier(n_points=50, weight_bounds=(0, 1))

Generate points on the efficient frontier.

Parameters:

Name Type Description Default
n_points int

Number of points to generate

50
weight_bounds tuple

Min and max weight for each asset

(0, 1)

Returns:

Type Description
DataFrame

DataFrame with return, volatility, and Sharpe for each point

Source code in portfolio_analysis/analysis/optimization.py
def generate_efficient_frontier(
    self, n_points: int = 50, weight_bounds: tuple[float, float] = (0, 1)
) -> pd.DataFrame:
    """
    Generate points on the efficient frontier.

    Parameters
    ----------
    n_points : int, default 50
        Number of points to generate
    weight_bounds : tuple, default (0, 1)
        Min and max weight for each asset

    Returns
    -------
    pd.DataFrame
        DataFrame with return, volatility, and Sharpe for each point
    """
    # Find return range
    min_vol = self.optimize_min_volatility(weight_bounds)
    _max_sharpe = self.optimize_max_sharpe(weight_bounds)  # noqa: F841

    min_ret = min_vol["return"]
    max_ret = max(self.mean_returns)

    target_returns = np.linspace(min_ret, max_ret, n_points)

    frontier = []
    failed_count = 0
    for target in target_returns:
        try:
            portfolio = self.optimize_target_return(target, weight_bounds)
            frontier.append(
                {
                    "return": portfolio["return"],
                    "volatility": portfolio["volatility"],
                    "sharpe_ratio": portfolio["sharpe_ratio"],
                }
            )
        except (ValueError, RuntimeError) as e:
            # Optimization may fail for extreme target returns
            failed_count += 1
            logger.debug(f"Optimization failed for target return {target:.4f}: {e}")
            continue

    if failed_count > 0:
        warnings.warn(
            f"Optimization failed for {failed_count}/{n_points} target returns. "
            "This is normal for extreme values at the frontier edges.",
            stacklevel=2,
        )

    if len(frontier) == 0:
        raise OptimizationError(
            "Failed to generate any points on the efficient frontier. "
            "Check that your data is valid and has sufficient history."
        )

    return pd.DataFrame(frontier)

plot_efficient_frontier(n_points=50, show_assets=True, show_optimal=True, weight_bounds=(0, 1), show=True)

Plot the efficient frontier with optimal portfolios marked.

Parameters:

Name Type Description Default
n_points int

Number of points on the frontier

50
show_assets bool

Show individual assets

True
show_optimal bool

Mark optimal portfolios (max Sharpe, min vol)

True
weight_bounds tuple

Min and max weight for each asset

(0, 1)
show bool

Whether to display the plot. Set to False for automated/server contexts.

True

Returns:

Type Description
Figure

The matplotlib figure object

Source code in portfolio_analysis/analysis/optimization.py
def plot_efficient_frontier(
    self,
    n_points: int = 50,
    show_assets: bool = True,
    show_optimal: bool = True,
    weight_bounds: tuple[float, float] = (0, 1),
    show: bool = True,
) -> plt.Figure:
    """
    Plot the efficient frontier with optimal portfolios marked.

    Parameters
    ----------
    n_points : int, default 50
        Number of points on the frontier
    show_assets : bool, default True
        Show individual assets
    show_optimal : bool, default True
        Mark optimal portfolios (max Sharpe, min vol)
    weight_bounds : tuple, default (0, 1)
        Min and max weight for each asset
    show : bool, default True
        Whether to display the plot. Set to False for automated/server contexts.

    Returns
    -------
    plt.Figure
        The matplotlib figure object
    """
    frontier = self.generate_efficient_frontier(n_points, weight_bounds)

    fig, ax = plt.subplots(figsize=(12, 8))

    # Plot efficient frontier
    ax.plot(
        frontier["volatility"] * 100,
        frontier["return"] * 100,
        "b-",
        linewidth=2,
        label="Efficient Frontier",
    )

    if show_assets:
        # Plot individual assets
        for i, ticker in enumerate(self.tickers):
            ax.scatter(
                np.sqrt(self.cov_matrix.iloc[i, i]) * 100,
                self.mean_returns.iloc[i] * 100,
                s=100,
                marker="o",
                label=ticker,
            )

    if show_optimal:
        # Mark max Sharpe portfolio
        max_sharpe = self.optimize_max_sharpe(weight_bounds)
        ax.scatter(
            max_sharpe["volatility"] * 100,
            max_sharpe["return"] * 100,
            s=200,
            marker="*",
            c="red",
            label="Max Sharpe",
        )

        # Mark min volatility portfolio
        min_vol = self.optimize_min_volatility(weight_bounds)
        ax.scatter(
            min_vol["volatility"] * 100,
            min_vol["return"] * 100,
            s=200,
            marker="*",
            c="green",
            label="Min Volatility",
        )

    ax.set_xlabel("Volatility (%)")
    ax.set_ylabel("Expected Return (%)")
    ax.set_title("Efficient Frontier")
    ax.legend()
    ax.grid(True, alpha=0.3)
    fig.tight_layout()

    if show:
        plt.show()

    return fig

print_comparison(weight_bounds=(0, 1))

Print comparison of optimization strategies.

Source code in portfolio_analysis/analysis/optimization.py
def print_comparison(self, weight_bounds: tuple[float, float] = (0, 1)) -> None:
    """Print comparison of optimization strategies."""
    equal_weight = np.array([1 / self.n_assets] * self.n_assets)
    max_sharpe = self.optimize_max_sharpe(weight_bounds)
    min_vol = self.optimize_min_volatility(weight_bounds)
    risk_parity = self.optimize_risk_parity()

    print("\n" + "=" * 70)
    print("PORTFOLIO OPTIMIZATION COMPARISON")
    print("=" * 70)
    print(f"{'Strategy':<20} {'Return':>12} {'Volatility':>12} {'Sharpe':>10}")
    print("-" * 70)

    # Equal weight
    print(
        f"{'Equal Weight':<20} "
        f"{self._portfolio_return(equal_weight)*100:>11.2f}% "
        f"{self._portfolio_volatility(equal_weight)*100:>11.2f}% "
        f"{self._portfolio_sharpe(equal_weight):>10.2f}"
    )

    # Max Sharpe
    print(
        f"{'Max Sharpe':<20} "
        f"{max_sharpe['return']*100:>11.2f}% "
        f"{max_sharpe['volatility']*100:>11.2f}% "
        f"{max_sharpe['sharpe_ratio']:>10.2f}"
    )

    # Min Volatility
    print(
        f"{'Min Volatility':<20} "
        f"{min_vol['return']*100:>11.2f}% "
        f"{min_vol['volatility']*100:>11.2f}% "
        f"{min_vol['sharpe_ratio']:>10.2f}"
    )

    # Risk Parity
    print(
        f"{'Risk Parity':<20} "
        f"{risk_parity['return']*100:>11.2f}% "
        f"{risk_parity['volatility']*100:>11.2f}% "
        f"{risk_parity['sharpe_ratio']:>10.2f}"
    )

    print("=" * 70)

    print("\nOptimal Weights (Max Sharpe):")
    for ticker, weight in max_sharpe["weights"].items():
        if weight > 0.01:
            print(f"  {ticker}: {weight*100:.1f}%")