Technical indicators, tools for predicting trading market trends (drl4t-02)
The most basic method to predict trends in the trading market is to analyze historical trading data. Technical indicators are mathematical calculations built on historical trading data and are more effective for traders to use to identify potential buying and selling opportunities in the trading market.
Categories of Technical Indicators
Technical indicators can be broadly classified into four categories:
Trend Indicators
These indicators are used to identify the direction of a trend and whether it is bullish (upward) or bearish (downward). Simple Moving Average (SMA) is a popular example of trend indicators.
Momentum Indicators
These indicators measure the speed or rate of price movements. They are used to identify overbought and oversold conditions as well as potential trend reversals. Moving Average Convergence Divergence (MACD) is an example of momentum indicators.
Volatility Indicators
These indicators measure the volatility of the market or the degree of price fluctuations. Bollinger Bands (BB) is an example of volatility indicators.
Volume Indicators
These indicators measure the amount of trading activity in the market. They are used to confirm price action and identify potential trend reversals. Chaikin Money Flow (CMF) is an example of volume indicators.
These categories are not mutually exclusive, and many indicators can fall into more than one category. For example, MACD is both a momentum indicator and a trend indicator.
No single indicator can guarantee a successful trade, but a combination of several different types of technical indicators is still valid.
Calculate technical indicators with Python
We will use a combination of the four technical indicators mentioned above (SMA, MACD, BB and CMF) to build the dataset for machine learning.
First thing first, as described in Acquiring data, the first step towards using machine learning for stock trading (drl4t-01), let’s download some historical trading data of Apple as example:
import yfinance as yf
stock = yf.Ticker('AAPL')
hist = stock.history(period='2y', interval='1d', actions=False)
Simple Moving Average (SMA)
The Simple Moving Average (SMA) is calculated by taking the average closing price of a stock over a specified period of time.
The SMA is a lagging indicator, meaning that it is based on past prices and does not predict future prices. It is used to smooth out price fluctuations and to identify trends. When the price of an asset is above its SMA, it is generally considered to be in an uptrend, and when the price is below its SMA, it is generally considered to be in a downtrend.
Using the trading data we obtained using yfinance earlier, the 10-day and 20-day SMAs can be easily calculated as:
hist['SMA10'] = hist['Close'].rolling(window=10).mean()
hist['SMA20'] = hist['Close'].rolling(window=20).mean()
Moving Average Convergence Divergence (MACD)
The Moving Average Convergence Divergence (MACD) shows the relationship between two exponential moving averages (EMA) of a stock’s price. The MACD is calculated by subtracting the 26-day EMA from the 12-day EMA.
In addition to the MACD line (the difference between the two EMAs), the MACD indicator also includes a signal line and a histogram. The signal line is a 9-day EMA of the MACD line, and the histogram represents the difference between the MACD line and the signal line.
The MACD is used to identify changes in momentum and trend direction. When the MACD line crosses above the signal line, the histogram is positive, it is considered a bullish signal, indicating that the momentum is shifting to the upside. Conversely, when the MACD line crosses below the signal line, the histogram is negative, it is considered a bearish signal, indicating that the momentum is shifting to the downside.
Calculating MACD with Python is still straightforward as follows:
ema_short = hist['Close'].ewm(span=12, adjust=False).mean()
ema_long = hist['Close'].ewm(span=26, adjust=False).mean()
hist['MACD_DIF'] = ema_short - ema_long
hist['MACD_SIGNAL'] = hist['MACD_DIF'].ewm(span=9, adjust=False).mean()
hist['MACD'] = hist['MACD_DIF'] - hist['MACD_SIGNAL']
Bollinger Bands (BB)
Bollinger Bands are based on a moving average of a stock’s price, and are designed to show the volatility and potential trading range of the stock.
Bollinger Bands include a middle line which is a 20-day simple moving average that represents the trend of the stock’s price, while the upper and lower bands are calculated as double standard deviations away from the middle line.
When the price of the asset moves outside of the bands, it is considered to be overbought or oversold.
Bollinger Bands can be calculated with Python like this:
sma = hist['Close'].rolling(window=20).mean()
std = hist['Close'].rolling(window=20).std()
hist['UB'] = sma + 2 * std
hist['LB'] = sma - 2 * std
Chaikin Money Flow (CMF)
Chaikin Money Flow (CMF) measures the volume-weighted average of accumulation and distribution over a specific period of time. CMF is used to identify buying and selling pressure of a stock.
CMF is calculated by multiplying the volume of each trading period by the difference between the closing price and the midpoint of the trading range (the average of the high and low prices). This value is then accumulated over 21 days, and divided by the total volume for the period to give the CMF value.
A high CMF indicates that the stock is being accumulated, while a low CMF suggests that it is being distributed.
CMF can be calculated with Python as follows:
mfm = ((hist['Close'] - hist['Low']) - (hist['High'] - hist['Close'])) / (hist['High'] - hist['Low'])
mfv = mfm * hist['Volume']
hist['CMF'] = mfv.rolling(21).sum() / hist['Volume'].rolling(21).sum()
In the end, let’s check what the dataset looks like now:
hist[['SMA10', 'SMA20', 'MACD_DIF', 'MACD_SIGNAL', 'MACD', 'UB', 'LB', 'CMF']]