Search code examples
pythonpandastrading

How to remove duplicated buy signal


I'm testing my stock trading logic and I made a position column to check the buying / selling signal

df = pd.DataFrame({'position': [1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]})

I want to replace 1.0 value occurs between 1.0 and -1.0 with 0.0, and replace -1.0 value occurs between -1.0 and 1.0 with 0.0

here is the desired output:

df = pd.DataFrame({'position': [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]})

NOTE: the output only keeps the initial signal of 1.0 or -1.0


Solution

  • Here is a basic implementation based on the approach described by the previous answer:

    lastseen = 0
    
    for n,el in enumerate(df["position"]):
        if lastseen == 0 and el == -1:
            raise Exception("Inconsistent data")
        
        if (el in [1, -1] and el != lastseen) or lastseen == 0:
            lastseen = el
        else:
            df["position"][n] = 0
    

    I added the first check by considering the domain you described. If it's not correct for your problem feel free to remove it