🎯 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.

6.1 β€” The Classical Portfolio Optimization Problem

Markowitz Mean-Variance Optimization

The central problem: select portfolio weights that maximize return while minimizing risk.

$$\min_{\mathbf{w}} \left( \mathbf{w}^T \boldsymbol{\Sigma} \mathbf{w} - \lambda \, \boldsymbol{\mu}^T \mathbf{w} \right)$$

Where $\mathbf{w}$ = weights, $\boldsymbol{\Sigma}$ = covariance matrix, $\boldsymbol{\mu}$ = expected returns, $\lambda$ = risk-aversion parameter.

Ξ» ValueStrategyRisk Level
High (Ξ» >> 1)Aggressive β€” maximize returnsHigh risk
Balanced (Ξ» β‰ˆ 1)Balanced β€” consider bothMedium risk
Low (Ξ» << 1)Conservative β€” minimize riskLow risk

Why This Is Hard

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.

Python: Efficient Frontier

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 AvailableSelectPossible PortfoliosTime (1ΞΌs/eval)
1052520.25 ms
2010184,7560.18 sec
501010.27 billion2.85 hours
100205.36 Γ— 10²⁰17 million years
50050~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.

6.2 β€” QUBO: Making Problems Quantum-Compatible

What Is QUBO?

Quadratic Unconstrained Binary Optimization β€” the mathematical framework that maps optimization to quantum hardware:

$$\min_{\mathbf{x}} \mathbf{x}^T Q \mathbf{x}$$

Where $\mathbf{x}$ = binary vector ($x_i \in \{0, 1\}$ β€” include asset $i$ or not), $Q$ = QUBO matrix encoding objective and constraints.

Portfolio Optimization as QUBO

$$\min_{\mathbf{x}} \left[ q \sum_{i,j} \sigma_{ij} x_i x_j - (1-q) \sum_i \mu_i x_i + A\left(\sum_i x_i - B\right)^2 \right]$$

Where $q$ = risk-return tradeoff, $B$ = budget (number of assets to select), $A$ = penalty for violating budget.

Classical FormulationQUBO Formulation
Continuous weights (0 to 1)Binary decisions (0 or 1)
Quadratic programmingIsing/QUBO model
Classical solvers (CPLEX, Gurobi)Quantum hardware compatible
Polynomial time for convex caseMaps 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$):

$$\min_{x} \; 0.5 \sum \sigma_{ij} x_i x_j - 0.5 \sum \mu_i x_i + 10(x_1 + x_2 + x_3 - 2)^2$$

All possible portfolios:

x₁xβ‚‚x₃PortfolioBudget PenaltyFeasible?
110Asset 1 + 2$10(2-2)^2 = 0$βœ…
101Asset 1 + 3$10(2-2)^2 = 0$βœ…
011Asset 2 + 3$10(2-2)^2 = 0$βœ…
111All three$10(3-2)^2 = 10$❌ Heavy penalty
100Only 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.

6.3 β€” QAOA: The Quantum Optimization Algorithm

QAOA (Farhi et al., 2014) is a hybrid quantum-classical algorithm for combinatorial optimization:

1. INITIALIZE
All qubits in equal superposition (all portfolios equally likely)
β–Ό
2. PROBLEM HAMILTONIAN $U_p(\gamma)$
Encodes cost function β€” penalizes bad portfolios
β–Ό
3. MIXER HAMILTONIAN $U_m(\beta)$
Allows exploration β€” tries new portfolio combinations
β–Ό
4. MEASURE β†’ CLASSICAL OPTIMIZER
Adjust Ξ³, Ξ² β†’ repeat until convergence β†’ optimal portfolio

QAOA vs VQE

FeatureQAOAVQE
Circuit structureFixed (alternating layers)Flexible (parameterized ansatz)
Parameters2p parameters (Ξ³, Ξ²)Variable
Best forCombinatorial optimizationGeneral eigenvalue problems
DepthUsually moderateCan be very shallow

6.4 β€” Python Demo: Brute Force vs QAOA

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}")

Conceptual QAOA Workflow

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:

  1. The circuit structure is identical for 4 or 400 assets β€” only the number of qubits changes
  2. Classical brute force fails beyond ~30 assets β€” $C(30,15) \approx 155$ million combinations
  3. QAOA explores via superposition β€” it doesn't enumerate; it searches the entire space simultaneously
  4. Benchmarks are promising β€” Brandhofer et al. (2022) showed QAOA works well with appropriate parameter strategies

πŸ’‘ 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."

πŸ“š References

  1. Markowitz, H. (1952). Portfolio selection. The Journal of Finance, 7(1), 77–91.
  2. Farhi, E., Goldstone, J., & Gutmann, S. (2014). A quantum approximate optimization algorithm. arXiv:1411.4028.
  3. Brandhofer, S., Braun, D., & Dehn, V. (2022). Benchmarking portfolio optimization with QAOA. Quantum Information Processing, 22(1). doi:10.1007/s11128-022-03766-5
  4. Kaushik, N., Raj, A., & Srivastava, M. (2023). Financial portfolio optimization: QAOA and VQE for Sharpe ratio. IEEE ICRTAC, 575–581.