Backtesting_quantum_computing_algorithms_for_portf
Backtesting_quantum_computing_algorithms_for_portf
INDEX TERMS Backtesting, CVaR VQE, Portfolio Optimization, Quantum Computing, VQE
VOLUME 4, 2016 1
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
that uses a quantum computer to find the lowest energy state as there are many factors that need to be considered, such
of a system, which in this case would be the optimal portfolio as investment objectives, constraints, market conditions, and
[6]. To test whether VQE can outperform classical algorithms individual preferences. This typically involves analyzing the
for optimization, researchers at IBM conducted a series of potential risks and returns of different assets, such as stocks,
experiments on IBM Quantum devices [7]. They found that bonds, and real estate, and then creating a balanced portfolio
VQE was able to find the global minimum in most cases and that aligns with the investor’s risk tolerance and financial
theoretically can outperform classical algorithms when the goals.
number of assets in the portfolio was large. While further The process of portfolio optimization involves several
research is needed to determine if VQE can be successfully key steps. First, the investor must define their investment
applied to real-world financial portfolios, these results sug- objectives, including their desired level of risk and return.
gest that quantum computers may one day play an important This will help to determine the overall mix of assets that
role in helping us make better investment decisions. should be included in the portfolio. Next, the investor must
Backtesting is crucial in evaluating the performance of a identify the various assets that are available for inclusion in
portfolio optimization algorithm. It involves using historical the portfolio and analyze their potential risks and returns.
data or Monte Carlo simulations to determine the algorithm’s Then, the investor must determine the optimal mix of assets
ability to find the optimal portfolio and assess its robustness. that will form the portfolio. This typically involves using
When backtesting, one should consider using a large enough mathematical optimization techniques to find the combina-
dataset, paying attention to results from different tests, and tion of assets that are expected to provide the best return for
including a risk analysis to understand potential downsides. a given level of risk. Finally, the investor must implement
However, past performance does not guarantee future results. the chosen portfolio and monitor it regularly to ensure that it
This work explores the backtesting of quantum and clas- is still meeting the investment objectives. This may involve
sical computing algorithms for portfolio optimization and adjusting the portfolio, such as buying or selling assets, in
compares the results. We address the challenges involved in order to maintain the desired level of risk and return.
using current real quantum computers of 27 and 127 qubits, While mathematical optimization can be a powerful tool
especially the definition of an ansatz with low length and the for portfolio optimization, there are several limitations to be
search for a suitable path in the real chip to map the circuit, aware of. One major limitation is that optimization models
in terms of quality and connectivity, to avoid a bigger circuit are based on assumptions and historical data, and they may
in the transpilation phase. Results show quantum algorithms not accurately predict future market conditions [9]. In other
can be competitive with classical ones, with the advantage of words, the optimization process can only provide a best
being able to handle a large number of assets in a reasonable guess as to how a portfolio is likely to perform, and there
time on a future bigger quantum computer. is no guarantee that it will actually provide the expected
This paper is organized as follows: Section II introduces return. Another limitation is that those optimization models
the idea of portfolio optimization. Section III explains the are typically based on a static view of the market, which
implications of quadratic programming. Section IV describes means that they do not consider any changes that may occur
the possibilities of using quantum computing for portfolio over time [10]. This can make it difficult for investors to adapt
optimization. Section V introduces backtesting as well as to changing market conditions and to respond to unexpected
its benefits and drawbacks. Sections VI lists the various events.
traditional methods that are used to solve this problem, and
Section VII describes the quantum algorithms that can be an III. QUADRATIC PROGRAMMING
alternative. Section VIII describes our methodology based on Quadratic programming is a mathematical optimization tech-
backtesting comparison of different classical and quantum nique that is often used in portfolio optimization. It is a
algorithms for portfolio optimization. Section IX details the type of nonlinear optimization that involves minimizing or
implementation of the different algorithms to be comparable, maximizing an objective function subject to constraints. It is
and the considerations we take with real quantum comput- an NP problem [11].
ers. Section X presents the results. Section XI contains our In the context of portfolio optimization, the objective func-
conclusions. tion is typically a measure of portfolio performance, such
as expected return or risk-adjusted return. The constraints
II. PORTFOLIO OPTIMIZATION typically include limits on the amount of each asset that can
Portfolio optimization is the process of selecting the best be included in the portfolio, as well as other factors such as
mix of investments. To identify assets with low correlations the overall level of risk or the level of exposure to specific
and determine the optimal allocation of assets to maximize assets or sectors.
return on investment while minimizing risk. This selection To solve a quadratic programming problem, an optimiza-
must be made according to the client’s characteristics and risk tion algorithm is used to find the values of the variables
aversion [8]. (in this case, the amounts of each asset in the portfolio)
The goal of portfolio optimization is to find the optimal that minimize or maximize the objective function, subject
balance between risk and return. This can be a difficult task, to the constraints. The resulting portfolio is then expected
2 VOLUME 4, 2016
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
to provide the best possible performance, given the specified timization problems. It is based on the principle of quantum
constraints. Quadratic programming has been widely used in mechanics, which allows for the representation of complex
portfolio optimization because it can handle a large number mathematical functions as quantum states [14].
of variables and constraints, and it can provide solutions that The VQE algorithm works by representing the objective
are efficient and easy to interpret. It is also relatively fast function and the constraints of the optimization problem as
and scalable, which makes it well-suited to the demands parameterized quantum states, and then using a classical
of modern investment management [12]. However, it has optimizer to find the values of the variables (in this case,
several limitations. It only works for differentiable objective the amounts of each asset in the portfolio) that minimize or
functions and constraints. Besides, it assumes that they are maximize the objective function, subject to the constraints.
convex (i.e., have only one global minimum or maximum). A quadratic program (QP) is a type of mathematical opti-
This means that it may not be suitable for solving problems mization problem that involves minimizing or maximizing a
with discontinuous or non-differentiable functions, or non- quadratic objective function subject to linear constraints. A
convex problems. It is important for users to be aware of these quadratic binary optimization (QUBO) problem is a similar
limitations and use quadratic programming appropriately. type of optimization problem, but it involves binary variables
The number of assets that can be included in portfolio (i.e., variables that can take on only two values, such as 0 or
optimization using quadratic programming is limited by the 1) and quadratic objectives without constraint functions.
computational power of the computer and the complexity of Our problem is: VQE can solve a QUBO, not a QP.
the problem. The exact number of assets that can be consid- In some cases, it is possible to transform a quadratic
ered will depend on the specific implementation and avail- program into a quadratic binary optimization (QUBO) prob-
able computing resources, but some quadratic programming lem by replacing the continuous variables in the QP with
solvers can handle problems with thousands of variables [13]. binary variables. This can be done by defining a set of
Quadratic programming algorithms may get stuck at a binary variables that represent the possible values of the
local minimum or maximum, rather than finding the global continuous variables, and then using these binary variables
optimum. A local minimum (or maximum) is a point in the in the objective and constraint functions of the QP.
search space where the objective function has a lower (or For example, suppose we have a quadratic program with a
higher) value than in the immediate surrounding area, but is continuous variable x that can take on any real value. We can
not the global minimum (or maximum) of the function. This define binary variables, x0 ...xN , that represent the possible
limitation can arise due to the specific optimization algorithm values of x (i.e., x0 ...xN can be the binary representation of
being used, as well as the nature of the objective function x real value with certain precision). We can then rewrite the
and the constraints. To try to avoid getting stuck at local objective and constraint functions of the QP using the binary
optima, quadratic programming algorithms may use heuristic variables x0 ...xN , to create a QUBO problem.
techniques such as random restarts or simulated annealing, As a general rule, the process of transforming a quadratic
but these techniques do not guarantee finding the global program into a QUBO problem can be complex, but it can
optimum. It is important for users to be aware of this potential provide valuable insights and more efficient solutions to the
limitation and use appropriate algorithms and heuristics to try optimization problem. By leveraging the unique properties of
to avoid it. binary variables and quadratic functions, QUBO optimiza-
tion can provide more accurate and efficient solutions to
IV. QUANTUM COMPUTING FOR PORTFOLIO a wide range of optimization problems, including those in
OPTIMIZATION finance and investment management.
Quantum computing is a new field that uses the principles of
quantum mechanics to perform calculations that are beyond V. BACKTESTING: AN ESSENTIAL TOOL FOR
the reach of classical computers. It has the potential to solve VALIDATION
complex problems, including some problems in finance and Backtesting is a method of evaluating the performance of
investment management. In the context of portfolio optimiza- a trading strategy or investment portfolio by simulating its
tion, quantum computing could be used to solve large or performance on historical data. It allows traders and investors
complex optimization problems, allowing for more accurate to see how the strategy or portfolio would have performed
and sophisticated portfolio models and more informed asset under different market conditions and can be used to validate
allocation and risk management decisions. It could also be the effectiveness of the strategy or portfolio and to identify
used to develop new optimization algorithms and techniques any potential weaknesses. To conduct a backtest, a trader or
that take advantage of the unique properties of quantum investor specifies the parameters of the strategy or portfolio
systems, potentially providing more accurate and efficient and simulates its performance over a specific time period
solutions to portfolio optimization problems. While quantum using historical data. Many authors use backtesting to show
computing is still in the early stages of development, it has the benefits of their proposed algorithms or strategies [15],
the potential to significantly improve portfolio optimization. [16].
The Variational Quantum Eigensolver (VQE) is an algo- While backtesting can be a useful tool for evaluating and
rithm for quantum computing that is often used to solve op- optimizing strategies or portfolios, it is important to note
VOLUME 4, 2016 3
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
that past performance is not necessarily indicative of future a time series. That is, for a time series, such as the closing
results and that backtesting can be subject to biases that can prices of an asset, which we will denote xt on each day t, the
affect the accuracy of the results. MA with a time window τ , is calculated as
Survivorship bias is a type of bias that occurs when a sam- s=t
ple of data used in a backtest only includes assets that have 1 X
MAt (X) = xs .
survived until the present time and excludes assets that have τ s=t−τ +1
been removed from the market or are no longer being traded.
This can lead to an overestimation of the performance of the For example, a 50-day SMA would be calculated by
trading strategy or investment portfolio being tested, as it adding up the closing prices for the past 50 days and then
does not take into account the performance of assets that did dividing the sum by 50.
not survive. To avoid survivorship bias, it is important to use For the implementation of the Simple Moving Average
a representative sample of data that includes both surviving Strategy (SMAS) algorithm, the MA of each of the assets
and non-surviving assets when conducting a backtest. This considered at the present moment is calculated. We will
can help to provide a more accurate representation of the randomly choose the agreed number (budget) of assets from
performance of the strategy or portfolio being tested [17]. among those that are above their MA. These assets will be
Look-ahead bias, also known as peeking or snooping bias, the ones that make up our investment portfolio, which we
is a type of bias that occurs when a trading strategy or consider to have the same weight in the portfolio.
investment portfolio is evaluated using data that was not The SMAS algorithm is widely used in the financial world
available at the time the decisions were made. In the context due to its easy understanding [21]. Moving averages can be
of backtesting, look-ahead bias can occur when the backtest used in various ways in technical analysis, such as identifying
includes data that were not available to the trader or investor trends, spotting trend reversals, and identifying support and
at the time the trades or investments were made. This can resistance levels. However, it is important to keep in mind
lead again to an overestimation of the performance of the that moving averages are a lagging indicator, meaning that
strategy or portfolio being tested, as it does not accurately they are based on past price data and may not always accu-
reflect the information and resources that were available to rately predict future price movements.
the trader or investor at the time the decisions were made.
To avoid look-ahead bias, it is important to use only data that B. RISK-RETURN OPTIMIZATION (MARKOWITZ MODEL)
was available at the time the trades or investments were made The main theory on which portfolio optimization models
when conducting a backtest. This can help to provide a more are based is known as modern portfolio theory. This new
accurate representation of the performance of the strategy or approach was introduced by Markowitz who suggested ana-
portfolio being tested [18]. lyzing both profitability and risk as a whole for the first time,
As a result, backtesting can be a useful tool for evaluating which caused a revolution in the financial world, giving rise
and optimizing trading strategies and investment portfolios, to the new theory of portfolio optimization [22], [23].
but it is important to keep in mind its limitations and to use it This type of algorithm optimizes the risk-return ratio
in conjunction with other tools and analyses. Although there (MVO, Mean-Variance optimization). Risk should be min-
is a work from Owhadi-Kareshk and Boulanger [19] describ- imized and profitability should be maximized at the same
ing a tool for backtesting classical and quantum annealing time.
algorithms for portfolio optimization, they make an example Profitability is defined as a financial ratio that measures the
of use for their software and not an actual analysis of the ability to generate profits, the measure of profitability will
algorithms. To the best of our knowledge, this is the first be the expected return of portfolio prices. The criterion that
work that performs a systematic backtesting comparison of Markowitz’s theory uses to choose the assets that make up
classical and quantum portfolio optimization algorithms. the portfolio is their performance in relation to others. These
must have low correlation between them and be diversified.
VI. CLASSICAL ALGORITHMS FOR PORTFOLIO This asset diversification process consists of dividing the
OPTIMIZATION investment among different stocks to reduce their overall
Next, we will explain three classical algorithms used to solve exposure to risk without reducing the expected return.
the portfolio problem. Mathematically, a Markowitz model can be defined as
follows:
A. MOVING AVERAGE STRATEGY
A moving average [20] is a technical analysis tool that is max Rp − qσp2
used to smooth out price data by calculating the average s.t.
price over a specified period of time. It is often used to help (1)
≥ 0, i = 1, ..., n
xi P
identify trends, spot trend reversals, and smooth out price n
i=1 xi = 1,
fluctuations.
The concept of moving averages or Moving Average (MA) where q is a risk aversion factor, Rp is the total return and
refers to the calculation of the average in a time window of σp2 is the variance of the portfolio. Besides, xi are the amount
4 VOLUME 4, 2016
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
invested in each asset, subject to budget and non-negativity where µ represents the return of the portfolio made up of
restrictions. assets with strictly positive risk, Rf is the return of the asset
Prior to Markowitz’s model, portfolio selection focused without risk and σ the volatility of the portfolio.
primarily on returns generated by investment opportunities. A higher Sharpe ratio indicates a higher risk-adjusted
Markowitz maintains the emphasis on these, at the same time return, meaning that the portfolio has generated a higher
begins to consider risk as an important factor and the variance return per unit of risk.
of a portfolio as a way of measuring risk. The Sharpe Ratio Optimization (SRO) algorithm is based
Markowitz was the first to demonstrate how the variance on maximizing the Sharpe Ratio to improve the return-risk
of a portfolio can be reduced through the impact of diver- ratio of our investment. The resulting portfolio is known as
sification. It is proposed that investors focus on selecting the market portfolio (optimal risky portfolio) [25].
portfolios based on their overall risk-reward rather than se- This can be achieved through a variety of methods, such
lecting portfolios that individually have attractive risk-return as diversifying the portfolio across a range of assets, using
characteristics. risk management techniques, or selecting assets with lower
Markowitz’s model accommodates the choice between risk volatility.
and return of the investor. Regardless of the preference of the It is important to note that while maximizing the Sharpe
inverter, all these are under what is called the Markowitz effi- ratio may be a useful goal in some cases, it is not always
cient boundary. It is defined as the set of efficient portfolios, the best approach to portfolio optimization. For example, an
that is, those that offer a higher expected return according to investor who is seeking to maximize the expected return of
the different levels of risk that can be assumed. their portfolio may be willing to accept a higher level of risk
This relates volatility and profitability of a portfolio, that in order to achieve higher returns. In these cases, maximizing
is, the benefits that the investor can obtain and the risks he the Sharpe ratio may not be the most appropriate goal [26].
must face to have it. This relationship must be positive, the
higher the profitability, the larger the risk. At the border, VII. QUANTUM ALGORITHMS FOR PORTFOLIO
risk-free assets are portfolios of minimum variance and are OPTIMIZATION
located to the left of the border (Fig. 1). The routines presented here are hybrid quantum-classical and
compatible with each other.
used to go iteratively from one estimate of ψmin to another, the variable. And the CVaR is defined as the expected value,
seeking that in each assessment the expected value of the among the observations below the VaR. That is,
eigenvector is lower. There are different variational forms, −1
CVaRα (X) = E[X|X ≤ FX (α)].
but all depend on a series of parameters that grow with the
number of qubits. Adjusting these parameters to the specific When we measure the qubits in a quantum circuit, the
problem is done with a classical optimizer, hence the VQE is result is not a string of bits, but several strings accompanied
a hybrid algorithm. by a probability. If we assume that x1 (θ), ..., xr (θ) are the
Given a Hamiltonian H, of dimension 2N × 2N , which we observations obtained in a measurement with probabilities
can write in quantum form as a function of Pauli matrices p0 , ..., pr , ordered in such a way that pi ≤ pi+1 , our objective
(σx , σy , σz ) as in (4) where i, j = 1, ..., N ; α, β ∈ {x, y, z}; function for a fixed α will be
hi , hi,j ∈ R. On one hand, σαi refers to the tensor product ⌊rα⌋
1 X
of N − 1 identity matrices of size 2 × 2 (σ1 ) and the Pauli CVaRα (θ) = xi (θ),
matrix σα at position i. On other hand, σαi αβj refers to the ⌊rα⌋ i=0
tensor product of N − 2 matrices (σ1 ) and σα at position i where ⌊.⌋ is the integer part function.
and σβ at position j. For example, for N = 3, σz1 = σ1 σz σ1 , Using the CVaR as the objective function in our prob-
and σz0 σx2 = σz σ1 σx . We can rewrite H as a sum of K lem becomes a generalization between the objective func-
‘elementary’ Hamiltonians Hk , k = 1, ..., K formed by a tion f (θ) of the previous VQE and min{x1 (θ), ..., xK (θ)},
matrix of the type σαi or σαi σβj multiplied by a real value. since when α = 1, CVaR1 (θ) = E[f (θ)] and
X X limα→0+ CVaRα (θ) = min{x1 (θ), ..., xK (θ)}.
H= hi σαi + hi,j σαi σβj (4)
i,α i,j,α,β VIII. PROPOSED METHODOLOGY
The VQE for this Hamiltonian H works by minimizing To compare and analyze the algorithms, we have performed
(with a classical optimizer) the value of the function (5) several tests. The first test group analyzes the execution times
where the calculation of ⟨ϕ(θ)|Hk |ϕ(θ)⟩ is performed by of quantum and classical algorithms. The most important
the quantum computer each time the function (5) is to be factor to consider is scalability. We examine the possibilities
evaluated. of current large real quantum computers from IBM, identi-
fying the strengths and the limiting factors. In the second
K set of tests, we check which algorithm provides the best
1 1 X results, based on backtesting. To obtain statistically signif-
f (θ) = ⟨ϕ(θ)|H|ϕ(θ)⟩ = ⟨ϕ(θ)|Hk |ϕ(θ)⟩
K K icant results, we make hundreds of backtesting comparison
k=1
(5) experiments with different random subsets of stocks from
IBEX35 (benchmark stock market index of the Bolsa de
B. CONDITIONAL VALUE AT RISK - VARIATIONAL Madrid, Spain’s principal stock exchange.) [27]
QUANTUM EIGENSOLVER (CVARVQE) Currently, quantum computers work with a queuing sys-
The VQE explained above seeks to reduce the mean (5). This tem in which users send their jobs to a quantum computer
would be the original approach of the algorithm, however, it and wait for the computer to finish executing all the previous
is possible to consider other criteria when forming our asset circuits, and then receive the results. Unfortunately, this
portfolio. way of working, when coupled with an iterative algorithm
Barkoutsos et al. [7] argue that an algorithm that seeks such as VQE, which sends a new request to a computer at
a good approximation to the optimum we are looking for each iteration, means that the execution of the program is
is better than an algorithm that tries to reach the optimum prolonged. Not only because we have to wait in line, but
and ends up giving a very poor approximation. Since the because although the execution of the quantum circuit is fast,
result that an optimization algorithm gives is usually not the communication times between the quantum computer and
the optimal one, but rather the best result found, instead of our own computer are not. For this reason, it has been decided
choosing an objective function that tries to find the optimum, to execute a VQE on real quantum computers only for
it is proposed to consider an objective function that allows us validation and illustrative purposes and make the backtesting
to find a better result. using simulators.
With this idea, a better objective function for the optimiza-
tion problem would be to find the minimum of a set of ob- IX. IMPLEMENTATION OF PORTFOLIO ALGORITHMS
servations, min{x1 (θ), ..., xK (θ)}. However, this objective The algorithms mentioned in VI and VII have been imple-
function is not adequate, since it is very poorly conditioned. mented in Python using the Qiskit [28] library with different
It is proposed to minimize Conditional Value at Risk (CVaR) sets of historical adjusted closing price data from the IBEX35
instead. stock market. These data have been taken from Yahoo! Fi-
Formally, the Value at Risk (VaR) of a variable X for a nance [29] using the Python library bt [30].
value α ∈ {0, 1} is defined as the smallest value x that Given a set of assets, we can build a portfolio by associat-
verifies FX (x) ≥ α where FX is the distribution function of ing each asset with a (non-negative) weight that will represent
6 VOLUME 4, 2016
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
the proportion of total capital that has been invested in the The previous problem has a solution for each expected
aforementioned asset. Associated with a portfolio, there are return of the portfolio, R, fixed. We obtain for each valid R a
the concepts of profitability and risk (sometimes we will point of the efficient frontier. Any efficient portfolio is a good
refer to it as volatility) [22]. If we represent by µ the vector solution for this type of optimization algorithm. There are
of expected returns of the considered assets and by Σ the multiple criteria for choosing the most convenient efficient
matrix of variances and covariances between the assets, the portfolio for the investor, and there are lines of study focused
return of the portfolio C with weights w will be given by the exclusively on this aspect.
expression Following the MVO algorithm, some efficient frontier
µC = µT w, portfolios are calculated and one of them is chosen using the
cvxopt solver [31].
and its risk for
σC = wT Σw.
3) Sharpe Ratio Optimization
In this study, we are going to work exclusively with The problem of maximizing the Sharpe Ratio is given by
portfolios whose assets all have the same weight. In other
words, the decision that interests us is to choose which assets µT w − R
maxn √
are interesting to invest in and which are not. We will also w∈R wT Σw
impose the restriction that you can only invest in a maximum s.a (8)
number of assets (budget). One way of expressing this in a 1T w = 1,
matrix is to replace the vector of weights w by a binary vector wi ≥ 0 ∀i.
x that verifies
To solve the Sharpe Ratio maximization problem, the SRO
1T x = B, (6)
has been implemented using function calc_mean_var_weights
where B is the budget. Another approach is to use the vector from package ffn (complement of the bt Python library).
of weights w and then pick a number B of assets randomly
from among those with positive weight. We are indirectly B. QUANTUM ALGORITHMS
assuming that all assets have the same cost and that with the The formulation of the portfolio problem that we solve with
value B together with (6), we have capital that we want to the VQE algorithm is (9), where x will represent the binary
fully invest. vector of assets chosen to build our portfolio, µ and Σ the
The classical algorithms used to solve this problem, gener- return vector and the matrix of variances and covariances of
ally are not comparable. It is not possible to asevere com- the n assets considered, B the number of assets in which one
pletely that one gives better results than others. However, wants to invest (budget) and q a positive term that measures
all of these algorithms become inefficient since they require the risk aversion of the investor.
a large computational cost that grows exponentially with
the number of assets considered for the construction of the min qxT Σx − µT x
x∈{0,1}n
portfolio. (9)
s.a
1T x = B.
A. CLASSICAL ALGORITHMS
1) Moving Average Strategy The expression 1T x = B is transformed into (1T x − B)2
Following this strategy, the MA of the data is calculated and and subtracted from the objective function of (9) multiplied
the assets whose closing price is higher than their moving by a penalty term. It must be taken into account that by
average are considered. Finally, the desired amount of assets performing this transformation we accept that the solution
is chosen randomly among them to form the investment found chooses a number of assets different from the budget.
portfolio, weighted with equal weights. The penalty term is the one that will measure how much it is
The SMAS algorithm has been implemented with a time acceptable to relax this restriction. For example, if it is very
window of 50 days since most of the tests carried out have detrimental to our interests when solving the problem, the
been done using similar timeframes. penalty term will have to be greatly increased. By operating,
we transform the expression in (9) into a quadratic form (10),
2) Risk-rentability Optimization for certain A and b.
To calculate the efficient frontier, we must solve for each
value of R the problem (7). xT Ax + bT x, x ∈ {0, 1}n (10)
min wT Σw Performing the change of variable xi = (1 − zi )/2, for
w∈Rn
s.t. zi ∈ {−1, 1} in (10), we transform our problem into a new
1T w = 1, (7) problem, which will consist of minimizing the expression
wi ≥ 0 ∀i, (11), which coincides with the expression of the energy of
wµ = R. the Hamiltonian of the Ising model. That is, our problem is
VOLUME 4, 2016 7
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
FIGURE 2. Example of full entangled ansatz VQE Quantum Circuit for three assets.
equivalent to finding the lowest energy level of a Hamilto- During the preparation of this work (December 2022), we
nian, which is possible using the VQE, where C and d are utilized the most stable and proven 27 qubit machines from
the coefficients in the new domain. the Falcon family and the bigger experimental 127 qubit
machines from the Eagle family.
z T Cz + dT z, z ∈ {1, −1}n (11)
C. CONSIDERATIONS FOR 27 QUBIT MACHINES
The Hamiltonian of the Ising model is constructed by Falcon quantum computers have a heavy hexagonal layout.
substituting in (11) the terms zi by σzi and the terms zi zj This has to be taken into account to define a hardware
by σzi σzj , obtaining a decomposition of the Hamiltonian as viable ansatz. For this experiment, we selected ibm_cairo as
shown (4). Using Qiskit functions, we transform our problem a 27 qubit machine (December 2022). The processor type
into this new formulation in terms of Pauli Z-matrices. This is Falcon r5.11 (Multi-chip stack: The qubit chip is bump-
formulation is common to both VQE and CVaRVQE. bonded to an "interposer" chip that provides readout and
The VQE algorithm has a quantum part and a classical signal delivery wiring). It has a Quantum Volume (QV) of 64
part. The classical optimizer performs several iterations to and can perform 2.4K Circuit Layer Operations Per Second
calculate the parameters that optimize the problem and exe- (CLOPS).
cutes a circuit on a quantum computer in each iteration. Fur- The system has the following native basis gates: CX, ID,
thermore, for our type of problem, the use of the COBYLA IF_ELSE, RZ, SX, X.
optimizer [6] is recommended. An example of a quantum Its median errors are:
circuit that VQE uses for three assets can be seen in Fig. 2. • Median CNOT Error: 1.049e−2
The execution time of a job in a quantum computer can • Median Readout Error: 1.180e−2
be divided into communication time (between the classical • Median T1: 106.81 µs
computer and the quantum computer), validation time (veri- • Median T2: 102.88 µs
fication of the sent job), queue time, and execution time. This
The chip has the individual error distribution shown in Fig.
last time comprises the time it takes to execute the circuit in
3. Observe that not all the qubits and connections are equally
the quantum chip and the measurements and post-processing
reliable, with bigger error rates on lighter-colored ones.
that are made to transform the values of the qubits into bits
understandable by a classical computer. It must be taken into
account that this execution time includes several executions
of the quantum circuit and the corresponding measurements
of the qubits after each execution of the circuit, in order to
obtain the probabilities of the possible solutions.
In general, the validation time is negligible, being only a
few milliseconds. In addition, the running time of a quantum
circuit is also extremely short, so the running time is mainly FIGURE 3. Layout and individual error distribution on ibm_cairo" real quantum
the measurement time of the qubits. Finally, we comment computer.
that after carrying out various tests with real backends with
different job numbers in the queue, it has been observed Before executing the quantum circuits we have to map the
that communication times do not significantly affect the total circuit qubits to the real hardware one, and also translate the
execution time of the job. As such, queue time is by far original gates to the equivalent native ones.
the most time-consuming, but the analysis we are really To get the best results in the hardware we need to consider
interested in this section is execution time. two important aspects: first, we need to use the qubits and
The stability of the current qubits does not reach the links with better quality, and second, we need to select the
second [32], so the execution time of a quantum circuit (each mapping of the qubits to maximize the CNOT gates between
shot) must not exceed that time in any case. With this in mind, real qubits with actual connection. If we need to perform
we run the following tests to assess the possibilities of using CNOT gates between non-conected qubits, we will need to
this quantum portfolio optimization strategy on the largest add swap gates to move the needed qubits to a position in the
available IBM real quantum computers. chip with actual connection, generating a larger circuit.
8 VOLUME 4, 2016
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
FIGURE 5. Evolution of closing price for the selected 19 stocks from IBEX35. Avoiding qubits and CNOT links with bigger errors, we
can find a circular path with an optimum performance of 28
To make the optimization we create an ansatz with linear qubits, as shown in Fig. 8. It is possible to find longer paths,
entanglement that fits on the selected linear path and uses one but currently, this one will avoid an ansatz with depth near
qubit for each of the 19 stocks (Fig. 6). the coherence time of the chip.
VOLUME 4, 2016 9
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
FIGURE 8. Optimum circular path with 28 qubits on ”ibm_washington” Choice [111] [011] [101] [001]
real quantum computer. Values 4.0006 16.0000 16.0005 36.0000
Choice [110] [010] [100] [000]
Values 16.0001 35.9996 36.0004 64.0000
We can create a VQE algorithm to select the best 5 out of
19 assets using this quantum computer. In order to do this,
we create an ansatz with circular entanglement (Fig. 9). B. EXECUTION TIME ON REAL QUANTUM COMPUTER
VS CLASICAL
In this example, the approximate average time that each
iteration has taken is 2 hours (including communication and
queue times), however, these data is not really relevant, as
it depends on many factors unrelated to the algorithm. As
a comment and by way of illustration, it must be said that
on other occasions, circuits with twice as many qubits have
taken around 44 seconds for each iteration. The big difference
is due to the waiting time in the queue. In this case, the
execution time in each iteration of the algorithm has been
around 9 seconds.
Although this time may seem quite long, the advantages of
quantum computers over classical ones are that, presumably,
this execution time does not increase exponentially with the
number of assets (qubits), which is the case with classical
computers. To verify experimentally that this statement is
correct, a VQE has been executed with data sets with between
FIGURE 9. Linear entangled ansatz VQE Quantum Circuit for 19 assets. 2 and 15 random assets and the average execution time has
been calculated in each case. These executions were carried
out on the backend ibmq_16_melbourne (real quantum com-
X. RESULTS puter with only 15 qubits. Despite its name, it had only 15
A. BASIC EXECUTION 3 ASSETS ON REAL QUANTUM usable qubits due to error rate of the qubit 16). The results
COMPUTER VS CLASICAL are shown in Fig. 11.
Figure 10 represents the obtained probabilities after execut- To compare with the behavior of classical algorithms, the
ing a VQE with the data of three random assets from October same experiment could be carried out as with the quantum,
2020. For the execution of this instance, the 5-qubit real however, working with 35 assets (Fig. 12). In the case of the
backend ibmq_athens has been used, simply because it was SMAS, its computational cost is effectively linear, since the
the quantum computer with fewer tasks in the queue among calculation of the MA is of np sums and p products, where
those that meet the minimum requirements for the problem p is the number of periods considered and n the number of
at that moment. In addition, the number of iterations of the assets with those who work. As for SRO and MVO, both al-
VQE has been limited to 20. gorithms involve solving a quadratic programming problem,
Table 1 shows the exact values of the objective function which is difficult to solve when real data is used together with
for each possible choice of assets chosen. As can be seen, extra constraints [33]. Both algoritms show an exponential
the result obtained with the algorithm is different from the trend. As the numbers grow larger, the exponential nature
10 VOLUME 4, 2016
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
FIGURE 14. Linear entangled ansatz VQE Quantum Circuit for 19 assets
FIGURE 12. Execution time of classical algorithms depending on the number transpiled for ”ibm_cairo” real quantum computer.
of assets.
An alternative to using a real quantum computer is the after 10 iterations (Fig. 16) we obtain the following proposed
use of a simulator. These simulators mimic the behavior optimal portfolio:
of a quantum computer, making them very inefficient, but
with the advantage of not having to wait in line or have ITX.MC, BBVA.MC, ACS.MC, ACX.MC, SAN.MC
the problem of communication times. In the previous ex- As an example, Fig. 15 shows the probabilities measured
ample, we saw that the time for each iteration was huge, in the real quantum computer for one VQE iteration executed
so the same problem has been solved with the simulator on ibm_cairo with 100000 shots.
ibmq_qasm_simulator by allowing the optimizer to perform We can now use the operator we built above regardless
100 iterations. The results are seen in Fig. 13. In this case, the specifics of how it was created. We set the algorithm for
the desired optimum has been reached. the NumPyMinimumEigensolver so we can have a classical
reference. A backend is not required since this is computed
C. EXECUTING ON 27 QUBIT MACHINES classically not using quantum computation. It took 126.57s
Fig. 14 shows the previously defined ansatz circuit transpiled to obtain the following results:
to the system’s available gates and mapped to the selected
ITX.MC, BBVA.MC, ACS.MC, MTS.MC, SAN.MC
19 qubits, having a depth of 27 Circuit Layer Operations on
the real hardware. This takes a time of approximately 1125 As can be observed, it differs from the quantum result only
µs on the quantum chip for each shot. The actual execution in one of the selected stocks.
for 100000 shots takes an average of 35.3 s in the quantum
system (including quantum compute and near-time classical D. EXECUTING ON 127 QUBIT MACHINES
pre- and post-processing. The queue time is not included.) As shown in Fig. 17, this circuit transpiled to the system
The CVaR VQE algorithm converges very quickly and available gates and mapped to the selected 28 qubits has a
VOLUME 4, 2016 11
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
FIGURE 15. Example of probabilities measured on ibm_cairo", 27 qubit real quantum computer.
E. BACKTESTING
To analyze the performance of the algorithms, we prepare
an experimental set with IBEX35 historical data from 2016
to 2020. As many algorithms rely on historical data, we left
2016 data for historical calculations, and start investing in
2017. Each strategy is permitted to calculate and rebalance
the portfolio once a month. To be able to compare the results,
the five tested algorithms (SMA, MVO, SRO, VQE, and VaR-
VQE) were configured under the same conditions of risk
aversion factor and avoided selecting 2 out of 5 available
FIGURE 16. Convergence of CVaR VQE on ibm_cairo", 27 qubit real stocks. Then the portfolio is rebalanced with the selected
quantum computer. stocks equally weighted.
A suite of 210 backtesting experiments has been carried
out with 5 different random assets from IBEX35. Each exper-
depth of 37 Circuit Layer Operations on the real hardware. iment provides a backtesting comparison of the performance
This will take an estimated time of 4352 µs on the quantum of the different algorithms with the same data. An example
chip. The actual execution for 100000 shots takes 48.6 s in of the results obtained on each experiment can be shown in
the quantum system. The result is too big to be displayed as Fig. 18.
a histogram. The statistics of the results have been collected in tables
2 and 3 where we can observe the mean and variance of
the results of each algorithm among the 210 simulations, as
well as the number of times that each algorithm has given a
better solution than the others. The high variance reflects the
unpredictability of the stock market, where past events do not
guarantee future outcomes.
TABLE 2. Main statistics obtains after the execution of 210 simulations with
six random assets.
TABLE 3. Number of times that the algorithm gets the best strategy (210
simulations with six random assets).
FIGURE 18. Example of one iteration of backtesting comparison of portfolio optimization with 5 random assets from IBEX35.
other algorithms, both quantum and classic. Given that the VQE and the CVaRVQE are useful algorithms and to some
rest of the algorithms have a very similar mean and a very extent competitive with the classical algorithms.
large variance, it has been decided to filter the 210 executions But the real advantage of using quantum computers for the
based on the mean and variance of each execution. portfolio optimization problem is not that the algorithm pro-
We want to find out which algorithm performs better for vides better or worse results, but that for a tremendously large
a given set of assets. To do this, we need to compare the number of assets, the classical algorithms become unfeasible.
results of each algorithm for each record. A record is a set However, quantum algorithms would not have that problem.
of stocks that we run the algorithms on. We use the intra- As long as there is a quantum computer with sufficient spec-
record variance to quantify how much the results differ from ifications, the VQE, and VQE-CVaR algorithms will allow
each other for each record. A higher variance means that the us to calculate a good solution to the portfolio optimization
results are more spread out and less similar. We are interested problem in a reasonable time.
in the records that have a high variance, because they show
us which algorithm stands out from the others. To filter out
XI. CONCLUSION
the low-variance records, we calculate the average of all the
variances for all the records. Then we only keep the records This work addresses a backtesting methodology of classical
that have a variance higher than this average. These are the and quantum computing algorithms for portfolio optimiza-
records that we use to compare the algorithms and find out tion. Results from backtesting the VQE and CVaR-VQE
which one is better. We check again how many times each algorithms suggest that they are useful and competitive with
algorithm has provided the best of the strategies. The results classical algorithms to some extent.
are collected in table 4. The scalability of current quantum computers from IBM
is analyzed by testing their execution times. A second set of
TABLE 4. Number of times that the algorithm gets the best strategy (filtered tests checks which algorithm provides the best results based
simulations).
on backtesting using historical data from the IBEX35 stock
SMAS SRO MVO VQE CVaRVQE Total
market in Spain. The algorithms were implemented using
Times Best 11 12 14 14 21 72 Python and the Qiskit library.
For running on real quantum computers, we take into
As can be seen, although initially, the MVO seemed to give account the hardware design and qubit error distribution to
better results on more occasions than the other algorithms, find the best qubit mappings and gates to use. We also aim
in particular the quantum ones, after filtering we verified that to keep the depth of the quantum circuits to a minimum to
the results of the quantum algorithms are much better than the minimize errors and maintain execution within the coherence
others on more occasions, highlighting especially the VQE- time of the chip. It has been used IBM backends of 27 and
CVaR. In any case, all the algorithms (both before and after 127 qubits.
filtering) always result in a better strategy than the others The backtesting results showed that, after filtering the
between 20% and 30% of the time, it is challenging to deter- experiments, both VQE and CVaR-VQE algorithms were
mine with complete certainty which algorithm outperforms competitive with the classical algorithms, with the advantage
the others. of being able to handle a large number of assets in a reason-
The results shown in tables 3 and 4, suggest that both the able time on a future quantum computer.
VOLUME 4, 2016 13
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
Our models are still limited by the assumptions and simpli- [13] M. J. Best and J. K. Kale, “Quadratic programming for large-scale portfo-
fications that we have made to represent the stock market as lio optimization,” in Financial Services Information Systems, pp. 531–548,
Auerbach Publications, 2000.
a quantum system. Therefore, as future work, we plan to de- [14] D. A. Fedorov, B. Peng, N. Govind, and Y. Alexeev, “VQE method: A
velop more realistic models that can capture the complexity short survey and recent developments,” Materials Theory, vol. 6, no. 1,
and uncertainty of the real stock market conditions. The main pp. 1–21, 2022. Publisher: SpringerOpen.
[15] J. Sen and A. Dutta, “A comparative study of hierarchical risk parity
problem to solve is how to select a portfolio of securities portfolio and eigen portfolio on the NIFTY 50 stocks,” in Computational
that maximizes the expected return and minimizes the risk, Intelligence and Data Analytics, pp. 443–460, Springer, 2023.
while taking into account the transaction costs and the integer [16] A. Dezhkam and M. T. Manzuri, “Forecasting stock market for an efficient
portfolio by combining XGBoost and Hilbert-Huang,” Engineering Appli-
constraints on the quantities of securities. Transaction costs cations of Artificial Intelligence, vol. 118, p. 105626, 2023. Publisher:
are the fees that investors have to pay when buying or selling Elsevier.
securities, such as commissions, taxes, or bid-ask spreads. [17] C. Garcia and F. Gould, “Survivorship bias,” Journal of Portfolio Manage-
ment, vol. 19, no. 3, p. 52, 1993. Publisher: Pageant Media.
Integer constraints are the restrictions that some securities [18] G. Daniel, D. Sornette, and P. Woehrmann, “Look-ahead benchmark bias
can only be bought or sold in fixed units, such as shares or in portfolio performance evaluation,” The Journal of Portfolio Manage-
bonds. These factors make the portfolio selection problem ment, vol. 36, no. 1, pp. 121–130, 2009. Publisher: Institutional Investor
Journals Umbrella.
more realistic but also more challenging to solve. We also [19] M. Owhadi-Kareshk and P. Boulanger, “Portfolio Optimization on
plan to implement error mitigation techniques to reduce the Classical and Quantum Computers Using PortFawn,” arXiv preprint
noise and errors that affect the quantum algorithms. More- arXiv:2112.08998, 2021.
[20] M. T. Faber, “A Quantitative Approach to Tactical Asset Allocation,” The
over, we plan to test our models on larger and more diverse Journal of Wealth Management, vol. 9, p. 69, Jan. 2007.
data sets to validate their scalability and robustness. [21] M. I. Ahmed, W. Ghohui, M. Hasan, A. Sattar, M. Ahmed, and R. U.
Rehman, “Performance of Moving Average Investment Timing Strategy
in UK Stock Market: Individual Stocks versus Portfolios,” Journal of
ACKNOWLEDGMENT Economic and Social Studies, vol. 7, no. 2, 2018.
This work was supported by grant PID2021-123041OB- [22] H. Markowitz, “Portfolio Selection*,” The Journal of
Finance, vol. 7, no. 1, pp. 77–91, 1952. _eprint:
I00 funded by MCIN/AEI/ 10.13039/501100011033 and by https://onlinelibrary.wiley.com/doi/pdf/10.1111/j.1540-
“ERDF A way of making Europe” and by the CM under grant 6261.1952.tb01525.x.
S2018/TCS-4423. [23] H. Markowitz, Portfolio Selection: Efficient Diversification of Invest-
ments. Yale University Press, 1959.
We acknowledge the use of IBM Quantum services for this [24] W. F. Sharpe, “Capital Asset Prices: A Theory of
work. The views expressed are those of the authors and do Market Equilibrium Under Conditions of Risk*,” The
not reflect the official policy or position of IBM or the IBM Journal of Finance, vol. 19, no. 3, pp. 425–442, 1964.
_eprint: https://onlinelibrary.wiley.com/doi/pdf/10.1111/j.1540-
Quantum team. 6261.1964.tb02865.x.
[25] D. H. Bailey and M. Lopez de Prado, “The Sharpe ratio efficient frontier,”
Journal of Risk, vol. 15, no. 2, p. 13, 2012.
REFERENCES
[26] S. Farinelli, M. Ferreira, D. Rossello, M. Thoeny, and L. Tibiletti, “Beyond
[1] M. M. Waldrop, “The chips are down for Moore’s law,” Nature News, Sharpe ratio: Optimal asset allocation using different performance ratios,”
vol. 530, p. 144, Feb. 2016. Cg_type: Nature News Section: News Feature. Journal of Banking & Finance, vol. 32, no. 10, pp. 2057–2063, 2008.
[2] R. P. Feynman, “Simulating Physics with Computers,” International Jour- Publisher: Elsevier.
nal of Theoretical Physics, vol. 21, no. 6, pp. 467–488, 1982. [27] “BME Bolsas y Mercados Españoles.”
[3] E. Yndurain, S. Woerner, and D. J. Egger, “Exploring quantum computing https://www.bolsasymercados.es/esp/Home.
use cases for financial services,” IBM Institute for business value. URL: [28] “Qiskit: An Open-source Framework for Quantum Computing,” 2017.
https://www. ibm. com/downloads/cas/2YPRZPB3.[dl: 29.07. 2020], https://qiskit.org/.
2019. [29] Yahoo Finanzas, “Componentes de IBEX 35... (^IBEX).”
[4] J. Gacon, C. Zoufal, and S. Woerner, “Quantum-Enhanced Simulation- https://es.finance.yahoo.com/quote//%5EIBEX/components?p=\%5EIBEX.
Based Optimization,” in 2020 IEEE International Conference on Quantum [30] P. Morissette, “bt - Flexible Backtesting for Python,” 2015.
Computing and Engineering (QCE), pp. 47–55, 2020. https://pmorissette.github.io/bt/.
[5] R. O. Michaud and R. O. Michaud, Efficient Asset Management: A Prac- [31] J. Dahl, L. Vandenberghe, and M. Andersen, “CVXOPT - Python Software
tical Guide to Stock Portfolio Optimization and Asset Allocation. Oxford for Convex Optimization,” 2004. https://cvxopt.org/.
University Press, Mar. 2008. Google-Books-ID: CzhnDAAAQBAJ. [32] J. Gambetta and S. Sheldon, “Cramming More Power Into a Quantum
[6] Qiskit, “Simulating Molecules using VQE.” Device | IBM Research blog,” 2019.
https://community.qiskit.org/textbook/ch-applications/vqe- [33] R. Mansini and M. G. Speranza, “An exact approach for portfolio selection
molecules.html. with transaction costs and rounds,” IIE transactions, vol. 37, no. 10,
[7] P. K. Barkoutsos, G. Nannicini, A. Robert, I. Tavernelli, and S. Woerner, pp. 919–929, 2005. Publisher: Taylor & Francis.
“Improving Variational Quantum Optimization using CVaR,” Quantum,
vol. 4, p. 256, Apr. 2020. Publisher: Verein zur Förderung des Open Access
Publizierens in den Quantenwissenschaften.
[8] M. J. Best, Portfolio optimization. CRC Press, 2010.
[9] M. E. Stucke, “Behavioral economists at the gate: Antitrust in the twenty-
first century,” Loy. U. Chi. LJ, vol. 38, p. 513, 2006. Publisher: HeinOn-
line.
[10] S. K. Mehra, “Competition Law for a Post-Scarcity World,” Tex. A&M L.
Rev., vol. 4, p. 1, 2016. Publisher: HeinOnline.
[11] S. A. Vavasis, “Quadratic programming is in NP,” Information Processing
Letters, vol. 36, no. 2, pp. 73–77, 1990. Publisher: Elsevier.
[12] A. J. King and D. L. Jensen, “Linear-quadratic efficient frontiers for
portfolio optimization,” Applied Stochastic Models and Data Analysis,
vol. 8, no. 3, pp. 195–207, 1992. Publisher: Wiley Online Library.
14 VOLUME 4, 2016
G. Carrascal et al.: Backtesting quantum computing algorithms for portfolio optimization
GINÉS CARRASCAL was born in Salamanca, ALBERTO A. DEL BARRIO (SM’19) received
Spain in 1975. He received an M.Sc. degree in the Ph.D. degree in Computer Science from
physics from the University of Salamanca (Spain) the Complutense University of Madrid (UCM),
in 1999. Madrid, Spain, in 2011.
Since 2000 he has been working as Architect He has performed stays at Northwestern Uni-
at IBM Consulting Spain, getting involved with versity, the University of California at Irvine, and
quantum computing in 2017, and now acting as the University of California at Los Angeles. Since
Quantum Technical Ambassador and Qiskit Ad- 2021, he is an Associate Professor (tenure-track,
vocate. He has become IBM Certified Associate civil-servant) of Computer Science with the De-
Developer - Quantum Computation using Qiskit partment of Computer Architecture and System
v0.2X in 2021. Since 2014 he has been an Adjunct Professor of computer Engineering, UCM. His main research interests include Design Automation,
science at Universidad Carlos III de Madrid and since 2018, an Adjunct Arithmetic, Analog/Quantum Computing, and their application to the field
Professor at Universidad Complutense de Madrid at the computer science of Artificial Intelligence.
departmental section of the Mathematics Faculty. His research interest Dr. del Barrio has been the PI of the PARNASO project, funded by the
includes Artificial Intelligence and the application of Quantum Computing Leonardo Grants program by Fundación BBVA, and currently, he is the PI
to optimization problems, especially but not only in the field of Banking and of the ASIMOV project, funded by the Spanish MICINN, which includes a
Financial Services. work package to research on the applicability of Quantum Computing. Since
Prof. Ginés Carrascal has received two Outstanding Technical Achieve- 2019 he is an IEEE Senior Member and since December 2020, he is an ACM
ment Awards (OTAA), the highest IBM technical award in 2012 and 2016. Senior Member, too.
VOLUME 4, 2016 15