[Python] converting pine script to python

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    i am converting the following pine script to python. the python code works good but the last part of code which detects the dir/direction doesn't work.

    //@version=4
    study("STrend", overlay=true)

    length = input(title="ATR Period", type=input.integer, defval=22)
    mult = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3)
    src = input(title="Source", type=input.source, defval=hl2)
    wicks = input(title="Take Wicks into Account ?", type=input.bool, defval=true)
    showLabels = input(title="Show Buy/Sell Labels ?", type=input.bool, defval=true)
    highlightState = input(title="Highlight State ?", type=input.bool, defval=true)

    atr = mult * atr(length)
    highPrice = wicks ? high : close
    lowPrice = wicks ? low : close
    doji4price = open == close and open == low and open == high

    longStop = src - atr
    longStopPrev = nz(longStop[1], longStop)
    if longStop > 0
    if doji4price
    longStop := longStopPrev
    else
    longStop := (lowPrice[1] > longStopPrev ? max(longStop, longStopPrev) : longStop)
    else
    longStop := longStopPrev


    shortStop = src + atr
    shortStopPrev = nz(shortStop[1], shortStop)
    if shortStop > 0
    if doji4price
    shortStop := shortStopPrev
    else
    shortStop := (highPrice[1] < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop)
    else
    shortStop := shortStopPrev


    var int dir = 1
    dir :=
    dir == -1 and highPrice > shortStopPrev ? 1 :
    dir == 1 and lowPrice < longStopPrev ? -1 :
    dir

    plot(longStop, color=color.green)
    plot(shortStop, color=color.red)
    plotshape(dir == 1 ? dir: na, color=color.green)
    plotshape(dir == -1 ? dir: na, color=color.red)


    here is the python code which is converted from the above pine-script.

    #!/usr/bin/env python3

    import matplotlib.pyplot as plt
    import pandas as pd
    import pandas_ta as ta
    import yfinance as yf


    plt.style.use("fivethirtyeight")

    df = yf.download("TSLA", start="2023-01-01")
    print(df.head())

    length = 22
    mult = 3
    df["hl2"] = (df["High"] + df["Low"]) / 2
    src = df["hl2"]
    atr = mult * ta.atr(df["High"], df["Low"], df["Close"], length=length)
    doji4price = (
    (df["Open"] == df["Close"]) & (df["Open"] == df["Low"]) & (df["Open"] == df["High"])
    )

    long_stop = src - atr
    long_stop_prev = long_stop.shift(1).fillna(long_stop)
    for i in range(1, len(long_stop)):
    if long_stop > 0:
    if doji4price:
    long_stop = long_stop_prev
    else:
    long_stop = (
    max(long_stop, long_stop_prev)
    if df["Low"][i - 1] > long_stop_prev
    else long_stop
    )
    else:
    long_stop = long_stop_prev


    short_stop = src + atr
    short_stop_prev = short_stop.shift(1).fillna(short_stop)
    for i in range(1, len(short_stop)):
    if short_stop > 0:
    if doji4price:
    short_stop = short_stop_prev
    else:
    short_stop = (
    min(short_stop, short_stop_prev)
    if df["High"][i - 1] < short_stop_prev
    else short_stop
    )
    else:
    short_stop[i] = short_stop_prev[i]

    d = 1
    direction = []
    for i in range(len(df)):
    if d == -1 and df["High"][i] > short_stop_prev[i]:
    d = 1
    direction.append(1)
    elif d == 1 and df["Low"][i] < long_stop_prev[i]:
    d = -1
    direction.append(-1)
    else:
    d = d
    direction.append(d)

    direction = pd.Series(direction)
    direction.index = df.index


    plt.plot(df["Close"], color="cyan")
    plt.plot(long_stop, color="green")
    plt.plot(short_stop, color="red")
    plt.plot(df["Close"][direction == 1], "^", color="darkgreen")
    plt.plot(df["Close"][direction == -1], "v", color="darkred")
    plt.legend(["close", "long stop", "short stop", "^", "v"])
    plt.show()


    here is the [B]problem[/B]; the output of following python code is not same as the output of following pine script. from the month 1 to 7 the else part of the python code is executed which is wrong. look at the python plot and tradingview plot, the direction in python is not equal to the dir.

    dir :=
    dir == -1 and highPrice > shortStopPrev ? 1 :
    dir == 1 and lowPrice < longStopPrev ? -1 :
    dir


    the python code in the below was written from the above pine-script but it's not doing the same thing. what's wrong with this part of the code?

    d = 1
    direction = []
    for i in range(len(df)):
    if d == -1 and df["High"][i] > short_stop_prev[i]:
    d = 1
    direction.append(1)
    elif d == 1 and df["Low"][i] < long_stop_prev[i]:
    d = -1
    direction.append(-1)
    else:
    d = d
    direction.append(d)


    here is the plot of python code.

    [URL='https://i.sstatic.net/Ucn9u.png'][IMG]https://i.sstatic.net/Ucn9u.png[/IMG][/URL]

    and here is the plot of the tradingview pine script. the green line is longStop variable, red line is shortStop, green x is dir == 1 shows uptrend and red x shows downtrend dir == -1. the blue line is the close price.

    [URL='https://i.sstatic.net/6mGGA.png'][IMG]https://i.sstatic.net/6mGGA.png[/IMG][/URL]

    [url="https://stackoverflow.com/questions/77312679/converting-pine-script-to-python"]Continue reading...[/url][/i][/i][/i][/i][/i][/i][/i][/i][/i][/i]

Compartilhe esta Página