Converting linreg function from pinescript to Python?
Converting linreg function from pinescript to Python?
Loading saved threads...
YoYoYo · External communityPost link
External question — Stack Overflow Stack Exchange
Author: YoYoYo
Original post: https://stackoverflow.com/questions/67719509
License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: HTML converted to plain text; contact email addresses removed.
I am trying to convert a TradingView indicator into Python (also using pandas to store its result).
This is the indicator public code I want to convert into a python indicator:
https://www.tradingview.com/script/sU9molfV/
And I am stuck creating that pine script
linereg
default function.
This is the fragment of the pinescript indicator I have troubles with:
lrc = linreg(src, length, 0)
lrc1 = linreg(src,length,1)
lrs = (lrc-lrc1)
TSF = linreg(src, length, 0)+lrs
This is its documentation:
Linear regression curve. A line that best fits the prices specified
over a user-defined time period. It is calculated using the least
squares method. The result of this function is calculated using the
formula: linreg = intercept + slope * (length - 1 - offset), where
length is the y argument, offset is the z argument, intercept and
slope are the values calculated with the least squares method on
source series (x argument). linreg(source, length, offset) →
series[float]
Source:
https://www.tradingview.com/pine-script-reference/#fun_linreg
I have found this mql4 code and tried to follow it step by step in order to convert it and finally to create a function linreg in Python in order to use it further for building that pine script indicator:
https://www.mql5.com/en/code/8016
And this is my code so far:
# calculate linear regression:
# https://www.mql5.com/en/code/8016
barsToCount = 14
# sumy+=Close[i];
df['sumy'] = df['Close'].rolling(window=barsToCount).mean()
# sumxy+=Close[i]*i;
tmp = []
sumxy_lst = []
for window in df['Close'].rolling(window=barsToCount):
for index in range(len(window)):
tmp.append(window[index] * index)
sumxy_lst.append(sum(tmp))
del tmp[:]
df.loc[:,'sumxy'] = sumxy_lst
# sumx+=i;
sumx = 0
for i in range(barsToCount):
sumx += i
# sumx2+=i*i;
sumx2 = 0
for i in range(barsToCount):
sumx2 += i * i
# c=sumx2*barsToCount-sumx*sumx;
c = sumx2*barsToCount - sumx*sumx
# Line equation:
# b=(sumxy*barsToCount-sumx*sumy)/c;
df['b'] = ((df['sumxy']*barsToCount)-(sumx*df['sumy']))/c
# a=(sumy-sumx*b)/barsToCount;
df['a'] = (df['sumy']-sumx*df['b'])/barsToCount
# Linear regression line in buffer:
df['LR_line'] = 0.0
for x in range(barsToCount):
# LR_line[x]=a+b*x;
df['LR_line'].iloc[x] = df['a'].iloc[x] + df['b'].iloc[x] * x
# print(x, df['a'].iloc[x], df['b'].iloc[x], df['b'].iloc[x]*x)
print(df.tail(50))
print(list(df))
It doesn't work.
Any idea how to create a similar pine script
linereg
function into python, please?
Thank you in advance!
Quote
Report
jukeboX · External communityPost link
External answer — Stack Overflow Stack Exchange
Author: jukeboX
Original post: https://stackoverflow.com/a/68889027
License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: HTML converted to plain text; contact email addresses removed.
I used talib to calculate the slope and intercept on the closing prices, then realised talib offers the full calc also. The result looks to be same as TradingView (just eyeballing).
Did the following in jupyterlab:
import pandas as pd
import numpy as np
import talib as tl
from pandas_datareader import data
%run "../../plt_setup.py"
asset = data.DataReader('^AXJO', 'yahoo', start='1/1/2015')
n = 270
(asset
.assign(linreg = tl.LINEARREG(asset.Close, n))
[['Close', 'linreg']]
.dropna()
.loc['2019-01-01':]
.plot()
);
Quote
Report
Slyly Sly · External communityPost link
External answer — Stack Overflow Stack Exchange
Author: Slyly Sly
Original post: https://stackoverflow.com/a/75833487
License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: HTML converted to plain text; contact email addresses removed.
I was soaring with this question for a very long time, as a result I made such a function, it calculates linear regression as on the TradingView function ta.linreg() in PineScript:
import numpy as np
def np_shift(array: np.ndarray, offset: int = 1, fill_value=np.nan):
result = np.empty_like(array)
if offset > 0:
result[:offset] = fill_value
result[offset:] = array[:-offset]
elif offset < 0:
result[offset:] = fill_value
result[:offset] = array[-offset:]
else:
result[:] = array
return result
def Linreg(source: np.ndarray, length: int, offset: int = 0):
size = len(source)
linear = np.zeros(size)
for i in range(length, size):
sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for z in range(length):
val = source[i-z]
per = z + 1.0
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
average = sumY / length
intercept = average - slope * sumX / length + slope
linear[i] = intercept
if offset != 0:
linear = np_shift(linear, offset)
return linear
Quote
Report
Tony_Tong · External communityPost link
External answer — Stack Overflow Stack Exchange
Author: Tony_Tong
Original post: https://stackoverflow.com/a/77056392
License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: HTML converted to plain text; contact email addresses removed.
import talib
def linreg(data, period, offset):
intercept = talib.LINEARREG_INTERCEPT(data, period)
slope = talib.LINEARREG_SLOPE(data, period)
return intercept + slope * (period - 1 - offset)
Quote
Report
Post Reply
Quoted from Forex.com.bd-Editorial External answer — Stack Overflow Stack Exchange Author: jukeboX Source score (net votes, not local likes): 2 Original post: https://stackoverflow.com/a/68889027 License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/ Adaptation: HTML converted to plain text; contact email addresses removed. I used talib to calculate the slope and intercept on the closing prices, then realised talib offers the full calc also. The result looks to be same as TradingView (just eyeballing). Did the following in jupyterlab: import pandas as pd import numpy as np import talib as tl from pandas_datareader import data %run "../../plt_setup.py" asset = data.DataReader('^AXJO', 'yahoo', start='1/1/2015') n = 270 (asset .assign(linreg = tl.LINEARREG(asset.Close, n)) [['Close', 'linreg']] .dropna() .loc['2019-01-01':] .plot() );
Checking account access…