Part 6 of 7
π― Learning Objective
By the end of this section, you will understand how classical portfolio optimization maps to quantum optimization through QUBO formulation and how QAOA/VQE algorithms solve these problems.
The central problem: select portfolio weights that maximize return while minimizing risk.
Where $\mathbf{w}$ = weights, $\boldsymbol{\Sigma}$ = covariance matrix, $\boldsymbol{\mu}$ = expected returns, $\lambda$ = risk-aversion parameter.
| Ξ» Value | Strategy | Risk Level |
|---|---|---|
| High (Ξ» >> 1) | Aggressive β maximize returns | High risk |
| Balanced (Ξ» β 1) | Balanced β consider both | Medium risk |
| Low (Ξ» << 1) | Conservative β minimize risk | Low risk |
For continuous weights, this is solvable classically. But real-world constraints make it NP-hard:
π‘ Key Insight
For 50 assets choosing 10, there are $C(50,10)$ = 10.27 billion possible portfolios. This is where quantum computing can help.
Pythonimport numpy as np
import matplotlib.pyplot as plt
assets = ['RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ITC']
expected_returns = np.array([0.12, 0.15, 0.10, 0.14, 0.08])
volatilities = np.array([0.25, 0.22, 0.18, 0.24, 0.15])
correlation_matrix = np.array([
[1.00, 0.45, 0.50, 0.40, 0.30],
[0.45, 1.00, 0.35, 0.70, 0.20],
[0.50, 0.35, 1.00, 0.30, 0.40],
[0.40, 0.70, 0.30, 1.00, 0.25],
[0.30, 0.20, 0.40, 0.25, 1.00]
])
D = np.diag(volatilities)
cov_matrix = D @ correlation_matrix @ D
# Generate 10,000 random portfolios
n_portfolios = 10000
results = np.zeros((3, n_portfolios))
np.random.seed(42)
for i in range(n_portfolios):
weights = np.random.random(len(assets))
weights /= weights.sum()
portfolio_return = np.dot(weights, expected_returns)
portfolio_vol = np.sqrt(weights @ cov_matrix @ weights)
sharpe = (portfolio_return - 0.06) / portfolio_vol
results[0, i] = portfolio_vol
results[1, i] = portfolio_return
results[2, i] = sharpe
plt.figure(figsize=(12, 7))
scatter = plt.scatter(results[0], results[1], c=results[2],
cmap='viridis', alpha=0.5, s=10)
plt.colorbar(scatter, label='Sharpe Ratio')
max_sharpe_idx = results[2].argmax()
plt.scatter(results[0, max_sharpe_idx], results[1, max_sharpe_idx],
marker='*', s=300, c='red', edgecolors='black',
label=f'Max Sharpe: {results[2, max_sharpe_idx]:.2f}')
for i, asset in enumerate(assets):
plt.scatter(volatilities[i], expected_returns[i], marker='D', s=100,
c='white', edgecolors='black', linewidths=1.5)
plt.annotate(asset, (volatilities[i], expected_returns[i]),
fontsize=9, fontweight='bold', xytext=(10, 5),
textcoords='offset points')
plt.title('Efficient Frontier: 10,000 Random Portfolios',
fontsize=14, fontweight='bold')
plt.xlabel('Portfolio Volatility (Ο)')
plt.ylabel('Expected Return (ΞΌ)')
plt.legend(fontsize=11)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
The combinatorial explosion:
| Assets Available | Select | Possible Portfolios | Time (1ΞΌs/eval) |
|---|---|---|---|
| 10 | 5 | 252 | 0.25 ms |
| 20 | 10 | 184,756 | 0.18 sec |
| 50 | 10 | 10.27 billion | 2.85 hours |
| 100 | 20 | 5.36 Γ 10Β²β° | 17 million years |
| 500 | 50 | ~10βΈβ° | Heat death of universe |
Random search samples a tiny fraction. Classical heuristics (genetic algorithms, simulated annealing) help but offer no optimality guarantee. QAOA explores the space via quantum superposition, potentially finding better solutions faster.
Quadratic Unconstrained Binary Optimization β the mathematical framework that maps optimization to quantum hardware:
Where $\mathbf{x}$ = binary vector ($x_i \in \{0, 1\}$ β include asset $i$ or not), $Q$ = QUBO matrix encoding objective and constraints.
Where $q$ = risk-return tradeoff, $B$ = budget (number of assets to select), $A$ = penalty for violating budget.
| Classical Formulation | QUBO Formulation |
|---|---|
| Continuous weights (0 to 1) | Binary decisions (0 or 1) |
| Quadratic programming | Ising/QUBO model |
| Classical solvers (CPLEX, Gurobi) | Quantum hardware compatible |
| Polynomial time for convex case | Maps to quantum ground state search |
π‘ The Key Insight
By converting to QUBO, the optimal portfolio corresponds to the ground state (lowest energy) of a quantum system. Quantum algorithms are naturally suited to finding ground states β this is what quantum computers do best!
Given: 3 assets with returns $\mu = [0.12, 0.15, 0.10]$ and covariances, select exactly 2.
The QUBO objective (simplified, $q=0.5$, $A=10$):
All possible portfolios:
| xβxβxβ | Portfolio | Budget Penalty | Feasible? |
|---|---|---|---|
| 110 | Asset 1 + 2 | $10(2-2)^2 = 0$ | β |
| 101 | Asset 1 + 3 | $10(2-2)^2 = 0$ | β |
| 011 | Asset 2 + 3 | $10(2-2)^2 = 0$ | β |
| 111 | All three | $10(3-2)^2 = 10$ | β Heavy penalty |
| 100 | Only Asset 1 | $10(1-2)^2 = 10$ | β Heavy penalty |
The penalty term $A(\sum x_i - B)^2$ ensures QAOA strongly prefers exactly $B$ assets. The quantum algorithm searches all combinations simultaneously and converges on the minimum-cost feasible portfolio.
QAOA (Farhi et al., 2014) is a hybrid quantum-classical algorithm for combinatorial optimization:
| Feature | QAOA | VQE |
|---|---|---|
| Circuit structure | Fixed (alternating layers) | Flexible (parameterized ansatz) |
| Parameters | 2p parameters (Ξ³, Ξ²) | Variable |
| Best for | Combinatorial optimization | General eigenvalue problems |
| Depth | Usually moderate | Can be very shallow |
Pythonimport numpy as np
from itertools import combinations
n_assets = 4
assets = ['RELIANCE', 'TCS', 'HDFCBANK', 'INFY']
expected_returns = np.array([0.12, 0.15, 0.10, 0.14])
cov_matrix = np.array([
[0.0625, 0.0248, 0.0225, 0.0240],
[0.0248, 0.0484, 0.0139, 0.0370],
[0.0225, 0.0139, 0.0324, 0.0130],
[0.0240, 0.0370, 0.0130, 0.0576]
])
budget = 2 # Select exactly 2 assets
risk_factor = 0.5
print("=" * 60)
print(f"{'PORTFOLIO OPTIMIZATION: Select 2 from 4 assets':^60}")
print("=" * 60)
print(f"\n{'Portfolio':<25} {'Return':<10} {'Risk':<10} {'Objective':<12}")
print("-" * 60)
best_obj = float('inf')
best_portfolio = None
for combo in combinations(range(n_assets), budget):
x = np.zeros(n_assets)
for i in combo:
x[i] = 1
risk = x @ cov_matrix @ x
ret = x @ expected_returns
objective = risk_factor * risk - (1 - risk_factor) * ret
portfolio_str = ' + '.join([assets[i] for i in combo])
print(f" {portfolio_str:<23} {ret:<10.4f} {risk:<10.4f} {objective:<12.6f}")
if objective < best_obj:
best_obj = objective
best_portfolio = combo
print("-" * 60)
print(f"\nβ
Optimal: {' + '.join([assets[i] for i in best_portfolio])}")
print(f" Objective value: {best_obj:.6f}")
Python# βββ Conceptual QAOA for Portfolio Optimization βββ
print("\n" + "=" * 60)
print(f"{'QAOA CONCEPTUAL WORKFLOW':^60}")
print("=" * 60)
print("""
STEP 1: QUBO Formulation
x_i β {0, 1} for each asset | Q matrix encodes covariances
STEP 2: Map to Quantum Hamiltonian
QUBO β Ising: H = Ξ£ J_ij Z_i Z_j + Ξ£ h_i Z_i
4 assets β 4 qubits
STEP 3: QAOA Circuit (p=1)
|0β© ββ€ H ββββ€ e^(-iΞ³H_p) ββββ€ e^(-iΞ²H_m) ββββ€Mβ
(Γ4 qubits)
STEP 4: Classical Optimization Loop
Measure β Compute cost β Update Ξ³, Ξ² β Repeat
STEP 5: Read Optimal Portfolio
Most frequent bitstring = optimal portfolio
E.g., "0110" β Select TCS and HDFCBANK
""")
# Simulated QAOA convergence
print("Simulated QAOA Optimization Progress:")
print(f"{'Iter':<8} {'Ξ³':<8} {'Ξ²':<8} {'Best Objective':<18} {'Portfolio'}")
print("-" * 65)
np.random.seed(42)
gamma, beta = np.random.uniform(0, np.pi, 2)
best_obj_qaoa = float('inf')
for iteration in range(1, 11):
gamma += np.random.uniform(-0.1, 0.1)
beta += np.random.uniform(-0.1, 0.1)
current_obj = best_obj * (1 + 0.5 * np.exp(-0.5 * iteration)
* np.random.uniform(-1, 1))
if current_obj < best_obj_qaoa:
best_obj_qaoa = current_obj
label = ' + '.join([assets[i] for i in best_portfolio])
print(f" {iteration:<6} {gamma:<8.3f} {beta:<8.3f} "
f"{best_obj_qaoa:<18.6f} {label}")
print("-" * 65)
print(f"\nβ
QAOA Result: {' + '.join([assets[i] for i in best_portfolio])}")
print(f" Matches classical optimal: YES β")
Four critical reasons:
π‘ The Scaling Argument
"With 4 assets and 4 qubits, a classical computer solves this instantly. The quantum approach becomes valuable at 20+ assets where classical brute force fails. We demonstrate with 4 assets to show the workflow β the same workflow scales to real institutional portfolios."