Portfolio Optimization Modelling with R for Enhancing Decision Making and Prediction in Case of Uganda Securities Exchange

Portfolio Optimization involves choosing proportions of assets to be held in a portfolio, so as to make the portfolio better than any other. In this research, we use a software for statistical computing R to analyse the performance of portfolio optimization models which include; Markowitz’s Mean-Variance (MV) model, the VaR model, and Konno and Yamazaki’s Mean-Absolute Deviation (MAD) model. We start by analysing multi-asset data for the major indexes in the world followed by historical data of 16 constituent shares listed on the Uganda Securities Exchange (USE) covering 6.5 years. The paper then tests the stock performance of the models using R. We found that GREXP bonds dominated the world market as they accounted for more than 60% of the Maximum Diversified Portfolio (MDP). For the USE, we generated more risk measures like volatility, Sharpe Ratio (SR), Risk Parity (RP), Expected Shortfall (ES) or CVaR which we used to assess stock performance. UMEME, NVL, BATU, JHL, DFCU, EBL, EABL, KCB, SBU and CENT were the bestperforming stocks. By understanding the performance of portfolio optimization models in R, Ugandan investors will develop a better view of the latest performance of the stocks listed on the USE. This will help them to decide on which stocks to include in their investment portfolios, thus prevent wrong investment decisions.


Introduction
The capital market is an important component of the financial system, which entails funds being mobilized by firms, institutions or the government directly from savers through the issuance of equities or bonds (Kasekende, 2017b).Efficient capital markets can accommodate the needs of investors and are well suited to provide long-term finance to the corporate and public sectors (Kasekende, 2017b).It is important to emphasise the role of the capital markets in business and economic research in Uganda.By using the media and research to feed the public on investment opportunities available in the Ugandan capital market, Ugandans will make a useful decision on where to invest their money (Kasekende, 2017a).It is surprising that only a few Ugandans know about treasury bills as opposed to buying a boda-boda and taxi (Semakula, 2017).Therefore, we are motivated to use analytical skills to synthesize complicated economic and financial issues such as portfolio optimization for the public.Since this paper focuses on Uganda's capital market, a brief review of the Capital Markets Authority (CMA), the ALTX, and the Uganda Securities Exchange (USE) is worthwhile.
The responsibilities of the CMA include: development, promotion, and regulation the Uganda capital markets industry, with the main objectives of ensuring market efficiency and investor protection (CMA, 2017).A stock exchange is a marketplace for securities, with stockbrokers who earn commissions on transactions they make (Njanike, Katsuro, & Mudzura, 2009;Quaye, Mu, Abudu, & Agyare, 2016).The USE and the ALTX are currently the two licensed and registered stock exchanges in Uganda.The USE with close to 40,000 registered investors is the central place for trading securities by licensed dealers (USE, 2017b).It provides a platform for raising capital through the issuance of debt, equity and any other instruments to potential investors.
The USE operates through 3 market segments: the Fixed Income Securities Market Segment (FISMS); the Main Investment Market Segment (MIMS); and the Growth Enterprise Market Segment (GEMS) (USE, 2017a).The MIMS is the market for established companies looking to raise funding.It consists of 16 listed Equities 8 of which are locally listed: Bank of Baroda Uganda (BOBU); British American Tobacco Uganda (BATU); Uganda Clays Limited (UCL); New Vision Printing and Publishing Company Ltd (NVL); Stanbic Bank Uganda (SBU); Development Finance Company of Uganda Ltd (DFCU); National Insurance Corporation (NIC) and Umeme Limited (UMEME).MIMS also consists of 8 other equity securities that are cross-listed on the Nairobi Securities Exchange (NSE): Equity Bank Limited (EBL); Kenya Commercial Bank (KCB); Jubilee Holdings Limited (JHL); Centum Investment Company Ltd (CENT); East African Breweries Limited (EABL); Kenya Airways (KA); Nation Media Group (NMG); Uchumi Supermarkets Limited (UCHM).NSE is the main stock exchange in Kenya and offers an automated platform for the listing and trading of various securities (NSE, 2017).
The FISMS offers a platform for fixed income securities.Its main objective is to provide a separate independent market for the companies wishing to raise capital through issuing and listing of fixed income securities like treasury bonds, preference shares, corporate bonds, and debenture stocks (USE, 2017a).It also acts as a market for investors wishing to trade the above securities at the USE.
The FISMS also lists other short-term financial instruments such as commercial papers and treasury bills.It currently has 39 government of Uganda treasury bonds and 6 corporate bonds listed.
The Bank of Uganda (BOU) licensed all commercial banks to have unrestricted access to the primary market for all government security operations.This is part of BOU's ongoing commitment to make an investment in government securities easier to the public (Mutebile, 2017).The primary dealer system aims to promote participation in government securities markets, to foster the development of financial markets, to improve the secondary market trading system, and to ensure efficiency in the operations related to the government securities market at the central bank (Mutebile, 2017).Primary dealers are acknowledged for their contribution to the growth of the government securities market as they ensure high demand during primary market auctions (Mutebile, 2017).
The ATLX East Africa exchange went live in Kampala in July 2016, with the optimism of improving access to foreign financial securities by local stockbrokers (Busuulwa, 2016).The ATLX trading platform provides a medium for Exchange Traded Funds (ETFs), foreign equities, Asset-Backed Securities (ABS), and bonds.ETFs are recognized as investment vehicles of choice for investors targeting any asset classes, industry sectors, and low-cost exposure to equity market indices (Krause, Ehsani, & Lien, 2014).ALTX is owned by ALTEX Africa Group (AAG), a firm based in Mauritius and founded by Jatin Jivram and Joseph Kitamirike in 2013 (Reuters, 2016).
The USE is a reflection of Uganda's economy; when the economy does not perform well, the markets do not do well.The automation of the stock trading at the USE in July 2015 was highly anticipated to turn around the fate of the stock market.At the same time, it would act as an eye opener for Uganda's stock market to foreign investors (Bwiso, 2017).

Portfolio Optimization
Portfolio Optimization involves choosing proportions of assets to be held in a portfolio, so as to make the portfolio better than any other.Simultaneous profit maximization and risk minimization has been a decision rule over the years with the development of the minimax concept providing more interesting insight into the history of risk research (Li, Wu, & Ojiako, 2014).The minimax concept deals with the provision of choice reasons behind an individual's decision choice when faced with a number of possible alternative actions, with the impact of each decision choice unknown (Naslund & Whinston, 1964;Li et al., 2014).
According to Li et al. (2014), the major reason for decision choice was because rational individuals were more likely to seek to maximize expected returns from a decision, but this expectation would be weighted by the probability of an alternative outcome (Simon, 1959).They, therefore, advocated for decision models to come into play.Quantitative and mathematical models have been increasingly applied to decision making and prediction, especially in aspects of business management with highly complex characteristics (Watson & Brown, 1978;Xu, Zhou, Jiang, Yu, & Niu, 2016;Li et al., 2014) individuals who are wealth maximization minded and always aim for higher returns on their investments in stocks listed on exchanges (Quaye et al., 2016).Investment management involves an investor deciding on whether to invest in a particular stock, to increase or reduce their portfolio investment, to carry out portfolio diversification or to entirely exit the market (Li et al., 2014).
The first portfolio optimization model was developed by Markowitz (1952) which now serves as an inspiration to a number of scholars interested in understanding the relationship between risk and profits.Then other scholars like Konno & Yamazaki (1991) developed their portfolio optimization model.Risk measure is a key research component in portfolio optimization (Xu et al., 2016).Risk is the chance of exposure to adverse consequences of uncertain future events (ACCA, 2017).It refers to the uncertainty associated with a decision which may deliver undesirable outcomes (Sitkin & Pablo, 1992).It involves risk management and risk evaluation (Hansson, 1996).Risk management consists of aspects such as; outcome uncertainty, outcome expectations, and the potential of an outcome (Polak, Rogers, & Sweeney, 2010;Li et al., 2014).Risk management is used to identify the risks associated with new opportunities that lead to an increase in the chance of profitability and maximized returns (ACCA, 2017).Effective risk management improves financial performance thereby boosting shareholders' value (ACCA, 2017).
It is perceived that risk has economic characteristics, which prescribe that larger risks are associated with events that vary most economically (Sitkin & Pablo, 1992).Therefore, we assume that events that are characterized by large variability between actual and expected outcomes will accrue more risk (Li et al., 2014).These outcomes may be either positive or negative (Ward, 2003).Although risk management is about managing both negative and positive risks (Haimes, 2009), this paper mainly focuses on the management of the negative impact of risk.The study aims to generate an understanding of how the balance between risk minimization and profit maximization can be optimized by using R language to test the performance of models against data obtained from the USE.
We believe that investment decisions in listed securities are driven by the investors' ability to understand the data and information at their disposal in order to make informed decisions.A good understanding of the performance of models will enable risk managers better manage corporate risks.After this introduction, in the next section, we introduce the concept of portfolio optimization modelling.We also refer to the literature to review the optimization models of interest.

Model Overview
Portfolio Optimization has been used over the years in the financial services industry.It is the allocation of capital to the available assets so as to maximize return on the investment and minimize risk (Mayanja et al., 2013).It has been applied by various scholars (Polak et al., 2010;Li et al., 2014;Xu et al., 2016) in finance to generate an understanding how risk may be minimized while profits are maximized.Portfolio Optimization research can be traced to the work of Markowitz (1952), who developed a model to solve the problem of selecting stocks.Markowitz's mean-variance (MV) model is a quadratic program model, where the variance of each stock is adapted for measuring risk (Xu et al., 2016).
The model assumes that all investors are reasonable (rational) and reluctant to take risks (risk-averse).Thus, in effect, it is expected that investors are more likely to choose assets with a higher return given the same level of risks.
According to Luenberger (1998), MV portfolios are obtained from formulating a mathematical problem.We assume n assets, whose rates of return are , , , n r r r  and covariances ij σ , for , 1, 2, , i j n =  .We define a portfolio by a set of n weights , 1, 2, ,  , that add to one.With negative weights corres- ponding to short selling.Therefore, in order to find a minimum-variance portfolio, the value of the mean is fixed at some arbitrary value r then a portfolio of minimum variance with this mean can be found.Hence the problem is formulated.
This problem lays a foundation for single-period investment theory.It addresses the trade-off between expected rate of return and variance of the rate of return in a portfolio (Luenberger, 1998).The resulting Markowitz problem can be solved numerically to obtain a solution.It can also be solved analytically to get strong additional conclusions from the analytic solution.The Markowitz problem is used when a risk-free asset (e.g.: treasury bills), as well as a risky asset, are available.

Solution to the Markowitz problem
The conditions for the solution to the problem is found using Lagrange multipliers α and β .The Lagrangian (L) is formed.

(
) ( ) The first derivative of L with respect to each variable i w is found and set to zero.The differentiation is done for two-variable cases, then it becomes easy to generalize for n variables.For the two variables, Equations ( 2)-( 5) are solved simultaneously to find the unknowns 1 2 , , w w α and β .

Limitations of the model
The MV model has some limitations.Chen et al. (2009) argue that the model utilizes standard deviation for measuring risks and that both negative and positive risks are employed as variables.Li et al. (2014) argue that investors only tend to focus on negative risks.Bodie, Kane, & Marcus (2011) argue that the model limits the role of conventional risk measures.Much as it gauges how much an investment's returns vary over time, it is affected by downside and upside moves, whereas investors fear losses much more than they value gains (Wang, Song, & Lin, 2017).Xu et al. (2016) argue that it is difficult to use the model for optimizing large portfolios.
After Markowitz, other scholars developed portfolio optimization models.Konno and Yamazaki (1991) developed the mean-absolute deviation (MAD) portfolio optimization model which adopts a mean's absolute deviation for measuring risk instead of the variance.Based on the guidance by Li et al. (2014), the MAD model is mathematically expressed as: ( ) , where: j R = the random return of asset j.
They also proved that the mean absolute deviation can be approximated as: ( ) ( ) , where: jt r = the realization of random variable j R during period t.Therefore Li et al. (2014) further expressed the MAD model as: ( ) In the above equations, d is the required rate of return, i x is the weight vari- able.Constraint ( 7) is for ensuring that the minimum portfolio return achieves the investors' minimum requirements.( 8) means that the total fraction equals to one, implying that all the money must be invested.( 9) means that short selling is prohibited in the model.
Various scholars (Simaan, 1997;Liu & Gao, 2006;Li et al., 2014) where: x µ = the portfolio VaR, d is the required rate of return, and i x is the weight variable.
Just like in the case of MV and MAD models, the constraint ( 11) is for ensuring that minimum portfolio return achieves investors' minimum requirements.
(12) means that the total fraction equals to one, implying that all the money must be invested.( 13) means that short selling is prohibited in the model.The VaR model uses variance-covariance approach, and according to Li et al. (2014), the mathematical formula for this can be expressed as: VaR M t λ δ = * * * where: M = portfolio market value, λ = confidence level, δ = volatility of the portfolio and t = time period.As , , M t λ are all constants, δ which is the standard deviation is the only variable in the formula.

Risk-Based Performance Measures
In addition to analysing the above models in R, we generated the following measures that helped us to explain overall stock performance.

Volatility
Refers to the degree of variation of stock prices over time as measured by the standard deviation (Bodie et al., 2011).It is a statistical measure of dispersion of the returns of a security or market index which can be measured by standard deviation or variance between returns from that same security or market index (Namugaya et al., 2014).

Sharpe Ratio (SR)
It was developed by Sharpe in 1966 and it's derived from the capital market line (Rana & Akhter, 2015).It's advantageous because it provides returns (reward) per total risk (volatility) for a security or index (Bodie et al., 2011).Since risk is measured by standard deviation of the security, SR gives a risk and return trade-off (Rana & Akhter, 2015).Therefore, it explains an investor's compensation for assuming additional risk.Higher SR reflects the superior performance of a security.This reward-to-volatility measure is used for evaluating investment managers' performance.

Risk Parity (RP)
RP is used in portfolio management to focus on allocation of risk (volatility), instead of capital allocation.The RP approach advocates that when asset allocations are adjusted to the same level of risk, the RP portfolio can achieve a higher SR and become more resistant to market downturns than traditional portfolios (Lee, 2014).This approach to building a RP portfolio is similar to the one of creating a minimum variance portfolio subject to the constraint that each asset contributes equally to overall volatility (Amundi, 2014).RP means that each asset (single stock, asset class, equity sector) has an equal contribution to the total portfolio risk (Amundi, 2014).

Conditional Value at Risk (CVaR) or Expected Shortfall (ES)
ES and CVaR are downside risk measures (Xu et al., 2016).ES is a risk measure used to evaluate market risk or credit risk of a portfolio (Xu et al., 2016).It is the expected portfolio loss when VaR has been breached (Bodie et al., 2011).CVaR helps to estimate the magnitude of expected loss on the very bad days (Xu et al., 2016).
After this review of the literature, we describe the data collection method employed.

Data Collection
We utilized the 6.5 years' historical data for 16 constituent shares listed on the USE indexes (LSI & ALSI).The USE has two indexes, the All Share Index (ALSI) which tracks all the 16 listed companies (8 local and 8 cross-listed at Nairobi Securities Exchange) and the local share index (LSI) which tracks only the 8 local companies.Both indexes are market-cap or value weighted.Stock prices were obtained from the website, https://www.use.or.ug/.Returns of each stock at the closing price of daily trading was computed and used for data analysis.

Data analysis techniques
The calculation of portfolio optimization models includes 6.5 year's historical data for 16 different stocks from January 2010 to June 2016.All calculations were undertaken using the R language.We tested the performance of models using the same sets of historical data in order to generate an understanding of how stocks performed during the period under study.
A graphical analysis of the movement of the LSI & ALSI between January 2010 and December 2016 is shown in Figure 1 below.

Calculating techniques
The portfolio optimization code was written in R, a software for statistical computing (R Project, 2016).To exemplify our analysis, we considered portfolios of common stocks.Raw data downloaded from USE website contains Source: (USE product markets|ALSI All share Index|LSI Local share Index).historical prices of each stock.To estimate returns empirically, the daily stock prices were used as follows: The stock returns were converted into .xlsxreadable in R language.We also obtained sector numbers of each of the stocks from the USE website.The sector file was converted into a.csv file readable in R language.

Markowitz's Mean-Variance (MV) Model Portfolio Settings >Library (fPortfolio)
MV portfolios are defined by time series data set, the portfolio specification object, and the constraint strings.Specifying the portfolio requires three steps: Step 1: portfolio data Step 2: portfolio specification For Markowitz's MV portfolio we use the default settings (Würtz et al., 2015).
The printout tells us that the portfolio type is concerned with the mean-variance portfolio "MV", that we want to optimize (minimize) the risk "minrisk" using the quadprog solver "solveRquadprog", and that the sample covariance estimator "covEstimator" will be applied.The other two parameters shown are the riskfree rate and the number of frontier points.The first will only be used when we calculate the tangency portfolio and the Sharpe ratio, and the second when we calculate the whole efficient frontier (Würtz et al., 2015).
Step 3: portfolio constraints In most cases, we worked with long-only portfolios.
Specifying forces the lower and upper bounds for the weights to zero and one respectively.Many alternative constraints have already been implemented in fPortfolio.These include unlimited short selling, lower and upper bounds, linear equality and inequality constraints, covariance risk budget constraints, and nonlinear function constraints.The solver for dealing with these constraints has to be selected and assigned by the function setSolver().

Konno and Yamazaki's Mean-Absolute Deviation Model
For MAD model we also use the default settings and then make the code for portfolio optimization as shown below (Würtz et al., 2015).

VaR Model
Risk-optimal portfolios can be differentiated from Markowitz's portfolios based on the fact that a certain VaR or ES (expected shortfall) level is not the result of an efficient portfolio allocation, but an objective (Pfaff, 2016).The market risk measure CVaR is the expected loss exceeding the VaR for a given confidence level (Pfaff, 2016).For CVaR model we can use the default settings as shown below (Würtz et al., 2015).
A tangency portfolio was computed for the multi-assets using the solver; sol-veRquadprog as shown below.We obtained portfolio weights, covariance risk budgets, and target returns and risks.
GREXP had the highest portfolio weight followed by GDAXI and GLD.
GREXP had the highest covariance risk budgets followed by GLD and GDAXI.
The target return was 0.4773, covariance was 0.9110, CVaR was 1.4095 and the VaR was 1.2320.
An efficient frontier for multi-assets was drawn with standard deviation set as 8.We also incorporated minimum tail dependence (MTD) and risk parity (RP) also known as equal risk contribution (ERC) and obtained results on the efficient frontier as shown in Figure 2.

Uganda Securities Exchange (USE) Data Analysis
After having a thorough analysis of world major stock indexes data, we then focused on USE data.We read the USE data in R language using the following code and assumed 250 working days in a year: We then extracted the MV portfolio frontier data as shown by the following output indicating the portfolio weights, covariance risk budgets and target returns and risk for the 2 indexes and 16 stocks listed on the USE.
We obtained the MV tangency portfolio for all stocks listed on USE showing that BATU had the highest portfolio weight and covariance risk budget followed by JHL.ALSI dominated LCI in terms of portfolio weight and covariance risk budget over the 6.5 year period.The mean return was 0.0012, covariance was 0.0100, CVaR was 0.0161 and VaR was 0.0091.Cardinality shows the performance of portfolios in the following order; w_MV, w_MSR, w_8, w_RP and w_RP2.
A plot for the various portfolio histograms is as shown in Figure 6.
We used R to get the risk parity plot by typing > plot(w_RP), > plot  This could also be obtained by looking at the head and tail by using > head (vol) then Ctrl+R, > tail (vol) then Ctrl+R.The following results in the console.
We extracted the minimum and maximum values of the various portfolios as shown below.
We extracted pie chart plots showing the USE portfolios and the multi-asset portfolio as the Max Diversified portfolio as shown in Figure 8.

Discussions
ALSI dominated LCI in overall performance because of the benefits of crosslisting.The LCI performance is based on a single listing on USE.The NSE is more developed than USE, therefore various benefits accrue from the crosslisting.Increased marketability for firms' securities and access to a broader investor base are the major benefits of cross-listings (Chouinard & D'Souza, 2004).
Other benefits (De Landsheere, 2012) include financial gains; liquidity; increase in the volume of trading; reduced cost of capital; increased shareholder base; and the establishment of a secondary market for shares used in acquisitions.
Managers prefer debt issuance (increase gearing) when the share price is low and issuance of equity when the share price is high.The resulting issue of debt or equity is used by investors as a signal from managers as to the true worth of the company's shares.The information asymmetry between investors and managers can be used to value shares (ACCA, 2016).When equity is issued, the market takes it as a signal that shares are overvalued.This may make investors sell their shares and make substantial gains which lead to a fall in the share price.
As a result, the cost of equity rises, which leads to a higher marginal cost of finance.To avoid this scenario, managers may issue debt even if shares are seen as overvalued.The issue of debt is interpreted as share undervaluation.Investors will have an incentive to get a bargain and will, therefore, start to buy the shares, leading to an increase in share price (ACCA, 2016).
We establish the major reasons behind individual best-performing stocks based on the latest financial statements; UMEME, NVL, BATU, JHL, DFCU, Financial institutions use VaR model to manage risk.Xu et al. (2016) used a large CVaR-based method for portfolio selection.Risk management is a subject of interest in finance and management, therefore a comprehensive understanding of portfolio optimization models by Ugandan investors will enable them to assess the performance of stocks listed on the USE and thus preventing wrong investment decisions.
The portfolio functions expect S4 time series objects.We use Rmetrics timeseries package for time series generation.Alternatively, we can load a data set from the demo examples provided in the fPortfolio package(Würtz, Setz, Chalabi, Chen, & Ellis, 2015).The portfolio functions expect time-ordered data records.To sort S4 time series objects, use the generic function sort().To align time series objects and to manage missing values we use the function align().If we want to bind and merge several time series to a data set of assets, we can use the functions cbind(), rbind() and merge().

Figure 3 .
Figure 3.The efficient frontier with various portfolios.

Figure 4 .
Figure 4. Pie chart plots for world major indexes.

Figure 5 .
Figure 5.The efficient frontier with various USE portfolios.
Figure 8. Pie chart plots USE portfolios and the multi-asset portfolio.