Beginner Guide to Technical Analysis in Python

Tom Clarke
CodeX
Published in
6 min readSep 1, 2021

We all love making money, there’s no hiding from it. If you’re new to trading, then before you jump in it is important to have at least a basic understanding of some of the technical indicators. It’s too easy to get lost in the charts if you’re a newbie, and inevitably lose money, which no one wants! If you also like coding in python, then it’s a great way to familiarise yourself with the indicators and do some data analysis of your own.

So in this post I will go over some of the basics for storing and displaying data from forex or cryptocurrency markets, as well as a brilliant library full of technical indicators to try out.

We will need a few packages for this project:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mplfinance as mpf
from datatime import datetime as dt
import talib as ta

TA-Lib is a fantastic library for technical analysis, and this is what we will use to generate a lot of our analytical data. This will all be stored using pandas dataframes, and the data will be displayed using mplfinance.

So to start with you will want to download some historical data for a particular stock, curreny, or any other kind of asset. In this tutorial I will be using bitcoin for the example. Yahoo finance is a very easy way to get price data, where you can download a csv for free, or if you are more interested in cryptocurrency, you may have a Binance account. With Binance you are able to setup an API and you can install the python-binance library.

from binance.client import Client

For Binance users you will want to do as follows:

api_key = 'YOUR API KEY' #found on binance site when setting up api
api_secret = 'YOUR API SECRET'
client = Client(api_key,api_secret)
symbol = 'BTCUSDT'
kline = '1d'
data_since = '100 days ago'
df = pd.DataFrame(
client.get_historical_klines(symbol,kline,data_since)).drop(columns={6,7,8,9,10,11}).astype('float')

This leaves you with a data frame with: Date, Open, High, Low, Close, Volume columns filled with float data.

If you download a csv from another site, all you will need to do is write:

df = pd.read_csv('PATH TO YOUR CSV FILE')

If you do get your data elsewhere make sure it as at least the same data as if you get it from Binance.

So from here for simplicity we will rename the columns to make it clear which is which:

df.columns = ['Date',Open','High','Low','Close','Volume']

For mpl finance to be able to handle this data, we need to set the date column as a datetime index. It also usually comes in the for of a timestamp rather than date, so we will convert that as well

df.index = pd.DatetimeIndex(
[dt.fromtimestamp(x/1000) for x in df['Date']
)

If your data already comes in datetime format, then simple pass ‘df[‘Date’]’ into the method instead.

So now our data is ready to be displayed. We can do this in two lines of code:

mpf.plot(df,type='candle')
plt.show()

Easy as that! Although it would be easier to use if it looked more like the charts we are used to online, so we will add some simple styling to it.

colors = mpf.marketcolors(up='lime',down='r',
wick={'up':'lime','down':'r'},
edge={'up':'lime','down':'r'},
volume={'up':'lime','down':'r'})
s = mpf.make_mpf_style(marketcolors=colors,facecolor='black,
edgecolor='w',gridstyle='solid',
gridcolor='grey')
kwargs = dict(type='candle',style=s,figratio=(20,10),
width_adjuster_version='v0')
mpf.plot(df,**kwargs)
plt.show()

Now we have something that looks a lot more like what we know and love! There is one more thing we can add quickly and that’s the volume bar chart at the bottom. To do that all we need to do is add ‘volume=True’ to our kwargs dictionary, so it becomes:

kwargs = dict(type='candle',style=s,figratio=(20,10),
width_adjuster_version='v0', volume=True)

Now we can easily display candlestick data with the volume in it. Next we get to move onto the technical analysis indicators. There are so many available options, so I will cover some of the more popular ones:

  • Moving Average (MA)
  • Exponential Moving Average (EMA)
  • Relative Strength Index (RSI)
  • Stochastic RSI
  • Moving Average Convergence Divergence (MACD)
  • Bollinger Bands
  • Average True Range (ATR)

Since we already have a data frame holding all our price data, it makes sense to add some new columns to store the values from our indicators. The first two indicators: MA and EMA are easiest to do using pandas built in methods. For each I will do a 12 day MA and EMA, but this is up to you, and you will probably want to add a few of each.

df['12MA'] = df['Close'].rolling(12).mean()
df['12EMA'] = df['Close'].ewm(com=12,adjust=False).mean()

So that’s how pandas can create some of the moving averages we will need. Note: now that we have added extra columns to our data frame, we need to change our plot code slightly to this:

mpf.plot(df[['Date','Open','High','Low','Close','Volume]],**kwargs)

Moving onto the other indicators, you will see just how easy TA-Lib makes these calculations. Starting with the RSI:

df['RSI'] = ta.RSI(df['Close'],timeperiod=14)

That’s how easy it is! TA-Lib is so helpful and simple. Some of the other indicators have multiple outputs, so will span more than one column. Another thing you will note is that after performing these operations, some of the starting rows will read NaN. This is perfectly normal and is just a consequence of the mathematics, so this is another reason so collect a lot of data. The rest of the indicators can be implemented like this:

df['fastk'],df['fastd'] = ta.STOCHRSI(df['Close'],timeperiod=14,
fastk_period=5,fastd_period=3)
df['macd'],df['macdsignal'],df['macdhist'] = ta.MACD(df['Close'],fastperiod=12,slowperiod=26,signalperiod=9)df['upperBB'],df['midBB'],df['lowerBB'] = ta.BBANDS(df['Close'],timeperiod=5)df['ATR'] = ta.ATR(df['High'],df['Low'],df['Close'],timeperiod=14)

For all the possible indicators I recommend checking over the documentation here: https://mrjbq7.github.io/ta-lib/func_groups/volatility_indicators.html

For plotting these new indicators we have, you need to know which ones belong on the candlestick plot, and which ones require a subplot. The only data you may want to plot on top of the candlestick data is any type of moving average, and the Bollinger Bands. The rest will be better off in a subplot because the scale is very different.

So adding this is very easy, above our ‘kwargs’ dictionary, we want to add a list called apdict, and can add in our new indicators:

apdict = [mpf.make_addplot(df[['upperBB','lowerBB']],color='b',
type='scatter',panel=0),
mpf.make_addplot(df['RSI'],color='cyan',
type='scatter',panel=2)]

This will add our Bollinger Bands to the candlestick chart, while creating a third panel at the bottom for our RSI. The panel argument is how we determine where to plot the data, and you can add as many as you like

Then in the ‘kwargs’ dictionary we add another variable ‘addplot=apdict’, and that’s all it takes. You should end up with something like this:

It’s entirely up to you how you choose to style it. This is a great way to get to grips with how to analyse stock market or cryptocurrency data. It is also a great way to gather extra data for machine learning if you wanted to try and create a price prediction model!

To take this further, definitely have a look at the documentation for TA-Lib I linked earlier, and also the documentation for ‘mplfinance’ so you can see how to style and improve the plots.

If you’re looking for some ideas to put this into use here’s a few to get you thinking:

  • Machine Learning price prediction
  • Stream live stock price data to your charts
  • Create a tkinter app with you data
  • Create a flask webapp with you indicators on
  • Make a trading strategy tester
  • Make a trading bot

I hope you found this introduction helpful, and you get a better understanding price trends. Have fun with these libraries and create some cool stuff!

I must add that this is in no way any financial advice, and is purely to help demonstrate how you can do your own technical analysis with python.

--

--

Tom Clarke
CodeX
Writer for

I enjoy coming up with fun and interesting python concepts, as well as useful projects. You can also view my articles on Blogger: https://azcoding.blogspot.com/