Joshs Finance

Getting Started with Technical Indicators in Python | by Ibrahim Saidi | Aug, 2022 – DataDrivenInvestor

💹Learn to calculate, plot and understand the implications of indicators in Python💵

Image from freepik.com

Technical indicators are a useful tool for constructing trading signals and building strategies. Technical analysis can be performed on any security with historical data (think stocks, futures, commodities, or currencies).

A technical indicator is a calculation based on historical market data, such as price, volumes, etc. Technical indicators are used by traders and investors to gain insight into past price patterns and even to predict future price movements.

In this article, you’ll get familiar with two trend indicators and one momentum indicator:

  • Trend indicator: Simple Moving Average (SMA)[1]
  • Trend indicator: Exponential Moving Average (EMA)[2]
  • Momentum indicator: The Relative Strength Indicator (RSI)[3]

📝 How this article is structured

This article follows the pattern of understanding → implement → visualise. I also share the formulas for these indicators. Don’t stress too much if these don’t make sense. What’s important is understanding what each indicator tries to achieve and how it is implemented in Python.

I believe the code shared in this article is self-explanatory(through comments), therefore I don’t explain in detail what each code section is doing. At the end of the article, I share links to relevant sources that complement the topics covered.

*** IMPORTANT LEGAL DISCLAIMER ***
This article is intended for educational purposes only, and has been prepared without taking into account your particular circumstunces and needs. Before acting on any advice in this article you should seek professional fiancial advice.

🧰 Tools for the task 🔨

  • We’ll get our financial data from yahoo finance using the yfinance package[4]
  • We’ll use the TA-Lib package[5] to implement technical indicators in Python. TA-Lib, which stands for Technical Analysis Library, includes over 150 indicators and is very popular among technical traders.
  • Finally, we’ll create interactive plots using the plotly package[6]. Plotly is great for generating interactive plots.

Trend Indicators SMA

Trend indicators are one of the most common technical indicators. Simple Moving Averages (SMA) and Exponential Moving Average (EMA) are the most common trend indicators.

Let’s look at SMAs first. A Simple Moving Average or SMA is simply the mean of the previous n prices(see equation below). Since every value is derived from data points of the most recent n periods, they move along with the price (hence the name moving average).

The formula for SMA. Source: Investopedia

Averaging out the prices creates a smoothing effect, which clarifies the price’s direction — upward, downward, or sideways. Moving averages based on a longer lookback period have a better smoothing effect compared to those with shorter ones.

Okay, time to get our hands dirty! Let’s implement SMAs in Python. To set the scene, we import all the required packages for our analyses down the track.

As mentioned at the beginning of the article, we’ll get all our data using the yfinance package, so that’s what we do next. Throughout this article, we’ll work with Apple’s historical prices from January 2020 to June 2022.

Importing packages and data
Top 5 rows of Apple data

With our data successfully imported, we are ready to implement a simple moving average for this stock. Now let’s use TA-Lib to implement this in Python. We simply call talib.SMA() and pass a DataFrame column containing the daily historical price data. We also need to specify the averaging period with the timeperiod parameter.

Implementing and plotting SMAs

In the plot above, the green line is the SMA calculated with a shorter lookback period and traces the price movement closely. The red line is the SMA calculated with a longer lookback and is smoother and less responsive to price fluctuations.

Trend Indicator EMA

Another popular type of moving average is the Exponential Moving Average (EMA). An EMA is an exponentially weighted average of the last n prices, where the weight decreases exponentially with each previous price.

The formula for EMA. Source: Investopedia

Implementing an EMA with TA-Libfollows a similar pattern to that of an SMA.

Implementing and plotting EMAs

As with SMAs, we see when plotting EMAs and the price data, that the shorter EMA in green is more reactive to the price movement compared to the longer EMA in red.

SMA vs EMA

As discussed above, SMAs and EMAs are both commonly-used trend indicators. While SMAs assign equal weight to all data points, EMAs apply more weight to recent data points.

Let’s calculate both the SMA and EMA indicators with the same lookback period, and plot them together.

SMAs vs EMAs

From the plot above, notice how the Exponentially weighted moving average(green line) responds to price changes faster than the simple moving average (orange line).

Momentum Indicator RSI

The Relative Strength Indicator (RSI) is a very popular momentum indicator. It was developed by J.Welles Wilder and has been the most popular indicator used to measure momentum, which is the speed of rising or falling in prices.

The relative strength index (RSI) is a momentum indicator used in technical analysis. RSI measures the speed and magnitude of a security’s recent price changes to evaluate overvalued or undervalued conditions in the price of that security. — Investopedia

The RSI calculation follows a straightforward formula. RS, or Relative Strength, is the average of the upward price changes over a chosen n period, divided by the average of downwards price changes over those n periods.

The formula for RSI. Source: Investopedia

The RSI formula is constructed so that an RSI oscillates between 0 and 100. The RSI indicator is usually plotted below an asset’s price chart. In the code below, we create two subplots, the top plot shows the price, and the bottom plot shows the RSI(with horizontal lines at 30 and 70).

Implementing and plotting RSI

Notice the horizontal lines on the RSI plot. These indicate the 70 and 30 RSI points on the chart. Traditionally, an RSI over 70 indicates the security is overbought and overvalued, which means the price may reverse. Likewise, an RSI below 30 means the asset is oversold and undervalued and the price may rally from hereon.

Therefore, an RSI informs technical traders whether the price’s momentum is bearish or bullish. Using this information, one might consider an RSI above 70 as a sell signal because the security is becoming overbought. Likewise, traders may consider an RSI of 30 or less as a buy signal because the security is becoming oversold.

Leave a Comment

Your email address will not be published. Required fields are marked *