PortfolioOptimization_EN.ipynb 22.8 KB
Notebook
Newer Older
Q
Quleaf 已提交
1 2 3 4
{
 "cells": [
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
5
   "metadata": {},
Q
Quleaf 已提交
6 7 8 9
   "source": [
    "# Quantum Finance Application on Portfolio Optimization\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
Q
Quleaf 已提交
10
   ]
Q
Quleaf 已提交
11 12 13
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
14
   "metadata": {},
Q
Quleaf 已提交
15 16 17 18 19 20
   "source": [
    "## Overview\n",
    "\n",
    "Current finance problems can be mainly tackled by three areas of quantum algorithms: quantum simulation, quantum optimization, and quantum machine learning [1,2]. Many financial problems are essentially combinatorial optimization problems, and corresponding algorithms usually have high time complexity and are difficult to implement. Due to the power of quantum computing, these complex problems are expected to be solved by quantum algorithms in the future.\n",
    "\n",
    "The Quantum Finance module of Paddle Quantum focuses on quantum optimization: how to apply quantum algorithms in real finance optimization problems. This tutorial focuses on how to use quantum algorithms to solve the portfolio optimization problem."
Q
Quleaf 已提交
21
   ]
Q
Quleaf 已提交
22 23 24
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
25
   "metadata": {},
Q
Quleaf 已提交
26 27 28
   "source": [
    "## Portfolio Optimization Problem\n",
    "\n",
Q
Quleaf 已提交
29
    "A portfolio is a collection of financial investments, such as stocks, bonds, cash, etc. Many investment managers face the portfolio optimization problem. This problem requires practitioners to invest in various projects, according to their target returns and risks. This aims to minimize the risk given a certain return or maximize the return given a certain risk.\n",
Q
Quleaf 已提交
30
    "\n",
Q
Quleaf 已提交
31 32
    "A detailed description of portfolio optimization is as follows: If you are an active investment manager who wants to invest $K$ dollars to $N$ projects, each with its return and risk, your goal is to find an optimal way to invest in the projects, taking into account the market impact and transaction costs."
   ]
Q
Quleaf 已提交
33 34 35
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
36
   "metadata": {},
Q
Quleaf 已提交
37 38 39
   "source": [
    "### Encoding Portfolio Optimization Problem\n",
    "\n",
Q
Quleaf 已提交
40
    "To transform the portfolio optimization problem into a problem applicable for parameterized quantum circuits, we need to encode the portfolio optimization problem into a Hamiltonian. To make the modeling easy to formulate, two assumptions are made to constrain the problem:\n",
Q
Quleaf 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    "* Each asset is invested with an equal amount of money.\n",
    "* Budget is a multiple of each investment amount and must be fully spent.\n",
    "\n",
    "\n",
    "In this model we unitize the investment amount, i.e., if the budget is $3$, then the manager should invest $3$ assets. Since the actual investment budget is limited and there are many investable assets, it is important to set the number of investable assets larger than the budget.\n",
    "\n",
    "In the theory of portfolio optimization, the overall risk of a portfolio is related to the covariance between assets, which is proportional to the correlation coefficients of any two assets. The smaller the correlation coefficients, the smaller the covariance, and then the smaller the overall risk of the portfolio [3].\n",
    "\n",
    "Here we use the mean-variance approach to model this problem:\n",
    "\n",
    "$$\n",
    "\\omega = \\max _{x \\in\\{0,1\\}^{n}} \\mu^{T} x - q x^{T} S x \\quad\\quad  \\tag{1}\n",
    "\\text { subject to: } 1^{T} x=B,\n",
    "$$\n",
    "\n",
    "where each symbol has the following meaning:\n",
    "* $x\\in {\\{0,1\\}}^N$ denotes the vector of binary decision variables, which indicate which each assets is picked ($x_i=1$) or not ($x_i = 0$),\n",
    "* $\\mu \\in \\mathbb{R}^n$ defines the expected returns for the assets,\n",
    "* $S \\in \\mathbb{R}^{n \\times n}$ represents the covariances between the assets,\n",
    "* $q > 0$ represents the risk factor of investment decision making,\n",
    "* $\\mathbb{1}$ denotes a vector with all values of $1$,\n",
    "* $B$ denotes the budget, i.e. the number of assets to be selected out of $N$.\n",
    "\n",
    "\n",
    "According to the model equation, we can define the loss function:\n",
    "\n",
    "$$\n",
    "C_x = q \\sum_i  \\sum_j s_{ji}x_ix_j - \\sum_{i}x_i \\mu_i + A \\left(B - \\sum_i x_i\\right)^2,  \\tag{2}\n",
    "$$\n",
    "\n",
    "where $s_{ij}$ denotes the elements of the covariance matrix $S$.\n",
    "\n",
    "Since the loss function is to be optimized using the gradient descent method, some modifications are made in the definition based on the equations of the model. The first term represents the risk of the investment. The second term represents the expected return on this investment. The third term constrains the budget $B$ to be invested evenly in different projects. $A$ is the penalty parameter, usually set to a larger number. \n",
    "\n",
Q
Quleaf 已提交
75
    "We now need to transform the cost function $C_x$ into a Hamiltonian to realize the encoding of the portfolio optimization problem. Each variable $x_{i}$ has two possible values, $0$ and $1$, corresponding to quantum states $|0\\rangle$ and $|1\\rangle$. Note that every variable corresponds to a qubit and so $n$ qubits are needed for solving the portfolio optimization problem. The Pauli $Z$ operator has two eigenstates, $|0\\rangle$ and $|1\\rangle$ . Their corresponding eigenvalues are 1 and -1, respectively. So we consider encoding the cost function as a Hamiltonian using the Pauli $Z$ matrix.\n",
Q
Quleaf 已提交
76 77 78 79 80 81 82 83 84
    "\n",
    "Now we would like to consider the mapping\n",
    "$$\n",
    "x_{i} \\mapsto \\frac{I-Z_{i}}{2}, \\tag{4}\n",
    "$$\n",
    "\n",
    "where $Z_{i} = I \\otimes I \\otimes \\ldots \\otimes Z \\otimes \\ldots \\otimes I$ with $Z$ operates on the qubit at position $i$. Under this mapping, the value of $x_i$ can be illustrated in a different way. If the qubit $i$ is in state $|1\\rangle$, then $x_{i} |1\\rangle = \\frac{I-Z_{i}}{2} |1\\rangle = 1|1\\rangle $, which means that the stork $i$ is in the optimal portfolio. Also, for a qubit $i$ in state $|0\\rangle$, $x_{i}|0\\rangle  = \\frac{I-Z_{i}}{2} |0\\rangle = 0 |0\\rangle $.\n",
    "\n",
    "Thus using the above mapping, we can transform the cost function $C_x$ into a Hamiltonian $H_C$ for the system of $n$ qubits and realize the quantumization of the portfolio optimization problem. Then the ground state of $H_C$ is the optimal solution to the portfolio optimization problem. In the following section, we will show how to use a parameterized quantum circuit to find the ground state, i.e., the eigenvector with the smallest eigenvalue."
Q
Quleaf 已提交
85
   ]
Q
Quleaf 已提交
86 87 88
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
89
   "metadata": {},
Q
Quleaf 已提交
90 91 92 93
   "source": [
    "## Paddle Quantum Implementation\n",
    "\n",
    "To investigate the portfolio optimization problem using Paddle Quantum, there are some required packages to import, which are shown below. "
Q
Quleaf 已提交
94
   ]
Q
Quleaf 已提交
95 96 97 98
  },
  {
   "cell_type": "code",
   "execution_count": 1,
Q
Quleaf 已提交
99 100 101 102 103 104 105
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-05-17T08:00:15.901429Z",
     "start_time": "2021-05-17T08:00:12.708945Z"
    }
   },
   "outputs": [],
Q
Quleaf 已提交
106 107 108 109 110 111 112 113
   "source": [
    "# Import packages needed\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import datetime\n",
    "\n",
    "# Import related modules from Paddle Quantum and PaddlePaddle\n",
    "import paddle\n",
Q
Quleaf 已提交
114 115
    "import paddle_quantum\n",
    "from paddle_quantum.ansatz import Circuit\n",
Q
Quleaf 已提交
116
    "from paddle_quantum.finance import DataSimulator, portfolio_optimization_hamiltonian"
Q
Quleaf 已提交
117
   ]
Q
Quleaf 已提交
118 119 120
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
121
   "metadata": {},
Q
Quleaf 已提交
122 123 124
   "source": [
    "### Prepare experimental data\n",
    "\n",
Q
Quleaf 已提交
125
    "In this tutorial, we choose stocks as an investment assets. For the data used in the experimental tests, two options are provided:\n",
Q
Quleaf 已提交
126 127
    "* The first method is to generate random data according to certain requirements, e.g. number of assets.\n",
    "\n",
Q
Quleaf 已提交
128 129
    "If the user prepares data using this method, then when initializing the data, it is necessary to give the list of parameters: a list of names of investable stocks (assets), the start date, and the end date of the trading data."
   ]
Q
Quleaf 已提交
130 131 132 133
  },
  {
   "cell_type": "code",
   "execution_count": 2,
Q
Quleaf 已提交
134 135
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
136 137 138
   "source": [
    "num_assets = 7  # Number of investable projects\n",
    "stocks = [(\"STOCK%s\" % i) for i in range(num_assets)]  \n",
Q
Quleaf 已提交
139 140
    "data = DataSimulator( stocks = stocks, start = datetime.datetime(2016, 1, 1), end = datetime.datetime(2016, 1, 30))\n",
    "data.randomly_generate() # Generate random data"
Q
Quleaf 已提交
141
   ]
Q
Quleaf 已提交
142 143 144
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
145 146 147 148 149 150
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-05-17T08:00:16.212260Z",
     "start_time": "2021-05-17T08:00:15.918792Z"
    }
   },
Q
Quleaf 已提交
151 152 153 154 155 156
   "source": [
    "* The second method is that the user can choose to set the data themselves, i.e. real stock data collected by themselves. Considering that the number of stocks contained in the file may be large, the user can specify the number of stocks used for this experiment, i.e. `num_assets` as initialized above.\n",
    "\n",
    "We collect the closing prices of 12 stocks for 35 trading days into the `realStockData_12.csv` file, where we choose to read only the first 3 stocks.\n",
    "\n",
    "In this tutorial, we choose to read real data as experimental data."
Q
Quleaf 已提交
157
   ]
Q
Quleaf 已提交
158 159 160 161
  },
  {
   "cell_type": "code",
   "execution_count": 3,
Q
Quleaf 已提交
162 163 164 165 166 167 168 169 170 171
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[16.87, 17.18, 17.07, 17.15, 16.66, 16.79, 16.69, 16.99, 16.76, 16.52, 16.33, 16.39, 16.45, 16.0, 16.09, 15.54, 13.99, 14.6, 14.63, 14.77, 14.62, 14.5, 14.79, 14.77, 14.65, 15.03, 15.37, 15.2, 15.24, 15.59, 15.58, 15.23, 15.04, 14.99, 15.11, 14.5], [32.56, 32.05, 31.51, 31.76, 31.68, 32.2, 31.46, 31.68, 31.39, 30.49, 30.53, 30.46, 29.87, 29.21, 30.11, 28.98, 26.63, 27.62, 27.64, 27.9, 27.5, 28.67, 29.08, 29.08, 29.95, 30.8, 30.42, 29.7, 29.65, 29.85, 29.25, 28.9, 29.33, 30.11, 29.67, 29.59], [5.4, 5.48, 5.46, 5.49, 5.39, 5.47, 5.46, 5.53, 5.5, 5.47, 5.39, 5.35, 5.37, 5.24, 5.26, 5.08, 4.57, 4.44, 4.5, 4.56, 4.52, 4.59, 4.66, 4.67, 4.66, 4.72, 4.84, 4.81, 4.84, 4.88, 4.89, 4.82, 4.74, 4.84, 4.79, 4.63], [3.71, 3.75, 3.73, 3.79, 3.72, 3.77, 3.76, 3.74, 3.78, 3.71, 3.61, 3.58, 3.61, 3.53, 3.5, 3.42, 3.08, 2.95, 3.04, 3.05, 3.05, 3.13, 3.12, 3.14, 3.11, 3.07, 3.23, 3.3, 3.31, 3.3, 3.33, 3.31, 3.22, 3.31, 3.25, 3.12], [5.72, 5.75, 5.74, 5.81, 5.69, 5.79, 5.77, 5.8, 5.89, 5.78, 5.7, 5.69, 5.75, 5.7, 5.71, 5.54, 4.99, 4.89, 4.94, 5.08, 5.39, 5.35, 5.23, 5.26, 5.19, 5.18, 5.31, 5.33, 5.31, 5.38, 5.39, 5.41, 5.28, 5.3, 5.38, 5.12], [7.62, 7.56, 7.68, 7.75, 7.79, 7.84, 7.82, 7.8, 7.92, 7.96, 7.93, 7.87, 7.86, 7.82, 7.9, 7.7, 6.93, 6.91, 7.18, 7.31, 7.35, 7.53, 7.47, 7.48, 7.35, 7.33, 7.46, 7.47, 7.39, 7.47, 7.48, 8.06, 8.02, 8.01, 8.11, 7.87], [3.7, 3.7, 3.68, 3.7, 3.63, 3.66, 3.63, 3.63, 3.66, 3.63, 3.6, 3.59, 3.63, 3.6, 3.61, 3.54, 3.19, 3.27, 3.27, 3.31, 3.3, 3.32, 3.33, 3.38, 3.36, 3.34, 3.39, 3.39, 3.37, 3.42, 3.43, 3.37, 3.32, 3.36, 3.37, 3.3]]\n"
     ]
    }
   ],
Q
Quleaf 已提交
172 173 174 175 176 177 178 179 180 181
   "source": [
    "df = pd.read_csv('realStockData_12.csv')\n",
    "dt = []\n",
    "for i in range(num_assets): \n",
    "    mylist = df['closePrice'+str(i)].tolist()\n",
    "    dt.append(mylist)   \n",
    "# Output the closing price of the seven stocks read from the file for the 35 trading days\n",
    "print(dt)  \n",
    "# Specify the experimental data as a local file read by the user\n",
    "data.set_data(dt)  "
Q
Quleaf 已提交
182
   ]
Q
Quleaf 已提交
183 184 185
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
186
   "metadata": {},
Q
Quleaf 已提交
187 188 189 190 191 192
   "source": [
    "### Encoding Hamiltonian\n",
    "\n",
    "Here we construct the Hamiltonian $H_C$ of Eq. (2) with the replacement in Eq. (3). \n",
    "\n",
    "In the process of encoding Hamiltonian, we first need to calculate the covariance matrix $S$ between the returns of each stock, which is available in the ``finance`` module and can be called directly."
Q
Quleaf 已提交
193
   ]
Q
Quleaf 已提交
194 195 196 197
  },
  {
   "cell_type": "code",
   "execution_count": 4,
Q
Quleaf 已提交
198 199
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
200 201
   "source": [
    "s = data.get_asset_return_covariance_matrix()"
Q
Quleaf 已提交
202
   ]
Q
Quleaf 已提交
203 204 205
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
206
   "metadata": {},
Q
Quleaf 已提交
207
   "source": [
Q
Quleaf 已提交
208 209
    "The second step is to compute the expected return vector $\\mu$ for each stock. Similarly, paddle quantum also supports this function for users."
   ]
Q
Quleaf 已提交
210 211 212 213
  },
  {
   "cell_type": "code",
   "execution_count": 5,
Q
Quleaf 已提交
214 215
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
216 217
   "source": [
    "mu = data.get_asset_return_mean_vector()"
Q
Quleaf 已提交
218
   ]
Q
Quleaf 已提交
219 220 221
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
222
   "metadata": {},
Q
Quleaf 已提交
223 224
   "source": [
    "Based on the provided and calculated parameters, the Hamiltonian is constructed below. Here we set the penalty parameter to the number of investable stocks."
Q
Quleaf 已提交
225
   ]
Q
Quleaf 已提交
226 227 228 229
  },
  {
   "cell_type": "code",
   "execution_count": 6,
Q
Quleaf 已提交
230 231
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
232 233 234 235 236
   "source": [
    "q = 0.5  # risk appetite of the decision maker\n",
    "budget = num_assets // 2   # budget\n",
    "penalty = num_assets       # penalty parameter  \n",
    "hamiltonian = portfolio_optimization_hamiltonian(penalty, mu, s, q, budget)"
Q
Quleaf 已提交
237
   ]
Q
Quleaf 已提交
238 239 240
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
241
   "metadata": {},
Q
Quleaf 已提交
242 243 244
   "source": [
    "### Calculating the loss function \n",
    "\n",
Q
Quleaf 已提交
245
    "We adopt a parameterized quantum circuit consisting of $U_3(\\vec{\\theta})$ and $\\text{CNOT}$ gates. It can be constructed by calling the built-in method [`complex_entangled_layer()`](https://qml.baidu.com/api/paddle_quantum.ansatz.circuit.html#Circuit.complex_entangled_layer).\n",
Q
Quleaf 已提交
246 247 248 249 250 251 252 253 254 255
    "\n",
    "After running the quantum circuit, we obtain the circuit output $|\\vec{\\theta\n",
    "}\\rangle$. From the output state of the circuit, we can calculate the loss function of the portfolio optimization under the classical-quantum hybrid model:\n",
    "\n",
    "$$\n",
    "L(\\vec{\\theta}) =  \\langle\\vec{\\theta}|H_C|\\vec{\\theta}\\rangle.\n",
    "\\tag{4}\n",
    "$$\n",
    "\n",
    "We then use a classical optimization algorithm to minimize this function and find the optimal parameters $\\vec{\\theta}^*$. The following code shows a complete network built with Paddle Quantum and PaddlePaddle."
Q
Quleaf 已提交
256
   ]
Q
Quleaf 已提交
257 258 259 260
  },
  {
   "cell_type": "code",
   "execution_count": 7,
Q
Quleaf 已提交
261 262
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
263 264 265
   "source": [
    "class PONet(paddle.nn.Layer):\n",
    "\n",
Q
Quleaf 已提交
266
    "    def __init__(self, num_qubits, p, dtype=\"float64\"):\n",
Q
Quleaf 已提交
267 268
    "        super(PONet, self).__init__()\n",
    "\n",
Q
Quleaf 已提交
269 270 271 272
    "        self.depth = p\n",
    "        self.num_qubits = num_qubits\n",
    "        self.cir = Circuit(self.num_qubits)\n",
    "        self.cir.complex_entangled_layer(depth=self.depth)\n",
Q
Quleaf 已提交
273
    "\n",
Q
Quleaf 已提交
274
    "    def forward(self):\n",
Q
Quleaf 已提交
275 276 277
    "        \"\"\"\n",
    "        Forward propagation\n",
    "        \"\"\"\n",
Q
Quleaf 已提交
278 279 280 281 282
    "        state = self.cir(init_state)\n",
    "        loss = loss_func(state)\n",
    "\n",
    "        return loss, self.cir"
   ]
Q
Quleaf 已提交
283 284 285
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
286
   "metadata": {},
Q
Quleaf 已提交
287 288 289 290
   "source": [
    "### Training the quantum neural network\n",
    "\n",
    "After defining the quantum neural network, we use the gradient descent method to update the parameters to minimize the expectation value in Eq. (4). "
Q
Quleaf 已提交
291
   ]
Q
Quleaf 已提交
292 293 294 295
  },
  {
   "cell_type": "code",
   "execution_count": 8,
Q
Quleaf 已提交
296 297
   "metadata": {},
   "outputs": [],
Q
Quleaf 已提交
298 299 300 301 302
   "source": [
    "SEED = 1000   # Set a global RNG seed \n",
    "p = 2        # Number of layers in the quantum circuit\n",
    "ITR = 600    # Number of training iterations\n",
    "LR = 0.4     # Learning rate of the optimization method based on gradient descent"
Q
Quleaf 已提交
303
   ]
Q
Quleaf 已提交
304 305 306
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
307
   "metadata": {},
Q
Quleaf 已提交
308 309
   "source": [
    "Here, we optimize the network defined above in PaddlePaddle."
Q
Quleaf 已提交
310
   ]
Q
Quleaf 已提交
311 312 313
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iter:  50     loss:  0.0399189\n",
      "iter:  100     loss:  0.0098760\n",
      "iter:  150     loss:  0.0085572\n",
      "iter:  200     loss:  0.0074596\n",
      "iter:  250     loss:  0.0066504\n",
      "iter:  300     loss:  0.0061929\n",
      "iter:  350     loss:  0.0059874\n",
      "iter:  400     loss:  0.0059097\n",
      "iter:  450     loss:  0.0058763\n",
      "iter:  500     loss:  0.0058761\n",
      "iter:  550     loss:  0.0058756\n",
      "iter:  600     loss:  0.0058689\n"
     ]
    }
   ],
Q
Quleaf 已提交
336 337
   "source": [
    "# number of qubits\n",
Q
Quleaf 已提交
338
    "num_qubits = len(mu)\n",
Q
Quleaf 已提交
339 340 341
    "# Fix paddle random seed\n",
    "paddle.seed(SEED)\n",
    "# Building Quantum Neural Networks\n",
Q
Quleaf 已提交
342 343 344 345 346
    "net = PONet(num_qubits, p)\n",
    "# Define initial state\n",
    "init_state = paddle_quantum.state.zero_state(num_qubits)\n",
    "# Define loss function\n",
    "loss_func = paddle_quantum.loss.ExpecVal(hamiltonian)\n",
Q
Quleaf 已提交
347 348 349 350 351 352
    "# Use Adam optimizer\n",
    "opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
    "\n",
    "# Gradient descent iteration\n",
    "for itr in range(1, ITR + 1):\n",
    "    # Run the network defined above\n",
Q
Quleaf 已提交
353
    "    loss, cir = net()\n",
Q
Quleaf 已提交
354 355 356 357 358 359 360
    "    # Calculate the gradient and optimize\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "    if itr % 50 == 0:\n",
    "        print(\"iter: \", itr, \"    loss: \", \"%.7f\"% loss.numpy())\n",
    "        "
Q
Quleaf 已提交
361
   ]
Q
Quleaf 已提交
362 363 364
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
365
   "metadata": {},
Q
Quleaf 已提交
366 367 368 369
   "source": [
    "### Theoretical minimum loss value\n",
    "\n",
    "The theoretical minimum value of $C_x$ corresponds to the minimum eigenvalue of the Hamiltonian constructed above. So we would like to see the value of the loss function found by the parameterized circuit optimization close to the theoretical minimum. For smaller ``num_assets``, we can verify this based on the following code."
Q
Quleaf 已提交
370
   ]
Q
Quleaf 已提交
371 372 373
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
374 375
   "execution_count": 11,
   "metadata": {},
Q
Quleaf 已提交
376 377 378
   "outputs": [
    {
     "name": "stdout",
Q
Quleaf 已提交
379
     "output_type": "stream",
Q
Quleaf 已提交
380
     "text": [
Q
Quleaf 已提交
381 382
      "Theoretical minimum loss value:  0.0058722496\n",
      "Practical minimum loss value:  0.0058689117431640625\n"
Q
Quleaf 已提交
383 384 385
     ]
    }
   ],
Q
Quleaf 已提交
386 387 388 389 390
   "source": [
    "H_C_matrix = hamiltonian.construct_h_matrix()\n",
    "print(\"Theoretical minimum loss value: \", np.linalg.eigvalsh(H_C_matrix)[0])\n",
    "print(\"Practical minimum loss value: \", float(loss.numpy()))"
   ]
Q
Quleaf 已提交
391 392 393
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
394
   "metadata": {},
Q
Quleaf 已提交
395 396
   "source": [
    "In this case, the minimum loss from the parameterized circuit optimization is the same as the theoretical minimum loss, which ensures that the investment solution found is optimal. If two values do not match well, we can adjust parameters such as the random seed ``SEED``, the number of layers of the quantum circuit ``p``, the number of iterations ``ITR`` and the gradient descent optimization rate ``LR``, to reapproximate the optimal solution."
Q
Quleaf 已提交
397
   ]
Q
Quleaf 已提交
398 399 400
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
401
   "metadata": {},
Q
Quleaf 已提交
402 403 404
   "source": [
    "### Decoding the quantum solution\n",
    "\n",
Q
Quleaf 已提交
405
    "After obtaining the minimum value of the loss function and the corresponding set of parameters $\\vec{\\theta}^*$, our task has not been completed. To obtain an approximate solution to the portfolio optimization problem, it is necessary to decode the solution to the classical optimization problem from the quantum state $|\\vec{\\theta}^*\\rangle$ output by the circuit. Physically, to decode a quantum state, we need to measure it and then calculate the probability distribution of the measurement results:\n",
Q
Quleaf 已提交
406 407 408 409 410 411
    "\n",
    "$$\n",
    "p(z) = |\\langle z|\\vec{\\theta}^*\\rangle|^2.\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
Q
Quleaf 已提交
412
    "In the case of quantum parameterized circuits with sufficient expressiveness, the greater the probability of a certain bit string, the greater the probability that it corresponds to an optimal solution to the portfolio optimization problem.\n",
Q
Quleaf 已提交
413 414
    "\n",
    "Paddle Quantum provides a function to read the probability distribution of the measurement results of the state output by the quantum circuit:"
Q
Quleaf 已提交
415
   ]
Q
Quleaf 已提交
416 417 418
  },
  {
   "cell_type": "code",
Q
Quleaf 已提交
419 420
   "execution_count": 13,
   "metadata": {},
Q
Quleaf 已提交
421 422 423
   "outputs": [
    {
     "name": "stdout",
Q
Quleaf 已提交
424
     "output_type": "stream",
Q
Quleaf 已提交
425 426 427 428 429
     "text": [
      "The bit string form of the solution:  0100110\n"
     ]
    }
   ],
Q
Quleaf 已提交
430 431 432 433 434 435 436
   "source": [
    "# Repeat the simulated measurement of the circuit output state 2048 times\n",
    "final_state = cir(init_state)\n",
    "prob_measure = final_state.measure(shots=2048)\n",
    "investment = max(prob_measure, key=prob_measure.get)\n",
    "print(\"The bit string form of the solution: \", investment)"
   ]
Q
Quleaf 已提交
437 438 439
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
440
   "metadata": {},
Q
Quleaf 已提交
441
   "source": [
Q
Quleaf 已提交
442 443
    "The result of our measurement is a bit string that represents the solution to the portfolio optimization problem: $1$ appearing at the $i$th bit indicates that the $i$th asset was selected for investment. For example, the result `0100110` above would indicate that the second, fifth, and sixth stocks were selected out of the seven available investments. The number of $1$s in the string should be the same as the budget $B$. If the result is not like this, users can also get better training results by adjusting the parameters or structure of parameterized quantum circuits."
   ]
Q
Quleaf 已提交
444 445 446
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
447
   "metadata": {},
Q
Quleaf 已提交
448 449 450
   "source": [
    "### Conclusion\n",
    "\n",
Q
Quleaf 已提交
451 452
    "In this tutorial, the optimal solution to the portfolio optimization is approximated through the Variational Quantum Eigensolver (VQE) based on the mean-variance approach. Given the budget, available assets, and investment risks, the parameterized quantum circuits are applied to find the optimal portfolio by calculating the returns of investment projects and the covariance matrix between the returns of each investment project. "
   ]
Q
Quleaf 已提交
453 454 455
  },
  {
   "cell_type": "markdown",
Q
Quleaf 已提交
456
   "metadata": {},
Q
Quleaf 已提交
457 458 459 460 461 462 463 464 465 466
   "source": [
    "_______\n",
    "\n",
    "## References\n",
    "\n",
    "[1] Orus, Roman, Samuel Mugel, and Enrique Lizaso. \"Quantum computing for finance: Overview and prospects.\" [Reviews in Physics 4 (2019): 100028.](https://arxiv.org/abs/1807.03890)\n",
    "\n",
    "[2] Egger, Daniel J., et al. \"Quantum computing for Finance: state of the art and future prospects.\" [IEEE Transactions on Quantum Engineering (2020).](https://arxiv.org/abs/2006.14510)\n",
    "\n",
    "[3] Markowitz, H.M. (March 1952). \"Portfolio Selection\". [The Journal of Finance. 7 (1): 77–91. doi:10.2307/2975974. JSTOR 2975974.](https://www.jstor.org/stable/2975974)"
Q
Quleaf 已提交
467
   ]
Q
Quleaf 已提交
468 469 470 471 472 473 474
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "3b61f83e8397e1c9fcea57a3d9915794102e67724879b24295f8014f41a14d85"
  },
  "kernelspec": {
Q
Quleaf 已提交
475
   "display_name": "Python 3 (ipykernel)",
Q
Quleaf 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
Q
Quleaf 已提交
489
   "version": "3.9.7"
Q
Quleaf 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
Q
Quleaf 已提交
507
}