Linear regression forecast and intercept
Created at 29 Sep 2016, 18:28
SO
Linear regression forecast and intercept
29 Sep 2016, 18:28
Hi Does anyone have the exact code for the linear regression forecast and linear regression intercept indicators used in ctrader?
Replies
galafrin
30 Sep 2016, 16:42
RE:
lucian said:
using System; using cAlgo.API; using cAlgo.API.Internals; using cAlgo.API.Indicators; namespace cAlgo.Indicators { [Indicator(IsOverlay = true, AccessRights = AccessRights.None)] public class Linearregressionintercept : Indicator { [Parameter(DefaultValue = 30)] public int Period { get; set; } [Output("Main", Color = Colors.Yellow, PlotType = PlotType.Line)] public IndicatorDataSeries Result { get; set; } public override void Calculate(int index) { double sumx = 0, sumx2 = 0, sumy = 0, sumxy = 0; int start = (index + 1) - Period; int end = index; for (int i = start; i <= end; i++) { sumx += i; sumx2 += i * i; sumy += MarketSeries.Close[i]; sumxy += MarketSeries.Close[i] * i; } double m = (Period * sumxy - sumx * sumy) / (Period * sumx2 - sumx * sumx); double b = (sumy - m * sumx) / Period; Result[index] = start * m + b; } } }
Nice try Lucian , a correct solution would be this :
using System; using cAlgo.API; using cAlgo.API.Internals; using cAlgo.API.Indicators; namespace cAlgo.Indicators { [Indicator(IsOverlay = true, AccessRights = AccessRights.None)] public class Linearregressionintercept : Indicator { [Parameter(DefaultValue = 30)] public int Period { get; set; } [Output("LF", Color = Colors.Yellow, PlotType = PlotType.Line)] public IndicatorDataSeries LF { get; set; } [Output("LFI", Color = Colors.Orange, PlotType = PlotType.Line)] public IndicatorDataSeries LFI { get; set; } public override void Calculate(int index) { double sumx = 0, sumx2 = 0, sumy = 0, sumxy = 0; for (int i = 1; i <= Period; i++) { sumx += i; sumx2 += i * i; sumy += MarketSeries.Close [ index - Period + i ] ; sumxy += MarketSeries.Close[ index - Period + i ] * i ; } double m = (Period * sumxy - sumx * sumy) / (Period * sumx2 - sumx * sumx); double b = (sumy - m * sumx) / Period; LF[index] = Period * m + b; LFI[index] = b; } } }
Btw be aware that corresponding builtin indicators are flawed from period 283 upward. I alerted Spotware to no avail yet : TimeSeries MA , LRF , LRFI , LR slope.
@galafrin
... Deleted by UFO ...