Kind_Man
Kind_Man

Reputation: 1

How to convert trading strategies from PineScript to Python so signals would match?

I want to turn strategies/indicators from TradingView PineScript scripts to Python. Can someone explain me on basic and, I think, simple example, why PineScripts are different and whats wrong I am doing?

I have very simple TV indicator: Momentum Strategy. You can find it, it is basic non community strategy

It has such code:

strategy("Momentum Strategy", overlay=true)
length = input(12)
price = close
momentum(seria, length) =>
    mom = seria - seria[length]
    mom
mom0 = momentum(price, length)
mom1 = momentum( mom0, 1)
if (mom0 > 0 and mom1 > 0)
    strategy.entry("MomLE", strategy.long, stop=high+syminfo.mintick, comment="MomLE")
else
    strategy.cancel("MomLE")
if (mom0 < 0 and mom1 < 0)
    strategy.entry("MomSE", strategy.short, stop=low-syminfo.mintick, comment="MomSE")
else
    strategy.cancel("MomSE")

As you can see, very simple. This code generates such signals: As you can see, only 2 signals for 42 minutes

But when I started turning this script into Python and then plotting, I found out that my code generates so much more signals and I can't understand why.

Firstly, I tried this solution. Calculation without ta libraries:

def add_momentum_strategy_signals(df, length=12):
    df['mom0'] = df['close'] - df['close'].shift(length)
    df['mom1'] = df['mom0'] - df['mom0'].shift(1)
    
    df['momentum_signal'] = 0
    
    long_condition = (df['mom0'] > 0) & (df['mom1'] > 0)
    short_condition = (df['mom0'] < 0) & (df['mom1'] < 0)
    
    df.loc[long_condition, 'momentum_signal'] = 1
    df.loc[short_condition, 'momentum_signal'] = -1
    tick_size = df['close'].diff().abs().median()
    df['long_stop'] = df['high'] + tick_size
    df['short_stop'] = df['low'] - tick_size
    
    return df

As you can see, it generated me much more signals:

signals

Well, then I decided to use TAlib library:

def momentum_strategy_talib(df, length=12):
    mom0 = ta.MOM(df['close'], timeperiod=length)
    mom1 = ta.MOM(mom0, timeperiod=1)

    df['signal'] = None
    df['stop_price'] = None
    df['order_type'] = None

    for i in range(length, len(df)):
        if mom0[i] > 0 and mom1[i] > 0:
            df.loc[i, 'signal'] = 'buy'
            df.loc[i, 'stop_price'] = df['high'][i] + df['high'].diff().mean()
            df.loc[i, 'order_type'] = 'stop'


        elif mom0[i] < 0 and mom1[i] < 0:
            df.loc[i, 'signal'] = 'sell'
            df.loc[i, 'stop_price'] = df['low'][i] - df['low'].diff().mean() 
            df.loc[i, 'order_type'] = 'stop'

    return df

Result is the same. So much more signals, than it should be. results with talib

I guess, this is my misunderstanding of basics PineScript vs Python. Can you please, on this basic and easy example, show me how can I fix my code so my Python implementation would match TV signals? Give your example?

Upvotes: 0

Views: 418

Answers (0)

Related Questions