1

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.

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This will work. Now I just need to get index from series mask for further processing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.