Portfolio Optimization using Qiskit and Eikon Data API

Shadab Hussain
LSEG Developer Community
12 min readNov 3, 2021

--

1. Introduction

Financial institutions are testing early use-cases of Quantum Technologies for NP-hard problems which are uncertain or difficult to optimize. In this article, we are going to make use of quantum computers for building an optimal portfolio out of FAANG (Facebook, Apple, Amazon, Netflix, Google) stocks using the mean-variance portfolio optimization technique. Initially, we will talk about the basics of Quantum Computing and Portfolio Optimization. Later on, we will jump to coding- where we will do the initial setup, load data from Eikon API, do some basic analysis, implement mean-variance portfolio technique classically and then use VQE & QAOA.

1.1 Introduction to Quantum Computing

1.PNG

Quantum computing is an area of computing that focuses on developing computer technology based on quantum theory’s concepts (which explains the behavior of energy and material at the atomic and subatomic levels).

Computers used today can only encode information in bits that take the value of 1 or 0, whereas, in Quantum computing, we have quantum bits, called qubits. QuBits can be in the state 0,1 & 0|1 (superposition- existing simultaneously with a certain probability across the spectrum of 0 to 1). This helps us achieve parallel programming and hence solve computations at an exponential speed compared to a normal computer. When qubits are measured, they will either collapse to 0 or 1.

So, in short, a Quantum Computer makes use of quantum mechanical phenomena such as superposition and entanglement to perform computation.

2.PNG

Superposition

A quantum system’s ability to be in numerous states at the same time until it is measured is known as superposition.

To illustrate this Schrodinger posited a thought experiment involving putting a cat and a sealed bottle of poison in a closed box together. The question now is, how would we know if the poison bottle broke open and the cat died or if the cat is still alive inside the box?

Entanglement

Quantum entanglement is a quantum mechanical phenomenon in which the quantum states of two or more objects must be described in relation to each other, even if the individual objects can be spatially separated.

One of the most commonly used qubits is photon spins. A photon can either have spin up (one state) or spin down (zero states). If we have two entangled photons, then they must have opposite spins, if one is up then the other must be down.

In this article, we will explore about Portfolio Optimization problem and see how we can solve them with Qiskit.

1.2 Why Quantum Computing for Finance

Applications of QC in finance are currently being developed and worked on. Two such applications are:

Portfolio Optimization- It is an optimization problem where we have a collection of assets and we want to select these assets that maximize our return but at the same time minimize the risk. These optimization problems can be formulated as quadratic programs which are well studied classically and are very difficult to solve.

Option Pricing- It is an estimation problem and these problems mostly rely on Monte Carlo simulations. If the function that we want to estimate is a difficult function, then classical computers will have a very slow convergence.

With a quantum computer, there are two possible approaches with which we hope to improve optimization algorithms that we can run in the near-term devices that we already have today and fault-tolerant devices in the next couple of years.

Heuristic algorithms like Variational Quantum Eigensolver (Variational algorithm) have a classical and a quantum processor, so it depends on the problem that we want to solve and the models that we have and there’s no speed up that we can prove here right now.

On the other hand, if we look into the future when we get fault-tolerant quantum computers then there are algorithms based on Grover Search like Grover Adaptive Search where we can expect quadratic speed up.

For Monte Carlo Simulations, there’s a quantum algorithm called the Quantum Amplitude Estimation algorithm with which we can also expect a quadratic speed up.

1.3 Qiskit Finance

Let’s have a short overview of what Qiskit Finance is, and what sub-modules it contains

image-2.png

Two applications module available in Qiskit Finance, that we can see in the above diagram:

  • Portfolio Optimization
  • Option Pricing

It gives us the tools to solve optimization and option pricing problems like the European Call Option or fixed-income pricing.

It also has the sub-modules containing circuits and tools to build these quantum circuits that we need to run these algorithms.

We also have some modules for data providers where we can load random data or we can even load historical stock market data to test our algorithms. Here we have extended the historical data loading module to load data from Eikon API.

1.4 Mean-Variance Portfolio Optimization

Portfolio optimization is a process of selecting the best assets out of the available options in order to maximize the return and minimize the risk. For more info read here.

First, we need to find the best-performing assets and then decide how much need to be invested in each of the selected assets.
Some of the basic terms before moving ahead:
Risk: Deviation of the return on investment from the expected level.
Return: Reward of investment to a given asset.
Portfolio: Collection of assets such as stocks, currencies, bonds, etc.

There are different strategies/frameworks for Portfolio Optimization, however, in this article, we are going to use Mean-Variance Portfolio Theory also known as Modern Portfolio Theory (MPT) which is a very basic one but good to explore use case on quantum computers and it evaluate assets in two dimensions that is risk and return. Using MPT we will find the assets to invest in out of available options, in our case which is FAANG.

Let’s see how we will be solving the mean-variance portfolio optimization problem for nassets:

where we use the following notation:

  • 𝑥∈{0,1}ⁿ denotes the vector of binary decision variables, which indicate which assets to pick (𝑥[𝑖]=1) and which not to pick (𝑥[𝑖]=0),
  • 𝜇∈ℝⁿ defines the expected returns for the assets,
  • Σ∈ℝⁿ*ⁿ specifies the covariances between the assets,
  • 𝑞>0 controls the risk appetite of the decision-maker,
  • and 𝐵 denotes the budget, i.e. the number of assets to be selected out of 𝑛.

We assume that one has to select exactly 𝐵 assets.

The equality constraint 1ᵀ𝑥=𝐵 is mapped to a penalty term (1ᵀ𝑥−𝐵)² 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. In this notebook, we will see how to use the Variational Quantum Eigensolver (VQE) or the Quantum Approximate Optimization Algorithm (QAOA) to find the optimal solution for a given set of parameters.

Example of Mean-Variance Analysis

It is possible to calculate which investments have the greatest variance and expected return. Assume the following investments are in an investor’s portfolio:

Asset A: Amount = $1000 with the expected return of 5%

Asset B: Amount = $3000 with the expected return of 10%

In a total portfolio value, the weight of each asset is 25% and 75% respectively.

Therefore, the total expected return of the portfolio is the weight of the asset in the portfolio multiplied by the expected return:

Portfolio expected return = (25% * 5%) + (75% * 10%) = 8.75%. Portfolio variance is more complicated to calculate because it is not a simple weighted average of the investments’ variances. The correlation between the two investments is 0.65. The standard deviation, or the square root of the variance, for Investment A, is 7%, and the standard deviation for Investment B is 14%.

In this example,

Portfolio variance = (25% ^ 2 * 7% ^ 2) + (75% ^ 2 * 14% ^ 2) + (2 * 25% * 75% * 7% * 14% * 0.65) = 0.0137

The portfolio standard deviation is the square root of the answer: 11.71%.

Number of Possible Combination of Assets for FAANG

Since we have 5 assets in the list from which we are going to find optimal asset names to be invested, we will be making use of 5 qubits, where each qubit will be mapped with one asset. A 5-qubit system uses combinations of numbers up to five-place values `11111` and each place value will be representing one of the assets.

There are 2⁵ (32) states (possible combinations of assets):
00000, 00001, 00010, 00100, 01000, 10000, 00011, 00110, 01100, 11000, 10001, 10100, 00101, 01010, 01001, 10010, 00111, 01110, 11100, 11001, 10011, 10101, 01011, 01101, 10110, 11010, 01111, 11110, 10111, 11011, 11101, and 11111.

We will be observing the probabilities and optimal values of these states when running them on classical and quantum computers.

Current Limitations

  • Quantum Systems with a lesser number of qubit available publicly
  • Fault-tolerant Quantum Systems to be built for quadratic speed up
  • More efficient ways to load classical data into quantum states and perform fast computations with them
  • An effective quantum error rate of the hardware should be very small, in order to ensure that no errors occur in the applications, however, a quantum error correction algorithm can be used to lower this

2. Environment Setup & Package Installation

Assuming you already have anaconda installed or python supported IDE To execute the below codes, we need to install the following modules:

2.1 Qiskit Setup & Installation

Qiskit: An open-source SDK for working with quantum computers at the level of circuits, algorithms, and application modules. For more info, visit here.

Qiskit Finance: It contains uncertainty components for stock/securities problems, Ising translators for portfolio optimizations and data providers to source real or random data to finance experiments. For more info, visit here.

Execute the below cells to install Qiskit and its components:

Check the version of Qiskit and its installed components

[Optional] Set up a token to run the experiment on a real device

If you would like to run the experiment on a real device, you need to set up your account first. You can get your API token from here

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

2.2 Eikon API Installation

Eikon API: It allows to access data directly from Eikon or Refinitv Workspace using python giving capabilities to data scientists, quants to prototype or production solutions. For more info, visit here.

Execute the below cells to install Eikon:

Check version of the Eikon API

Setup Eikon API

I have saved my Eikon Data API key in a text file for security reasons and not displaying here in the notebook.

Other packages which need to be installed if not installed already- numpy, pandas, matplotlib, seaborn

Importing Packages

3. Getting Data using Eikon API & Pre-Processing

Defining EikonDataProvider class for Loading Data as needed by Qiskit

We will inherit BaseDataProvider from the data provider module of Qiskit Finance to extend its functionality of getting data from Eikon API in the desired format and make use of existing functions.

Initializing Required Parameters

Getting data from Eikon API using EikonDataProvider class

png

Statistical Data of the Loaded Data

png

Closing Price History Chart

png

Expected Return (Mean) of each Asset

png

Covariance Matrix

Diagonal elements of the covariance matrix shows the variance of each of the assets whereas off-diagonal elements shows the correlation of one asset with the other assets.

png

Correlation Matrix

png

Let’s explore the data by plotting a 5*5 matrix with the correlation of the returns between the five stocks. We can see that the stocks’ returns are strongly correlated. At the same time, we plotted the histogram of the returns in the diagonal of the matrix. We can estimate that the returns are not distributed normally due to the leptokurtic shape of the histogram. At the same time, we can see that the stocks’ returns are strongly correlated.

png

Here an Operator instance is created for our Hamiltonian. In this case, the Paulis are from an Ising Hamiltonian translated from the portfolio problem.

Utility Functions

4. Classical Implementation using Eigen Solver

Classical Eigensolver

Let's 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 and not using quantum computation. The result is returned as a dictionary.

Classical Benchmark

png

5. VQE Implementation

First, let’s understand what is VQE

The Variational Quantum Eigensolver (VQE) algorithm is one of the essential algorithms to learn in the NISQ era. It makes the idea of the famous Quantum Phase Estimation Algorithm usable with the small number of qubits Quantum Computers currently possess. VQE presents us with a hybrid quantum-classical approach to tackle the current hardware limits.

VQE exploits the fact that the ground state energy is always less than or equal to the expectation value of the Hamiltonian of the state. Hence, by minimizing the expectation value of the Hamiltonian, we can find the upper bound of the ground state energy. And by varying the state, we can find the wave function on which the value of the expectation value is the lowest.

VQE, in a straightforward language, consists of three steps:

  • Converting the Hamiltonian into Pauli basis
  • Creation of a variational form
  • Parameter Optimization

Goal: Find ground state |Ψ⟩ of the Hamiltonian 𝐻.

Idea: Choose model |𝜙(𝜃)⟩ that can approximate |Ψ⟩ well and minimize the energy

For more info, visit here.

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

VQE Benchmark

png

6. QAOA Implementation

The Quantum Approximate Optimization Algorithm (QAOA) is a widely-studied method for solving combinatorial optimization problems on NISQ devices. The applications of QAOA are broad and far-reaching, and the performance of the algorithm is of great interest to the quantum computing research community.

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.

For more info, visit here.

QAOA Benchmark

png

7. Conclusion

Portfolio optimization is just one of the many applications that can be solved using Quantum Computers. As we can observe above, the output from Classical EigenSolver matches with the output of VQE and QAOA implementation. Quantum computers are expected to have a substantial impact on the Finance industry, as they will eventually be able to solve certain problems considerably faster than the best known classical algorithms.

Currently, it is a major challenge to determine when this impact will occur for each application, and, in fact, one of the most pressing challenges is to redesign quantum algorithms in order to both considerably reduce the quantum hardware requirements and at the same time keep their provable impact.

I hope this article gives the reader a good start in the exploration of the wonderful field of research on portfolio construction and optimization. Advances in quantum algorithms together with better quantum hardware will continue to bring these applications closer to reality.

Downloads

You can download the complete code from this github repo.

References

To learn more about the amazing contents Eikon Data API has to offer, visit at this link.

Learn more about Refinitiv products and play around different APIs available on the developer portal.

For any question related to this example or Eikon Data API, please use the Developers Community Q&A Forum.

Don’t forget to register on https://developers.refinitiv.com/ and be part of our developer community.

--

--

Shadab Hussain
LSEG Developer Community

MLOps @themathcompany, #AWS Community Builder for #data, #DataScience, #Quantum, #MachineLearning