I have an Dataframe with columns below minus the position column and my goal is to create a new column with name position that equals 1 when signal equals 1 and the Closeprice from the row that signals equals 1 is larger than the ATR. When Closeprice falls below the value of the ATR where Signals equal 1 the position will be equal to Zero.
Do you have any tips how I can do this?
CodePudding user response:
We can do it using the select
method from numpy
:
>>> import numpy as np
>>> condlist = [(df['Signal'] == 1) & (df['Closeprice'] > df['ATR']),
... (df['Signal'] == 1) & (df['Closeprice'] < df['ATR'])]
>>> choicelist = [1, 0]
>>> df['Position'] = np.select(condlist, choicelist, default=0)
>>> df
Signal Closeprice ATR Position
0 1 10 5 1
1 0 20 15 0
2 0 30 25 0
3 0 40 50 0
On the second line the Position
is 0
since the Signal
value is 0
.
CodePudding user response:
Use boolean mask
. Create masks for your 2 conditions:
import numpy as np
m1 = df['Signal'].eq(1) & df['Closeprice'].gt(df['ATR'])
m2 = m1.shift() & df['Closeprice'].gt(df['ATR'])
df['Position'] = np.where(m1|m2, 1, 0)
Output:
>>> df
Signal Closeprice ATR Position
0 1 10 5 1 # True for m1 mask
1 0 20 15 1 # True for m2 mask
2 0 30 25 0
3 0 40 50 0