How to build Stock Technical Indicators with Python
Stock technical indicators are indispensable in stock analysis. They are calculated by a different mathematical formula based on the historical stock prices. In algorithmic trading, technical indicators are also essential to form a trading signal that can trigger the opening and closing of a trade by a trading robot.
Please feel free to visit my GitHub page (https://github.com/alletale/StockTecnicalIndicator.git) to see the entire code.
DISCLAIMER:
This post is purely educational and does not aim at giving any recommendation whatsoever regarding business nor trading. All information and data used is public and free access. Investing in stock markets involves risk and can lead to monetary loss. The content of this articles is not to be taken as financial advice.
Let's build some technical indicators with a few line of codes. There are two main groups of technical indicators will be presented here:
Acquisition of stock data
stock_data = yf.download("AAPL", start="2020-01-01", end="2021-01-01"
)
Let's plot a line chart to observe the time series stock prices.
plt.plot(stock_data['Close'], color='blue'
plt.title("Daily Close Price (AAPL)")
plt.show(
)
The output is:
Building Trending Indicator
Trend indicators are basically a measurement of the direction of a stock price trend (upwards, downwards or sideways). Let’s started with the most basic one, simple moving average (SMA).
Simple Moving Average (SMA)
A simple moving average (SMA) is a rolling mean of the recent prices over a specific number of time periods (e.g. 10 days, 20 days, 50 days etc). SMA moves with the price and it can smooth out the daily price to show the price direction.
Let's code a command to build SMA indicator for 20 days and 50 days time frames.
stock_data['SMA_20'] = talib.SMA(stock_data['Close'], timeperiod=20
stock_data['SMA_50'] = talib.SMA(stock_data['Close'], timeperiod=50)
)
We obtain:
Please note that the first 20 days of SMA_20 and SMA_50 we don't obtain the SMA due to the setting of the start period at 2020-01-01.
We can observe that the two SMA line plots show a much clearer uptrend pattern of the stock prices compared with the raw closing price line chart. Besides, the line plot of SMA 50 is smoother than the SMA 20.
Exponential Moving Average
Exponential moving average (EMA) is similar to SMA except that EMA gives a higher weight to the more recent prices while SMA assigns equal weight to all values. I set the timeframe to 20 days and 50 day as I did for the SMA. Let's use the code below to see what happens.
stock_data['EMA_20'] = talib.EMA(stock_data['Close'], timeperiod=20
stock_data['EMA_50'] = talib.EMA(stock_data['Close'], timeperiod=50)
)
And the output is:
Recommended by LinkedIn
Now let us try to compare the SMA 50 and EMA 50.
From the chart figure above, we can observe the EMA is more sensitive to the price movement due to the different weighting on the more recent prices.
Average Directional Movement (ADX)
Average directional movement (ADX) is an indicator developed by J. Welles Wilder to measure the strength of a trend rather than just the price movement. The higher the magnitude of the ADX, the stronger the trend. The measurement of the ADX oscillates between 0 and 100 and it can be categorized into three range groups:
ADX ≤ 25: No trend
25 < ADX ≤ 50: Trending
ADX > 50: Strong Trending
Let's us the code below to see what happen to our data.
stock_data['ADX'] = talib.ADX(stock_data['High'], stock_data['Low'], stock_data['Close'], timeperiod=14
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
)
And the graph we obtain is:
From the ADX plot above, we can see an upward trend is formed when the ADX value stands between 25–50. When the ADX falls under 25, the sideways price movement is observed.
Building Momentum Indicators
Momentum indicators are to measure the velocity of the price movement instead of a trend. This type of indicators offers a signal if the price movement is strengthening or weakening.
Moving Average Convergence Divergence (MACD)
Moving average convergence divergence (MACD) shows the relationship between two exponential moving averages (EMA) of a stock price. It is calculated by subtracting the EMA-26 from the EMA-12. This will result in a MACD line. Another EMA-9 of the MACD will also be plotted on top of the MACD line as the signal line to trigger a buy and sell action.
Let's use the code below to see the MACD plotted on the graph.
macd, macdsignal, macdhist = talib.MACD(stock_data['Close'], fastperiod=12, slowperiod=26, signalperiod=9
)
And we obtain:
The MACD plot above shows that the higher the histogram (purple bar) above the baseline, the stronger bullish momentum is formed to push the price movement upwards. On another hand, the lower the histogram below the baseline, the stronger bearish momentum is formed to push the price movement downwards.
Conclusion
This article is only aimed to offer a primer to algorithmic trading by showing the steps to build the technical indicators using a few Python libraries. We can then move on to use these indicators to develop our trading strategy in our trading bot.
Besides, this is important to remind that calculates based on the historical price data don't guarantee you a 100% accurate prediction of the future stock price or movement. However, the correct usage of the indicators can still project a general picture of the current market condition and trigger some potential trading signals. In algorithmic trading, technical indicators are always used to trigger these potential trading signals with a reasonably high winning rate.
Please do NOT use this information to trade. You may feel free to replicate and improve the code above but I already DECLINE all responsibility.
I wish you enjoy reading this article.