Calculating Swing high and Swing low indicator in python

Swing high and swing low points are also referred to as pivot points in many literatures. During price movement, prices form many patterns. The point of reversal of prices from a temporarily high is known as swing high point and reversal from temporarily formed low is known as swing low point. 

In the tradingview pine script we have in-built function known as pivothigh and pivotlow for the identification of such swing points. If you are new to pinescript and want to learn pinescript, refer following sources :

1. Book

2. Highest Rated Udemy Course

For calculation of swing high/low points, pinescript takes two parameters from the user i.e. number of left bars and number of right bars. It is recommended that these parameters may be set as 4 for left and 2 for right bars. 

The python code that I am going to demonstrate, I have used 4 as left bars and 2 as right bars and no input has been asked from the user. The purpose of the function is to identify, swing points so with the default setting of 4 left and 3 right bars, the function will consider seven bars at a time. If the bar is lowest among 4 left bars and 2 right bars, the bar can be considered as swing high point. The function will mark that bar as swing high bar and store the value of highest value else a NAN value is stored. The graphical representation of the concept for calculation of pivot high and pivot low points in python is shown below:

High

4

5

6

7

8

4

3

2

PH

Nan

Nan

Nan

Nan

8 Nan Nan

Nan

The value of swing point is stored as soon as it is identified but in any case it can only be identified after a lapse of at least 2 bars. Thus marking of pivot points will be lagging by 2 bars. 

Similarly, for pivot low, lowest value among the 4 left bars and 2 right bars is looked for, if the value of a bar is lowest among 4 left bars and 2 right bars, the lowest of the bar can be considered as pivot low. 

The Code

The code in python for calculation of swing high and swing low points is provided below:

def pivot(df):
data = df.copy()
data['d1'] = data.High.shift(-1)
data['d2'] = data.High.shift(-2)
data['d3'] = data.High.shift(0)
data['d4'] = data.High.shift(1)
data['d5'] = data.High.shift(2)
data['d6'] = data.High.shift(3)
data['d7'] = data.High.shift(4)
data['maxPH'] = data[['d1','d2','d3','d4','d5','d6','d7']].max(axis=1)
data['PH'] = np.where(data['maxPH'] == data['d3'], data['d3'], "NaN")

data['d1'] = data.Low.shift(-1)
data['d2'] = data.Low.shift(-2)
data['d3'] = data.Low.shift(0)
data['d4'] = data.Low.shift(1)
data['d5'] = data.Low.shift(2)
data['d6'] = data.Low.shift(3)
data['d7'] = data.Low.shift(4)
data['minPL'] = data[['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7']].min(axis=1)
data['PL'] = np.where(data['minPL'] == data['d3'], data['d3'], "NaN")

data['recentPL'] = data.PL.shift(2).astype(float).fillna(method='ffill')
data['recentPH'] = data.PH.shift(2).astype(float).fillna(method='ffill')

data = data.drop(columns=['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'minPL', 'maxPH','PL','PH'])

return data 

Explanation to Swing high and swing low Code in python

The above python code is written in a very crude way so that new users can understand from the concepts learned so far. You can always use your programming skills for improving the code.

The following new terms have appeared and may need further explanation for understanding:

1. shift() : shift function operates on dataframe and is used to shift the entire column values downward or upwards. 

2. fillna() : this function is also used with pandas dataframe. It has two method of filling missing values or "na" values. One is forward fill (ffill) method and another is backward fill (bfill) method.

An analogy with excel operations for calculation of pivot

To calculate swing high with parameters 4 bar left and 2 bar right. We will first calculate seven period's highest value as shown below.
 

This value will include 4 previous bar's high and two next bars. This can easily be done by using "max" formula of excel. 


If the highest highs of the previous calculation is equal to the current bar's high, then the current bar's high is the swing high point. 


You can manually verify that the pivot values calculated using excel are correct. The swing high point can only be identified after the occurrence of two more bars. 

How calculations done in excel can be repeated in pandas dataframe?

Assume that you have a data frame named df with Datetime, open high, low, close, volume as columns. New columns d1 to d7 can be created from column 'High' by using the following instructions:
    data['d1'] = data.High.shift(-1)
data['d2'] = data.High.shift(-2)
data['d3'] = data.High.shift(0)
data['d4'] = data.High.shift(1)
data['d5'] = data.High.shift(2)
data['d6'] = data.High.shift(3)
data['d7'] = data.High.shift(4)
Now calculating the maximum value among d1 to d7 is as good as calculating max in 'High' column with 4 left bars and 2 right bars. 

The max value from d1 to d8 is stored in column maxPH using the below instruction:
data['maxPH'] = data[['d1','d2','d3','d4','d5','d6','d7']].max(axis=1)
 

If the calculated maxPH happens to be equal to the current bar's high value, then the PH column value is set to the current bar's high value else 'NaN' is set. 
data['PH'] = np.where(data['maxPH'] == data['d3'], data['d3'], "NaN")

Since the PH value can only be identified after the lapse of two bars, the PH value so calculated seems to have forward bias. Therefore a new column, recentPH is created with shift =2 and forward fill as under:
data['recentPH'] = data.PH.shift(2).astype(float).fillna(method='ffill')



Python pandas dataframe fillna() function

Lets assume that we have a dataframe named 'df' with following columns where some of the values of temperature are missing

Date

Temperature

14-March-98

 

15-March-98

14

16-March-98

 

17-March-98

15

18-March-98

 

19-March-98

16

20-March-98

 

The forward fill (ffill) method will write the preceding available value in missing places. 

df['Temperature'] = df['Temperature'].fillna(method='ffill')

The result of above instruction will be :

Date

Temperature

14-March-98

 

15-March-98

14

16-March-98

14

17-March-98

15

18-March-98

15 

19-March-98

16

20-March-98

16

The backward fill (ffill) method will write the next available value in missing places. 

df['Temperature'] = df['Temperature'].fillna(method='bfill')

The result of above instruction will be :

Date

Temperature

14-March-98

14 

15-March-98

14

16-March-98

15

17-March-98

15

18-March-98

16

19-March-98

16

20-March-98

 

 

Resources

Highest Rated Udemy Course on PineScript - Grab your Seat Now 

Udemy Discount Coupon Code : UDEMY-JAN23 (Valid upto 30th Nov 2023)

Learn more about coding on tradingview in PineScript through Books on pinescript available on amazon and kindle.


200+ pages book100 pages book200+ pages book


Point and Figure Charts : A Time-Tested Tool for Technical Analysis

In the dynamic world of financial markets, investors and traders constantly seek tools that can provide valuable insights into market trends...