preview
Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything?

Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything?

MetaTrader 5 — Indicators |
35 0
Hammad Dilber
Hammad Dilber

Contents


Introduction

Open any regime detection tool: the first input is the number of regimes. Nobody knows the right number, and the setting matters. A model forced to find two states will find two even if the market had one, or six. The transition matrix, the per regime statistics and the position sizing rule all sit on a number guessed before any data was read.

The Dirichlet process removes the guess. Each new observation either joins an existing cluster, with probability proportional to its size, or opens a brand new one. The number of clusters is therefore a random variable with a distribution, not a setting with a value, and it grows as data arrives at a rate known in closed form.

It is a different question from the one a change point detector answers: a detector says the series just broke, a mixture names what it broke into. It is also unusually testable. The prior's mean and variance are exact sums. The fitter has an invariant a correct implementation cannot break. The predictive density must integrate to one. Most of the code can be validated before any price data is used.

The library consists of nine header files with no external dependencies. It fits a truncated stick-breaking Gaussian mixture with full covariance using coordinate ascent rather than sampling. On top of that, it provides an indicator that scores each bar against a model fitted on strictly older data, and a market scan that compares the system to a null.

The indicator plots one continuous reading, the novelty of the current bar under the fitted mixture, colored by the regime that claims it. The panel names the regimes, reports the bound that chose them, and says whether the truncation is binding. No input anywhere asks for a cluster count.

That is narrower than it sounds. Removing this setting does not eliminate all ways to change the result. The truncation level, alpha, seeding, the empty component mass threshold, and the merge gates still affect the outcome. What changes is the kind of parameter, from an assertion about the data to a prior and a few thresholds the bound can be read against. Every one of them is listed with its value, for every run quoted in this article, in the configuration table in the verification section.

Here, four different quantities are referred to as a count, and they are kept distinct:

  • the prior table count in the restaurant process;
  • the number of active components above the mass threshold;
  • the number of regimes after sorting, matching and persistence filtering;
  • the planted count used by the generator.

A result about one is not a result about another.

DPM_Regime on a chart

Fig. 1. The indicator on EURUSD H1: the subwindow curve is each bar's predictive novelty, colored by the regime it belongs to, and the panel reports how many regimes the fit settled on


The prior that makes the count a random variable

A finite mixture puts a Dirichlet prior on a fixed length vector of weights. You choose the length, and that choice is the cluster count. The Dirichlet process replaces the vector with a prior over partitions of any size. Two equivalent constructions describe it, and the library implements both, because implementing both is what makes each testable.

The restaurant, and the two moments it has to reproduce

The Chinese restaurant process is the sequential description. Customers arrive one at a time into a restaurant with unlimited tables; the first sits anywhere. Customer i, counted from zero, joins an occupied table with probability proportional to how many people are already at it, or opens a new one with probability alpha divided by (alpha plus i). The concentration alpha does not fix the count, it sets how readily a new table opens.

The seating is written out literally rather than as the equivalent shortcut, so the test exercises the code the model uses:

//+------------------------------------------------------------------+
//| Seat n customers and return the number of occupied tables        |
//|                                                                  |
//|  Written as the metaphor is stated rather than as the equivalent |
//|  Bernoulli shortcut, so that the test exercises the seating code |
//|  the mixture model would actually use, not an algebraic identity |
//|  standing in for it.                                             |
//+------------------------------------------------------------------+
int CDPMCrp::Seat(CDPMRandom &rng, const int n, const double alpha, int &assign[])
  {
   if(ArraySize(assign) < n)
      ArrayResize(assign, n);
 
   Reserve(n);
   int tables = 0;
 
   for(int i = 0; i < n; i++)
     {
      double u = rng.Uniform() * ((double)i + alpha);
 
      if(u < alpha)                               // a new table opens
        {
         m_sizes[tables] = 1;
         assign[i] = tables;
         tables++;
         continue;
        }
 
      u -= alpha;                                 // otherwise walk the open tables
      int k = 0;
      while(k < tables - 1 && u >= (double)m_sizes[k])
        {
         u -= (double)m_sizes[k];
         k++;
        }
 
      m_sizes[k]++;
      assign[i] = k;
     }
 
   for(int k = tables; k < m_cap; k++)
      m_sizes[k] = 0;
 
   return(tables);
  }

The walk over open tables is the "proportional to size" part: a uniform draw scaled by total occupancy plus alpha, alpha peeled off the front for the new table, the rest spent walking the existing tables.

Whether customer i opens a table is a Bernoulli trial with probability alpha over (alpha plus i), and those trials are independent. The number of tables after n customers is therefore a sum of independent Bernoulli variables, and both of its moments are closed forms:

E[K_n] = sum over i from 0 to n-1 of alpha / (alpha + i)

Var[K_n] = sum over i from 0 to n-1 of p_i * (1 - p_i), with p_i = alpha / (alpha + i)

//+------------------------------------------------------------------+
//| Exact expected number of tables after n customers                |
//|                                                                  |
//|  Customer i opens a table with probability alpha/(alpha+i), and  |
//|  those events are independent, so the count is a sum of          |
//|  Bernoulli variables and both its moments are closed forms.      |
//+------------------------------------------------------------------+
double CDPMCrp::ExpectedTables(const int n, const double alpha)
  {
   double s = 0.0;
   for(int i = 0; i < n; i++)
      s += alpha / (alpha + (double)i);
   return(s);
  }
 
//+------------------------------------------------------------------+
//| Exact variance of the number of tables after n customers         |
//+------------------------------------------------------------------+
double CDPMCrp::VarianceTables(const int n, const double alpha)
  {
   double s = 0.0;
   for(int i = 0; i < n; i++)
     {
      double p = alpha / (alpha + (double)i);
      s += p * (1.0 - p);
     }
   return(s);
  }

The growth of the cluster count is loosely quoted as alpha times the logarithm of n, and the looseness matters, because the two candidate forms have different gaps to the exact sum. Against the bare alpha times log n the difference tends to minus alpha times digamma(alpha); against alpha times log(1 + n / alpha), the form that tracks the sum from small n, it tends to alpha times (digamma(alpha) minus log alpha). Neither gap shrinks, so neither form is the quantity to test against. The library computes the second and asserts its limit: at alpha equal to three the measured gap is -0.527469 against a limit of -0.527484.

Expected number of clusters under the Dirichlet process prior

Fig. 2. The prior's growth: solid lines the exact sum, dashed lines alpha times log(1 + n / alpha), dots the means of 3000 simulated restaurants per point

The dots are measured, not drawn: the seating code above, run 3000 times per cell. Because the exact variance is available too, the comparison is a z statistic rather than an eyeball, and across three sample sizes and three concentrations the worst absolute z was 1.85. Nothing in that test touches a price series or another library.

Breaking a stick instead of seating customers

The second construction draws the weights first. Take a stick of length one, draw v_1 from a Beta(1, alpha) and break off that fraction: the piece is the weight of cluster one. Draw v_2 the same way, break off that fraction of what remains, and repeat forever. The weights always sum to one and they decay, which is why a practical implementation can truncate after a finite number of sticks.

Stick breaking weights for two concentrations

Fig. 3. Fourteen sticks under two concentrations: at alpha equal to one the first four pieces are almost the whole stick, at alpha equal to five the same fourteen leave a visible remainder, and that remainder is what a truncation discards

That remainder is why the library reports whether the truncation binds instead of quietly capping the answer: a ceiling is only harmless while the last stick stays empty.

The two constructions describe one prior, so they can be made to meet. Break a stick, sample two hundred points from the measure, count the distinct sticks used, and the average over many replications has to match the restaurant's expected table count. It does: worst z 1.23 across two concentrations, with a worst mean discarded tail mass of 2.9e-26.


Fitting the mixture without a sampler

With the prior settled, the model is the usual mixture on top of it. Each component is a Gaussian with unknown mean and unknown full covariance under the conjugate Normal-Wishart prior, and the stick breaking weights assign observations to components. What remains is to turn data into a posterior.

The textbook route is a collapsed Gibbs sampler, and the library does not take it. An indicator refitting on a chart thread cannot afford convergence diagnostics, and a sampler that has not mixed gives an answer that looks exactly like one that has.

Coordinate ascent variational inference replaces sampling with optimization: a factorized approximation to the posterior, maximizing a lower bound on the model evidence one factor at a time. Every update is a closed form, the same data with the same seed gives the same answer on every call, and the bound can never fall between iterations. That last property is what turns a transcription error in the update equations into a single visible number.

The sticks, and what the truncation costs

Truncating at T components makes the final stick deterministic: v_T is set to one, so the weights sum exactly to one over the T components and there is no leftover to account for. Every stick before it gets a Beta posterior whose second parameter carries the mass of everything after it, which is what makes the construction order dependent. That is the whole of the stick half of the posterior update:

//+------------------------------------------------------------------+
//| One update of the stick breaking weights from the masses         |
//|                                                                  |
//|  The truncation fixes the last stick at one, so the weights sum  |
//|  exactly to one over the T components. Every stick before it     |
//|  gets a Beta posterior whose second parameter carries the mass   |
//|  of everything after it, which is what makes the order matter.   |
//+------------------------------------------------------------------+
void CDPMVariational::UpdateSticks(void)
  {
   int t = m_t;
 
   //--- the mass sitting behind each stick, accumulated in one backward pass
   double tail[];
   ArrayResize(tail, t);
   tail[t - 1] = 0.0;
   for(int k = t - 2; k >= 0; k--)
      tail[k] = tail[k + 1] + m_nk[k + 1];
 
   double acc = 0.0;
   for(int k = 0; k < t - 1; k++)
     {
      m_g1[k] = 1.0 + m_nk[k];
      m_g2[k] = m_cfg.alpha + tail[k];
 
      double dg = DPMDigamma(m_g1[k] + m_g2[k]);
      m_elnv[k]   = DPMDigamma(m_g1[k]) - dg;
      m_eln1mv[k] = DPMDigamma(m_g2[k]) - dg;
 
      //--- the accumulator is the log of what earlier sticks left behind,
      //--- which is the pressure that stops the model overspending on components
      m_elnpi[k] = m_elnv[k] + acc;
      acc += m_eln1mv[k];
     }
 
   m_g1[t - 1]     = 1.0;
   m_g2[t - 1]     = 0.0;
   m_elnv[t - 1]   = 0.0;
   m_eln1mv[t - 1] = 0.0;
   m_elnpi[t - 1]  = acc;
  }

The tail array is the running sum of the masses of later components, built backwards in one pass, and the two digamma differences are the expectations of log v and log (1 minus v) under the Beta posterior. The accumulator turns them into each stick's expected log weight, which carries the accumulated log of (1 minus v) for every stick before it: a penalty growing with the index, and the built-in pressure against overspending.

It is also why the index matters to the optimizer and not to the answer. Inside the fit it is load bearing: an earlier stick carries less of that penalty, so where a cluster lands changes the bound it can reach. Outside the fit it is arbitrary, two runs putting the same cluster at different indices, which is why anything leaving the fitter is sorted by mass first.

The responsibilities

With the components fixed, each observation is scored against all of them and the scores are normalized. The score is the expected log weight, plus half the expected log determinant of the precision, minus the expected quadratic form, and the expectation of that quadratic form picks up an extra term because the mean itself is uncertain:

//+------------------------------------------------------------------+
//| One update of the responsibilities                               |
//+------------------------------------------------------------------+
void CDPMVariational::UpdateResponsibilities(void)
  {
   int t = m_t, d = m_d, n = m_n;
 
   double lr[];
   ArrayResize(lr, t);
 
   double half = 0.5 * (double)d * MathLog(2.0 * M_PI);
 
   for(int i = 0; i < n; i++)
     {
      for(int k = 0; k < t; k++)
        {
         double quad = (double)d / m_beta[k]
                       + m_nu[k] * DPMQuadFormBlock(m_w, k * d * d, m_x, i * d,
                                                    m_mean, k * d, d);
 
         lr[k] = m_elnpi[k] + 0.5 * m_elndet[k] - half - 0.5 * quad;
        }
 
      double lse = DPMLogSumExp(lr, t);
      for(int k = 0; k < t; k++)
         m_r[i * t + k] = MathExp(lr[k] - lse);
     }
  }

The d / m_beta[k] term is that extra piece: with beta_k large the mean is well determined and it vanishes, with beta_k small the component is penalized for not knowing where it is. The log-sum-exp matters, because the raw scores routinely reach several hundred and a direct exponential would overflow long before the softmax did. This loop is also the hot spot, one quadratic form per observation per component, so it reads straight out of the flat blocks.

The bound, and the one class of error it rules out

Coordinate ascent alternates: update the components from the responsibilities, then the responsibilities from the components. Each step maximizes the same bound with respect to one factor, so the bound cannot decrease. That makes the whole fitting loop a checkable invariant, and it is what decides whether the update equations were transcribed correctly.

//+------------------------------------------------------------------+
//| Coordinate ascent from whatever responsibilities are in place    |
//+------------------------------------------------------------------+
bool CDPMVariational::Ascend(double &boundOut, const int iterCap)
  {
   double prev = -DBL_MAX;
   boundOut    = -DBL_MAX;
   m_converged = false;
   int sweeps  = 0;
   int budget  = (iterCap > 0 && iterCap < m_cfg.maxIter ? iterCap : m_cfg.maxIter);
 
   for(int it = 0; it < budget; it++)
     {
      if(!UpdatePosterior())
         return(false);
 
      //--- the bound is read between the two updates, where every term belongs
      //--- to one variational state, which is what keeps the sequence monotone
      double b = ComputeBound();
 
      UpdateResponsibilities();
      sweeps = it + 1;
 
      if(prev != -DBL_MAX)
        {
         double drop = prev - b;                  // positive means the bound fell
         if(drop > m_worstDrop)
            m_worstDrop = drop;
 
         if(MathAbs(b - prev) <= m_cfg.tol * MathMax(1.0, MathAbs(prev)))
           {
            m_converged = true;
            break;
           }
        }
 
      prev = b;
     }
 
   //--- settle the posterior onto the responsibilities the loop ended with,
   //--- so the bound returned and the state left behind describe the same q
   if(!UpdatePosterior())
      return(false);
 
   boundOut = ComputeBound();
   m_runIters += sweeps;
   return(true);
  }

Where the bound is read inside that loop is not a detail. Read it after the responsibility update, which looks harmless, and the sufficient statistics still held belong to the previous responsibilities while the entropy term comes from the new ones: the number is then the bound of no particular distribution. If you read the bound between the two updates, every term belongs to a single variational state. In that case, the worst relative drop across nine configurations is 2.35e-16 (rounding error).

What that settles is narrow. A monotone bound catches an update that does not maximize the factor it claims to, which is what a mistranscribed formula does. It is silent on whether a Gaussian mixture suits returns, whether the optimum is global, whether a bound and an update are wrong in the same direction, and whether the count means anything. Each needs its own test, and the rest of the article is those tests.


The move the standard algorithm is missing

Coordinate ascent on a mixture has a well-known weakness. Seed the fit with k-means using fourteen centers on data that really has three clusters, and k-means cuts each true cluster into pieces coordinate ascent cannot put back together: moving a single point between two heavily overlapping components lowers the bound even though the merged solution is higher. The algorithm can split, and it cannot merge.

The tempting conclusion is that the model simply prefers the finer answer, and measuring settles it. The same planted data at two truncation levels, every other setting fixed, gave -6500.17 at a ceiling of six and -6534.42 at a ceiling of fourteen. The fourteen component run reported four clusters and a worse bound than the six component run that reported three: the model did not prefer four, the optimizer failed to reach three.

The repair is a merge move: propose the closest pair of components as one, refit from there, and keep the result only if the bound actually rises.

//+------------------------------------------------------------------+
//| Offer the closest pairs of components as a single component      |
//|                                                                  |
//|  Coordinate ascent can split a cluster and then cannot undo it:  |
//|  moving a point between two overlapping components lowers the    |
//|  bound even though the merged solution is higher. The merge is   |
//|  proposed, refitted, and kept only if the bound actually rises.  |
//+------------------------------------------------------------------+
bool CDPMVariational::TryMerges(double &bound)
  {
   if(m_cfg.mergeTries <= 0)
      return(true);
 
   int t = m_t, n = m_n;
   int cand = (m_cfg.mergeCandidates < 1 ? 1 : m_cfg.mergeCandidates);
 
   double saveR[];
   ArrayResize(saveR, n * t);
 
   for(int accepted = 0; accepted < m_cfg.mergeTries; accepted++)
     {
      int    pa[], pb[];
      double pd[];
      ArrayResize(pa, cand);
      ArrayResize(pb, cand);
      ArrayResize(pd, cand);
      for(int c = 0; c < cand; c++)
        {
         pa[c] = -1;
         pb[c] = -1;
         pd[c] = DBL_MAX;
        }
 
      for(int a = 0; a < t; a++)                  // keep the closest few pairs
        {
         if(m_nk[a] < m_cfg.minCount)
            continue;
         for(int b = a + 1; b < t; b++)
           {
            if(m_nk[b] < m_cfg.minCount)
               continue;
 
            //--- a pair this far apart cannot merge profitably, and trying it
            //--- costs a full ascent to learn what the divergence already said
            double dv = PairDivergence(a, b);
            if(dv > m_cfg.mergeMaxKL)
               continue;
 
            for(int c = 0; c < cand; c++)
               if(dv < pd[c])
                 {
                  for(int s = cand - 1; s > c; s--)
                    {
                     pd[s] = pd[s - 1];
                     pa[s] = pa[s - 1];
                     pb[s] = pb[s - 1];
                    }
                  pd[c] = dv;
                  pa[c] = a;
                  pb[c] = b;
                  break;
                 }
           }
        }
 
      bool improved = false;
 
      for(int c = 0; c < cand && !improved; c++)
        {
         if(pa[c] < 0)
            break;
 
         ArrayCopy(saveR, m_r, 0, 0, n * t);
 
         int a = pa[c], b = pb[c];
         for(int i = 0; i < n; i++)               // pour b into a
           {
            m_r[i * t + a] += m_r[i * t + b];
            m_r[i * t + b]  = 0.0;
           }
 
         //--- a merge that is going to pay does so early, so the trial runs on
         //--- a short budget before it can earn a full ascent
         double merged;
         bool   ran = Ascend(merged, m_cfg.mergeProbeIter);
 
         if(ran && merged > bound - 1e-6 * MathMax(1.0, MathAbs(bound)))
            ran = Ascend(merged);                 // promising, so finish it
 
         if(ran && merged > bound + 1e-9 * MathMax(1.0, MathAbs(bound)))
           {
            bound    = merged;
            improved = true;
            m_runMerges++;
            break;
           }
 
         ArrayCopy(m_r, saveR, 0, 0, n * t);      // put the split back
         if(!UpdatePosterior())
            return(false);
        }
 
      if(!improved)
         break;
     }
 
   return(true);
  }

Three details decide whether this is usable, and two are heuristics rather than results. The first is the divergence gate: a pair far enough apart is unlikely enough to merge profitably that trying it is not worth a full ascent. On the planted data the pairs a bad seeding duplicated sat at 2.3 and 4.2, the closest genuinely different pair at 124.7, so a ceiling of thirty divides those cases cleanly. That is one geometry, not a theorem, which is why mergeMaxKL is an input.

The second is the short probe. The merges here that eventually paid were already close to the incumbent bound early, so the trial runs on a thirty sweep budget and only earns a full ascent if it looks promising; a merge whose gain appears only after deeper optimization would be missed. Gate and probe together keep the move affordable: the pinned three thousand bar export fits in about nine seconds.

The third is that the acceptance test is the bound and nothing else: a merge is accepted because the refitted solution scores higher, never because the components looked similar, and a rejected proposal restores the saved responsibilities.

The merge move against coordinate ascent alone

Fig. 4. One planted data set, six configurations run twice: plain coordinate ascent reports four clusters in two, and with the merge move all six report three

The count is what the move repairs, on this data set. Plain coordinate ascent reports four clusters in two of the six configurations; with the move all six report three, which is what was planted. The bound improves in every configuration at a ceiling of fourteen, by five to twenty seven nats, and the spread across the six halves from 56.6 nats to 30.6. That rests on one planted geometry and is no guarantee elsewhere: the move removes one failure, a cluster split by a bad seeding, and leaves every other route to a wrong count open.

What the move does not do is make the truncation level free. At a ceiling of six the fit reaches -6500.17; at fourteen the best it manages is -6525.75, twenty five nats short, on data whose answer is three clusters either way. A wider ceiling gives a rough surface more places to get stuck in, and a longer ascent can settle into a basin the merge move would otherwise have escaped.

These numbers require a caveat: changing T changes the model, not just the optimizer. T=6 and T=14 imply different priors and different variational families. Therefore the two values are lower bounds on different evidences, and their gap is not a model comparison. What makes it usable here is that both runs converge on the same three component solution, every later stick below the mass threshold, so the extra sticks add their prior terms and little else. The difference is the optimizer's, and that is all it is read as.

So the ceiling is not a free parameter. The library runs several seedings, keeps the best bound it saw, and prints it with whether the truncation binds, so two runs can be compared on the number the model is maximizing rather than on the count alone.


From a fit to something you can read on a chart

A posterior over components is not yet a chart. Four pieces stand between them: the features, a density that can score an unseen bar, an identity that survives a refit, and a way to handle a mixture with no notion of time.

What a regime is allowed to differ along

The feature builder works from closes alone and offers two or three axes: the bar's own log return, the log of the standard deviation of the last volWin returns, and optionally the recent drift measured in units of that same deviation.

//+------------------------------------------------------------------+
//| The three features for one bar, from closes alone                |
//|                                                                  |
//|  idx indexes the closes chronologically, and the row needs       |
//|  volWin returns behind it, so the first bar that has an answer   |
//|  is at index volWin. Returning false rather than a padded row    |
//|  keeps a warm up bar out of the fit entirely.                    |
//+------------------------------------------------------------------+
bool CDPMFeatures::BuildOne(const double &close[], const int n, const int idx, double &row[])
  {
   if(idx < m_volWin || idx >= n)
      return(false);
 
   if(ArraySize(row) < m_dim)
      ArrayResize(row, m_dim);
 
   double prev = close[idx - 1];
   double cur  = close[idx];
   if(prev <= 0.0 || cur <= 0.0)
      return(false);
 
   double ret = MathLog(cur / prev);
 
   double sum = 0.0, sum2 = 0.0;
   for(int k = 0; k < m_volWin; k++)
     {
      int    t  = idx - k;
      double p0 = close[t - 1];
      double p1 = close[t];
      if(p0 <= 0.0 || p1 <= 0.0)
         return(false);
      double r = MathLog(p1 / p0);
      sum  += r;
      sum2 += r * r;
     }
 
   double w    = (double)m_volWin;
   double mean = sum / w;
   double var  = (sum2 - w * mean * mean) / (w - 1.0);
   if(var < 0.0)
      var = 0.0;
 
   double sd = MathSqrt(var);
   if(sd < 1e-12)
      sd = 1e-12;                                 // a flat window, not an error
 
   row[0] = ret;
   row[1] = MathLog(sd);
   if(m_dim > 2)
      row[2] = mean / sd;
 
   return(true);
  }

A bar without a full window behind it is refused rather than padded, so a warm-up bar never enters the fit, and the standard deviation is floored rather than treated as an error, because a flat window is a market condition and not a bad input. The length of that window is a choice rather than a derived quantity, and it is measured rather than asserted: the market scan at the end of this article is rerun at ten, twenty and fifty bars, and the table there reports what moves with it.

Refusing bad input is a layer of its own, and the fragments in this article are the arithmetic rather than that layer. The fitter validates its configuration before allocating anything: dimension and truncation level, at least as many observations as components, nu_0 at least d plus two so the prior covariance exists, alpha, beta_0 and w0Scale strictly positive, and a data block as long as n times d promises. Each refusal returns false with its own message. The feature builder clamps instead where refusing would be unhelpful. Seven checks feed bad configurations in on purpose and assert each comes back refused.

The drift feature is optional for a measured reason. On a planted series where only volatility changes, adding it took the raw label switches from 165 to 370 and bought nothing: both feature sets recover the planted state on 100.00 percent of bars clear of a switch, and pooled over every bar the third axis moves accuracy from 97.73 to 97.77 percent. It is off by default, and the rest of this article uses two features.

The features are standardized on the fitting window and the constants stored. The prior centers every component at the origin with unit scale, so a bar scored later arrives on the same footing as the window the model was fitted on.

The predictive density, and the novelty it gives a bar

To score a new bar you need the posterior predictive, which means integrating the unknown mean and precision out of the Gaussian. The result is not a Gaussian. It is a Student-t:

//+------------------------------------------------------------------+
//| Log density of one component's Student-t predictive              |
//|                                                                  |
//|  Integrating the Wishart out of a Gaussian leaves a Student-t,   |
//|  not a Gaussian. The difference is the tail, and on returns the  |
//|  tail is the part that matters: a Gaussian predictive would call |
//|  every large move novel.                                         |
//+------------------------------------------------------------------+
double DPMLogStudentT(CDPMComponents &c, const int k, const double &x[], const int xoff)
  {
   int    d  = c.Dim();
   double dd = (double)d;
   double nu = c.dof[k];
 
   double q = DPMQuadFormBlock(c.prec, k * d * d, x, xoff, c.mean, k * d, d);
 
   return(DPMLogGamma(0.5 * (nu + dd))
          - DPMLogGamma(0.5 * nu)
          - 0.5 * dd * MathLog(nu * M_PI)
          + 0.5 * c.logDetPrec[k]
          - 0.5 * (nu + dd) * MathLog(1.0 + q / nu));
  }

The difference is the tail, and on returns the tail is the part that matters: a Gaussian predictive treats a four sigma move as essentially impossible and would call every large bar novel, while the Student-t has the degrees of freedom to accommodate it. The mixture's predictive is the weighted sum of these through a log-sum-exp, and the plotted reading is the negative of that log density: larger means stranger.

The three fields that fragment reads are where the conjugate model does its work, so it is worth saying what they hold. The degrees of freedom are nu_k minus d plus one, not nu_k. The precision is the posterior scale matrix times beta_k times those degrees of freedom over beta_k plus one, the factor that widens the predictive to pay for not knowing the mean. The log determinant carries that factor d times over. All three depend on the dimension.

Because the weights sum to exactly one, this is a genuine probability density, which numerical integration can check. In one dimension, over 30001 nodes spanning plus and minus thirty standard units, the integral came to 0.999999937. But d equal to one hides the dimension everywhere it appears above, so the same integral runs in two dimensions on a fit whose components are deliberately correlated and differently scaled: 410881 nodes, twelve active components, integral 0.999999439. That exercises the multivariate normalizer, the precision scaling and the determinant term at once.

Keeping a regime's name across a refit

A refit on a shifted window is a new fit, and its ordering carries no memory of the last one. Without something in between, a chart would renumber its regimes on every refit, which would look exactly like a regime change.

The tracker matches components between consecutive fits by the symmetric Kullback-Leibler divergence. In the symmetric form the log determinants cancel, which is why none appear in the implementation, and the cancellation makes the measure exactly symmetric and exactly zero against itself. Both are asserted: across every active pair of a real fit, worst self divergence 4.4e-16, worst asymmetry exactly zero.

Matching is greedy: the closest pair below a threshold is taken, both marked used, and the search repeats. A component unmatched on the new side is a birth, one on the old side a death. Fitting three planted clusters, tracking them, then fitting a four-cluster version of the same geometry gave exactly one birth and zero deaths.

The flicker, and what a filter costs

Here is the trap anyone building this will hit. A mixture fitted on bars treats them as independent, so nothing prevents the label alternating from one bar to the next. On the planted series, where seven regime changes were built in, the raw labels switched 165 times.

The smallest honest answer is a persistence filter: hold the current label until a rival has argued for it for a minimum number of consecutive bars.

//+------------------------------------------------------------------+
//| Hold a label until a rival has argued for it long enough         |
//|                                                                  |
//|  A mixture fitted on bars alone has no notion of time, so its    |
//|  labels can alternate from one bar to the next. This is the      |
//|  smallest honest answer: a switch costs minRun bars of lag, and  |
//|  the study measures what that lag buys.                          |
//+------------------------------------------------------------------+
int CDPMTracker::Stabilize(const int rawId)
  {
   if(m_stableId == DPM_NO_REGIME)                // nothing to defend yet
     {
      m_stableId = rawId;
      m_candId   = DPM_NO_REGIME;
      m_candRun  = 0;
      return(m_stableId);
     }
 
   if(rawId == m_stableId)
     {
      m_candId  = DPM_NO_REGIME;
      m_candRun = 0;
      return(m_stableId);
     }
 
   if(rawId == m_candId)
      m_candRun++;
   else
     {
      m_candId  = rawId;
      m_candRun = 1;
     }
 
   if(m_candRun >= m_minRun)
     {
      m_stableId = rawId;
      m_candId   = DPM_NO_REGIME;
      m_candRun  = 0;
     }
 
   return(m_stableId);
  }

The cost is exact. A switch that holds is adopted on the minRun-th consecutive bar, so it arrives minRun minus one bars late, asserted for minimum runs of two, three and four. A minimum run of one passes every label through unchanged, the nesting check that stops the filter doing something else quietly.

Label switches before and after the persistence filter

Fig. 5. Seven regime changes planted into a 2400 bar series, 2380 bars of it labeled: the raw labels switch 165 times with two features and 370 with three, and a three bar persistence requirement removes two thirds of the first and four fifths of the second

The filter is worth having, and it does not get near the truth. Fifty five switches against seven planted ones is an order of magnitude too many, and no amount of filtering fixes that, because the flicker is not noise on top of a regime signal: it is what an independence assumption produces on a time series. Temporal structure built into the model, rather than filtered on afterwards, is the real answer, and that is a different model.


Verification

The test suite runs in six levels, each one depending only on what the levels below it have already established, and it writes its report to a file, so the numbers quoted here come from a run rather than from memory. The first five levels are the five sections of the attached test script and need no price data at all; the sixth drives the finished indicator on a chart.

Three fitting regimes appear here and they are not interchangeable. The indicator is out of sample: it fits on closed bars and scores only bars after them, so no bar it scores contributed to the model that scored it. The planted tests below are deliberately in sample, fitting the whole synthetic window and then asking whether the components landed on the planted parameters, which is a question about recovery rather than prediction. The export and the scan fit a window pinned to a fixed bar for reproducibility; they are in sample too. Nothing below is an out of sample result unless it says so.

Every number quoted in this article comes from one of the five runs below, and each row is the complete setting list that run was made with, down to the seed and the pinned bar. Set them and the procedure repeats exactly. Whether the digits repeat is a separate question, and the settings do not decide it: the price history does.

The synthetic half has no such dependence. Levels one to five fit series the script builds from its own seed, so those numbers reproduce on any terminal. The export and the scan instead read whatever bars a trade server holds, and the bars behind every market number here came from one retail MetaTrader 5 demo feed, read through terminal build 6230, which is also where the m suffix on EURUSDm and the rest of the list comes from. The pinned timestamp 2026.09.01 00:00 is a reading on that server's clock: a datetime input and iBarShift both work in trade server time, which is neither UTC nor the local time of the machine, so the same literal selects a different bar on a server at a different offset. The history itself is not attached, and no two feeds agree bar for bar. Run these scripts against another terminal's data and expect the procedure to reproduce and the digits to move, because a different bar at the pinned time and different returns inside the window give different cluster counts, bounds, spell lengths and volatility spreads.

Run
What it produces here
Configuration
Test suite, DPM_Test.mq5
Levels one to five of the next table, the prior z values, the bound invariant, the predictive density integrals and the planted recovery
Seed 20260923, with fixed per section offsets in the script, so the facade fit runs at 20260923 + 44 and the indicator level at 20260923 + 66; tolerances 1e-12 on functions and 1e-10 on matrices; 3000 replications per cell; rejection at z 4.0; 200 sticks for the truncated twin; planted separation 5.0; integration step 0.002 over plus and minus 30; synthetic series 2400 bars, planted switch every 300, sigma 0.0010 quiet and 0.0040 busy; feature window 20 bars; two features; minRun 3; matching KL 8.0. The facade fit takes ceiling 16, alpha 1.0, four seedings and a mass threshold of 2 percent of the fitted rows
Split probe on a planted three cluster sample
The bound and KL numbers in the merge section
Seed 20260954; 1600 points in two dimensions drawn around (0,0), (12,0) and (0,12) with unit variance, so the planted count is three; alpha 1.0; ceilings 6 and 14 run as a pair; six seedings; mass threshold 32, which is 2 percent of 1600; the merge move offered 4 times on the arms that have it and 0 on the arms that do not; seeding modes k-means, random and both
Export and cross-check, DPM_Export_ForCrosscheck.mq5 with dpm_crosscheck.py
The agreement figures against numpy, the fitted bound, the sweep count and the nine second fit
EURUSDm H1, 3000 bars ending 2026.09.01 00:00, which is the window 2026.03.10 01:00 to 2026.09.01 00:00 and 2980 fitted rows; feature window 20 bars; two features; ceiling 12; alpha 1.0; four seedings; 200 sweeps allowed; stopping tolerance 1e-7; mass threshold 59.6, which is 2 percent of the rows; seed 20260923
Market scan, DPM_Scan_Market.mq5
Fig. 7, the regime counts, the spell lengths, the volatility spreads and both sign tests
Set one is EURUSDm, GBPUSDm, USDJPYm, AUDUSDm, USDCHFm and XAUUSDm on H1; set two is EURJPYm, EURGBPm, AUDJPYm, CADJPYm, CHFJPYm and BTCUSDm on H4, where EURJPYm had no H4 bar at the pinned time when this run was made and was skipped, leaving the five H4 symbols quoted below, so a broker that has since filled that history will fit six. 3000 bars per symbol ending 2026.09.01 00:00; feature window 20 bars; two features; ceiling 12; alpha 1.0; two seedings; mass threshold 59.6, which is 2 percent of the fitted rows; minRun 3; matching KL 8.0; five shuffles per symbol. Seed 20260923, which the script turns into a fit seed of 20260923 + 101s and a shuffle stream of 20260923 + 7919s + 13r, for symbol index s and replicate r
Indicator, DPM_Regime.mq5
Fig. 1 and level six of the next table
800 bars fitted, 400 displayed and scored, refit every 50 bars; feature window 20 bars; two features; ceiling 10; alpha 1.0; two seedings; 3 merge moves per seeding; mass threshold 2 percent of the fitted rows; minRun 3; matching KL 8.0; novelty cut at the 95th percentile; seed 20260923
Shared fitter defaults, DPMDefaultConfig
Everything above, wherever the row does not override it
nu_0 = d + 2, so 4 on two features; beta_0 1.0; W_0 scale 1.0; 200 sweeps allowed; stopping tolerance 1e-7 on the relative change in the bound; both seedings tried; 4 merge moves per seeding; the 2 closest pairs offered each time; no pair past symmetric KL 30; 30 probe sweeps before a merge is kept or refused
Level
What it checks
Checks
Sharpest measured result
1
Special functions and small symmetric matrices
36
Worst absolute error 5.68e-14 against published values
2
The Dirichlet process prior
10
Worst z 1.85 over nine cells; a 20 percent wrong alpha is rejected at z 22.06
3
The variational fitter
23
Bound drop 2.35e-16 relative; seven unusable configurations all refused
4
Predictive density and regime identity
24
Density integrates to 0.999999439 in two dimensions; filter lag exactly minRun minus one
5
Features and the facade
21
Planted state recovered on 100.00 percent of bars clear of a switch
6
The indicator's buffers and panel
12
The novelty cut sits at exactly the 5.00 percent asked for

A prior tested without any data

Level two is the one worth copying into other projects. It compares the simulated restaurant against exact closed forms, and because the variance is one of them the comparison is a proper z statistic rather than a tolerance someone chose. A second closed form is checked off the same runs: the expected number of tables holding exactly one customer, n times alpha over (alpha plus n minus one).

It also contains a negative control, without which the rest would be worth much less: a test accepting the correct concentration proves nothing unless it also rejects a wrong one. Scoring a correct run against a concentration twenty percent away gives z 22.06, against the correct one 0.67.

The last check ties the prior code to the special function code: the expected table count as a loop over n Bernoulli probabilities has to equal alpha times a difference of two digammas, and across fifteen cells the worst relative gap was 8.3e-15.

A planted answer, and an honest disagreement

Level five generates a price series that switches between two known volatilities every three hundred bars, fits the whole pipeline on it, and asks what came back. The two planted volatilities were 0.0010 and 0.0040; the nearest fitted components sat at 0.001053 and 0.003977.

The cluster count did not match. Two volatilities were planted and the model reported four components. The first instinct is to call that a failure, and the masses say otherwise.

What four components on a two regime series actually are

Fig. 6. Four components on a series with two planted volatilities: the one between them holds 126.9 bars, against the 140 bars whose twenty bar window straddles a planted switch

The component between the two planted values holds 126.9 bars. Seven switches were planted, and every feature row within twenty bars of one has a volatility window straddling both regimes: 140 bars that genuinely are neither state, and the model gave them their own component. The remaining extra component splits the quiet state into 0.00087 and 0.00105, a Gaussian mixture answering the skew of a log standard deviation over twenty samples.

So the test asserts what was actually planted: a component on each planted volatility, the intermediate mass a boundary effect rather than a state, and the labels mapping onto the planted state. Clear of a switch that mapping is correct 100.00 percent of the time; pooled over all bars it drops to 97.73 percent, exactly where the straddling window predicts. The count itself is reported, not asserted.

The same fit rebuilt in Python

The export script dumps a complete fit at seventeen significant figures: the standardized features, every responsibility, the posterior parameters, the component summary and a scored row per observation. A Python script rebuilds the posterior and the evidence bound from the model equations in numpy and compares, on a window pinned to a fixed bar so the agreement is reproducible.

The reference side is written from the model rather than translated from the MQL5, so agreement is evidence about the equations and not a shared typo. On a 2980 row EURUSD H1 fit, the responsibility masses, the Normal-Wishart parameters, the predictive weights and the degrees of freedom all agreed to 0.00e+00, the evidence bound to 6.88e-16 relative, and the predictive log density on every one of the 2980 rows to 8.92e-13.

The numpy rebuild is the part that counts as verification, because it implements the same equations and so has a right answer to agree with. The script also fits the same data with scikit-learn's own Dirichlet process mixture, which is a sanity check of a much weaker kind. Both settled on four components; scored under our own bound, ours came to -7932.38 and scikit-learn's to -7948.05, a gap of 0.197 percent.

The two are not solving the same problem: different priors, truncation conventions, initialization and stopping rules, local optima on both sides, and scoring their solution under our bound is not symmetrical. A small gap is therefore reassurance that neither has gone badly wrong rather than proof that either is right, a large one would have been a reason to look rather than a verdict, and which lands higher carries no information.

The interesting number is beside it: the adjusted Rand index between the two partitions is 0.0721. Two competent fitters, both reporting four regimes on the same 2980 bars, put almost none of the same bars together. The count agrees and the partition does not, which is a warning about the labels: a chart color is this fitter's partition of this window, not a property of the bar. Hold onto that, because the last section arrives there from a different direction.


What the market says, and what a shuffle says

Everything so far establishes that the library computes what it claims to compute. It says nothing about whether the answer is worth having on a price series, and that needs a control.

The control keeps every return the symbol actually produced and destroys only the order they arrived in. Shuffling leaves the marginal untouched, skew and fat tails included, and removes any clustering the returns carried. If a real series asks for more regimes, or longer lived ones, than a shuffle of itself, that difference came from the order. If it does not, whatever the model found came from the shape of the return distribution.

One thing the shuffle cannot remove: the model sees feature rows from a rolling twenty bar window, not returns, and consecutive rows share nineteen returns whether the series was shuffled or not. The shuffled features are therefore still strongly autocorrelated. That is the window and not the market, which is exactly why it belongs on both sides: the null carries the same manufactured persistence, so whatever survives is not that.

//+------------------------------------------------------------------+
//| Rebuild a price path from the same returns in a random order     |
//|                                                                  |
//|  The null keeps every return the symbol produced and destroys    |
//|  only the order they arrived in. Volatility clustering is the    |
//|  thing removed, so any regime structure that survives the        |
//|  shuffle came from the marginal distribution and not from time.  |
//+------------------------------------------------------------------+
bool ShuffleReturns(CDPMRandom &rng, const double &close[], const int n, double &out[])
  {
   //--- a log return needs two prices and a positive divisor, so the series is
   //--- validated here rather than assumed to have been validated by the caller
   if(n < 2)
      return(false);
   for(int i = 0; i < n; i++)
      if(!(close[i] > 0.0))
         return(false);
 
   int m = n - 1;
   double r[];
   ArrayResize(r, m);
   for(int i = 0; i < m; i++)
      r[i] = MathLog(close[i + 1] / close[i]);
 
   for(int i = m - 1; i > 0; i--)                 // Fisher-Yates
     {
      int    j = rng.Below(i + 1);
      double t = r[i];
      r[i] = r[j];
      r[j] = t;
     }
 
   ArrayResize(out, n);
   double logp = MathLog(close[0]);
   out[0] = close[0];
   for(int i = 0; i < m; i++)
     {
      logp += r[i];
      out[i + 1] = MathExp(logp);
     }
 
   return(true);
  }

The scan fits each symbol and five shuffles of its own returns on a pinned window, and compares three statistics: the number of regimes settled on, the mean length of a regime spell after the persistence filter, and the ratio of the busiest fitted regime's volatility to the quietest. The comparison is a per symbol sign test rather than a pooled statistic over bars, because rows inside one symbol share nineteen of their twenty returns.

Two limits belong in front of the numbers. Five shuffles per symbol is a coarse ruler: the smallest per symbol significance it can express is one in six, enough to show a statistic not separating from its null, not enough to resolve a small real effect. And the sign test removes the dependence between bars inside a symbol, not between symbols. Four H1 names contain the dollar, three H4 names the yen, and all move on the same macro news, so eleven symbols are fewer than eleven independent observations and every pooled p value below overstates the evidence.

Ties go against the real series. The regime count is a small integer, so matching a shuffle is common, and the code counts a shuffle as beaten only on a strict inequality. One in six is therefore an upper bound on the null probability there, which cuts the right way for a null result and the wrong way for a positive one.

Two sets were run. The first is the script's default list, EURUSD, GBPUSD, USDJPY, AUDUSD, USDCHF and XAUUSD on H1, three thousand bars each ending on the first of September 2026. The second points the same script at EURGBP, AUDJPY, CADJPY, CHFJPY and BTCUSD on H4. Names carry whatever suffix your broker uses, so check the list first; a symbol with no bar at the pinned time is skipped rather than fitted on a different window. The bars themselves are the ones held by the demo feed described in the verification table, and the pinned hour is a reading on that server's clock, so everything below describes one feed: the same scan against another broker's history lands on different bars and returns different digits.

Real symbols against shuffles of their own returns

Fig. 7. Eleven symbols against five shuffles of each: on the regime count the real series sits inside its shuffles, on the volatility spread to the right of them

The left panel is a null result, and it is the important one. Under the null a symbol tops all five of its own shuffles with probability one in six; on the regime count, one symbol out of eleven did. The mean count was 4.33 for real H1 series against 4.90 for their shuffles, and 4.80 against 4.40 on H4. Spell length is no better: two symbols out of eleven, real spells averaging 29.1 bars against 27.3 on H1, and 22.2 against 24.5 on H4.

Stated as what it is: this test detected no difference. A series whose returns were put in random order asks for just as many regimes and holds them just as long. Five shuffles cannot upgrade that to no difference existing, but what it does license is enough. The number of regimes this model reports is not evidence of regime structure, because a null with no ordering produces the same number. Two mechanisms explain why: a twenty bar window shared between consecutive rows autocorrelates the label by construction, and the rolling standard deviation of twenty fat tailed draws varies enough on its own to need several Gaussian components.

The right panel is different. On the ratio between the busiest and quietest fitted regime, the real series topped all five of its shuffles in five of six symbols on H1 and all five on H4. The H1 set is where the statistic was noticed, so its binomial p value of 6.6e-04 is not a clean test. The H4 set is better placed: different symbols, a different timeframe, the statistic fixed in advance, p equal to 1.3e-04. Both numbers are the nominal binomial values, and both are conditional on the symbols inside a set being independent observations, which the paragraph above already says they are not. Read them as a heuristic ranking of the two sets, not as significance levels.

Clustering the symbols by the currency they share puts a conservative number on the same result. The whole H1 set carries the dollar, five names directly and gold quoted in it, so that set is one cluster and one observation, worth no more than the one in six a single symbol is worth. The H4 set splits into three: the yen crosses AUDJPY, CADJPY and CHFJPY, then EURGBP, then BTCUSD. Every member of every cluster topped all five of its shuffles, so the cluster level sign test is (1/6)^3, p equal to 4.6e-03. That is the number worth quoting on the volatility spread, and it still assumes the three clusters do not move together.

One setting has to be tested rather than asserted: the twenty bar feature window. Both mechanisms above are made of it, it was picked as a round number, and either result could be an artifact of its length. The whole scan was therefore rerun at ten bars and at fifty, with every other setting, both symbol sets and the seed held fixed. The H4 side keeps the five symbols the published run compared, because a sixth has since become quotable at the pinned bar and adding it would change the set rather than the window.

Run
Regime count, real vs shuffled
Mean spell in bars, real vs shuffled
Volatility spread, real vs shuffled
Symbols topping all five shuffles: count / spell / spread
H1, window 10
5.00 vs 5.27
27.0 vs 38.3
4.47 vs 2.69
0/6   1/6   4/6
H1, window 20, the published run
4.33 vs 4.90
29.1 vs 27.3
3.28 vs 2.19
0/6   2/6   5/6
H1, window 50
5.00 vs 5.40
45.4 vs 28.9
2.80 vs 1.81
1/6   3/6   4/6
H4, window 10
5.20 vs 4.68
21.2 vs 90.1
3.71 vs 1.91
2/5   0/5   4/5
H4, window 20, the published run
4.80 vs 4.40
22.2 vs 24.5
2.88 vs 1.96
1/5   0/5   5/5
H4, window 50
6.00 vs 4.72
35.4 vs 26.1
3.25 vs 1.75
1/5   1/5   5/5

Both halves of the result survive the window. The regime count never separates from its own shuffles anywhere: the best any cell manages is two symbols of five, which a null produces about one time in five, and the mean real count sits below the shuffled mean in all three H1 cells and above it in all three H4 cells. The volatility spread separates everywhere instead, in four or five symbols of six on H1 and four or five of five on H4, with the mean real spread above the mean shuffled spread in all six cells.

What the window changes is the size of the readings, not the verdict they support. The shortest window gives the widest spreads on H1, 4.47 against 2.69, and the longest gives the highest real count on H4, 6.00 against 4.72. The spell length is the one genuinely window driven statistic: its sign flips from cell to cell, and at ten bars on H4 the shuffles average 90.1 bars against 21.2 for the real series. That belongs to the window and not to the market, which is why no claim here rests on how long a regime lasts. Its closest thing to a positive result is H1 at fifty bars, three symbols of six, which a null produces 6.2 percent of the time, in one cell out of eighteen.

One boundary belongs around all of it. Every number in this section was measured at a single DPM configuration: alpha 1.0, a ceiling of 12, two seedings, a mass threshold at 2 percent of the fitted rows, minRun 3, matching at KL 8.0, and the two features of the verification table. The feature window is the one setting that was varied, so these findings apply to the tested configuration and are shown robust to the length of the feature window, not to the concentration parameter, the truncation level, the component mass threshold or anything else the fitter takes. Those were held fixed rather than swept.

Important: the two halves of this result point in opposite directions and should not be collapsed into one sentence. How many regimes the model finds showed no separation from the return marginal on this feature set. How far apart those regimes are did separate, on both sets. Under the tested DPM configuration, neither the recovered regime count nor the regime spell length consistently separated from the shuffle-null. No trading strategy was evaluated, so these results do not establish whether either measure has predictive or trading value.

What survives belongs to the order of the returns, since the order is all the shuffle changed. Order is not the same thing as volatility clustering, and this test cannot separate them: trends, sessional volatility, jump clusters and structural shifts all die in the same shuffle, and any would widen the spread between fitted regimes. Volatility clustering is the most likely contributor on hourly FX, but what is measured is the whole of the ordering.

One symbol shows the size of it. USDJPY on H1 fitted a busiest regime 7.44 times more volatile than its quietest, while its five shuffles landed between 3.10 and 4.23. Whatever the order of returns carries, it is large, and it shows up in the separation between the states rather than in how many there are.


Conclusion

The library does what it set out to do. It fits a Dirichlet process mixture without being told how many regimes to look for, and every claim about its arithmetic is checked against something independent: closed form moments for the prior, a monotone bound for the fitter, numerical integrals in one and two dimensions for the predictive density, and a numpy rebuild of the whole fit. On the planted geometry that drove the merge move, all six configurations recover the planted three with the move in, against four of six without.

Those are statements about arithmetic, and arithmetic is the cheap half: correct prior moments, a correct bound and a correct density say nothing about whether the components a fit lands on correspond to anything a market does. That is what the last section is for, and it is the section that bounds what the library is good for.

The honest finding is narrower than the pitch usually is. Removing the cluster count as a setting does not turn it into a meaningful measurement: on hourly and four-hour series the recovered count did not separate from a shuffle of the same returns, and the partition behind it does not reproduce across two implementations that agree on the count. What did separate is the distance between the regimes, on ten of eleven symbols across two sets that share currencies and so are not eleven independent trials.

What was built, and what you can run:

  • A nine header library implementing the Chinese restaurant process, truncated stick breaking, a Normal-Wishart variational fitter with a merge move, a Student-t posterior predictive, and a regime tracker with a persistence filter.
  • A test suite of 126 checks in six levels, 114 of them in one attached script, including a prior tested entirely without data, a monotone bound invariant, a predictive density integrated in one and two dimensions, and a negative control that rejects a wrong concentration.
  • An export script and a Python cross-check that rebuilds the posterior and the bound from the model equations and agrees to 6.88e-16 on the bound.
  • A market scan that puts every symbol against five shuffles of its own returns, on a pinned window, with a per symbol sign test.
  • An indicator that plots the predictive novelty of each bar colored by its regime, scored entirely out of sample, with a panel that reports the cluster count, the bound, and whether the truncation is binding.
#
Filename
Type
Description
1
DPMRandom.mqh
Include
Seeded 64-bit generator with uniforms, normals, gamma and beta deviates
2
DPMMath.mqh
Include
Log-gamma, digamma, log-sum-exp and Cholesky operations on small symmetric matrices
3
DPMTypes.mqh
Include
The fit configuration and the sorted component summary a fit leaves
4
DPMCrp.mqh
Include
The Chinese restaurant process, stick breaking and the exact prior moments
5
DPMFeatures.mqh
Include
Return, log volatility and optional drift features, with window standardization
6
DPMVariational.mqh
Include
The coordinate ascent fitter, the evidence bound and the merge move
7
DPMPredict.mqh
Include
Student-t posterior predictive and the per bar novelty score
8
DPMTracker.mqh
Include
Regime identities that survive a refit, plus the persistence filter
9
DPMixture.mqh
Include
One class over the pipeline: features, fit, score, identity
10
DPM_Test.mq5
Script
Five sections and 114 checks, from the special functions up to the facade
11
DPM_Export_ForCrosscheck.mq5
Script
Dumps a complete fit at seventeen figures for the Python cross-check
12
DPM_Scan_Market.mq5
Script
Fits each symbol against shuffles of its own returns, pinned window
13
dpm_crosscheck.py
Python
Rebuilds the posterior, bound and predictive density in numpy and compares
14
DPM_Regime.mq5
Indicator
Out of sample novelty colored by regime, model panel on the main chart
15
MQL5.zip
Archive
All project files in their subfolders; unpack into the terminal data directory and each lands where it belongs
Attached files |
MQL5.zip (67.29 KB)
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4) Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4)
This article refines a multilayer market‑noise filter by sanitizing moving‑average inputs via Discrete Wavelet Transform and constructing a FastICA manifold on the denoised signals. We expand lag horizons (10–80 days), calibrate spectral clusters, and replace non-ONNX steps with surrogate models for MT5 deployment. The result is a reproducible MQL5 workflow that reduces forecasting error and integrates directly into an Expert Advisor.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module) Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module)
The article presents an implementation of the Adaptive Density Module (ADM), a key component of the EEMFlow framework, using MQL5. It examines the steps involved in building and combining the MDC and MDS submodules, as well as integrating ADM into the existing BAT trading model. Backtesting results on historical EURUSD data show robust growth in the account balance, controlled drawdowns, and a highly stable equity curve.