Linear Regression

Posted By: Andrea66

Linear Regression - 02/12/17 17:03

Dear All,
how is possible to print and calculate the linear regression as in the below picture ?
I need also to print the straight line for a duration of several years ( lots of bars ).

http://drive.google.com/open?id=0B7OAmRgfpHP-WkRjSk1uV3BVT2s
Posted By: dr_panther

Re: Linear Regression - 02/12/17 20:18

In general, Zorro is lighting fast, as long you don't do something stupid, it is fast enough laugh

Please check, if the following is, what you need, and search for "linear regression" in the manual, you will find some stuff there too.

Code:
function run(){
StartDate= 20060101; 
BarPeriod = 1440;
LookBack = 1000 ;

vars Price = series(price());
 

vars linreg = series(LinearReg(Price, 1000));
 
plot("linreg", linreg[0],MAIN, BLUE); 
 
}

Posted By: Andrea66

Re: Linear Regression - 02/13/17 08:36

dr_panther,

thanks for your reply.
Unfortunately the result is not what I' m searching for.
In the picture below the blue line is the result of the code you provided while the red line ( hand painted) is the regression straight line I need.
Furthermore I would avoid to pass past data to the method calculation of the linear regression . For the linear regression you need only the present data for the calculation of the straight line.

https://drive.google.com/open?id=0B7OAmRgfpHP-WkRjSk1uV3BVT2s

Thanks in advance, Andrea

Posted By: MatPed

Re: Linear Regression - 02/13/17 10:37

Andrea,
Is your question regarding the indicator linearreg that is returning only one Var, while you expect two values in order to be able to plot the line y= b+mx?
Am I correct?

Ciao
Posted By: Andrea66

Re: Linear Regression - 02/13/17 10:53

MatPed,

yes you are right; I would plot the standard regression straight line which of course needs 2 values ( as per my picture above ).
My final target would be also to plot the regression channels of the series.

If you could provide also the r-squared value like in the picture below, would be great.

https://drive.google.com/open?id=0B7OAmRgfpHP-YkVycXJIeXNRQlE

Ciao
Posted By: MatPed

Re: Linear Regression - 02/13/17 11:37

Ok,
I guess that linearreg is built not taking into consideration the time axis. Is more like the linear regression of all point as they appear at the same instant. I could be wrong and I would wait some input from people more expert than me, but I guess that you can find two points of the line you are looking for using two simple call:

var Point1 = LinearReg(Price, 500);
var Point2 = LinearReg(Price, 1000);
connecting point 1 and point 2 should be an approximation "your" line.

Try if it answer your point, if it does not double check the TA-Lib source code of the indicator in order to understand what the indicator really does or start from the math to code a new indicator that will suit your need.

If you are looking for a channel breakout strategy, I guess that dr_panther will be the proper approach, because you may be looking for a channel that will adapt to market conditions...

Ciao
Posted By: Andrea66

Re: Linear Regression - 02/13/17 16:43

MatPed,

the linear regression straight line needs to evaluate all the points of the curve; it can't be calculate as your proposal.
Posted By: Andrea66

Re: Linear Regression - 02/15/17 10:47

In MQL the code is something like this :



// variables
double a,b,c,
sumy=0.0,
sumx=0.0,
sumxy=0.0,
sumx2=0.0,
h=0.0,l=0.0;
int x;

// calculate linear regression

for(int i=0; i<barsToCount; i++)
{
sumy+=Close[i];
sumxy+=Close[i]*i;
sumx+=i;
sumx2+=i*i;
}

c=sumx2*barsToCount-sumx*sumx;

if(c==0.0)
{
Alert("Error in linear regression!");
return;
}


// Line equation
b=(sumxy*barsToCount-sumx*sumy)/c;
a=(sumy-sumx*b)/barsToCount;

// Linear regression line in buffer
for(x=0;x<barsToCount;x++)
LR_line[x]=a+b*x;


but I'm not able to translate in Zorro code.
"barsToCount" is the number of bars displayed in the graph.

May be also R has similar calculation but it's too difficult for me.
Any help ?
Posted By: MatPed

Re: Linear Regression - 02/15/17 11:47

Well perfection is the worst enemy of production. so I guess that my proposal could be quite good laugh

Anyway, I remember little regarding Mql, but if you change "double" with "var", fill the value in 2 "vars" named Close and LR_line, your code should work 90%.
You my encounter be the "vars Close" declaretion Close is a reserved name. Just use myClose or something like that. Try it and let me know.

Ciao
Posted By: Andrea66

Re: Linear Regression - 02/15/17 15:32

I tried with the following code but without success ( it doesn'plot a straight line but a curve ):

#define N 50 // Number of bars
function run()
{
StartDate= 20060101;
EndDate = 20060601;

BarPeriod = 15;

// variables
var a,b,c,sumy=0.0,sumx=0.0,sumxy=0.0,sumx2=0.0,h=0.0,l=0.0;
int x,i;
int barsToCount=50;

vars myClose = series(priceClose());



for( i=0; i<N; i++)
{
sumy+=myClose[i];
sumxy+=myClose[i]*i;
sumx+=i;
sumx2+=i*i;
}

c=sumx2*N-sumx*sumx;

// Line equation
b=(sumxy*barsToCount-sumx*sumy)/c;
a=(sumy-sumx*b)/N;

var LR_line[N];
// Linear regression line in buffer
for(x=0;x<N;x++)
{ LR_line[x]=a+b*x;
plot("NEW_linreg", LR_line[x],MAIN, RED);
}




}


Setting LR_line as vars generate an error, thus I changed to var.
Posted By: MatPed

Re: Linear Regression - 02/15/17 15:59

yes,
it does not work in that way. Fill the myClose with some sample data and than check the math. When the calculation will be ok will fix the first part.

delete the
StartDate= 20060101;
EndDate = 20060601;

BarPeriod = 15;

just plain c
Posted By: Andrea66

Re: Linear Regression - 02/15/17 16:57

I tried with the following code without success, sorry I'm a newbie:

#define N 10 // Number of bars

function run()
{

var myClose[10] = { 1,3,9,4,12,6,5,10,15,5};
var LR_line[10];

// variables
var a,b,c,sumy=0.0,sumx=0.0,sumxy=0.0,sumx2=0.0,h=0.0,l=0.0;
int x,i;
int barsToCount=50;


for( i=0; i<N; i++)
{
sumy+=myClose[i];
sumxy+=myClose[i]*i;
sumx+=i;
sumx2+=i*i;
}

c=sumx2*N-sumx*sumx;

// Line equation
b=(sumxy*barsToCount-sumx*sumy)/c;
a=(sumy-sumx*b)/N;

for(x=0;x<N;x++)
{ LR_line[x]=a+b*x;
plot("NEW_linreg", LR_line[x],MAIN, RED);
}




}

The calculation should be correct; the issue is related how to plot the straight line in a time chart.
Posted By: Andrea66

Re: Linear Regression - 02/17/17 20:24

This is another example from cAlgo :

using System;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
[Indicator(IsOverlay = true, AccessRights = AccessRights.None)]
public class LinearRegressionChannel : Indicator
{
[Parameter(DefaultValue = 200)]
public int Bars { get; set; }

[Parameter(DefaultValue = "Yellow")]
public string Color { get; set; }

[Parameter(DefaultValue = 1.0)]
public double LineThickness { get; set; }

[Parameter("Center", DefaultValue = true)]
public bool ShowCenter { get; set; }

[Parameter("Channel", DefaultValue = true)]
public bool ShowChannel { get; set; }

[Parameter("Standard deviation", DefaultValue = true)]
public bool ShowDeviantion { get; set; }


private Colors color;

protected override void Initialize()
{
// Parse color from string, e.g. "Yellow", "Green", "Red". string must start with large letter, "Red" is valid, "red" - not.
if (!Enum.TryParse(Color, out color))
color = Colors.Yellow;
}

public override void Calculate(int index)
{
if (IsLastBar)
LinearRegression(MarketSeries.Close);
}

private void LinearRegression(DataSeries series)
{
// Linear regresion

double sum_x = 0, sum_x2 = 0, sum_y = 0, sum_xy = 0;

int start = series.Count - Bars;
int end = series.Count - 1;

for (int i = start; i <= end; i++)
{
sum_x += 1.0 * i;
sum_x2 += 1.0 * i * i;
sum_y += series[i];
sum_xy += series[i] * i;
}

double a = (Bars * sum_xy - sum_x * sum_y) / (Bars * sum_x2 - sum_x * sum_x);
double b = (sum_y - a * sum_x) / Bars;


// Calculate maximum and standard devaitions

double maxDeviation = 0;
double sumDevation = 0;

for (int i = start; i <= end; i++)
{
double price = a * i + b;
maxDeviation = Math.Max(Math.Abs(series[i] - price), maxDeviation);
sumDevation += Math.Pow(series[i] - price, 2.0);
}

double stdDeviation = Math.Sqrt(sumDevation / Bars);

// draw in future
end += 20;

double pr1 = a * start + b;
double pr2 = a * end + b;

if (ShowCenter)
{
ChartObjects.DrawLine("center", start, pr1, end, pr2, color, LineThickness, LineStyle.Lines);
}

if (ShowChannel)
{
ChartObjects.DrawLine("top", start, pr1 + maxDeviation, end, pr2 + maxDeviation, color, LineThickness, LineStyle.Solid);
ChartObjects.DrawLine("bottom", start, pr1 - maxDeviation, end, pr2 - maxDeviation, color, LineThickness, LineStyle.Solid);
}

if (ShowDeviantion)
{
ChartObjects.DrawLine("dev-top", start, pr1 + stdDeviation, end, pr2 + stdDeviation, color, LineThickness, LineStyle.DotsVeryRare);
ChartObjects.DrawLine("dev-bottom", start, pr1 - stdDeviation, end, pr2 - stdDeviation, color, LineThickness, LineStyle.DotsVeryRare);
}
}

}
}


thus the calculation should be fine but what about the plotting in Zorro?
Posted By: MatPed

Re: Linear Regression - 02/18/17 09:50

Ciao,
the calculation for getting the line equation look correct to me, but I am not an expert on how plotting with Zorro.
Sorry
© 2024 lite-C Forums