So far, we have discussed the workflow of the program
in general. In this section, we are going to discuss the work in more technical
details and we are going to describe the code we used to create the
application. Figure 4 shows the interface of the program we created. As we can
see, the interface contains three menus, five grid views and a graph space to
draw the efficient frontier and a navigation bar which is used to select the
weight of the risk and return that used in the fitness function.

Figure 4: Program
interface.
The left grid views are used to list the stocks used
in creation of the portfolios. Where the right grid views are used to list the
portfolios created in the different stages of the program run. The top left
grid view is used to list all the available stocks which we created from the
data we extracted from Amman Stock Exchange website. The bottom left grid view
is used to list the stocks which are used to create the optimum portfolios to
be used in the HGA to create the second generation portfolios [42]. The right
top grid view is used to display the 10000 portfolios we created using the
stocks listed in the top left grid view, where each portfolio consists of six
different stocks.
The right middle grid view is used to list the optimum
portfolios which consist of the stocks listed in the bottom left grid view. The
right bottom grid view is used to list the second generation portfolios which
are the result of the genetic algorithm and the crossover operation. As Figure
5 shows we have five different options which work as follows:

Figure 5: File
Menu.
Figure 6 shows the code that runs when the “Select
Data” option is clicked from the file menu. The first line of code defines a
list of strings named lines to store the lines. The second line of code defines
and creates an open file dialog box which is shown when the select data option
is clicked. The dialog box allows us to select the file which contains the
stocks data. The file should be in .txt format. The “IF statement” block is
used to make sure a file is selected and then add the file lines into the list
of lines which we defined in the first line.

Figure 6: Select
data code.
Figure 7 shows the stocks data file. Each line in the
file represents a stock where the entries represent the stock code, expected
return, ID and risk respectively. The entries are separated by tabs. The “For
loop” block of code is used to create a stock for each line and assign the
code, expected return, ID and risk for each stock and then add the stock to a
list of stocks. The last two lines of code are used to list the data on the
application interface grid view.
Figure 8 shows the code which runs when the “Create
portfolios” option is selected from the file menu. As we can see, the function
contains a for-loop statement which is used to repeat the code within the block
10,000 times. In the first line of code we define a temporary portfolio, and
then we define a temporary stock. After that, we keep repeating the code within
the while-loop block until the number of stocks the portfolio contains is six.
In the while loop, we create random number generator. The random number
generator is defined as a random number that is bigger or equal to its lower
limit, in our case 60, and less than its maximum limit, in our case 121, which
gives us a random number from 60-120.

Figure 7: Stocks data file.
Then, we use the random number and search for the
stock that has the same number as its ID and assign its value to the temporary
stock that we defined earlier.
After that, we make sure that the portfolio does not
contain this stock to make sure a portfolio does not have the same stock more
than one time.
When the portfolio number of stocks is six the
while-loop stops from adding more stocks to the portfolio. Then, we add the
portfolio to a list of portfolios and proceed to create another portfolio until
the predefined number, in our case 10,000 is created and the loop stops
[43-49].

Figure 8: Creating portfolios code.
Figure 9 shows the code which runs when “Load Daily
data” option is clicked from the file menu. The first line is used to define a
list of string values named lines. The second line is used to create an open
file dialog box which is used to select a file that contains the daily data of
the stocks.

Figure 9: Load daily data code.
The If-statement block is used to make sure a file is
selected and then it reads the content of the file and adds them into the array
of lines.
Figure 10: Daily data file.
The first line in the for-loop block splits each line
based on the tab spaces between each value and assign them into an array named
daily. The second line finds the stock that has the same code as found in the
selected data file. Then, in the inner for-loop we add the daily data of the
stock into the stock.
Figure 11: Save Portfolios Code.
Figure 10 shows the daily data file. The file contains
a line for each stock, where each line starts by the stock code, and then it
contains the daily return of each stock. The values are separated by tabs.
Figure 11 shows the code which runs when “Save
portfolios” option from the file menu is clicked. Since the process of creation
of 10,000 seems to be a time consuming process, where we need to repeat the
process of creation, random an ID number, search for the stock, check if the
portfolio contains the stock or not, adding the stock and repeating this
operation for 10,000 times, we figured that we can create the portfolios and
save them, then we can load the portfolios later to assure the results
consistency. The function saves the ID’s of the stocks which the portfolio
contains as a string then writes the string to a file named “portfolios.txt”
[50].

Figure 12: Load Portfolios Code.
Figure 12 shows the code which runs when the “Load
portfolios” option from the file menu is clicked. As we can see the code,
creates a file reader and read the contents of the “portfolios.txt” file and
use the saved ID’s to create new portfolios using these ID’s.
Figure 13 shows the options of the calculate menu, the
menu contains two options as shown. The “Portfolio Risk Return” option is used
to calculate the Risk and Return of the portfolios, while the “Apply Genetic
Phase 1” is used to create the second generation portfolios.

Figure 13: Calculate menu options.
Figure 14 shows the code which is used to calculate
the risk and return for each portfolio, as we can see in the figure, the code
calls the functions from the portfolio class to calculate the risk and return.

Figure 14: Calculate risk and
return code.
Figure 15 shows the code used to calculate the
portfolio return. At first we defined a dummy variable named sum then we
calculated the sum of the stocks ID’s which is used to calculate the weight for
each stock. Where the weight for any stock is the stock ID divided by the sum
of stocks ID’s. Then in the second for-loop we calculate the value of each
stock return multiplied by its weight and add it to the variable named “re”.
Finally the function returns the Return value to be assigned as the portfolio
expected return.

Figure 15: Calculate Return Code.
Figure 16 shows the code used to calculate the
portfolio risk. To simplify the risk equation we divided the equation into
three loops, in the first for-loop we calculate the weights of the stocks and
add them into a list for an easier access in the later loops. In the second
loop we calculated the terms which contain the square value of the weight
multiplied by the square value of the stock risk then add them into the
variable named “variance”.

Figure 16: Calculate risk code.
The last for-loop is used to calculate the terms where
the covariance is required, as we can see the loop calls a function named
“Covariance (i,j)” which is used to calculate the covariance between the stocks
referred to as “i” and “j”.

Figure 17: Covariance Code.
Figure 17 shows the code used to calculate the
covariance between two stocks. The line inside the for-loop block is where the
work is done, to calculate the risk we subtract the expected return of the
stock from its daily value then multiply the result by the difference between
the second stock daily value and its expected return then add the result to the
variable named “cov”. This process is repeated for the number of available
daily data for the stocks. Finally the function divides the “cov” value by the
number of available daily data and returns the result as the covariance between
the stocks “i” and “j”.

Figure 18: Apply Genetic Phase1
Code.
Figure 18 shows the code to apply
HGA and the crossover operation. The first line reads the return weight
selected from the track bar shown in the application interface, while the
second line calculates the weight of the risk weight from the same track bar.
Then the for-loop is used to calculate the fitness for each portfolio given the
risk and return weights as selected in the track bar.

Figure 19: Calculate Fitness Code.
Figure 19 shows the fitness
calculation code which is simply the result of multiplying the weight of risk
with the expected risk of the portfolio added to the result of multiplying the
risk weight by the expected portfolio risk. Then, we call the function
“Select_Top_10” passing the list of portfolios named “GP1_Portfolios” which is
going to contain the top 10 portfolios.

Figure 20: Select Top 10 Portfolios Code.
Figure 20 shows the code to select
the top 10 portfolios. In the first for-loop we add the first 10 portfolios to
the list, then in the second loop we compare each portfolio fitness with the
fitness of the selected 10 portfolios and if the fitness of any portfolio is
greater than the fitness of one of the selected portfolios, we replace the
selected portfolio with the one with the greater fitness and break from the
comparison loop to prevent replacing more than one portfolio with the same
portfolio. The two lines of code after the top 10 selection are used to format
and view the data in the interface grid view. Then we use a function called
“Extract_GP1_Stocks” followed by a function called “Crossover”.

Figure 21: Extract GP1 Stocks Code.
Figure 21 shows the code used to extract
the GP1 stocks. GP1 is the name of the list that contains the top 10 selected
portfolios based on the highest fitness. This function extracts the stocks that
are used to create these top 10 portfolios, which are the genes to be used in
the crossover operation later on. In our application, we list those genes in
the bottom left grid view. The function checks if the list names “GP1_Stocks”
contains the stocks of each portfolio and if it does not contain that stock, it
adds the stock into the list, then it updates the grid view shown in the
application interface.

Figure 22: Crossover Code.
Figure 22 shows the code used to
create the crossover operation which is the core function of HGA. The crossover
operation is the operation in which the genes of the optimum selected
chromosomes are swapped between chromosomes in promises of generating a more
optimum chromosome. Since the crossover is basically a genes swapping
operation, instead of swapping a single gene at a time, we extracted the genes
and created a pool of genes using the “Extract_GP1_Stocks” function. In this
function, we use those genes to create a new generation of chromosomes
“portfolios”. At first, we create a temporary portfolio and temporary stock.
Then, we random a number between 0 and the number of extracted stocks. Then, we
add that stock to the portfolio after checking if the portfolio already
contains that stock or not, then we make sure that the portfolio we have
created does not match another portfolio that have been created earlier. Then,
we repeat this operation to generate six times the number of extracted stocks,
and then apply genetic phase2 and select the top 10 portfolio from the
portfolios.

Figure 23: Generate Menu.
Figure 23 shows the generate menu
which contains only one option used to generate the efficient frontier graph,
which is shown in the bottom left interface of the application. A point worth
mentioning here that, we have to normalize the risk and return values for the
portfolios so we can generate an efficient frontier graph.
Figure 24 shows the code used to
normalize the risk and return values for each portfolio. The normalized value
of the return is the result of dividing the portfolio return by the maximum
return in the portfolios. While the normalized risk is the result of dividing
the portfolios minimum risk by the portfolio expected risk. To do this, we
started by finding the maximum risk, minimum risk, maximum return and minimum
return. Then we shifted the intervals to a positive interval in order to
prevent the divide by 0 mathematical errors and calculated the normalized
values.

Figure 24: Normalization Code.