Reputation: 13426
I have DataFrame df
df=pd.DataFrame([[47,55,47,50], [33,37,30,25],[61,65,54,57],[25,26,21,22], [25,29,23,28]], columns=['open','high','low','close'])
print(df)
open high low close
0 47 55 47 50
1 33 37 30 25
2 61 65 54 57
3 25 26 21 22
4 25 29 23 20
I want to use previous values in if statement to compare. Logic is as below:
if (close[i-1]/close[i] > 2) and (high[i] < low[i-1]) and
((open[i] > high[i-1]) or (open[i] <low[i-1])) :
I have written a code :
for idx,i in df.iterrows():
if idx !=0 :
if ((prv_close/i['close'])>2) and (i['high'] < prv_low) and ((i['open'] > prv_high) or (i['open'] < prv_low)):
print("Successful")
else:
print("Not Successful")
prv_close = i['close']
prv_open = i['open']
prv_low = i['low']
prv_high = i['high']
output:
Not Successful
Not Successful
Successful
Not Successful
But For millions of rows it's taking too much time. Is there any other way to implement it faster?
P.S : Action to be taken on data are different in if statement. For simplicity I'm using print statement. My columns may not have same order this is why I'm using iterrows()
instead of itertuples()
.
Any suggestions are welcome. Thanks.
Upvotes: 1
Views: 47
Reputation: 294586
d0 = df.shift()
cond0 = (d0.close / df.close) > 2
cond1 = df.high < d0.low
cond2 = df.open > d0.high
cond3 = df.open < d0.low
mask = cond0 & cond1 & (cond2 | cond3)
mask
0 False
1 False
2 False
3 True
4 False
dtype: bool
Upvotes: 1