Search code examples
pythonapivisual-studio-codebinancetradingview-api

Convert tradingview's pine script to python in VScode


I want to convert the following Pine script to python to calculate the value for vwap1 variable without plotting the results, I just want to calculate the value for vwap1:

...
wapScore(pds) =>
    mean = sum(volume*close,pds)/sum(volume,pds)
    vwapsd = sqrt(sma(pow(close-mean, 2), pds) )
    (close-mean)/vwapsd

vwap1 = input(48)
plot(vwapScore(vwap1),title="ZVWAP2-48",color=#35e8ff, linewidth=2,transp=0.75)
...

I have tried the following:

...
def calculate_SMA(ser, days):
    sma = ser.rolling(window=days).mean()
    return sma


def calculate_Zscore(pds, volume, close):
    mean = sum(volume * close, pds) / sum(volume, pds)
    vwapsd = np.sqrt(calculate_SMA(pow(close - mean, 2), pds))
    return (close - mean) / vwapsd

...

And I am using calculate_Zscore function to calculate the value and add it to pandas dataframe but it gives me different values rather than the values on trading view


Solution

  • I just wanted to comment ...but my reputation cannot allow me :)

    Surely the sum of pine script (tradingview) has a different type signature than the python sum. In particular the second parameter has a totally different meaning. In pine script sum(x,y) tells you the sliding sum of last y values of x (sum of x for y bars back). In python sum(x,y) sum the iterable x and if y, the second parameter has passed (optional), this value is added to the sum of items of the iterable.So if your sum(x) == 4.5 then sum(x,10) == 14.5

    So your code surely need to be changed at least on the use of this method

    Hoping to be helpful