Portfolio Management Using Artificial Trading Systems Based on Technical Analysis

Evolutionary algorithms consist of several heuristics able to solve optimization tasks by imitating some aspects of natural evolution. In the field of computational finance, this type of procedures, combined with neural networks, swarm intelligence, fuzzy systems and machine learning has been successfully applied to a variety of problems, such as the prediction of stock price movements and the optimal allocation of funds in a portfolio.

near-optimal set of rules varies among market phases but presents stable results and is able to reduce or eliminate losses in down-trend periods.
As a natural consequence of these studies, evolutionary algorithms may constitute a promising tool also for portfolio strategies involving more than two stocks. In the field of portfolio selection, Markowitz and Sharpe models are frequently used as a task for genetic algorithm optimization. For instance, the problem of finding the efficient frontier associated with the standard mean-variance portfolio is tackled by Chang et al. (2000). They extend the standard model to include cardinality and composition constraints by applying three heuristic algorithms based upon genetic algorithms, tabu search and simulated annealing. Computational results are presented for five data sets involving up to 225 assets. Wilding (2003) proposes a hybrid procedure for portfolio management based on factor models, allowing constraints on the number of trades and securities. A genetic algorithm is responsible for selecting the best subset of securities that appears in the final solution, while a quadratic programming routine determines the utility value for that subset. Experiments show the ability of this approach to generate portfolios highly able to track an index.
The β − G genetic portfolio algorithm proposed by Oh et al. (2006) selects stocks based on their market capitalization and optimizes their weights in terms of portfolio β's standard deviation. The performance of this procedure depends on market volatility and tends to register outstanding performance for short-term applications.
The approach I consider for portfolio management is quite different from the previous models and is based on technical analysis. In general, portfolio optimizations using technical analysis are modular procedures where a module employs a set of rules based on technical indicators in order to classify the assets in the market, while another module concentrates on generating and managing portfolio over time (for a detailed presentation of the subject, the interested reader may refer to Jasemi et al. (2011)).
An interesting application in this context is the approach developed by Korczak & Lipinski (2003) that leads to the optimization of portfolio structures by making use of artificial trading experts, previously discovered by a genetic algorithm (see Korczak & Roger (2002)), and evolutionary strategies. The approach has been tested using data from the Paris Stock Exchange. The profits obtained by this algorithm are higher than those of the buy-and-hold strategy.
Recently, Ghandar et al. (2009) describe a two-modules interacting procedure where a genetic algorithm optimizes a set of fuzzy technical trading rules according to market conditions and interacts with a portfolio strategy based on stock ranking and cardinality constraints. They introduce several performance metrics to compare their portfolios with the Australian Stock Exchange index, showing greater returns and lower volatility.
An alternative multi-modular approach has been developed by Gorgulho et al. (2011) that aims to manage a financial portfolio by using technical analysis indicators optimized by a genetic algorithm. In order to validate the solutions, authors compare the designed strategy against the market itself, the buy-and-hold and a purely random strategy, under distinct market conditions. The results are promising since the approach outperforms the competitors.
As the previous examples demonstrate, the technical module occupies, in general, a subordinate position relative to the management component. Since transaction costs, cardinality and composition constraints are of primary importance for the rebalancing purpose, the effective impact of technical signals in the development of optimal portfolios is not clear. To highlight the benefits of using technical analysis in portfolio management, I propose an alternative genetic optimization heuristic, based on an equally weighted zero investment strategy, where funds are equally divided among the stocks of a long portfolio and the stocks of a short one. Doing so, the trading signals directly influence the portfolio construction. Moreover, I implement three types of portfolio generation models according to the risk-adjusted measure considered as the objective, in order to study the relation between portfolio risk and market condition changes.
The remainder of the chapter is organized as follows. Section 2 explains in detail the proposed method, focusing on the investment strategy, the definitions of the technical indicators and the evolutionary learning algorithm adopted. Section 3 presents the experimental results and discussions. Finally, Section 4 concludes the chapter with some remarks and ideas for future improvements.

Trading strategy implementation
Three interacting modules compose the management system I have developed. The trading strategy is represented by the investment module, the calculation of trading signals is assigned to the technical module and an evolutionary learning component, based on Kaucic (2010), generates optimal portfolios. The core of the last module consists, in particular, of two parts: i) a learning mechanism, that manages the information derived from the technical module; ii) a variable length string genetic algorithm, that optimizes the portfolios according to the technical committee's sentence produced in the learning phase.

Investment module
As I mentioned in the introduction, I define the portfolio management problem in terms of a zero investment strategy (see, for example, Chincarini & Kim (2006)). According to this approach, I seek to profit from detecting perceived mispricings in individual securities. The buying and selling are concurrent events -I buy underpriced securities and simultaneously sell an offsetting amount of overpriced securities. The combination of the long and short portfolios generates the so-called long-plus-short portfolio. The excess return on this combined portfolio equals the excess return generated by the short portfolio and the interest earned on the proceeds from the short sales, increased by the excess return obtained from the long portfolio. In this sense, the ability to short, by increasing the investor's freedom to act on his/her insights, has the potential to enhance returns from active security selection. Thus, the zero investment strategy used in the portfolio management module should highlight the capabilities of technical indicators to rank assets in a stock picking perspective.

Technical module
The detection of overbought/oversold conditions and short-term changes in the relative value of stocks are tackled by applying technical analysis in order to summarize all relevant information of the past history of financial time series into short-term statistics. This approach has the advantage of obtaining up-to-date technical indicators as often as every few seconds. I adopt different types of technical indicators in order to dispose of different points of view 283 Portfolio Management Using Artificial Trading Systems Based on Technical Analysis www.intechopen.com from which to analyze price movements and unrealized piece of news that would influence a given security in the near future. Once a signal is produced for the stocks in the market, a positive number (ID) is assigned to the corresponding parameter configuration. These IDs represent the genetic material for the next step. The technical indicators employed are the described in the following subsections (for an exhaustive list of indicators used by practitioners, refer to Colby & Meyers (1990) and Murphy (1998)).

Rate of change indicator
The rate of change (ROC) indicator represents the speed at which a variable changes over a specific period of time. In this study, it is calculated as the relative difference between the current closing price P t and the closing price n days in the past P t−n−1 , i.e. (1)

Relative strength index
The relative strength index (RSI) is a momentum oscillator that compares the magnitude of recent gains to the magnitude of recent losses for a given stock, in order to highlight potential short-term overbought and oversold levels. It is defined at each time t as: where RS is the ratio of average gains and average losses during the last n days. It assumes values between 0 and 100. A level less than 30 indicates a buy signal, conversely, a level greater than 70 suggests a sell signal.

Moving average indicators
A moving average is a mean value calculated over a previous rolling period of fixed length n. I use three types of moving averages for a rolling window of length n at time t: i) the simple moving average (SMA), defined by ii) the weighted moving average (WMA), calculated as where n = ∑ n−1 j=1 j; iii) the exponential moving average (EMA), expressed by EMA 0 (n)=P 0 and 0 is a reference date.
These moving averages constitute the building-blocks of all the technical signals I define in what follows. The idea is to use the down crossing of a shorter moving average with respect to a longer moving average as a buy signal and the crossing in the opposite direction as a sell signal.

Hull moving average
The Hull moving average is a smoothing signal defined by the WMA of length square root n of the difference between a WMA of length n/2 and a WMA of length n, i.e.
HMA is more responsive to current price activity with respect to SMA, WMA and EMA while maintaining curve smoothness.

Variable-length moving average
The variable-length moving average (VMA), applied extensively in literature for their simplicity (see, for example, Brock et al. (1992)), is defined at time t as the difference between a n 1 days SMA (shorter) and a n 2 days SMA (longer): with n 1 < n 2 .

Moving average convergence divergence
The moving average convergence divergence (MACD) is a trend follower procedure that combines two EMAs of past prices: with n 1 < n 2 . It performs better during strong trending periods and, conversely, tends to lose money during periods of choppy trading.
I consider a variant of this indicator, according to which a trigger signal SL, expressed as a k period EMA of the MACD, is also used to obtain the MACD histogram (MACDH) indicator, defined by that highlights variations in the spread between fast and slow signals (see Fusai & Roncoroni (2008) for a detailed description).

Weighted and simple moving average
The weighted and simple moving average (WSMA), proposed by Leontitsis & Pange (2004) is a twice smoothed linear combination of the difference of a n 1 WMA and a n 2 SMA and is expressed by with n 1 < n 2 and v is a real number used to weight the moving averages. The WSMA is obtained by applying twice the procedure used to compute GD (see Leontitsis & Pange (2004) for the exact definition).

On balance volume indicator
The on balance volume (OBV) represents the flow of volume in a stock and is calculated as a running cumulative total of the daily volume transactions, adding the amount of daily volume when the closing price increases, and subtracting the daily volume when the closing price decreases: where Vol t is the volume at day t.
The signal employed for trading is obtained by comparing the OBV level with the simple moving average on the last n days of the OBV itself: an OBV greater (lesser) than the SMA indicates that the volume is on up (down) days, confirming a possible up (down) trend.

Evolutionary learning module
The portfolio selection problem can be stated as the problem of detecting the individual that produces the best risk-reward tradeoff among a set of artificial expert systems. In this context, an expert system becomes the result of the mean average of a set of technical signals, the so called plurality voting committee (PVC).
My evolutionary procedure is based on a genetic algorithm that uses an elite strategy to clone the best individual from one generation to the next. Selection is made by the stochastic universal sampling (Baker (1987)). Moreover, in order to generate portfolios consistent over time, I implement the population seeding suggested by Aranha & Iba (2007), according to which the best individual from the previous optimized population is copied in the initial population of the current optimization period.

Genetic encoding
My chromosome S would be composed of two blocks of genes. The first block uses one gene and represents the long-plus-short portfolio size. The second block represents the ensemble of technical signals. It is based on the variable length string encoding proposed in Kaucic (2010). This block uses a string of length l max , fixed by the user, that represents the maximum length acceptable for an ensemble. Each gene assumes a value in the enlarged discrete alphabet {0, 1, . . . , |S all |} where each non-zero number corresponds to an ID in S all and the zero index has been added in order to utilize the existing evolutionary operators as much as possible and corresponds to the "no rule" input. The chromosome is rearranged so that all 0's are pushed to the end. I define valid an individual when it has at least two non-zero alleles and all the included rules are different. In this manner, the genetic algorithm excludes the chromosome with all the alleles null and the ensembles with repeated signals. Subsequently, the non-zero genes of the second block are sorted in an increasing way to guarantee more diversity among population since the ensembles resulting by the PVC technique are invariant under permutations of their constituents.

Crossover
Uniform crossover is used to avoid the positional and distributional bias that may prevent the production of good solutions (see Reeves (2003) for a detailed discussion). A control on the composition of each offspring is included to guarantee its admissibility.

Mutation
An alternating mutation probability μ m (g) that depends on the generation g ∈{ 1, . . . , G}, throughout a triangle wave relation, is used to provide a better balance between exploration and exploitation of the search space. The mutation operator is based on Bandyopadhyay & Pal (2007): for each position in a string, it is determined whether conventional mutation can be applied or not with probability μ m . Otherwise, the position is set to 0 with probability μ m 1 and each "no signal" is set to a signal according to another mutation probability μ m 2 . Similar to the crossover, the string is then reordered to have the admissible form previously described.

Objective
My procedure applies to a general type of performance measures, grouped under the name of reward-to-risk ratio (refer to Rachev et al. (2008) for a detailed presentation), shortly RR. This performance measure is defined as the ratio between a reward measure of the active portfolio return and the risk of the active portfolio return: where r p denotes the return of the portfolio, r b represents the return of the benchmark portfolio, r p − r b is the active portfolio return, and ν(·) and ρ(·) are a generic reward measure and a generic risk respectively. In this case r b is the 3-month Treasury Bill. The objective is to find the portfolio with the maximum RR.
Since I base my investment solely on technical analysis and I make no hypothesis about the distributions of r p and r b , I can calculate RR(r p ) using the available historical returns in a certain period of length T back in time. Following Kaplan (2005), let r t = r p − r b t denote the active portfolio return at time t, t = 1, . . . , T, the reward measure becomes By varying the risk measure at the denominator of Equation (12) i) the information ratio (IR), for which the risk measure is the standard deviation of r t , that is ii) the Sortino Ratio (SR), for which the risk measure is the square root of the second lower partial moment of r t , that is A third performance measure that has become very popular among practitioners in the last years is the so-called Omega ratio, which is defined as: where μ (r t ) comes from Equation (13) and σ − 1 represents the first lower partial moment of r t , i.e.

Parameter values
In the following experiments, I used the same values for the genetic algorithm parameters, which were obtained from preliminary tests and gave acceptable convergence results. The parameter setting is listed in Table 1. A set of experiments is conducted to analyze whether the developed portfolio based on technical analysis suggestions and risk-adjusted measures consistently beats the index during the last 5.5 years. To this end, during the evaluation period I implement a sliding window procedure able to adapt the technical signals to the market conditions by matching the trading signal with a period in the recent past, that constitutes the training window. The resulting indicators are then applied to trading immediately after the last historical data period has expired, i.e. the testing window. A new search takes place for each new window. However, instead of starting with a completely new population, a memory is maintained of the best solution from the previous training window, that is used in the generation of the initial population for the next training window. This is achieved using the seeding operator explained in the previous pages.

Data and experiments description
The characteristics of each case-study are summarized in Table 2. It emerges that the only difference among the experiments is the risk-adjusted measure to optimize. The purpose, in fact, is to study the impact that these performance measures have on the zero investment portfolios according to changing market conditions, assuming no transaction costs.
Finally, I compare the performance of these evolved portfolios with the DJI index, which reflect the performance of the market as a whole.  By comparing the plots, it could be observed that the optimized zero investment portfolios outperform remarkably the index during the sample testing period, except for the meltdown. However, even in that period, the Omega based portfolio is able to control the losses better than all the other competitors. After April 2009, the Sortino ratio based portfolio attains results similar to those of the Omega based portfolio. In general, the Information ratio based portfolio does not succeed in obtaining the return levels of the other two optimized portfolios.

Analysis of the performance
In Table 3 I report the returns on an annualized basis and compare the realized values and the returns relative to the the 3-month Treasury Bill.
The total return represents the increase in portfolio values over the whole investment period. While the market improves slightly, with a total return of 29% and an annualized mean return of 5.5%, the Information ratio based portfolio increases by 70% with an annualized mean return of 14%. At the same time, the Sortino ratio based portfolio reaches levels of 119% and 26% respectively. The best results are attained by the Omega based portfolio, which realizes an increment of 125% and an annualized mean return of 26%. The annualized geometric mean returns, however, reveal the difficulties of all the optimized portfolios during the crisis. This is clear for the Information based portfolio, for which the geometric mean is negative (−1.35%). The portfolios I constructed present a double annualized volatility with respect to the market. Overall, from the summary statistics of the daily returns listed in Table 4 it emerges that the optimized portfolios guarantee a better return potential then the index, even if they may be more volatile. The largest loss, around −19% for all the simulated portfolios, is suffered during the crisis. In the same period the market produces a −8%. However, while the DJI returns to the pre-crisis levels only in the last weeks of the test period, the developed portfolios react faster, generating values comparable to those at the beginning of the crash after only six months.
Finally, I compare the portfolios according to the Sharpe ratio, a reward-to-variability measure that represents how much excess returns investors are awarded for each unit of volatility. It is defined as the difference between the annualized arithmetic mean fund return, r p , and the annualized arithmetic mean risk-free return, r f , divided by the annualized standard deviation σ p of the fund returns: Once again, the Omega based portfolio proves to be superior with respect to the other competitors.

Conclusions
In this chapter I discussed the development of artificial trading systems for portfolio optimization by using technical analysis.
From a mathematical point of view, I presented a multi-modular evolutionary heuristic capable to deal efficiently with the zero investment strategy. Optimal allocations were detected by using a trading system, structured on the basis of a pool of technical signals, in which the parameters were optimized by a variable length string genetic algorithm. In addition, the chromosome representation I adopt permitted to manage, at the same time, the parameters of the investment strategy.
From an economic point of view, I applied the developed procedure in the optimization of equity portfolios. In particular, I analyzed the efficiency of a general class of performance measures, i.e. the reward-to-risk ratios, for the generation of promising portfolios over time.
Experimental results using historical data from the Dow Jones Industrial Average index showed that the optimized portfolios tend to register outstanding performance for short-term applications. Moreover, they react faster to the market crashes, as I verified during the recent crisis between 2008 and 2009. I plan further work to implement the transaction costs in the management phase and a more robust learning method for the definition of the technical based committee in the selection of the more informative technical signals.

Acknowledgements
I wish to dedicate this work to the memory of my mother, Maria Cristina, who always believed in me and whose smile supported me in the development of these ideas. Genetic Algorithms (GAs) are one of several techniques in the family of Evolutionary Algorithms -algorithms that search for solutions to optimization problems by "evolving" better and better solutions. Genetic Algorithms have been applied in science, engineering, business and social sciences. This book consists of 16 chapters organized into five sections. The first section deals with some applications in automatic control, the second section contains several applications in scheduling of resources, and the third section introduces some applications in electrical and electronics engineering. The next section illustrates some examples of character recognition and multi-criteria classification, and the last one deals with trading systems. These evolutionary techniques may be useful to engineers and scientists in various fields of specialization, who need some optimization techniques in their work and who may be using Genetic Algorithms in their applications for the first time. These applications may be useful to many other people who are getting familiar with the subject of Genetic Algorithms.