how to find df cells that are above/below pivot points, but only once

54 Views Asked by At

I've got pandas dataframe with candle highs and lows. I've made new column, which shows pivot points (if the value in cell is lowest\highest between two above it an two below it, it has value 1 for lowest or 2 for highest , else 0) example:

date high low pivot takes pivot
01.01.2020 207 204 0
02.01.2020 208 205 0
03.01.2020 209 205 2
04.01.2020 207 203 0
05.01.2020 206 202 0
06.01.2020 205 200 0
07.01.2020 204 199 1
08.01.2020 206 201 0
09.01.2020 207 202 0
10.01.2020 208 205 0
11.01.2020 210 207 0
12.01.2020 212 209 0
13.01.2020 214 210 2
14.01.2020 207 204 0
15.01.2020 203 202 0
16.01.2020 201 198 0
17.01.2020 199 196 0

i need to find exact candles that made new high or low(according to pivotpoints,not all candles), something like this: for example in this table takes pivot=1 for 16.01.2020 and takes pivot=2 for 11.01.2020 only(takes pivot = 1 for lows and 2 for highs)

I've tried to make a loop, but cant really understand how exactly it should look

1

There are 1 best solutions below

2
Panda Kim On

Code

rolling and use np.select

import numpy as np
cond1 = df['high'].rolling(5, center=True).max().eq(df['high'])
cond2 = df['low'].rolling(5, center=True).min().eq(df['low'])
df['pivot'] = np.select([cond1, cond2], [2, 1], 0)

df

    date    high    low pivot
0   01.01.2020  207 204 0
1   02.01.2020  208 205 0
2   03.01.2020  209 205 2
3   04.01.2020  207 203 0
4   05.01.2020  206 202 0
5   06.01.2020  205 200 0
6   07.01.2020  204 199 1
7   08.01.2020  206 201 0
8   09.01.2020  207 202 0
9   10.01.2020  208 205 0
10  11.01.2020  210 207 0
11  12.01.2020  212 209 0
12  13.01.2020  214 210 2
13  14.01.2020  207 204 0
14  15.01.2020  203 202 0
15  16.01.2020  201 198 0
16  17.01.2020  199 196 0

Example Code

import pandas as pd
data1 = {'date': ['01.01.2020', '02.01.2020', '03.01.2020', '04.01.2020', '05.01.2020', '06.01.2020', '07.01.2020', '08.01.2020', '09.01.2020', '10.01.2020', '11.01.2020', '12.01.2020', '13.01.2020', '14.01.2020', '15.01.2020', '16.01.2020', '17.01.2020'], 'high': [207, 208, 209, 207, 206, 205, 204, 206, 207, 208, 210, 212, 214, 207, 203, 201, 199], 'low': [204, 205, 205, 203, 202, 200, 199, 201, 202, 205, 207, 209, 210, 204, 202, 198, 196]}
df = pd.DataFrame(data1)