Portfolio Optimization using Quantum Computing

I made a Portfolio Optimiser using Hadamard Gate and Quantum circuits. I used a Qiskit simulator (qasm_simulator) to simulate the circuits of qubits, transpiled the circuit to run it in the backend. I also compared the quantum approach with classical portfolio optimisation techniques and discussed the differences. Monte Carlo Simulation of the assets was also done to forecast their future variations.

Aman Behera
8 min readNov 4, 2023

Here I focused on Portfolio Optimisation and forecasting using sub-modules offered by qiskit. I also compared how the classical and quantum approaches compare to each other, thus providing a brief insight into how quantum computing techniques may be used to solve NP-hard problems (mean-variance optimization problem in this case) Taking inspiration from my previous project upon Monte Carlo simulation of time series, I have extended the discussion into quantum techniques as I was curious to see how they perform in comparison to classical techniques.

Make sure u checked my previous article to get a brief insight into the Monte Carlo Simulation, it would help you through this article.

First things First

Importing required libraries for analysis of portfolios

Yfinance for fetching the data

Qiskit for quantum computing algos, packages

Time for recording the time taken

Fetching the data and pre-processing

Let’s understand whats going on in this snippet

1) Firstly we choose what companies the investor is gonna focus on, it’s list is stored in tickers

2) We use the yfinance module to fetch data within the required time frame (b/w start and end dates)

3) We choose to focus on ‘Adj Close’ as it helps investors know the fair value of the stock after the corporate action is announced and also helps maintain an accurate record of where the stock price starts and where it ends so we choose to the analysis of it instead of closing price.

4) We calculate the daily percentage change and drop the NaN columns out of it

5) We find the cov and corr matrix of the returns

6) and fix a risk_free_rate (which can be changed and we will see how changing it would affect our optimization later)

But why Adjusted Close?

Here our main focus is on “Adjusted Close” section of the data, it means the cash value of the last transacted price before the market closes. The adjusted closing price is attributed to anything that would affect the stock price after the market closes for the day.

The adjusted closing price of the stock helps investors know the fair value of the stock after the corporate action is announced and also helps maintain an accurate record of where the stock price starts and where it ends so we choose to analyze it instead of the closing price.

Visualizing how the assets relate to each other, and how a change in one affects the others

For this we use covariance and correlation matrix to understand how the portfolio assets relate to each other, it’s important because we want our portfolio to be diversified, imagine there is a market crash and all assets are related in a similar manner hence the investor would only incur a loss, whereas if the assets are related in an opposite manner then some assets might produce enormous gains which would counterbalance the loss incurred by majority of the assets.

But at the same time if everything were to be normal then, going in the direction opposite to the direction of flow may be a risk-taking move. Thus this forms the basis of the risk-return optimization.

Heat map to demonstrate the matrices visually

But what do we infer from heatmaps?

Correlation, in the finance and investment industries, is a statistic that measures the degree to which two securities move in relation to each other the values are restricted to lie between -1 and +1.

A correlation of +1 means positive relation, i.e, if the correlation between Asset A and Asset B is 1, if Asset A increases, Asset B increases. A correlation of 0 means no relation.

Covariance tells you that two variables change the same way while correlation reveals how a change in one variable affects a change in the other.

Let’s head to Portfolio Optimisation

Quantum Register: The circuit is initialized with a quantum register containing num_assets qubits. In this example, num_assets is the number of assets in the portfolio.

Hadamard Gates (H): For each qubit in the register, a Hadamard gate (H) is applied. The Hadamard gate creates a superposition of basis states. In other words, it puts each qubit into a state where it has an equal probability of being in state |0> or |1>. This is a key step in quantum algorithms because it allows the quantum system to explore multiple states simultaneously.

Example: If there are 3 assets (qubits), the Hadamard gate is applied to each qubit, creating a superposition of 8 possible states: |000>, |001>, |010>, |011>, |100>, |101>, |110>, |111>. After applying the Hadamard gates, all qubits are measured. Measurement collapses the superposition of states into a specific outcome. Each qubit will yield either a |0> or a |1> with equal probability.

Defining the Simulator Backend- (backend = Aer.get_backend(‘qasm_simulator’))

Here, a quantum simulator backend is defined using the `Aer` module from Qiskit. The `’qasm_simulator’` is a simulator that allows us to simulate the behavior of a quantum circuit on a classical computer.

Transpiling the Quantum Circuit (t_qc = transpile(qc, backend))

The `transpile` function is used to convert the quantum circuit (`qc`) into a form that can be executed on the chosen backend. It transforms the high-level abstract operations in `qc` into the specific set of quantum gates supported by the target device.

Running the Transpiled Circuit on the Simulator (result = backend.run(t_qc, shots=1000).result())

backend.run(t_qc, shots=1000)` executes the transpiled quantum circuit `t_qc` on the chosen simulator backend. The `shots` parameter specifies how many times the circuit is executed to gather statistics.

Overall, this code block is responsible for preparing the quantum circuit for execution, selecting a simulator backend for the execution, transpiling the circuit for compatibility with the backend, and running the simulation with a specified number of shots. The result obtained represents the outcomes of the measurements in the quantum circuit.

Just to make sure we are in the same page

1.Transpile: is a function in Qiskit that takes a quantum circuit and converts it into a form that is suitable for execution on a specific quantum device or simulator.

2.Backend: a “backend” refers to the actual hardware or simulator on which a quantum circuit is executed. It could be a real quantum device, or it could be a classical simulator that emulates the behavior of a quantum computer.

3.qasm_simulator is a specific type of backend provided by Qiskit’s Aer module. It is a quantum simulator that emulates the behavior of a quantum computer on a classical computer.

4.Shots: a “shot” refers to a single execution of a quantum circuit.

Classical Approach

You may refer to my previous article to get a brief understanding of how the classical approach works.

The portfolio weights (w) are computed using linear algebra operations. It involves the dot product of the inverse covariance matrix and the expected returns, normalized by the dot product of the ones array and the result of another dot product operation.

The expected return of the portfolio is calculated as the dot product of the portfolio weights (w) and the expected returns of the assets (mu).

The standard deviation of the portfolio is calculated using linear algebra operations involving the covariance matrix (cov_matrix) and the portfolio weights (w).

The function returns the portfolio weights (w), expected return of the portfolio, and standard deviation of the portfolio.

In summary, it performs classical portfolio optimization by computing the optimal weights for assets in the portfolio, along with the expected return and standard deviation of the resulting portfolio.

Calculate the time required by both approaches

We calculate the time required for optimisation in both scenarios

Comparision

In this particular case, the classical approach is outperforming the quantum approach but, if we consider bigger portfolios and more complex relations then the quantum approach would be outperforming the classical analogy.

Also, Running a quantum simulation on a classical computer can sometimes be slower than performing the classical calculations directly, especially for small problem sizes.

A bar graph analyzing the difference in outputs by both approaches

Extras - Monte Carlo simulation and forecasting of the stock prices

The more the variance the more the spread is, and the less the steepness is.

In context to Monte Carlo Simulation, the random paths generated would be less differentiating if the variance is less and it would be more if the variance is more resulting in a flatter curve.

Where to go from here?

Here are some recommendations u may use to add to diversify the depth of analysis:

  1. Usage of log returns instead of daily returns for a better picture

2. Using normality quantifications measure to understand why log returns are better than simple returns

3. Observing how changing the risk factor changes the optimal portfolio

4. Using different risk-return measures to plot the efficient frontier (Sharpe ratio for example)

5. How using ABM over GBM changes the final outcome

For the complete codebase refer to my GitHub https://github.com/beingamanforever/MCS-using-Quantum-Computing

References used:

  1. My previous article
  2. Qiskit documentation on portfolio optimisation
  3. https://youtu.be/5S38HYloiaY?si=aCkXUoEPU0sCEcTb

--

--

Aman Behera

I am an ML Enthusiast. I love to keep myself indulged in competitive programming, writing blogs on tech, & sketching in my free time.