1

I am trying to define the trigger point when wt1(Moving average 1) crosses over wt2(moving average 2) and add it to the column ['side'].

So basically add 1 to side at the moment wt1 crosses above wt2.

This is the current code I am using but doesn't seem to be working.

for i in range(len(df)):
    if df.wt1.iloc[i] > df.wt2.iloc[i] and df.wt1.iloc[i-1] < df.wt2.iloc[i-1]:
        df.side.iloc[1]

If I do the following:

long_signals = (df.wt1 > df.wt2)

df.loc[long_signals, 'side'] = 1

it return the value of 1 the entire time wt1 is above wt2, which is not what i am trying to do.

Expected outcome is when wt1 crosses above wt2 side should be labeled as 1.

Help would be appreciated!

Sample_data

ABE
  • 11
  • 2
  • Can you provide some sample data and your expected output please? – sophocles Jan 14 '22 at 16:16
  • Updated @sophocles – ABE Jan 14 '22 at 17:26
  • btw when somebody suggests you post some data they do not mean a picture of it; pls see [asking good Pandas questions](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – piterbarg Jan 14 '22 at 20:33

1 Answers1

0

Use shift in your condition:

long_signals =    (df.wt1 > df.wt2) & (df.wt1.shift() <= df.wt2.shift())
df.loc[long_signals, 'side'] = 1
df

if you do not like NaNs in 'side', use df.fillna(0) at the end

Your first piece of code also works with the following small modification

for i in range(len(df)):
    if df.wt1.iloc[i] > df.wt2.iloc[i] and df.wt1.iloc[i-1] <= df.wt2.iloc[i-1]:
        df.loc[i,'side'] = 1
piterbarg
  • 8,089
  • 2
  • 6
  • 22