Best Stock Technical Indicators and How To Calculate Them In Python

Coder Singh
3 min readDec 28, 2022

--

Technical analysis is a method of evaluating securities by analyzing statistics generated by market activity, such as past prices and volume. Technical analysts use various indicators to help forecast future price movements, and one of the most popular types of indicators are stock technical indicators.

In this blog, we’ll take a look at some of the best stock technical indicators and how to calculate them in Python.

1. Moving Average (MA)

The moving average is a trend-following indicator that smooths out price data by calculating the average over a specified period of time. There are several types of moving averages, including simple, exponential, and weighted.

To calculate a simple moving average in Python, you can use the following code:

import numpy as np

# define a function to calculate the simple moving average
def simple_moving_average(data, window):
weights = np.ones(window) / window
return np.convolve(data, weights, mode='valid')

# calculate the simple moving average with a window of 10
ma = simple_moving_average(data, 10)

2. Bollinger Bands (BB)

Bollinger Bands are a type of volatility indicator that consists of a moving average and two bands that are placed above and below it. The bands widen or narrow based on the volatility of the underlying asset.

To calculate Bollinger Bands in Python, you can use the following code:

import numpy as np

# define a function to calculate Bollinger Bands
def bollinger_bands(data, window, num_std):
ma = simple_moving_average(data, window)
std = np.std(data, axis=0)
upper_band = ma + num_std * std
lower_band = ma - num_std * std
return ma, upper_band, lower_band

# calculate Bollinger Bands with a window of 20 and 2 standard deviations
ma, upper_band, lower_band = bollinger_bands(data, 20, 2)

3. Relative Strength Index (RSI)

The relative strength index is a momentum indicator that measures the strength of a trend by comparing the magnitude of recent gains to recent losses.

To calculate the relative strength index in Python, you can use the following code:

import pandas

def rsi(df, periods = 14, ema = True):
"""
Returns a pd.Series with the relative strength index.
"""
close_delta = df['close'].diff()

# Make two series: one for lower closes and one for higher closes
up = close_delta.clip(lower=0)
down = -1 * close_delta.clip(upper=0)

if ema == True:
# Use exponential moving average
ma_up = up.ewm(com = periods - 1, adjust=True, min_periods = periods).mean()
ma_down = down.ewm(com = periods - 1, adjust=True, min_periods = periods).mean()
else:
# Use simple moving average
ma_up = up.rolling(window = periods, adjust=False).mean()
ma_down = down.rolling(window = periods, adjust=False).mean()

rsi = ma_up / ma_down
rsi = 100 - (100/(1 + rsi))
return rsi

5. On-Balance Volume (OBV)

The on-balance volume is a momentum indicator that uses volume to predict changes in stock price. It is calculated by adding the volume on days when the stock price closes higher and subtracting the volume on days when the stock price closes lower.

To calculate the OBV in Python, you can use the following code:

import pandas as pd

def on_balance_volume(data, volume):
obv = [volume[0]]
for i in range(1, len(data)):
if data[i] > data[i-1]:
obv.append(obv[-1] + volume[i])
elif data[i] < data[i-1]:
obv.append(obv[-1] - volume[i])
else:
obv.append(obv[-1])
return obv

# calculate the OBV for a stock's closing price and volume
obv = on_balance_volume(data['Close'], data['Volume'])

These are just a few examples of the many stock technical indicators available, and there are many other ways to calculate them in Python. Technical analysis can be a powerful tool for identifying trends and making investment decisions, and by using Python and these indicators, you can gain valuable insights into the market.

--

--