# How to determine the best time for a stock market transaction: Trend following algorithms

For many years, stock market participants have been trying to develop ways to predict future price movements. For this, special algorithms and software , machine learning, or even external services like Google Trends are used . To date, there is no forecasting technique that is 100% effective.

Researchers from the University of Macau several years ago published a paper devoted to the analysis of the effectiveness of trend-following algorithms, which do not try to predict price changes, but precisely respond to its changes in real time. We bring to your attention the main thoughts of this study.

#### Introduction

In general, there are two main approaches to assessing the likelihood of making such forecasts. The followers of the first of them believe that the market can be predicted by analyzing the patterns of price behavior, and the accuracy of the forecast depends on the correct method for detecting these patterns, as well as using the correct set of parameters. The second approach assumes that the stock market is completely random, and it is impossible to predict it using mathematical formulas (there is also mathematical evidence that this is not so).

At the junction of these two "schools" was born the method of following the trend. He suggests that market trends are some random variables. Accordingly, it is not necessary to try to make any forecasts, it is only necessary to generate buy and sell signals by analyzing price movements in the long term. This method is widely used in financial markets, where traders use them to determine when to open or close positions in currency pairs, but it is not so widely used in the stock market.

In today's article, we will focus on two types of trend following algorithms. Researchers aimed to analyze the effectiveness of the application of these algorithms.

#### Two ways to analyze the market

There are two methods for forecasting stock prices:

• Fundamental analysis - in this case, analysts evaluate information that relates more to the company whose shares are traded on the stock exchange than to the shares themselves. Decisions about certain actions on the market are made based on an analysis of the company's previous activities, forecasts of revenue and profits, and so on.
• Technical analysis - in this case, the behavior of the stock price is examined and its various patterns are revealed (analysis of time series is used).

Many of the methods we have previously discussed for forecasting prices in the stock market relate specifically to the field of technical analysis. There is heated debate among financiers and scientists about whether it is possible to predict their future movement by analyzing past prices.

The method of following the trend here is an alternative - it does not imply the creation of forecasts and only responds to events that occurred recently or are happening right now, without thinking about the future. Moreover, trade is subject to certain statistical rules - and the main task is to formulate them.

#### Following the trend: basic principles

The success or failure of the trend-following algorithm depends on what assumptions underlie it. First of all, this assumption includes the regularity of the appearance of price trends, which are a result of many factors. The second important point is the ability of the algorithm to benefit from price movements that shape trends.

All traders strive to “limit losses” and “maximize profits” - you can earn the most by synchronizing with a powerful trend. And to do this, the trader needs to set aside the emotional part of the trade (“intuition”) - the method of following the trend does not imply guessing when it will be completed. On the contrary, it is necessary to act immediately after the onset of this moment.

Based on this, the Performance Probability Score (PPS) model was developed - it combines the analysis of price behavior to create a risk assessment and possible profit. The core of the model forms a binary separation of the behavior of prices into negative and positive. The basic rule when trading using this method sounds like holding a positive or negative rating until the moment when a definite change occurs - again, no predictions, only a reaction to changes.

Trend power price distribution

#### How to determine the right time for a deal

Changes in prices in the stock market provide an opportunity to increase the profit from the transaction or reduce the loss in the event of an unfortunate combination of circumstances. When a price change is detected that goes against an existing trend, a choice arises between immediately closing a position or waiting for confirmation of a change in the current trend and re-entering the position in accordance with the new trend. To automate the process of making such decisions, it is necessary to take into account several important aspects.

• Transaction management - the decision on how much financial asset to buy or sell should be made based on certain rules. To minimize risks, for example, the volume of transactions may decrease during a period of high volatility or a fall in the market. The goal of this is simple - to reduce losses in bad periods in anticipation of more positive trends.
• Market price - the system can use only the market price as input. Some data can be gleaned from the trading history, but they cannot be used to predict the direction of price changes. To create a trading system using the trend following algorithm, you only need to get the latest quotes data as much as possible. Time and price are the main elements.
• Rules - as stated above, you need to limit losses and maximize profits. For this, within the framework of a trend-following system, rules are needed that will not take into account fundamental indicators. They should only automate trading by making decisions about the moment of entering the market, the time of holding the position and the moment of exiting the position when it ceases to be profitable.

Based on the PPS model, researchers have developed a new approach to the implementation of such a trading system. It operates on the basis of two signals extracted from the price trend - based on this information, decisions are made on opening and closing positions.

#### Rules P and Q

The rules described above for limiting losses and maximizing profit in this case are based on two variables - P and Q. The first of them is used to determine the moment when you need to open a position, and the second - to exit it. If we denote the market trend as T, which is a function of time t - Price (t).

In this case, the system could open a position when the current Price price turns out to be above the P point on the trend, and on the contrary, when it falls below the Q level, the position will be closed:

In real life, however, trends do not develop along such clear lines, they are much more volatile, and the price can briefly rise and fall below the general trend line. Therefore, the rules P and Q cannot be applied directly to the trend T - frequent price fluctuations will lead to a huge number of trading signals for buying and selling. In order to avoid this, an Exponential Moving Average (EMA) is used, which is calculated by the formula:

Where price (t) is the current price at time t, n is the number of periods in minutes for intraday trading or in days for non-daily trade, and t is the point in time in the market. The logic for using the P and Q and EMA rules is described by the following pseudo-code:

In this case, the values ​​of P and Q are calculated based on historical data. There are several methods for their final determination. The first of these is the brute force method, which involves testing many combinations of P and Q. An alternative method is to use neural networks.

Ranges of P and Q values ​​obtained using heuristic measurements.

You can choose different values ​​of P and Q that will generate positive results.

#### Adaptive Rules P and Q

In the previous section, the values ​​of P and Q were obtained by analyzing the values ​​that give the best results in a relatively long time interval. However, it is obvious that rules that worked well in a particular section of the trend may not be so good in another. This means that the process of choosing P and Q must be modified so that they can be selected dynamically.

The new rules are called P 'and Q' - their values ​​can dynamically change, but do not remain unchanged, as it was before. In this case, some technical analysis tools, such as the Relative Strength Index (RSI) , can be used to determine the moments of entry and exit from a position . It is calculated by the following formula:

Where AU is the average price increase for n periods, AD is the average price decrease for n periods, n is the number of RSI periods (usually set to 14).

A simple use case. In the figure below, RSI has a range from 0 to 100. An asset is considered “overbought” above level 70 - this means that it can be revalued and is a good candidate for a price drop. Similarly, if the RSI reaches level 30, then this is a sure sign of the asset's undervaluation.

As a result, using RSI and the adaptive P&Q strategy, we can formulate the following rules for opening positions:

To open a long position in P ':

1. The price is rising
2. RSI (t) is greater than EMA (RSI (t))
3. EMA (RSI (t)) less than 40 or above 60

For a short position on Q ':

1. The price is down
2. RSI (t) is less than EMA (RSI (t))
3. EMA (RSI (t)) i less than 40 or higher 60

The figure below shows an example of opening a long position: at 10:35 it was opened after the relevant conditions were met. At 13:36, the criteria for opening a short position worked, and the long position was closed.

The values ​​of P 'and Q' adaptively and dynamically change in accordance with the RSI. During trading, the strategy assesses fluctuations in trends and, in accordance with them, generates buy or sell signals.

The pseudocode for such a strategy is as follows:

#### Simulation and Results

In an experiment designed to confirm or refute the performance of the proposed strategy, the researchers launched a simulation to analyze the futures contract on the Hong Kong Stock Exchange (Hang Seng). Analyzed historical data for 2008, only 355 days. The task was to calculate the ROI (return on investment) for trading specific stocks.

The figure below shows the performance of the static and dynamic P&Q strategy:

According to the data obtained, the adaptive strategy shows the best results - during the simulation, the average monthly ROI in this case was 75.63%, and for the static strategy - 67.67%.

In addition, the researchers wanted to know how to minimize losses in case of their occurrence. According to the experiment, the probability of losses when using strategies of following the trend increases with high market volatility. In order to confirm this hypothesis, a simulation of the occurrence of random fluctuations in the market was organized.

According to the results, automated trend following strategies began to operate at a loss when the level of fluctuations reached 45%. This means that it is possible to reduce the likelihood of losses by programming a certain threshold of fluctuations in the system, upon reaching which trade must be stopped.