Generating Moving Average Trading Rules on the Oil Futures Market with Genetic Algorithms

1 School of Humanities and Economic Management, China University of Geosciences, Beijing 100083, China 2 Key Laboratory of Carrying Capacity Assessment for Resource and Environment, Ministry of Land and Resources, Beijing 100083, China 3 Lab of Resources and Environmental Management, China University of Geosciences, Beijing 100083, China 4 Institute of China’s Economic Reform and Development, Renmin University of China, Beijing 100872, China


Introduction
Energy is vital for economic development.Household activities, industrial production, and infrastructure investments all consume energy directly or indirectly, no matter in developing or developed countries [1].Issues pertaining to energy trade [2], energy efficiency [3], energy policy [4][5][6], energy consumption [7], and energy finance [8] have received more importance in recent years.Crude oil futures market is a crucial part of energy finance within the scope of the global energy market.Traders and researchers employ technical analysis tools to identify gainful trading rules in financial markets.Accordingly, moving average indicators are commonly used in technical analysis to actualize greater returns.This paper attempts to answer whether in real life an investor can use moving average technical trading rules to obtain excess returns through searching for profitable moving average trading rules with genetic algorithms in the crude oil futures market.
Genetic algorithms are widely used in social sciences [9,10], especially in certain complex issues where it is difficult to conduct precise calculations.It is a trend to apply physical or mathematical methods in energy and resource economics [11][12][13][14][15][16].Researchers have applied genetic algorithms to the prediction of coal production-environmental pollution [17], the internal selection and market selection behavior in the market [18], the crude oil demand forecast [19], the minimization of fuel costs and gaseous emissions of electric power generation [20], and the Forex trading system [21].With respect to the financial technical analysis issues, scholars use genetic algorithms to search best trading rules and profitable technical indicators when making investment decisions [22][23][24][25].Genetic algorithms are combined with other tools such as the agent-based model [26], fuzzy math theory [27], and neural networks [28].There are also some studies that have used genetic algorithms to forecast the price trends in the financial market [29,30] or the exchange rate of the foreign exchange market [31].As there are a vast number of technical trading rules and technical indicators available in the crude oil futures market, it is impractical to use ergodic calculations or certain other accurate calculation methods.Therefore, using genetic algorithms is a feasible way to resolve this issue.
Moving average indicators have been widely used in studies of stocks and futures markets [32][33][34][35][36][37].Two moving averages of different lengths are compared to forecast the price trends in different markets.Short moving averages are more sensitive to price changes than long ones.If a short moving average price is higher than a long period moving average price, traders will believe the price will rise and take long positions.When the short moving average price falls and crosses with the long one, opposite trading activities will be taken [38].Allen and Karjalainen (AK) [39] used genetic algorithms to identify technical trading rules in stock markets with daily prices of the S&P 500.The moving average price was used as one of the many indicators of the technical rules.Other indicators, such as the mean value and maximum value, are also used when making investment decisions.Wang [40] conducted similar research on spot and futures markets using genetic programing, while How [41] applied AK's method to different cap stocks to determine the relevance of size.William, comparing different technical rules and artificial neural network (ANN) rules regarding oil futures market, determined that the ANN is a good tool, thus casting doubt on the efficiency of the oil market [38].All of these studies combine moving average indicators with other indicators to generate trading rules.However, in this paper, we utilize moving averages to generate trading rules, which may be a simple and efficient approach.
The performance of a moving average trading rule is affected significantly by the period lengths [42].Therefore, finding optimal lengths of the two periods above is a central issue in technical analysis literature.A variety of lengths have been tried in existing research projects [43][44][45][46][47][48].In the existing research, most of moving average rules use fixed moving average period lengths and single moving average calculation method.However, it is better to use variable lengths for different investment periods [49,50] and there are different types of moving average calculation method that can be used in technical analysis.
In this paper, considering that the optimal length of the moving average periods and the best calculation method may vary from one occasion to another we use genetic algorithms to determine the suitable length of the moving average period and the appropriate method.Six moving average calculation methods are considered in this paper and genetic algorithms can help us find out the best method and appropriate period lengths for different circumstances.Accordingly, we are able to present the most suitable moving average trading rules for traders in the crude oil futures market.

Data and Method
2.1.Data.We use the daily prices of the crude oil future contract 1 for the period 1983 to 2013 from the New York Mercantile Exchange (Data Source: http://www.eia.gov/dnav/pet/pet pri fut s1 d.htm).We select 20 groups of sample data, each containing 1000 daily prices.In the 1000 daily prices, a 500-day price series is used to train trading rules in every generation.The following 200 prices are used to select the best generated trading rule from all generations, and the last 300 daily prices are used to determine whether the generated rule can acquire excess returns.The first group begins in 1985, the last group ends in 2013, and each 1000day price series with a step of 300 is selected.We must also include 500 more daily prices before each sample series to calculate the moving prices for the sample period.Thus, every independent experiment requires a 1500-day price series.The data we use are presented in Figure 1.

Method.
Moving average trading rules facilitate decision-making for traders by comparing two moving averages of different periods.In this way, traders can predict the price trend by analyzing the volatility of the moving average prices.There are six moving average indictors usually used in technical analysis: simple moving average (SMA), weighted moving average (WMA), exponential moving average (EMA), adaptive moving average (AMA), typical price moving average (TPMA), and triangular moving average (TMA).The calculation methods of moving average indicators are presented in Table 1.
To use a moving average trading rule in the oil futures market, at least three parameters must be set to establish a trading strategy.These parameters include the lengths of two moving average periods and the choice of the moving average method from the above six types.Other researchers have used different lengths of sample periods in their studies.In this paper, we use genetic algorithms to determine appropriate lengths of the moving average period.According to existing literature, the long period is generally between 20 and 200 days (very few studies use periods longer than 200 days) [38,39], and the short period is generally no longer than 60 days.
If the long average price is lower than the short average price, a trader will take a long position.It follows that in opposite situations, opposite strategies will be adopted.Noting the price volatility in the futures market, taking a long position when the short average price exceeds the long average price by at least one standard deviation in the short period may be a good rule.Conversely, taking a short position may also be a good rule.Therefore, we designed the two rules in our initial trading rules.The detailed calculation methods of the six moving averages are presented in Figure 2.
A 17-binary string is used to represent a trading rule in which a seven-binary substring represents (M-N) ( is the long period length and  is the short period length); a six-binary substring is  ( belongs to the range of 1 to 64); a three-binary substring represents the calculation method of average prices.In this paper, the range of  to  is 5 to 132.The last binary determines whether to
AMA change trading strategies only when there is more than one standard deviation difference between two moving average prices.The structure of trading rules is presented in Figure 2.
The fitness of a trading rule is calculated according to the profit it can make in the crude oil futures market.To compare generated trading rules with the BH (buy-and-hold, taking the long position throughout the period) strategy, the profit of a generated rule is the excess return rate that exceeds the BH strategy.The calculation method of the return rate references AK's method.The difference is that we allow a trader to hold a position for a long time, and we do not calculate the return every day.Consider Ra is the excess return rate of a long position strategy, that is, the sum of the return of the long position and short position.Rf is the risk free return when out of market, and Rbh is the return rate of the BH strategy in the sample period.Rm is the margin ratio of the futures market.The parameter  denotes the one-way transaction cost rate. in and  out represent the opening price and closing price of a position (long or short), respectively. begin is the price of the first day in a whole period and  end is the price of the last day.As we ignore the amount of change in the everyday margin and the deadline of the contract, a trader can maintain his strategy by taking new positions when a contract nears its closing date.The fitness value is a number between 0 and 2 calculated through nonlinear conversion according to Ra.The fitness value calculation, selection, crossover, and mutation of individuals are implemented using the GA toolbox of Sheffield in the Matlab platform.In every generation, to avoid the overfitting of training data, the best trading rule in every generation will be tested in a selection sample period (the 200-day price series).Only when the fitness value is higher than the best value in the last generation or when the two values are almost the same ( last − now < 0.05) can the trading rule be marked as the best thus far.In every generation, 90 percent of the population will be selected to form a new generation, while the other 10 percent will be randomly generated.Accordingly, the evolution of individuals using genetic algorithms in a single independent experiment can be summarized as follows.
Step 1 (initialize population).Randomly create an initial population of 20 moving average trading rules.
Step 2 (evaluate individuals).The fitness of every individual is calculated in the evaluation step.The program calculates the moving average prices in two different scales during the training period using the auxiliary data and determines the positions on each trading day.The excess return rate of every individual is then calculated.Finally, the fitness value of each individual is calculated according to the excess return rate.
Step 3 (remember the best trading rule).Select the rule with the highest fitness value and evaluate it for the selection period to obtain its return rate.If it is better than or not inferior to the current best rule, it will be marked as the best trading rule.If its return rate is lower than or less than 0.05 higher than the current rate, we retain the current rule as the best one.
Step 4 (generate new population).Selecting 18 individuals according to their fitness values, the same individual could be selected more than once.Therefore, randomly create 2 additional trading rules.With a probability of 0.7, perform a recombination operation to generate a new population.Accordingly, all the recombination rules will be mutated with a probability of 0.05.
Step 5.Return to Step 2 and repeat 50 times.
Step 6 (test the best trading rule).Test the best trading rule as identified by the above program.This will generate the return rate and indicate whether genetic algorithms can help traders actualize excess returns during this sample period.

Results
Because, in this paper, we have not considered the amount of assets, we assume the margin ratio to be 0.05.In fact, as the parameter has no significant effect on our experiment results, the return rate is increased twenty times.With 20 trials in each period, 420 independent experiments are conducted to determine useful moving average trading rules in the crude oil futures market.The prices we used for the 21 periods are shown in Figure 3.
Based on previous studies [39,40,51] and on the decision to select an intermediate value for this study, the transaction cost rate is set at 0.1% for the 420 experiments.The risk free return rate is 2%, which is based primarily on the short-term treasury bond rate [41].
Of the 420 trials, 226 earn profits.With an average return rate of 1.446, it is concluded that genetic algorithms can facilitate traders to obtain returns in the crude oil futures  market.However, moving average trading rules identified by genetic algorithms do not result in excess returns as there are only 8 periods in which generated trading rules resulted in traders receiving excess returns.Given that the price of crude oil futures increased many times during the sample period, we further contend that genetic algorithms are helpful in investments.
For a better understanding, we divide the 21 periods into 4 categories according to the results (see the last column of Table 2).
Category 1 (periods 2, 3, and 9).In these periods, generated trading rules not only help traders obtain returns but also help them to realize excess returns.Generated trading rules generate more profits than the BH strategy in periods 3 and 9.In period 2, the BH strategy loses money, while the generated trading rules, as determined by the genetic algorithms, result in profits.Thus, the generated trading rules are far superior to the BH strategy in this period.A common feature of these three periods in Category 1 is that the crude oil prices fell during the test period and experienced significant fluctuations.
Category 2 (periods 5, 8, 12, 16, and 18).Generated moving average trading rules fail to generate profits during these five periods.Even so, the generated rules performed better than the BH strategy, as they significantly reduced losses.In these periods, prices declined smoothly, experiencing some small fluctuations during the process.
Category 3 (periods 1, 6, 7, 10, 11, 14, 15, and 17).In these eight sample data periods, genetic algorithms help traders to identify suitable moving average trading rules.However, the traders failed to obtain excess returns.While prices steadily increase in these periods, there are also some minor fluctuations, which cause the genetic algorithms to be inferior to the BH strategy in these periods.
Our genetic trading rules yield more severe losses.The BH strategy is considered superior to the generated trading rules in the other four periods as the BH strategy yields some returns.While there are no significant changes in the prices level in these periods, the prices are in volatile states throughout the five periods.Slight price changes with no apparent trends render the generated trading rules helpless in predicting price changes and providing returns.
We use genetic algorithms to search good moving average trading rules for traders in the crude oil market.Table 3, which shows the average number of  and  for every period, indicates that the value of long period () has a close relationship with the volatility of the prices in the sample period.A large  is set in periods with significant fluctuations and a small  is selected for periods in which price is relatively stable.
The distribution of  is shown in Figure 4.The value of Probability is very small and  does not follow normal distribution.The figure presents a typical fat tail characteristic with a kurtosis of 2.36.Compared with normal distribution, there are more values located in the tails of the distribution in our results.Only in half of the 420 experiments,  is between 70 days and 130 days.The values are decentralized and we believe it is more scientific to choose the best lengths of the two periods using a training process that we have used in this paper in actual investment.
Among the six moving average calculation methods, AMA and TMA are used more often than the other four (see Table 4), as more than half of the generated moving average trading rules use AMA or TMA.A small number of generated trading rules use WMA and EMA, while TPMA and SMA, which are easy to calculate, are frequently used in some periods, such as periods 1, 2, 3, 12, 19, and 21.
The selection of calculation method is associated with the price trends and volatility.Figure 5 shows that TPMA is used 31 times in the 60 independent experiments in periods 2, 3, and 9 (Category 1).Different from the overall proportion, TPMA is the most popular calculation method when price falls during the period and experienced significant fluctuations.AMA is the most popular method in the other three categories.EMA is never used in Categories 1 and 4.However, it takes a 24% proportion in Category 2, more than TMA, SMA, TPMA, and WMA.The proportions of TMA and SMA have no significant differences in different categories.In category 4, prices change with no apparent trends.No one method has obvious advantage over the others.
The results of 20 experiments in the same period indicate high consistency on the value sd (Table 5).When prices fluctuate, such as in periods 1, 2, 7, 8, 13, 19, and 20, then not opening positions until one average price exceeds another by at least one standard deviation is the best option.When the price is relatively stable, an investment decision should be made immediately as long as the two moving averages cross.

Discussion
This paper attempts to generate moving average trading rules in the oil futures market using genetic algorithms.Different from other studies, we use only moving averages as technical indicators to identify useful moving average trading rules, without any other complex technical analysis tools or indicators.Moving average trading rules are easy for traders to operate, and they are straightforward regardless of the situation.To identify the best trading rules in the crude oil futures market, we use genetic algorithms to select all the parameters in the moving average trading rules dynamically rather than doing so in a fixed manner.According to our genetic calculations, using genetic algorithms to find out the best lengths of the two moving average periods is advocated because the generated lengths differ from each other in different price trends.Static moving average trading rules with fixed period lengths cannot adapt to complex fluctuations of price in different periods.A training process, however, which takes dynamic features of price fluctuations into consideration, can help traders find out the optimal lengths of the two moving periods of a trading rule.
Among the six moving average methods, the AMA and TMA are the most popular among the generated trading rules as these two methods have the ability to adapt to the price trends.The AMA can change the weights of the current price according to the volatility in the last several days.As the TMA is the average of the SMA, it more accurately reflects the price level.However, the selection of best moving average calculation method is affected by price trends.Traders can choose methods more scientifically according to the price trends and fluctuations.Based on our experiment results, TPMA is an optimal choice when price experiences a decline process with significant fluctuations, and generating moving average trading rules are outstanding compared with BH strategy in these occasions.Although EMA takes a very small proportion in the total 420 experiments, it is also an applicable method other than AMA when price falls smoothly.
For the periods in which the price volatility is apparent, decisions will not be made until the difference between the two averages exceeds the standard deviation of the short sample prices, thereby reducing the transaction risk.However, this method is not suitable for a period in which the price is relatively stable.In these situations, hesitation may sometimes cause traders to miss possible profit opportunities.
As a whole, generated moving average trading rules can help traders make profits in the long term.However, genetic algorithms cannot guarantee access to additional revenue in every period as they are only useful in acquiring excess returns in special situations.The generated moving average trading rules demonstrate outstanding performance when the crude oil futures price falls with significant fluctuations.The BH strategy will lose on these occasions, while the generated trading rule can help traders foresee a decline in price and reduce losses.Our trading rules also yield positive returns during the fluctuations by the timely changing of positions.
When the price falls smoothly with few fluctuations in the process, generated trading rules can yield excess returns compared to the BH strategy.Although genetic algorithms cannot help traders receive positive returns during these periods, the algorithms can help traders reduce loss by changing positions with the change of price trends.When the price is stable or rising smoothly, the generated rules may generate returns.However, they cannot generate more returns than the BH strategy.Limited returns cannot afford the transaction costs.When the price falls, the generated rules may be superior to the BH strategy.Genetic algorithms can also help traders make profits in the process of price increases with small fluctuations.In these periods, the BH strategy is better than generated trading rules because the transactions in the process generate transaction costs and may miss some profit opportunities.Generated moving average trading rules  have poor performance if there are no notable trends in the price change.In these periods, moving average indicators cannot find profit opportunities because the volatility is too small.The trends of price changes are delayed by the moving average method.Therefore, when a decision is made, the price trend must also change, and as a result, there is no doubt that the trader will experience deficits.
Using genetic algorithms, moving average trading rules do help traders to gain returns in the actual futures market.
We also identified the best lengths for the two periods with respect to moving average rules and recommend the moving average calculation method for the crude oil futures market.Technical trading rules with only moving average indicators generated by genetic algorithms demonstrate no sufficient advantages compared to the BH strategy because the overall price increased during the 30-year period.Nevertheless, generated moving trading rules are beneficial for traders under certain circumstances, especially when there are significant changes in prices.
In this paper, we search best trading rules according to the return rate of each one without regard to asset conditions and open interest, which proves to be the greatest limitation of the study.To improve the accuracy of the results, a simulation with actual assets is recommended.Accordingly, we will undertake this endeavor in a subsequent research.

Concluding Remarks
We conclude that the genetic algorithms identify better technical rules that allow traders to actualize profits from their investments.While we have no evidence to demonstrate that generated trading rules result in greater returns than does the BH strategy, our conclusion is consistent with the efficient market hypothesis.While generated trading rules facilitate traders in realizing excess returns with respect to their investing activities under specific circumstances, they cannot, at least by using moving average trading rules, ensure more long-term excess returns than the BH strategy.With respect to the selection of two periods, finding out optimal lengths using genetic algorithms is helpful for making more profits.Of the six moving average indicators, AMA and TMA are the most popular moving average calculation methods for the crude oil futures market in total, while TPMA is an

Table 1 :
Details of the six moving average indicators.

Table 2 :
Results of experiment.
is the number of generated trading rules receiving positive excess returns compared with the BH strategy in the 20 trials. is the number of generated trading rules acquiring returns in the test periods.Rbh is the return rate of the BH strategy. is the average return rate of the 20 trials in each period. is the average excess return rate of 20 trials in each period.

Table 3 :
The average value of  and  in each period.

Table 4 :
Calculation methods of moving average price in each period.

Table 5 :
Numbers of trading rules in which sd = 1.