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:

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`

) 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.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
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
```

```
/tmp/ipykernel_2538/1146382125.py:1: DeprecationWarning: ``qiskit.algorithms`` has been migrated to an independent package: https://github.com/qiskit-community/qiskit-algorithms. The ``qiskit.algorithms`` import path is deprecated as of qiskit-terra 0.25.0 and will be removed no earlier than 3 months after the release date. Please run ``pip install qiskit_algorithms`` and use ``import qiskit_algorithms`` instead.
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
```

### [Optional] Setup token to run the experiment on a real device¶

If you would like to run the experiment on a real device, you need to setup your account first.

Note: If you do not store your token yet, use `IBMQ.save_account('MY_API_TOKEN')`

to store it first.

## 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()
```

```
[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.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")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.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.7334
[0 0 1 1] -0.0010 0.2041
[0 1 1 0] 0.0008 0.0244
[0 0 0 1] -0.0008 0.0127
[1 1 0 1] -0.0139 0.0078
[1 1 1 1] -0.0139 0.0039
[1 0 1 1] -0.0150 0.0039
[0 0 0 0] 0.0000 0.0029
[0 1 0 0] 0.0009 0.0020
[1 1 0 0] -0.0130 0.0020
[0 0 1 0] -0.0001 0.0020
[0 1 0 1] 0.0002 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 1 0 0] -0.0130 0.1650
[0 1 1 0] 0.0008 0.1650
[0 1 0 1] 0.0002 0.1631
[1 0 1 0] -0.0140 0.1533
[0 0 1 1] -0.0010 0.1504
[1 0 0 1] -0.0149 0.1475
[1 1 1 1] -0.0139 0.0107
[0 0 1 0] -0.0001 0.0078
[0 0 0 0] 0.0000 0.0068
[1 1 0 1] -0.0139 0.0059
[0 1 0 0] 0.0009 0.0059
[1 1 1 0] -0.0130 0.0049
[1 0 1 1] -0.0150 0.0049
[0 0 0 1] -0.0008 0.0039
[0 1 1 1] -0.0000 0.0029
[1 0 0 0] -0.0140 0.0020
```

```
[9]:
```

```
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
```

### Version Information

Software | Version |
---|---|

`qiskit` | None |

`qiskit-terra` | 0.25.1 |

`qiskit_finance` | 0.3.4 |

`qiskit_optimization` | 0.5.0 |

`qiskit_aer` | 0.12.2 |

System information | |

Python version | 3.8.17 |

Python compiler | GCC 11.3.0 |

Python build | default, Jun 7 2023 12:29:56 |

OS | Linux |

CPUs | 2 |

Memory (Gb) | 6.7694854736328125 |

Thu Aug 31 21:45:37 2023 UTC |

### This code is a part of Qiskit

© Copyright IBM 2017, 2023.

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.

```
[ ]:
```

```
```