[IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) -...

8
A Smart Agent to Trade and Predict Foreign Exchange Market Mohamed Taher Alrefaie, Alaa-Aldine Hamouda Systems and Computer Engineering Department Al-Azhar University Cairo, Egypt [email protected] , [email protected] Rabie Ramadan Computer Engineering Department Cairo University Gizah, Egypt [email protected] AbstractForeign Exchange market is a worldwide market to exchange currencies with 3.98 trillion US dollars daily turnover. With such a massive turnover, probability of profit is very high; however, trading in such massive market needs high knowledge, skills and full commitment in order to achieve high profit. The purpose of this work is to design a smart agent that 1) acquire Foreign Exchange market prices, 2) pre-processes it, 3) predicts future trend using Genetic Programming approach and Adaptive Neuro-fuzzy Inference System and 4) makes a buy/sell decision to maximize profitability with no human supervision. KeywordsAgent; ANFI; Genetic Algorithm; NSGA-II; Prediction; Forex. I. INTRODUCTION Foreign Exchange market, known as Forex, is the market in which participants are able to buy, sell, exchange and speculate on currencies. Foreign exchange markets are made up of banks, commercial companies, central banks, investment management firms, hedge funds, and retail forex brokers and investors. The forex market is considered to be the largest financial market in the world [1]. In addition, it’s not located in a specific city or country, but comprised of all the locations where a currency such as the Euro, US Dollar, and Egyptian Pound are exchanged for other currencies. All users interact with the market through the internet. [2] Small investors and traders with balance as low as $100 can still trade in such market through broker companies that help them with capital and software system to enter buy or sell orders and manage their money. This happens through margin and leverage systems. Leverage means borrowing amount of money from the broker company to maintain a high capital and subsequently a high profit at the end. For example, a trader with $100 could use a leverage with 1:100 which means he can trade with 100 x 100 = $10,000 to trade with. However, margin-based leverage does not necessarily affect one's risks. Thus in Forex, even small traders with only $100 capital can have $10,000 as an initial capital to start trading by borrowing such difference from their brokers. [3] Forex is modelled as a nonlinear and a chaotic time series [4]. Thus predicting such system isn’t easy. Most of the research published in the past few years use feed forward and recurrent Artificial Neural Networks due to its capability to map any nonlinear functions [5]. For instance, [6] used Support Vector Machine to predict the daily trend of the Forex market. ANFIS model is also used to predict the trend of the market [7]. As a conclusion, predicting Forex could be done through two methods, a regression method and a classification method. Regression method means prediction of the price of time t+1 using available information at time t. (1) Where is the price at the next timeframe. Function is the regression model with input to preprocessed with function that makes the input easier to be predicted by the regression model. The second method is done through classification. By using all available data at time t, a classifier could predict if the price trend would go up or down at time t+1. This helps knowing what decision to make at current time. For instance, if the classifier says price would go up, then a buy trade should be done. This model is much easier to be built and used than the regression model. The main objective of this study is to build a software agent capable of connecting to a broker server, retrieving real- time prices of Forex market and performing an action (buy or sell trades) on the market through the broker. Then it pre- processes prices and extracts features using mathematical and statistical functions and technical indicators. Technical Indicator result of mathematical calculations is based on indications of price and/or volume. The values obtained are used to forecast probable price changes where there are many technical indicators already developed. The agent then tries to answer two questions. Which are 1) Is it the right time to start a trade? And 2) How much is the profit in the next three hours if the agent started a trade now and how much it might lose until it reaches that profit? Sometimes market’s prices are highly chaotic, fluctuating rapidly or nearly constant. For sure, the agent shouldn’t start any trades at such time period to avoid probability of high loss or low prediction performance. If the answer is no, the agent will wait until the market status changes. If the answer is yes, the agent tries to find an answer to the second question. This is 141 978-1-4673-5851-4/13/$31.00 c 2013 IEEE

Transcript of [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) -...

Page 1: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

A Smart Agent to Trade and Predict Foreign Exchange Market

Mohamed Taher Alrefaie, Alaa-Aldine Hamouda

Systems and Computer Engineering Department Al-Azhar University

Cairo, Egypt [email protected] , [email protected]

Rabie Ramadan Computer Engineering Department

Cairo University Gizah, Egypt

[email protected]

Abstract—Foreign Exchange market is a worldwide market to exchange currencies with 3.98 trillion US dollars daily turnover. With such a massive turnover, probability of profit is very high; however, trading in such massive market needs high knowledge, skills and full commitment in order to achieve high profit. The purpose of this work is to design a smart agent that 1) acquire Foreign Exchange market prices, 2) pre-processes it, 3) predicts future trend using Genetic Programming approach and Adaptive Neuro-fuzzy Inference System and 4) makes a buy/sell decision to maximize profitability with no human supervision.

Keywords—Agent; ANFI; Genetic Algorithm; NSGA-II; Prediction; Forex.

I. INTRODUCTION Foreign Exchange market, known as Forex, is the market

in which participants are able to buy, sell, exchange and speculate on currencies. Foreign exchange markets are made up of banks, commercial companies, central banks, investment management firms, hedge funds, and retail forex brokers and investors. The forex market is considered to be the largest financial market in the world [1]. In addition, it’s not located in a specific city or country, but comprised of all the locations where a currency such as the Euro, US Dollar, and Egyptian Pound are exchanged for other currencies. All users interact with the market through the internet. [2]

Small investors and traders with balance as low as $100 can still trade in such market through broker companies that help them with capital and software system to enter buy or sell orders and manage their money. This happens through margin and leverage systems. Leverage means borrowing amount of money from the broker company to maintain a high capital and subsequently a high profit at the end. For example, a trader with $100 could use a leverage with 1:100 which means he can trade with 100 x 100 = $10,000 to trade with. However, margin-based leverage does not necessarily affect one's risks. Thus in Forex, even small traders with only $100 capital can have $10,000 as an initial capital to start trading by borrowing such difference from their brokers. [3]

Forex is modelled as a nonlinear and a chaotic time series [4]. Thus predicting such system isn’t easy. Most of the

research published in the past few years use feed forward and recurrent Artificial Neural Networks due to its capability to map any nonlinear functions [5]. For instance, [6] used Support Vector Machine to predict the daily trend of the Forex market. ANFIS model is also used to predict the trend of the market [7].

As a conclusion, predicting Forex could be done through two methods, a regression method and a classification method. Regression method means prediction of the price of time t+1 using available information at time t.

(1) Where is the price at the next timeframe. Function is the regression model with input to preprocessed with function that makes the input easier to be predicted by the regression model.

The second method is done through classification. By using all available data at time t, a classifier could predict if the price trend would go up or down at time t+1. This helps knowing what decision to make at current time. For instance, if the classifier says price would go up, then a buy trade should be done. This model is much easier to be built and used than the regression model.

The main objective of this study is to build a software agent capable of connecting to a broker server, retrieving real-time prices of Forex market and performing an action (buy or sell trades) on the market through the broker. Then it pre-processes prices and extracts features using mathematical and statistical functions and technical indicators. Technical Indicator result of mathematical calculations is based on indications of price and/or volume. The values obtained are used to forecast probable price changes where there are many technical indicators already developed.

The agent then tries to answer two questions. Which are 1) Is it the right time to start a trade? And 2) How much is the profit in the next three hours if the agent started a trade now and how much it might lose until it reaches that profit? Sometimes market’s prices are highly chaotic, fluctuating rapidly or nearly constant. For sure, the agent shouldn’t start any trades at such time period to avoid probability of high loss or low prediction performance. If the answer is no, the agent will wait until the market status changes. If the answer is yes, the agent tries to find an answer to the second question. This is

141978-1-4673-5851-4/13/$31.00 c©2013 IEEE

Page 2: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

done through a collection of rules generatealgorithm.

The agent couldn’t start a trade with calculprofit is expected within the next three housecond question. Furthermore, the market tendand down, so the agent needs to know how mprice go down until it rebounds and reaches This is very important because if the pricemuch, the agent could lose most of its gaineoriginal balance as well. This is done usinInference Systems trained by ANFIS algorithm

After answering these two questions, the astart a trade and knows how much the agent probability of loss in such trade should. Thmade through the Decision Making Process satisfy its main goal of maximizing the profitab

The paper is organized as follows: in thsome of the most related research is expladescribes the design of the proposed agent, inpprediction technique; section 4 has all results c5 discusses results and reasons behind selectioand decisions made regarding the design; and that concludes all work and results in this study

1. RELATED WORK Reference [8] has shown two learning strat

Genetic (Programming) Algorithm (GA) anlearning, and omethods based decision problemheuristic techniqureported results,generate significanout-of-sample transaction costs GA approach seenonzero transactaddition, it was

also state that when in-sample learning is not cthere is the risk of over-fitting.

Reference [9] used hybrid neural networknoisy time series prediction, especially for smhigh noise data. By using inference and extrneural network (RNN) models, it’s seems that for the detection of temporal patterns compamulti-layer perceptron neural networks. Tprovided insight into both the real world predictor.

Reference [10] used a fuzzy inference methtime series data to predict fluctuations of forates. Contents of the chaos theory were uinference method, which is the result of the prfed back repeatedly into the next one. It afunctions to express the dynamics of determinicertain steps any specific predicted value ofcould be obtained. It was found that the fundais useful in predicting long term trends butpredicting short-term movements of exchan

Fig. 1. Japanese candle.

ed by NSGA-II

lating how much urs which is the ds to fluctuate up much would the expected profit.

e went down so ed profit and its

ng twelve Fuzzy m.

agent is ready to should win and

en a decision is of the agent to

bility.

he next section, ained; section 3 put handling and collected; section on of algorithms finally section 6 y.

tegies based on a nd reinforcement on two simple

on a Markov m and a simple

ues. Based on all methods nt in-sample and profit when were zero. The

ems superior for tion costs. In stated that they constrained, then

k algorithms for mall samples and raction, recurrent they are suitable ared to standard The paper also system and the

hod on the fuzzy oreign exchange used in a fuzzy revious iterations also used fuzzy istic chaos. After f the data vector amental analysis t of little use in nge rates. Even

though technical analysis can be term period changes, there is a laThe author has examined severconsidered the behaviour of time sfuzzy inference technique to prefluctuations.

Reference [11] built an autoagent with the ability to trade in requiring human supervision for thewas done by multiple techniques; Expert System. In 14 months, it waby trading USD/JPY pairs and $10deposit.

A main disadvantage of most provide a consistent method to prethat could be used to generate profiall most papers used MSE to evaluprediction algorithm which might nthe technique is if it was applied Forex market. Furthermore, all ttechnique to build which causes inthe trained technique is outdated or changes.

In this paper, we developed astable algorithm consisting of twoForex market in a way that could Evaluating the performance of theprofitability and flexibility to marke

II. PROPOSEDIn this section, the structure of t

includes explaining the two diffpredict the Forex market future priwill be explained how the system cimplemented and how they interact

Fig. 2. Design of the agent.

A. Data Acquisition Data is collected from MetaQuo

MetaTrader, the most popular trForex which is used by over 450banks worldwide.Data collected inclose prices on the 30 minutes tirapidly fluctuating every second onmethod used to minimize that cal

useful in predicting short-ack of consistent accuracy. ral forecasting techniques, series data and advanced a

edict future exchange rate

nomous hybrid intelligent the Forex Market without

e USD/JPY pair. Prediction one of them is Rule-Based

as able to obtain 60% profit 00,000 dollars as an initial

techniques is the lack to edict the changes in a way it in the market. In addition, uate the performance of the not indicate how profitable in a real trading agent in

techniques depend on one nstability to the algorithm if

doesn’t adapt to the market

a smart agent with a new o techniques to predict the be used to generate profit.

e algorithm is based on its et fluctuations.

D AGENT the agent is explained. This ferent approaches used to ices. Later in the section, it components of the agent are t from sensing to actuating.

otes company, the owner of rading platform in trading brokerage companies and cludes open, high, low and meframe. Since prices are n Forex, there is a standard led the Japanese candle as

142 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES)

Page 3: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

illustrated in figure 1. The Japanese candle sof information every specific timeframe whichhighest price and the price at the beginning antimeframe. For example, a Japanese candtimeframe has: 1. the lowest price that ever pair during that day, 2. the highest price, 3. beginning of the day and 4. and the price at the

B. Structure of the Software Agent The software agent is an autonomous so

that carries out tasks on behalf of users. Thisuser has no obligation of any kind to tell the awhich means that the agent’s behaviour is fulits knowledge base, perception to its environmgoal.

In our case, the agent’s environment is thewhich is fully observable, stochastic, sequediscrete and single-agent-operating at the same

The agent’s main operation is sensing andagent, in our case, senses the price changes oThe actions of the agent are open a buy/sell buy/sell trades and close a buy/sell trades.

The agent structure is illustrated in figure 2MetaTrader API, Feature Selection Module, PDecision Making process and a database.

This API provides a high level communthe local agent and the remote server of theagent can retrieve all price fluctuations at real-or sell operation, check for profit and current b

The MetaTrader API is broker-independethe user can change the broker company at agent can still operate with no problem or anbusiness logic.

The main objective of the API is recfluctuations sent by the broker server, wrap thehistorical rates needed and send them to FModule.

The Feature Selection Module is responormalization as well as data preparation andand then passes them to all Prediction Moduleinclude three categories of function to pre-ptechnical indicators, mathematical functions afunctions. Technical indicators consist ofunctions that are designed by forex experts to

Fig. 3. How a rule is generated using NSGA-II.

Current rates and historical currency

rates

Data Pproces

aves four pieces h is lowest price, nd the end of the dle on a daily happened of the the price at the

e end of the day.

oftware program s means that the agent what to do lly dependent on

ment and its main

e broker’s server ential, dynamic, e time.

d actuating. The nce it happened. trades, modify a

2 and consists of Prediction Tools,

nication between e broker. So, the -time, send a buy balance.

ent which means anytime and the

ny changes to its

eiving all price em with required eature Selection

onsible for data d pre-processing es. It is design to process the data, and mathematical of 62 financial o classify certain

patterns, collect financial or econfrom the historical prices of thefunctions include different ones sucstatistical functions have many fudeviation, variance, etc.

Prediction Tools -as the name inpredicting the future price or the fuis passed to the Decision Making ph

In our work, two different prefirst one uses 12 trained Fuzzy Inhigh and low prices of the next sitime. The second one is a trading ruusing Non-dominated Sorting Gene

A decision is finally made in whether to buy or sell. The input the predicted information, saveenvironment and current investmen

All decisions are written to thefile to back-trace the system in casemaintenance.

Fig. 4. Design of the rule in GP Individual.

After that, the decision is formed iMqlRequest and sent to the MetaTrMqlRequest is an object in Metadetails of the operation that’s sent to execute the operation. This mea

nand

and

Intersetcs

>

or

not

==

Pre-ssing

Non-dominated Sorting Genetic Algorithm

Multi-objective function

Set of nodes

nomical-related information e pairs. The mathematical ch as sin, cos, log, etc. The

functions such as standard

ndicates- are responsible for uture trend. Such prediction hase.

ediction tools are used: the nference Systems to predict ix timeframes after current ule generated and optimized etic Algorithm II.

Decision Making Process to this decision function is d information about the

nt status.

e database along with a log e of any failure, statistics or

into a standard MetaTrader rader API. The MetaTrader aTrader API including all to the servers of the broker ans that the agent asks the

low-3

open-1

TA-SAR

TA-CCI

>=TA-Avg

TA-MAXclose-1

minclose-0

open-1

2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) 143

Page 4: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

broker to open or close an operation at the cFinally, MqlResult is immediately sent back Making Phase with operation success or failucurrent system status and write that to the log.

All data used are collected from MMetaTrader platform. The training data star2009 to December 2010. Testing data is from July 2012.

C. Prediction using Genetic Programming In this prediction model, genetic program

generate a trading rule that gets the input throindicators, 2) current and historical pricefunctions and its output is either true of false.price of the pair will go high for at least 15 pgives false if either the price would go lowwon’t exceed 15 pips.

The trading rule is illustrated in figure 4. output of different functions (input of thehistorical rates of the pair) and raw data (realtime and past history) at its leaves. Then, thefunction is compared to its neighbouring leaf uFalse value gets to the top of the tree whicoutput. This output is interpreted as a predictmarket fluctuations.

genruleff

pretreprithaavalggenuse

searching for near-optimal solution since threally huge.

The genetic programming algorithm used NSGA-II is the Non-dominated Sorting Geversion II. It’s different from the standard GAsorts all individuals of each generation accorobjective function and uses Pareto principlobjective dominates another one; this teoverfitting in training phases. [12]

In the first step of NSGA-II, a populationgroup of rules is generated randomly. Each r

TABLE I TRUTH TABLE OF GPINDIVIDUAL

Rule 1 (buy)

Rule 2 (sell)

Output

False False Hold

False True Sell

True False Buy

True True Hold

Fig. 5. Design of the GPIndividual

current moment. to the Decision

ure to update its

MetaQuotes on rts from January

January 2011 to

mming is used to ough 1) technical es 3) statistical . True means the ips difference. It

w or go high but

It compares the ese functions is l price of current e output of each until one True or ch is the desired tion to the future

In order to nerate a trading le that could fectively and

successfully edict the future end of the market ices out of over an 62 nodes ailable, genetic gorithm in neral is only eful tool for

he state space is

is the NSGA-II. enetic Algorithm A algorithm as it rding to a multi-le to ensure no ends to reduce

n consisting of a rule is generated

from a set of nodes while satisfyinode. In this study, two different seone returns a double value and thefalse value. The first set with the output includes raw prices, histofunctions (Ex. Standard deviationindicators that returns a double comparison operators that take douBoolean value as an output (Ex. Gfinally the third set includes Bodouble as input and returns doubleoutput.

As an example, in figure 3, NSGA-II, leaves of the tree has indicators, current prices (close0, current time period), historical pricthree time periods ago), technical and Reverse) and statistical functionodes return double value which using comparators like greater orBoolean value which is fed to logicand NAND. Finally, the output ofalse.

Each individual can give one oor hold. Buy means the price of thgoing up to the target profit desirethe price will fall in the next few -tiindividual is unsure of the future pr

Each individual has two rules asnumber 1 gives a buy signal whnumber 2 gives a sell signal when true at the same timeframe, they deoutput is hold signal. The truth table

Individuals generated at the firmulti-objective function and sortedensure that no objective dominated

The multi-objective function individual has two objectives. The f

Fig. 6. Design of the ANFIS model

ing the constraints of each ets of nodes exist. The first

e second one returns true of double value as input and

orical prices, all statistical n, Max, ..), and technical value. The second set is

uble as an input and returns Greater than, equals, ..) and oolean operators that gets e (Ex. AND, OR, ..) as an

a rule is generated using different sets of technical i.e., the close price at the

ces (low-3 i.e., lowest price indicators (SAR, i.e., Stop

ons (Average, max). These is compared to each other

r less. These nodes return cal operators like AND, OR f the rule is either true of

of three decisions; buy, sell he selected currency pair is d. Sell decision means that imeframes. Hold means the ice.

s illustrated in figure 5; rule henever it’s true and rule it’s true. If both rules give

eny each other and the final e is illustrated in table 1.

rst step are evaluated by a d using Pareto principle to the other.

used to evaluate each first objective is:

144 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES)

Page 5: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

And the second objective is:

The first objective tests the percentage

prediction in the training phase which optimithe individual. The second objective testssuccessful operations is higher than number operations. The second objective optimizes ththe agent. So, the best individual should be thehighest profitability and accuracy.

D. Prediction Using ANFIS ANFIS is an acronym for Adaptive Neuro

System. ANFIS is a fuzzy inference system the framework of adaptive networks. By learning procedure, it can construct an input-based on both human knowledge (in the formrules) and stipulated input-output data pairs. Inthe ANFIS architecture is employed to m

functions, identify nonlinear components on-system, and predict a chaotic time serieremarkable results [13]. Reference [14] explaiworks extensively.

As discussed earlier, GP model is used tbest entry points and the job of the ANFIS momuch profit is expected and how much loss coreaching that profit.

Design of the Prediction Model: Twelve mto predict high(t+1) to high(t+6) and low(t+High(t+1) means the high price at t+1 timeframcurrent time. With these twelve models, constructed for the time t+1 to time t+6. Thengoing to rise, a buy decision is made and the

Fig 7. Data Pre-processing different functions.

(2)

(3)

e of successful izes accuracy of s if number of

of unsuccessful he profitability of e one that has the

o-fuzzy Inference implemented in using a hybrid

-output mapping m of fuzzy if-then

n the simulation, model nonlinear

line in a control es, all yielding ined how ANFIS

to determine the del is to tell how

ould occur before

models are trained +1) to low(t+6). me where t is the two graphs are

n if the system is e expected profit

and stop loss is calculated. In figupredict the next six time frames usin

Fig. 8. An example of the output given by th

The algorithm that calculates thworks as follows:

Search for the point when the loss allowed. Assume the index is k

Search for the highest price frAssume the index is h.

Stop loss is calculated by thoccurred between time+1 to timcalculated by subtracting the priceprice.

For instance, in the figure 8, pris plotted. The stop loss is exceedeprice occurred before stop loss is at

E. Input Preprocessing The input used for the ANFIS m

from current price(t) to price(t-40).

Exponential Moving Average (Ecurve of the data to minimize equation of EMA is:

Where

Desired look-back is the N perminimized on.

III. RESUIn this section, results of the G

of ANFIS predictive model anfollowed by a discussion of all resu

A. Genetic Programming PredictAll data collected are done afte

individual in each generation.

As a reminder, the desired ogenerate an individual that’s cap

1.2335

1.234

1.2345

1.235

1.2355

1.236

1.2365

1.237

1 2 3 4

Pric

e

Time t

Prediction of AN

ure 6, six FISs are used to ng input from t to t-40.

he 12 FISs

he target profit and stop loss

price drops under the stop k.

rom time t+1 to t+k time.

he lowest price that ever me t+h and take profit is

at time t+h by the current

rediction of the twelve FISs ed at t+6 time. The highest t+4.

model is 41 input attributes

EMA) is used to smooth the chaotic fluctuations. The

(4)

riod that the data should be

ULTS GP predictive model, results nd the agent profitability lts.

ive Model er 50 generations with 2048

output of this model is to able of doing the highest

5 6 7 8

NFIS

high

low

2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) 145

Page 6: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

number operations (buy/sell) with the highest precision possible. This means, evaluation depends on two objectives mentioned earlier in equation (2) and (3) where take profit was set to 15 pips and stop loss to 10 pips.

All individuals are compared against these two objectives to select the most profitable one.

NSGA-II generated promising individuals with performance as shown in the figure 9.

Figure 5. Objective 1 against Objective 2 in generated individuals using NSGA-II.

As illustrated in figure 9, the relationship between accuracy (objective 1) and successful operations (objective 2) is plotted. This shows that some individuals are capable of doing 4000 predictions successfully with accuracy of 61% which means 39% of its operations are not successful.

As inferred in the last graph, the more the accuracy, the less the successful operations successful.

This leads to an optimization problem. In another word, which individual to use that could make the highest profit possible? The optimization problem is solved as follows; all individuals are ranked according to the following function:

Where SO is successful operations/trades and UO is the unsuccessful operations/trades.

(5)

The individual with the highest rank is the most profitable one.

B. ANFIS Predictive Model Twelve models were made to evaluate high and low prices

from t+1 timeframe to t+6 timeframe. The mean absolute error is illustrated in the following image.

Using the predictive model, it could open up 130 operations and achieved a profit of 1545 pips in the testing time period. All operations were closed at profitable status and none of them were unsuccessful.

In order to pick up the best options for input and ANFIS model options, several tests were made. Three input was used (price(t), price(t-1), price(t-2)) and normalized then fed to the network from 0.1 to 0.9 and the MSE of the model was 0.004.

Fig. 6. MSE in ANFIS models made.

The MSE of such model was 0.001534 with 3 inputs, 0.001533 with 5 inputs, 0.001529 with 11 inputs. All inputs are the prices from time t to t - no. of inputs. With 100 inputs, the MSE was 0.001067. As noticed, the MSE decreases when more historical data is fed each time. However, it doesn’t decrease enough. This could be due to the fact that raw data is noisy and has a bit of chaotic fluctuations that need to be removed.

To solve this issue, many moving average algorithms such as simple, exponential and weighted moving average. Exponential moving average, after several experiments we did on different moving average algorithms, has proved to be the best one that removes noise and still keep the basic fluctuations needed for predictions. Thus, it was used to smooth up the input.

Finding the near-optimal number of input to use is also a crucial point to the performance of the the FIS. However, since it’s computationally hard and time consuming to find the best number of inputs in the range between two inputs to 100 inputs, a binary search method was used to find the best number of inputs to feed the FIS with. This helped decrease number of trained FISs from 98 FISs to 8 FISs only. The lowest MSE possible happened to be 0.0000656 with 41 inputs (prices from time t to time t-40).

0

1000

2000

3000

4000

5000

0.61

6991

20.

6766

610.

7043

640.

7346

939

0.75

9633

540.

7871

5146

0.80

3532

0.82

2144

750.

8413

002

0.85

4421

80.

8709

583

0.88

2474

960.

8896

361

0.89

6973

250.

9272

0306

0.94

0078

560.

9670

3297

Succ

essf

ul p

redi

ctio

ns

Accuracy

0

0.0002

0.0004

0.0006

0.0008

0.001

0.0012

0.0014

t+1 t+2 t+3 t+4 t+5 t+6MSE of high price FISs MSE of low price FISs

TABLE II COMPARISON BETWEEN OUR AGENT AND (BARBOSA & BELO, 2006) AGENT.

Agent name Accuracy Drawdown Trades

Our agent 82.12% 409 329

Barbosa & Belo’s agent 54.41% 421 421

146 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES)

Page 7: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

C. The Software Agent The agent was tested on Strategy Tester, the worldwide

standard tester for the Forex strategies built on MetaTrader platform.

The agent was tested on 30 minutes (M30) timeframe using EURUSD pair from 1/7/2011 to 7/7/2012 and achieved approx. 120% profit with $1000 as an initial deposit; thus the total balance at the end of the year is approx. $2202. The relative drawdown was 409 which is 35.6% to the initial deposit. Drawdown means that after opening a trade, the price drops to specific percentage of the balance of the agent, however, it was raised in a bit and closed with profit.

For rough comparison, in table 2, results of our agent compared to [15] agent are compared. Although Barbosa and Belo’s agent trades USDJPY and our agent trades EURUSD on different timeframes, the following table shows a rough comparison between the prediction accuracy and how they turn it into profit.

IV. DISCUSSION

A. Agent The agent has performed very well. The final total net

profit in one year, compared to the initial deposit, is very promising. However, the relative drawdown is 35% which is very high and could lead to lose all balance in case the market fluctuated rapidly. Nevertheless, the system proved its stability on timeframes like 30 minutes but on timeframes like 1 minute or 5 minutes where the fluctuations are more sensed, it lost profit and in some testing cases -with low initial deposit- it lost all balance in few operations.

In order to solve this, more time should be spent in adjusting the trading strategy to keep control of the current loss in dollars and terminate all losing operations once they get below a pre-calculated maximum allowed loss value.

The agent has performed better than the agent built by [15]. Their agent has gained 60% of its initial deposit in 14 months. In comparison, our agent was able to obtain 102% of its own initial deposit in 12 months only. In addition, the drawdown was less than theirs which leads to better stability and robustness in trades.

B. ANFIS Model The ideal model to predict the future price using ANFIS

was found after doing many experiments to find out the best adjustments to its parameter. The raw input was used ranging from 3 to 100 inputs searching for the best number. The best input size was 41 inputs.

ANFIS performance was relatively low on raw (unadjusted) input. This is probably because the price fluctuations include some chaotic periodicity caused by the psychological behaviour of the trader or by the news or rumours.

By using exponential moving average, the curve is smoothed and some periodic random or chaotic fluctuations were removed and the main periodicity of the input was left to give ANFIS the chance to predict it.

Another thing to mention, ANFIS has proved to be the better in predicting chaotic time series compared to ANN.

C. GP Model GP model used NSGA-II algorithm to generate the best

rules using multi-objective evaluation function.

Before using NSGA-II, the basic Koza algorithm was used and unfortunately, all rules after the 5th generation had really good results on training data, however, it failed to make the same performance in testing data which is overfitting. And this is the dominance problem, once an over fitted individual appears in a generation, it dominates all other average individuals. And by the time, all individuals appearing in the next generations are also over fitted. Many experiments were made to stop the training before that point, but nothing could solve it.

The best solution to the dominance problem is multi-objective evaluation. This means that each individual has more than one objective and in each generation, individuals are sorted using Pareto principle to ensure that no objective dominates the other. This results in the non-dominance of any over fitted individual.

D. Why Merging ANFIS Model and GP Model Both models have their own advantages and

disadvantages. GP predictive model has the capability to predict if the price would rise; however, it doesn’t know how much high would it get and not sure when exactly.

In other side, ANFIS model has the capability to predict if the price would rise and it’s sure how much would go far up or down; however, it’s not sure if how the price would be like after 6 timeframes.

Thus, both techniques were merged to make full use of their capabilities since each one’s advantage compromises the other one’s disadvantage.

As a result, by integrating both techniques, our decision making process now has the capability to know if the price would go up, how high would the price go and when exactly would be any stop loss in the next 6 timeframes.

V. CONCLUSION The main goal of this project was to build an agent capable

of predicting Foreign Exchange market (Forex) and then trade automatically with no human supervision.

The agent used two predictive models. The first one is based on Genetic Programming to generate an individual with two trading rules predicting if the buy, hold or sell operation should be performed depending on technical analysis functions, statistical and mathematical functions. The two rules inside each individual are pretty similar to if statements with functions return double on its leaves, then compared to each other using logical comparators (<, >, ==) and then logically compared using logical operators (AND, OR, etc). The return value of the rule is either true or false. Finally, the return values of two rules are compared and one final output is given to the agent with buy, sell or hold.

2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) 147

Page 8: [IEEE 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES) - singapore, Singapore (2013.04.16-2013.04.19)] 2013 IEEE Symposium on Computational Intelligence

The second predictive model is based on ANFIS. Twelve FISs were generated using Sugeno-Type Fuzzy Inference. All membership functions were generated using Subtractive Clustering. Six FISs were used to predict the high price on the next 6 timeframes. The other six FISs were used to predict the lowest prices of the next 6 timeframes. With such information, the agent checks if there is an opportunity to gain profit if performed an operation at the moment, then calculates take profit and stop loss and makes the decision. The agent watches the price fluctuations and ends the operation whenever the price exceeds stop-loss or take-profit values.

Finally, the agent itself was implemented and tested on a worldwide standard tester and it achieved 102% profit in one year (7/2011 to 7/2012) on EURUSD pair using 30 minutes timeframe. The main advantages of the prediction algorithm are its high profitability and its flexibility to market changes.

The decision-making process has at least 40 parameters that need to be tuned. Probably this could be done through some optimization techniques to avoid any expected high losses if the market fluctuated rapidly.

Training FISs and GP should be automated by building a framework to make the learning an online process. This could help build many predictive tools to all Forex pairs to expose the agent to more trading options and more profit.

REFERENCES [1] Investopedia. "Foreign Exchange Market." Internet :

http://www.investopedia.com/terms/forex/f/foreign-exchange-markets.asp#ixzz207HQyKBp, [Jan. 12, 2012]

[2] XE. "What is currency trading?" Internet: http://www.xe.com/currencytrading/, [Jan 12, 2012]

[3] C. Garner, "Currency Trading in the Forex and Futures Markets," FT Press, 2012.

[4] H. Kiehling, "Nonlinear and chaotic dynamics and its application to ," in Historical Social Research., 1996.

[5] Y. Li and W. Ma, "Applications of artificial neural networks in financial economics: a survey," in Computational Intelligence and Design (ISCID), 2010 International Symposium, 2010.

[6] M. W. Fakhr and A. Baasher, "Forex daily trend prediction using machine learning techniques," ACS'11 Proceedings of the 11th WSEAS international conference on Applied computer science, Pages 41-47, 2011.

[7] G.S.Astalakis and C. H. Skiadas, I. Braimis, "Probability of trend prediction of exchange rate by ANFIS," in Recent Advances in Stochastic Modeling and Data Analysis., 2007.

[8] M. A. H. Dempster, T. W. Payne, Y. Romahi, and G. W. P. Thompson, "Computational learning techniques for intraday fx trading using popular technical indicators," IEEE Transactions on Neural Networks, Vol. 12 No.4, pp 744, 2001.

[9] Giles, C. Lee, Lawrence, Steve and Tsoi, Ah Chung, "Rule inference for financial prediction using recurrent neural networks", in IEEE/IAFE Conference on Computational Intelligence for Financial Engineering, New York city, 1997.

[10] S. Ghoshray, "Foreign exchange rate prediction by fuzzy inferencing

on deterministic chaos," in IEEE/IAFE Computational Intelligence for Financial Engineering, New York City, 1996, pp. pp 96-102.

[11] R. P. Barbosa, and O. Belo , "Autonomous forex trading agents,"ICDM '08 Proceedings of the 8th industrial conference on Advances in Data Mining: Medical Applications, E-Commerce, Marketing, and Theoretical Aspects, Pages 389 - 403, 2008.

[12] E. Zitzler, S. Bleuler, and M. Laumanns "A tutorial on evolutionary multiobjective optimization," 2003.

[13] J. Shing and R. Jang, "ANFIS: adaptive-network-based fuzzy inference system," Systems, Man and Cybernetics, IEEE Transactions on, 1993.

[14] M. Buragohain and C. Mahanta, "A novel approach for ANFIS modeling based on full factorial design.", Applied Soft Computing,Volume 8, Issue 1, Pages 609–625, 2008.

[15] R. P. Barbosa and O. Belo, "Autonomous forex trading agents," in Advances in Data Mining. Medical Applications, E-Commerce, Marketing, and Theoretical Aspects. New York City: Springer, p. 401, 2008,.

[16] L. Yu , S. Wang , W. Huang and K. K. Lai, "Are foreign exchange rates predictable? a survey from artificial neural networks perspective," A Journal of International Institute for General Systems Studies, Inc., 2006.

148 2013 IEEE Symposium on Computational Intelligence for Engineering Solutions (CIES)