Algo
Algo
Abstract
In this report we have tried to implement various trading strategies with the help of machine learning
and deep learning models. This report has tried to develop an algorithmic model based on technical
indicators for the selection of stocks to be traded and machine learning for forecasting of stocks price.
Also a trading strategy is developed which can provide maximum profit or minimize the loss.
This report will first explain various technical indicators in detail. Indicators explained will be Exponential
moving average, Moving average convergence and divergence, Average true range, RSI which will be
used for stocks selection. Then it will explain the LSTM machine learning model which will be used for
forecasting of stocks prices. And based on all these indicators and LSTM models, a new trading strategy is
developed.
There are many types of tradings but this report will focus only on day trading in which stocks are bought
and sold on same day thereby called intraday trading.
Keywords: EMA, RSI, MACD, LSTM, intraday,machine learning
Introduction
For years people wanted to predict the stock market but no one can accurately predict it as there are
many factors that affects it . Generally, prices are governed by the demand and supply principle. When
demand for a particular product is more than the supply of the product then prices will increase and
when demand is less than the supply of the product then prices will decrease. Same condition happens
in case stocks are overbought or oversold. There are various factors that affect stock prices in the stock
market and we can classify these factors into three categories: Fundamental factors, technical factors,
and market sentiments.
Fundamental factors are those factors which affects the stocks prices due to fundamentals of the
company like: the profitability of the company’s, earnings per share, dividend per share, cash flow per
share, debt to equity of a company, working environment of a company. Technical factors are those
factors which arises due to change in market, industry, government or environment as a whole. These
factors includes inflation, economic strength of the markets and peers, demographics of the market,
liquidity present in the market etc. Market sentiment is a bizarre concept that is completely independent
of the financial condition of a company. If a piece of a news started circulating in the market then it is
enough to change the market sentiment of a company.
Today historical prices of every company is readily available and with the use of these historical data one
can make a informed trading decision. In tradional approach market analysist used these historical data
to calculate various technical indicators like SMA, EMA, RSI, MACD Bollinger bands etc on the analysis of
these indicators they decide whether to buy or sell a stock. But these indicators only shows the past
trends of the stock and general direction of the future trends of the stock.
But with the use of machine learning one can predict stock prices. So this report has tried to use a mix
approach where traditional approach like technical indicators is use for selection of the stock and and
modern approach like machine learning is used for prediction of future stock price and algorithm is
developed for execution of trading decisions based on results derived from predefined rules.
There are many ways one can trade in financial market. One can appoint an agent to execute trading
orders on his behalf or one can use services of any stock broking firm and directly invest in the market. It
starts with selection of a company to executing the buy or sell order on trading platform after login on
the brokerage sites.
One of the most important factors while operating in the intraday market is the timing of the execution
of the trade. Intraday markets changed in nanoseconds and any delay in execution of order can result in
huge losses to the investor. Another problem faced while trading is the selection of right stock. There are
thousands of companies operating in the market with different fundamental. To select a stock with
sound fundamental and right technical is huge problem as researching a company requires technical
expertise and which is not found everywhere. And these processes are time consuming and prone to
errors due to human interventions and time constraints.
This paper focuses on these challenges and tries to find a way which can solve all these problem by
minimizing the human contact and using a predefined set of instruction to automate all the process
involves in trading using algorithmic trading.
Algorithmic trading
There is no single definition of algorithmic intraday trading. Different people use algorithmic intraday
trading for different purposes but all use cases and applications have two things in common. First of all,
algo trade follows a clear strategy or plan either it has pre-planned rules/algorithms to execute
instructions or it has learning algorithms like machine learning or artificial intelligence to make decisions
without human interference. Secondly, trades are automated and executed by computers and not by
humans. This enables high-frequency trading and trading that is too complex or too fast for a human
brain to process.
Algorithmic trading is a data-driven process as trading strategies are based on data. There are two types
of data. Fundamental data and price/volume data. Fundamental data can be interest rates, GDP growth,
inflation, unemployment, and company revenues and profits. And prices/volume data are prices of the
securities, return on securities, trading volume, and volatility of the prices/return.
Objectives
The main objective of the report:
• Researching and evaluating various fundamental and technical indicators that can be used in
algo trading. Key indicators reviewed will be SMA, EMA, MACD, RSI
• Researching and evaluating strategies followed in the day trading like SMA cross over, mean
reversion, arbitrage, momentum.
• Developing a new algorithm-based trading program with the help of various intraday strategies
and machine learning models like CNN, LSTM, Q-learning
• Back-testing the strategy to find the technical and theoretical flaws in the strategy and to
optimize and improve the trading strategy before using the real-world data.
1.4 Extension
• Developing program to download live data as well historical data using Yfinance.
• Identifying the success and failures of these trading strategies by critically analysing the methods
and tools involved in the execution of these methods.
• Selecting at least ten stocks based on the algorithm developed and critically analysing all the
algo trading methods.
• Analysing all the challenges faced and threats posed by the algo trading system.
Theoretical fundamentals
Intraday trading
While the literature of intraday trading is diverse, definitions of the term are similar. The term ‘intraday
trading’ is equivalent to the term ‘day trading. The prevailing understanding is that day trading is “the
activity, often on the internet, of buying and selling shares on the same day, reacting to small changes in
prices in order to make a profit.
Technical indicators
There are mainly two types of indicators that are used while researching a stock. These are lagging
indicators and leading indicators. This paper analyses these trading indicators to form trading strategies
to make a robust trading program for intraday trading to get maximum profit with minimum loss.
Moving average
Moving average is used to determine the market sentiment and used to get an idea to determine the
direction in which stock is moving. The basic rule is that if the price of a security is trending above its
moving average, then it’s an uptrend and if it is trading below its moving average then it is downtrends.
It also helps in taking a trading position. If an investor has researched a company and found its
fundamentals are strong and good for investment then moving average can help in determining the right
time of investing in the market. For a good company, it is said that the company's share prices will go up
in long term. So, whenever the price of a security moves down, is a good time for investing. So, if the
trending price of a share is below its moving average, then it is showing a downward trend. And if the
price of a security is moving above its moving average, then it may be expected that a sell-off will be
coming in near future and indicates towards selling the stock and making a profit.
Since moving averages are lagging indicators, they are not designed to identify the exact bottom or top
of stock price, they are only used for getting an idea of direction or trend, which stock price will take.
There are many types of moving averages used in the market like simple moving average, exponential
moving average, weighted moving average.
Simple moving average (SMA) is one of the easiest moving averages which is calculated as the average
of previous N days stock prices. It is used to identify the upward and downward trends in the market.
Exponential moving average
EMA is similar to SMA as both calculate the average of last N day’s prices but EMA gives more weight-
age to the recent prices thereby giving more importance to recent changes and making it more sensitive
to price changes. EMA can be double aged sword as on one hand it can help in identifying the trend
before SMA but on other the hand, it will show more short-term changes as against SMA.
Moving Average Convergence Divergence (MACD)
MACD is also known as MACD oscillator which shows the convergence and divergence of moving
averages. It is classified as an absolute price oscillator as it deals with the actual price of underlying
assets rather than their percentage change. Moving averages used in MACD are fast-moving average
with a smaller number of days like 12 days EMA and slow-moving average which are longer days like 26
days EMA. When two moving averages drift apart then it is called divergence and when they come
towards each other then it is called convergence. This is used to analyze the direction and momentum of
the trend of stock price. MACD can be interpreted in mainly three ways: Moving Average crossover,
MACD Histogram, MACD Divergence.
Moving average crossover is used by turning two trends following indicator into a momentum oscillator
by subtracting the longer moving average (Short EMA) from the shorter moving average (Long EMA)
which is called the MACD line. A 9-day EMA is calculated on this MACD line which works as a signal line.
The difference between the MACD line and the Signal line is called Histogram. MACD line and signal line
fluctuate above and below zero line because of their convergence and divergence.
Now, these three are used to generate trading signals and trends of stock prices. When the MACD line
crosses the signal line below zero then it is expected that stock will take an uptrend and indicate buying
signal. Also, when the MACD line crosses the signal line above zero then it points towards a downtrend
and forms a selling signal. MACD divergence is also used for knowing potential reversal in market trends.
A bullish divergence is created when the MACD line moves lower than the signal line which indicates that
the downtrend is losing momentum and reversal is likely. Similarly, when the MACD line moves above the
signal line then it indicates that the uptrend is losing momentum and reversal is likely and this trend is
called bearish divergence.
MACD histogram is an indicator of indicator which is represented by the difference between MACD line
and Signal line. It is also used for knowing stock trends and reversals in stock prices. When the MACD
histogram starts to decline from its peak then it shows a bearish trend and indicates a selling signal.
Similarly, when the histogram starts to rise from its troughs then it shows a bullish trend and indicates
buying signal. Change in the slop of MACD histogram gives an early signal than the MACD signal line
crossover. And an early signal can make a huge difference in the profit.
Like any forecasting algorithm, MACD also generates a false signal. A false positive is where MACD
indicates bullish crossover but is followed by a decrease in stock prices. And a false negative is a condition
where MACD indicates a bearish crossover but is followed by an increase in stock prices.
Relative Strength Index
RSI is a momentum indicators which is used to evaluate overbought and oversold condition of a stock by
ploting a line graph between 0 to 100. When the RSI is above 70% then stock is considered overbought
and when RSI is below 30% then stock is considered as oversold.
Average True Range
ATR shows asset movement during a given period. It is a volatility indicator, not a trending indicator
means volatility can be high while the market is trending low and vice versa. It can help to determine
when one can initiate an order or when one can place a stop-loss order. An ATR can be calculated for one
minute, one day, or one month on a one-minute chart, one day chart, and on a monthly chart
respectively. ATR can be calculated as the maximum of any of the following absolute true ranges. Then an
average of these true ranges is calculated to find the Average True Range (ATR).
• Current high-previous close
Trading strategy
In this report a trading strategy is developed which is based on technical indicators as well as machine
learnig approach. Trading strategy is developed based on the mix of mean reversion
Due to the volatility of the market and uncertainty in stocks trends, the model has not selected any
particular stocks. The selection of stocks is done algorithmically. For stock selection, code is developed
which will download 100 of the most traded stocks. Next stocks which are trending above their 20 days
EMA and trending below 20 days EMA are selected and then categorized as short and long stocks. Then
by using the LSTM machine learning model their prices are predicted and where stocks categorized as
short and long are also predicted accordingly short or long are selected.
Since the selection of stocks is based on the LSTM model and technical indicators, the process is
completed before the starting of the trading window to avoid any technical delay.
Even after the selection of stocks is done using technical indicators and forecasting of stocks prices is
done using the LSTM model, our predictions can be wrong, so to minimize our losses, our model is
developed where code will run every 5 minutes and check the condition based on MACD, ATR based
trading strategy and decides target price and stop-loss. Target prices and stop-loss prices are also made
dynamic which will change according to the movement of the stock price to maximize profit.
Trading Strategy
To make maximum profit in the intraday trading, it is very essential to know not only which stock to buy
but also when to buy the stock. In trading, not only selection of the right stock is important but also
making the right trading decision at the right time is also very important. For this trading strategy is
divided into three parts-
• Selection of stocks
• Forecasting of stocks
• Trade execution
Selection of stocks
In the case of day trading when stock prices are affected by sentiments and any small change in public
view can move the stock prices in opposite direction, so it is very important to make the correct
selection of the stocks. This model is developed for the selection of stocks based on EMA and RSI.
Exponential Moving Average stipulates that all price movement is cyclic in nature and whenever prices
move away from the average they tend to come back to their average. So if a price is moving above its
average then it is expected that it will come back to its average and if a price is trending below its
average then it is expected that it will move up to its average.
The relative Strength Index is a momentum indicator that evaluates overbought or oversold conditions
by measuring the magnitude of recent price changes of various assets. The RSI is displayed as a line
graph that moves between two extremes which is called an oscillator. Its reading can range from zero to
100.*
https://www.investopedia.com/articles/active-trading/042114/overbought-or-oversold-use-relative-
strength-index-find-out.asp
RSI below 30% is considered an oversold position of stock which indicates that a fresh purchase of stocks
will take place so this condition may be used for generating a stock buying signal.
Similarly, RSI above 70% is considered an overbought situation which indicates that stock is excessively
bought and selling of stocks is expected in near future and this situation can be used for generating a
selling signal.
Selecting stocks below 30% RSI does not necessarily indicate reversion in trends and if a stock is
undergoing a really bad phase then it may downgrade more so all those stocks which are trending below
30% RSI are dropped from the list and all those stocks which are trending between 30% and 45% are
selected as these stocks at least shows that there is positive interest present in the market and investors
are at least buying the stock and by investing in them we can earn some profit. Similarly, stocks that are
moving above 75% RSI can be selected for the stock selling category.
For the selection of stocks, this report has used a list of most traded stocks from the London stocks
exchange and the top 100 stocks are selected. As per the mean reversion strategy, all the stocks which
are trending below their 20-day EMA and standard deviation combined and having RSI between 30 and
45 are selected. These stocks are grouped into the stock category to buy.
In this report we are only considering stocks which are showing buying signal and category for stocks to
sell is ignored.
Forecasting of stock prices
For a long time, investors desired that they can predict stock prices so that they make huge profit or at
least limit their losses but the accurate prediction of stocks is extremely difficult because of multiple
micro and macro factors. Our model has used Long Short Term Memory(LSTM) of Deep learning for
predicting future stock prices where it predicts prices of all the stocks which are selected in the first
steps and all those stocks which show results in accordance with the results of the first steps are selected
for trading.
Trade execution
The last step in this report is trade execution, In which the interactive broker platform is used for
executing the trade. Due to system limitation, continuous forecasting of multiple stocks using LSTM is not
possible as it will provide price predictions with delay so LSTM model is only used for knowing the stocks
trend and for trading MACD crossover strategy with stochastic indicator is used.
Algorithm is executed as soon as market open. Since market is volatile and can move in any direction
stoploss is placed simultaneously. Stoploss is placed at closing price minus 60 period ATR.
A buying signal is generated whenever MACD line is above the signal line and stochastic is greater than
30 and its value is keep on increasing.
Also algorithm is set for auto squaring off all the trade to half an hour before the closing of trading
window so add to avoid last minute rush or any technical clitch.
Methodology and experiments
We run our code for 5 days between 11th April 2022 to 14th April 2022 and 10 stocks are selected from
the 100 most traded stocks on 8th April 2022 with the help on ‘selection of stocks’ step.
Selection of stocks is done after the closing of trading windows and Yahoo finance is used for
downloading the historical data. With the help of historical data, EMA and RSI is calculated for each stock
and all those stocks where closing price is less than EMA and standard deviation combined and RSI is
between 30 and 45 are selected. These stocks are grouped in stocks to buy category.
Now second step is predictions of stock price using LSTM. This step is also done before the market
open’s. Keras module is used for time series forecasting. For this data is divided into training set and test
set. Dataset with Open and Close column is used for LSTM modelling. To normalize the dataset,
MinMaxScaler from scikit-learn is used to scaled the dataset into numbers between 0 and 1. Then
dataset is divided into 60 timesteps and converted into 3-D array using Numpy. Then LSTM layers along
with dropout layers are added to training dateset to prevent overfittng. Then Dense layer is added to
specifies the unit output and model is complied using the adam optimizer and loss is set as mean
squared error. After compliling of LSTM model on training dataset, then test dataset is used for
predicting stock prices.
Since we are not able to use LSTM on live data we have only used LSTM for recognition of stocks trends.
On all those stocks where trend predict upward movement, are selected for for live trading. During live
trading MACD crossover with stochastic oscillator is used.
for live trading ten stocks were selected after performing LSTM model. Buying decision is made at the
start of the trading session and simultaneously stop loss and target price is also decided. Stop loss is set
at closing price minus ATR and target price is set at closing price plus ATR. $10000 is invested on each
stock and trading for stock is done only once in a trading day. i.e if any trade is completed within half an
hour then new trade for same stock or other stock is not made. Also stoploss and target price for the
stock is made dynamic i.e in case any stock achieve target price then target price and stop loss is
changed with addition or substraction of ATR. In this way we were able to achieve maximum profit with
minimu results.
Concusion
After performing algorithmic trading for ten stocks for 5 days, we were able to achieve a 3% return from
the investment, which can be considered as good results considering the dynamic nature of stock
market. We were able to achieve better results if were able to implement sentiment analysis in the code
but it is difficult to get quality sentiments data on daily basis.
6 Requirement analysis
6.1 Technical requirement for the project
Algorithmic trading uses complex formulas with mathematical models and human oversight to make
trading decisions like buying, selling, or holding a financial asset. Formulation and implementation of a
profitable strategy is the main objective of algorithmic trading. Following are the requirement for
algorithmic day trading.
• Knowledge of programming language to develop a successful strategy (Python and ML in case of
this report), or hiring of a professional who can help in developing the required strategy, or
premade algo trading software.
• Internet connectivity and access to the trading platforms to make trading orders like buying or
selling of financial assets (in this e-Toro platform is used for testing and deploying of strategies).
• Access to market data like historical prices and live tick of various tickers so that algorithm can
use it for executing various trading strategies ( Yfinance API is used for getting historical data and
tick data).
• Infrastructure to back-test a trading strategy before it can be used in real-world markets.
6.2 Subjective requirement for the project
Algorithmic trading requires computer-based programs to execute trades and knowledge of the
programming language, Python in this case, is required for developing a successful strategy. Following
are the requirement
• Understanding of the financial statements like profit and loss account, balance sheet, cash flow
statement, fund flow statement, etc.
• Understanding of various financial ratios like debt-to-equity ratio, earning per share, current
ratio, quick ratio, etc.
• Understanding of statistical concepts like simple moving average, exponential moving average,
standard deviation, correlation, regression, etc.
• Understanding of trading strategies like SMA crossover, mean reversion, arbitrage, super-trends,
etc.
6.3 Non-functional requirement
6.3(a) Usability
• Algo-trading should be user-friendly. After deployment of strategy, user can the make necessary
changes in variables to optimize the strategy.
• Algo developed should run without human intervention on its own and make a suitable trading
decision.
6.3(b) Supportability
• Algorithms should be able to support new financial derivatives without major changes or
updates.
• Algorithms should support major update in trading platform or update in programming used
without any crashes or bugs in the code.
6.3(c) Reliability
• Algorithms should support a minimum of 15-minute downtime to support updates in the system.
6.3(d) Security
• Since programs contain all financial information about an individual and leak of this important
information can wreak havoc in the life of an investor so, adequate security methods should be
used.
6.3(e) Documentation and help
• Should be provided so that it can be helpful to new users.
• Should be provided so that novice users can use it to gain proficiency with the program.
• Should be provided to existing users to solve any interface-level problem.
6.3(f) Limitations
• Need to know a programming language or need to hire a programming expert
• All strategies cannot be automated
• There is no human control
• More time spends on the computer
Bibliography and references
• Jan Fraenkle and Svetlozar T. Rachev (2009). Review: algorithmic trading. Investment
Management and Financial Innovations
• Admiral Markets (Ed.) (2020): Intraday Handel - Available online at
https://admiralmarkets.de/wissen/articles/forex-strategy/intraday-trading,
• BaFin - Bundesanstalt für Finanzdienstleistungsaufsicht (Ed.) (2019): Frequently asked questions
(FAQs) relating to algorithmic trading and high-frequency trading (Update: 17 July 2019).
Available online at https://www.bafin.de/SharedDocs/Downloads/DE/FAQ/dl_faq_hft.html,
• Bigiotti A., Navarra A. (2019): Optimizing Automated Trading Systems. In: Antipova T., Rocha A.
(eds) Digital Science. Advances in Intelligent Systems and Computing, Vol 850, pp. 254-261, 2018.
• Charles, D. (2018): A Practical Introduction to Day Trading. Available online at
https://www.cambridgescholars.com/download/sample/64855, \
• Admiral Markets (Ed.) (2020): Intraday Handel - So funktioniert der kurzfristige Handel mit DAX,
Gold und Co. Updated on 03/08/2020. Available online at
https://admiralmarkets.de/wissen/articles/forex-strategy/intraday-trading, checked on
15/11/2020.
• Asness, C.; Frazzini, A.; Israel, R.; Moskowitz, T. (2014): Fact, Fiction and Momentum Investing. In
The Journal of Portfolio Management Special 40th Anniversary, 2014, Issue 40 (5), pp. 75-92.
• Auquan (Ed.) (2017): Mean Reversion: Simple Trading Strategies Part 1. Updated on 30/08/2017.
Available online at https://medium.com/auquan/mean-reversionsimple-trading-strategies-part-
1-a18a87c1196a, checked on 15/11/2020.
• Algorithm-Based Intraday Trading Strategies and their Market Impact by Müller, Luisa ,2017