May cohort is now open: How to secure your spot:

Technical analysis with Python: 3 indicators you can learn in 2.5 minutes

Technical analysis with Python: 3 indicators you can learn in 2.5 minutes

When I first started trading, I sat next to Eddie.

Eddie was on his second career. During his first, he had a few bad trades and blew up his trading account. He took some time off and started again.

Instead of relying on his instincts like the first time, he used technical analysis to get an edge.

I watched as he put levels into his spreadsheet, drew lines on the chart, and religiously bought at sold when the charts told him to.

Eddie always seemed to make money.

“Hey Eddie, what are those levels you always trade?” I asked one day.

He gave me his secret:

“Ah, it’s where all the traders think something’s going to happen.”

Then he walked away.

“Useless I thought.”

Only now do I realize what he was talking about.

Lines on charts are self-fulfilling prophecies and important to understand.

All traders see the same thing and often trade the same way.

This is what Eddie understood that most traders do not.

Today, you will use the popular TA-Lib technical analysis library to plot Bollinger Bands, RSI, and MACD using Python.

Traders use Bollinger Bands to identify potential trading opportunities in the financial markets.

They’re usually used for identifying overbought and oversold conditions.

People also use them for measuring volatility and getting ahead of trend reversals.

Traders use the Relative Strength Index (RSI) to identify overbought or oversold conditions.

RSI oscillates between 0 and 100. Values above 70 show overbought conditions and values below 30 show oversold conditions.

The Moving Average Convergence Divergence (MACD) is a popular technical analysis tool, too. It’s used by traders to identify trend reversals, momentum shifts, and trend strength.

MACD is based on the difference between two exponential moving averages with different periods.

Import and setup

Start by importing Matplotlib for plotting and pandas for data manipulation.

Then import TA-Lib and the OpenBB SDK.

%matplotlib inline

import matplotlib.pyplot as plt
import pandas as pd
from talib import RSI, BBANDS, MACD

from openbb_terminal.sdk import openbb
from openbb_terminal.sdk import TerminalStyle
theme = TerminalStyle("light", "light", "light")

Use OpenBB to grab some stock data.

data = (
    openbb
    .stocks
    .load("AAPL", start_date="2020-01-01")
    .rename(columns={"Adj Close": "close"})
)

Compute the indicator values

TA-Lib has more than 150 indicators and is one of the most popular libraries around. Using it is simple with Python.

# Create Bollinger Bands
up, mid, low = BBANDS(
    data.close, 
    timeperiod=21, 
    nbdevup=2, 
    nbdevdn=2, 
    matype=0
)

# Create RSI
rsi = RSI(data.close, timeperiod=14)

# Create MACD
macd, macdsignal, macdhist = MACD(
    data.close, 
    fastperiod=12, 
    slowperiod=26, 
    signalperiod=9
)

Depending on the indicator, the function takes different values. BBANDS takes the closing price, the lookback window, and the number of standard deviations. RSI just takes the lookback window, and MACD takes the fast, slow, and signal periods.

Plot the indicators

Use pandas to put all the data together and Matplotlib to plot it. First the data.

macd = pd.DataFrame(
    {
        "MACD": macd,
        "MACD Signal": macdsignal,
        "MACD History": macdhist,
    }
)

data = pd.DataFrame(
    {
        "AAPL": data.close,
        "BB Up": up,
        "BB Mid": mid,
        "BB down": low,
        "RSI": rsi,
    }
)

Create two DataFrames: the first for the MACD signals, the second for the remaining indicators.

Then plot them.

fig, axes = plt.subplots(
    nrows=3,
    figsize=(15, 10),
    sharex=True
)

data.drop(["RSI"], axis=1).plot(
    ax=axes[0],
    lw=1,
    title="BBANDS"
)
data["RSI"].plot(
    ax=axes[1],
    lw=1,
    title="RSI"
)
axes[1].axhline(70, lw=1, ls="--", c="k")
axes[1].axhline(30, lw=1, ls="--", c="k")
macd.plot(
    ax=axes[2],
    lw=1,
    title="MACD",
    rot=0
)
axes[2].set_xlabel("")
fig.tight_layout()

You created tree charts, all aligned by date. The top shows the Bollinger Bands, the middle one RSI, and the bottom the MACD.

PQN #035: Technical analysis with Python: 3 indicators you can learn in 2.5 minutes

Since all traders see the same charts, you can use technical analysis to find out what other traders are doing.

Used with time series and other quantitative technicals, technical analysis can be used to filter out the noise from messy data.