Generate Support Resistance Line for any stocks in 3 Minutes

Lidian
3 min readSep 12, 2020

--

Square Stock Price from March to September with 4 SR Levels

From my experience, every traders exploit support and resistance level in their entry/exit decision and it’s like trading 101. I might as well learn how to do so. Above is the end-result from the Algorithm.

After hours of researching, I found several mechanical methods to draw those levels, and one particularly draws my attentions, which is Agglomerative Clustering.

The basic concept is to group the close points into clusters , so that we are able to identify levels of infections as they are all lie close to each other.

Unlike some ML algorithms, clustering flexible as this algorithm does not limit data length as input and number of SR lines as outputs.

The Full Code Link is here if you want to implement the code. Below is the basic usage.

Step 1: Download Stock Data From any source you prefer (e.g. yFinance)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.cluster import AgglomerativeClustering
import mplfinance as mpf
from datetime import date,timedelta

# Calculate VERY simple waves
df = yf.Ticker("SQ").history(period="max") # Download Data
df.index = pd.to_datetime(df.index)
df.drop(['Dividends','Stock Splits'], axis=1, inplace=True)

I use Square.inc as an example here. I download all available stock data from yahoo Finance, and strip out useless columns likes Dividends and Stock Splits.

Step 2: Pass the Stock data to the generate_SR_line Function

W2 = generate_SR_line(df, duration=100, n = 4)
Square Stock Price from March to September with 4 SR Levels

Where below are the descriptions of the parameters.

df = DataFrame 
n = Number of Clusters / Number of Support/Resistance Line
Start = Start index e.g. 0
End = End index e.g. 100
Duration = # of days used in S&R line from today

In the example above, I use 100 periods (roughly 100/22 = 4.5 months worth of Stock Data) to build the support and resistance level. It seems to me that currently Square is hitting its resistance level @ ~$138.

Step 2B: Build S&R levels over time (optional for feature engineering)

Not only we can visualise the SR level, we could also use them as nice features to predict stock prices/when to entry or exit.

col_names = ['SR1','SR2','SR3','SR4']
start = 0
period = 100 # roughly 1 quarter + 20 days for rolling data

SRs = pd.DataFrame()
for i in range(0, len(df) - period):
W = generate_SR_line(df, start = start+i, end = start+i+period, plot=False)
SRs = SRs.append(W.iloc[0:4], ignore_index=True)
if i == 0 or i == len(df) - period - 1:
print('Ending Date: ' + str(df.index[start+i+period]))
SRs.columns = col_names
SRs.index = df.iloc[period:].index

To prepare the data frame, I used a for loop to generate the SR level on a rolling basis.

dfs = pd.concat([df, SRs], axis=1).dropna()
ends(dfs)

Here’s the output of the code.

Original Stock data with 4 SR levels over time

On the next post, I’m going to explore whether the SR levels actually helps in stock predictions.

Also, I will compare what methods (Reinforcement Learning, Clustering, basic rules) yield SR levels based on profit/loss regime in the near future. Stay tuned and please subscribe if you like to see more of the content.

For convenience, the Full Source Code Link is shown here.

--

--