Professional Documents
Culture Documents
For Ex Project
For Ex Project
net/publication/337984522
CITATIONS READS
0 3,246
1 author:
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.
BY
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.
____________________ ___________________
Mr. Ekundayo, S. O.
____________________ ___________________
Prof. L. O. Adetula
____________________ ___________________
ii
DEDICATION
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.
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.
iv
TABLE OF CONTENT
Title page i
Certification ii
Dedication iii
Acknowledgement iv
Table of Content v
Abstract ix
CHAPTER ONE
1.0 Introduction 1
1.4 Methodology 4
CHAPTER TWO
v
2.4 Traditional Forecasting Technique for the Currency Market 13
CHAPTER THREE
3.1 Introduction 21
3.2 Methodology 21
CHAPTER FOUR
4.2 Results 29
4.4 Discussion 32
vi
CHAPTER FIVE
5.1 Summary 33
5.2 Conclusion 33
5.3 Recommendation 34
5.4 Limitation 34
References 35
Appendix 43
vii
LIST OF FIGURES
LIST OF TABLES
viii
ABSTRACT
ix
CHAPTER ONE
INTRODUCTION
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.
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).
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.
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.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
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.
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).
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.
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).
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).
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.
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).
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).
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).
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.
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
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).
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).
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
Yes
IS STOP LOSS HIT?
No
24
STOP
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)
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?
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
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
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
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
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
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.
Appel, Gerald (1999). Technical Analysis Power Tools for Active Investors.
Financial Times Prentice Hall. pp. 166.
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.
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.
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.
Diebold. F.X. and Nason, J.A., (1990). Nonparametric exchange rate prediction.
Journal of International Economics 28 (1990) 315–322.
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.
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.
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.
Lento, C., Gradojevic, N., (2007). The profitability of technical trading rules: a
combined signal approach. Journal of applied business research, volume
23, number 1.
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.
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.
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)
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.
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.
Trippi, R.R., and D. DeSieno (1992).Trading equity index futures with a neural
network; J Portfolio Management 19 27-33.
43
APPENDIX
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>
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);
}
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);
}
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);
}
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();
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", "");}
}
}
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", "");
}
}
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", "");
}
}
52
if (sellMethod==0 || sellMethod==1)
{
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