3

i want to transfer a pine-script linreg function to php, and i need some help which values are exactly passed to the linreg function.

i.e. my linreg function in pine-script looks like this:

linreg(close, 20, 0)

for calculating the linear regression in php, i have the following function:

public static function linear_regression($x, $y) {

        // calculate number points
        $n = count($x);

        // ensure both arrays of points are the same size
        if ($n != count($y)) {

          trigger_error("linear_regression(): Number of elements in coordinate arrays do not match.", E_USER_ERROR);

        }

        // calculate sums
        $x_sum = array_sum($x);
        $y_sum = array_sum($y);

        $xx_sum = 0;
        $xy_sum = 0;

        for($i = 0; $i < $n; $i++) {

          $xy_sum+=($x[$i]*$y[$i]);
          $xx_sum+=($x[$i]*$x[$i]);

        }

        // calculate slope
        $m = (($n * $xy_sum) - ($x_sum * $y_sum)) / (($n * $xx_sum) - ($x_sum * $x_sum));

        // calculate intercept
        $b = ($y_sum - ($m * $x_sum)) / $n;

        // return result
        return array("m"=>$m, "b"=>$b);
    }

my question now is what data i have to pass to my php function to get the same result as in the pine-script.

Lukas F.
  • 55
  • 8

2 Answers2

1

I've created a pure Pine linreg function based on your PHP script. This produces exactly the same results as the builtin ta.linreg.

pine_linreg(src, len, offset=0) =>
    // These are constants, we need to calculate them only on the 1st bar
    var float x_sum = 0.0
    var float xx_sum = 0.0
    if bar_index == 0
        for i = 0 to len - 1
            x_sum += i
            xx_sum += i * i

    y_sum = math.sum(src, len)
    xy_sum = 0.0
    for i = len - 1 to 0
        xy_sum += i * src[len - 1 - i]

    // slope
    slope = (len * xy_sum - x_sum * y_sum) / (len * xx_sum - x_sum * x_sum)
    // intercept
    intercept = (y_sum - slope * x_sum) / len

    linreg = intercept + slope * (len - 1 - offset)

The trick is that the x array is the time axis, and always [0, 1, ..., len-1]. The y array is the source. Then the formula you should use is the last line in pine function, also documented in ta.linreg's documentation.

Adam Wallner
  • 2,292
  • 23
  • 20
0

According to the reference manual, the result of the linreg function is calculated as linreg = intercept + slope * (length - 1 - offset), where intercept and slope are the values calculated with the least squares method on source series.

This question has also been asked here: Converting linreg function from pinescript to Python?. Have you tried the solution proposed there?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
MRYR
  • 72
  • 5