The example data goes like this, with prices of a stock, and buy indicating the possible buy points.
Price Buy
0 121385 0
1 121375 0
2 121375 0
3 121360 121360
4 121360 121360
5 121350 121350
6 121350 121350
7 121340 121340
8 121345 121345
9 121340 121340
10 121340 121340
11 121345 121345
12 121350 121350
13 121350 0
14 121340 121340
15 121345 121345
16 121345 121345
17 121350 0
18 121355 0
19 121255 0
20 121245 0
21 121245 0
22 121240 0
23 121240 0
24 121225 0
25 121235 0
26 121225 0
27 121220 0
28 121215 121215
29 121225 0
30 121230 0
After the first nonzero Buy, the output column should , repeate the same first buy value while price dont deviate 130 points below or above the first buy point. Like this:
Price Buy output
121385 0 0.0
121375 0 0.0
121375 0 0.0
121360 121360 121360.0
121360 121360 121360.0
121350 121350 121360.0
121350 121350 121360.0
121340 121340 121360.0
121345 121345 121360.0
121340 121340 121360.0
121340 121340 121360.0
121345 121345 121360.0
121350 121350 121360.0
121350 0 121360.0
121340 121340 121360.0
121345 121345 121360.0
121345 121345 121360.0
121350 0 121360.0
121355 0 121360.0
121255 0 121360.0
121245 0 121360.0
121245 0 121360.0
121240 0 121360.0
121240 0 121360.0
121225 0 0.0
121235 0 0.0
121225 0 0.0
121220 0 0.0
121215 121215 121215.0
121225 0 121215.0
121230 0 121215.0
The following loop does the work, though with a long computational time.
import pandas as pd
df=pd.read_csv('DataStack.CSV',delimiter=';')
Poze=0 #0=waiting 1=buying
FirstBuy=0 #Buy
SL=130 #deviation
for index, row in df.iterrows():
if (Poze==0): #check if already has a entry buy point
if (row['Buy']!=0): #assign entry buy point
Poze=1
FirstBuy=row['Price']
else:
if (Poze==1): # stop replicating if deviation is enough
if (row['Price']>=FirstBuy+SL):
Poze=0
elif (row['Price']<=FirstBuy-SL):
Poze=0
df.loc[index,'pose']=Poze
df.loc[index,'first']=FirstBuy
df['output']=df['pose']*df['first']
- Link to the CSV with data: https://drive.google.com/file/d/1uI3GDh2HTrqyubaLWw6hG3pxtbKdzqBl/view?usp=sharing
- Link to the code: https://colab.research.google.com/drive/11osytR5iC3TIC8gkQhZ3t307qozlItoe?usp=sharing
Anyone knows how can i find the same output column, avoiding loops? Tks!