RegressionPolynomial

Download script
Author: Copyright � 2011, paladin80

Technical Logic Overview: RegressionPolynomial

This script is designed to provide a sophisticated moving average by applying advanced mathematical regressions to price data. Rather than simply calculating a standard average of past prices, it uses polynomial logic to "fit" a curve to the market's movement, allowing for a more nuanced representation of trends.

Core Methodology

The indicator functions by analyzing historical price points and identifying the underlying trajectory. Depending on the user's settings, it employs three distinct calculation tiers:

  • Linear Regression (Degree 1): This mode uses a combination of Simple Moving Averages (SMA) and Linear Weighted Moving Averages (LWMA). By blending these two specific types of averages, the script attempts to create a smoothed line that reacts more intelligently to price momentum than a standard average.
  • Quadratic Regression (Degree 2): This is a more complex calculation that incorporates a "Weighted" component. It looks at the relationship between the SMA, the LWMA, and a specially weighted data series. This allows the indicator to account for curvature in the price movement, making it potentially more responsive to accelerating or decelerating trends.
  • Polynomial Regression (Advanced): For higher degrees of calculation, the script performs full polynomial regression. It constructs a mathematical matrix to solve for the best-fitting curve based on a specific number of "degrees." This is essentially an attempt to model the price action as a complex geometric arc rather than a simple straight line.

Data Processing & Smoothing

The script includes several layers of refinement to ensure the final output is readable and useful for analysis:

  1. Price Selection: The user can choose which type of price data drives the calculation (e.g., Close, Open, High, Low, or various weighted "Median" and "Typical" prices). This allows the indicator to be tuned to different trading styles.
  2. Signal Smoothing: Once the initial regression value is calculated, the script passes that result through a secondary smoothing algorithm (XMA). This final layer removes "noise" from the calculation, ensuring the visual output remains stable while maintaining the integrity of the regression logic.
  3. Visual Presentation: The indicator is designed to appear as a "filling" cloud or band on the chart. This provides a visual area of focus where the price is expected to trend based on the mathematical curve generated by the script.

Summary for the User

In essence, this tool moves away from "laggy" averages. By using regression logic, it tries to predict the "path of least resistance" by fitting a mathematical curve to recent history. Whether it uses simple linear blending or complex polynomial matrices, the goal is to provide a smooth, aesthetically pleasing trend indicator that stays closer to the actual movement of the market than traditional moving averages.

5 Views
0 Downloads
0 Favorites
RegressionPolynomial
//+---------------------------------------------------------------------+
//|                                            RegressionPolynomial.mq5 |
//|                                     Copyright © 2012, Ivan Kornilov |
//|                                     excelf@gmail.com, skype: excelf |
//+---------------------------------------------------------------------+ 
//| Äëÿ ðàáîòû  èíäèêàòîðà  ñëåäóåò  ïîëîæèòü ôàéë SmoothAlgorithms.mqh |
//| â ïàïêó (äèðåêòîðèþ): êàòàëîã_äàííûõ_òåðìèíàëà\\MQL5\Include        |
//+---------------------------------------------------------------------+
#property copyright "Copyright © 2011, paladin80"
#property link "forevex@mail.ru"
//--- íîìåð âåðñèè èíäèêàòîðà
#property version   "1.02"
//--- îòðèñîâêà èíäèêàòîðà â ãëàâíîì îêíå
#property indicator_chart_window 
//--- äëÿ ðàñ÷¸òà è îòðèñîâêè èíäèêàòîðà èñïîëüçîâàíî äâà áóôåðà
#property indicator_buffers 2
//--- èñïîëüçîâàíî îäíî ãðàôè÷åñêîå ïîñòðîåíèå
#property indicator_plots   1
//+----------------------------------------------+
//|  Ïàðàìåòðû îòðèñîâêè èíäèêàòîðà 1            |
//+----------------------------------------------+
//--- îòðèñîâêà èíäèêàòîðà â âèäå öâåòíîãî îáëàêà
#property indicator_type1   DRAW_FILLING
//--- â êà÷åñòâå öâåòîâ èíäèêàòîðà èñïîëüçîâàíû
#property indicator_color1  clrAquamarine,clrViolet
//--- îòîáðàæåíèå ìåòêè èíäèêàòîðà
#property indicator_label1  "RegressionPolynomial"
//+-----------------------------------+
//|  Îïèñàíèå êëàññîâ óñðåäíåíèé      |
//+-----------------------------------+
#include <SmoothAlgorithms.mqh> 
//+-----------------------------------+
//--- îáúÿâëåíèå ïåðåìåííûõ êëàññà CXMA èç ôàéëà SmoothAlgorithms.mqh
CXMA XMA1;
//+-----------------------------------+
//|  îáúÿâëåíèå ïåðå÷èñëåíèé          |
//+-----------------------------------+
/*enum Smooth_Method - ïåðå÷èñëåíèå îáúÿâëåíî â ôàéëå SmoothAlgorithms.mqh
  {
   MODE_SMA_,  //SMA
   MODE_EMA_,  //EMA
   MODE_SMMA_, //SMMA
   MODE_LWMA_, //LWMA
   MODE_JJMA,  //JJMA
   MODE_JurX,  //JurX
   MODE_ParMA, //ParMA
   MODE_T3,    //T3
   MODE_VIDYA, //VIDYA
   MODE_AMA,   //AMA
  }; */
//+----------------------------------------------+
//|  îáúÿâëåíèå ïåðå÷èñëåíèé                     |
//+----------------------------------------------+
enum Applied_price_ //Òèï êîíñòàíòû
  {
   PRICE_CLOSE_ = 1,     //Close
   PRICE_OPEN_,          //Open
   PRICE_HIGH_,          //High
   PRICE_LOW_,           //Low
   PRICE_MEDIAN_,        //Median Price (HL/2)
   PRICE_TYPICAL_,       //Typical Price (HLC/3)
   PRICE_WEIGHTED_,      //Weighted Close (HLCC/4)
   PRICE_SIMPL_,         //Simple Price (OC/2)
   PRICE_QUARTER_,       //Quarted Price (HLOC/4) 
   PRICE_TRENDFOLLOW0_,  //TrendFollow_1 Price 
   PRICE_TRENDFOLLOW1_,  //TrendFollow_2 Price
   PRICE_DEMARK_         //Demark Price
  };
//+-----------------------------------+
//| Âõîäíûå ïàðàìåòðû èíäèêàòîðà      |
//+-----------------------------------+
input uint period=55;                     // Ïåðèîä ìóâèíãà
input Smooth_Method XMA_Method=MODE_SMA_; // Ìåòîä óñðåäíåíèÿ ñèãíàëüíîé ëèíèè
input uint XLength=8;                     // Ãëóáèíà ñãëàæèâàíèÿ ñèãíàëüíîé ëèíèè                   
input int XPhase=15;                      // Ïàðàìåòð ñãëàæèâàíèÿ ñèãíàëüíîé ëèíèè
//--- äëÿ JJMA èçìåíÿþùèéñÿ â ïðåäåëàõ -100 ... +100, âëèÿåò íà êà÷åñòâî ïåðåõîäíîãî ïðîöåññà;
//--- Äëÿ VIDIA ýòî ïåðèîä CMO, äëÿ AMA ýòî ïåðèîä ìåäëåííîé ñêîëüçÿùåé
input Applied_price_ IPC=PRICE_TYPICAL;   // Öåíîâàÿ êîíñòàíòà
input uint degree=1;                      // Àëãîðèòì ðàñ÷¸òà
input int Shift=0;                        // Ñäâèã èíäèêàòîðà ïî ãîðèçîíòàëè â áàðàõ
input int PriceShift=0;                   // Ñäâèã èíäèêàòîðà ïî âåðòèêàëè â ïóíêòàõ
//+-----------------------------------+
//--- îáúÿâëåíèå äèíàìè÷åñêèõ ìàññèâîâ, êîòîðûå áóäóò â äàëüíåéøåì èñïîëüçîâàíû â êà÷åñòâå èíäèêàòîðíûõ áóôåðîâ
double UpBuffer[],DnBuffer[];
//--- îáúÿâëåíèå ïåðåìåííîé çíà÷åíèÿ âåðòèêàëüíîãî ñäâèãà ìóâèíãà
double dPriceShift;
//--- îáúÿâëåíèå öåëî÷èñëåííûõ ïåðåìåííûõ íà÷àëà îòñ÷¸òà äàííûõ
int min_rates_total,min_rates_;
//+------------------------------------------------------------------+   
//| RegressionPolynomial indicator initialization function           | 
//+------------------------------------------------------------------+ 
void OnInit()
  {
//--- èíèöèàëèçàöèÿ ïåðåìåííûõ íà÷àëà îòñ÷¸òà äàííûõ
   min_rates_=int(period);
   min_rates_total=min_rates_+GetStartBars(XMA_Method,XLength,XPhase);
//--- óñòàíîâêà àëåðòîâ íà íåäîïóñòèìûå çíà÷åíèÿ âíåøíèõ ïåðåìåííûõ
   XMA1.XMALengthCheck("XLength",XLength);
   XMA1.XMAPhaseCheck("XPhase",XPhase,XMA_Method);
//--- èíèöèàëèçàöèÿ ñäâèãà ïî âåðòèêàëè
   dPriceShift=_Point*PriceShift;
//--- ïðåâðàùåíèå äèíàìè÷åñêîãî ìàññèâà â èíäèêàòîðíûé áóôåð
   SetIndexBuffer(0,UpBuffer,INDICATOR_DATA);
//--- ïðåâðàùåíèå äèíàìè÷åñêîãî ìàññèâà â èíäèêàòîðíûé áóôåð
   SetIndexBuffer(1,DnBuffer,INDICATOR_DATA);
//--- îñóùåñòâëåíèå ñäâèãà íà÷àëà îòñ÷¸òà îòðèñîâêè èíäèêàòîðà
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,min_rates_total);
//--- óñòàíîâêà çíà÷åíèé èíäèêàòîðà, êîòîðûå íå áóäóò âèäèìû íà ãðàôèêå
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
//--- èíèöèàëèçàöèè ïåðåìåííîé äëÿ êîðîòêîãî èìåíè èíäèêàòîðà
   string shortname;
   string Smooth1=XMA1.GetString_MA_Method(XMA_Method);
   StringConcatenate(shortname,"RegressionPolynomial(",XLength,", ",Smooth1,")");
//--- ñîçäàíèå èìåíè äëÿ îòîáðàæåíèÿ â îòäåëüíîì ïîäîêíå è âî âñïëûâàþùåé ïîäñêàçêå
   IndicatorSetString(INDICATOR_SHORTNAME,shortname);
//--- îïðåäåëåíèå òî÷íîñòè îòîáðàæåíèÿ çíà÷åíèé èíäèêàòîðà
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//--- çàâåðøåíèå èíèöèàëèçàöèè
  }
//+------------------------------------------------------------------+ 
//| RegressionPolynomial iteration function                          | 
//+------------------------------------------------------------------+ 
int OnCalculate(const int rates_total,    // êîëè÷åñòâî èñòîðèè â áàðàõ íà òåêóùåì òèêå
                const int prev_calculated,// êîëè÷åñòâî èñòîðèè â áàðàõ íà ïðåäûäóùåì òèêå
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//--- ïðîâåðêà êîëè÷åñòâà áàðîâ íà äîñòàòî÷íîñòü äëÿ ðàñ÷¸òà
   if(rates_total<min_rates_total) return(0);
//--- îáúÿâëåíèå ïåðåìåííûõ ñ ïëàâàþùåé òî÷êîé  
   double price,sma,lwma;
//--- îáúÿâëåíèå öåëî÷èñëåííûõ ïåðåìåííûõ è ïîëó÷åíèå óæå ïîñ÷èòàííûõ áàðîâ
   int first,bar;
   static CXMA XMA2,XMA3;
//--- ðàñ÷¸ò ñòàðòîâîãî íîìåðà first äëÿ öèêëà ïåðåñ÷¸òà áàðîâ
   if(prev_calculated>rates_total || prev_calculated<=0) // ïðîâåðêà íà ïåðâûé ñòàðò ðàñ÷¸òà èíäèêàòîðà
     {
      if(degree!=1 && degree!=2) first=min_rates_; // ñòàðòîâûé íîìåð äëÿ ðàñ÷¸òà âñåõ áàðîâ
      else first=0;
      sma=XMA2.XMASeries(0,prev_calculated,rates_total,MODE_SMA_,0,period,0,0,false);
      lwma=XMA3.XMASeries(0,prev_calculated,rates_total,MODE_LWMA_,0,period,0,0,false);
     }
   else first=prev_calculated-1; // ñòàðòîâûé íîìåð äëÿ ðàñ÷¸òà íîâûõ áàðîâ
//--- îñíîâíîé öèêë ðàñ÷¸òà èíäèêàòîðà
   for(bar=first; bar<rates_total && !IsStopped(); bar++)
     {
      if(degree==1)
        {
         price=PriceSeries(IPC,bar,open,low,high,close);
         sma=XMA2.XMASeries(0,prev_calculated,rates_total,MODE_SMA_,0,period,price,bar,false);
         lwma=XMA3.XMASeries(0,prev_calculated,rates_total,MODE_LWMA_,0,period,price,bar,false);
         UpBuffer[bar]=regression_LRMA(sma,lwma);
        }
      else if(degree==2)
        {
         price=PriceSeries(IPC,bar,open,low,high,close);
         sma=XMA2.XMASeries(0,prev_calculated,rates_total,MODE_SMA_,0,period,price,bar,false);
         lwma=XMA3.XMASeries(0,prev_calculated,rates_total,MODE_LWMA_,0,period,price,bar,false);
         if(bar<min_rates_) continue;
         UpBuffer[bar]=regression_QRMA(sma,lwma,period,bar,IPC,open,low,high,close);
        }
      else UpBuffer[bar]=regression_regressionPolynomial(bar,period,degree,IPC,open,low,high,close);

      DnBuffer[bar]=XMA1.XMASeries(min_rates_,prev_calculated,rates_total,XMA_Method,XPhase,XLength,UpBuffer[bar],bar,false)+dPriceShift;
      UpBuffer[bar]+=dPriceShift;
     }
//---     
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| regression_LRMA()                                                |
//+------------------------------------------------------------------+
double regression_LRMA(double Sma,double Lwma) {return(3*Sma-2*Lwma);}
//+------------------------------------------------------------------+
//| regression_QRMA()                                                |
//+------------------------------------------------------------------+
double regression_QRMA(double Sma,
                       double Lwma,
                       int len,
                       int shift,int price,
                       const double &Open[],
                       const double &Low[],
                       const double &High[],
                       const double &Close[])
  {
//---
   double qwma=ma_qwma(len,shift,price,Open,Low,High,Close);
   double value=3.0*Sma+qwma*(10-15/(len+2))-Lwma*(12-15/(len+2));
//---
   return(value);
  }
//+------------------------------------------------------------------+
//| ma_qwma()                                                        |
//+------------------------------------------------------------------+
double ma_qwma(int len,
               int shift,
               int price,
               const double &Open[],
               const double &Low[],
               const double &High[],
               const double &Close[])
  {
//---
   double sum=0;
   int j,i;
   for(j=shift,i=1; j>shift-len; j--,i++) sum+=PriceSeries(price,j,Open,Low,High,Close)*MathPow(len-i+1,2);
   double value=6.0/(len *(len+1) *(2*len+1));
//---
   return(value*sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double regression_regressionPolynomial(int shift,int len,
                                       int fdegree,int price,
                                       const double &Open[],
                                       const double &Low[],const double &High[],
                                       const double &Close[])
  {
//---
   double a[10][10];
   double b[10];
   double x[10];
   double sx[20];
   int n=0;
   int i;
   int k;
   double t;
   int degree1;
   ArrayInitialize(a,0.0);
   ArrayInitialize(b,0.0);

   sx[1]=len+1;
   degree1=fdegree+1;
   for(i=1; i<=degree1*2-2; i++)
     {
      sx[i+1]=0;
      for(n=0; n<=len; n++) sx[i+1]+=MathPow(n,i);
     }
   for(i=1; i<=degree1; i++)
     {
      b[i]=0;
      for(n=0; n<=len; n++)
        {
         if(i==1) b[i]+=PriceSeries(price,shift-n,Open,Low,High,Close);
         else b[i]+=PriceSeries(price,shift-n,Open,Low,High,Close)*MathPow(n,i-1);
        }
     }

   for(int j=1; j<=degree1; j++)
     {
      for(i=1; i<=degree1; i++)
        {
         k=i+j-1;
         a[i][j]=sx[k];
        }
     }

   for(k=1; k<=degree1-1; k++)
     {
      int l=0;
      double mm=0;
      for(i=k; i<=degree1; i++)
        {
         if(MathAbs(a[i][k])>mm)
           {
            mm= MathAbs(a[i][k]);
            l = i;
           }
        }
      if(!l) return(0);

      if(l!=k)
        {
         for(int j=1; j<=degree1; j++)
           {
            t=a[k,j];
            a[k][j] = a[l][j];
            a[l][j] = t;
           }
         t=b[k];
         b[k] = b[l];
         b[l] = t;
        }
      double div=0;
      for(i=k+1; i<=degree1; i++)
        {
         div=a[i][k]/a[k][k];
         for(int j=1; j<=degree1; j++)
           {
            if(j==k) a[i][j]=0;
            else a[i][j]=a[i][j]-div*a[k][j];
           }
         b[i]=b[i]-div*b[k];
        }
     }

   x[degree1]=b[degree1]/a[degree1][degree1];
   for(i=fdegree; i>=1; i--)
     {
      t=0;
      for(int j=1; j<=degree1-i; j++)
        {
         t=t+a[i][i+j]*x[i+j];
         x[i]=(1/a[i][i])*(b[i]-t);
        }
     }

   double value=x[1];
   for(i=1; k<=fdegree; i++) value+=x[i+1]*MathPow(n,i);
//---
   return(value);
  }
//+------------------------------------------------------------------+

Comments