Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Portfolio Optimization with Constraints | Risk Analysis and Portfolio Optimization
Python for Financial Analysts

bookPortfolio Optimization with Constraints

Portfolio optimization is a fundamental task in financial analysis, aiming to allocate investments across different assets to achieve the best possible balance between expected return and risk. The concept of the efficient frontier is central to this process. It represents the set of optimal portfolios that offer the highest expected return for a specific level of risk. Constraints play a crucial role in portfolio optimization. Common constraints include prohibiting short selling (no negative asset weights) and requiring full investment (the sum of all asset weights equals one). These constraints ensure that the resulting portfolio is practical and aligns with real-world investment policies.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
import numpy as np import pandas as pd from scipy.optimize import minimize # Simulated expected returns and covariance matrix for three assets expected_returns = np.array([0.08, 0.12, 0.10]) cov_matrix = np.array([ [0.005, -0.010, 0.004], [-0.010, 0.040, -0.002], [0.004, -0.002, 0.023] ]) assets = ['Asset A', 'Asset B', 'Asset C'] def portfolio_stats(weights, returns, cov): port_return = np.dot(weights, returns) port_volatility = np.sqrt(np.dot(weights.T, np.dot(cov, weights))) return port_return, port_volatility def objective(weights, returns, cov): # Minimize negative Sharpe ratio (assume risk-free rate = 0 for simplicity) port_return, port_volatility = portfolio_stats(weights, returns, cov) return -port_return / port_volatility constraints = ( {'type': 'eq', 'fun': lambda x: np.sum(x) - 1}, # Full investment ) bounds = tuple((0, 1) for _ in assets) # No short selling initial_guess = np.array([1/3, 1/3, 1/3]) result = minimize( objective, initial_guess, args=(expected_returns, cov_matrix), method='SLSQP', bounds=bounds, constraints=constraints ) optimal_weights = result.x optimal_port_return, optimal_port_volatility = portfolio_stats(optimal_weights, expected_returns, cov_matrix) print("Optimal Weights:") for asset, weight in zip(assets, optimal_weights): print(f"{asset}: {weight:.2%}") print(f"Expected Portfolio Return: {optimal_port_return:.2%}") print(f"Portfolio Volatility: {optimal_port_volatility:.2%}")
copy

In this optimization process, you set up a mean-variance optimization for three assets by defining their expected returns and covariance matrix. The objective is to maximize the Sharpe ratio, which balances return against risk. The constraints ensure that the sum of the asset weights equals one (full investment) and that each weight is between zero and one (no short selling). The optimization algorithm searches for the combination of asset weights that yields the highest expected return for the lowest risk, given these constraints. The resulting optimal weights tell you how much of your portfolio to allocate to each asset. Interpreting these weights helps you decide on a practical investment strategy that aligns with your risk preferences and investment policy.

1234567891011121314151617181920212223242526
import matplotlib.pyplot as plt # Generate portfolios along the efficient frontier num_portfolios = 100 results = np.zeros((2, num_portfolios)) weight_records = [] for i in range(num_portfolios): # Random weights, normalized to sum to 1, no short selling weights = np.random.rand(len(assets)) weights /= np.sum(weights) if np.all(weights >= 0): # Enforce no short selling port_return, port_volatility = portfolio_stats(weights, expected_returns, cov_matrix) results[0, i] = port_volatility results[1, i] = port_return weight_records.append(weights) plt.figure(figsize=(8, 5)) plt.scatter(results[0, :], results[1, :], c=results[1, :] / results[0, :], marker='o') plt.scatter(optimal_port_volatility, optimal_port_return, marker='*', color='r', s=200, label='Optimal Portfolio') plt.xlabel('Portfolio Volatility (Risk)') plt.ylabel('Expected Return') plt.title('Efficient Frontier (No Short Selling)') plt.colorbar(label='Sharpe Ratio') plt.legend() plt.show()
copy

1. What is the efficient frontier in portfolio theory?

2. Why are constraints important in portfolio optimization?

3. Which Python libraries are commonly used for numerical optimization in finance?

question mark

What is the efficient frontier in portfolio theory?

Select the correct answer

question mark

Why are constraints important in portfolio optimization?

Select the correct answer

question mark

Which Python libraries are commonly used for numerical optimization in finance?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

Can you explain what the efficient frontier plot tells me about my investment options?

How would the results change if short selling were allowed?

What does the Sharpe ratio represent in this context?

bookPortfolio Optimization with Constraints

Свайпніть щоб показати меню

Portfolio optimization is a fundamental task in financial analysis, aiming to allocate investments across different assets to achieve the best possible balance between expected return and risk. The concept of the efficient frontier is central to this process. It represents the set of optimal portfolios that offer the highest expected return for a specific level of risk. Constraints play a crucial role in portfolio optimization. Common constraints include prohibiting short selling (no negative asset weights) and requiring full investment (the sum of all asset weights equals one). These constraints ensure that the resulting portfolio is practical and aligns with real-world investment policies.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
import numpy as np import pandas as pd from scipy.optimize import minimize # Simulated expected returns and covariance matrix for three assets expected_returns = np.array([0.08, 0.12, 0.10]) cov_matrix = np.array([ [0.005, -0.010, 0.004], [-0.010, 0.040, -0.002], [0.004, -0.002, 0.023] ]) assets = ['Asset A', 'Asset B', 'Asset C'] def portfolio_stats(weights, returns, cov): port_return = np.dot(weights, returns) port_volatility = np.sqrt(np.dot(weights.T, np.dot(cov, weights))) return port_return, port_volatility def objective(weights, returns, cov): # Minimize negative Sharpe ratio (assume risk-free rate = 0 for simplicity) port_return, port_volatility = portfolio_stats(weights, returns, cov) return -port_return / port_volatility constraints = ( {'type': 'eq', 'fun': lambda x: np.sum(x) - 1}, # Full investment ) bounds = tuple((0, 1) for _ in assets) # No short selling initial_guess = np.array([1/3, 1/3, 1/3]) result = minimize( objective, initial_guess, args=(expected_returns, cov_matrix), method='SLSQP', bounds=bounds, constraints=constraints ) optimal_weights = result.x optimal_port_return, optimal_port_volatility = portfolio_stats(optimal_weights, expected_returns, cov_matrix) print("Optimal Weights:") for asset, weight in zip(assets, optimal_weights): print(f"{asset}: {weight:.2%}") print(f"Expected Portfolio Return: {optimal_port_return:.2%}") print(f"Portfolio Volatility: {optimal_port_volatility:.2%}")
copy

In this optimization process, you set up a mean-variance optimization for three assets by defining their expected returns and covariance matrix. The objective is to maximize the Sharpe ratio, which balances return against risk. The constraints ensure that the sum of the asset weights equals one (full investment) and that each weight is between zero and one (no short selling). The optimization algorithm searches for the combination of asset weights that yields the highest expected return for the lowest risk, given these constraints. The resulting optimal weights tell you how much of your portfolio to allocate to each asset. Interpreting these weights helps you decide on a practical investment strategy that aligns with your risk preferences and investment policy.

1234567891011121314151617181920212223242526
import matplotlib.pyplot as plt # Generate portfolios along the efficient frontier num_portfolios = 100 results = np.zeros((2, num_portfolios)) weight_records = [] for i in range(num_portfolios): # Random weights, normalized to sum to 1, no short selling weights = np.random.rand(len(assets)) weights /= np.sum(weights) if np.all(weights >= 0): # Enforce no short selling port_return, port_volatility = portfolio_stats(weights, expected_returns, cov_matrix) results[0, i] = port_volatility results[1, i] = port_return weight_records.append(weights) plt.figure(figsize=(8, 5)) plt.scatter(results[0, :], results[1, :], c=results[1, :] / results[0, :], marker='o') plt.scatter(optimal_port_volatility, optimal_port_return, marker='*', color='r', s=200, label='Optimal Portfolio') plt.xlabel('Portfolio Volatility (Risk)') plt.ylabel('Expected Return') plt.title('Efficient Frontier (No Short Selling)') plt.colorbar(label='Sharpe Ratio') plt.legend() plt.show()
copy

1. What is the efficient frontier in portfolio theory?

2. Why are constraints important in portfolio optimization?

3. Which Python libraries are commonly used for numerical optimization in finance?

question mark

What is the efficient frontier in portfolio theory?

Select the correct answer

question mark

Why are constraints important in portfolio optimization?

Select the correct answer

question mark

Which Python libraries are commonly used for numerical optimization in finance?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4
some-alt