Introduction to Technical Analysis in Python using TA-Lib
Tags: trading, python
Published: 2022-10-03 16:55:06

---
title: Introduction to Technical Analysis in Python using TA-Lib
published: true
date: 2022-02-16 09:06:12 UTC
tags: trading,python
canonical_url: https://itnext.io/introduction-to-technical-analysis-in-python-using-ta-lib-ac1562849b1e
---

![](https://cdn-images-1.medium.com/max/1024/0*uArkQ1qBx9qbPZtp.jpg)

In this tutorial, I am going to discuss TA-Lib, a technical analysis library for Python apps. Before I move on and discuss how you can do technical analysis in Python, allow me to discuss what technical analysis is and how it helps to make a decision whether you buy an asset, sell or hold it.

### What is Technical Analysis

From [Investopedia](https://www.investopedia.com/terms/t/technicalanalysis.asp):

> Technical analysis is a trading discipline employed to evaluate investments and identify trading opportunities by analyzing statistical trends gathered from trading activity, such as price movement and volume.

In short, it is the study of past and current data and trying to figure out what’s going to be next. You use indicators and try to find out different patterns that help to make decisions.

On the other hand, _Fundamental Analysis_ is all about making decisions based on a company’s financials like yearly/quarterly profits, PE Ratios, etc.

### Development Setup

Installing the TA-Lib python wrapper is pretty easy. All are required to execute the pip command:

pip install TA-Lib

You must install the TA-Lib library itself so that you can use it in your applications. On macOS you may install via Homebrew:

brew install ta-lib

If you are using Linux or Windows then you may get the details [here](https://ta-lib.org/hdr_dw.html).

I am also installing the Yahoo Finance library to fetch our required data:

pip install yfinance

Alright! so everything is set up. Now before we start using this library, we must know some basics of technical analysis and how TA-Lib can help us to achieve our goals.

I am going to use Yahoo Finance to fetch data and **_Jupyter Notebook_** for this tutorial as they make it easy to write interactive code. Use jupyter notebook command to start the IDE and create a new file **Analysis Intro.ipynb**.

The very first thing I am going to do is to import all required libraries:

```
# All Imports
import yfinance as yf
import talib as ta
import pandas as pd
```

We are going to analyze Facebook shares which are already [25% decline](https://www.theguardian.com/technology/2022/feb/03/why-facebook-shares-are-in-freefall-meta-zuckerberg), as the article said as millions of users quit FB in recent days.

The very first thing which we are going to check is the _Simple Moving Average(SMA)_ of this scrip.

#### What is Moving Average

If you notice the chart of a stock price, you will find it fluctuating a lot. This fluctuation could lead to generating false signals. Moving averages(MA) help to filter out the noise from the random price movements and smooth it out in order to see the average value. MAs are used to identify trends and reversals. When the price is above the MA, we say it’s an _uptrend_ otherwise a _downtrend_. They are also used to identify areas of _support_ and _resistance_. MAs are based on past price and is also termed as a _lagging indicator_. When the price cross over MA, it is a signal to buy, and when it crosses down under the MA, it is a signal to sell. There are two types of MAs: Simple and Exponential

- **Simple Moving Average:-** A simple moving average (SMA) is a calculation that takes the arithmetic mean of a given set of (_closing_)prices over the specific number of days in the past; for example, over the previous 15, 30, 100, or 200 days (_Source: Investopedia_).
- **Exponential Moving Average:-** Exponential moving average (EMA) is a weighted average that gives greater importance to the price of a stock in more recent days, making it an indicator that is more responsive to new information(_Source: Investopedia_).

If you plot both SMA and EMA on a chart, you will find that the EMA line is pretty close to the actual chart than an SMA because it’s reacting faster than an SMA. This is the reason that SMA is considered a lagging indicator. MAs are available for different time periods: 10,20,500,100,200. 10–20 for short-term trends, 50 for mid-term, and 200 for long-term trends.

Enough discussion of MA background, let’s write some code!

First, I will be fetching FB stock price data from the beginning of the year to date.

```
# Facebook Historial Data
fb = yf.Ticker("FB")
df = fb.history(start="2022-01-03")
df
```

The data is now available in a pandas dataframe, let’s plot a graph showing data about the closing price and the SMA of the closing price

```
plt.style.use('fivethirtyeight')
df['MA'] = ta.SMA(df['Close'],timeperiod=5)
df[['Close','MA']].plot(figsize=(8,8))
plt.show()
```

When I execute the code in the notebook, it generates the following:

![](https://cdn-images-1.medium.com/max/1024/0*UJhkXsHJLVEiCjeW.png)

As you can see, unlike the closing chart, the SMA chart is smoother.  
 Let’s add an EMA chart to it.

```
plt.style.use('fivethirtyeight')
df['MA'] = ta.SMA(df['Close'],timeperiod=5)
df['EMA'] = ta.EMA(df['Close'], timeperiod = 5)
df[['Close','MA','EMA']].plot(figsize=(8,8))
plt.show()
```

And when I run this code, the chart looks like the below:

![](https://cdn-images-1.medium.com/max/1024/0*Mg4g70_ShM32GKqc.png)

As you can notice, the MA chart is responding slower than the EMA chart, it determines the downtrend slower than the EMA chart.

#### What is Relative Strength Index(RSI)

RSI is a momentum indicator that helps to learn whether a certain share is overbought or oversold. Its value lies between 0–100. If it is under _30_, it means it is oversold and has a chance to buy it. If the value lies above _70_, it means it is overbought and it is a good chance to dump your stock. Let’s calculate and chart the RSI of the FB/Meta stock. Let’s check the RSI of FB.

```
# RSI
df['RSI'] = ta.RSI(df['Close'],14)
df['RSI'].plot(figsize=(8,8),marker='o')
df.tail(10)
```

And it produces. 14 is the default period where it is calculated.

![](https://cdn-images-1.medium.com/max/1024/0*iwia4b9uTFWNvWAQ.png)

As you can see, there was a big rally between 1 and 2 Feb and then it was dumped badly between 3 to 9 Feb and it seems it is trying to recover again.

### Conclusion

In this tutorial, we learned how you can use TA-Lib and charts to figure out your next trading strategy. It is not possible to cover everything related to TA-Lib in this post but I hope it gives you an idea of what to do next. You may create a bot that checks RSI values and give signals periodically. Like always, the code is available on [Github](https://github.com/kadnan/IntroTechnicalAnalysis).

_Originally published at_ [_http://blog.adnansiddiqi.me_](http://blog.adnansiddiqi.me/introduction-to-technical-analysis-in-python-using-ta-lib/) _on February 16, 2022._

* * *