Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/337984522

DESIGN AND IMPLEMENTATION OF FOREIGN EXCHANGE PREDICTION TOOL


USING MACHINE LEARNING

Thesis · December 2019


DOI: 10.13140/RG.2.2.23490.94401

CITATIONS READS
0 3,246

1 author:

Oyaniyi Lawrence Olanrewaju


Auchi Polytechnic
8 PUBLICATIONS   1 CITATION   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

INTEGRATING TRUST-BASED ACCESS CONTROL INTO AUTOMATIC TELLER MACHINE (ATM) SECURITY View project

All content following this page was uploaded by Oyaniyi Lawrence Olanrewaju on 17 December 2019.

The user has requested enhancement of the downloaded file.


DESIGN AND IMPLEMENTATION OF FOREIGN EXCHANGE PREDICTION TOOL
USING MACHINE LEARNING

BY

OYANIYI LAWRENCE OLANREWAJU


AUO/15BC/0299

BEING A PROJECT SUBMITTED TO THE DEPARTMENT OF MATHEMATICAL


SCIENCES, COLLEGE OF NATURAL AND APPLIED SCIENCES,
ACHIEVERS UNIVERSITY, OWO.

IN PARTIAL FULFILLMENT OF THE REQUIREMENT FOR THE AWARD OF


BACHELOR OF SCIENCE (B.Sc.) DEGREE IN COMPUTER AND INFORMATION
SYSTEMS.

DECEMBER, 2017.
CERTIFICATION

The undersigned certify that this project report prepared by Oyaniyi, Lawrence
Olanrewaju (AUO/15BC/0299) titled: Design and Implementation of Foreign
Exchange Prediction Tool Using Machine Learning meets the requirements
of the Department of Mathematics/Computer & Information System.

____________________ ___________________

Project Supervisor Date

Mr. Ekundayo, S. O.

____________________ ___________________

Head of Department Date

Prof. L. O. Adetula

____________________ ___________________

External Supervisor Date

ii
DEDICATION

This project work is dedicated to my mother Princes Mary Adebisi Oyaniyi

iii
ACKNOWLEDGMENT

I wish to appreciate the almighty God, the alpha and omega of this programme.
I give you all the glory and honour.

I appreciate the effort of my supervisor, Mr. Ekundayo Sunday for his advice and
thorough supervision. May Almighty God bless you abundantly in Jesus Name.

My profound gratitude goes to my wife Oyaniyi Bukola Oyaniyi, my children,


Michael, Raphael and Margaret. You’ve all contributed immensely to see me to
this extent. I pray that you will all grow beyond where I will stop in Jesus Name.
May God fulfill His promises in your lives in Jesus Name (Amen). Thank you all.

I appreciate my elder brother, Anthony Olusina Oyaniyi and my mother Princess


Mary Adebisi Oyaniyi for your constant prayers and support.

I appreciate all other colleagues Damilola, Ajayi, Ehis, Paul, Raphael, Ibrahim.
We started together and we finished together, may God’s abundant grace
remained with us in Jesus Name.

I wish to thank other numerous people who have contributed in one way or the
other for the success of this project. May almighty God continue to shower his
blessing upon you.

To my late father, Michael Olatoye Asola Oyaniyi, your advice and prayer really
worked and take me to where I am today. May your soul rest in peace.

Thank you and God bless you all.

iv
TABLE OF CONTENT

Title page i

Certification ii

Dedication iii

Acknowledgement iv

Table of Content v

List of Figures viii

List of Tables viii

Abstract ix

CHAPTER ONE

1.0 Introduction 1

1.1 Background of the Study 1

1.2 Problem Statement 3

1.3 Aim and Objectives of the Study 4

1.4 Methodology 4

1.5 Contribution to the Knowledge 5

CHAPTER TWO

2.0 Literature Review 6

2.1 Historical Background 6

2.1 Financial Market 8

2.3 Forecasting Financial Market 10

v
2.4 Traditional Forecasting Technique for the Currency Market 13

2.4.1 Fundamental Analysis 14

2.4.2 Technical Analysis 15

2.5 Related Work 18

CHAPTER THREE

3.0 System Analysis and Design 21

3.1 Introduction 21

3.2 Methodology 21

3.3 Architectural Model of the New System 24

3.4 Analysis of the New System 25

CHAPTER FOUR

4.0 System Implementation 27

4.1 System Implementation Tools 27

4.1.1 Hardware Requirements 28

4.1.2 Software Requirements 28

4.2 Results 29

4.2.1 Buy Signal 29

4.2.2 Sell Signal 30

4.3 Experimental Result 31

4.4 Discussion 32

vi
CHAPTER FIVE

5.0 Summary, Conclusion and Recommendation 33

5.1 Summary 33

5.2 Conclusion 33

5.3 Recommendation 34

5.4 Limitation 34

References 35

Appendix 43

vii
LIST OF FIGURES

Figure 3.1 System Flowchart 24

Figure 3.2 Decision Tree for Trading Decision 25

Figure 4.2 User Interface 28

Figure 4.2 Buy Signal on CHF/JPY on 4 Hours Chart 29

Figure 4.3 Sell Signal Generated on 13th November, 2017 30

LIST OF TABLES

Table 4.1 Experimental Result

viii
ABSTRACT

Foreign Currency Exchange is concerned with the exchange rates of foreign


currencies compared to one another. These rates provide significant data
necessary for currency trading in the international monetary markets. This
project shows an evolutionary algorithm application to generate profitable
strategies to trade future contracts on foreign exchange market (FOREX). The
modeled strategy is based on two decision trees, responsible for taking decisions
of opening long and short positions on any currency pair. This strategy use
technical indicators, which are connected by logic operators to identify border
values in making profitable decision(s). 20 trades were taken from 9 different
currency pairs between October 17 and December 4, 2017. The results show
that 15 out of the 20 trades representing 75% are profitable, while 5
representing 25% are not profitable.
Keyword: Foreign exchange, prediction, decision tree

ix
CHAPTER ONE

INTRODUCTION

1.1 BACKGROUND OF THE STUDY


The foreign exchange market, called FOREX (FX) or the currency market, is a
decentralized market where currencies are traded. This includes all aspects of
buying, selling and exchanging currencies at current or determined prices. In
terms of trading volume, it is by far the largest market in the world, followed by
the Credit market (Record N.,2014)

The main participants in this market are the larger international banks. Financial
centers around the world function as anchors of trading between a wide range of
multiple types of buyers and sellers around the clock, with the exception of
weekends.

The foreign exchange market works through financial institutions, and operates
on several levels. Behind the scenes, banks turn to a smaller number of financial
firms known as "dealers", who are involved in large quantities of foreign
exchange trading. Most foreign exchange dealers are banks, so this behind-the-
scenes market is sometimes called the "interbank market" (although a few
insurance companies and other kinds of financial firms are involved). Trades
between foreign exchange dealers can be very large, involving hundreds of
millions of dollars. Because of the sovereignty issue when involving two
currencies, FOREX has little (if any) supervisory entity regulating its actions.

1
The foreign exchange market assists international trade and investments by
enabling currency conversion. For example, it permits a business in the United
States to import goods from European Union member states, especially Eurozone
members, and pay Euros, even though its income is in United States dollars. It
also supports direct speculation and evaluation relative to the value of currencies
and the carry trade speculation, based on the differential interest rate between
two currencies (Heiner Flassbeck and Massimiliano La Marca, 2007). The mere
pursuit of profit through financial speculation is a bad activity in the moral
context even if made within legal limits that are different in each country.

Financial forecasting is truly a challenging task and remains a very active


research area. Many researchers have proposed many methodologies in helping
prospective traders analyze market situation with a view of making trading
decision. Despite these, greater percentage of both new traders and experience
traders sometimes run into loss.

Many algorithms were designed for effective prediction and profit making. Most
of these algorithms are only suitable on paper but failed during implementation.
In this thesis, we want to use machine learning and decision tree algorithm in
particular for effective FOREX market movement prediction.

Decision tree learning uses a decision tree (as a predictive model) to go from
observations about an item (represented in the branches) to conclusions about
the item's target value (represented in the leaves). It is one of the predictive
modeling approaches used in statistics, data mining and machine learning. Tree
models where the target variable can take a discrete set of values are called
classification trees; in these tree structures, leaves represent class labels and

2
branches represent conjunctions of features that lead to those class labels.
Decision trees where the target variable can take continuous values (typically
real numbers) are called regression trees (Rokach, Lior; Maimon, O., 2008).

Decision tree is a type of supervised learning algorithm (having a pre-defined


target variable) that is mostly used in classification problems. It works for both
categorical and continuous input and output variables. In this technique, we split
the population or sample into two or more homogeneous sets (or sub-
populations) based on most significant splitter / differentiator in input variables.

Tree based learning algorithms are considered to be one of the best and mostly
used supervised learning methods. Tree based methods empower predictive
models with high accuracy, stability and ease of interpretation.

1.2 PROBLEM STATEMENT


FOREX market is the largest and most accessible financial market in the world,
but although there are many FOREX investors, few are truly successful ones.
Many traders fail for the same reasons that investors fail in other asset classes.
In addition, the extreme amount of leverage - the use of borrowed capital to
increase the potential return of investments - provided by the market, and the
relatively small amounts of margin required when trading currencies, deny
traders the opportunity to make numerous low-risk mistakes. Factors specific to
trading currencies can cause some traders to expect greater investment returns
than the market can consistently offer, or to take more risk than they would
when trading in other markets (Investorpedia, 2017).

3
The economics of supply and demand largely determine the exchange rate
fluctuations. Calculating the supply and demand curves to determine the
exchange rate has shown to be unfeasible (Alamili, M., 2011). Therefore, one
needs to rely on various forecasting methods. The traditional linear forecasting
methods suffer from their linear nature, since empirical evidence has
demonstrated the existence of nonlinearities in exchange rates. In addition, the
usefulness of the parametric and nonparametric, nonlinear models, has shown to
be restricted (Mohamad Alamili, 2011).

For these reasons, the use of computational intelligence in predicting the foreign
exchange rate is investigated, in which these previously mentioned limitations
may be overcome. The method used here is decision tree machine learning
algorithm.

1.3 AIM AND OBJECTIVES OF THE STUDY


The main aim of the research work is to develop and implement a Foreign
Exchange forecasting tool using machine learning.
The specific objectives of the study are:
i. To develop a FOREX Advisor tools that guides FOREX traders in trading
decision
ii. To evaluate the efficacy of the FOREX Advisor tools developed

1.4 METHODOLOGY
This research work was carried out using Machine Learning method with
emphasis on decision tree Algorithm. A review of available literature in the area
of machine learning for currency forecasting was carried out.

4
1.5 CONTRIBUTION TO KNOWLEDGE
This research work designed a tool that will take trades on its own without
traders spending time in analyzing the market condition.

5
CHAPTER TWO

LITERATURE REVIEW

2.1 HISTORICAL BACKGROUND


The creation of the gold standard monetary system in 1875 is one of the most
important events in the history of the FOREX market. Before the gold standard
was created, countries would commonly use gold and silver as method of
international payment. The main issue with using gold and silver for payment is
that the value of these metals is greatly affected by global supply and demand.
For example, the discovery of a new gold mine would drive gold prices down.

The basic idea behind the gold standard was that governments guaranteed the
conversion of currency into a specific amount of gold, and vice versa. In other
words, a currency was backed by gold. Obviously, governments needed a fairly
substantial gold reserve in order to meet the demand for currency exchanges.
During the late nineteenth century, all of the major economic countries had
pegged an amount of currency to an ounce of gold. Over time, the difference in
price of an ounce of gold between two currencies became the exchange rate for
those two currencies. This represented the first official means of currency
exchange in history.

The gold standard eventually broke down during the beginning of World War I.
Due to the political tension with Germany, the major European powers felt a
need to complete large military projects, so they began printing more money to
help pay for these projects. The financial burden of these projects was so

6
substantial that there was not enough gold at the time to exchange for all the
extra currency that the governments were printing off.
Although the gold standard would make a small comeback during the years
between the wars, most countries had dropped it again by the onset of World
War II. However, gold never stopped being the ultimate form of monetary value.

Bretton Woods System


Before the end of World War II, the Allied nations felt the need to set up a
monetary system in order to fill the void that was left when the gold standard
system was abandoned. In July 1944, more than 700 representatives from the
Allies met in Bretton Woods, New Hampshire, to deliberate over what would be
called the Bretton Woods system of international monetary management.

To simplify, Bretton Woods led to the formation of the following:


 A method of fixed exchange rates;
 The U.S. dollar replacing the gold standard to become a primary reserve
currency; and
 The creation of three international agencies to oversee economic activity: the
International Monetary Fund (IMF), International Bank for Reconstruction and
Development, and the General Agreement on Tariffs and Trade (GATT).

The main feature of Bretton Woods was that the U.S. dollar replaced gold as the
main standard of convertibility for the world's currencies. Furthermore, the U.S.
dollar became the only currency in the world that would be backed by gold. (This
turned out to be the primary reason why Bretton Woods eventually failed.) Over
the next 25 or so years, the system ran into a number of problems. By the early
1970s, U.S. gold reserves were so low that the U.S. Treasury did not have

7
enough gold to cover all the U.S. dollars that foreign central banks had in
reserve.

Finally, on August 15, 1971, U.S. President Richard Nixon closed the gold
window, essentially refusing to exchange U.S. dollars for gold. This event marked
the end of Bretton Woods. Even though Bretton Woods didn't last, it left an
important legacy that still has a significant effect today. This legacy exists in the
form of the three international agencies created in the 1940s: the International
Monetary Fund, the International Bank for Reconstruction and Development
(now part of the World Bank) and the General Agreement on Tariffs and Trade
(GATT), which led to the World Trade Organization (investopedia, 2017).

2.2 FINANCIAL MARKETS


A necessary precondition for financial forecasting is an understanding of financial
markets and the data that is derived from these markets. This section starts with
explaining what is meant by a financial market in the broader term and by a
currency market in the specific term. A financial market is a mechanism that
allows people to buy and sell financial securities and commodities, to facilitate
the raising of capital in capital markets, the transferring of risk in derivatives
markets, or the international trading in currency markets (Pilbeam, 2010). These
securities and commodities come in many different kinds. For instance, the
classical share is a popular security that represents a piece of ownership of a firm
and which is exchanged on the stock market. Other popular securities are bonds,
currencies, futures, options and warrants.

All of these financial securities are traded every day on specific financial markets
with specific rules governing their quotation (Bodt, E, et. al., 2001). However,

8
quotation is not the only financial data that can be retrieved from a financial
market. The trading volume or the amount of dividends of a specific share can
provide valuable information regarding that share’s value. Moreover, not all
financial data are retrieved from the financial markets; data can also be retrieved
from financial statements, forecasts from a financial analysts, etc. It is out of
the scope of this research to cover all these kinds of financial securities with all
the different financial data.

The global foreign currency market is undoubtedly considered the largest and
most liquid of all financial markets, with an estimated average daily turnover of
$4.0 trillion (Bank of International Settlements, 2010). Currencies are traded in
the form of currency pairs through a transaction between one country's currency
and another's. These transactions are not limited to the exchange of currencies
printed by a foreign country's central bank, but also includes checks, wire
transfers, telephone transfers, and even contracts to sell or buy currency in the
future (Rugman and Collinson, 2006). These different transactions are facilitated
through four different markets, which include the spot market, the futures
market, the options market, and the derivatives market (Levinson, 2006). All
these different markets function separately but are yet closely interlinked.

The spot market facilitates an immediate delivery for the currencies to be traded,
while the future and option markets allow participants to lock in an exchange
rate at a certain future date by buying or selling a futures contract or on option.
The most trading in the currency market now occurs in the derivatives market,
which accounts for the forward contracts, foreign-exchange swaps, foreign rate
agreements and barrier options (Levinson, 2006). These currency markets are
highly distributed geographically and have no single physical location. Most

9
trading occurs in the interbank markets among financial institutions across the
world. The participants in the currency market are composed of exporters and
importers, investors, speculators and governments. The most widely traded
currency is the US dollar, while the most popular currency pair is the EUR/USD
(Bank of International Settlements, 2010).

The price of a specific currency is referred to as the exchange rate, which also
accounts for the spread established by the participants in the market. The
economics of supply and demand largely determine the exchange rate
fluctuations (Rugman and Collinson, 2006). Ideally, one would determine the
exchange rate by calculating supply and demand curves for each exchange
market participant and anticipate government constraints on the exchange
market. However, this information is lacking due to the immense size of the
exchange market, by which calculating the supply and demand curve for each
participant is simply unfeasible. This is the reason why there is no certainty in
determining the exchange rate and therefore one needs to rely on various
forecasting models, being either fundamental or technical forecasting methods.

2.3 FORECASTING FINANCIAL MARKETS


There are many typical applications of forecasting in the financial world, e.g.
simulation of market behavior, portfolio selection/diversification, economic
forecasting, identification of economic explanatory variables, risk rating of
mortgages, fixed income investments, index construction, etc. (Trippi, et.
al.,1992). Literature shows that opposing views exist between academic
communities on whether financial markets are susceptible to forecasting.

10
Fama (1965) presents empirical tests of the random walk hypothesis, that was
first proposed by Bachelier in 1900. The random walk hypothesis states that past
stock prices are of no real value in forecasting future prices because past,
current, and future prices merely reflect market responses to information that
comes into the market at random (Bachelier, 1900). Fama’s conclusion (1965)
based on empirical tests is: “the main conclusion will be that the data seem to
present consistent and strong support for the random walk hypothesis. This
implies, of course, that chart reading, though perhaps an interesting pastime, is
of no real value to the stock market investor ” However, the statistical tests that
Fama performed and that support the notion that financial markets follow a
random walk were based on the discovery that there was no linear dependency
in the financial market (Tenti, 1996). Nevertheless, the lack of a linear
dependency did not rule out nonlinear dependencies, which would contradict the
random walk hypothesis. Some researchers argue that nonlinearities do exist in
the currency market (Brock et al., 1991; Grauwe De, et. al., 1993; Fang et al.,
1994; Taylor, 1986).

Fama’s conclusion (1965) is supported by the main theoretical argument of the


efficient market hypothesis. This hypothesis states that a particular market is
said to be efficient, if all the participants and actors related to that market
receive all possible information at any time and at the same time (Malkiel, 1987).
As a consequence, the price in such a market will only move at the arrival of new
information, which is by definition impossible to forecast on historical data only.
Nevertheless, despite this reason why financial forecasting is criticized by many
economists, most notably by Malkiel (1995), financial forecasting has still
received an increasing amount of academic attention. It has been shown by
some researchers that financial forecasting does hold a predictive ability and

11
profitability by both technical analysis and fundamental analysis (Sweeney, 1988;
Brock, Lakonishok, LeBaron, 1992; Bessembinder and Chan, 1995; Huang, 1995;
Raj and Thurston, 1996). While this shows that evidence has been found of
predictive ability by financial forecasting, it does, however, not always provide
profitability when appropriate adjustments are made for risk and transaction
costs (Corrado and Lee, 1992; Hudson et al.,1996; Brown et al., 1995;
Bessembinder and Chan, 1998; Allen et. al., 1999).

In addition, it is questionable whether the financial markets can be portrayed as


an ideal representation of an efficient market. That financial markets are not so
efficient is supported by Campbell, the Lo and MacKinley (1997) in which they
state: “Recent econometric advances and empirical evidence seem to suggest
that financial asset returns are predictable to some degree”. One of those
econometric advances has been conducted by Brock, Lakonishok and Le Baron in
1992. They used a bootstrap methodology to test the most popular technical
trading rules on the Dow Jones market index for the period 1897 to 1986. They
concluded that their results provide strong support for market predictability.
Sullivan, Timmerman and White (1999) showed new results on that same data
set, extended with 10 years of data. Their bootstrap methodology avoided at
least to some extent the data snooping bias by which they were able to confirm
that the results of Brock, Lakonishok and Le Baron are still valid. The concept of
the data snooping bias appears as soon as a specific data set is used more than
once for purposes of forecasting model selection (Lo and MacKinley, 1990).

More recently, Lo, Mamaysky and Wang (2000) showed that a new approach
based on nonparametric kernel regression was able to provide incremental
market information and may therefore have some practical value. Based on all

12
the empirical evidence mentioned above, it is at least evident that there is some
sort of interest in trying to forecast the financial markets, and at most safe to
consider that it might indeed be possible.

Lastly, it is noteworthy to mention that a clear distinction must be made between


successfully being able to forecast the market and the possibility to gain
financially from this forecast. The difference is in order to gain financially from a
forecast, one needs to take a trading strategy into account with all the
associated transaction costs, which is a much more complicated task (Chordia
and Shivakumar , 2000).

2.4 TRADITIONAL FORECASTING TECHNIQUES FOR THE CURRENCY


MARKET
This section follows up on the philosophy of financial forecasting in the previous
two sections by presenting some of the most popular financial forecasting
techniques (without the use of computational intelligence) for which some show
certain successes. Examining these techniques may provide valuable insight in
how the more advanced computational intelligence techniques may be applied to
exchange rate prediction. Many of these so-called traditional forecasting
techniques are found in literature for financial forecasting in general and for
forecasting the currency market in particular (Bilson, 1992; LeBaron, 1993,
Levich & Thomas, 1993; Taylor 1994). There exists an important distinction
within these techniques, which entails forecasting by means of fundamental
analysis versus technical analysis (Bodt et al., 2001). Both of these techniques
are described in this section, while the focus is more on technical analysis to be
more in line with the focus of his research.

13
2.4.1 Fundamental Analysis
Fundamental analysis is concerned with analyzing the macroeconomic and/or the
micro economic factors that influence the price of a specific security in order to
predict its future movement (Lam, 2004). An example is examining a firm's
business strategy or its competitive environment to forecast whether its share
value will rise or decline. In the case of the currency market, one would mostly
examine macroeconomic factors. For instance, the interest rate, the inflation
rate, the rate of economic growth, employment, consumer spending, and other
economic variables can have a significant impact on the currency market
(EddelButtel and McCurdy, 1998). The enormous literature measuring the effects
of macro news on the currency market within the field of fundamental analysis
includes Hakkio and Pearce (1985), Ito and Roley (1987), Ederington and Lee
(1995), DeGennaro and Shrieves (1997), Almeida et al.(1998), Andersen and
Bollerslev (1998), Melvin and Yin (2000), Faust et al. (2003), Love and Payne
(2003), Love (2004), Chaboud et al. (2004) and Ben Omrane et al. (2005).

However, there exists controversy in the academic literature concerning financial


forecasting in terms of fundamental analysis. A series of papers by Meese and
Rogoff (1983) have shown that forecasting the currency market based on a
random walk model perform better than basing the forecast on microeconomic
models. A number of researchers have reinvestigated the papers proposed by
Meese and Rogoff and have generally found it to be robust (Flood and Rose,
1995; Cheung et al., 2005).

14
Nevertheless, some researchers found that they are able to find a strong
relationship between certain macro surprises and exchange rate returns, given
that a narrow time window is used (Anderson et al., 2003).

2.4.2 Technical Analysis


Technical analysis involves the prediction of future price movement of a specific
financial security based on only historical data (Achelis, 1995). This data usually
consists only of past prices. However, it can also include other information about
the market, most notably volume. Volume refers to the amount of the trades
that has been made in that specific financial market over a specified time period
(Cambell et al., 1997). Technical analysis can either be of qualitative nature or
quantitative nature (Achelis, 1995). When it is of qualitative nature, it aims to
recognize certain patterns in the data by visually inspecting the price. When it is
of quantitative nature, it aims to base the prediction on analyzing mathematic
representations of the price, e.g. a moving average. Forecasting by means of
technical analysis is commonly used in forecasting the currency market, where
the traders that use technical analysis are mostly interested in the short-term
movement of currencies (Taylor and Allen, 1992).

Many technical analysis techniques have been empirically tested in an attempt to


determine their effectiveness. The effectiveness is often explained by the so-
called self-fulfilling property that financial markets may hold, which refers to the
phenomena that if a large group is made to believe the market is going to rise,
then that group will most likely act as if the market is truly going to rise,
eventually leading to an actually rise (Sewell, 2007). During the 1990s, the
studies on technical analysis techniques increased, along with the methods used
to test them. A selection of the most influential studies that have provided

15
support for technical analysis techniques include (in no particular order):
Rouwenhorst (1998). Stronger evidence can be found in Neftci (1991), Brock,
Lakonishok, and LeBaron (1992).

One of the first technical analysis techniques are the common market structure
trading rules, of which its indicators monitor price trends and cycles (Pereira,
1999). These indicators include the filter rule, the moving average crossover
rule, Bollinger bands, trading range breakout (TRB), and many more (Pereira,
1999). Some of these indicators were used in one of the most influential and
referenced studies ever conducted on technical analysis, the studies by Brock,
Lakonishok, and LeBaron in 1992. As mentioned before, Levich and Thomas
conducted a related study with the same indicators in 1993 in which they
provided further evidence of the profitability of technical analysis techniques
.
The filter rule is defined by a single parameter, which is the filter size (Ball,
1978). The most basic filter rules are simply based on the assumption that if a
market price rises or declines by a certain percentage defined by the filter size,
then the price is most likely to continue on that direction. The moving average
crossover rule compares to moving averages, mostly a short-run moving average
with a long-run moving average (Appel, 1999). This indicator proposes that if the
short run moving average is above the long run moving average, the price is
likely to decline and vice versa. The moment that both averages cross, is the
moment of trend reversal. This is the most basic form of the moving average
cross over rule, while there exists many variations.

Bollinger bands are two standard deviations plots above and below a specific
moving average (Murphy, 1999). When the markets exceed one of the trading

16
bands, the market is considered to be overextended. It is assumed that the
market will then often pull back to the moving average line (Murphy, 2000).

The trading range breakout rule is also referred to as resistance and support
levels (Lento and Gradojevic, 2007). The assumption of this indicator is that
when the market breaks out above a resistance level, the market is most likely to
continue to rise, while as when a market breaks through and below a support
level, the market is most likely to continue to decline. The resistance level is
defined as the local maximum, and the support level is defined as the local
minimum (Brock, Lakonishok, and LeBaron in 1992). The reasoning behind this
indicator is that at the resistance level, intuition would suggest that many
investors are willing to sell, while at the support level many investors are willing
to buy. The selling or buying pressure will create resistance or support
respectively, against the price breaking through the level. These common market
structure trading rules, together with other traditional approaches to time series
prediction, such as the ARIMA method or the Box-Jenkins (Box and Jenkins,
1976; Pankratz, 1983), assumed that the data from the financial market is of a
linear nature. However, it is certainly questionable whether this data is indeed
linear, as explained before. As a matter of fact, empirical evidence has
demonstrated the existence of nonlinearities in exchange rates (Fang et
al.,1994). In addition, systems in the real world are often nonlinear (Granger and
Terasvirta, 1993).

In order to cope with the nonlinearity the exchange rates, certain techniques
that are nonlinear of nature have been developed and applied to exchange rate
prediction. These include but are not limited to the bilinear model by Granger
and Anderson (1978), the threshold autoregressive model (TAR) by Tong and

17
Lim (1980), the autoregressive random variance (ARV) model (So et al.,1999),
autoregressive conditional heteroscedasticity (ARCH) model (Engle, 1982; Hsieh,
1989), general autoregressive conditional heteroskedasticity (GARCH) model
(Bollerslev, 1990), chaotic dynamic (Peel et al., 1995), and self-exciting threshold
autoregressive (Chappel et al., 1996). The problem with these models however,
is that they are parametric nonlinear models, in that they need to be pre-
specified, therefore restricting the usefulness of these models since not all the
possible nonlinear patterns will be captured (Huang et al., 2004). In other
words, one particular nonlinear specification will not be general enough to
capture all the nonlinearities in the data. Furthermore, the few nonparametric
nonlinear models that have been investigated and applied to exchange rate
prediction, seem unable to improve upon a single random walk model
(Fama,1965) in out of sample predictions of exchange rates (Diebold and Nason,
1990; Meese and Rose, 1991).

2.5 RELATED WORK


Philip et al. (2011) implemented an artificial neural network foreign exchange
rates (AFERFM) to forecast USD/Naira, EUR/Naira, GBP/Naira and JPY/Naira
currency pairs daily fluctuations. The data used were daily averages from 2003
to 2005, the total sample size counting approximately 800 observations. The
training sample was made of 500 observations, 200 observations were used for
validation and finally 100 observations were used for testing. Regarding the
methodology, the authors used the back propagation algorithm in the training
phase and then the Sigmoid Activation Function (SAF) to standardized the input.
Next, the learning weights were randomly assigned in the (-0.1,0.1) range. Then
the authors used the Feed Forward Network, which has for effect to enhance the
efficiency of the back propagation algorithm. Finally, the Multilayer Perceptron

18
Network was used for the purpose of forecasting. The authors found using this
method, along with a particular parameterization detailed in their study, that an
AFERFM has a 81:2% accuracy while the best related work (a Hidden Markov
foreign exchange rate forecasting model) displayed a precision of 69:9%.

Sarantis (2006) applied for the first time a Bayesian vector autoregressive model
with time varying parameters (BVAR TVP) to short term exchange rate
predictions of DM/USD JPY/USD, USD/GBP and DM/GBP. The author used as
explanatory variables short term interest rate differentials, long term interest rate
differentials, equity return differentials and one month implied volatility to
forecast daily exchange rates. The data used spanned the period January 1991
to March 2001. Sarantis found that the BVAR TVP model outperformed the
random walk for all exchange rates.
.
Using daily exchange rates from 2005 to 2013, Oancea and Ciucu (2014)
compared the accuracy of different feed forward and recurrent NNs and training
algorithms to forecast the EUR/RON and USD/RON exchange rates. The authors
found that the recurrent network outperforms the feed forward network in the
context of the study.

Ratcliff (2010) tested whether daily movements in the skewness of a currency


option premium can predict fluctuations in the next day EUR/USD exchange rate
over the January 2002 - June 2004 period. The study showed that forecasts
including the relative price of a 2% OTM call and put currency option significantly
outperform either the Random Walk model or an interest rate parity model in
terms of out-of-sample predictions of tomorrow's exchange rate. This conclusion
was reached by comparing a Random Walk model and an Interest Rate Parity

19
model to versions including the skewness preminum as an explanatory variable.
The intuition behind the inclusion of the skewness premium in the models is that
OTM options being bets on upcoming movements of the exchange rate, their
relative price is an indicator of the market expectations of the future EUR/USD
exchange rate fluctuations over the life of the option. The author also found that
the skewness premium does not however help to make long run forecasts.

Teneng (2013) demonstrated that the Normal Inverse Gaussian (NIG) and
Variance Gamma (VG) Levy processes outperform, in term of RMSE, the Random
Walk model to forecast daily exchange rate closing prices. More precisely, Levy
processes effectively forecast the following currency pairs: TND/GBP, EGP/EUR,
EUR/GBP, EUR/JPY, JOD/JPY, USD/GBP, XAU/USD whereas USD/JPY and
QAR/JPY can only be forecasted with the VG process. Daily closing prices from
11/29/2007 to 04/28/2011 were used as the training sample and data from
04/29/2011 to 07/22/2011 were used as the test sample.

20
CHAPTER THREE

SYSTEM ANALYSIS AND DESIGN

3.1 INTRODUCTION
In this chapter, an analysis of the problem defined in chapter one is presented.
Detail methods and steps taken are fully explained.

3.2 METHODOLOGY
Decision Tree Algorithm
For the purpose of this project work, machine learning is employed with
emphasis on decision tree algorithm.
Decision trees can be described as the combination of mathematical and
computational techniques to aid the description, categorization and
generalization of a given set of data.
Data comes in records of the form:
X,Y=(x1, x2, x3, …, xk,, Y).

The dependent variable, Y, is the target variable that we are trying to


understand, classify or generalize. The vector x is composed of the input
variables, x1, x2, x3 etc., that are used for that task.
Decision tree are of two main types:
 Classification tree analysis is when the predicted outcome is the class to
which the data belongs.
 Regression tree analysis is when the predicted outcome can be considered
a real number (e.g. the price of a house, or a patient's length of stay in a
hospital).

21
The term Classification And Regression Tree (CART) analysis is an umbrella
term used to refer to both of the above procedures, first introduced by Breiman
et al., 1984. Trees used for regression and trees used for classification have
some similarities - but also some differences, such as the procedure used to
determine where to split (Breiman, et. al., 1984).
The CART decision tree is a binary recursive partitioning procedure capable of
processing continuous and nominal attributes both as targets and predictors.
Data are handled in their raw form; no binning is required or recommended.
Trees are grown to a maximal size without the use of a stopping rule and then
pruned back (essentially split by split) to the root via cost-complexity pruning
(Han, Jiawei and Kamber, Micheline, 2015).

Justification for the use of Decision Tree


 Simple to understand and interpret. People are able to understand decision
tree models after a brief explanation. Trees can also be displayed graphically
in a way that is easy for non-experts to interpret(Gareth, James; Witten,
Daniela; Hastie, Trevor; Tibshirani, Robert 2015)
 Able to handle both numerical and categorical data (Gareth, James, et. al;
2015). Other techniques are usually specialized in analyzing datasets that
have only one type of variable. (For example, relation rules can be used only
with nominal variables while neural networks can be used only with numerical
variables or categorical converted to 0-1 values.)
 Requires little data preparation. Other techniques often require data
normalization. Since trees can handle qualitative predictors, there is no need
to create dummy variables (Gareth, James, et. al; 2015).
 Uses a white box model. If a given situation is observable in a model the
explanation for the condition is easily explained by boolean logic. By contrast,

22
in a black box model, the explanation for the results is typically difficult to
understand, for example with an artificial neural network.
 Possible to validate a model using statistical tests. That makes it possible to
account for the reliability of the model.
 Non-statistical approach that makes no assumptions of the training data or
prediction residuals; e.g., no distributional, independence, or constant
variance assumptions
 Performs well with large datasets. Large amounts of data can be analysed
using standard computing resources in reasonable time.
 Mirrors human decision making more closely than other approaches (Gareth,
James, et. al; 2015). This could be useful when modeling human
decisions/behavior.
 Robust against co-linearity, particularly boosting
 In built feature selection. Additional irrelevant feature will be less used so that
they can be removed on subsequent runs.

23
3.3 THE ARCHITECTURAL MODEL OF THE NEW SYSTEM

START

RETRIEVE CURRENT
MARKET DATA

IS BUY
CONDICTION Yes
MEET?

No

No IS SELL Yes
CONDICTION
MEET?

TAKE TRADE

SET TAKE PROFIT TARGET

SET TAKE PROFIT TARGET

Yes
IS STOP LOSS HIT?

No

IS TAKE PROFIT HIT?


No
Yes

24
STOP

Fig 3.1: System Flowchart

25
3.4 ANALYSIS OF THE NEW SYSTEM
This work is based on Machine Learning with emphasis on decision tree
algorithm. The proposed system generates trade strategy based on BUY/SELL
decision trees that consists of technical indicators that are connected by logical
operators. The below decision tree depicts the proposed system.

Live Data

Stochastic (130,3,3)

Value <=20 Value >=80

Linear Weight Moving Current Price Below Linear Weight Moving Current Price
Average (15) AND Linear 50 Linear Weighted Average (15) AND Linear Below 50 Linear
Weighted Moving Moving Average? Weighted Moving Weighted Moving
Average (50) Average (50) Average?

15 Moving Average Cross 15 Moving Average 15 Moving Average


15 Moving Average Cross
Above 50? Cross Below 50? Cross Below 50?
Above 50?

Enter Sell Do not take Enter Sell


Enter Buy Do not take Enter Buy
Order any Trade Order
Order any Trade Order

Fig. 3.2: Decision Tree for Trading Decision

26
As depicted above, each decision can either by Buy or Sell. This is represented
as two decision trees, where one is responsible for Buy Signal and the other one
for Sell Signals recognition. Each of the decision trees is actually a trading rule.
It consists of logical functions binding leafs, which are technical analysis
indicators.

Used technical indicators are some variants of Weighted Linear Moving Average
and Stochastic indicator. They are very useful tools for investors to determine
trends, reversal points, to identify interesting buy/sell points. They are very
popular among investors of any kind, but can be used in sometimes very
complex ways, where the same indicator value can be interpreted by various
investors in different way.

27
CHAPTER FOUR

SYSTEM IMPLEMENTATION

4.1 SYSTEM IMPLEMENTATION TOOLS


FOREX forecasting tools was implemented with computer system using
MetalEditor programming language. Metal Editor programming language has
similar syntax with C and C++ programming language. This is the language
used in developing tools used in Metal Trader 4 which is the most widely used
Trading Platform. MT4 is a programming language used in developing financial
market tools. The tool was implemented on MT4 trading platform from different
broker such as FOREXTime, HotFOREX, FxPro and JustFOREX.
The MT4 was used to create user interface and the trading logic. Historical data
for testing the trading logic were downloaded from the MT4 and live data from
world market were also used to test the efficacy of the tool.

User Interface
The below is the user interface where user input parameters for the trading
logic. This gives the user the opportunity to change the parameters of the
decision logic if not satisfied with the input value. This gives the tool the
flexibility of adapting to any given value. If user is not satisfied with the
outcome of the performance of the tool, he/she can decide to change the input
parameter and observed the outcome until the result is satisfied.

28
Fig 4.2 User Interface

4.1.1 Hardware Requirements


The work is carried out with the use of a Zinox Laptop have a dual core
processor with 2.20GHZ speed, with 4GB RAM and 500GB Hard disk drive; 64 bit
windows Operating System with wifi facility to provide Internet Connection.

4.1.2 Software Requirements


MetaTrader 4 is installed from various brokers as mentioned above. This
software comes with Metal Editor, a programming language in which the FOREX
forecasting tool was developed.

29
4.2 RESULT
In order to ascertain the efficacy of the tool, a backtest was carried out using
historical data as well as live data. The results are presented and discussed
below.
4.2.1 Buy Signal

Fig. 4.2 Buy Signal on CHF/JPY on 4Hours Chart.

The above image shows buy signal generated on the 14th of July, 2017. The
system predicted that the price of CHF/JPY (France/Japanes Yuan) will move up
and it goes up from 112.815. This is a long term signal as it was held till July 11,
2017 when a Sell signal was generated.

30
4.2.2 Sell Signal

Fig. 4.3 Sell Signal Generated on 13th November, 2017.

The above image shows Sell signal generated on the 13th of November, 2017 on
30Minutes Time Frame. The system predicted that the price of CAD/CHF
(Canadian Dollar/ Swiss Franc) will move down and it goes down from 0.78548
as predicted. The sell pressure comes to an end on the 15th of November 2017
when the price closed above 50 Linear Weight Moving Average and Stochastic
indicator reached an oversold area. A new buy signal was generated towards
the end of the trading day.

31
4.3 EXPERIMENTAL RESULT
SN Date/Time Type Symbol Price SL TP Profit
1 2017-10-17 02:30 Buy CAD/CHF 0.77852 0.77595 0.78609 75pips
2 2017-10-19 06:30 Sell CAD/CHF 0.78609 0.78779 0.78176 45pips
3 2017-10-19 01:00 Buy CAD/CHF 0.78176 0.77998 0.78464 28pips
4 2017-10-20 01:00 Buy CAD/CHF 0.77951 0.77786 0.77941 -1pips
5 2017-11-01 14:30 Buy EUR/GBP 0.87386 0.87315 0.89202 185pips
6 2017-11-03 09:00 Sell EUR/GBP 0.89202 0.89399 0.88045 115pips
7 2017-10-30 06:00 Buy AUD/JPY 87.211 87.051 87.204 -7pips
8 2017-10-31 14:00 Buy AUD/JPY 87.192 87.676 87.676 48pips
9 2017-10-31 14:00 Sell XAU/USD 133.80 1341.73 1334.69 1pips
10 2017-07-11 08:00 Sell CHF.JPY 117.950 118.583 117.173 77pips
11 2017-07-19 04:00 Buy CHF.JPY 117.173 116.393 117.214 -6pips
12 2017-07-25 04:00 Sell CHF.JPY 117.214 117.786 Stop -53pips
Loss Hit
13 2017-10-10 20:00 Buy CAD/JPY 89.824 89.610 90.288 48pips
14 2017-10-12 00:00 Sell CAD/JPY 90.288 90.329 89.551 62pips
15 2017-12-04 10:30 Buy GDP/AUD 1.76771 1.76649 Stop -10pips
Loss Hit
16 2017-12-04 20:30 Sell GBP/AUD 1.77304 1.77970 1.75418 186pips
17 2017-11-01 12:00 Sell GBP/JPY 151.722 151.900 147.967 368pips
18 2017-11-20 04:00 Buy GBP/JPY 147.976 147.611 149.022 111pips
19 2017-12-04 20:00 Buy EUR/USD 1.18497 1.18376 1.18687 18pips
20 2017-12-06 06:00 Sell EUR/USD 1.18687 1.18757 1.17871 53pips
Table 4.1: Experimental Result

Total No of Transaction = 20
Total No of Profitable Transaction = 15
Total No of Failed Transaction = 5
% of Profitability = 75%

% of Loss = 25%

32
4.4 DISCUSSION
This project aimed forecasting foreign exchange using decision tree algorithm.
From the table above, twenty transactions were carried out basically on the
signal generated by the system on different time frame and currency pair. Out
of this number, 15 (75%) of the transactions were profitable and 5 representing
25% were lost. It was observed that out of the failed transactions two of them
hit stop loss before heading to a profitable point.

Also, some of the generated signals were late due to negative shift setting on the
15 moving average. This affected all signal generated, if this barrier is not
present most of the negative profit would have been positive and those that are
profitable would have generated more pips that the one presented in the table
above.

33
CHAPTER FIVE

SUMMARY, CONCLUSION AND RECOMMENDATION

5.1 SUMMARY
The research was center on the design of and implementation of foreign
exchange prediction tool using machine learning. This new method uses two
decision tree to make predictions based on the buy and sell rules. The
experimentation of the new system showed that 15 out of 20 predictions made
are profitable. This proved that investors such as bank, financial institution, fund
edge and even individual can use this tool without fear of uncertainties. This
system helps in eliminating sentiment and emotion which are always the problem
many traders encounter during trading session which eventually lead to lose.

5.2 CONCLUSION
From the result presented in chapter four, it was established, theoretically and
empirically that the proposed system can generate profitable signal without prior
knowledge about currency market. Decision tree algorithm clearly show how the
logic are connected together to arrive at a decision before signal is generated.
Statistically, this project has proven that in every ten predictions, seven will be
accurate and profitable regardless of the negative value generated from invalid
signal generated.

34
5.3 RECOMMENDATION
Prediction in Foreign exchange (FOREX) market has been on for a very long
time. Every now and then, FOREX market traders examine various methods that
could help them to successfully predict the currency price movement. Majority of
traders spent hours looking at their screen with a view of predicting the direction
of price movement. It is widely reported that about 95% of FOREX traders are
unsuccessful.

With the success recorded on the implementation of this project, the tool
developed from this project is highly recommended for those traders that are
struggling at the financial market.

5.4 LIMITATION
Despite the success recorded during the implementation of this project and
profitable opportunity it presents, the indicator is lagging, users is notified after
few candles after the signal is generated. This reduces the profit target and
misleading in a very narrow or ranging market.

35
REFERENCES
Achelis S. B. (1995) Technical Analysis from A to Z. Probus Publishing, Chicago.

Alamili, M. (2011) Exchange Rate Prediction Using Support Vector Machines: a


Comparison with Artificial Neural Networks. A Master Thesis Submitted to
the Faculty of Technology, Policy and Management Section of Information
and Communication Technology, Delft University of Technology.

Allen F., Karjalainen R. (1999). Using Genetic Algorithms to Find Technical


Trading Rules. Journal Finance Economics 51, 245–271.

Appel, Gerald (1999). Technical Analysis Power Tools for Active Investors.
Financial Times Prentice Hall. pp. 166.

Bachelier, L, (1900). Théorie de la spéculation, Gauthier-Villars, Paris, Annales


Scientifiques de l’École Normale Supérieure 3 (17): 21–86

Ball R. (1978) Filter Rules: Interpretation of Market Efficiency, Experimental


Problems and Australian Evidence. Accounting Education 18, 1–17.

Ben Omrane, W., Bauwens, L., Giot, P. (2005). News announcements, market
activity and volatility in the euro/dollar foreign exchange market. Journal
of International Money and Finance 24 (7), 1108e1125.

Bessembinder H., Chan K. (1995). The Profitability of Technical Trading Rules in


the Asian Stock Markets. Pacific Basin Finance Journal 3, 257–284.

Bessembinder H., Chan K. (1995). The Profitability of Technical Trading Rules in


the Asian Stock Markets. Pacific Basin Finance Journal 3, 257–284
Bessembinder H., Chan K. (1998). Market Efficiency and the Returns to
Technical Analysis. Financial Management 27, 5–17.

Bilson, J.F.O. (1992). Technical currency trading. Chicago, I 11; The Chicago
Corporation.

Bodt, E., Rynkiewicz, J., Cottrell, M. (2001). Some known facts about financial
data. European symposium on artificial neural networks 25-27. pp. 223-
236.

36
Bollerslev, T., (1990). Modeling the coherence in short-run nominal exchange
rates: A multivariate generalized ARCH model, Review of Economics and
Statistics 72 (1990) 498–505.

Breiman, Leo; Friedman, J. H.; Olshen, R. A.; Stone, C. J. (1984). Classification


and regression trees. Monterey, CA: Wadsworth & Brooks/Cole Advanced
Books & Software. ISBN 978-0-412-04841-8.

Brock W., Lakonishok J., Le Baron B., (1992). Simple Technical Trading Rules
and the Stochastic Properties of Stock Returns, The Journal of Finance,
vol. XLVII, n°5, pp. 1731-1764

Brock W., Lakonishok J., LeBaron B. (1992). Simple Technical Trading Rules and
the Stochastic Properties of Stock Returns. Journal of Finance 47, 1731–
1764.

Brock W., Lakonishok J., LeBaron B. (1992). Simple Technical Trading Rules and
the Stochastic Properties of Stock Returns. Journal of Finance 47, 1731–
1764.

Brock W., Lakonishok J., LeBaron B. (1992). Simple Technical Trading Rules and
the Stochastic Properties of Stock Returns. Journal of Finance 47, 1731–
1764

Brock, W.A.D.A., Hsieh, and B. LeBaron. (1991). Nonlinear dynamics, chaos, and
instability. Cambrigde, Mass.:MIT Press.

Brock, W.A.D.A., Hsieh, and B. LeBaron. (1991). Nonlinear dynamics, chaos, and
instability. Cambrigde, Mass.:MIT Press.

Brown S., Goetzmann W., Ross S. (1995). Survival. Journal of Finance 50, 853–
873 Brown S., Goetzmann W., Kumar A. (1998). The Dow Theory: William
Peter Hamilton’s Track Record Reconsidered. Working Paper, Stern School
of Business, New York University.

Chaboud, A., Chernenko, S., Howorka, E., Iyer, R., Liu, D., Wright, J., (2004).
The high-frequency effects of U.S. macroeconomic data releases on prices
and trading activity in the global interdealer foreign exchange market.
Board of Governors of the Federal Reserve System, IFDP No. 823.

37
Chappel, D., J. Padmore, P. Mistry and C. Ellis, (1996). A threshold model for
French franc/Deutsch mark exchange rate, Journal of Forecasting 15 155–
164.
Cheung, Y., Chinn, M., Pascual, A., (2005). Empirical exchange rate models of
the nineties: are any fit to survive? Journal of International Money and
Finance 24 (7), 1150e1175.

Chordia T., Shivakumar L., (2000). Momentum, Business Cycle and Time-Varying
Expected Returns, FEN Working Paper.

Cristianini, N. and Shawe-Taylor,(2000). J. An introduction to support vector


machines and other kernelbased learning methods. Cambridge: Cambridge
University Press.

D. Teneng. Outperforming the naive Random Walk forecast of foreign exchange


daily closing prices using Variance Gamma and normal inverse Gaussian
Levy processes. Munich Personal RePEc Archive, Jun. 2013.

Diebold. F.X. and Nason, J.A., (1990). Nonparametric exchange rate prediction.
Journal of International Economics 28 (1990) 315–322.

EddelButtel, D. and McCurdy, T.H.(1998). The impact of news on foreign


exchange rates: evidence from high-frequency data. University of Toronto.

Ederington, L., Lee, J., (1995). The short-run dynamics of price adjustment to
new information. Journal of Financial and Quantitative Analysis 30,
117e134.

Fama E., (1965). The Behavior of Stock Market Prices, Journal of Business, 38,
p.34-105 Fama, E., (1965). Random Walks In Stock Market Prices.
Financial Analysts Journal 21 (5): 55–59.

Fang, H.,L. S.Lai, and M.Lai. (1994). Fractal structure in currency futures price
dynamics. Journal of futures markets 14:169-181.

Fang, H.,L. S.Lai, and M.Lai. (1994). Fractal structure in currency futures price
dynamics. Journal of futures markets 14:169-181.

Faust, J., Rogers, J., Wang, S., Wright, J., (2003). The high-frequency response
of exchange rates and interest rates to macroeconomics announcements.
Board of Governors of the Federal Reserve System, IFDP No. 784.

38
Flood, R., Rose, A., (1995). Fixing exchange rates: a virtual quest for
fundamentals. Journal of Monetary Economics 36, 3e37.
Gareth, James; Witten, Daniela; Hastie, Trevor; Tibshirani, Robert (2015). An
Introduction to Statistical Learning. New York: Springer. p. 315. ISBN 978-
1-4614-7137-0.

Gareth, James; Witten, Daniela; Hastie, Trevor; Tibshirani, Robert (2015). An


Introduction to Statistical Learning. New York: Springer. p. 315. ISBN 978-
1-4614-7137-0.

Granger, C.W.J., (1993). Strategies for modelling nonlinear time series


relationships. The Economic Record 69 (206), 233–238.

Grauwe de, P., H. Dewachter, and M.Embrechts. (1993). Exchange rate theory.
Chaotic models of foreign exchange markets. London: Blackwell.

Hakkio, C., Pearce, D.K., (1985). The reaction of exchange rates to economic
news. Economic Inquiry 23 (4), 621e636.

Han, Jiawei and Kamber, Micheline (2006) Data Mining: Concepts and
Techniques-Second Edition, Morgan Kaufmann,USA, pp 291-315.

Heiner Flassbeck and Massimiliano La Marca (2007). Global imbalances and


destabilizing speculation Trade and development report 2007 (Chapter
1B).

http://www.investopedia.com/articles/FOREX/10/top-reasons-FOREX-traders-
fail.asp (accessed 27th July, 2017)

Huang Y -S. (1995).The Trading Performance of Filter Rules On the Taiwan Stock
Exchange. Applied Financial Economics 5, 391–395

Huang, Lai, Mori, Wang (2004) . Forecasting foreign exchange rates with artificial
neural networks, a review. International Journal of Information Technology
& Decision Making. Vol 3, No 1, 145-165

Huang, Lai, Mori, Wang (2004) . Forecasting foreign exchange rates with artificial
neural networks, a review. International Journal of Information Technology
& Decision Making. Vol 3, No 1, 145-165

39
Huang, W., Nakamori, Y., and Wang, S.Y. (2002).Using change-point detection
to seek optimal training set for neural networks in foreign exchange rates
forecasting. International Journal of Computational Intelligence and
Organization.

Hudson R., Dempsey M., Keasey K. (1996). A Note on the Weak Form of
Efficiency of Capital Markets: The Application of Simple Technical Trading
Rules to the U.K. Stock Markets– 1935-1994. Journal of Banking and
Finance 20, 1121–1132.

Ito, T., Roley, V., (1987). News from the US and Japan: which moves the
yen/dollar exchange rate? Journal of Monetary Economics 19 (2),
255e277.

LeBaron, B. (1993). Practical comparisons of foreign exchange forecasts. Neural


Network World (November); 779-791.

Lento, C., Gradojevic, N., (2007). The profitability of technical trading rules: a
combined signal approach. Journal of applied business research, volume
23, number 1.

Lo A. W., MacKinley A. G. (1990) Data Snooping Biases in Tests of Financial


Asset Pricing Models. The Review of Financial Studies 3, 431–467.

Lo A. W., MacKinley A. G. (1990) Data Snooping Biases in Tests of Financial


Asset Pricing Models. The Review of Financial Studies 3, 431–467.

Love, R., (2004). First and second moment effects of macro news in high
frequency foreign exchange data. Mimeo, FMG, London School of
Economics.

Love, R.R. Payne, R., (2003). Macroeconomic news, order flows, and exchange
rates. Discussion Paper 475, FMG, London School of Economics.

Malkiel B. (1995) .A Random Walk Down Wall Street, 6th edn. W. W. Norton,
New York.

Marc Levinson (2006) The guide to financial markets. Profile Books Ltd, 3a
Exmouth House, Pine Street, London.

40
Meese, R., Rogoff, K., (1983a). Empirical exchange rate models of the seventies.
Journal of International Economics 14, 3e24.

Meese, R., Rogoff, K., (1983a). Empirical exchange rate models of the seventies.
Journal of International Economics 14, 3e24.

Meese, R., Rogoff, K., (1983b). The out-of-sample failure of empirical exchange
rate models. In: Frenkel, J. (Ed.), Exchange Rate and International
Macroeconomics. University of Chicago Press, Chicago.

Meese, R., Rogoff, K., (1983b). The out-of-sample failure of empirical exchange
rate models. In: Frenkel, J. (Ed.), Exchange Rate and International
Macroeconomics. University of Chicago Press, Chicago.

Melvin, M., Yin, X., (2000). Public information arrival, exchange rate volatility,
and quote frequency. Economic Journal 110, 644e661.

Monica Lam (2004). Neural network techniques for financial performance


prediction: integrating fundamental and technical analysis, Volume 37,
Issue 4, Data mining for financial decision making,Pages 567-581.

Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York


Institute of Finance.

Murphy, J. J. (2000). Charting Made Easy. Marketplace Books (Wiley).

N. Sarantis. On the short-term predictability of exchange rates: A BVAR time


varying parameters approach. Journal of Banking and Finance,
30(8):2257–2279, Aug. 2006.

Neuroph (2010). Java neural network framework. Source:


http://neuroph.sourceforge.net/

Peel, D.A., and Yadav, P.(1995).The time series behavior of spot exchange rates
in the German hyper-inflation period: Was the process chaotic? Empirical
Economics 20 455–463.

Pereira, R., (1999). Forecasting ability but no profitability: An empirical


evaluation of genetic algorithm optimized technical trading rules. MPRA
paper no. 9055.

41
Philip, A. A., Akinwale, A. T. and Akintomide, A. B. (2011) World of Computer
Science and Information Technology Journal (WCSIT) ISSN: 2221-0741
Vol. 1, No. 3,110-118.
Pilbeam, K. (2010). Finance and Financial Markets.Palgrave (ISBN-13 978-
0230233218)

R. Ratcliff. Predicting Nominal Exchange Rate Movements Using Skewness


Information from Options Prices. International Journal of Finance and
Economics, 15(1): 75–92, Jan. 2010.

Raj M., Thurston D. (1996). Effectiveness of Simple Technical Trading Rules in


the Hong Kong Futures Market. Applied Economic Letters 3, 33–36.

Record, Neil (2014) Currency Overlay (Wiley Finance Series)

Rokach, Lior; Maimon, O. (2008). Data mining with decision trees: theory and
applications. World Scientific Pub Co Inc. ISBN 978-9812771711.

Rugman, A.M., Collinson, S., (2006). International business. Prentice Hall, fourth
edition.

Sewell, M., (2007).Technical Analysis. Department of Computer Science,


University College London.

So, M. K. P. , Lam, K. and W. K. Li (1999)., Forecasting exchange rate volatility


using autoregressive random variance model, Applied Financial Economics
9 583–591.

Sullivan R., Timmerman A. White H., (1999). Data-Snooping, Technical Trading


Rule Performance, and the Bootstrap, The Journal of Finance, vol. 54,
issue 5, pp. 1647-1691.

Sweeney R. J. (1988). Some New Filter Rule Tests: Methods and Results. Journal
of what of Financial and Quantitative Analysis 23, 285–301.

Taylor M. P., Allen H. (1992). The Use of Technical Analysis in the Foreign
Exchange Market. Journal of Money and Finance 11, 304–314.

Taylor, M.P. and Allen, H. (1992). The Use of Technical Analysis in the Foreign
Exchange Market. Journal of Money and Finance, Vol.11, pp.304–314.
Taylor, S.J. (1994). Trading futures using a channel rule: A study of the

42
predictive power of technical analysis with currency examples. Journal of
Futures Markets 14:215-235.

Tenti,P., (1996). Forecasting foreign exchange rates using recurrent neural


networks. Applied Artificial Intelligence 10, 567–581.

Trippi, R.R., and D. DeSieno (1992).Trading equity index futures with a neural
network; J Portfolio Management 19 27-33.

43
APPENDIX

SAMPLE TRADING RESULTS

PERFORMANCE REPORT

44
SOURCE CODE
//+------------------------------------------------------------------+
//| Strategy: Newest Strategy.mq4 |
//| Created with EABuilder.com |
//| http://eabuilder.com |
//+------------------------------------------------------------------+
#property copyright "Created by Oyaniyi Lawrence Olanrewaju"
#property link "Matric No. AUO/15BC/0299"
#property version "1.00"
#property description ""

#include <stdlib.mqh>
#include <stderror.mqh>

int LotDigits; //initialized in OnInit


int MagicNumber = 1838136;
double TradeSize = 0.01;
int MaxSlippage = 3; //adjusted in OnInit
bool crossed[1]; //initialized to true, used in function Cross
int MaxOpenTrades = 1;
int MaxLongTrades = 1;
int MaxShortTrades = 1;
int MaxPendingOrders = 1;
bool Hedging = true;
int OrderRetry = 5; //# of retries if sending order returns error
int OrderWait = 5; //# of seconds to wait if sending order returns error
double myPoint; //initialized in OnInit
int sellMethod=0;
int buyMethod=0; //Method used in buy

bool Cross(int i, bool condition) //returns true if "condition" is true and was false
in the previous call
{
bool ret = condition && !crossed[i];
crossed[i] = condition;
return(ret);
}

void myAlert(string type, string message)


{

45
if(type == "print")
Print(message);
else if(type == "error")
{
Print(type+" | Newest Strategy @ "+Symbol()+","+Period()+" |
"+message);
}
else if(type == "order")
{
}
else if(type == "modify")
{
}
}

int TradesCount(int type) //returns # of open trades for order type, current
symbol and magic number
{
int result = 0;
int total = OrdersTotal();
for(int i = 0; i < total; i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() ||
OrderType() != type) continue;
result++;
}
return(result);
}

int myOrderSend(int type, double price, double volume, string ordername)


//send order, return ticket ("price" is irrelevant for market orders)
{
if(!IsTradeAllowed()) return(-1);
int ticket = -1;
int retries = 0;
int err;
int long_trades = TradesCount(OP_BUY);
int short_trades = TradesCount(OP_SELL);
int long_pending = TradesCount(OP_BUYLIMIT) +
TradesCount(OP_BUYSTOP);

46
int short_pending = TradesCount(OP_SELLLIMIT) +
TradesCount(OP_SELLSTOP);
string ordername_ = ordername;
if(ordername != "")
ordername_ = "("+ordername+")";
//test Hedging
if(!Hedging && ((type % 2 == 0 && short_trades + short_pending > 0) ||
(type % 2 == 1 && long_trades + long_pending > 0)))
{
myAlert("print", "Order"+ordername_+" not sent, hedging not allowed");
return(-1);
}
//test maximum trades
if((type % 2 == 0 && long_trades >= MaxLongTrades)
|| (type % 2 == 1 && short_trades >= MaxShortTrades)
|| (long_trades + short_trades >= MaxOpenTrades)
|| (type > 1 && long_pending + short_pending >= MaxPendingOrders))
{
myAlert("print", "Order"+ordername_+" not sent, maximum reached");
return(-1);
}
//prepare to send order
while(IsTradeContextBusy()) Sleep(100);
RefreshRates();
if(type == OP_BUY)
price = Ask;
else if(type == OP_SELL)
price = Bid;
else if(price < 0) //invalid price for pending order
{
myAlert("order", "Order"+ordername_+" not sent, invalid price for pending
order");
return(-1);
}
int clr = (type % 2 == 1) ? clrRed : clrBlue;
while(ticket < 0 && retries < OrderRetry+1)
{
ticket = OrderSend(Symbol(), type, NormalizeDouble(volume, LotDigits),
NormalizeDouble(price, Digits()), MaxSlippage, 0, 0, ordername, MagicNumber,
0, clr);
if(ticket < 0)

47
{
err = GetLastError();
myAlert("print", "OrderSend"+ordername_+" error #"+err+"
"+ErrorDescription(err));
Sleep(OrderWait*1000);
}
retries++;
}
if(ticket < 0)
{
myAlert("error", "OrderSend"+ordername_+" failed "+(OrderRetry+1)+"
times; error #"+err+" "+ErrorDescription(err));
return(-1);
}
string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell
Stop"};
myAlert("order", "Order sent"+ordername_+": "+typestr[type]+"
"+Symbol()+" Magic #"+MagicNumber);
return(ticket);
}

void myOrderClose(int type, int volumepercent, string ordername) //close open


orders for current symbol, magic number and "type" (OP_BUY or OP_SELL)
{
if(!IsTradeAllowed()) return;
if (type > 1)
{
myAlert("error", "Invalid type in myOrderClose");
return;
}
bool success = false;
int err;
string ordername_ = ordername;
if(ordername != "")
ordername_ = "("+ordername+")";
int total = OrdersTotal();
for(int i = total-1; i >= 0; i--)
{
while(IsTradeContextBusy()) Sleep(100);
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;

48
if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() ||
OrderType() != type) continue;
while(IsTradeContextBusy()) Sleep(100);
RefreshRates();
double price = (type == OP_SELL) ? Ask : Bid;
double volume = NormalizeDouble(OrderLots()*volumepercent * 1.0 / 100,
LotDigits);
if (NormalizeDouble(volume, LotDigits) == 0) continue;
success = OrderClose(OrderTicket(), volume, NormalizeDouble(price,
Digits()), MaxSlippage, clrWhite);
if(!success)
{
err = GetLastError();
myAlert("error", "OrderClose"+ordername_+" failed; error #"+err+"
"+ErrorDescription(err));
}
}
string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell
Stop"};
if(success) myAlert("order", "Orders closed"+ordername_+":
"+typestr[type]+" "+Symbol()+" Magic #"+MagicNumber);
}

bool NewBar()
{
static datetime LastTime = 0;
bool ret = Time[0] > LastTime && LastTime > 0;
LastTime = Time[0];
return(ret);
}

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//initialize myPoint
myPoint = Point();
if(Digits() == 5 || Digits() == 3)
{
myPoint *= 10;

49
MaxSlippage *= 10;
}
//initialize LotDigits
double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
if(LotStep >= 1) LotDigits = 0;
else if(LotStep >= 0.1) LotDigits = 1;
else if(LotStep >= 0.01) LotDigits = 2;
else LotDigits = 3;
return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
int ticket = -1;
double price;
bool isNewBar = NewBar();

//Close Long Positions

if (buyMethod==1)
{
if(iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_MAIN, 0) <
iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL, 0) //MACD
< MACD
&& iClose(NULL, PERIOD_H4, 1) < iMA(NULL, PERIOD_H4, 15, 0,
MODE_EMA, PRICE_CLOSE, 0) //Candlestick Close < Moving Average
)
{
if(IsTradeAllowed()){
myOrderClose(OP_BUY, 100, "");

50
buyMethod=0;}
else { //not autotrading => only send alert
myAlert("order", "");}
}
}

//Close Short Positions

if (sellMethod==1)
{
if(iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL, 0)
> 0 //MACD > fixed value
&& iClose(NULL, PERIOD_H4, 1) > iMA(NULL, PERIOD_H4, 15, 0,
MODE_EMA, PRICE_CLOSE, 0) //Candlestick Close > Moving Average
&& iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_MAIN, 0)
> iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL, 0)
//MACD > MACD
)
{
if(IsTradeAllowed())
{
sellMethod=0;
myOrderClose(OP_SELL, 100, "");
}
else //not autotrading => only send alert
{
myAlert("order", "");
}
}

//Open Buy Order

if (buyMethod==0 || buyMethod==1)
{
if(iMA(NULL, PERIOD_CURRENT, 200, 0, MODE_EMA, PRICE_CLOSE, 0) >
iMA(NULL, PERIOD_CURRENT, 88, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving
Average > Moving Average

51
&& iMA(NULL, PERIOD_CURRENT, 88, 0, MODE_EMA, PRICE_CLOSE, 0) >
iMA(NULL, PERIOD_CURRENT, 15, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving
Average > Moving Average
&& iRSI(NULL, PERIOD_CURRENT, 14, PRICE_CLOSE, 0) > 70 //Relative
Strength Index > fixed value
&& iClose(NULL, PERIOD_H4, 1) > iMA(NULL, PERIOD_H4, 15, 0,
MODE_EMA, PRICE_CLOSE, 0) //Candlestick Close > Moving Average
&& iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_MAIN, 0) >
iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL, 0) //MACD
> MACD
&& iMA(NULL, PERIOD_H4, 200, 0, MODE_EMA, PRICE_CLOSE, 0) >
iMA(NULL, PERIOD_H4, 88, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
> Moving Average
&& iMA(NULL, PERIOD_H4, 88, 0, MODE_EMA, PRICE_CLOSE, 0) >
iMA(NULL, PERIOD_H4, 15, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
> Moving Average
&& iClose(NULL, PERIOD_D1, 1) > iOpen(NULL, PERIOD_D1, 1)
//Candlestick Close > Candlestick Open
&& iMA(NULL, PERIOD_D1, 200, 0, MODE_EMA, PRICE_CLOSE, 0) >
iMA(NULL, PERIOD_D1, 88, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
> Moving Average
&& iMA(NULL, PERIOD_D1, 88, 0, MODE_EMA, PRICE_CLOSE, 0) >
iMA(NULL, PERIOD_D1, 15, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
> Moving Average
)
{
RefreshRates();
price = Ask;
if(IsTradeAllowed())
{
buyMethod=1;
ticket = myOrderSend(OP_BUY, price, TradeSize, "");
printf("Method Used", buyMethod);
if(ticket <= 0) return;
}
else //not autotrading => only send alert
myAlert("order", "");
}
}

//Open Sell Order

52
if (sellMethod==0 || sellMethod==1)
{

if(iMA(NULL, PERIOD_CURRENT, 15, 0, MODE_EMA, PRICE_CLOSE, 0) <


iMA(NULL, PERIOD_CURRENT, 88, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving
Average < Moving Average
&& iMA(NULL, PERIOD_CURRENT, 88, 0, MODE_EMA, PRICE_CLOSE, 0) <
iMA(NULL, PERIOD_CURRENT, 200, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving
Average < Moving Average
&& iMACD(NULL, PERIOD_CURRENT, 12, 26, 9, PRICE_CLOSE,
MODE_SIGNAL, 0) < 0 //MACD < fixed value
&& iMA(NULL, PERIOD_H4, 15, 0, MODE_EMA, PRICE_CLOSE, 0) <
iMA(NULL, PERIOD_H4, 88, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
< Moving Average
&& iMA(NULL, PERIOD_H4, 88, 0, MODE_EMA, PRICE_CLOSE, 0) <
iMA(NULL, PERIOD_H4, 200, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
< Moving Average
&& iMACD(NULL, PERIOD_H4, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL,
0) < 0 //MACD < fixed value
&& Close[1] < iMA(NULL, PERIOD_H4, 15, 0, MODE_EMA, PRICE_CLOSE,
0) //Candlestick Close < Moving Average
&& iMACD(NULL, PERIOD_D1, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL,
0) > 0 //MACD > fixed value
&& iMACD(NULL, PERIOD_D1, 12, 26, 9, PRICE_CLOSE, MODE_MAIN, 0)
< iMACD(NULL, PERIOD_D1, 12, 26, 9, PRICE_CLOSE, MODE_SIGNAL, 0)
//MACD < MACD
&& iMA(NULL, PERIOD_D1, 15, 0, MODE_EMA, PRICE_CLOSE, 0) <
iMA(NULL, PERIOD_D1, 88, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
< Moving Average
&& iMA(NULL, PERIOD_D1, 88, 0, MODE_EMA, PRICE_CLOSE, 0) <
iMA(NULL, PERIOD_D1, 200, 0, MODE_EMA, PRICE_CLOSE, 0) //Moving Average
< Moving Average
&& iHigh(NULL, PERIOD_D1, 1) > iMA(NULL, PERIOD_D1, 15, 0,
MODE_EMA, PRICE_CLOSE, 0) //Candlestick High > Moving Average
&& iMACD(NULL, PERIOD_D1, 12, 26, 9, PRICE_CLOSE, MODE_MAIN, 0)
> 0 //MACD > fixed value
)
{
RefreshRates();
price = Bid;

53
if(IsTradeAllowed())
{
sellMethod=1;
ticket = myOrderSend(OP_SELL, price, TradeSize, "");
printf("Method Used", sellMethod);
if(ticket <= 0) return;
}
else //not autotrading => only send alert
myAlert("order", "");
}
}
}
//+--------------------------------------------

54

View publication stats

You might also like