Tom
Tom

Reputation: 1

Convert Pine Script into Python

I am just wondering how to convert the PineScript dev() function into Python code. Is my interpretation correct?

Pine Scripts Example is the following:

plot(dev(close, 10))

// the same on pine
pine_dev(source, length) =>
    mean = sma(source, length)
    sum = 0.0
    for i = 0 to length - 1
        val = source[i]
        sum := sum + abs(val - mean)
    dev = sum/length
plot(pine_dev(close, 10))

My Python code is the following:

df["SMA_highest"] = ta.sma(df["Close"], 10)
df["dev_abs_highest"] = (df["Close"] - df["SMA_highest"]).abs()
df["dev_cumsum_highest"] = df["dev_abs_highest"].rolling(window=10).sum()
df["DEV_SMA_highest"] = df["dev_cumsum_highest"] / 10

What do I need to adjust in the Python code to have the same result as in the Pine Script?

Thanks for any hints :)

Upvotes: 0

Views: 2205

Answers (1)

tommygun
tommygun

Reputation: 11

I was looking for the same script too and did not find a ready-to-go solution. So I implemented myself. Unfortunately I did not test it completely because the stock prices between yfinance and TradingView differ a little bit, so the result differs a little bit too.

    diffavg    = stock[columnname].rolling(days).apply(pine_dev)

    def pine_dev(column):
       summ       = 0.0
       mean       = column.mean() 
       length     = len(column)
       for i in range(0, length):
         summ = summ +  abs( column[i] - mean )
    
       ret_val  = summ / length
       return ret_val

Basically I use the rolling function and if you apply a function to this, you get all Values from the rolling timeframe in the function.

Upvotes: 1

Related Questions