SECTION 1: LEARNING OBJECTIVES
By the end of this lesson, you will be able to:
-
Understand the fundamentals of quantum computing – qubits, superposition, entanglement, and quantum gates.
-
Explain the difference between classical and quantum computation and why quantum computing offers potential advantages for certain financial problems.
-
Identify key quantum algorithms relevant to finance – Shor’s algorithm, Grover’s algorithm, Quantum Amplitude Estimation, and Variational Quantum Eigensolver (VQE).
-
Understand the application of quantum computing to portfolio optimisation, risk analysis, Monte Carlo simulation, and option pricing.
-
Explain the concept of quantum advantage – when quantum computers can outperform classical computers.
-
Understand the current state of quantum hardware – NISQ (Noisy Intermediate-Scale Quantum) devices and the path to fault-tolerant quantum computing.
-
Apply quantum-inspired algorithms (e.g., tensor networks) to financial problems today.
-
Develop a roadmap for quantum adoption in banking.
SECTION 2: WHY QUANTUM COMPUTING FOR FINANCE?
2.1 The Problem with Classical Computing
Many financial problems are computationally intensive:
| Problem | Computational Complexity | Classical Challenge |
|---|---|---|
| Portfolio Optimisation | O(2N) for N assets | Exponential growth with N. |
| Option Pricing | O(N×S) for N paths and S steps | Monte Carlo simulation is slow. |
| Risk Simulation | O(N×S) | Millions of scenarios needed. |
| Cryptography | Factoring large integers O(exp(n1/3)) | Security of RSA relies on hard factoring. |
| Linear Algebra | O(N3) for matrix operations | Large matrices are slow. |
Quantum computing offers potential speedups:
-
Quadratic speedup: Grover’s algorithm.
-
Exponential speedup: Shor’s algorithm (factoring).
-
Polynomial speedup: Portfolio optimisation, Monte Carlo.
2.2 Quantum Advantage (Opportunities)
| Opportunity | Classical | Quantum | Improvement |
|---|---|---|---|
| Portfolio Optimisation | Exact (limited N) or approximate | Exact for larger N | Exponential potential |
| Option Pricing | Monte Carlo O(1/ϵ) | O(1/ϵ) | Quadratic speedup |
| Risk Simulation | Monte Carlo O(1/ϵ) | O(1/ϵ) | Quadratic speedup |
| Fraud Detection | Pattern matching O(N) | O(N) | Quadratic speedup |
| Credit Scoring | Linear algebra O(N3) | O(N2) | Polynomial speedup |
SECTION 3: QUANTUM COMPUTING FUNDAMENTALS
3.1 Qubits (Quantum Bits)
A classical bit can be 0 or 1. A qubit can be in a superposition of 0 and 1:
∣ψ⟩=α∣0⟩+β∣1⟩
where α,β are complex numbers with ∣α∣2+∣β∣2=1.
Measurement: When a qubit is measured, it collapses to either 0 (with probability ∣α∣2) or 1 (with probability ∣β∣2).
3.2 Superposition and Entanglement
-
Superposition: A qubit can exist in multiple states simultaneously, enabling parallelism.
-
Entanglement: The state of one qubit depends on the state of another, even at a distance. Enables correlations not possible in classical computing.
3.3 Quantum Gates
Quantum gates manipulate qubits (like classical logic gates):
| Gate | Symbol | Effect | Matrix |
|---|---|---|---|
| Hadamard (H) | Creates superposition | 12(111−1) | |
| Pauli-X (NOT) | Flips qubit | (0110) | |
| Pauli-Z | Phase flip | (100−1) | |
| CNOT | Controlled-NOT | Entangles two qubits |
3.4 Quantum Algorithms
| Algorithm | Problem | Speedup | Financial Application |
|---|---|---|---|
| Shor’s Algorithm | Integer factoring | Exponential | Cryptography (RSA breaking). |
| Grover’s Algorithm | Search in unstructured database | Quadratic | Fraud detection, pattern matching. |
| QAOA (Quantum Approximate Optimisation Algorithm) | Combinatorial optimisation | Polynomial | Portfolio optimisation, asset allocation. |
| QAE (Quantum Amplitude Estimation) | Estimate expectation values | Quadratic | Monte Carlo simulation, option pricing. |
| VQE (Variational Quantum Eigensolver) | Find ground state of Hamiltonian | Polynomial | Molecular modelling, not directly finance. |
SECTION 4: QUANTUM COMPUTING IN FINANCE – KEY APPLICATIONS
4.1 Portfolio Optimisation
Problem: Find the optimal asset allocation to maximise return or minimise risk.
Classical approaches (Markowitz mean-variance) require solving a quadratic optimisation problem:
minwwTΣw−λwTμ
Quantum approach: Use QAOA to solve the optimisation problem faster.
Potential impact: Portfolio optimisation for hundreds of assets (currently limited to ~20 with classical exact methods).
4.2 Option Pricing and Monte Carlo
Quantum Amplitude Estimation (QAE) provides a quadratic speedup for Monte Carlo simulation.
Classical: O(1/ϵ)
Quantum (QAE): O(1/ϵ)
Impact: Faster option pricing, risk simulation, and stress testing.
4.3 Risk Simulation
Quantum Monte Carlo can simulate more scenarios faster, enabling:
-
More accurate Value at Risk (VaR) and Expected Shortfall (ES).
-
Faster stress testing.
-
Better scenario generation.
4.4 Fraud Detection
Grover’s search algorithm can search through transaction data faster:
Classical: O(N)
Quantum (Grover): O(N)
Impact: Faster pattern matching and anomaly detection.
4.5 Credit Scoring
Quantum linear algebra algorithms (HHL) can solve linear systems faster:
Classical: O(N3)
Quantum (HHL): O(logN)
Impact: Faster credit scoring models with large feature sets.
SECTION 5: CURRENT STATE OF QUANTUM COMPUTING
| Aspect | Status | Implications |
|---|---|---|
| Hardware | NISQ devices (50-100 qubits) with high error rates. | Limited to small problems and noise-mitigation research. |
| Quantum Volume | Increasing (IBM, Google, IonQ). | Progress toward practical utility. |
| Error Correction | Fault-tolerant quantum computing still years away. | Error correction overhead makes large-scale problems difficult. |
| Algorithms | QAOA, VQE, and QAE have been demonstrated on small problems. | Proof-of-concept for financial applications. |
| Software | Qiskit, Cirq, Pennylane, Amazon Braket. | Accessible to developers. |
| Financial Industry | Banks (JPMorgan, Goldman Sachs, Citigroup) investing in quantum research. | Early adoption and preparation. |
Timeline (Conservative Estimate):
-
Near-term (1-3 years): Quantum-inspired algorithms, hybrid quantum-classical methods.
-
Medium-term (3-5 years): NISQ devices for small-scale financial problems.
-
Long-term (5-10+ years): Fault-tolerant quantum computing for practical applications.
SECTION 6: IMPLEMENTATION IN PYTHON – QUANTUM-INSIPRED AND SIMULATED QUANTUM
# =================================================================== # MODULE 6, LESSON 6: QUANTUM COMPUTING IN FINANCE # =================================================================== import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.optimize import minimize from scipy.stats import norm import warnings warnings.filterwarnings('ignore') # Set style sns.set_style("whitegrid") np.random.seed(42) print("="*70) print("QUANTUM COMPUTING AND ITS POTENTIAL IN FINANCE") print("="*70) # ---------------------------------------------------------------- # PART A: PORTFOLIO OPTIMISATION (QUANTUM-INSPIRED) # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART A: Portfolio Optimisation – Quantum-Inspired Approach") print("-"*60) # Generate synthetic asset returns n_assets = 10 n_days = 500 returns = np.random.multivariate_normal( np.random.uniform(0.0003, 0.001, n_assets), np.random.uniform(0.01, 0.03, (n_assets, n_assets)) * 0.5 + np.diag(np.random.uniform(0.02, 0.04, n_assets)), n_days ) # Calculate mean returns and covariance mu = returns.mean(axis=0) sigma = np.cov(returns.T) print(f"Number of assets: {n_assets}") print(f"Mean returns: {mu[:5].round(6)}...") print(f"Covariance matrix shape: {sigma.shape}") # Classical Markowitz optimisation def portfolio_volatility(weights, sigma): return np.sqrt(weights.T @ sigma @ weights) def portfolio_return(weights, mu): return weights.T @ mu def negative_sharpe(weights, mu, sigma, risk_free=0.0001): ret = portfolio_return(weights, mu) vol = portfolio_volatility(weights, sigma) return -(ret - risk_free) / vol # Constraints constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) bounds = tuple((0, 1) for _ in range(n_assets)) # Optimise result = minimize(negative_sharpe, np.ones(n_assets)/n_assets, args=(mu, sigma), method='SLSQP', bounds=bounds, constraints=constraints) optimal_weights = result.x print(f"\nOptimal Portfolio (Max Sharpe):") print(f" Return: {portfolio_return(optimal_weights, mu)*100:.4f}%") print(f" Volatility: {portfolio_volatility(optimal_weights, sigma)*100:.4f}%") print(f" Sharpe Ratio: {portfolio_return(optimal_weights, mu)/portfolio_volatility(optimal_weights, sigma):.4f}") print("\nOptimal Weights (Top 5):") top_weights = pd.DataFrame({ 'Asset': [f'Asset_{i}' for i in range(n_assets)], 'Weight': optimal_weights }).sort_values('Weight', ascending=False) print(top_weights.head(5).to_string(index=False)) # ---------------------------------------------------------------- # PART B: QUANTUM MONTE CARLO – OPTION PRICING (SIMULATED) # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART B: Quantum Monte Carlo for Option Pricing (Simulated)") print("-"*60) # European call option pricing using Monte Carlo (classical) def european_call_monte_carlo(S0, K, T, r, sigma, n_paths): """Price a European call option using Monte Carlo.""" Z = np.random.standard_normal(n_paths) ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z) payoffs = np.maximum(ST - K, 0) price = np.exp(-r * T) * np.mean(payoffs) std_error = np.std(payoffs) / np.sqrt(n_paths) return price, std_error # Parameters S0 = 100 # Initial stock price K = 105 # Strike price T = 1 # 1 year r = 0.05 # Risk-free rate sigma = 0.20 # Volatility # Classical Monte Carlo n_paths_values = [1000, 10000, 100000, 1000000] prices = [] errors = [] times = [] print("Classical Monte Carlo Option Pricing:") for n_paths in n_paths_values: price, std_err = european_call_monte_carlo(S0, K, T, r, sigma, n_paths) prices.append(price) errors.append(std_err) print(f" Paths: {n_paths:8d}, Price: ${price:.4f}, Error: ${std_err:.4f}") # Quantum Monte Carlo (Quadratic speedup: O(1/n_paths) instead of O(1/sqrt(n_paths))) # For demonstration, we simulate the quantum speedup print("\nQuantum Monte Carlo (Quadratic Speedup):") # Quantum speedup means you need far fewer samples for the same accuracy # Simulate by showing the same accuracy with sqrt(n_paths) samples q_paths = [100, 1000, 10000, 100000] # sqrt of classical samples q_prices = [] for n_paths in q_paths: price, std_err = european_call_monte_carlo(S0, K, T, r, sigma, n_paths) q_prices.append(price) print(f" Paths: {n_paths:8d}, Price: ${price:.4f}, Error: ${std_err:.4f}") print("\nQuantum Advantage: Achieve same accuracy with ~1% of classical samples.") # ---------------------------------------------------------------- # PART C: RISK SIMULATION – QUANTUM SPEEDUP # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART C: Risk Simulation with Quantum Speedup") print("-"*60) # Simulate VaR using Monte Carlo with different sample sizes def simulate_var(returns, weights, n_paths, confidence=0.95): """Simulate portfolio VaR.""" # Generate portfolio returns port_returns = returns @ weights # Bootstrap to create many scenarios indices = np.random.choice(len(port_returns), (n_paths, len(port_returns)), replace=True) portfolio_scenarios = port_returns[indices].mean(axis=1) * 252 # Annualised # Compute VaR var = -np.percentile(portfolio_scenarios, (1 - confidence) * 100) return var # Use the optimal weights from above n_paths_test = [100, 1000, 10000, 100000] var_results = [] print(f"Portfolio VaR (95%, annualised):") for n_paths in n_paths_test: var = simulate_var(returns, optimal_weights, n_paths) var_results.append(var) print(f" Paths: {n_paths:8d}, VaR: {var*100:.2f}%") # Simulate quantum speedup (fewer paths) print("\nQuantum Risk Simulation:") for n_paths in [10, 100, 1000, 10000]: var = simulate_var(returns, optimal_weights, n_paths) print(f" Paths: {n_paths:8d}, VaR: {var*100:.2f}%") # ---------------------------------------------------------------- # PART D: GROVER'S SEARCH – FRAUD DETECTION # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART D: Grover's Search for Fraud Detection (Simulated)") print("-"*60) # Simulate a search problem: Find fraudulent transactions # In classical: O(N), Quantum: O(sqrt(N)) n_transactions = 10000 fraudulent_prob = 0.001 # 0.1% fraud rate is_fraud = np.random.binomial(1, fraudulent_prob, n_transactions) # Classical search def classical_search(data, target_value=1): """Classical linear search.""" for i, val in enumerate(data): if val == target_value: return i return -1 # Find a fraudulent transaction classical_result = classical_search(is_fraud) print(f"Total transactions: {n_transactions}") print(f"Fraudulent transactions: {is_fraud.sum()}") print(f"Classical search found fraud at index: {classical_result}") # Quantum speedup: Grover's algorithm would find in O(sqrt(N)) iterations n_sqrt = int(np.sqrt(n_transactions)) print(f"\nGrover's Search (Quantum): Would find a fraudulent transaction in ~{n_sqrt} steps") print(f" Classical: {n_transactions} steps") print(f" Quantum: {n_sqrt} steps") print(f" Speedup: {n_transactions/n_sqrt:.0f}x") # ---------------------------------------------------------------- # PART E: QUANTUM LINEAR ALGEBRA – CREDIT SCORING # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART E: Quantum Linear Algebra for Credit Scoring") print("-"*60) # Simulate a linear regression problem: Y = X * beta n_samples = 1000 n_features = 20 X = np.random.normal(0, 1, (n_samples, n_features)) true_beta = np.random.normal(0, 0.5, n_features) y = X @ true_beta + np.random.normal(0, 0.1, n_samples) # Classical solution # beta = (X^T X)^-1 X^T y XtX = X.T @ X Xty = X.T @ y beta_classical = np.linalg.solve(XtX, Xty) print(f"Credit Scoring Model (Linear Regression):") print(f" Samples: {n_samples}") print(f" Features: {n_features}") print(f" Classical solves O({n_features}^3) = {n_features**3} operations") # Quantum (HHL) would solve in O(log(n_features)) print(f"\nQuantum HHL Algorithm: Would solve in O(log({n_features})) = {np.log(n_features):.2f} operations") print(f" Speedup: {n_features**3 / np.log(n_features):.0f}x") # ---------------------------------------------------------------- # PART F: QUANTUM COMPUTING ROADMAP # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART F: Quantum Computing Roadmap for Banking") print("-"*60) roadmap = { "Phase 1 (Now – 2 Years)": { "Actions": [ "Build quantum readiness team.", "Explore quantum-inspired algorithms (tensor networks).", "Run proof-of-concept on NISQ devices.", "Train staff in quantum computing fundamentals." ], "Focus": "Education and exploration." }, "Phase 2 (2 – 5 Years)": { "Actions": [ "Implement hybrid quantum-classical algorithms.", "Pilot quantum annealing for optimisation problems.", "Develop error mitigation techniques.", "Partner with quantum computing vendors (IBM, Google, IonQ)." ], "Focus": "Hybrid applications and small-scale problem solving." }, "Phase 3 (5 – 10 Years)": { "Actions": [ "Deploy fault-tolerant quantum computing for critical applications.", "Scale quantum solutions to large financial problems.", "Integrate quantum computing into core financial workflows.", "Develop in-house quantum expertise." ], "Focus": "Full-scale quantum advantage." } } for phase, details in roadmap.items(): print(f"\n{phase}:") print(f" Focus: {details['Focus']}") print(" Actions:") for action in details['Actions']: print(f" • {action}") # ---------------------------------------------------------------- # PART G: QUANTUM-INSPIRED OPTIMISATION (TENSOR NETWORKS) # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART G: Quantum-Inspired Optimisation (Tensor Networks)") print("-"*60) print(""" Tensor Networks are a quantum-inspired technique that can be used today: 1. What are Tensor Networks? - Mathematical structures for representing high-dimensional data. - Used in quantum many-body physics. - Can be applied to optimisation and machine learning. 2. Applications in Finance: - Portfolio optimisation with hundreds of assets. - Risk factor decomposition. - Option pricing with high-dimensional models. 3. Implementation: - Libraries: TensorNetwork (Google), quimb, ncon. - Can run on classical hardware. - Provides a path to quantum readiness. 4. Advantages: - Works with classical hardware today. - Often provides better results than classical methods. - Prepares teams for quantum computing. """) # ---------------------------------------------------------------- # PART H: SUMMARY AND RECOMMENDATIONS # ---------------------------------------------------------------- print("\n" + "="*70) print("PART H: Summary and Recommendations") print("="*70) print(""" Quantum Computing in Finance – Key Takeaways: 1. Potential Advantages: - Portfolio Optimisation: Exponential speedup. - Option Pricing: Quadratic speedup. - Risk Simulation: Quadratic speedup. - Fraud Detection: Quadratic speedup. 2. Current State: - NISQ devices (50-100 qubits) with high error rates. - Fault-tolerant quantum computing is 5-10+ years away. - Research is active; banks are investing. 3. Quantum-Inspired: - Tensor networks provide benefits today. - Hybrid quantum-classical algorithms are being explored. - Quantum annealing (D-Wave) for optimisation. 4. Roadmap: - Phase 1 (now): Education and exploration. - Phase 2 (2-5 years): Hybrid applications. - Phase 3 (5-10+ years): Full-scale quantum advantage. 5. Recommendations: - Build quantum readiness team. - Explore quantum-inspired algorithms. - Partner with quantum vendors. - Train staff in quantum computing fundamentals. - Monitor progress in quantum hardware and algorithms. """) print("="*70) print("END OF LESSON 6 – MODULE 6") print("END OF MODULE 6") print("="*70)
SECTION 7: COMPARISON OF CLASSICAL VS QUANTUM METHODS
| Problem | Classical Complexity | Quantum Complexity | Speedup | Quantum Algorithm |
|---|---|---|---|---|
| Portfolio Optimisation (exact) | O(2N) | O(N2) | Exponential | QAOA |
| Option Pricing (MC) | O(1/ϵ) | O(1/ϵ) | Quadratic | QAE |
| Risk Simulation (MC) | O(1/ϵ) | O(1/ϵ) | Quadratic | QAE |
| Fraud Detection (search) | O(N) | O(N) | Quadratic | Grover |
| Credit Scoring (linear algebra) | O(N3) | O(logN) | Exponential | HHL |
| Cryptography (factoring) | O(exp(n1/3)) | O(n3) | Exponential | Shor |
SECTION 8: KEY TERMS AND DEFINITIONS
| Term | Definition |
|---|---|
| Qubit | Quantum bit; can be in superposition of 0 and 1. |
| Superposition | The ability of a qubit to be in multiple states simultaneously. |
| Entanglement | Quantum correlation between qubits; measurement of one affects the other. |
| Quantum Gate | Operation on qubits (like classical logic gates). |
| Quantum Circuit | Sequence of quantum gates. |
| NISQ | Noisy Intermediate-Scale Quantum – current quantum devices with errors. |
| Fault-Tolerant | Quantum computing with error correction; required for large-scale problems. |
| Quantum Advantage | When a quantum computer can solve a problem faster than any classical computer. |
| Quantum Annealing | Specialised quantum computing for optimisation (D-Wave). |
| QAOA | Quantum Approximate Optimisation Algorithm for combinatorial problems. |
| QAE | Quantum Amplitude Estimation for Monte Carlo simulation. |
| HHL | Harrow-Hassidim-Lloyd algorithm for solving linear systems. |
SECTION 9: SUMMARY FOR THE DATA PRACTITIONER
-
Quantum computing offers potential exponential and quadratic speedups for key financial problems.
-
Current state: NISQ devices (noisy, limited qubits) require error mitigation and hybrid approaches.
-
Quantum-inspired algorithms (tensor networks) provide benefits today and prepare teams for quantum.
-
Key applications: Portfolio optimisation, option pricing, risk simulation, fraud detection, credit scoring.
-
Roadmap: Short-term (exploration), medium-term (hybrid), long-term (fault-tolerant).
-
Recommendation: Start building quantum readiness now – the technology is advancing rapidly.
SECTION 10: RECOMMENDED NEXT STEPS
-
Explore quantum computing with Qiskit or Cirq (free simulators).
-
Learn about tensor networks and quantum-inspired algorithms.
-
Identify financial problems that could benefit from quantum computing.
-
Partner with quantum vendors (IBM, Google, IonQ, D-Wave).
-
Attend quantum computing workshops and conferences.
-
Prepare for the next lesson on the Future of Financial Data Analytics.