SlideShare a Scribd company logo
1 of 103
Download to read offline
MECN4005 – Design Project
Agent Based Simulation of the JSE
Name: Ashail Maharaj
Student Number: 536684
Supervisor: Dr Ian Campbell
2 November 2016
A project report submitted to the Faculty of Engineering and the Built Environment, University
of the Witwatersrand, Johannesburg, in partial fulfilment of the requirements for the degree of
Bachelor of Science in Engineering.
Johannesburg, November 2016
ii
DECLARATION
UNIVERSITY OF THE WITWATERSRAND, JOHANNESBURG
SCHOOL OF MECHANICAL, INDUSTRIAL AND
AERONAUTICAL ENGINEERING
I Ashail Maharaj Student Number: 536684, am registered for the course No. MECN 4005 - in the
year 2016.
I herewith submit the following task, “Design Project: Agent Based Simulation of The JSE” in partial
fulfilment of the requirements of the above course.
I hereby declare the following:
 I am aware that plagiarism (the use of someone else’s work without their permission and/or
without acknowledging the original source) is wrong;
 I confirm that the work submitted herewith for assessment in the above course is my own
unaided work except where I have explicitly indicated otherwise;
 This task has not been submitted before, either individually or jointly, for any course
requirement, examination or degree at this or any other tertiary educational institution;
 I have followed the required conventions in referencing the thoughts and ideas of others;
 I understand that the University of the Witwatersrand may take disciplinary action against me
if it can be shown that this task is not my own unaided work or that I have failed to acknowledge
the sources of the ideas or words in my writing in this task.
Signature: ________________________________ Date: 2/11/2016
iii
EXECUTIVE SUMMARY
This project focuses on the simulation of trading on the Johannesburg Stock Exchange (JSE). For the
purpose of this project, one share had been selected to be traded in the simulation. The share that was
chosen was Richemont CFR, which is one of the top five companies listed on the JSE. The simulation
designed in this report initially aimed at modelling the share price as a function of multiple factors, the
factors that were initially considered were:
 Fundamental pricing information including dividends.
 Distribution of knowledge.
 Economic conditions such as exchange rate, overseas market closing levels, inflation, interest
rates and commodity prices that may be correlated to the share.
 Market perceptions of the company including company ethics.
 Risk profiles and time views (e.g. buy and hold, day trading, etc.)
 Competition and alternatives in the market.
 Financial level (and size of trades).
Prior research found that only the volume traded was strongly correlated to the share price. The volume
traded however showed strong correlations with the Rand-Euro and Rand-Dollar exchange rate as well
as the platinum price. This finding led to the idea of modelling the market through supply and demand
due to the strong relationship between the share price and volume traded.
After concept selection was done, simplifying assumptions were made to start building the model. The
chosen model had agents that entered the market, and made decisions on whether to buy or sell a share.
This decision was based on whether their intrinsic value was less than or greater than the market value.
If the intrinsic value was greater, then the agent would buy. If the intrinsic value was less, the agent
would sell.
The model was then broken down into two major components, namely the agent and the trading system.
The agent logic comprised of agent decisions to transact, intrinsic value estimation, agent logic and the
agent attributes. The trading system was broken down into the matching of orders, exchange of shares
and cash, expiration of orders, maintaining trading hours and creating an overreaction in the market.
While validating the components, it was found that the neural network function created in Anylogic,
which was used for the estimation of the intrinsic value for the agents, did not perform as required,
although it was still responsive and changed values with given inputs. Using the neural network resulted
in incorrect values which did not change much from day to day. The model was also found to be too
slow if too many agents were used. Validating the model using historic data was not possible as the
simulation created very high frequency intraday data, for which actual data was not available.
iv
However, as part of the validation, the simulations’ price series was tested to see if the presence of
stylized facts existed. These stylized facts show that the model can represent reality to some degree.
This resulted in the finding that the returns were non-normally distributed and leptokurtic. It was then
recommended that a software called Matlabcontrol should be used to link Matlab with Anylogic. Using
as this would allow the user to get exactly the function created in Matlab. A number of other
recommendations pertaining to the decision logic and further building of the model, to make it more
realistic, were noted in Section 9.
v
Acknowledgements
I would like to acknowledge and thank my parents for always supporting me, no matter the
circumstance.
I would also like to thank Dr Ian Campbell for supervising me through this period. His guidance and
advice has been invaluable to me.
vi
TABLE OF CONTENTS
DECLARATION....................................................................................................................................ii
ACKNOWLEDGEMENTS....................................................................................................................v
TABLE OF CONTENTS.......................................................................................................................vi
LIST OF FIGURES ................................................................................................................................x
LIST OF TABLES...............................................................................................................................xiii
1. INTRODUCTION ..........................................................................................................................1
1.1 Background.............................................................................................................................1
1.2 Motivation...............................................................................................................................2
1.3 Task as given...........................................................................................................................3
1.4 Task as understood..................................................................................................................3
2 LITERATURE REVIEW ...............................................................................................................4
2.1 Agent based Simulation ..........................................................................................................4
2.2 Discrete Event Simulation ......................................................................................................4
2.3 System Dynamics Simulation.................................................................................................4
2.4 Johannesburg Stock exchange ................................................................................................5
2.5 Option trading.........................................................................................................................5
2.6 Double auction market............................................................................................................5
2.7 Limit order book .....................................................................................................................5
2.7.1 Limit order ......................................................................................................................5
2.7.2 Market order....................................................................................................................6
2.8 Supply and Demand................................................................................................................6
2.9 Market Efficiency ...................................................................................................................9
2.10 Martingales .............................................................................................................................9
2.11 Stylized facts...........................................................................................................................9
2.12 Agent Learning and Artificial Intelligence ...........................................................................10
2.12.1 Neural Networks ...........................................................................................................10
2.12.2 Feed-Forward Back Propagation (FFBP) neural network.............................................11
vii
2.12.3 Fuzzy Logic ..................................................................................................................13
2.12.4 Genetic Algorithms.......................................................................................................13
2.13 Fundamental analysis............................................................................................................13
2.14 Technical Analysis................................................................................................................14
2.14.1 Trend Analysis..............................................................................................................15
2.14.2 Support and Resistance Analysis ..................................................................................15
2.14.3 Volume Analysis...........................................................................................................15
2.15 Kurtosis.................................................................................................................................16
2.16 Skewness...............................................................................................................................17
2.17 Normality..............................................................................................................................17
2.18 Stationarity............................................................................................................................18
2.18.1 Difference stationarity...................................................................................................18
2.18.2 Trend Stationarity .........................................................................................................18
2.18.3 Difference and Trend Stationary...................................................................................18
2.18.4 Testing for Trend stationarity and Difference Stationarity...........................................18
2.19 Homoscedasticity..................................................................................................................20
2.19.1 Engle test for residual heteroscedasticity......................................................................20
2.20 Random Walk Hypothesis ....................................................................................................20
2.20.1 Pure Random Walk.......................................................................................................20
2.20.2 Random walk with drift ................................................................................................21
2.20.3 Deterministic trend........................................................................................................21
2.20.4 Random walk with drift and deterministic trend...........................................................21
2.21 Related studies ......................................................................................................................21
2.21.1 Chan et al. 1999 ............................................................................................................21
2.21.2 Preyen Nair 2014 .........................................................................................................22
3 HIGH LEVEL PRODUCT REQUIREMENT SPECIFICATION ...............................................23
3.1 Requirements ........................................................................................................................23
3.2 Constraints ............................................................................................................................23
3.3 Criteria ..................................................................................................................................23
viii
3.4 Assumptions..........................................................................................................................23
4 CONCEPT GENERATION..........................................................................................................24
4.1 Concept Creation ..................................................................................................................26
4.1.1 Concept 1 ......................................................................................................................27
4.1.2 Concept 2 ......................................................................................................................28
4.1.3 Concept 3 ......................................................................................................................29
4.2 Concept Selection .................................................................................................................30
5 THE DESIGN PROCESS.............................................................................................................33
6 DESIGN DEVELOPMENT OF THE MODEL ...........................................................................34
6.1 Agents (Traders) ...................................................................................................................34
6.1.1 Product Requirement Specification...............................................................................34
6.1.2 Concept Development and Specification......................................................................35
6.1.3 Validation......................................................................................................................44
6.2 Trading platform ...................................................................................................................59
Product Requirement Specification...............................................................................59
Concept Development and Specifications ....................................................................60
6.2.2 Validation......................................................................................................................69
6.3 Assumptions Made for the Model.........................................................................................78
6.4 Limitations of the model.......................................................................................................79
7 VALIDATION OF MODEL’S PERFORMANCE AS A WHOLE.............................................79
8 CRITICAL ANALYSIS OF DESIGN..........................................................................................82
8.1 Comparing Completed model with the criteria.....................................................................83
8.1.1 Accuracy of prediction..................................................................................................83
8.1.2 Data Presentation and collection...................................................................................83
8.1.3 Ease of use ....................................................................................................................83
8.1.4 Speed.............................................................................................................................83
8.1.5 Realistic behaviour........................................................................................................83
8.1.6 Ease of creating the concept in Anylogic......................................................................83
8.1.7 Modular building and interactions ................................................................................83
ix
8.2 Shortcomings in representing the market..............................................................................84
9 RECOMMENDATIONS..............................................................................................................84
9.1 Representing the market........................................................................................................84
9.2 Neural network......................................................................................................................84
10 REFERENCES .........................................................................................................................85
APPENDIX A:......................................................................................................................................90
x
LIST OF FIGURES
Figure 1: Demand Relationship[15]........................................................................................................6
Figure 2: Supply Relationship[15]..........................................................................................................7
Figure 3: Economic Equilibrium [15].....................................................................................................7
Figure 4: Excess Supply[15]...................................................................................................................8
Figure 5: Excess Demand [15]................................................................................................................8
Figure 6: Graphical Explanation of Kurtosis and Skewness[21]..........................................................10
Figure 7: Perceptron Configuration[28]................................................................................................11
Figure 8: Moods of the masses according to technical analysis[38].....................................................14
Figure 10: Concept 1 Flow Chart..........................................................................................................27
Figure 11: Concept 2 Agent State Chart ...............................................................................................28
Figure 12: Concept 2 Activity Cycle Diagram .....................................................................................28
Figure 13: Concept 3 Agent State Chart ...............................................................................................29
Figure 14: Concept 3 Activity Cycle Diagram .....................................................................................30
Figure 15: Agent Logic Flowchart........................................................................................................37
Figure 16:Flowchart for Decisions to Buy or Sell ................................................................................38
Figure 17: Flowchart of the general logic for creation of Intrinsic Value ............................................39
Figure 18: Flowchart of the Feedforward Back Propagation used to create a function in Anylogic....40
Figure 19: Structure of neural network used in Matlab ........................................................................41
Figure 20: An Increase in Demand [64]................................................................................................42
Figure 21: Flowchart of The Logic Used for The Buy and Sell Buttons Which Are Used to Represent
an Overreaction in The Market .............................................................................................................43
Figure 22: Validation that Changing of states occurs...........................................................................44
Figure 23: Validation That the Share Price is Never Below Zero ........................................................45
Figure 24:Validation That the Minimum Amount of Shares an Agent Can Hold is Zero....................45
Figure 25:Validation That Cash held is Always Positive .....................................................................46
Figure 26:Validation That Cash Never Goes Below Zero....................................................................46
Figure 27: Validation That the Number of Shares in The System Stays Constant Throughout ...........47
Figure 28: Screenshot of Simulation Before Pressing Buy Button.......................................................48
Figure 29:Screenshot of Simulation After Pressing Buy Button ..........................................................48
Figure 30: Screenshot of Simulation Before Pressing Sell Button .......................................................49
Figure 31: Screenshot of Simulation After Pressing Sell Button..........................................................49
Figure 32: Screenshot of simulation before (left side) and after (right side) pressing Buy Now button
..............................................................................................................................................................50
Figure 33: Screenshot of simulation before (left side) and after (right side) pressing Sell Now button
..............................................................................................................................................................51
xi
Figure 34: Screenshot of Simulation Before (Left Side) And After (Right Side) Increasing the Share
Price ......................................................................................................................................................52
Figure 35: Screenshot of Simulation Before (Left Side) And After (Right Side) Decreasing the Share
Price ......................................................................................................................................................52
Figure 36: Plot of Output and Error of Feed Forward Backpropagation Neural Network as well as the
Actual Data ...........................................................................................................................................53
Figure 37:R2
Values Between Target and the Output of the Neural Network, for the Training,
Validation, Test and All 3 Runs............................................................................................................54
Figure 38: Sum Squared Error for training, testing and validation runs...............................................54
Figure 39: Validation of Neural Network Using Newer Data ..............................................................54
Figure 40: Screenshot of Simulation Before (Left Side), After Decreasing (Middle) and After Increasing
(Right) the Platinum Price ....................................................................................................................55
Figure 41: Screenshot of Simulation Before (Left Side), After Increasing (Middle) and After Decreasing
(Right) the Rand-Dollar Exchange Rate...............................................................................................56
Figure 42: Screenshot of Simulation Before (Left Side), After Increasing (Middle) and After Decreasing
(Right) the Rand-Euro Exchange Rate..................................................................................................56
Figure 43: Output from neural network in Matlab................................................................................57
Figure 44:Inputs and output to neural network in Anylogic.................................................................57
Figure 45:Price Sensitivity to Platinum Price.......................................................................................58
Figure 46: Price Sensitivity to Change in the Rand-Euro Exchange Rate............................................58
Figure 47:Price Sensitivity to Rand-Dollar Exchange Rate..................................................................58
Figure 48: Queuing System Used in Model..........................................................................................60
Figure 49: Flowchart of The Logic Used for The Exchange of Share and Money...............................61
Figure 50: Calculations Done in The False Then False Action Box in The Flowchart of The Logic Used
for The Exchange of Shares and Money...............................................................................................62
Figure 51: Calculations Done in The False Then True Action Box in The Flowchart of The Logic Used
for The Exchange of Shares and Money...............................................................................................62
Figure 52: Calculations Done in The True Action Box in The Flowchart of The Logic Used for The
Exchange of Shares and Money............................................................................................................63
Figure 53: Flowchart of The Expiration of Orders ...............................................................................64
Figure 54: Screenshot of The Trading Hours Schedule........................................................................65
Figure 55: Screenshot of the “TradingHours” Parameter .....................................................................66
Figure 56: Screenshot of “event1”........................................................................................................67
Figure 57: Screenshot of the Logic Used in the “EvalEvent” Function................................................68
Figure 58: Screenshot of the SelectOuput4 logic..................................................................................68
Figure 59: Screenshot of the Queuing System Used in the Model .......................................................69
xii
Figure 60:Validation That Continuous Match Will Occur till The Entire Number of Shares to Trade Has
Been Traded..........................................................................................................................................70
Figure 61: Screenshot of Simulation Before Agent Buys Shares .........................................................73
Figure 62: Screenshot of Simulation After Agent Buys Shares............................................................74
Figure 63: Screenshot of Simulation Before Agent Sells Shares..........................................................75
Figure 64: Screenshot of Simulation After Agent Sells Shares ............................................................76
Figure 65: Validation That After Expiry Agents Leave the Matching Queue......................................77
Figure 66: Validation That After Trading Hours No Shares are Traded ..............................................78
Figure 67: Frequencies of The Share Prices from The Simulation Model............................................82
Figure 68: Frequency Plot of the Returns .............................................................................................82
xiii
LIST OF TABLES
Table 1: Agent logic for price, logic and order types[2].......................................................................22
Table 2: Concept Creation Matrix ........................................................................................................26
Table 3: Concept Rating Table .............................................................................................................30
Table 4: Summary of Data from Buying Screenshots ..........................................................................71
Table 5: Summary of Data from Selling Screenshots...........................................................................72
Table 6: Comparison of Model Data with Actual Data ........................................................................80
Table 7: Summary of tests done on the outputs of the simulation........................................................81
1
1. INTRODUCTION
1.1 Background
A stock market is a network of buyers and sellers, each of whom are trading stocks. Stocks represent a
shareholding in the company that issued the share. Companies issue shares to raise capital, and initially
the stock is valued by the amount of capital require divided by the number of shares issued. The capital
is exchanged for holdings in the company.
This project focuses around the simulation of the trading that occurs on the JSE. For the purpose of this
project, one share has been selected to be traded in the simulation. The share that was chosen is
Richemont CFR which is listed in the top five companies on the JSE. The simulation designed in this
report initially aimed at modelling the share price as a function of multiple factors. The factors that were
initially considered were:
 Fundamental pricing information including dividends.
 Distribution of knowledge.
 Economic conditions such as exchange rate, overseas market closing levels, inflation and
interest rates as well as commodity prices that may be correlated to the share.
 Market perceptions of the company including company ethics.
 Risk profiles and time views (e.g. buy and hold, day trading, etc.)
 Competition and alternatives in the market.
 Financial level (and size of trades).
The project was then split into two components. The first being the research of factors that correlated
with the share price, which was prior research to the design of the simulation. In the research, it was
found that the Richemont share price was only strongly correlated to the volume traded. The volume
traded however showed strong correlations with the Rand-Euro and Rand-Dollar exchange rate as well
as the platinum price.
Upon finding this, the idea for the simulation had changed from the all-encompassing view to trying to
model the share price as a function of its volume, while using the other factors to forecast the share
price.
2
1.2 Motivation
The modelling of a market generally requires theories to understand how the entire market will react.
The agent-based approach to simulating a market requires basic logic that can vary from trader to trader.
Each of these traders’ logic then create reactions in the market. This is why neuroeconomics is useful.
Neuroeconomics is an interdisciplinary field that provides explanation behind the motivation of
individuals’ actions. The study of this allows for the individualism of entities to be taken into account
when modelling complex systems. For modelling these complex systems using neuroeconomics, agent-
based simulations are becoming more widely used.
One of the fields of interest for the application of agent-based simulations is the social science of
economics. Economics is defined as the study of production and trade. One of the fundamentals upon
which economics was based is the theory of supply and demand. This theory tries to create an
understanding about how buyers and sellers interact, how they make their choices according to the
quantities demanded and supplied, and how price is affected by these interactions. This design project
tries to incorporate economics of financial markets with the individualistic decision making that
neuroeconomics studies by creating an agent based model of a financial market.
Forecasting and modelling of financial markets have led to interesting discussions about accuracies and
the ability of a model to explain certain aspects of real markets. These aspects have come to be known
as stylised facts. Recently the growing trend in artificial intelligence and automation have also led to
the creation of interesting ideas such as the algobot. An algobot is a programme that makes decisions
on whether to place orders to buy or sell shares, how long to hold for or even when to buy or sell shares.
The concept of algobots, is what inspired this project.
Having an algobot does not necessarily mean that it be correct all the time. As seen with most AI
algorithms, training is needed before prediction can become accurate. This could be a problem as
inaccuracy in training could lead to financial losses. To avoid these risks, a simulation of a market that
could represent reality would be a good place to train an algobot or to test different trading strategies.
Drawing on all of the above mentioned, the idea of creating a simulation model, that could model
individual decisions based on their perception of a share and other environmental factors, was created.
3
1.3 Task as given
Design, build and validate a market model of a financial trading market. The model should encompass
the influential factors which affect the market. Agent-based simulation will be used to simulate the
individual interactions of traders.
1.4 Task as understood
Design an agent-based simulation of a financial trading market. The market will be driven by the factors
within the market such as price, demand and supply of shares, and external environmental factors.
Seeing as the scope of the task is large, there will be justified simplifying assumptions made so that the
project can be completed in the time given. The simulation will be built as a foundation to creating a
more complex market structure. The factors that will be considered in the external environment are the
Platinum price(R/oz.), Rand-Euro exchange rate and the Rand-Dollar exchange rate.
The above factors were chosen due to prior research which had found a strong correlation between the
volume traded and the Richemont share price. The relationship between the volume traded had strongly
negative correlations to the factors mentioned above. Therefore, this simulation is an attempt to model
the share price based on volume traded, while trying to model the volume traded with the external
environmental factors. [1]
Due to the nature of this problem, a supply-demand formulation will be applied to this model. Where
the price will move to try to reach an equilibrium point. Validation of the model will include comparison
to the Richemont share price, comparing the volume traded with the share price to ensure that the
volume traded is creating changes in the share price, and ensuring that agents are making choices
according to the environmental factors.
4
2 LITERATURE REVIEW
2.1 Agent Based Simulation
Agent based simulation is a method used for modelling complex scenarios which involve individual
decision making and interactions between individuals. Agent based models may combine elements of
game theory, complex systems, emergence or evolutionary programming. Agents may also use artificial
intelligence in their decision-making processes to learn over time[2]. Agent based models have three
elements [3]:
1. Self-contained, autonomous agents with attributes and behaviour
2. Interaction between agents
3. An environment in which the agents can interact with each other and the environment
Agent based simulations are used in a wide variety of fields. Fields including economics, finance,
military planning, city management, traffic simulations, routing problems and most social sciences.
Simulations are used to test a hypothesis by changing factors in the real world, as this cannot be done
feasibly, it is best to test these in a simulation. ABMs are also used to confirm theoretical results or
when a problem is too complex to be solved analytically[3], [4].
2.2 Discrete Event Simulation
A discrete event simulation is a method of explaining behaviour of a complex system as a sequence of
ordered events. Discrete event simulations are stochastic as each of the events that occur introduce
randomness to the system. A discrete event simulation must include the following properties[5], [6]:
1. Predetermined starting and ending points
2. A method of keeping track of the time that has passed since the start of the process.
3. A list of events that have occurred
4. A list of events that are expected
2.3 System Dynamics Simulation
System dynamics is used to understand nonlinear complex systems over time using feedback loops,
stocks and flows. When modelling system dynamics it is recommended that one[5] :
 models the system as a causally closed structure which defines its own behaviour
 discovers the circular causality balancing or reinforcing
 identifies stocks and flows that affects the system
5
2.4 Johannesburg Stock Exchange
The Johannesburg Stock Exchange (JSE) is the 19th
largest stock exchange in the world and the largest
in Africa, by market capitalisation. The JSE offers secure and efficient primary and secondary capital
markets across a diverse range of securities[7]. The JSE provides a market where securities can be
traded and regulated. The exchange raises primary capital by channelling cash resources into productive
economic activity.
2.5 Option Trading
An option is a contract which gives the buyer the right to buy or sell an asset at a specified price before
a specified date. There are two types of options, namely; calls and puts. A put order gives the holder
the option to sell their assets at a given price within the period stipulated by the contract. The buyer of
a put hopes that the stock falls before the option expires. A call order gives the holder the option to buy
an asset at a given price within the specified period. The buyer of the call hopes that the stock increases
before the option expires[8].
2.6 Double Auction Market
A double auction market is the system which is used to buy and sell securities through brokers on stock
exchanges. The double auction market consists of many buyers and many sellers[9]. In a double auction
market buyers and sellers enter competitive offers with their orders, as opposed to the over the counter
method which uses negotiation to reach a deal. Double auction markets can also use the outcry method,
which is characterised by buyers and sellers calling out prices till a transaction occurs when a buyer and
a seller call out the same price[10].
2.7 Limit Order Book
A limit order book is a list of unexecuted limits orders which is maintained by a member of the stock
exchange, who acts as the market maker. This member posts the bid and ask prices, manages limit
orders and executes trades between the buyers and sellers. It is the duty of the market maker to ensure
that during large movements in the demand or supply, it reaches an equilibrium. If not for this market
maker, prices would rise or fall during large movements in the demand and supply respectively[11].
2.7.1 Limit Order
A limit order, as the name states, is an order that states the limit that the buyer or seller is willing to
trade at. For example, if a buyer wants to buy a share at a maximum price of R2 per share, he will place
a buy limit order. A sell limit sets the minimum price the seller is willing to sell at[12]. Limit orders
have to have an expiration date which is usually a 90-day period at maximum.
6
2.7.2 Market Order
A market order is an order that is made immediately at the best available current price. In the trading
system, a market order is guaranteed to be executed as there are no time constraints like options or price
restrictions as there are with limit orders. For this reason, the market order is also known as an
unrestricted order. There is also one other difference between the order limit and the market order, this
is the price of the transaction. In general, the price of a limit order transaction is higher than the cost of
the market order. It is also important to note that is some markets, market orders are not allowed.[13],
[14]
2.8 Supply and Demand
Supply is defined as the quantity of a commodity that is available to be sold in a market. Demand is
defined as the total quantity of a commodity that is wanted by the traders in the market. Supply and
demand are the fundamentals behind the study of a market economy. The law of demand states that
there is a negative relationship between price and the quantity demanded. In Figure 2 the relationship
between price and quantity for demand is shown. The law of demand basically states that as the price
of some commodity decreases; the more people would want to buy.
Figure 1: Demand Relationship[15]
The law of supply, has a positive relationship between the price and the quantity. This is due to suppliers
seeing higher opportunity at higher prices, this results in more suppliers wanting to sell. In Figure 2, the
relationship between price and quantity supplied is shown.
7
Figure 2: Supply Relationship[15]
Economic equilibrium is said to be reached when the quantity supplied and the quantity demanded are
equal. As seen in Figure 3, when the quantities of supply meet that of the demand there is a single price
that the commodity is worth. The equilibrium can only be reached in theory and as a result the price
keeps fluctuating.
Figure 3: Economic Equilibrium [15]
When the market is not in equilibrium there are two possibilities that could occur, excess demand or
excess supply. If the price is set too high, an excess in supply will be created as the buyers would not
want to buy and the sellers would want to sell. In Figure 4, it can be seen that an excess supply is created
by both, the buyers and sellers moving away from the equilibrium point due to the high price. In order
to reach equilibrium, the price of the commodity would need to decrease. This can be seen by shifting
the the price till the supply line meets the demand line.
8
Figure 4: Excess Supply[15]
On the other extreme, if the price is too low, the quantity supplied would decrease and the quantity
demanded would increase. As seen in Figure 5, shifting the price upward would allow the market to
reach equilibrium.
Figure 5: Excess Demand [15]
It is also important to note that the demand and supply curves can both be shifted, keeping the price
constant but changing the quantity and thus creating a new equilibrium relationship. These shifts can
be created on the demand due to the lack of substitutable commodities and as a result people are willing
to pay the set price. A change in supply would result from a shortage of sellers in the market [14].
Supply and demand relationships can be exploited to understand markets, for example most share prices
are highly correlated with the volume traded, this is often seen by chartists.
9
2.9 Market Efficiency
Market efficiency is derived from the Efficient Market Hypothesis (EMH), which states that at any
given time, the prices fully reflect all available information on the stock or market involved. There are
three degrees of efficiency in the market[16]:
1. Strong Efficiency
This states that all information about the stock or the market are accounted for in the stock price and
that insider information wouldn’t even give the trader an advantage.
2. Semi-Strong Efficiency
This form of the EMH states that all public information about the stock or market are included in the
share price and that technical or fundamental strategies would not give the user superior gains.
3. Weak Efficiency
This type of EMH states that all of the previous prices of the price series are reflected in the stock price
currently and therefore technical analysis would not gain the user an advantage in beating the market.
2.10 Martingales
The martingale property states that the conditional expectations of a sequence of partial sums is its
current value. The martingale property ensures that, in a fair game, knowledge of the past is of no use
to predicting the future outcomes[17].
2.11 Stylized Facts
A stylised fact refers to empirical findings that are consistent across different instruments, markets and
time periods. Stylised facts are presented as a truth or a generalisation about the properties of the subject
matter. Theories and model must fit these empirical findings in order to validly explain these
phenomena, the absence of these empirical finding may then be attributed to inaccuracies in the theories
or models[18], [19].
Some of the stylized facts relating to share price prediction are[20];
1. Non-Normal Return Distributions
This can be tested by doing a Kolmogorov-Smirnov test to check whether the distribution is normal or
not. The kurtosis and skewness need to be tested. Kurtosis above a value of 3 is known to be leptokurtic
whereas kurtosis below 3 is said to be platykurtic. In Figure 6 below the shapes of the graphs are shown
for each of the skewness and kurtosis cases. Skewness can also be measured to indicate if the return
data is identically distributed.
10
Figure 6: Graphical Explanation of Kurtosis and Skewness[21]
2. Volatility clustering of returns
Volatility clustering, as defined by Benoit Mandelbrot, refers to “large changes in returns tend to follow
large changes in returns” and that “small changes in returns would be followed by small changes in
returns” [22]. This can be tested by testing if the returns are autocorrelated followed by testing if the
series is heteroscedastic using the Engle’s ARCH test[23].
3. High and persistent trading volume
4. Existence of technical trading
2.12 Agent Learning and Artificial Intelligence
Artificial intelligence is defined as intelligence displayed by computer programs or machines. It also
generally describes the ability of a non-living entity to exhibit cognitive ability. Cognitive ability is
generally defined by problem solving and learning abilities. The field draws on knowledge from the
computer science, mathematics, psychology, linguistics, philosophy, neuroscience and artificial
psychology backgrounds. Commonly used AI algorithms are; Neural networks, decision trees, fuzzy
logic and genetic algorithms[24].
2.12.1 Neural Networks
A neural network is derived from the way biological nervous systems process information. Neural
networks are large networks that connect inputs to outputs using links. Each link has its own weight
which changes as the neural network is trained (this is synonymous to learning as it is trial and error,
until the correct method is learnt from previous mistakes or errors). Just like in the brain, training helps
11
improve connections between the nodes in order to better the result. Figure 7 shows the structure of a
perceptron neural network, note that there are three layers; an input layer, hidden layer and an output
layer. Between the input and the hidden layers are connections and each connection has a weight
annotated by the letter w. Weights are also found on the connections between the hidden layer and the
output layer[25]–[27].
Figure 7: Perceptron Configuration[28]
For the purpose of this report only one type of neural networks is specifically important, this is the Feed
Forward Back Propagation (FFBP) method.
2.12.2 Feed-Forward Back Propagation (FFBP) Neural Network
The FFBP neural network is identical to the neural network in Figure7. The calculations required by
the neural network, assuming that there are no biases, that the delta learning rule is applied and that the
inputs and outputs are scaled between 0 and 1, are listed below.
 Step 1
Create a set of weights between the values of 0.2 and 0.8 for the all the connections in the network.
 Step 2
Calculate the effective input into the hidden layer using Equation 1.
𝑆ℎ = ∑(𝑥𝑖×𝑤𝑖ℎ)
𝑛
𝑖=1
(1)
Where
𝑆ℎ is the Effective input
𝑥𝑖 is the input of the network
𝑤𝑖ℎ is the matrix of weights between input i and hidden node h
12
 Step 3
Calculate the outputs of the hidden layer using Equation 2. This uses the log sig activation function as
the inputs and outputs are between 0 and 1.
𝑌ℎ =
1
1 + 𝑒−𝑆ℎ
(2)
Where
𝑌ℎ is the vector of outputs from the hidden layer
 Step 4
Calculate the outputs of the neural network using Equation 3.
𝑌𝑜 = ∑(𝑦ℎ×𝑤ℎ𝑜)
𝑛
𝑖=1
(3)
Where
𝑌𝑜 is the vector of outputs from the neural network.
 Step 5
Calculate the error between the target and the output of the neural network using Equation 4.
𝑒𝑟𝑟𝑜𝑟 = 𝑡𝑎𝑟𝑔𝑒𝑡 − 𝑌𝑜 (4)
 Step 6
Adjust the weights between the outputs and the hidden layer using Equation 5 to find the amount that
the weights need to be adjusted by and Equation 6 to update the weights.
∆𝑤ℎ𝑜 =∝ (𝑒𝑟𝑟𝑜𝑟)×𝑌ℎ (5)
𝑤ℎ𝑜 = 𝑤ℎ𝑜 + ∆𝑤ℎ𝑜 (6)
Where
∆𝑤ℎ𝑜 is the amount that the weights need to be updated by
∝ is the learning rate, usually set to 0.5
13
 Step 7
Update the weights between the input and the hidden layer using Equation 7 to calculate the error,
Equation 8 to calculate the amount that the weights need to updated by and Equation 9 to calculate the
and update the weights.
𝛿ℎ = 𝛿 𝑜× (∑ 𝑤ℎ𝑜) ×2×𝑌ℎ×(1 − 𝑌ℎ) (7)
∆𝑤𝑖ℎ =∝×𝛿ℎ×𝑥𝑖 (8)
𝑤𝑖ℎ = 𝑤𝑖ℎ + ∆𝑤𝑖ℎ (9)
Where
𝛿ℎ is the error propagated back to the connections between the input and the hidden layer
𝛿 𝑜 = error
2.12.3 Fuzzy Logic
Fuzzy logic makes use of degrees of truth rather than having Boolean decisions. For example, making
use of fuzzy logic helps generate truth about agents belonging to a number of states rather than strictly
one. A good example of this is having hard logic of whether an object is hot or cold compare to having
fuzzy logic with states that lay between the two, warm, room temperature or cool[24], [27], [29]–[31].
2.12.4 Genetic Algorithms
Genetic algorithms are used for solving constrained and unconstrained optimisation problems. They ae
based upon the process of natural selection, in which only the strongest survive and pass their genetics
to the future generation. Genetic algorithms are used in agent based simulations to get populations that
are more adapted to the situations that occurred in the past. The ability of an agent to survive is measured
by the fitness of each agent. In the context of a financial market, genetic algorithms could be used to
identify which strategies are most suited to which situations in the market [23], [26], [31], [32].
2.13 Fundamental analysis
Fundamental analysis is a method of evaluating the value of a share through company performance and
reactions to economic conditions. Fundamental analysis seeks to understand more about the company
and the actions taken by the company to essentially answer the question “Does the company make a
good investment?”. [34]
Fundamental analysis is not limited to using purely qualitative or purely quantitative data. News about
a company can usually be helpful in evaluating a company. Quantitative analysis usually includes
14
looking at the company’s finances to create an intrinsic value of the share. Revenue, debt, dividends,
and company performance ratios are used to measure intrinsic value [35].
The objectives of fundamental analysis are [36]:
 To predict the performance of economies that impact a company. This is done because the financial
performance of the company is dependent upon the economy is resides within.
 To estimate the intrinsic value of the stock and try to predict when changes in this value will occur.
 To select the right time to buy and sell stocks to maximise investment returns.
2.14 Technical Analysis
Technical analysis is the analysis of statistics generated by market activity. These statistics are generally
past prices or volumes traded[37]. The aim of technical analysis is to identify patterns that can suggest
future activity. Technical analysis typically depends on the use of charts patterns, technical indicators,
oscillators or some combination of the above mentioned[38]. Technical analysts believe that charts
show the moods of the crowds and therefore focus on the analysis of mass human psychology.
Emotional risk is inversely correlated to financial risk; Figure 1 below displays the moods associated
with the different price trends.
Figure 8: Moods of the masses according to technical analysis[38]
People are generally motivated by greed and optimism when buying and are driven by fear or pessimism
when selling. It is believed that people formulate scenarios based on their emotional state in order to
rationalise their emotions. Investors will try to sell at the top or as close to the top, and buy at the bottom
or as close to the bottom as possible[38].
15
2.14.1 Trend Analysis
Trend analysis is one of the most important and most used techniques in technical analysis. In trend
analysis, trends are classified according to their direction into three sets; uptrends, horizontal trends and
downtrends. An uptrend is characterised by a series of higher highs and higher lows whereas a
downtrend is characterised by lower lows and lower highs[39][38].
Trends can then be classified into a further set of three; a long-term trend, an intermediate trend and a
short-term trend. A long-term trend is one that last longer than a year, an intermediate trend lasts
between one and three months and a short-term trend is considered to last up to a month. Channel lines
are the addition of two parallel trend lines which act as areas of support and resistance[38].
2.14.2 Support and Resistance Analysis
Support is defined as the price level which the stock seldom falls below and resistance is the price level
which the stock seldom increases above. Support and resistance are governed by the psychology behind
supply and demand. Where the support is the price level which the market is willing to buy at and the
resistance level is the price at which the market is willing to sell at. When the price breaches the support
or the resistance level this means that there has been a shift in the supply or demand curves for the
shares. Once the resistance or support level is breached, it’s role will be reversed, i.e. the resistance
level will become the support level if the resistance level is broken and vice versa for the support
level[39][40].
2.14.3 Volume Analysis
Volume analysis is important to technical analysis because it is used to confirm chart trends and
patterns. In most scenarios, a change in volume precedes a change in price. The exception to this is
when the volume and price relationship starts to deteriorate[40][41].
2.3.4 Pearson’s Product Moment Correlation Coefficient
Pearson’s Product moment correlation (PPMC) also referred to as the Pearson’s correlation coefficient
is a measure of how well two variables are related linearly. It enables the user to know whether fitting
a straight line to the data accurately represents the relationship between the variables in question. The
equation below is used to calculate the coefficient of correlation. A strong correlation is represented by
an r value within the intervals [0.7; 1] or [ -1; -0.7]. Where an absolute value of 1 represents a perfect
linear relationship. A moderate strength correlation would fall within the intervals [0.3;0.7] or [-0.7; -
0.3]. Low correlation is represented with a value within the ranges [0.1;0.3] or [-0.3; -0.1]. No
correlation results in an r value of 0. [1]
16
𝑟 =
𝑛(∑ 𝑥𝑦) − (∑ 𝑥)(∑ 𝑦)
√(𝑛 ∑ 𝑥2 − (∑ 𝑥)2)(𝑛 ∑ 𝑦2 − (∑ 𝑦)2)
(10)
𝑟 =
𝑐𝑜𝑣(𝑥, 𝑦)
𝑆 𝑥 𝑆 𝑦
(11)
Where
𝑛 is the number of observations in the sample
𝑥 is the independent variable
𝑦 is the dependant variable
𝑐𝑜𝑣(𝑥, 𝑦) is the covariance between the two variables
𝑆 𝑥 is the sample standard deviation of the independent variable
𝑆 𝑦 is the sample standard deviation of the dependent variable
2.15 Kurtosis
Kurtosis is used as a statistical tool to evaluate a probability distribution. Kurtosis describes the shape
of the distribution, more specifically it measures the weight of the tails of a distribution. There are three
states of kurtosis. Mesokurtic describes a distribution with a kurtosis value of 3, which is the same as a
standard normal curve. Leptokurtic distributions have a kurtosis value of above 3, this describes a
distribution with a higher peak than the normal curve and has fatter tails than the standard normal curve.
A Platykurtic distribution has a kurtosis value of less than 3, it describes the distribution as a flatter,
more spread out distribution of the data[42].
Sample kurtosis is calculated using the Equation 12.
𝐾 =
𝑛(𝑛 + 1)×(𝑛 − 1)
(𝑛 − 2)×(𝑛 − 3)
×
∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
4𝑛
𝑖=1
(∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
2𝑛
𝑖=1 )
2 (12)
Where
𝑥𝑖 is the ith
value of the dataset
𝑛 is the sample size
𝐾 is the kurtosis
17
The population kurtosis is calculated using Equation 13
𝐾 = 𝑛×
∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
4𝑛
𝑖=1
(∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
2𝑛
𝑖=1 )
2 (13)
2.16 Skewness
Skewness is the measure how identical a distribution is. A non-zero value of skewness means that the
data is skewed. Sample skewness is calculated using Equation 14.
𝑆 =
𝑛√𝑛 − 1
𝑛 − 2
×
∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
3𝑛
𝑖=1
(∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
2𝑛
𝑖=1 )
3
2
(14)
Population skewness is calculated using Equation 15.
𝑆 = √ 𝑛×
∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
3𝑛
𝑖=1
(∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔)
2𝑛
𝑖=1 )
3
2
(15)
2.17 Normality
Normality is the measure of how data is distributed and if the normal distribution can be fit to the data
significantly. The statistical methods that can be used to test this, are the Kolmogorov-Smirnov Test
[29] (see Equation 16 for test statistic) and the Shapiro-Wilk test (see Equation 17 and 18 for test
statistic) [30].
𝑇 = 𝑚𝑎𝑥|𝐹∗(𝑥) − 𝑆(𝑥)| (16)
Where
𝑇 is the test statistic used for the Kolmogorov-Smirnov test
𝐹∗(𝑥) is the data being tested
𝑆(𝑥) is the empirical distribution data (data from the normal distribution for normality tests)
𝑊 = (
𝑏
𝑠√𝑛 − 1
)
2 (17)
𝑏 = ∑ 𝑏𝑖 = ∑ 𝑎(𝑛 − 𝑖 + 1)(𝑋 𝑛−𝑖+1 − 𝑋𝑖) (18)
18
Where
𝑊 is the test statistic for the Shapiro-Wilk test
𝑏 is defined by Equation 10
𝑎 is defined as a Shapiro-Wilk coefficient
(𝑛 − 𝑖 + 1) is defined as a Shapiro-Wilk coefficient
𝑥 is defined as the data from the series being tested
Kolmogorov-Smirnov Test uses p-values to compare the test statistic and to accept or reject the null
hypothesis of the data being normal. The Shapiro-Wilk test uses critical values from a Shapiro-Wilk
table of values to compare the test statistic and conclude if the null hypothesis is accepted or rejected.
2.18 Stationarity
2.18.1 Difference Stationarity
A series with a random walk can be transformed into a stationary process using differencing,
irrespective of whether it has drift or not. [43]
2.18.2 Trend Stationarity
A nonstationary process with a deterministic trend can be transformed into a stationary process by
detrending. [43]
2.18.3 Difference and Trend Stationary
In cases where a random walk with drift and a deterministic trend, stationarity can be achieved through
detrending but differencing needs to also be applied in order to ensure that the variance does not grow
to infinity over time. [43]
2.18.4 Testing for Trend Stationarity and Difference Stationarity
There are two preferred methods for testing for stationarity, these are the Augmented Dickey-Fuller
(ADF) test and the Kwiatkowski–Phillips–Schmidt–Shin (KPSS) test [43]–[48].
2.18.4.1 Augmented Dickey-Fuller Test (ADF)
In the ADF test Equation 17 below is used to represent an AR process [44], [49], [50]
Where 𝛿 ∈ [0,1], when 𝛿 is 0 the process is unit root stationary, when 𝛿 ≠ 0 then the process is not.
The test sets a null hypothesis that the process is unit root stationary.
𝐻0: 𝛿 = 0
𝐻1: 𝛿 ≠ 0
∆𝑌𝑡 = 𝛼 + 𝛿𝑌𝑡−1 + 𝑒𝑡 (19)
19
A t-statistic is calculated for the 𝛿̂ which is the estimated value of 𝛿. This test statistic is then compared
to the critical values from the Dickey-Fuller Distribution.
When
𝑡 < 𝐷𝐹𝐶𝑟𝑖𝑡𝑖𝑐𝑎𝑙 (20)
The null hypothesis is rejected. The 𝐷𝐹𝐶𝑟𝑖𝑡𝑖𝑐𝑎𝑙 value can be calculated using Equation 21.
𝐷𝐹𝐶𝑟𝑖𝑡𝑖𝑐𝑎𝑙 =
𝛿̂
𝑆𝐸(𝛿̂ )
(21)
2.18.4.2 Kwiatkowski–Phillips–Schmidt–Shin (KPSS) Test
This test evaluates whether a univariate series is trend stationary as the null hypothesis and that it is a
nonstationary unit root process. It does this by first defining the series with Equation 22 below [51][52].
𝑌𝑡 = 𝑐𝑡 + 𝛽𝑡 + 𝑢1𝑡 (22)
𝑐𝑡 = 𝑐𝑡−1 + 𝑢2𝑡′ (23)
Where
𝑐𝑡 is some random walk process
𝑢1𝑡 is a stationary process
𝑢2𝑡′ is and independent and iid process with a mean of 0 and variance 𝜎2
𝐻0: 𝜎2
= 0
𝐻0: 𝜎2
> 0
With the test statistic
𝑝𝑡𝑒𝑠𝑡 =
∑ 𝑆𝑡
2𝑇
𝑡=1
𝑆2 𝑇2
(24)
Where
𝑝𝑡𝑒𝑠𝑡 is the p-test statistic
𝑇 is the sample size
𝑆2
is the Newey-West estimate of the long-run variance
And
𝑆𝑡 = 𝑒1 + 𝑒2 + 𝑒3 + ⋯ +𝑒𝑡 (25)
20
2.19 Homoscedasticity
Homoscedasticity describes the variance of a series, it means that the variance does not increase with
time[53]. Homoscedasticity can be tested graphically by looking at plots of residuals against actuals. It
can also be tested using the Engle test for residual heteroscedasticity.
2.19.1 Engle Test for Residual Heteroscedasticity
Residuals of the series are defined as in Equation 24
𝑒𝑡 = 𝑦𝑡 − 𝑢̂ 𝑡 (26)
Where
𝑢̂ 𝑡 is the conditional mean of the process
𝑒𝑡 is the residual which is identically distributed with a mean of 0 and variance of 1
𝐻0: 𝛼0 = 𝛼1 = 𝛼2 = ⋯ = 𝛼 𝑚
𝐻1: 𝑒𝑡
2
= 𝛼0 + 𝛼1 𝑒𝑡−1
2
+ 𝛼2 𝑒𝑡−2
2
= ⋯ = 𝛼 𝑚 𝑒𝑡−𝑚
2
+ 𝑢 𝑡
Where
𝑢 𝑡 is a white noise error process
The null hypothesis tests that series is not heteroscedastic. The test statistic is found by using the F
statistic for regression on the squared residuals, and the critical value is found in the 𝒳2
distribution
using m degrees of freedom and the required significance[54][55].
2.20 Random Walk Hypothesis
2.20.1 Pure Random Walk
A pure random walk is defined by the equation
𝑌𝑡 = 𝑌𝑡−1 + 𝜀𝑡 (27)
Where
𝜀𝑡 is white noise
𝑌𝑡 is the series value at time t
𝑌𝑡−1 is the series value at time t-1
White noise is stochastic; this means that this series will not become mean reverting as the variance will
evolve over time. The variance of the series will tend to infinity as time tends to infinity. This is a
difference stationary process[43].
21
2.20.2 Random Walk with Drift
This series is defined by the equation below
𝑌𝑡 = 𝛼 + 𝑌𝑡−1 + 𝑒𝑡 (28)
Where
𝛼 is the drift term in the series
This series too has a variance that is dependent on time and hence is not mean reverting. This is a
difference stationary process. [43]
2.20.3 Deterministic Trend
This is defined by the equation below
𝑌𝑡 = 𝛼 + 𝛽𝑡 + 𝑒𝑡 (29)
Where
𝛽𝑡 is the deterministic trend
This series although it looks similar to that of a random walk with drift is different as it is a regressed
series of the time trend 𝛽𝑡. A nonstationary process with a deterministic trend has a mean that grows
around a fixed trend which is constant and independent of time. This is a trend stationary process. [43]
2.20.4 Random Walk with Drift and Deterministic Trend
This series is described by the equation below
𝑌𝑡 = 𝛼 + 𝑌𝑡−1 + 𝛽𝑡 + 𝑒𝑡 (30)
This series has both a drift component and a deterministic trend. This is both difference and trend
stationary. [43]
2.21 Related Studies
2.21.1 Chan et al. 1999
Chan et al. constructed a simulation of a double auction market. The simulation modelled the complex
interactions between artificially intelligent traders. The traders had varying degrees of learning
capabilities. The price efficiency, speed of price convergence to rational equilibrium, dynamics of
wealth distribution amongst the AI trade, trading volume and the bid ask spread were monitored during
the simulation in order to tell how accurately the simulation modelled the market behaviour.
In the breakdown of the problem, Chan et al. created four major components for the simulation. These
were the economic environment, the trading systems, the types of the traders and the learning
mechanisms. The traders were also split into three groups, Insiders, partially informed and the
uninformed trader.
22
The trading mechanism used was a simple double auction market, within which agents could only
submit bids and asks. The prices of subsequent bids, had to be higher than the current bid and asks had
to be lower than the current asks. The agents were also restricted to the trade of a single share at a time.
Traders were assumed to be risk neutral, and agent maximised their end-of-period expected values of
their portfolios by forecasting the liquidating dividend. The agents then bought when market prices
were low relative to their forecast and sold when market prices were higher than their forecast. Chan et
al. also created three types of traders, empirical Bayesian traders, momentum traders and nearest
neighbour traders. Each of these had different learning mechanisms.[56]
2.21.2 Preyen Nair 2014
Nair created an agent based simulation of the trading of a single share on the JSE. As part of the scope
and requirements, Nair had to design a double auction market according to the specifications used by
the JSE for creating their order matching engine. Auction periods and hidden order were outside the
scope of the model created.
Nair split up his model into three components and focused on completing these before moving on. These
components were; the orders, order processing engine and the order book. These three components were
central to his design. The orders had to validated and work in the system that he created. Upon
completion of the three components, agents were developed. The logic that was used to model the agents
decisions to buy, sell or hold was based on the risk and return of the transactions. Table 1 below
summarises the logic used to create the decisions for each agent.
Table 1: Agent logic for price, logic and order types[2]
Where
p is the price level aq
t is the best quoted ask price
bq
t is the best quoted bid price P*
is the agents comfort price level
Si
t is the current stock portfolio of agent i at time t
pM is the upper value that the agent is comfortable paying
i
(p) is the demand function at p for agent I
pm is the lower value that the agent is comfortable paying
23
3 HIGH LEVEL PRODUCT REQUIREMENT SPECIFICATION
3.1 Requirements
 Behaviour matches market behaviour
 Outputs share price information as a time series.
 Uses agent-based simulation
 Uses input data for agents to make decisions with
3.2 Constraints
 All agents are rational
 A single share will be used in the model
 Assumptions could make the model less realistic
 Difficult to identify and quantify all the drivers for price
3.3 Criteria
 Accuracy of prediction
 Data Presentation and collection
 Ease of use
 Speed
 Realistic behaviour
 Ease of creating the concept in Anylogic.
 Modular building and interactions
3.4 Assumptions
 All agents will be rational
 Agents will only transact with the cash that they have and no borrowing of money will be
allowed
 Prices will not be less than zero
 Intraday factor values will be created by using a uniform distribution between the upper and
lower values for the day.
 Only one share will be traded
 A set number of agents will be within the market (there are no new entities entering the market
or any leaving)
24
4 CONCEPT GENERATION
Before concept generation, it is important to survey literature to see what has been done and how it was
done previously. In doing this it was found that when creating an agent based model the following are
considered[13], [20], [57]–[61], [33], [62], [63].
1. Agent Learning
Learning in the models generally include genetic algorithms and neural networks in order for
each agent to change over time and adapt to the situation that they are in. The learning is applied
to agents’ decisions to buy, sell or hold shares, as well as decide what price the share is worth
or even which share to buy. These would usually be used in conjunction with different strategies
of trading. Some models use strategies like technical and fundamental trading while others use
maximisation of utility or portfolio values.
2. Zero-Intelligence traders
Zero-intelligence traders are traders who buy or sell randomly in the market with some
constraints attached to them, Farmer et al explain that zero-intelligence agents are able to
explain stylized facts on the London Stock Exchange. One of these facts being allocative
efficiency, also known as Smiths Invisible hand, which guides the market toward an
equilibrium price based on the supply demand and the price.
3. Minimal Rationality
This follows the argument that not all agents act in the interest to maximise their portfolio, and
in trying to model the market realistically, needs to be considered.
4. Replication of Stylized Facts
When building a model, there are various checks to see how realistic the model is, these checks
are done by looking for certain characteristics within the data. Characteristics such as non-
normal return distributions (described by a kurtosis greater than 3 or a Jarque-Bera test with a
p-value of 0), volatility clustering of returns, high and persistent trading volumes, and the
existence of technical trading.
5. Trading Logic (Technical traders, Fundamental traders or a combination of both)
6. Double Auction Markets
Many models use this method to create the value of the shares, the process consists of buyers
and sellers submitting bids for a share at a price they value it at, the auctioneer would then select
a price that clears the market.
7. Matching Engines
The order matching engine allows for each order to be matched by price and preference
(decided by first in first out or other such queuing criteria).
25
Before the concept creation, Anylogic was used to create a few sample models to better understand the
problems that would be faced when trying to create the model. Some of the problems found were;
 Creation of an order book that each agent can read and then value the share
 Using the shares like resources, as it made it difficult to attach the shares to the agent if agents
just sent orders instead of standing going through a queuing system.
 Creating a population for orders and ensuring that information is copied from agent to the order
as well as keeping count of the orders and which order belonged to which trader.
 Creating new agents that enter the trader population and having some leave too. This created a
problem as this could create a time varying total number of shares in the market.
To deal with these problems various solutions were tried, Concepts 1 to 3 shown below solved most of
the problems. It is also important to note that due to time constraints the model will need to be
simplified. Although simplified, the model will be flexible and will be able to be developed further and
could be seen as a base for future work.
26
4.1 Concept Creation
In Table 2, each concept is defined by the components that will make up the design, each component
can be made modularly and then the whole concept put together. Agent logic describes how the trader
agent creates different actions under the given scenarios. The trading system is the component that
allows for the bids and exchange of the share to occur. The evaluation of the share price would be a
subcomponent of the agent logic as this is what is used to decide what price the trader is willing to pay
according to the factors given. Intrinsic value is what the agent is willing to pay at maximum when
buying or receive at minimum when selling.
Table 2: Concept Creation Matrix
Concepts
Agent
Logic
Trading
System
Valuating
Share
Price
Intrinsic
Value
Buy/Sell/Hold
Decisions
Matching
Orders
Concept
1
State
Chart
Agent
Based
According
to Intrinsic
value
Uses linear
regression
Price based
Decision by
entity
responding to
message and
FIFO
Concept
2
State
Chart
Modelled
as
Queueing
According
to last sold
Uses linear
regression
Demand/supply
based
Modelled as
Queuing
Concept
3
State
Chart
Modelled
as
Queueing
According
to last sold
Neural
network with
scaling using
supply
demand ratio
Demand/Supply
and Price based
Modelled as
Queuing
27
4.1.1 Concept 1
This concept tries to function as an agent only model, making use of only the agents logic and trading
occurs through communication between agents directly. It uses the state chart to define its behaviour
entirely. The biggest foreseen problem with this concept is the messages the sellers continue to send,
this could affect the speed of the simulation as this means there would be more event occurring at any
given time. Figure 9 below shows the state chart and the logic within each state. This logic is still basic
as this is still a concept.
Figure 9: Concept 1 Flow Chart
28
4.1.2 Concept 2
This concept makes use of a queuing system to handle the exchange and matching of shares. The order
agent is sent to the queue with the details of the transaction, like the quantity and price. This method
also requires there to be a resource used for the shares. Figure 10 shows the state chart that will be used
in this concept, notice that it is similar to that of Concept 1, although this does not have as many
processes within the states. Figure 11 shows the queuing systems proposed for this concept.
Figure 10: Concept 2 Agent State Chart
Figure 11: Concept 2 Activity Cycle Diagram
29
4.1.3 Concept 3
This concept uses a very similar state chart to the first two concepts, although there are more ways for
an agent to enter into the buy or sell state, as can be seen in Figure 13. Figure 14 shows the queuing
system to be used in the model, note that in this concept no agents will leave the queuing system, the
agents will be moving from state to state and while doing that will be moving in the queuing systems
according to their state.
Figure 12: Concept 3 Agent State Chart
30
Figure 13: Concept 3 Activity Cycle Diagram
4.2 Concept Selection
Each concept is rated out of 5 for each of the judging criteria, note that the accuracy of the concept is
uncertain at this stage and can only be measured accurately after the model is completed as this is a
complex system. There is a chance that the observations after the model has been complete may deviate
from these ratings. As a result of this, flexibility of the model has not been added as one of the judging
criteria. All criteria will however, be kept in mind while creating the chosen concept. Extra steps will
be taken to try to ensure that the criteria have been kept at the level expected. Table 3, rates each concept
and compares them amongst each other.
Table 3: Concept Rating Table
Concepts
Data Presentation
and collection
Ease of
use
Speed
Realistic
behaviour
Ease of creating
in Anylogic
Totals
Concept
1
4 4 5 2 2 17
Concept
2
4 4 3 5 2 18
Concept
3
4 4 3 5 3 19
31
 Data Presentation and collection
Data presentation and collection is defined by the ability to gather important information about
the model and convert it into graphs or other means of summarising the data. This would be
easy for each concept due to Anylogic being simple to use for information and statistical
gathering. The log function allows one to see in what order events are occurring. The dataset
functions allow for quick gathering of statistical data throughout a time series.
 Ease of use
The ease of use of the model is defined by the ability of the user to change the parameters to
better suit the scenario they are trying to create. In Anylogic these changes can be made easily
by creating either sliding bars, buttons, radio buttons, and other GUIs. The change of the data
that is needed for the environmental factors would have to be done using the databases that
have been imported from excel files. All concepts would score high on this due to the ease of
use of Anylogic.
 Speed
The speed is defined as the time it takes to run the simulation. This would vary according to the
method used. For example, running an agent-based simulation with lots of agents and with
complex interactions may take longer than a normal discrete time simulation. Concept 1 would
be faster than the other concepts due to the simplicity of the model. Concept 1 would use purely
agent based simulation, and transactions would occur almost instantly due to the auction
method coupled with FIFO for matching the orders. Concepts 2 and 3 are hybrid models, the
agent exists within a system while making decisions based on the environment, for this reason
these two models would take longer than the first.
 Realistic behaviour
The behaviour of the model would need to come close to that of the interactions in reality (with
some simplifying assumptions). There are a few stylised facts that could be simulated using the
model. The main aim is to have traders buy and sell according to supply and demand while
changing the price accordingly. Model 1 is a simple solution which bases the decisions on
whether the agent wants to accept an offer or reject it. Model 1 uses linear regression to evaluate
the intrinsic value and then if the offer is god enough it is accepted. Model 1 has one major
flaw; it only has the sellers sending out offers and the buyers react to that. For this reason, it is
not as realistic as the other two models. Model 2 also uses linear regression to create the intrinsic
value, this could lead to incorrect calculation of the share’s intrinsic value. This makes Concept
3 the best in this category.
32
 Ease of creating the concept in Anylogic
Concept 3 seems to be the easiest to create as the potential problems are less. Some of the
foreseen major problems for each concept are as listed below;
Concept 1
 Selecting which agent sent the message to the agent who is selling first.
 Sending an offer to buy the share to a specified agent.
 Creating the trade between the two agents
 Telling the agents when the seller has found a buyer.
 Selecting which selling agent will be selected or ignored while there are many sellers
 Selecting an agent when there are multiple offers to buy, at the same price at the same time.
Concept 2
 Creating an order as an agent and sending this as a message which has been fully
customised according to the expiry time, price, volume.
 After the order seizes the share (in the buying case), there would be a problem of attaching
the share to the trader who created the order.
 Orders will be destroyed when they leave the queuing system
 Selling orders would need to be attached to shares when entering the system
 Orders are randomly chosen to be used by a trader, this could mean that the possibility of
leaving all shares attached to the order for each trader.
Concept 3
 Creating the neural network in Anylogic
 Matching orders according to the price
 Having entities from a specific a population enter the system and interact with the system
according to the decisions the agents make
Concept 3 has been chosen to continue further development as it is rated the best out of the three
concepts created, as seen in Table 3.
33
5 THE DESIGN PROCESS
The design process used in creating this model followed the steps listed below.
1. Literature search on how other similar models were created.
2. Break down the problem into a number of smaller problems and start finding ways to solve
each problem.
3. Create basic flow charts of how each solution can be modelled.
4. Create simplifying assumptions.
5. Try to create a basic model to find the difficulty areas.
6. Create concepts to get around the problem areas.
7. Choose a concept.
8. Develop the concept.
9. Iterate steps 1 until 8 until a possible way to model each system is found.
10. Test the model and debug.
11. Validate the model components.
12. Validate the model as a whole.
The bottom-up approach was used to design the model, this entails modelling the agents behaviour and
their interaction first. The model was developed in the order listed below. Note this is a not an
exhaustive list as there are too many components to be listed individually.
1. Create the agents and their attributes.
2. Create their states and ensure that they are able to move between states.
3. Create the queuing system and ensure that agents can move around in it according to their states.
4. Create the intrinsic value algorithm (basic).
5. Create the share price and intrinsic value comparison method.
6. Ensure that agents can change states according to the intrinsic value and the share price.
7. Ensure that the correct number of shares and cash are traded.
8. Create databases for each factor.
9. Create a schedule for each factor to change according to the day.
10. Create the neural network function.
34
6 DESIGN DEVELOPMENT OF THE MODEL
The simulation has been broken down into 2 main subsystems. The subsystems are the traders and the
trading platform. Each of these needs the other to perform. The basic idea the concept should follow is
that the agents will be in the observe state initially. While in the observe state the agents will watch the
share price, they will then compare the share price to an intrinsic value. On comparing the share price
to the intrinsic value, the agent will decide whether or not to buy or sell. The agent will buy if the share
price is lower than their intrinsic value and sell if the share price is higher than their intrinsic value.
Upon making this decision, the agent will then be sent to the trading platform to trade with another
agent. The trading of the share will only occur if the price an agent is willing to sell is less than the price
the other agent wants to buy at, i.e. their price ranges must overlap. Upon doing this the agents are
matched and carry out the transaction. If one of the agents has a greater number of shares to transact,
that agent will return to the queue to be matched again, this will continue until the agent has no more
shares that they want to buy or sell. The design specifications for each component will follow under
Sections 6.1 and 6.2. Each of the subsystems will then be further broken down into the respective
components.
6.1 Agents (Traders)
The agents used in this model are only one set of traders, these traders all act to buy or sell. There are
no holding periods for the agents of this population. The only time that the agents stay within the observe
state is when the trading day has ended. Note that these traders will only trader if they perceive a as
share worth buying or selling (there is some sort of benefit that they can receive from trading). A further
population of agents could easily be generated and the frequency of transacting could be changed. The
current population are high frequency traders. In Section 6.1.1 the product requirement specifications
are listed for the creation of the agents. The agent design is split into four components namely, agent
decisions to buy or sell, agent intrinsic value creation, agent logic and the agent attributes.
6.1.1 Product Requirement Specification
6.1.1.1 Requirements
 Agents must be able to buy and sell shares
 Agents need to be able to determine when to buy shares and sell the shares they hold
 Agents need to be able to determine what price the shares are worth intrinsically
 Agents need to have different levels of income
 Agents will need to interact with each other when sharing information
6.1.1.2 Constraints
 Agents cannot have negative amounts of shares
 Agents cannot borrow money to buy more shares
 Agents have to place an order and wait till the trading system matches the order
35
6.1.1.3 Criteria
 Agents are able to valuate a share price according to environmental factors
 Agents are able to buy a share when required
 Agents are able to sell a share when required
 Agents can interact if required
 Agents receive a fixed income every month
 Agents are able to act individually
 Ease of use in Anylogic
 Model created needs to be flexible.
6.1.2 Concept Development and Specification
In this section the various subcomponents of the agents’ design will be detailed further.
6.1.2.1 Agent Parameters
Agents have various factors as attributes such as;
 Money held.
 Selling, holding or buying.
 Number of shares held.
 Expiry.
 Maximum price willing to buy at.
 Minimum price willing to sell at.
 Waiting in queue (Binary 0 meaning that it is waiting in a queue to transact, 1 meaning it is not).
 Forecasted price.
 Learning rate for neural network.
 Weights for neural network.
 Biases for neural network.
 Current time.
 Exited (This attribute says whether the agent has left the trading or not).
 Trading hours (this attribute tells the agent how long the trading should occur for).
 Transaction (Transaction =0 if in observe state, Transaction=1 if in waiting to buy state and
Transaction=2 if in waiting to sell state).
36
6.1.2.2 Agent Logic
In Figure 14, the logic for the agent state changes as well as the logic for the entry and exit of the
queueing system is shown. Note that there are three more states than with the concepts. The states that
were added, are there for the transitions between the observe state and the buy state as well as between
the observe state and the sell state, these two were added to create a visual validation that agents are
buying, selling or waiting to carry out those transactions. The third state, called the return state in Figure
15, is there to ensure that when the buy or sell button is pressed agents enter and change their colour to
black. This too is for a visual validation of the buy and sell buttons.
When an agent is moving from the observe state to the waiting to buy state, it has to meet the condition
that the cash it has is greater than the cost of the number of shares the agent wishes to purchase. This
constraint ensures that the cash an agent has is never negative. When an agent is moving from the
observe state to the waiting to sell state, it must meet the condition that the agent must be holding more
shares than it wants to sell. This constraint ensures that the agent is always holding a non-negative
number of shares. Both transitions require the condition that it must be trading hours to move from the
observe state. Outside of trading hours all agents will not flow into the waiting to transact states.
37
Figure 14: Agent Logic Flowchart
38
6.1.2.3 Agent Decisions to Buy or Sell
While agents are in the observe state, they need to evaluate whether they want to buy or sell. The logic
in Figure 15 shows what the process for deciding to buy or sell entails. This logic is basically checking
if the share price is greater than or less than the intrinsic value the agent has for the share price. If the
intrinsic value is greater than or equal the share price, the agent will sell. If the intrinsic value is less
than the share price, the agent will buy.
Figure 15:Flowchart for Decisions to Buy or Sell
39
6.1.2.4 Agent Intrinsic Value Creation
In Figure 16 below, is the general flow chart for the creating of intrinsic value of the agents in the
population trader. The data is scaled linearly according to the maximum and minimum data of each
daily data set for the past 5 years. After scaling the data, it will be between 0.2 and 0.8, this was done
to account for data going below or above the historic data. After the neural network, the data is scaled
back into the share price data. From this point the share price is then scaled according to the supply and
demand with Equation 31 and Equation 32 below.
𝑀𝑖𝑛𝑊𝑖𝑙𝑙𝑖𝑛𝑔𝑇𝑜𝑆𝑒𝑙𝑙𝐴𝑡 = IntrinsicValue× (1 + (
(𝑉𝑜𝑙𝑢𝑚𝑒𝑇𝑜𝐵𝑢𝑦 − 𝑉𝑜𝑙𝑢𝑚𝑒𝑇𝑜𝑆𝑒𝑙𝑙)
10000 ∗ 𝑉𝑜𝑙𝑢𝑚𝑒𝑇𝑜𝑆𝑒𝑙𝑙
)) (31)
𝑀𝑎𝑥𝑊𝑖𝑙𝑙𝑖𝑛𝑔𝑇𝑜𝐵𝑢𝑦𝐴𝑡 = IntrinsicValue ∗ (1 + (
VolumeToBuy − VolumeToSell
10000 ∗ VolumeToBuy
)) (32)
Figure 16: Flowchart of the general logic for creation of Intrinsic Value
In Figure 17, the flow chart for the neural network function created in Anylogic is shown. The neural
network function is adaptable to the number of hidden nodes without changing anything but the weights.
The weights that are used in to function were trained in Matlab before being used in Anylogic. This is
important as the training needed to be done for the agents to have accurate relationships between the
factors input and the share price.
Start Neural Network
Rand:
Euro
Rand:
Dollar
Platinum
Price
Scale data
Scale Output
Create randomness by
using a normal distribution
Adjust according to
Demand and supply
End
40
Figure 17: Flowchart of the Feedforward Back Propagation used to create a function in Anylogic
Start Declare Variables h<3
Effective Input
Calculation
h=0
i=0
True
i<3
True
S[h]+=X[i]*Wih[i][h]
i+=i
False
S[h]+=bih[h]
h+=1
False
OutputFrom
HiddenLayer
Calculations
h=0
h<3
True
Yh[h]=1/(1+math.exp(-S[h])
h+=1
Summation Into
Output Node
Calculations
h=0
h<3
True
Yo=(Who[h]*Yh[h])+
bho
h+=1
False
Error=Target-Yo;
Changing Weights
between Output and
Hidden Layer
h=0
h<3
True
DeltaWho[h]=LearningRate*Error*Yh[h
Who[h]+=DeltaWho[h]]
h+=1
False
Error for
Weights
between Input
and hidden
layer
calculation
h=0
h<3
True
AltError[h]=2*error*Who[h]*Yh[h]*(1-Yh[h])
h+=1
False
Update
Weights
between input
and hidden
layer
h=0
i=0
i<3
True
h<3
True
DeltaWih[i][h]=LearningRate*Alterror[h]*X[i]
Wih[i][h]+=DeltaWih[i][h]
h+=1
False
i+=1
False End
41
Figure 18 shows the neural network that was used in creating the intrinsic value using the factors,
platinum price, Rand-Euro and Rand-Dollar exchange rates. The neural network was trained using
1250 data points with 60% being used for training, 15% for testing and 25% for testing. After training
the weights were exporting into Anylogic and used in the neural network function created. The neural
network will be attached in the digital appendix.
Figure 18: Structure of neural network used in Matlab
Figure 19 shows the relationship between price and quantity as the demand increases. In this case as
the quantity demanded increases the price increases proportionally. This proportional increase is given
by Equation 33 and 34 below.
𝑃 𝐷𝑡
= 𝑞 𝐷𝑡
𝑚 𝐷𝑡
+ 𝑃 𝐷𝑡−1
(33)
𝑃𝑆𝑡
= 𝑞 𝑆𝑡
𝑚 𝑆𝑡
+ 𝑃𝑆𝑡−1
(34)
Assuming that the price is highly elastic and after a few iterations trying to get the price within a more
realistic range, the price elasticity was then used as 10000 as seen in Equations 31 and 32. Price
Elasticity is related to the volume and price through Equation 35
𝐸 =
(
𝑞 𝑡− 𝑞 𝑡−1
𝑞 𝑡−1
)
(
𝑃𝑡 −𝑃𝑡−1
𝑃𝑡−1
)
(35)
42
Figure 19: An Increase in Demand [64]
When the quantity supplied surpasses the quantity demanded the price will decrease to reach
equilibrium, if the price supplied is higher than the price demanded the quantity demanded will reduce
and reach equilibrium. This equilibrium is also known as allocative efficiency.
6.1.2.5 Overreaction in market
Figure 20, shows the logic used to create the overreaction in the market using two buttons, buy and
sell, these buttons send the agents into a state of “panic” in which they all want to buy or sell.
43
Buy
On Press
delivertoallagentsInside( BuyNotSell
Transaction>0
Agent Receive
Message
SendToRandom( Buy
Transaction==1
True
True
False
Expiry=0
Exit==1
False
Agent Leaves State
and moves to
observe state
True
Agent Enters Buy
State on receiving
message buy
End
End
Sell
On Press
delivertoallagentsInside( SellNotBuyl
Transaction>0
Agent Receive
Message
SendToRandom( Sell
Transaction==2
True
True
False
Expiry=0
Exit==1
False
Agent Leaves State
and moves to
observe state
True
Agent Enters Sell
State on receiving
message Sell
End
End
Expiry=0
Timeout
On Timeout
Exit==1
End
Figure 20: Flowchart of The Logic Used for The Buy and Sell Buttons Which Are Used to Represent an Overreaction in The Market
44
6.1.3 Validation
The validation has been split into 3 sections, namely; agent decisions, agent logic and agent intrinsic
value creation. This has been done to validate that each component works as required.
6.1.3.1 Agent Logic
Validation that changing of states occur
To validate that agents are able to move between states, a count of the number of agents within each
set is done at 1 second intervals as seen in Figure 21 below. The blue lines represent the agents within
the sell state, the green represents the agents within the buying state and the purple represents the
agents within the observe state. Note that this data was collected from running the simulation with
trading hours set between 8:00 am and 9:00 am and therefore the trading occurs until around 3600
seconds.
Figure 21: Validation that Changing of states occurs
Validation that share price is always positive
The share price as in reality should not decrease to zero or less as this would mean that a company is
giving shares out for free or paying people to buy the shares. This needs to be validated to ensure that
the model prices meet that requirement. In Figure 22, it is seen that the share price falls to a minimum
that is greater than 2900 cents. It can also be seen that the mean of this series does change over time by
looking at the gradient of the mean line as well as the small spikes at certain points.
45
Figure 22: Validation That the Share Price is Never Below Zero
Validation that number of shares held is positive
One of the assumptions held in this model is that the number of shares that an agent can hold cannot be
less than 0. This is a practical assumption that ensures that no credit trading occurs. In Figure 23, the
minimum number of shares that any agent in the population trader holds is never less than zero.
Figure 23:Validation That the Minimum Amount of Shares an Agent Can Hold is Zero
46
Validation that cash held is always positive
Another assumption that ensures that no credit trading occurs, is the assumption that the minimal cash
that an agent holds cannot go below zero. In Figure 24 is a graph of the minimum cash that any agent
holds in the population trader over time. It can be seen that the smallest value that an agents’ money
goes to is 80000 cents. One could argue that due to the large amount of starting cash and a short run
time, the agents don’t get the chance to spend all their cash. To show that the cash does not go below
zero, a simulation was run with the starting amount of cash set to 0 for each agent. As seen in Figure
25, the minimum stays at zero and never goes below.
Figure 24:Validation That Cash held is Always Positive
Figure 25:Validation That Cash Never Goes Below Zero
47
Validation that the number of shares in the system stays constant
The assumption that the total number of shares in the market is conserved and will neither grow nor
decrease over time also needs to be validated to show that this does not cause any price fluctuations. In
Figure 26 below depicts the constant number of share in the market for the simulation running for 3600
seconds.
Figure 26: Validation That the Number of Shares in The System Stays Constant Throughout
Validate that agents can leave their states on the message buy or sell
Buy and sell buttons were created to show how the model would simulate an overreaction in the market,
over reaction caused by events that make the traders want to buy or to sell. Figure 27 shows the what
states the agents are in before the buy button is pressed, note that the pink represents the buying state,
the red represents the selling state, green represents the waiting to buy state, the blue represents the
waiting to sell state and the yellow represents the observing state. Figure 28 shows the population states
after the button has been pressed, note that there are agents which have turned black, this means that
the agents have left their selling states and are leaving to move to the waiting to buy state. The black
colour could be seen as the agents moving into a panic state. On entering this “panic” state, agents send
messages to random agents telling them to buy the share.
Figure 29 shows the agents before the sell button has been pressed, note that there are no black coloured
agents, this means that there are no agents in the “panic” state before the sell button was pressed. Figure
30 shows the agents leave their states and enter a panic state and start sending messages to random
agent to sell their shares. The black colour acts as the validation that the agents are performing the
require action upon pressing the button.
NumberofSharesinMarket
48
Figure 27: Screenshot of Simulation Before Pressing Buy Button
Figure 28:Screenshot of Simulation After Pressing Buy Button
49
Figure 29: Screenshot of Simulation Before Pressing Sell Button
Figure 30: Screenshot of Simulation After Pressing Sell Button
50
6.1.3.2 Agent Decisions to Buy, Hold or Sell
Validation that the price changes according to the supply and demand for the share
In order to validate that the price changes according to the supply and demand quantities of the share,
buttons were created to change the values of the volumes demanded and supplied. These buttons are
called “BuyNow” and “SellNow”. Figures 31 and 32 both have four graphs each, the graphs on the top
represent the share price series, the graphs at the bottom represent the volume to buy and volume to sell
series. The graphs on the left are prior to pressing the respective button and the graphs on the right are
the graphs post pressing the buttons.
In Figure 31, it can be seen that after pressing the button, the share price series started to have higher
highs than prior to the pressing the “BuyNow” button. In Figure 32, it can be seen that the share price
has lower lows after pressing the “SellNow” button. While doing this, it was observed that the
relationship is complex, due to agent buying the moment the share price is lower than they expect or
selling the moment the share price is higher than expected. Pressing the button that increases the number
of sellers, results in a decrease in the price which then results in an increase the number of buyers.
Whereas pressing the button that increases the number of buyers, results in a higher share price which
then results in an increase in the number of sellers. The price reaches equilibrium fast and as such the
overreaction or underreaction in the market creates a small impact on the market in the model.
Figure 31: Screenshot of simulation before (left side) and after (right side) pressing Buy Now button
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684
536684

More Related Content

What's hot

T19 factor analysis
T19 factor analysisT19 factor analysis
T19 factor analysiskompellark
 
IRJET- Prediction of Stock Market using Machine Learning Algorithms
IRJET- Prediction of Stock Market using Machine Learning AlgorithmsIRJET- Prediction of Stock Market using Machine Learning Algorithms
IRJET- Prediction of Stock Market using Machine Learning AlgorithmsIRJET Journal
 
Yelp dataset challenge
Yelp dataset challengeYelp dataset challenge
Yelp dataset challengeArnabKMCS156
 
Graphical Analysis of Simulated Financial Data Using R
Graphical Analysis of Simulated Financial Data Using RGraphical Analysis of Simulated Financial Data Using R
Graphical Analysis of Simulated Financial Data Using RIRJET Journal
 
Final Presentation
Final PresentationFinal Presentation
Final Presentationssuseraf9eb5
 

What's hot (9)

T19 factor analysis
T19 factor analysisT19 factor analysis
T19 factor analysis
 
IRJET- Prediction of Stock Market using Machine Learning Algorithms
IRJET- Prediction of Stock Market using Machine Learning AlgorithmsIRJET- Prediction of Stock Market using Machine Learning Algorithms
IRJET- Prediction of Stock Market using Machine Learning Algorithms
 
Yelp dataset challenge
Yelp dataset challengeYelp dataset challenge
Yelp dataset challenge
 
Surstromming
Surstromming Surstromming
Surstromming
 
STOCK MARKET PREDICTION
STOCK MARKET PREDICTIONSTOCK MARKET PREDICTION
STOCK MARKET PREDICTION
 
Graphical Analysis of Simulated Financial Data Using R
Graphical Analysis of Simulated Financial Data Using RGraphical Analysis of Simulated Financial Data Using R
Graphical Analysis of Simulated Financial Data Using R
 
Final Presentation
Final PresentationFinal Presentation
Final Presentation
 
D0962227
D0962227D0962227
D0962227
 
Biuspp metrex
Biuspp metrexBiuspp metrex
Biuspp metrex
 

Viewers also liked

2013 Red Cross Blood Bank - Rajkot Contract
2013 Red Cross Blood Bank - Rajkot Contract 2013 Red Cross Blood Bank - Rajkot Contract
2013 Red Cross Blood Bank - Rajkot Contract JIGAR VYAS
 
Regime de trabalho docente
Regime de trabalho docenteRegime de trabalho docente
Regime de trabalho docenteAndré Boaratti
 
Mba em marketing e comunicação digital – cultura digital
Mba em marketing e comunicação digital – cultura digitalMba em marketing e comunicação digital – cultura digital
Mba em marketing e comunicação digital – cultura digitalBruno Messias
 
Richmond Music Fest
Richmond Music FestRichmond Music Fest
Richmond Music FestJ Carman
 
te process
te processte process
te processPTF
 
PrabhatKumarCV_Spanish
PrabhatKumarCV_SpanishPrabhatKumarCV_Spanish
PrabhatKumarCV_SpanishPrabhat Kumar
 
Presentación 2° Focus Group Enero 2016
Presentación 2° Focus Group Enero 2016Presentación 2° Focus Group Enero 2016
Presentación 2° Focus Group Enero 2016cpepresentations
 
Florette (presentación investigación primaria)
Florette (presentación investigación primaria)Florette (presentación investigación primaria)
Florette (presentación investigación primaria)Alejandra Martínez Mayans
 
English Biscuit Manufacturers SCM ASSIGNMENT EBM
English Biscuit Manufacturers SCM ASSIGNMENT EBMEnglish Biscuit Manufacturers SCM ASSIGNMENT EBM
English Biscuit Manufacturers SCM ASSIGNMENT EBMFurqan Aslam
 
FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...
FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...
FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...MedicReS
 
2015 - 2016 Life Blood Centre .PDF
2015 - 2016 Life Blood Centre .PDF2015 - 2016 Life Blood Centre .PDF
2015 - 2016 Life Blood Centre .PDFJIGAR VYAS
 

Viewers also liked (15)

2013 Red Cross Blood Bank - Rajkot Contract
2013 Red Cross Blood Bank - Rajkot Contract 2013 Red Cross Blood Bank - Rajkot Contract
2013 Red Cross Blood Bank - Rajkot Contract
 
Regime de trabalho docente
Regime de trabalho docenteRegime de trabalho docente
Regime de trabalho docente
 
Mba em marketing e comunicação digital – cultura digital
Mba em marketing e comunicação digital – cultura digitalMba em marketing e comunicação digital – cultura digital
Mba em marketing e comunicação digital – cultura digital
 
Richmond Music Fest
Richmond Music FestRichmond Music Fest
Richmond Music Fest
 
Historia del celular
Historia del celularHistoria del celular
Historia del celular
 
Wikis lizbeth y michelle
Wikis lizbeth y michelleWikis lizbeth y michelle
Wikis lizbeth y michelle
 
te process
te processte process
te process
 
Amanresume
AmanresumeAmanresume
Amanresume
 
SOMOTEX PRESENTATION
SOMOTEX PRESENTATIONSOMOTEX PRESENTATION
SOMOTEX PRESENTATION
 
PrabhatKumarCV_Spanish
PrabhatKumarCV_SpanishPrabhatKumarCV_Spanish
PrabhatKumarCV_Spanish
 
Presentación 2° Focus Group Enero 2016
Presentación 2° Focus Group Enero 2016Presentación 2° Focus Group Enero 2016
Presentación 2° Focus Group Enero 2016
 
Florette (presentación investigación primaria)
Florette (presentación investigación primaria)Florette (presentación investigación primaria)
Florette (presentación investigación primaria)
 
English Biscuit Manufacturers SCM ASSIGNMENT EBM
English Biscuit Manufacturers SCM ASSIGNMENT EBMEnglish Biscuit Manufacturers SCM ASSIGNMENT EBM
English Biscuit Manufacturers SCM ASSIGNMENT EBM
 
FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...
FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...
FDA 2013 Clinical Investigator Training Course: Issues in Clinical Trial Desi...
 
2015 - 2016 Life Blood Centre .PDF
2015 - 2016 Life Blood Centre .PDF2015 - 2016 Life Blood Centre .PDF
2015 - 2016 Life Blood Centre .PDF
 

Similar to 536684

Pratik_Nawani_Executive Summary_J025_71112110004
Pratik_Nawani_Executive Summary_J025_71112110004Pratik_Nawani_Executive Summary_J025_71112110004
Pratik_Nawani_Executive Summary_J025_71112110004Pratik Nawani
 
4317mlaij02
4317mlaij024317mlaij02
4317mlaij02mlaij
 
Survey analytics conjointanalysis_1
Survey analytics conjointanalysis_1Survey analytics conjointanalysis_1
Survey analytics conjointanalysis_1QuestionPro
 
IRJET- Slant Analysis of Customer Reviews in View of Concealed Markov Display
IRJET- Slant Analysis of Customer Reviews in View of Concealed Markov DisplayIRJET- Slant Analysis of Customer Reviews in View of Concealed Markov Display
IRJET- Slant Analysis of Customer Reviews in View of Concealed Markov DisplayIRJET Journal
 
Project report on Share Market application
Project report on Share Market applicationProject report on Share Market application
Project report on Share Market applicationKRISHNA PANDEY
 
BEGIN TITLE THREE INCHES FROM TOP OF PAPER
BEGIN TITLE THREE INCHES FROM TOP OF PAPERBEGIN TITLE THREE INCHES FROM TOP OF PAPER
BEGIN TITLE THREE INCHES FROM TOP OF PAPERbutest
 
Chang_Lu.pdf
Chang_Lu.pdfChang_Lu.pdf
Chang_Lu.pdfAbdetaImi
 
IRJET- Stock Market Prediction using Machine Learning Techniques
IRJET- Stock Market Prediction using Machine Learning TechniquesIRJET- Stock Market Prediction using Machine Learning Techniques
IRJET- Stock Market Prediction using Machine Learning TechniquesIRJET Journal
 
Estimize Bull speed using Back propagation
Estimize Bull speed using Back propagationEstimize Bull speed using Back propagation
Estimize Bull speed using Back propagationIJMER
 
STOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHON
STOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHONSTOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHON
STOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHONIRJET Journal
 
Essay On Rain Prediction
Essay On Rain PredictionEssay On Rain Prediction
Essay On Rain PredictionKimberly Thomas
 
Impact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock MarketImpact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock Marketinventionjournals
 
Impact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock MarketImpact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock Marketinventionjournals
 
[Project] Customer experience and buying behaviour in e-commerce sites
[Project] Customer experience and buying behaviour in e-commerce sites[Project] Customer experience and buying behaviour in e-commerce sites
[Project] Customer experience and buying behaviour in e-commerce sitesBiswadeep Ghosh Hazra
 
Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...
Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...
Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...IRJET Journal
 
Estimize Bull speed using Back propagation
Estimize Bull speed using Back propagationEstimize Bull speed using Back propagation
Estimize Bull speed using Back propagationIJMER
 
Mini Projects
Mini ProjectsMini Projects
Mini Projectspichu90
 
Big Data Analytics for Predicting Consumer Behaviour
Big Data Analytics for Predicting Consumer BehaviourBig Data Analytics for Predicting Consumer Behaviour
Big Data Analytics for Predicting Consumer BehaviourIRJET Journal
 
Prediction system report and results-Jay Vora
Prediction system report and results-Jay VoraPrediction system report and results-Jay Vora
Prediction system report and results-Jay VoraJay Vora
 

Similar to 536684 (20)

Pratik_Nawani_Executive Summary_J025_71112110004
Pratik_Nawani_Executive Summary_J025_71112110004Pratik_Nawani_Executive Summary_J025_71112110004
Pratik_Nawani_Executive Summary_J025_71112110004
 
4317mlaij02
4317mlaij024317mlaij02
4317mlaij02
 
Survey analytics conjointanalysis_1
Survey analytics conjointanalysis_1Survey analytics conjointanalysis_1
Survey analytics conjointanalysis_1
 
IRJET- Slant Analysis of Customer Reviews in View of Concealed Markov Display
IRJET- Slant Analysis of Customer Reviews in View of Concealed Markov DisplayIRJET- Slant Analysis of Customer Reviews in View of Concealed Markov Display
IRJET- Slant Analysis of Customer Reviews in View of Concealed Markov Display
 
Neural trading term paper
Neural trading term paperNeural trading term paper
Neural trading term paper
 
Project report on Share Market application
Project report on Share Market applicationProject report on Share Market application
Project report on Share Market application
 
BEGIN TITLE THREE INCHES FROM TOP OF PAPER
BEGIN TITLE THREE INCHES FROM TOP OF PAPERBEGIN TITLE THREE INCHES FROM TOP OF PAPER
BEGIN TITLE THREE INCHES FROM TOP OF PAPER
 
Chang_Lu.pdf
Chang_Lu.pdfChang_Lu.pdf
Chang_Lu.pdf
 
IRJET- Stock Market Prediction using Machine Learning Techniques
IRJET- Stock Market Prediction using Machine Learning TechniquesIRJET- Stock Market Prediction using Machine Learning Techniques
IRJET- Stock Market Prediction using Machine Learning Techniques
 
Estimize Bull speed using Back propagation
Estimize Bull speed using Back propagationEstimize Bull speed using Back propagation
Estimize Bull speed using Back propagation
 
STOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHON
STOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHONSTOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHON
STOCK MARKET PREDICTION USING MACHINE LEARNING IN PYTHON
 
Essay On Rain Prediction
Essay On Rain PredictionEssay On Rain Prediction
Essay On Rain Prediction
 
Impact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock MarketImpact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock Market
 
Impact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock MarketImpact and Implications of Operations Research in Stock Market
Impact and Implications of Operations Research in Stock Market
 
[Project] Customer experience and buying behaviour in e-commerce sites
[Project] Customer experience and buying behaviour in e-commerce sites[Project] Customer experience and buying behaviour in e-commerce sites
[Project] Customer experience and buying behaviour in e-commerce sites
 
Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...
Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...
Identifying Malicious Reviews Using NLP and Bayesian Technique on Ecommerce H...
 
Estimize Bull speed using Back propagation
Estimize Bull speed using Back propagationEstimize Bull speed using Back propagation
Estimize Bull speed using Back propagation
 
Mini Projects
Mini ProjectsMini Projects
Mini Projects
 
Big Data Analytics for Predicting Consumer Behaviour
Big Data Analytics for Predicting Consumer BehaviourBig Data Analytics for Predicting Consumer Behaviour
Big Data Analytics for Predicting Consumer Behaviour
 
Prediction system report and results-Jay Vora
Prediction system report and results-Jay VoraPrediction system report and results-Jay Vora
Prediction system report and results-Jay Vora
 

536684

  • 1. MECN4005 – Design Project Agent Based Simulation of the JSE Name: Ashail Maharaj Student Number: 536684 Supervisor: Dr Ian Campbell 2 November 2016 A project report submitted to the Faculty of Engineering and the Built Environment, University of the Witwatersrand, Johannesburg, in partial fulfilment of the requirements for the degree of Bachelor of Science in Engineering. Johannesburg, November 2016
  • 2. ii DECLARATION UNIVERSITY OF THE WITWATERSRAND, JOHANNESBURG SCHOOL OF MECHANICAL, INDUSTRIAL AND AERONAUTICAL ENGINEERING I Ashail Maharaj Student Number: 536684, am registered for the course No. MECN 4005 - in the year 2016. I herewith submit the following task, “Design Project: Agent Based Simulation of The JSE” in partial fulfilment of the requirements of the above course. I hereby declare the following:  I am aware that plagiarism (the use of someone else’s work without their permission and/or without acknowledging the original source) is wrong;  I confirm that the work submitted herewith for assessment in the above course is my own unaided work except where I have explicitly indicated otherwise;  This task has not been submitted before, either individually or jointly, for any course requirement, examination or degree at this or any other tertiary educational institution;  I have followed the required conventions in referencing the thoughts and ideas of others;  I understand that the University of the Witwatersrand may take disciplinary action against me if it can be shown that this task is not my own unaided work or that I have failed to acknowledge the sources of the ideas or words in my writing in this task. Signature: ________________________________ Date: 2/11/2016
  • 3. iii EXECUTIVE SUMMARY This project focuses on the simulation of trading on the Johannesburg Stock Exchange (JSE). For the purpose of this project, one share had been selected to be traded in the simulation. The share that was chosen was Richemont CFR, which is one of the top five companies listed on the JSE. The simulation designed in this report initially aimed at modelling the share price as a function of multiple factors, the factors that were initially considered were:  Fundamental pricing information including dividends.  Distribution of knowledge.  Economic conditions such as exchange rate, overseas market closing levels, inflation, interest rates and commodity prices that may be correlated to the share.  Market perceptions of the company including company ethics.  Risk profiles and time views (e.g. buy and hold, day trading, etc.)  Competition and alternatives in the market.  Financial level (and size of trades). Prior research found that only the volume traded was strongly correlated to the share price. The volume traded however showed strong correlations with the Rand-Euro and Rand-Dollar exchange rate as well as the platinum price. This finding led to the idea of modelling the market through supply and demand due to the strong relationship between the share price and volume traded. After concept selection was done, simplifying assumptions were made to start building the model. The chosen model had agents that entered the market, and made decisions on whether to buy or sell a share. This decision was based on whether their intrinsic value was less than or greater than the market value. If the intrinsic value was greater, then the agent would buy. If the intrinsic value was less, the agent would sell. The model was then broken down into two major components, namely the agent and the trading system. The agent logic comprised of agent decisions to transact, intrinsic value estimation, agent logic and the agent attributes. The trading system was broken down into the matching of orders, exchange of shares and cash, expiration of orders, maintaining trading hours and creating an overreaction in the market. While validating the components, it was found that the neural network function created in Anylogic, which was used for the estimation of the intrinsic value for the agents, did not perform as required, although it was still responsive and changed values with given inputs. Using the neural network resulted in incorrect values which did not change much from day to day. The model was also found to be too slow if too many agents were used. Validating the model using historic data was not possible as the simulation created very high frequency intraday data, for which actual data was not available.
  • 4. iv However, as part of the validation, the simulations’ price series was tested to see if the presence of stylized facts existed. These stylized facts show that the model can represent reality to some degree. This resulted in the finding that the returns were non-normally distributed and leptokurtic. It was then recommended that a software called Matlabcontrol should be used to link Matlab with Anylogic. Using as this would allow the user to get exactly the function created in Matlab. A number of other recommendations pertaining to the decision logic and further building of the model, to make it more realistic, were noted in Section 9.
  • 5. v Acknowledgements I would like to acknowledge and thank my parents for always supporting me, no matter the circumstance. I would also like to thank Dr Ian Campbell for supervising me through this period. His guidance and advice has been invaluable to me.
  • 6. vi TABLE OF CONTENTS DECLARATION....................................................................................................................................ii ACKNOWLEDGEMENTS....................................................................................................................v TABLE OF CONTENTS.......................................................................................................................vi LIST OF FIGURES ................................................................................................................................x LIST OF TABLES...............................................................................................................................xiii 1. INTRODUCTION ..........................................................................................................................1 1.1 Background.............................................................................................................................1 1.2 Motivation...............................................................................................................................2 1.3 Task as given...........................................................................................................................3 1.4 Task as understood..................................................................................................................3 2 LITERATURE REVIEW ...............................................................................................................4 2.1 Agent based Simulation ..........................................................................................................4 2.2 Discrete Event Simulation ......................................................................................................4 2.3 System Dynamics Simulation.................................................................................................4 2.4 Johannesburg Stock exchange ................................................................................................5 2.5 Option trading.........................................................................................................................5 2.6 Double auction market............................................................................................................5 2.7 Limit order book .....................................................................................................................5 2.7.1 Limit order ......................................................................................................................5 2.7.2 Market order....................................................................................................................6 2.8 Supply and Demand................................................................................................................6 2.9 Market Efficiency ...................................................................................................................9 2.10 Martingales .............................................................................................................................9 2.11 Stylized facts...........................................................................................................................9 2.12 Agent Learning and Artificial Intelligence ...........................................................................10 2.12.1 Neural Networks ...........................................................................................................10 2.12.2 Feed-Forward Back Propagation (FFBP) neural network.............................................11
  • 7. vii 2.12.3 Fuzzy Logic ..................................................................................................................13 2.12.4 Genetic Algorithms.......................................................................................................13 2.13 Fundamental analysis............................................................................................................13 2.14 Technical Analysis................................................................................................................14 2.14.1 Trend Analysis..............................................................................................................15 2.14.2 Support and Resistance Analysis ..................................................................................15 2.14.3 Volume Analysis...........................................................................................................15 2.15 Kurtosis.................................................................................................................................16 2.16 Skewness...............................................................................................................................17 2.17 Normality..............................................................................................................................17 2.18 Stationarity............................................................................................................................18 2.18.1 Difference stationarity...................................................................................................18 2.18.2 Trend Stationarity .........................................................................................................18 2.18.3 Difference and Trend Stationary...................................................................................18 2.18.4 Testing for Trend stationarity and Difference Stationarity...........................................18 2.19 Homoscedasticity..................................................................................................................20 2.19.1 Engle test for residual heteroscedasticity......................................................................20 2.20 Random Walk Hypothesis ....................................................................................................20 2.20.1 Pure Random Walk.......................................................................................................20 2.20.2 Random walk with drift ................................................................................................21 2.20.3 Deterministic trend........................................................................................................21 2.20.4 Random walk with drift and deterministic trend...........................................................21 2.21 Related studies ......................................................................................................................21 2.21.1 Chan et al. 1999 ............................................................................................................21 2.21.2 Preyen Nair 2014 .........................................................................................................22 3 HIGH LEVEL PRODUCT REQUIREMENT SPECIFICATION ...............................................23 3.1 Requirements ........................................................................................................................23 3.2 Constraints ............................................................................................................................23 3.3 Criteria ..................................................................................................................................23
  • 8. viii 3.4 Assumptions..........................................................................................................................23 4 CONCEPT GENERATION..........................................................................................................24 4.1 Concept Creation ..................................................................................................................26 4.1.1 Concept 1 ......................................................................................................................27 4.1.2 Concept 2 ......................................................................................................................28 4.1.3 Concept 3 ......................................................................................................................29 4.2 Concept Selection .................................................................................................................30 5 THE DESIGN PROCESS.............................................................................................................33 6 DESIGN DEVELOPMENT OF THE MODEL ...........................................................................34 6.1 Agents (Traders) ...................................................................................................................34 6.1.1 Product Requirement Specification...............................................................................34 6.1.2 Concept Development and Specification......................................................................35 6.1.3 Validation......................................................................................................................44 6.2 Trading platform ...................................................................................................................59 Product Requirement Specification...............................................................................59 Concept Development and Specifications ....................................................................60 6.2.2 Validation......................................................................................................................69 6.3 Assumptions Made for the Model.........................................................................................78 6.4 Limitations of the model.......................................................................................................79 7 VALIDATION OF MODEL’S PERFORMANCE AS A WHOLE.............................................79 8 CRITICAL ANALYSIS OF DESIGN..........................................................................................82 8.1 Comparing Completed model with the criteria.....................................................................83 8.1.1 Accuracy of prediction..................................................................................................83 8.1.2 Data Presentation and collection...................................................................................83 8.1.3 Ease of use ....................................................................................................................83 8.1.4 Speed.............................................................................................................................83 8.1.5 Realistic behaviour........................................................................................................83 8.1.6 Ease of creating the concept in Anylogic......................................................................83 8.1.7 Modular building and interactions ................................................................................83
  • 9. ix 8.2 Shortcomings in representing the market..............................................................................84 9 RECOMMENDATIONS..............................................................................................................84 9.1 Representing the market........................................................................................................84 9.2 Neural network......................................................................................................................84 10 REFERENCES .........................................................................................................................85 APPENDIX A:......................................................................................................................................90
  • 10. x LIST OF FIGURES Figure 1: Demand Relationship[15]........................................................................................................6 Figure 2: Supply Relationship[15]..........................................................................................................7 Figure 3: Economic Equilibrium [15].....................................................................................................7 Figure 4: Excess Supply[15]...................................................................................................................8 Figure 5: Excess Demand [15]................................................................................................................8 Figure 6: Graphical Explanation of Kurtosis and Skewness[21]..........................................................10 Figure 7: Perceptron Configuration[28]................................................................................................11 Figure 8: Moods of the masses according to technical analysis[38].....................................................14 Figure 10: Concept 1 Flow Chart..........................................................................................................27 Figure 11: Concept 2 Agent State Chart ...............................................................................................28 Figure 12: Concept 2 Activity Cycle Diagram .....................................................................................28 Figure 13: Concept 3 Agent State Chart ...............................................................................................29 Figure 14: Concept 3 Activity Cycle Diagram .....................................................................................30 Figure 15: Agent Logic Flowchart........................................................................................................37 Figure 16:Flowchart for Decisions to Buy or Sell ................................................................................38 Figure 17: Flowchart of the general logic for creation of Intrinsic Value ............................................39 Figure 18: Flowchart of the Feedforward Back Propagation used to create a function in Anylogic....40 Figure 19: Structure of neural network used in Matlab ........................................................................41 Figure 20: An Increase in Demand [64]................................................................................................42 Figure 21: Flowchart of The Logic Used for The Buy and Sell Buttons Which Are Used to Represent an Overreaction in The Market .............................................................................................................43 Figure 22: Validation that Changing of states occurs...........................................................................44 Figure 23: Validation That the Share Price is Never Below Zero ........................................................45 Figure 24:Validation That the Minimum Amount of Shares an Agent Can Hold is Zero....................45 Figure 25:Validation That Cash held is Always Positive .....................................................................46 Figure 26:Validation That Cash Never Goes Below Zero....................................................................46 Figure 27: Validation That the Number of Shares in The System Stays Constant Throughout ...........47 Figure 28: Screenshot of Simulation Before Pressing Buy Button.......................................................48 Figure 29:Screenshot of Simulation After Pressing Buy Button ..........................................................48 Figure 30: Screenshot of Simulation Before Pressing Sell Button .......................................................49 Figure 31: Screenshot of Simulation After Pressing Sell Button..........................................................49 Figure 32: Screenshot of simulation before (left side) and after (right side) pressing Buy Now button ..............................................................................................................................................................50 Figure 33: Screenshot of simulation before (left side) and after (right side) pressing Sell Now button ..............................................................................................................................................................51
  • 11. xi Figure 34: Screenshot of Simulation Before (Left Side) And After (Right Side) Increasing the Share Price ......................................................................................................................................................52 Figure 35: Screenshot of Simulation Before (Left Side) And After (Right Side) Decreasing the Share Price ......................................................................................................................................................52 Figure 36: Plot of Output and Error of Feed Forward Backpropagation Neural Network as well as the Actual Data ...........................................................................................................................................53 Figure 37:R2 Values Between Target and the Output of the Neural Network, for the Training, Validation, Test and All 3 Runs............................................................................................................54 Figure 38: Sum Squared Error for training, testing and validation runs...............................................54 Figure 39: Validation of Neural Network Using Newer Data ..............................................................54 Figure 40: Screenshot of Simulation Before (Left Side), After Decreasing (Middle) and After Increasing (Right) the Platinum Price ....................................................................................................................55 Figure 41: Screenshot of Simulation Before (Left Side), After Increasing (Middle) and After Decreasing (Right) the Rand-Dollar Exchange Rate...............................................................................................56 Figure 42: Screenshot of Simulation Before (Left Side), After Increasing (Middle) and After Decreasing (Right) the Rand-Euro Exchange Rate..................................................................................................56 Figure 43: Output from neural network in Matlab................................................................................57 Figure 44:Inputs and output to neural network in Anylogic.................................................................57 Figure 45:Price Sensitivity to Platinum Price.......................................................................................58 Figure 46: Price Sensitivity to Change in the Rand-Euro Exchange Rate............................................58 Figure 47:Price Sensitivity to Rand-Dollar Exchange Rate..................................................................58 Figure 48: Queuing System Used in Model..........................................................................................60 Figure 49: Flowchart of The Logic Used for The Exchange of Share and Money...............................61 Figure 50: Calculations Done in The False Then False Action Box in The Flowchart of The Logic Used for The Exchange of Shares and Money...............................................................................................62 Figure 51: Calculations Done in The False Then True Action Box in The Flowchart of The Logic Used for The Exchange of Shares and Money...............................................................................................62 Figure 52: Calculations Done in The True Action Box in The Flowchart of The Logic Used for The Exchange of Shares and Money............................................................................................................63 Figure 53: Flowchart of The Expiration of Orders ...............................................................................64 Figure 54: Screenshot of The Trading Hours Schedule........................................................................65 Figure 55: Screenshot of the “TradingHours” Parameter .....................................................................66 Figure 56: Screenshot of “event1”........................................................................................................67 Figure 57: Screenshot of the Logic Used in the “EvalEvent” Function................................................68 Figure 58: Screenshot of the SelectOuput4 logic..................................................................................68 Figure 59: Screenshot of the Queuing System Used in the Model .......................................................69
  • 12. xii Figure 60:Validation That Continuous Match Will Occur till The Entire Number of Shares to Trade Has Been Traded..........................................................................................................................................70 Figure 61: Screenshot of Simulation Before Agent Buys Shares .........................................................73 Figure 62: Screenshot of Simulation After Agent Buys Shares............................................................74 Figure 63: Screenshot of Simulation Before Agent Sells Shares..........................................................75 Figure 64: Screenshot of Simulation After Agent Sells Shares ............................................................76 Figure 65: Validation That After Expiry Agents Leave the Matching Queue......................................77 Figure 66: Validation That After Trading Hours No Shares are Traded ..............................................78 Figure 67: Frequencies of The Share Prices from The Simulation Model............................................82 Figure 68: Frequency Plot of the Returns .............................................................................................82
  • 13. xiii LIST OF TABLES Table 1: Agent logic for price, logic and order types[2].......................................................................22 Table 2: Concept Creation Matrix ........................................................................................................26 Table 3: Concept Rating Table .............................................................................................................30 Table 4: Summary of Data from Buying Screenshots ..........................................................................71 Table 5: Summary of Data from Selling Screenshots...........................................................................72 Table 6: Comparison of Model Data with Actual Data ........................................................................80 Table 7: Summary of tests done on the outputs of the simulation........................................................81
  • 14. 1 1. INTRODUCTION 1.1 Background A stock market is a network of buyers and sellers, each of whom are trading stocks. Stocks represent a shareholding in the company that issued the share. Companies issue shares to raise capital, and initially the stock is valued by the amount of capital require divided by the number of shares issued. The capital is exchanged for holdings in the company. This project focuses around the simulation of the trading that occurs on the JSE. For the purpose of this project, one share has been selected to be traded in the simulation. The share that was chosen is Richemont CFR which is listed in the top five companies on the JSE. The simulation designed in this report initially aimed at modelling the share price as a function of multiple factors. The factors that were initially considered were:  Fundamental pricing information including dividends.  Distribution of knowledge.  Economic conditions such as exchange rate, overseas market closing levels, inflation and interest rates as well as commodity prices that may be correlated to the share.  Market perceptions of the company including company ethics.  Risk profiles and time views (e.g. buy and hold, day trading, etc.)  Competition and alternatives in the market.  Financial level (and size of trades). The project was then split into two components. The first being the research of factors that correlated with the share price, which was prior research to the design of the simulation. In the research, it was found that the Richemont share price was only strongly correlated to the volume traded. The volume traded however showed strong correlations with the Rand-Euro and Rand-Dollar exchange rate as well as the platinum price. Upon finding this, the idea for the simulation had changed from the all-encompassing view to trying to model the share price as a function of its volume, while using the other factors to forecast the share price.
  • 15. 2 1.2 Motivation The modelling of a market generally requires theories to understand how the entire market will react. The agent-based approach to simulating a market requires basic logic that can vary from trader to trader. Each of these traders’ logic then create reactions in the market. This is why neuroeconomics is useful. Neuroeconomics is an interdisciplinary field that provides explanation behind the motivation of individuals’ actions. The study of this allows for the individualism of entities to be taken into account when modelling complex systems. For modelling these complex systems using neuroeconomics, agent- based simulations are becoming more widely used. One of the fields of interest for the application of agent-based simulations is the social science of economics. Economics is defined as the study of production and trade. One of the fundamentals upon which economics was based is the theory of supply and demand. This theory tries to create an understanding about how buyers and sellers interact, how they make their choices according to the quantities demanded and supplied, and how price is affected by these interactions. This design project tries to incorporate economics of financial markets with the individualistic decision making that neuroeconomics studies by creating an agent based model of a financial market. Forecasting and modelling of financial markets have led to interesting discussions about accuracies and the ability of a model to explain certain aspects of real markets. These aspects have come to be known as stylised facts. Recently the growing trend in artificial intelligence and automation have also led to the creation of interesting ideas such as the algobot. An algobot is a programme that makes decisions on whether to place orders to buy or sell shares, how long to hold for or even when to buy or sell shares. The concept of algobots, is what inspired this project. Having an algobot does not necessarily mean that it be correct all the time. As seen with most AI algorithms, training is needed before prediction can become accurate. This could be a problem as inaccuracy in training could lead to financial losses. To avoid these risks, a simulation of a market that could represent reality would be a good place to train an algobot or to test different trading strategies. Drawing on all of the above mentioned, the idea of creating a simulation model, that could model individual decisions based on their perception of a share and other environmental factors, was created.
  • 16. 3 1.3 Task as given Design, build and validate a market model of a financial trading market. The model should encompass the influential factors which affect the market. Agent-based simulation will be used to simulate the individual interactions of traders. 1.4 Task as understood Design an agent-based simulation of a financial trading market. The market will be driven by the factors within the market such as price, demand and supply of shares, and external environmental factors. Seeing as the scope of the task is large, there will be justified simplifying assumptions made so that the project can be completed in the time given. The simulation will be built as a foundation to creating a more complex market structure. The factors that will be considered in the external environment are the Platinum price(R/oz.), Rand-Euro exchange rate and the Rand-Dollar exchange rate. The above factors were chosen due to prior research which had found a strong correlation between the volume traded and the Richemont share price. The relationship between the volume traded had strongly negative correlations to the factors mentioned above. Therefore, this simulation is an attempt to model the share price based on volume traded, while trying to model the volume traded with the external environmental factors. [1] Due to the nature of this problem, a supply-demand formulation will be applied to this model. Where the price will move to try to reach an equilibrium point. Validation of the model will include comparison to the Richemont share price, comparing the volume traded with the share price to ensure that the volume traded is creating changes in the share price, and ensuring that agents are making choices according to the environmental factors.
  • 17. 4 2 LITERATURE REVIEW 2.1 Agent Based Simulation Agent based simulation is a method used for modelling complex scenarios which involve individual decision making and interactions between individuals. Agent based models may combine elements of game theory, complex systems, emergence or evolutionary programming. Agents may also use artificial intelligence in their decision-making processes to learn over time[2]. Agent based models have three elements [3]: 1. Self-contained, autonomous agents with attributes and behaviour 2. Interaction between agents 3. An environment in which the agents can interact with each other and the environment Agent based simulations are used in a wide variety of fields. Fields including economics, finance, military planning, city management, traffic simulations, routing problems and most social sciences. Simulations are used to test a hypothesis by changing factors in the real world, as this cannot be done feasibly, it is best to test these in a simulation. ABMs are also used to confirm theoretical results or when a problem is too complex to be solved analytically[3], [4]. 2.2 Discrete Event Simulation A discrete event simulation is a method of explaining behaviour of a complex system as a sequence of ordered events. Discrete event simulations are stochastic as each of the events that occur introduce randomness to the system. A discrete event simulation must include the following properties[5], [6]: 1. Predetermined starting and ending points 2. A method of keeping track of the time that has passed since the start of the process. 3. A list of events that have occurred 4. A list of events that are expected 2.3 System Dynamics Simulation System dynamics is used to understand nonlinear complex systems over time using feedback loops, stocks and flows. When modelling system dynamics it is recommended that one[5] :  models the system as a causally closed structure which defines its own behaviour  discovers the circular causality balancing or reinforcing  identifies stocks and flows that affects the system
  • 18. 5 2.4 Johannesburg Stock Exchange The Johannesburg Stock Exchange (JSE) is the 19th largest stock exchange in the world and the largest in Africa, by market capitalisation. The JSE offers secure and efficient primary and secondary capital markets across a diverse range of securities[7]. The JSE provides a market where securities can be traded and regulated. The exchange raises primary capital by channelling cash resources into productive economic activity. 2.5 Option Trading An option is a contract which gives the buyer the right to buy or sell an asset at a specified price before a specified date. There are two types of options, namely; calls and puts. A put order gives the holder the option to sell their assets at a given price within the period stipulated by the contract. The buyer of a put hopes that the stock falls before the option expires. A call order gives the holder the option to buy an asset at a given price within the specified period. The buyer of the call hopes that the stock increases before the option expires[8]. 2.6 Double Auction Market A double auction market is the system which is used to buy and sell securities through brokers on stock exchanges. The double auction market consists of many buyers and many sellers[9]. In a double auction market buyers and sellers enter competitive offers with their orders, as opposed to the over the counter method which uses negotiation to reach a deal. Double auction markets can also use the outcry method, which is characterised by buyers and sellers calling out prices till a transaction occurs when a buyer and a seller call out the same price[10]. 2.7 Limit Order Book A limit order book is a list of unexecuted limits orders which is maintained by a member of the stock exchange, who acts as the market maker. This member posts the bid and ask prices, manages limit orders and executes trades between the buyers and sellers. It is the duty of the market maker to ensure that during large movements in the demand or supply, it reaches an equilibrium. If not for this market maker, prices would rise or fall during large movements in the demand and supply respectively[11]. 2.7.1 Limit Order A limit order, as the name states, is an order that states the limit that the buyer or seller is willing to trade at. For example, if a buyer wants to buy a share at a maximum price of R2 per share, he will place a buy limit order. A sell limit sets the minimum price the seller is willing to sell at[12]. Limit orders have to have an expiration date which is usually a 90-day period at maximum.
  • 19. 6 2.7.2 Market Order A market order is an order that is made immediately at the best available current price. In the trading system, a market order is guaranteed to be executed as there are no time constraints like options or price restrictions as there are with limit orders. For this reason, the market order is also known as an unrestricted order. There is also one other difference between the order limit and the market order, this is the price of the transaction. In general, the price of a limit order transaction is higher than the cost of the market order. It is also important to note that is some markets, market orders are not allowed.[13], [14] 2.8 Supply and Demand Supply is defined as the quantity of a commodity that is available to be sold in a market. Demand is defined as the total quantity of a commodity that is wanted by the traders in the market. Supply and demand are the fundamentals behind the study of a market economy. The law of demand states that there is a negative relationship between price and the quantity demanded. In Figure 2 the relationship between price and quantity for demand is shown. The law of demand basically states that as the price of some commodity decreases; the more people would want to buy. Figure 1: Demand Relationship[15] The law of supply, has a positive relationship between the price and the quantity. This is due to suppliers seeing higher opportunity at higher prices, this results in more suppliers wanting to sell. In Figure 2, the relationship between price and quantity supplied is shown.
  • 20. 7 Figure 2: Supply Relationship[15] Economic equilibrium is said to be reached when the quantity supplied and the quantity demanded are equal. As seen in Figure 3, when the quantities of supply meet that of the demand there is a single price that the commodity is worth. The equilibrium can only be reached in theory and as a result the price keeps fluctuating. Figure 3: Economic Equilibrium [15] When the market is not in equilibrium there are two possibilities that could occur, excess demand or excess supply. If the price is set too high, an excess in supply will be created as the buyers would not want to buy and the sellers would want to sell. In Figure 4, it can be seen that an excess supply is created by both, the buyers and sellers moving away from the equilibrium point due to the high price. In order to reach equilibrium, the price of the commodity would need to decrease. This can be seen by shifting the the price till the supply line meets the demand line.
  • 21. 8 Figure 4: Excess Supply[15] On the other extreme, if the price is too low, the quantity supplied would decrease and the quantity demanded would increase. As seen in Figure 5, shifting the price upward would allow the market to reach equilibrium. Figure 5: Excess Demand [15] It is also important to note that the demand and supply curves can both be shifted, keeping the price constant but changing the quantity and thus creating a new equilibrium relationship. These shifts can be created on the demand due to the lack of substitutable commodities and as a result people are willing to pay the set price. A change in supply would result from a shortage of sellers in the market [14]. Supply and demand relationships can be exploited to understand markets, for example most share prices are highly correlated with the volume traded, this is often seen by chartists.
  • 22. 9 2.9 Market Efficiency Market efficiency is derived from the Efficient Market Hypothesis (EMH), which states that at any given time, the prices fully reflect all available information on the stock or market involved. There are three degrees of efficiency in the market[16]: 1. Strong Efficiency This states that all information about the stock or the market are accounted for in the stock price and that insider information wouldn’t even give the trader an advantage. 2. Semi-Strong Efficiency This form of the EMH states that all public information about the stock or market are included in the share price and that technical or fundamental strategies would not give the user superior gains. 3. Weak Efficiency This type of EMH states that all of the previous prices of the price series are reflected in the stock price currently and therefore technical analysis would not gain the user an advantage in beating the market. 2.10 Martingales The martingale property states that the conditional expectations of a sequence of partial sums is its current value. The martingale property ensures that, in a fair game, knowledge of the past is of no use to predicting the future outcomes[17]. 2.11 Stylized Facts A stylised fact refers to empirical findings that are consistent across different instruments, markets and time periods. Stylised facts are presented as a truth or a generalisation about the properties of the subject matter. Theories and model must fit these empirical findings in order to validly explain these phenomena, the absence of these empirical finding may then be attributed to inaccuracies in the theories or models[18], [19]. Some of the stylized facts relating to share price prediction are[20]; 1. Non-Normal Return Distributions This can be tested by doing a Kolmogorov-Smirnov test to check whether the distribution is normal or not. The kurtosis and skewness need to be tested. Kurtosis above a value of 3 is known to be leptokurtic whereas kurtosis below 3 is said to be platykurtic. In Figure 6 below the shapes of the graphs are shown for each of the skewness and kurtosis cases. Skewness can also be measured to indicate if the return data is identically distributed.
  • 23. 10 Figure 6: Graphical Explanation of Kurtosis and Skewness[21] 2. Volatility clustering of returns Volatility clustering, as defined by Benoit Mandelbrot, refers to “large changes in returns tend to follow large changes in returns” and that “small changes in returns would be followed by small changes in returns” [22]. This can be tested by testing if the returns are autocorrelated followed by testing if the series is heteroscedastic using the Engle’s ARCH test[23]. 3. High and persistent trading volume 4. Existence of technical trading 2.12 Agent Learning and Artificial Intelligence Artificial intelligence is defined as intelligence displayed by computer programs or machines. It also generally describes the ability of a non-living entity to exhibit cognitive ability. Cognitive ability is generally defined by problem solving and learning abilities. The field draws on knowledge from the computer science, mathematics, psychology, linguistics, philosophy, neuroscience and artificial psychology backgrounds. Commonly used AI algorithms are; Neural networks, decision trees, fuzzy logic and genetic algorithms[24]. 2.12.1 Neural Networks A neural network is derived from the way biological nervous systems process information. Neural networks are large networks that connect inputs to outputs using links. Each link has its own weight which changes as the neural network is trained (this is synonymous to learning as it is trial and error, until the correct method is learnt from previous mistakes or errors). Just like in the brain, training helps
  • 24. 11 improve connections between the nodes in order to better the result. Figure 7 shows the structure of a perceptron neural network, note that there are three layers; an input layer, hidden layer and an output layer. Between the input and the hidden layers are connections and each connection has a weight annotated by the letter w. Weights are also found on the connections between the hidden layer and the output layer[25]–[27]. Figure 7: Perceptron Configuration[28] For the purpose of this report only one type of neural networks is specifically important, this is the Feed Forward Back Propagation (FFBP) method. 2.12.2 Feed-Forward Back Propagation (FFBP) Neural Network The FFBP neural network is identical to the neural network in Figure7. The calculations required by the neural network, assuming that there are no biases, that the delta learning rule is applied and that the inputs and outputs are scaled between 0 and 1, are listed below.  Step 1 Create a set of weights between the values of 0.2 and 0.8 for the all the connections in the network.  Step 2 Calculate the effective input into the hidden layer using Equation 1. 𝑆ℎ = ∑(𝑥𝑖×𝑤𝑖ℎ) 𝑛 𝑖=1 (1) Where 𝑆ℎ is the Effective input 𝑥𝑖 is the input of the network 𝑤𝑖ℎ is the matrix of weights between input i and hidden node h
  • 25. 12  Step 3 Calculate the outputs of the hidden layer using Equation 2. This uses the log sig activation function as the inputs and outputs are between 0 and 1. 𝑌ℎ = 1 1 + 𝑒−𝑆ℎ (2) Where 𝑌ℎ is the vector of outputs from the hidden layer  Step 4 Calculate the outputs of the neural network using Equation 3. 𝑌𝑜 = ∑(𝑦ℎ×𝑤ℎ𝑜) 𝑛 𝑖=1 (3) Where 𝑌𝑜 is the vector of outputs from the neural network.  Step 5 Calculate the error between the target and the output of the neural network using Equation 4. 𝑒𝑟𝑟𝑜𝑟 = 𝑡𝑎𝑟𝑔𝑒𝑡 − 𝑌𝑜 (4)  Step 6 Adjust the weights between the outputs and the hidden layer using Equation 5 to find the amount that the weights need to be adjusted by and Equation 6 to update the weights. ∆𝑤ℎ𝑜 =∝ (𝑒𝑟𝑟𝑜𝑟)×𝑌ℎ (5) 𝑤ℎ𝑜 = 𝑤ℎ𝑜 + ∆𝑤ℎ𝑜 (6) Where ∆𝑤ℎ𝑜 is the amount that the weights need to be updated by ∝ is the learning rate, usually set to 0.5
  • 26. 13  Step 7 Update the weights between the input and the hidden layer using Equation 7 to calculate the error, Equation 8 to calculate the amount that the weights need to updated by and Equation 9 to calculate the and update the weights. 𝛿ℎ = 𝛿 𝑜× (∑ 𝑤ℎ𝑜) ×2×𝑌ℎ×(1 − 𝑌ℎ) (7) ∆𝑤𝑖ℎ =∝×𝛿ℎ×𝑥𝑖 (8) 𝑤𝑖ℎ = 𝑤𝑖ℎ + ∆𝑤𝑖ℎ (9) Where 𝛿ℎ is the error propagated back to the connections between the input and the hidden layer 𝛿 𝑜 = error 2.12.3 Fuzzy Logic Fuzzy logic makes use of degrees of truth rather than having Boolean decisions. For example, making use of fuzzy logic helps generate truth about agents belonging to a number of states rather than strictly one. A good example of this is having hard logic of whether an object is hot or cold compare to having fuzzy logic with states that lay between the two, warm, room temperature or cool[24], [27], [29]–[31]. 2.12.4 Genetic Algorithms Genetic algorithms are used for solving constrained and unconstrained optimisation problems. They ae based upon the process of natural selection, in which only the strongest survive and pass their genetics to the future generation. Genetic algorithms are used in agent based simulations to get populations that are more adapted to the situations that occurred in the past. The ability of an agent to survive is measured by the fitness of each agent. In the context of a financial market, genetic algorithms could be used to identify which strategies are most suited to which situations in the market [23], [26], [31], [32]. 2.13 Fundamental analysis Fundamental analysis is a method of evaluating the value of a share through company performance and reactions to economic conditions. Fundamental analysis seeks to understand more about the company and the actions taken by the company to essentially answer the question “Does the company make a good investment?”. [34] Fundamental analysis is not limited to using purely qualitative or purely quantitative data. News about a company can usually be helpful in evaluating a company. Quantitative analysis usually includes
  • 27. 14 looking at the company’s finances to create an intrinsic value of the share. Revenue, debt, dividends, and company performance ratios are used to measure intrinsic value [35]. The objectives of fundamental analysis are [36]:  To predict the performance of economies that impact a company. This is done because the financial performance of the company is dependent upon the economy is resides within.  To estimate the intrinsic value of the stock and try to predict when changes in this value will occur.  To select the right time to buy and sell stocks to maximise investment returns. 2.14 Technical Analysis Technical analysis is the analysis of statistics generated by market activity. These statistics are generally past prices or volumes traded[37]. The aim of technical analysis is to identify patterns that can suggest future activity. Technical analysis typically depends on the use of charts patterns, technical indicators, oscillators or some combination of the above mentioned[38]. Technical analysts believe that charts show the moods of the crowds and therefore focus on the analysis of mass human psychology. Emotional risk is inversely correlated to financial risk; Figure 1 below displays the moods associated with the different price trends. Figure 8: Moods of the masses according to technical analysis[38] People are generally motivated by greed and optimism when buying and are driven by fear or pessimism when selling. It is believed that people formulate scenarios based on their emotional state in order to rationalise their emotions. Investors will try to sell at the top or as close to the top, and buy at the bottom or as close to the bottom as possible[38].
  • 28. 15 2.14.1 Trend Analysis Trend analysis is one of the most important and most used techniques in technical analysis. In trend analysis, trends are classified according to their direction into three sets; uptrends, horizontal trends and downtrends. An uptrend is characterised by a series of higher highs and higher lows whereas a downtrend is characterised by lower lows and lower highs[39][38]. Trends can then be classified into a further set of three; a long-term trend, an intermediate trend and a short-term trend. A long-term trend is one that last longer than a year, an intermediate trend lasts between one and three months and a short-term trend is considered to last up to a month. Channel lines are the addition of two parallel trend lines which act as areas of support and resistance[38]. 2.14.2 Support and Resistance Analysis Support is defined as the price level which the stock seldom falls below and resistance is the price level which the stock seldom increases above. Support and resistance are governed by the psychology behind supply and demand. Where the support is the price level which the market is willing to buy at and the resistance level is the price at which the market is willing to sell at. When the price breaches the support or the resistance level this means that there has been a shift in the supply or demand curves for the shares. Once the resistance or support level is breached, it’s role will be reversed, i.e. the resistance level will become the support level if the resistance level is broken and vice versa for the support level[39][40]. 2.14.3 Volume Analysis Volume analysis is important to technical analysis because it is used to confirm chart trends and patterns. In most scenarios, a change in volume precedes a change in price. The exception to this is when the volume and price relationship starts to deteriorate[40][41]. 2.3.4 Pearson’s Product Moment Correlation Coefficient Pearson’s Product moment correlation (PPMC) also referred to as the Pearson’s correlation coefficient is a measure of how well two variables are related linearly. It enables the user to know whether fitting a straight line to the data accurately represents the relationship between the variables in question. The equation below is used to calculate the coefficient of correlation. A strong correlation is represented by an r value within the intervals [0.7; 1] or [ -1; -0.7]. Where an absolute value of 1 represents a perfect linear relationship. A moderate strength correlation would fall within the intervals [0.3;0.7] or [-0.7; - 0.3]. Low correlation is represented with a value within the ranges [0.1;0.3] or [-0.3; -0.1]. No correlation results in an r value of 0. [1]
  • 29. 16 𝑟 = 𝑛(∑ 𝑥𝑦) − (∑ 𝑥)(∑ 𝑦) √(𝑛 ∑ 𝑥2 − (∑ 𝑥)2)(𝑛 ∑ 𝑦2 − (∑ 𝑦)2) (10) 𝑟 = 𝑐𝑜𝑣(𝑥, 𝑦) 𝑆 𝑥 𝑆 𝑦 (11) Where 𝑛 is the number of observations in the sample 𝑥 is the independent variable 𝑦 is the dependant variable 𝑐𝑜𝑣(𝑥, 𝑦) is the covariance between the two variables 𝑆 𝑥 is the sample standard deviation of the independent variable 𝑆 𝑦 is the sample standard deviation of the dependent variable 2.15 Kurtosis Kurtosis is used as a statistical tool to evaluate a probability distribution. Kurtosis describes the shape of the distribution, more specifically it measures the weight of the tails of a distribution. There are three states of kurtosis. Mesokurtic describes a distribution with a kurtosis value of 3, which is the same as a standard normal curve. Leptokurtic distributions have a kurtosis value of above 3, this describes a distribution with a higher peak than the normal curve and has fatter tails than the standard normal curve. A Platykurtic distribution has a kurtosis value of less than 3, it describes the distribution as a flatter, more spread out distribution of the data[42]. Sample kurtosis is calculated using the Equation 12. 𝐾 = 𝑛(𝑛 + 1)×(𝑛 − 1) (𝑛 − 2)×(𝑛 − 3) × ∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 4𝑛 𝑖=1 (∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 2𝑛 𝑖=1 ) 2 (12) Where 𝑥𝑖 is the ith value of the dataset 𝑛 is the sample size 𝐾 is the kurtosis
  • 30. 17 The population kurtosis is calculated using Equation 13 𝐾 = 𝑛× ∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 4𝑛 𝑖=1 (∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 2𝑛 𝑖=1 ) 2 (13) 2.16 Skewness Skewness is the measure how identical a distribution is. A non-zero value of skewness means that the data is skewed. Sample skewness is calculated using Equation 14. 𝑆 = 𝑛√𝑛 − 1 𝑛 − 2 × ∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 3𝑛 𝑖=1 (∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 2𝑛 𝑖=1 ) 3 2 (14) Population skewness is calculated using Equation 15. 𝑆 = √ 𝑛× ∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 3𝑛 𝑖=1 (∑ (𝑥𝑖 − 𝑥 𝑎𝑣𝑔) 2𝑛 𝑖=1 ) 3 2 (15) 2.17 Normality Normality is the measure of how data is distributed and if the normal distribution can be fit to the data significantly. The statistical methods that can be used to test this, are the Kolmogorov-Smirnov Test [29] (see Equation 16 for test statistic) and the Shapiro-Wilk test (see Equation 17 and 18 for test statistic) [30]. 𝑇 = 𝑚𝑎𝑥|𝐹∗(𝑥) − 𝑆(𝑥)| (16) Where 𝑇 is the test statistic used for the Kolmogorov-Smirnov test 𝐹∗(𝑥) is the data being tested 𝑆(𝑥) is the empirical distribution data (data from the normal distribution for normality tests) 𝑊 = ( 𝑏 𝑠√𝑛 − 1 ) 2 (17) 𝑏 = ∑ 𝑏𝑖 = ∑ 𝑎(𝑛 − 𝑖 + 1)(𝑋 𝑛−𝑖+1 − 𝑋𝑖) (18)
  • 31. 18 Where 𝑊 is the test statistic for the Shapiro-Wilk test 𝑏 is defined by Equation 10 𝑎 is defined as a Shapiro-Wilk coefficient (𝑛 − 𝑖 + 1) is defined as a Shapiro-Wilk coefficient 𝑥 is defined as the data from the series being tested Kolmogorov-Smirnov Test uses p-values to compare the test statistic and to accept or reject the null hypothesis of the data being normal. The Shapiro-Wilk test uses critical values from a Shapiro-Wilk table of values to compare the test statistic and conclude if the null hypothesis is accepted or rejected. 2.18 Stationarity 2.18.1 Difference Stationarity A series with a random walk can be transformed into a stationary process using differencing, irrespective of whether it has drift or not. [43] 2.18.2 Trend Stationarity A nonstationary process with a deterministic trend can be transformed into a stationary process by detrending. [43] 2.18.3 Difference and Trend Stationary In cases where a random walk with drift and a deterministic trend, stationarity can be achieved through detrending but differencing needs to also be applied in order to ensure that the variance does not grow to infinity over time. [43] 2.18.4 Testing for Trend Stationarity and Difference Stationarity There are two preferred methods for testing for stationarity, these are the Augmented Dickey-Fuller (ADF) test and the Kwiatkowski–Phillips–Schmidt–Shin (KPSS) test [43]–[48]. 2.18.4.1 Augmented Dickey-Fuller Test (ADF) In the ADF test Equation 17 below is used to represent an AR process [44], [49], [50] Where 𝛿 ∈ [0,1], when 𝛿 is 0 the process is unit root stationary, when 𝛿 ≠ 0 then the process is not. The test sets a null hypothesis that the process is unit root stationary. 𝐻0: 𝛿 = 0 𝐻1: 𝛿 ≠ 0 ∆𝑌𝑡 = 𝛼 + 𝛿𝑌𝑡−1 + 𝑒𝑡 (19)
  • 32. 19 A t-statistic is calculated for the 𝛿̂ which is the estimated value of 𝛿. This test statistic is then compared to the critical values from the Dickey-Fuller Distribution. When 𝑡 < 𝐷𝐹𝐶𝑟𝑖𝑡𝑖𝑐𝑎𝑙 (20) The null hypothesis is rejected. The 𝐷𝐹𝐶𝑟𝑖𝑡𝑖𝑐𝑎𝑙 value can be calculated using Equation 21. 𝐷𝐹𝐶𝑟𝑖𝑡𝑖𝑐𝑎𝑙 = 𝛿̂ 𝑆𝐸(𝛿̂ ) (21) 2.18.4.2 Kwiatkowski–Phillips–Schmidt–Shin (KPSS) Test This test evaluates whether a univariate series is trend stationary as the null hypothesis and that it is a nonstationary unit root process. It does this by first defining the series with Equation 22 below [51][52]. 𝑌𝑡 = 𝑐𝑡 + 𝛽𝑡 + 𝑢1𝑡 (22) 𝑐𝑡 = 𝑐𝑡−1 + 𝑢2𝑡′ (23) Where 𝑐𝑡 is some random walk process 𝑢1𝑡 is a stationary process 𝑢2𝑡′ is and independent and iid process with a mean of 0 and variance 𝜎2 𝐻0: 𝜎2 = 0 𝐻0: 𝜎2 > 0 With the test statistic 𝑝𝑡𝑒𝑠𝑡 = ∑ 𝑆𝑡 2𝑇 𝑡=1 𝑆2 𝑇2 (24) Where 𝑝𝑡𝑒𝑠𝑡 is the p-test statistic 𝑇 is the sample size 𝑆2 is the Newey-West estimate of the long-run variance And 𝑆𝑡 = 𝑒1 + 𝑒2 + 𝑒3 + ⋯ +𝑒𝑡 (25)
  • 33. 20 2.19 Homoscedasticity Homoscedasticity describes the variance of a series, it means that the variance does not increase with time[53]. Homoscedasticity can be tested graphically by looking at plots of residuals against actuals. It can also be tested using the Engle test for residual heteroscedasticity. 2.19.1 Engle Test for Residual Heteroscedasticity Residuals of the series are defined as in Equation 24 𝑒𝑡 = 𝑦𝑡 − 𝑢̂ 𝑡 (26) Where 𝑢̂ 𝑡 is the conditional mean of the process 𝑒𝑡 is the residual which is identically distributed with a mean of 0 and variance of 1 𝐻0: 𝛼0 = 𝛼1 = 𝛼2 = ⋯ = 𝛼 𝑚 𝐻1: 𝑒𝑡 2 = 𝛼0 + 𝛼1 𝑒𝑡−1 2 + 𝛼2 𝑒𝑡−2 2 = ⋯ = 𝛼 𝑚 𝑒𝑡−𝑚 2 + 𝑢 𝑡 Where 𝑢 𝑡 is a white noise error process The null hypothesis tests that series is not heteroscedastic. The test statistic is found by using the F statistic for regression on the squared residuals, and the critical value is found in the 𝒳2 distribution using m degrees of freedom and the required significance[54][55]. 2.20 Random Walk Hypothesis 2.20.1 Pure Random Walk A pure random walk is defined by the equation 𝑌𝑡 = 𝑌𝑡−1 + 𝜀𝑡 (27) Where 𝜀𝑡 is white noise 𝑌𝑡 is the series value at time t 𝑌𝑡−1 is the series value at time t-1 White noise is stochastic; this means that this series will not become mean reverting as the variance will evolve over time. The variance of the series will tend to infinity as time tends to infinity. This is a difference stationary process[43].
  • 34. 21 2.20.2 Random Walk with Drift This series is defined by the equation below 𝑌𝑡 = 𝛼 + 𝑌𝑡−1 + 𝑒𝑡 (28) Where 𝛼 is the drift term in the series This series too has a variance that is dependent on time and hence is not mean reverting. This is a difference stationary process. [43] 2.20.3 Deterministic Trend This is defined by the equation below 𝑌𝑡 = 𝛼 + 𝛽𝑡 + 𝑒𝑡 (29) Where 𝛽𝑡 is the deterministic trend This series although it looks similar to that of a random walk with drift is different as it is a regressed series of the time trend 𝛽𝑡. A nonstationary process with a deterministic trend has a mean that grows around a fixed trend which is constant and independent of time. This is a trend stationary process. [43] 2.20.4 Random Walk with Drift and Deterministic Trend This series is described by the equation below 𝑌𝑡 = 𝛼 + 𝑌𝑡−1 + 𝛽𝑡 + 𝑒𝑡 (30) This series has both a drift component and a deterministic trend. This is both difference and trend stationary. [43] 2.21 Related Studies 2.21.1 Chan et al. 1999 Chan et al. constructed a simulation of a double auction market. The simulation modelled the complex interactions between artificially intelligent traders. The traders had varying degrees of learning capabilities. The price efficiency, speed of price convergence to rational equilibrium, dynamics of wealth distribution amongst the AI trade, trading volume and the bid ask spread were monitored during the simulation in order to tell how accurately the simulation modelled the market behaviour. In the breakdown of the problem, Chan et al. created four major components for the simulation. These were the economic environment, the trading systems, the types of the traders and the learning mechanisms. The traders were also split into three groups, Insiders, partially informed and the uninformed trader.
  • 35. 22 The trading mechanism used was a simple double auction market, within which agents could only submit bids and asks. The prices of subsequent bids, had to be higher than the current bid and asks had to be lower than the current asks. The agents were also restricted to the trade of a single share at a time. Traders were assumed to be risk neutral, and agent maximised their end-of-period expected values of their portfolios by forecasting the liquidating dividend. The agents then bought when market prices were low relative to their forecast and sold when market prices were higher than their forecast. Chan et al. also created three types of traders, empirical Bayesian traders, momentum traders and nearest neighbour traders. Each of these had different learning mechanisms.[56] 2.21.2 Preyen Nair 2014 Nair created an agent based simulation of the trading of a single share on the JSE. As part of the scope and requirements, Nair had to design a double auction market according to the specifications used by the JSE for creating their order matching engine. Auction periods and hidden order were outside the scope of the model created. Nair split up his model into three components and focused on completing these before moving on. These components were; the orders, order processing engine and the order book. These three components were central to his design. The orders had to validated and work in the system that he created. Upon completion of the three components, agents were developed. The logic that was used to model the agents decisions to buy, sell or hold was based on the risk and return of the transactions. Table 1 below summarises the logic used to create the decisions for each agent. Table 1: Agent logic for price, logic and order types[2] Where p is the price level aq t is the best quoted ask price bq t is the best quoted bid price P* is the agents comfort price level Si t is the current stock portfolio of agent i at time t pM is the upper value that the agent is comfortable paying i (p) is the demand function at p for agent I pm is the lower value that the agent is comfortable paying
  • 36. 23 3 HIGH LEVEL PRODUCT REQUIREMENT SPECIFICATION 3.1 Requirements  Behaviour matches market behaviour  Outputs share price information as a time series.  Uses agent-based simulation  Uses input data for agents to make decisions with 3.2 Constraints  All agents are rational  A single share will be used in the model  Assumptions could make the model less realistic  Difficult to identify and quantify all the drivers for price 3.3 Criteria  Accuracy of prediction  Data Presentation and collection  Ease of use  Speed  Realistic behaviour  Ease of creating the concept in Anylogic.  Modular building and interactions 3.4 Assumptions  All agents will be rational  Agents will only transact with the cash that they have and no borrowing of money will be allowed  Prices will not be less than zero  Intraday factor values will be created by using a uniform distribution between the upper and lower values for the day.  Only one share will be traded  A set number of agents will be within the market (there are no new entities entering the market or any leaving)
  • 37. 24 4 CONCEPT GENERATION Before concept generation, it is important to survey literature to see what has been done and how it was done previously. In doing this it was found that when creating an agent based model the following are considered[13], [20], [57]–[61], [33], [62], [63]. 1. Agent Learning Learning in the models generally include genetic algorithms and neural networks in order for each agent to change over time and adapt to the situation that they are in. The learning is applied to agents’ decisions to buy, sell or hold shares, as well as decide what price the share is worth or even which share to buy. These would usually be used in conjunction with different strategies of trading. Some models use strategies like technical and fundamental trading while others use maximisation of utility or portfolio values. 2. Zero-Intelligence traders Zero-intelligence traders are traders who buy or sell randomly in the market with some constraints attached to them, Farmer et al explain that zero-intelligence agents are able to explain stylized facts on the London Stock Exchange. One of these facts being allocative efficiency, also known as Smiths Invisible hand, which guides the market toward an equilibrium price based on the supply demand and the price. 3. Minimal Rationality This follows the argument that not all agents act in the interest to maximise their portfolio, and in trying to model the market realistically, needs to be considered. 4. Replication of Stylized Facts When building a model, there are various checks to see how realistic the model is, these checks are done by looking for certain characteristics within the data. Characteristics such as non- normal return distributions (described by a kurtosis greater than 3 or a Jarque-Bera test with a p-value of 0), volatility clustering of returns, high and persistent trading volumes, and the existence of technical trading. 5. Trading Logic (Technical traders, Fundamental traders or a combination of both) 6. Double Auction Markets Many models use this method to create the value of the shares, the process consists of buyers and sellers submitting bids for a share at a price they value it at, the auctioneer would then select a price that clears the market. 7. Matching Engines The order matching engine allows for each order to be matched by price and preference (decided by first in first out or other such queuing criteria).
  • 38. 25 Before the concept creation, Anylogic was used to create a few sample models to better understand the problems that would be faced when trying to create the model. Some of the problems found were;  Creation of an order book that each agent can read and then value the share  Using the shares like resources, as it made it difficult to attach the shares to the agent if agents just sent orders instead of standing going through a queuing system.  Creating a population for orders and ensuring that information is copied from agent to the order as well as keeping count of the orders and which order belonged to which trader.  Creating new agents that enter the trader population and having some leave too. This created a problem as this could create a time varying total number of shares in the market. To deal with these problems various solutions were tried, Concepts 1 to 3 shown below solved most of the problems. It is also important to note that due to time constraints the model will need to be simplified. Although simplified, the model will be flexible and will be able to be developed further and could be seen as a base for future work.
  • 39. 26 4.1 Concept Creation In Table 2, each concept is defined by the components that will make up the design, each component can be made modularly and then the whole concept put together. Agent logic describes how the trader agent creates different actions under the given scenarios. The trading system is the component that allows for the bids and exchange of the share to occur. The evaluation of the share price would be a subcomponent of the agent logic as this is what is used to decide what price the trader is willing to pay according to the factors given. Intrinsic value is what the agent is willing to pay at maximum when buying or receive at minimum when selling. Table 2: Concept Creation Matrix Concepts Agent Logic Trading System Valuating Share Price Intrinsic Value Buy/Sell/Hold Decisions Matching Orders Concept 1 State Chart Agent Based According to Intrinsic value Uses linear regression Price based Decision by entity responding to message and FIFO Concept 2 State Chart Modelled as Queueing According to last sold Uses linear regression Demand/supply based Modelled as Queuing Concept 3 State Chart Modelled as Queueing According to last sold Neural network with scaling using supply demand ratio Demand/Supply and Price based Modelled as Queuing
  • 40. 27 4.1.1 Concept 1 This concept tries to function as an agent only model, making use of only the agents logic and trading occurs through communication between agents directly. It uses the state chart to define its behaviour entirely. The biggest foreseen problem with this concept is the messages the sellers continue to send, this could affect the speed of the simulation as this means there would be more event occurring at any given time. Figure 9 below shows the state chart and the logic within each state. This logic is still basic as this is still a concept. Figure 9: Concept 1 Flow Chart
  • 41. 28 4.1.2 Concept 2 This concept makes use of a queuing system to handle the exchange and matching of shares. The order agent is sent to the queue with the details of the transaction, like the quantity and price. This method also requires there to be a resource used for the shares. Figure 10 shows the state chart that will be used in this concept, notice that it is similar to that of Concept 1, although this does not have as many processes within the states. Figure 11 shows the queuing systems proposed for this concept. Figure 10: Concept 2 Agent State Chart Figure 11: Concept 2 Activity Cycle Diagram
  • 42. 29 4.1.3 Concept 3 This concept uses a very similar state chart to the first two concepts, although there are more ways for an agent to enter into the buy or sell state, as can be seen in Figure 13. Figure 14 shows the queuing system to be used in the model, note that in this concept no agents will leave the queuing system, the agents will be moving from state to state and while doing that will be moving in the queuing systems according to their state. Figure 12: Concept 3 Agent State Chart
  • 43. 30 Figure 13: Concept 3 Activity Cycle Diagram 4.2 Concept Selection Each concept is rated out of 5 for each of the judging criteria, note that the accuracy of the concept is uncertain at this stage and can only be measured accurately after the model is completed as this is a complex system. There is a chance that the observations after the model has been complete may deviate from these ratings. As a result of this, flexibility of the model has not been added as one of the judging criteria. All criteria will however, be kept in mind while creating the chosen concept. Extra steps will be taken to try to ensure that the criteria have been kept at the level expected. Table 3, rates each concept and compares them amongst each other. Table 3: Concept Rating Table Concepts Data Presentation and collection Ease of use Speed Realistic behaviour Ease of creating in Anylogic Totals Concept 1 4 4 5 2 2 17 Concept 2 4 4 3 5 2 18 Concept 3 4 4 3 5 3 19
  • 44. 31  Data Presentation and collection Data presentation and collection is defined by the ability to gather important information about the model and convert it into graphs or other means of summarising the data. This would be easy for each concept due to Anylogic being simple to use for information and statistical gathering. The log function allows one to see in what order events are occurring. The dataset functions allow for quick gathering of statistical data throughout a time series.  Ease of use The ease of use of the model is defined by the ability of the user to change the parameters to better suit the scenario they are trying to create. In Anylogic these changes can be made easily by creating either sliding bars, buttons, radio buttons, and other GUIs. The change of the data that is needed for the environmental factors would have to be done using the databases that have been imported from excel files. All concepts would score high on this due to the ease of use of Anylogic.  Speed The speed is defined as the time it takes to run the simulation. This would vary according to the method used. For example, running an agent-based simulation with lots of agents and with complex interactions may take longer than a normal discrete time simulation. Concept 1 would be faster than the other concepts due to the simplicity of the model. Concept 1 would use purely agent based simulation, and transactions would occur almost instantly due to the auction method coupled with FIFO for matching the orders. Concepts 2 and 3 are hybrid models, the agent exists within a system while making decisions based on the environment, for this reason these two models would take longer than the first.  Realistic behaviour The behaviour of the model would need to come close to that of the interactions in reality (with some simplifying assumptions). There are a few stylised facts that could be simulated using the model. The main aim is to have traders buy and sell according to supply and demand while changing the price accordingly. Model 1 is a simple solution which bases the decisions on whether the agent wants to accept an offer or reject it. Model 1 uses linear regression to evaluate the intrinsic value and then if the offer is god enough it is accepted. Model 1 has one major flaw; it only has the sellers sending out offers and the buyers react to that. For this reason, it is not as realistic as the other two models. Model 2 also uses linear regression to create the intrinsic value, this could lead to incorrect calculation of the share’s intrinsic value. This makes Concept 3 the best in this category.
  • 45. 32  Ease of creating the concept in Anylogic Concept 3 seems to be the easiest to create as the potential problems are less. Some of the foreseen major problems for each concept are as listed below; Concept 1  Selecting which agent sent the message to the agent who is selling first.  Sending an offer to buy the share to a specified agent.  Creating the trade between the two agents  Telling the agents when the seller has found a buyer.  Selecting which selling agent will be selected or ignored while there are many sellers  Selecting an agent when there are multiple offers to buy, at the same price at the same time. Concept 2  Creating an order as an agent and sending this as a message which has been fully customised according to the expiry time, price, volume.  After the order seizes the share (in the buying case), there would be a problem of attaching the share to the trader who created the order.  Orders will be destroyed when they leave the queuing system  Selling orders would need to be attached to shares when entering the system  Orders are randomly chosen to be used by a trader, this could mean that the possibility of leaving all shares attached to the order for each trader. Concept 3  Creating the neural network in Anylogic  Matching orders according to the price  Having entities from a specific a population enter the system and interact with the system according to the decisions the agents make Concept 3 has been chosen to continue further development as it is rated the best out of the three concepts created, as seen in Table 3.
  • 46. 33 5 THE DESIGN PROCESS The design process used in creating this model followed the steps listed below. 1. Literature search on how other similar models were created. 2. Break down the problem into a number of smaller problems and start finding ways to solve each problem. 3. Create basic flow charts of how each solution can be modelled. 4. Create simplifying assumptions. 5. Try to create a basic model to find the difficulty areas. 6. Create concepts to get around the problem areas. 7. Choose a concept. 8. Develop the concept. 9. Iterate steps 1 until 8 until a possible way to model each system is found. 10. Test the model and debug. 11. Validate the model components. 12. Validate the model as a whole. The bottom-up approach was used to design the model, this entails modelling the agents behaviour and their interaction first. The model was developed in the order listed below. Note this is a not an exhaustive list as there are too many components to be listed individually. 1. Create the agents and their attributes. 2. Create their states and ensure that they are able to move between states. 3. Create the queuing system and ensure that agents can move around in it according to their states. 4. Create the intrinsic value algorithm (basic). 5. Create the share price and intrinsic value comparison method. 6. Ensure that agents can change states according to the intrinsic value and the share price. 7. Ensure that the correct number of shares and cash are traded. 8. Create databases for each factor. 9. Create a schedule for each factor to change according to the day. 10. Create the neural network function.
  • 47. 34 6 DESIGN DEVELOPMENT OF THE MODEL The simulation has been broken down into 2 main subsystems. The subsystems are the traders and the trading platform. Each of these needs the other to perform. The basic idea the concept should follow is that the agents will be in the observe state initially. While in the observe state the agents will watch the share price, they will then compare the share price to an intrinsic value. On comparing the share price to the intrinsic value, the agent will decide whether or not to buy or sell. The agent will buy if the share price is lower than their intrinsic value and sell if the share price is higher than their intrinsic value. Upon making this decision, the agent will then be sent to the trading platform to trade with another agent. The trading of the share will only occur if the price an agent is willing to sell is less than the price the other agent wants to buy at, i.e. their price ranges must overlap. Upon doing this the agents are matched and carry out the transaction. If one of the agents has a greater number of shares to transact, that agent will return to the queue to be matched again, this will continue until the agent has no more shares that they want to buy or sell. The design specifications for each component will follow under Sections 6.1 and 6.2. Each of the subsystems will then be further broken down into the respective components. 6.1 Agents (Traders) The agents used in this model are only one set of traders, these traders all act to buy or sell. There are no holding periods for the agents of this population. The only time that the agents stay within the observe state is when the trading day has ended. Note that these traders will only trader if they perceive a as share worth buying or selling (there is some sort of benefit that they can receive from trading). A further population of agents could easily be generated and the frequency of transacting could be changed. The current population are high frequency traders. In Section 6.1.1 the product requirement specifications are listed for the creation of the agents. The agent design is split into four components namely, agent decisions to buy or sell, agent intrinsic value creation, agent logic and the agent attributes. 6.1.1 Product Requirement Specification 6.1.1.1 Requirements  Agents must be able to buy and sell shares  Agents need to be able to determine when to buy shares and sell the shares they hold  Agents need to be able to determine what price the shares are worth intrinsically  Agents need to have different levels of income  Agents will need to interact with each other when sharing information 6.1.1.2 Constraints  Agents cannot have negative amounts of shares  Agents cannot borrow money to buy more shares  Agents have to place an order and wait till the trading system matches the order
  • 48. 35 6.1.1.3 Criteria  Agents are able to valuate a share price according to environmental factors  Agents are able to buy a share when required  Agents are able to sell a share when required  Agents can interact if required  Agents receive a fixed income every month  Agents are able to act individually  Ease of use in Anylogic  Model created needs to be flexible. 6.1.2 Concept Development and Specification In this section the various subcomponents of the agents’ design will be detailed further. 6.1.2.1 Agent Parameters Agents have various factors as attributes such as;  Money held.  Selling, holding or buying.  Number of shares held.  Expiry.  Maximum price willing to buy at.  Minimum price willing to sell at.  Waiting in queue (Binary 0 meaning that it is waiting in a queue to transact, 1 meaning it is not).  Forecasted price.  Learning rate for neural network.  Weights for neural network.  Biases for neural network.  Current time.  Exited (This attribute says whether the agent has left the trading or not).  Trading hours (this attribute tells the agent how long the trading should occur for).  Transaction (Transaction =0 if in observe state, Transaction=1 if in waiting to buy state and Transaction=2 if in waiting to sell state).
  • 49. 36 6.1.2.2 Agent Logic In Figure 14, the logic for the agent state changes as well as the logic for the entry and exit of the queueing system is shown. Note that there are three more states than with the concepts. The states that were added, are there for the transitions between the observe state and the buy state as well as between the observe state and the sell state, these two were added to create a visual validation that agents are buying, selling or waiting to carry out those transactions. The third state, called the return state in Figure 15, is there to ensure that when the buy or sell button is pressed agents enter and change their colour to black. This too is for a visual validation of the buy and sell buttons. When an agent is moving from the observe state to the waiting to buy state, it has to meet the condition that the cash it has is greater than the cost of the number of shares the agent wishes to purchase. This constraint ensures that the cash an agent has is never negative. When an agent is moving from the observe state to the waiting to sell state, it must meet the condition that the agent must be holding more shares than it wants to sell. This constraint ensures that the agent is always holding a non-negative number of shares. Both transitions require the condition that it must be trading hours to move from the observe state. Outside of trading hours all agents will not flow into the waiting to transact states.
  • 50. 37 Figure 14: Agent Logic Flowchart
  • 51. 38 6.1.2.3 Agent Decisions to Buy or Sell While agents are in the observe state, they need to evaluate whether they want to buy or sell. The logic in Figure 15 shows what the process for deciding to buy or sell entails. This logic is basically checking if the share price is greater than or less than the intrinsic value the agent has for the share price. If the intrinsic value is greater than or equal the share price, the agent will sell. If the intrinsic value is less than the share price, the agent will buy. Figure 15:Flowchart for Decisions to Buy or Sell
  • 52. 39 6.1.2.4 Agent Intrinsic Value Creation In Figure 16 below, is the general flow chart for the creating of intrinsic value of the agents in the population trader. The data is scaled linearly according to the maximum and minimum data of each daily data set for the past 5 years. After scaling the data, it will be between 0.2 and 0.8, this was done to account for data going below or above the historic data. After the neural network, the data is scaled back into the share price data. From this point the share price is then scaled according to the supply and demand with Equation 31 and Equation 32 below. 𝑀𝑖𝑛𝑊𝑖𝑙𝑙𝑖𝑛𝑔𝑇𝑜𝑆𝑒𝑙𝑙𝐴𝑡 = IntrinsicValue× (1 + ( (𝑉𝑜𝑙𝑢𝑚𝑒𝑇𝑜𝐵𝑢𝑦 − 𝑉𝑜𝑙𝑢𝑚𝑒𝑇𝑜𝑆𝑒𝑙𝑙) 10000 ∗ 𝑉𝑜𝑙𝑢𝑚𝑒𝑇𝑜𝑆𝑒𝑙𝑙 )) (31) 𝑀𝑎𝑥𝑊𝑖𝑙𝑙𝑖𝑛𝑔𝑇𝑜𝐵𝑢𝑦𝐴𝑡 = IntrinsicValue ∗ (1 + ( VolumeToBuy − VolumeToSell 10000 ∗ VolumeToBuy )) (32) Figure 16: Flowchart of the general logic for creation of Intrinsic Value In Figure 17, the flow chart for the neural network function created in Anylogic is shown. The neural network function is adaptable to the number of hidden nodes without changing anything but the weights. The weights that are used in to function were trained in Matlab before being used in Anylogic. This is important as the training needed to be done for the agents to have accurate relationships between the factors input and the share price. Start Neural Network Rand: Euro Rand: Dollar Platinum Price Scale data Scale Output Create randomness by using a normal distribution Adjust according to Demand and supply End
  • 53. 40 Figure 17: Flowchart of the Feedforward Back Propagation used to create a function in Anylogic Start Declare Variables h<3 Effective Input Calculation h=0 i=0 True i<3 True S[h]+=X[i]*Wih[i][h] i+=i False S[h]+=bih[h] h+=1 False OutputFrom HiddenLayer Calculations h=0 h<3 True Yh[h]=1/(1+math.exp(-S[h]) h+=1 Summation Into Output Node Calculations h=0 h<3 True Yo=(Who[h]*Yh[h])+ bho h+=1 False Error=Target-Yo; Changing Weights between Output and Hidden Layer h=0 h<3 True DeltaWho[h]=LearningRate*Error*Yh[h Who[h]+=DeltaWho[h]] h+=1 False Error for Weights between Input and hidden layer calculation h=0 h<3 True AltError[h]=2*error*Who[h]*Yh[h]*(1-Yh[h]) h+=1 False Update Weights between input and hidden layer h=0 i=0 i<3 True h<3 True DeltaWih[i][h]=LearningRate*Alterror[h]*X[i] Wih[i][h]+=DeltaWih[i][h] h+=1 False i+=1 False End
  • 54. 41 Figure 18 shows the neural network that was used in creating the intrinsic value using the factors, platinum price, Rand-Euro and Rand-Dollar exchange rates. The neural network was trained using 1250 data points with 60% being used for training, 15% for testing and 25% for testing. After training the weights were exporting into Anylogic and used in the neural network function created. The neural network will be attached in the digital appendix. Figure 18: Structure of neural network used in Matlab Figure 19 shows the relationship between price and quantity as the demand increases. In this case as the quantity demanded increases the price increases proportionally. This proportional increase is given by Equation 33 and 34 below. 𝑃 𝐷𝑡 = 𝑞 𝐷𝑡 𝑚 𝐷𝑡 + 𝑃 𝐷𝑡−1 (33) 𝑃𝑆𝑡 = 𝑞 𝑆𝑡 𝑚 𝑆𝑡 + 𝑃𝑆𝑡−1 (34) Assuming that the price is highly elastic and after a few iterations trying to get the price within a more realistic range, the price elasticity was then used as 10000 as seen in Equations 31 and 32. Price Elasticity is related to the volume and price through Equation 35 𝐸 = ( 𝑞 𝑡− 𝑞 𝑡−1 𝑞 𝑡−1 ) ( 𝑃𝑡 −𝑃𝑡−1 𝑃𝑡−1 ) (35)
  • 55. 42 Figure 19: An Increase in Demand [64] When the quantity supplied surpasses the quantity demanded the price will decrease to reach equilibrium, if the price supplied is higher than the price demanded the quantity demanded will reduce and reach equilibrium. This equilibrium is also known as allocative efficiency. 6.1.2.5 Overreaction in market Figure 20, shows the logic used to create the overreaction in the market using two buttons, buy and sell, these buttons send the agents into a state of “panic” in which they all want to buy or sell.
  • 56. 43 Buy On Press delivertoallagentsInside( BuyNotSell Transaction>0 Agent Receive Message SendToRandom( Buy Transaction==1 True True False Expiry=0 Exit==1 False Agent Leaves State and moves to observe state True Agent Enters Buy State on receiving message buy End End Sell On Press delivertoallagentsInside( SellNotBuyl Transaction>0 Agent Receive Message SendToRandom( Sell Transaction==2 True True False Expiry=0 Exit==1 False Agent Leaves State and moves to observe state True Agent Enters Sell State on receiving message Sell End End Expiry=0 Timeout On Timeout Exit==1 End Figure 20: Flowchart of The Logic Used for The Buy and Sell Buttons Which Are Used to Represent an Overreaction in The Market
  • 57. 44 6.1.3 Validation The validation has been split into 3 sections, namely; agent decisions, agent logic and agent intrinsic value creation. This has been done to validate that each component works as required. 6.1.3.1 Agent Logic Validation that changing of states occur To validate that agents are able to move between states, a count of the number of agents within each set is done at 1 second intervals as seen in Figure 21 below. The blue lines represent the agents within the sell state, the green represents the agents within the buying state and the purple represents the agents within the observe state. Note that this data was collected from running the simulation with trading hours set between 8:00 am and 9:00 am and therefore the trading occurs until around 3600 seconds. Figure 21: Validation that Changing of states occurs Validation that share price is always positive The share price as in reality should not decrease to zero or less as this would mean that a company is giving shares out for free or paying people to buy the shares. This needs to be validated to ensure that the model prices meet that requirement. In Figure 22, it is seen that the share price falls to a minimum that is greater than 2900 cents. It can also be seen that the mean of this series does change over time by looking at the gradient of the mean line as well as the small spikes at certain points.
  • 58. 45 Figure 22: Validation That the Share Price is Never Below Zero Validation that number of shares held is positive One of the assumptions held in this model is that the number of shares that an agent can hold cannot be less than 0. This is a practical assumption that ensures that no credit trading occurs. In Figure 23, the minimum number of shares that any agent in the population trader holds is never less than zero. Figure 23:Validation That the Minimum Amount of Shares an Agent Can Hold is Zero
  • 59. 46 Validation that cash held is always positive Another assumption that ensures that no credit trading occurs, is the assumption that the minimal cash that an agent holds cannot go below zero. In Figure 24 is a graph of the minimum cash that any agent holds in the population trader over time. It can be seen that the smallest value that an agents’ money goes to is 80000 cents. One could argue that due to the large amount of starting cash and a short run time, the agents don’t get the chance to spend all their cash. To show that the cash does not go below zero, a simulation was run with the starting amount of cash set to 0 for each agent. As seen in Figure 25, the minimum stays at zero and never goes below. Figure 24:Validation That Cash held is Always Positive Figure 25:Validation That Cash Never Goes Below Zero
  • 60. 47 Validation that the number of shares in the system stays constant The assumption that the total number of shares in the market is conserved and will neither grow nor decrease over time also needs to be validated to show that this does not cause any price fluctuations. In Figure 26 below depicts the constant number of share in the market for the simulation running for 3600 seconds. Figure 26: Validation That the Number of Shares in The System Stays Constant Throughout Validate that agents can leave their states on the message buy or sell Buy and sell buttons were created to show how the model would simulate an overreaction in the market, over reaction caused by events that make the traders want to buy or to sell. Figure 27 shows the what states the agents are in before the buy button is pressed, note that the pink represents the buying state, the red represents the selling state, green represents the waiting to buy state, the blue represents the waiting to sell state and the yellow represents the observing state. Figure 28 shows the population states after the button has been pressed, note that there are agents which have turned black, this means that the agents have left their selling states and are leaving to move to the waiting to buy state. The black colour could be seen as the agents moving into a panic state. On entering this “panic” state, agents send messages to random agents telling them to buy the share. Figure 29 shows the agents before the sell button has been pressed, note that there are no black coloured agents, this means that there are no agents in the “panic” state before the sell button was pressed. Figure 30 shows the agents leave their states and enter a panic state and start sending messages to random agent to sell their shares. The black colour acts as the validation that the agents are performing the require action upon pressing the button. NumberofSharesinMarket
  • 61. 48 Figure 27: Screenshot of Simulation Before Pressing Buy Button Figure 28:Screenshot of Simulation After Pressing Buy Button
  • 62. 49 Figure 29: Screenshot of Simulation Before Pressing Sell Button Figure 30: Screenshot of Simulation After Pressing Sell Button
  • 63. 50 6.1.3.2 Agent Decisions to Buy, Hold or Sell Validation that the price changes according to the supply and demand for the share In order to validate that the price changes according to the supply and demand quantities of the share, buttons were created to change the values of the volumes demanded and supplied. These buttons are called “BuyNow” and “SellNow”. Figures 31 and 32 both have four graphs each, the graphs on the top represent the share price series, the graphs at the bottom represent the volume to buy and volume to sell series. The graphs on the left are prior to pressing the respective button and the graphs on the right are the graphs post pressing the buttons. In Figure 31, it can be seen that after pressing the button, the share price series started to have higher highs than prior to the pressing the “BuyNow” button. In Figure 32, it can be seen that the share price has lower lows after pressing the “SellNow” button. While doing this, it was observed that the relationship is complex, due to agent buying the moment the share price is lower than they expect or selling the moment the share price is higher than expected. Pressing the button that increases the number of sellers, results in a decrease in the price which then results in an increase the number of buyers. Whereas pressing the button that increases the number of buyers, results in a higher share price which then results in an increase in the number of sellers. The price reaches equilibrium fast and as such the overreaction or underreaction in the market creates a small impact on the market in the model. Figure 31: Screenshot of simulation before (left side) and after (right side) pressing Buy Now button