Note

This page was generated from docs/tutorials/01_portfolio_optimization.ipynb.

Portfolio Optimization#

Introduction#

This tutorial shows how to solve the following mean-variance portfolio optimization problem for \(n\) assets:

\[\begin{split}\begin{aligned} \min_{x \in \{0, 1\}^n} q x^T \Sigma x - \mu^T x\\ \text{subject to: } 1^T x = B \end{aligned}\end{split}\]

where we use the following notation:

  • \(x \in \{0, 1\}^n\) denotes the vector of binary decision variables, which indicate which assets to pick (\(x[i] = 1\)) and which not to pick (\(x[i] = 0\)),

  • \(\mu \in \mathbb{R}^n\) defines the expected returns for the assets,

  • \(\Sigma \in \mathbb{R}^{n \times n}\) specifies the covariances between the assets,

  • \(q > 0\) controls the risk appetite of the decision maker,

  • and \(B\) denotes the budget, i.e. the number of assets to be selected out of \(n\).

We assume the following simplifications: - all assets have the same price (normalized to 1), - the full budget \(B\) has to be spent, i.e. one has to select exactly \(B\) assets.

The equality constraint \(1^T x = B\) is mapped to a penalty term \((1^T x - B)^2\) which is scaled by a parameter and subtracted from the objective function. The resulting problem can be mapped to a Hamiltonian whose ground state corresponds to the optimal solution. This notebook shows how to use the Sampling Variational Quantum Eigensolver (SamplingVQE) or the Quantum Approximate Optimization Algorithm (QAOA) from Qiskit Algorithms to find the optimal solution for a given set of parameters.

Experiments on real quantum hardware for this problem are reported for instance in the following paper: Improving Variational Quantum Optimization using CVaR. Barkoutsos et al. 2019.

[1]:
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_algorithms import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit_algorithms.optimizers import COBYLA
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime

Define problem instance#

Here an Operator instance is created for our Hamiltonian. In this case the paulis are from an Ising Hamiltonian translated from the portfolio problem. We use a random portfolio problem for this notebook. It is straight-forward to extend this to using real financial data as illustrated here: Loading and Processing Stock-Market Time-Series Data

[2]:
# set number of assets (= number of qubits)
num_assets = 4
seed = 123

# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
    tickers=stocks,
    start=datetime.datetime(2016, 1, 1),
    end=datetime.datetime(2016, 1, 30),
    seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
[3]:
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
../_images/tutorials_01_portfolio_optimization_5_0.png
[4]:
q = 0.5  # set risk factor
budget = num_assets // 2  # set budget
penalty = num_assets  # set parameter to scale the budget penalty term

portfolio = PortfolioOptimization(
    expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
[4]:
<QuadraticProgram: minimize 0.001270694296030004*x_0^2 + 7.34022166934733e-05*..., 4 variables, 1 constraints, 'Portfolio optimization'>

We define some utility methods to print the results in a nice format.

[5]:
def print_result(result):
    selection = result.x
    value = result.fval
    print("Optimal: selection {}, value {:.4f}".format(selection, value))

    eigenstate = result.min_eigen_solver_result.eigenstate
    probabilities = (
        eigenstate.binary_probabilities()
        if isinstance(eigenstate, QuasiDistribution)
        else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
    )
    print("\n----------------- Full result ---------------------")
    print("selection\tvalue\t\tprobability")
    print("---------------------------------------------------")
    probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)

    for k, v in probabilities:
        x = np.array([int(i) for i in list(reversed(k))])
        value = portfolio.to_quadratic_program().objective.evaluate(x)
        print("%10s\t%.4f\t\t%.4f" % (x, value, v))

NumPyMinimumEigensolver (as a classical reference)#

Lets solve the problem. First classically…

We can now use the Operator we built above without regard to the specifics of how it was created. We set the algorithm for the NumPyMinimumEigensolver so we can have a classical reference. The problem is set for ‘ising’. Backend is not required since this is computed classically not using quantum computation. The result is returned as a dictionary.

[6]:
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)

result = exact_eigensolver.solve(qp)

print_result(result)
Optimal: selection [1. 0. 0. 1.], value -0.0149

----------------- Full result ---------------------
selection       value           probability
---------------------------------------------------
 [1 0 0 1]      -0.0149         1.0000

Solution using SamplingVQE#

We can now use the Sampling Variational Quantum Eigensolver (SamplingVQE) to solve the problem. We will specify the optimizer and variational form to be used.

[7]:
from qiskit_algorithms.utils import algorithm_globals

algorithm_globals.random_seed = 1234

cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
svqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
svqe = MinimumEigenOptimizer(svqe_mes)
result = svqe.solve(qp)

print_result(result)
Optimal: selection [1. 0. 0. 1.], value -0.0149

----------------- Full result ---------------------
selection       value           probability
---------------------------------------------------
 [1 0 0 1]      -0.0149         0.4893
 [0 1 1 0]      0.0008          0.4600
 [0 1 0 1]      0.0002          0.0137
 [0 1 0 0]      0.0009          0.0137
 [1 1 1 0]      -0.0130         0.0117
 [0 0 1 1]      -0.0010         0.0078
 [1 0 1 0]      -0.0140         0.0020
 [1 1 1 1]      -0.0139         0.0010
 [0 0 0 1]      -0.0008         0.0010

Solution using QAOA#

We also show here a result using the Quantum Approximate Optimization Algorithm (QAOA). This is another variational algorithm and it uses an internal variational form that is created based on the problem.

[8]:
algorithm_globals.random_seed = 1234

cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)

print_result(result)
Optimal: selection [1. 0. 0. 1.], value -0.0149

----------------- Full result ---------------------
selection       value           probability
---------------------------------------------------
 [1 0 0 1]      -0.0149         0.1758
 [1 0 1 0]      -0.0140         0.1709
 [0 1 1 0]      0.0008          0.1680
 [1 1 0 0]      -0.0130         0.1660
 [0 1 0 1]      0.0002          0.1631
 [0 0 1 1]      -0.0010         0.1475
 [0 1 0 0]      0.0009          0.0020
 [1 1 1 0]      -0.0130         0.0020
 [0 1 1 1]      -0.0000         0.0020
 [0 0 1 0]      -0.0001         0.0010
 [1 0 0 0]      -0.0140         0.0010
 [1 1 0 1]      -0.0139         0.0010
[9]:
import tutorial_magics

%qiskit_version_table
%qiskit_copyright

Version Information

SoftwareVersion
qiskit1.0.1
qiskit_finance0.4.1
qiskit_aer0.13.3
qiskit_algorithms0.3.0
qiskit_optimization0.6.1
System information
Python version3.8.18
OSLinux
Thu Feb 29 03:06:00 2024 UTC

This code is a part of a Qiskit project

© Copyright IBM 2017, 2024.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.

Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.

[ ]: