<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Market Meanness Index &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/market-meanness-index/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Sun, 04 Dec 2022 09:36:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://financial-hacker.com/wp-content/uploads/2017/07/cropped-mask-32x32.jpg</url>
	<title>Market Meanness Index &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Build Better Strategies! Part 2: Model-Based Systems</title>
		<link>https://financial-hacker.com/build-better-strategies-part-2-model-based-systems/</link>
					<comments>https://financial-hacker.com/build-better-strategies-part-2-model-based-systems/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Fri, 25 Dec 2015 12:34:08 +0000</pubDate>
				<category><![CDATA[Indicators]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[Arbitrage]]></category>
		<category><![CDATA[Bandpass filter]]></category>
		<category><![CDATA[Brexit]]></category>
		<category><![CDATA[CHF]]></category>
		<category><![CDATA[Currency strength]]></category>
		<category><![CDATA[Curve patterns]]></category>
		<category><![CDATA[Cycles]]></category>
		<category><![CDATA[Earnings]]></category>
		<category><![CDATA[Ehlers]]></category>
		<category><![CDATA[Fisher transformation]]></category>
		<category><![CDATA[Frechet algorithm]]></category>
		<category><![CDATA[Gap]]></category>
		<category><![CDATA[Heteroskedasticity]]></category>
		<category><![CDATA[Hurst exponent]]></category>
		<category><![CDATA[Market Meanness Index]]></category>
		<category><![CDATA[Mean Reversion]]></category>
		<category><![CDATA[Momentum]]></category>
		<category><![CDATA[Price shock]]></category>
		<category><![CDATA[Seasonality]]></category>
		<category><![CDATA[Spectral filter]]></category>
		<category><![CDATA[Support and resistance]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=318</guid>

					<description><![CDATA[Trading systems come in two flavors: model-based and data-mining. This article deals with model based strategies. Even when the basic algorithms are not complex, properly developing them has its difficulties and pitfalls (otherwise anyone would be doing it). A significant market inefficiency gives a system only a relatively small edge. Any little mistake can turn &#8230; <a href="https://financial-hacker.com/build-better-strategies-part-2-model-based-systems/" class="more-link">Continue reading<span class="screen-reader-text"> "Build Better Strategies! Part 2: Model-Based Systems"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Trading systems come in two flavors: <strong>model-based</strong> and <strong>data-mining</strong>. This article deals with model based strategies. Even when the basic algorithms are not complex, properly developing them has its difficulties and pitfalls (otherwise anyone would be doing it). A significant market inefficiency gives a system only a <strong>relatively small edge</strong>. Any little mistake can turn a winning strategy into a losing one. And you will not necessarily notice this in the backtest. <span id="more-318"></span></p>
<p>Developing a model-based strategy begins with the <strong>market inefficiency</strong> that you want to exploit. The inefficiency produces a <strong>price anomaly</strong> or <strong>price pattern</strong> that you can describe with a qualitative or quantitative <strong>model</strong>. Such a model predicts the current price <em><strong>y<sub>t</sub></strong></em> from the previous price <em><strong>y<sub>t-1</sub></strong></em> plus some function <em><strong>f</strong></em> of a limited number of previous prices plus some noise term <strong>ε</strong>:</p>
<p style="text-align: center;">[pmath size=16]y_t ~=~ y_{t-1} + f(y_{t-1},~&#8230;, ~y_{t-n}) + epsilon[/pmath]</p>
<p>The time distance between the prices <em><strong>y<sub>t</sub></strong></em> is the <strong>time frame</strong> of the model; the number <em><strong>n</strong></em> of prices used in the function <em><strong>f</strong></em> is the <strong>lookback period</strong> of the model. The higher the predictive <em><strong>f</strong></em> term in relation to the nonpredictive <strong>ε</strong> term, the better is the strategy. Some traders claim that their favorite method does not predict, but &#8216;reacts on the market&#8217; or achieves a positive return by some other means. On a certain trader forum you can even encounter a math professor who re-invented the grid trading system, and praised it as non-predictive and even able to trade a random walk curve. But systems that do not predict <em><strong>y<sub>t</sub></strong></em> in some way must rely on luck; they only can redistribute risk, for instance exchange a high risk of a small loss for a low risk of a high loss. The profit expectancy stays negative. As far as I know, the professor is still trying to sell his grid trader, still advertising it as non-predictive, and still regularly blowing his demo account with it. </p>
<p>Trading by throwing a coin loses the transaction costs. But trading by applying the wrong model &#8211; for instance, trend following to a mean reverting price series &#8211; can cause much higher losses. The average trader indeed loses more than by random trading (about 13 pips per trade according to FXCM statistics). So it&#8217;s not sufficient to have a model; you must also prove that it is valid for the market you trade, at the time you trade, and with the used time frame and lookback period.</p>
<p>Not all price anomalies can be exploited. Limiting stock prices to 1/16 fractions of a dollar is clearly an inefficiency, but it&#8217;s probably difficult to use it for prediction or make money from it. The working model-based strategies that I know, either from theory or because we&#8217;ve been contracted to code some of them, can be classified in several categories. The most frequent are:</p>
<h3>1. Trend </h3>
<p>Momentum in the price curve is probably the most significant and most exploited anomaly. No need to elaborate here, as trend following was the topic of a whole <a href="http://www.financial-hacker.com/trend-delusion-or-reality/">article series</a> on this blog. There are many methods of trend following, the classic being a <strong>moving average crossover</strong>. This &#8216;hello world&#8217; of strategies (<a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/">here</a> the scripts in R and in C) routinely fails, as it does not distinguish between real momentum and random peaks or valleys in the price curve.</p>
<p>The problem: momentum does not exist in all markets all the time. Any asset can have long non-trending periods. And contrary to popular belief this is not necessarily a &#8216;sidewards market&#8217;. A random walk curve can go up and down and still has zero momentum. Therefore, some good filter that detects the real market regime is essential for trend following systems. Here&#8217;s a minimal Zorro strategy that uses a lowpass filter for detecting trend reversal, and the <a href="http://www.financial-hacker.com/the-market-meanness-index/">MMI</a> indicator for determining when we&#8217;re entering trend regime:</p>
<pre class="prettyprint">function run()
{
  vars Price = series(price());
  vars Trend = series(LowPass(Price,500));
	
  vars MMI_Raw = series(MMI(Price,300));
  vars MMI_Smooth = series(LowPass(MMI_Raw,500));
	
  if(falling(MMI_Smooth)) {
    if(valley(Trend))
      reverseLong(1);
    else if(peak(Trend))
      reverseShort(1);
  }
}</pre>
<p>The profit curve of this strategy:</p>
<figure id="attachment_1224" aria-describedby="caption-attachment-1224" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/12/momentum.png"><img fetchpriority="high" decoding="async" class="wp-image-1224 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/12/momentum.png" alt="" width="879" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2015/12/momentum.png 879w, https://financial-hacker.com/wp-content/uploads/2015/12/momentum-300x110.png 300w, https://financial-hacker.com/wp-content/uploads/2015/12/momentum-768x280.png 768w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-1224" class="wp-caption-text">Momentum strategy profit curve</figcaption></figure>
<p>(For the sake of simplicity all strategy snippets on this page are barebone systems with no exit mechanism other than reversal, and no stops, trailing, parameter training, money management, or other gimmicks. Of course the backtests mean in no way that those are profitable systems. The P&amp;L curves are all from EUR/USD, an asset good for demonstrations since it seems to contain a little bit of every possible inefficiency). </p>
<h3><strong>2. Mean reversion</strong></h3>
<p>A mean reverting market believes in a &#8216;real value&#8217; or &#8216;fair price&#8217; of an asset. Traders buy when the actual price is cheaper than it ought to be in their opinion, and sell when it is more expensive. This causes the price curve to revert back to the mean more often than in a random walk. Random data are mean reverting 75% of the time (proof <a href="http://www.financial-hacker.com/the-market-meanness-index/">here</a>), so anything above 75% is caused by a market inefficiency. A model:</p>
<p>[pmath size=16]y_t ~=~ y_{t-1} ~-~ 1/{1+lambda}(y_{t-1}- hat{y}) ~+~ epsilon[/pmath]</p>
<p>[pmath size=16]y_t[/pmath] = price at bar <em><strong>t<br />
 </strong></em>[pmath size=16]hat{y}[/pmath] = fair price<br />
 [pmath size=16]lambda[/pmath] = half-life factor<br />
 [pmath size=16]epsilon[/pmath] = some random noise term</p>
<p>The higher the half-life factor, the weaker is the mean reversion. The half-life of mean reversion in price series ist normally in the range of  50-200 bars. You can calculate <em><strong>λ</strong></em> by linear regression between <em><strong>y<sub>t-1</sub></strong></em> and <em><strong>(y<sub>t-1</sub>-y<sub>t</sub>)</strong></em>. The price series need not be stationary for experiencing mean reversion, since the fair price is allowed to drift. It just must drift less as in a random walk. Mean reversion is usually exploited by removing the trend from the price curve and normalizing the result. This produces an oscillating signal that can trigger trades when it approaches a top or bottom. Here&#8217;s the script of a simple mean reversion system:</p>
<pre class="prettyprint">function run()
{
  vars Price = series(price());
  vars Filtered = series(HighPass(Price,30));
  vars Signal = series(FisherN(Filtered,500));
  var Threshold = 1.0;

  if(Hurst(Price,500) &lt; 0.5) { // do we have mean reversion?
    if(crossUnder(Signal,-Threshold))
      reverseLong(1); 
    else if(crossOver(Signal,Threshold))
      reverseShort(1);
  }
} </pre>
<p>The highpass filter dampens all cycles above 30 bars and thus removes the trend from the price curve. The result is normalized by the <strong>Fisher transformation </strong>which produces a Gaussian distribution of the data. This allows us to determine fixed thresholds at <strong>1</strong> and <strong>-1</strong> for separating the tails from the resulting bell curve. If the price enters a tail in any direction, a trade is triggered in anticipation that it will soon return into the bell&#8217;s belly. For detecting mean reverting regime, the script uses the <strong>Hurst Exponent</strong>. The exponent is 0.5 for a random walk. Above 0.5 begins momentum regime and below 0.5 mean reversion regime.</p>
<figure id="attachment_1226" aria-describedby="caption-attachment-1226" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/12/meanreversion.png"><img decoding="async" class="wp-image-1226 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/12/meanreversion.png" alt="" width="879" height="301" srcset="https://financial-hacker.com/wp-content/uploads/2015/12/meanreversion.png 879w, https://financial-hacker.com/wp-content/uploads/2015/12/meanreversion-300x103.png 300w, https://financial-hacker.com/wp-content/uploads/2015/12/meanreversion-768x263.png 768w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-1226" class="wp-caption-text">Mean reversion profit curve</figcaption></figure>
<h3>3. Statistical Arbitrage</h3>
<p>Strategies can exploit the similarity between two or more assets.  This allows to hedge the first asset by a reverse position in the second asset, and this way derive profit from mean reversion of their price difference:</p>
<p>[pmath size=16]y ~=~ h_1 y_1 &#8211; h_2 y_2[/pmath]</p>
<p>where <em><strong>y<sub>1</sub></strong></em> and <em><strong>y<sub>2</sub></strong></em> are the prices of the two assets and the multiplication factors <em><strong>h<sub>1</sub></strong></em> and <em><strong>h<sub>2</sub></strong></em> their <strong>hedge ratios</strong>. The hedge ratios are calculated in a way that the mean of the difference <em><strong>y</strong></em> is zero or a constant value. The simplest method for calculating the hedge ratios is linear regression between <em><strong>y<sub>1</sub></strong></em> and <em><strong>y<sub>2</sub></strong></em>. A mean reversion strategy as above can then be applied to <em><strong>y.</strong></em>  </p>
<p>The assets need not be of the same type; a typical arbitrage system can be based on the price difference between an index ETF and its major stock. When <em><strong>y</strong></em> is not <strong>stationary</strong> &#8211; meaning that its mean tends to wander off slowly &#8211; the hedge ratios must be adapted in real time for compensating. <a href="https://mktstk.wordpress.com/2015/08/18/the-kalman-filter-and-pairs-trading/" target="_blank" rel="noopener">Here</a> is a proposal using a <strong>Kalman Filter</strong> by a fellow blogger.</p>
<p>The simple arbitrage system from the <a href="http://manual.zorro-project.com/Lecture4.htm" target="_blank" rel="noopener">R tutorial</a>:<!--?prettify linenums=true?--></p>
<pre class="prettyprint">require(quantmod)

symbols &lt;- c("AAPL", "QQQ")
getSymbols(symbols)

#define training set
startT  &lt;- "2007-01-01"
endT    &lt;- "2009-01-01"
rangeT  &lt;- paste(startT,"::",endT,sep ="")
tAAPL   &lt;- AAPL[,6][rangeT]
tQQQ   &lt;- QQQ[,6][rangeT]
 
#compute price differences on in-sample data
pdtAAPL &lt;- diff(tAAPL)[-1]
pdtQQQ &lt;- diff(tQQQ)[-1]
 
#build the model
model  &lt;- lm(pdtAAPL ~ pdtQQQ - 1)
 
#extract the hedge ratio (h1 is assumed 1)
h2 &lt;- as.numeric(model$coefficients[1])

#spread price (in-sample)
spreadT &lt;- tAAPL - h2 * tQQQ
 
#compute statistics of the spread
meanT    &lt;- as.numeric(mean(spreadT,na.rm=TRUE))
sdT      &lt;- as.numeric(sd(spreadT,na.rm=TRUE))
upperThr &lt;- meanT + 1 * sdT
lowerThr &lt;- meanT - 1 * sdT
 
#run in-sample test
spreadL  &lt;- length(spreadT)
pricesB  &lt;- c(rep(NA,spreadL))
pricesS  &lt;- c(rep(NA,spreadL))
sp       &lt;- as.numeric(spreadT)
tradeQty &lt;- 100
totalP   &lt;- 0

for(i in 1:spreadL) {
     spTemp &lt;- sp[i]
     if(spTemp &lt; lowerThr) {
        if(totalP &lt;= 0){
           totalP     &lt;- totalP + tradeQty
           pricesB[i] &lt;- spTemp
        }
     } else if(spTemp &gt; upperThr) {
       if(totalP &gt;= 0){
          totalP &lt;- totalP - tradeQty
          pricesS[i] &lt;- spTemp
       }
    }
}
</pre>
<h3>4. Price constraints</h3>
<p>A price constraint is an artificial force that causes a constant price drift or establishes a price range, floor, or ceiling. The most famous example was the <a href="http://www.financial-hacker.com/build-better-strategies/" target="_blank" rel="noopener">EUR/CHF price cap</a> mentioned in the first part of this series. But even after removal of the cap, the EUR/CHF price has still a constraint, this time not enforced by the national bank, but by the current strong asymmetry in EUR and CHF buying power. An extreme example of a ranging price is the EUR/DKK pair (see below). All such constraints can be used in strategies to the trader&#8217;s advantage. </p>
<figure id="attachment_1983" aria-describedby="caption-attachment-1983" style="width: 979px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/12/PlotCurve_EURDKK.png"><img decoding="async" class="wp-image-1983 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/12/PlotCurve_EURDKK.png" width="979" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2015/12/PlotCurve_EURDKK.png 979w, https://financial-hacker.com/wp-content/uploads/2015/12/PlotCurve_EURDKK-300x98.png 300w, https://financial-hacker.com/wp-content/uploads/2015/12/PlotCurve_EURDKK-768x252.png 768w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-1983" class="wp-caption-text">EUR/DKK price range 2006-2016</figcaption></figure>
<h3>5. Cycles</h3>
<p>Non-seasonal cycles are caused by feedback from the price curve. When traders believe in a &#8216;fair price&#8217; of an asset, they often sell or buy a position when the price reaches a certain distance from that value, in hope of a reversal. Or they close winning positions when the favorite price movement begins to decelerate. Such effects can synchronize entries and exits among a large number of traders, and cause the price curve to oscillate with a period that is stable over several cycles. Often many such cycles are superposed on the curve, like this:</p>
<p>[pmath size=16]y_t ~=~ hat{y}  ~+~ sum{i}{}{a_i sin(2 pi t/C_i+D_i)} ~+~ epsilon[/pmath]</p>
<p>When you know the period <em><strong>C<sub>i</sub></strong></em> and the phase <em><strong>D<sub>i</sub></strong></em> of the dominant cycle, you can calculate the optimal trade entry and exit points as long as the cycle persists. Cycles in the price curve can be detected with spectral analysis functions &#8211; for instance, fast Fourier transformation (FFT) or simply a bank of narrow bandpass filters. Here is the frequency spectrum of the EUR/USD in October 2015:</p>
<figure id="attachment_1160" aria-describedby="caption-attachment-1160" style="width: 1599px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/11/spectrum.png"><img loading="lazy" decoding="async" class="wp-image-1160 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/11/spectrum.png" alt="" width="1599" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2015/11/spectrum.png 1599w, https://financial-hacker.com/wp-content/uploads/2015/11/spectrum-300x60.png 300w, https://financial-hacker.com/wp-content/uploads/2015/11/spectrum-1024x206.png 1024w, https://financial-hacker.com/wp-content/uploads/2015/11/spectrum-1200x241.png 1200w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-1160" class="wp-caption-text">EUR/USD spectrum, cycle length in bars</figcaption></figure>
<p>Exploiting cycles is a little more tricky than trend following or mean reversion. You need not only the cycle length of the dominant cycle of the spectrum, but also its phase (for triggering trades at the right moment) and its amplitude (for determining if there is a cycle worth trading at all). This is a barebone script:</p>
<pre class="prettyprint">function run()
{
  vars Price = series(price());
  var Phase = DominantPhase(Price,10);
  vars Signal = series(sin(Phase+PI/4));
  vars Dominant = series(BandPass(Price,rDominantPeriod,1));
  ExitTime = 10*rDominantPeriod;
  var Threshold = 1*PIP;
	
  if(Amplitude(Dominant,100) &gt; Threshold) {
    if(valley(Signal))
      reverseLong(1); 
    else if(peak(Signal))
      reverseShort(1);
  }
}</pre>
<p>The <strong>DominantPhase</strong> function determines both the phase and the cycle length of the dominant peak in the spectrum; the latter is stored in the <strong>rDominantPeriod</strong> variable. The phase is converted to a sine curve that is shifted ahead by <em><strong>π/4</strong></em>. With this trick we&#8217;ll get a sine curve that runs ahead of the price curve. Thus we do real price prediction here, only question is if the price will follow our prediction. This is determined by applying a bandpass filter centered at the dominant cycle to the price curve, and measuring its amplitude (the <em><strong>a<sub>i</sub></strong></em> in the formula). If the amplitude is above a threshold,  we conclude that we have a strong enough cycle. The script then enters long on a valley of the run-ahead sine curve, and short on a peak. Since cycles are shortlived, the duration of a trade is limited by <strong>ExitTime</strong> to a maximum of 10 cycles. </p>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/12/cycles2.png"><img loading="lazy" decoding="async" class="alignnone wp-image-1252 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/12/cycles2.png" alt="" width="879" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2015/12/cycles2.png 879w, https://financial-hacker.com/wp-content/uploads/2015/12/cycles2-300x110.png 300w, https://financial-hacker.com/wp-content/uploads/2015/12/cycles2-768x280.png 768w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a></p>
<p>We can see from the P&amp;L curve that there were long periods in 2012 and 2014 with no strong cycles in the EUR/USD price curve. </p>
<h3>6. Clusters</h3>
<p>The same effect that causes prices to oscillate can also let them cluster at certain levels. Extreme clustering can even produce &#8220;supply&#8221; and &#8220;demand&#8221; lines (also known as &#8220;<strong>support and resistance</strong>&#8220;), the favorite subjects in trading seminars. Expert seminar lecturers can draw support and resistance lines on any chart, no matter if it&#8217;s pork belly prices or last year&#8217;s baseball scores. However the mere existence of those lines remains debatable: There are few strategies that really identify and exploit them, and even less that really produce profits. Still, clusters in price curves are real and can be easily identified in a histogram similar to the cycles spectogram.</p>
<h3>7. Curve patterns</h3>
<p>They arise from repetitive behavior of traders. Traders not only produce, but also believe in many curve patterns; most &#8211; such as the famous &#8216;head and shoulders&#8217; pattern that is said to predict trend reversal &#8211; are myths (at least I have not found any statistical evidence of it, and heard of no other any research that ever confirmed the existence of predictive heads and shoulders in price curves). But some patterns, for instance &#8220;cups&#8221; or &#8220;half-cups&#8221;, really exist and can indeed precede an upwards or downwards movement. Curve patterns &#8211; not to be confused with <strong>candle patterns</strong> &#8211; can be exploited by pattern-detecting methods such as the <a href="http://zorro-project.com/manual/en/detect.htm" target="_blank" rel="noopener">Fréchet algorithm</a>. </p>
<p>A special variant of a curve pattern is the <strong>Breakout</strong> &#8211; a sudden momentum after a long sidewards movement. Is can be caused, for instance, by trader&#8217;s tendency to place their stop losses as a short distance below or above the current plateau. Triggering the first stops then accelerates the price movement until more and more stops are triggered. Such an effect can be exploited by a system that detects a sidewards period and then lies in wait for the first move in any direction.</p>
<h3>8. Seasonality</h3>
<p>&#8220;Season&#8221; does not necessarily mean a season of a year. Supply and demand can also follow monthly, weekly, or daily patterns that can be detected and exploited by strategies. For instance, the S&amp;P500 index is said to often move upwards in the first days of a month, or to show an upwards trend in the early morning hours before the main trading session of the day. Since seasonal effects are easy to exploit, they are often shortlived, weak, and therefore hard to detect by just eyeballing price curves. But they can be found by plotting a <a href="http://zorro-project.com/manual/en/profile.htm" target="_blank" rel="noopener">day, week, or month profile</a> of average price curve differences.</p>
<h3>9. Gaps</h3>
<p>When market participants contemplate whether to enter or close a position, they seem to come to rather similar conclusions when they have time to think it over at night or during the weekend. This can cause the price to start at a different level when the market opens again. Overnight or weekend price gaps are often more predictable than price changes during trading hours. And of course they can be exploited in a strategy. On the Zorro forum was recently a discussion about the &#8220;<a href="http://www.opserver.de/ubb7/ubbthreads.php?ubb=showflat&amp;Number=452807&amp;page=1" target="_blank" rel="noopener">One Night Stand System</a>&#8220;, a simple currency weekend-gap trader with mysterious profits.</p>
<h3>10. Autoregression and heteroskedasticity</h3>
<p>The latter is a fancy word for: &#8220;Prices jitter a lot and the jittering varies over time&#8221;. The ARIMA and GARCH models are the first models that you encounter in financial math. They assume that future returns or future volatility can be determined with a linear combination of past returns or past volatility. Those models are often considered purely theoretical and of no practical use. Not true: You can use them for predicting tomorrow&#8217;s price just as any other model. You can examine a <strong>correlogram</strong> &#8211; a statistics of the correlation of the current return with the returns of the previous bars &#8211; for finding out if an ARIMA model fits to a certain price series. Here are two excellent articles by fellow bloggers for using those models in trading strategies:  <a href="https://www.quantstart.com/articles/ARIMA-GARCH-Trading-Strategy-on-the-SP500-Stock-Market-Index-Using-R" target="_blank" rel="noopener">ARIMA+GARCH Trading Strategy on the S&amp;P500</a> and <a href="http://robotwealth.com/fitting-time-series-models-to-the-forex-market-are-arimagarch-predictions-profitable" target="_blank" rel="noopener">Are ARIMA/GARCH Predictions Profitable?</a></p>
<h3>11. Price shocks</h3>
<p>Price shocks often happen on Monday or Friday morning when companies or organizations publish good or bad news that affect the market. Even without knowing the news, a strategy can detect the first price reactions and quickly jump onto the bandwagon. This is especially easy when a large shock is shaking the markets. Here&#8217;s a simple Forex portfolio strategy that evaluates the relative strengths of currencies for detecting price shocks:</p>
<pre class="prettyprint">function run()
{
  BarPeriod = 60;
  ccyReset();
  string Name;
  while(Name = (loop(Assets)))
  {
    if(assetType(Name) != FOREX) 
      continue; // Currency pairs only
    asset(Name);
    vars Prices = series(priceClose());
    ccySet(ROC(Prices,1)); // store price change as strength
  }
  
// get currency pairs with highest and lowest strength difference
  string Best = ccyMax(), Worst = ccyMin();
  var Threshold = 1.0; // The shock level

  static char OldBest[8], OldWorst[8];	// static for keeping contents between runs
  if(*OldBest &amp;&amp; !strstr(Best,OldBest)) { // new strongest asset?
    asset(OldBest);
    exitLong();
    if(ccyStrength(Best) &gt; Threshold) {
      asset(Best);
      enterLong();
    }
  } 
  if(*OldWorst &amp;&amp; !strstr(Worst,OldWorst)) { // new weakest asset?
    asset(OldWorst);
    exitShort();
    if(ccyStrength(Worst) &lt; -Threshold) {
      asset(Worst);
      enterShort();
    }
  }

// store previous strongest and weakest asset names  
  strcpy(OldBest,Best);
  strcpy(OldWorst,Worst);
}</pre>
<p>The equity curve of the currency strength system (you&#8217;ll need Zorro 1.48 or above):</p>
<figure id="attachment_2004" aria-describedby="caption-attachment-2004" style="width: 879px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/12/CurrencyStrength_EURCHF.png"><img loading="lazy" decoding="async" class="wp-image-2004 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/12/CurrencyStrength_EURCHF.png" width="879" height="341" srcset="https://financial-hacker.com/wp-content/uploads/2015/12/CurrencyStrength_EURCHF.png 879w, https://financial-hacker.com/wp-content/uploads/2015/12/CurrencyStrength_EURCHF-300x116.png 300w, https://financial-hacker.com/wp-content/uploads/2015/12/CurrencyStrength_EURCHF-768x298.png 768w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-2004" class="wp-caption-text">Price shock exploiting system</figcaption></figure>
<p>The blue equity curve above reflects profits from small and large jumps of currency prices. You can clearly identify the <strong>Brexit</strong> and the <strong>CHF price cap shock</strong>. Of course such strategies would work even better if the news could be early detected and interpreted in some way. Some data services provide news events with a binary valuation, like &#8220;good&#8221; or &#8220;bad&#8221;. Especially of interest are <strong>earnings reports</strong>, as provided by data services such as Zacks or Xignite. Depending on which surprises the earnings report contains, stock prices and implied volatilities can rise or drop sharply at the report day, and generate quick profits.</p>
<p>For learning what can happen when news are used in more creative ways, I recommend the excellent <a href="http://www.amazon.de/gp/product/0099553279/ref=as_li_tl?ie=UTF8&amp;camp=1638&amp;creative=6742&amp;creativeASIN=0099553279&amp;linkCode=as2&amp;tag=worterbuchdes-21&quot;&gt;The Fear Index&lt;/a&gt;&lt;img src=&quot;http://ir-de.amazon-adsystem.com/e/ir?t=worterbuchdes-21&amp;l=as2&amp;o=3&amp;a=0099553279&quot; width=&quot;1&quot; height=&quot;1&quot; border=&quot;0&quot; alt=&quot;&quot; style=&quot;border:none !important; margin:0px !important;" target="_blank" rel="noopener">Fear Index</a> by Robert Harris &#8211; a mandatory book in any financial hacker&#8217;s library.</p>
<hr />
<p>This was the second part of the <a href="http://www.financial-hacker.com/build-better-strategies/">Build Better Strategies</a> series. The third part will deal with the process to develop a model-based strategy, from inital research up to building the user interface. In case someone wants to experiment with the code snippets posted here, I&#8217;ve added them to the 2015 scripts repository. They are no real strategies, though. The missing elements &#8211; parameter optimization, exit algorithms, money management etc. &#8211; will be the topic of the next part of the series.</p>
<p style="text-align: right;"><strong>⇒ <a href="http://www.financial-hacker.com/build-better-strategies-part-3-the-development-process/">Build Better Strategies &#8211; Part 3</a></strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/build-better-strategies-part-2-model-based-systems/feed/</wfw:commentRss>
			<slash:comments>46</slash:comments>
		
		
			</item>
		<item>
		<title>Boosting Strategies with MMI</title>
		<link>https://financial-hacker.com/boosting-systems-by-trade-filtering/</link>
					<comments>https://financial-hacker.com/boosting-systems-by-trade-filtering/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 28 Sep 2015 15:49:35 +0000</pubDate>
				<category><![CDATA[Indicators]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[System Evaluation]]></category>
		<category><![CDATA[Data mining bias]]></category>
		<category><![CDATA[Experiment]]></category>
		<category><![CDATA[Market Meanness Index]]></category>
		<category><![CDATA[White's reality check]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=320</guid>

					<description><![CDATA[We will now repeat our experiment with the 900 trend trading strategies, but this time with trades filtered by the Market Meanness Index. In our first experiment we found many profitable strategies, some even with high profit factors, but none of them passed White&#8217;s Reality Check. So they all would probably fail in real trading in spite of &#8230; <a href="https://financial-hacker.com/boosting-systems-by-trade-filtering/" class="more-link">Continue reading<span class="screen-reader-text"> "Boosting Strategies with MMI"</span></a>]]></description>
										<content:encoded><![CDATA[<p>We will now repeat our <a href="http://www.financial-hacker.com/trend-and-exploiting-it/">experiment</a> with the 900 trend trading strategies, but this time with trades filtered by the <strong><a href="http://www.financial-hacker.com/the-market-meanness-index/">Market Meanness Index</a></strong>. In our first experiment we found many profitable strategies, some even with high profit factors, but none of them passed <strong><a href="http://www.financial-hacker.com/whites-reality-check/">White&#8217;s Reality Check</a></strong>. So they all would probably fail in real trading in spite of their great results in the backtest. This time we hope that the MMI improves most systems by filtering out trades in non-trending market situations.<span id="more-320"></span></p>
<h3>900 systems experiment revisited</h3>
<p>I have been informed by readers that I committed two mistakes, or at least inaccuracies, in the previous experiment. First, I didn&#8217;t detrend the price data. Second, I used the equity curves instead of balance curves for determining the profit factor. I didn&#8217;t detrend the prices because the systems traded long/short in a symmetric way, and I supposed that this would eliminate any trend bias. But even if this was true back then, it is now not true anymore: filtering trades by MMI or other means can introduce asymmetry. Also, calculating the profit factor from the balance curve makes indeed more sense because you&#8217;re interested in the end profit of the trades, not in their interim behavior. Therefore and for the sake of comparable results I will now and in the future use detrended trade returns and balance curves for such experiments.</p>
<p>The original test, repeated with the modifications, produced a wider profit factor distribution due to eliminating intermediate returns. But the outcome of the experiment was the same. The statistic (including trade costs) did not change much, however the profit factor distribution (without trade costs) did. This is the new WRC histogram of the original 900 systems (best system vs. bootstrap-randomized returns of all systems):</p>
<figure id="attachment_438" aria-describedby="caption-attachment-438" style="width: 729px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/trendplain.png"><img loading="lazy" decoding="async" class="wp-image-438 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/trendplain.png" alt="" width="729" height="251" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/trendplain.png 729w, https://financial-hacker.com/wp-content/uploads/2015/09/trendplain-300x103.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a><figcaption id="caption-attachment-438" class="wp-caption-text">900 trend systems (no MMI)</figcaption></figure>
<p>Although the best system (black bar, a system using ALMA) is at the right side of the distribution, still 11% of random systems were better. The system does not pass the WRC at the required 95% confidence level. This turned out very different when filtering trades with the MMI.</p>
<h3>The MMI experiment</h3>
<p>This is our script <strong>TrendMMI.c</strong> for the new experiment:</p>
<pre><em><span style="color: #3366ff;">// helper function: remove systems that exceed the 4 months lookback period</span></em>
int checkLookBack(int Period) 
{
  if(Period &gt;= LookBack/TimeFrame) {
    StepNext = 0;	<em><span style="color: #3366ff;">// abort optimization</span></em>
    return LookBack/TimeFrame; <em><span style="color: #3366ff;">// reduce the period</span></em>
  } else
    return Period;
}

<em><span style="color: #3366ff;">// calculate profit factor and remove systems with not enough trades</span> </em>
var objective() 
{ 
  if(NumWinTotal &lt; 30 || NumLossTotal &lt; 30) { 
    StepNext = 0;     <em><span style="color: #3366ff;">// abort optimization</span></em>
    return 0;         <em><span style="color: #3366ff;">// don't store this system</span></em>
  } else
      return WinTotal/LossTotal; <em><span style="color: #3366ff;">// Profit factor</span></em>
}

var filter(var* Data,int Period);

void run()
{
  set(PARAMETERS|LOGFILE);
  Curves = "DailyBalance.bin";
  StartDate = 2010;
  BarPeriod = 15;
  LookBack = 80*4*24; <em><span style="color: #3366ff;">// ~ 4 months</span></em>
  Detrend = TRADES;<em><span style="color: #3366ff;">   // detrend trade results</span></em>
  while(asset(loop("EUR/USD","SPX500","XAG/USD")))
  while(algo(loop("MM15","MH1","MH4")))
  {
    TimeFrame = 1;
    if(Algo == "MH1")
      TimeFrame = 1*4;
    else if(Algo == "MH4")
      TimeFrame = 4*4;	

<em><span style="color: #3366ff;">// no trade costs</span></em>
    Spread = Commission = RollLong = RollShort = Slippage = 0;

    int Periods[10] = { 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000 };
    int Period = Periods[round(optimize(1,1,10,1),1)-1];
		
    var *Price = series(price());
    var *Smoothed = series(filter(Price,Period));

    bool DoTrade = true;
    int MMIPeriod = optimize(0,200,500,100);
    if(MMIPeriod) {
      MMIPeriod = checkLookBack(MMIPeriod);
      var *MMI_Raw = series(MMI(Price,MMIPeriod));
      var *MMI_Smooth = series(LowPass(MMI_Raw,MMIPeriod));
      DoTrade = falling(MMI_Smooth);
    }

    if(DoTrade) {
      if(valley(Smoothed))
        enterLong();
      else if(peak(Smoothed))
        enterShort();
    }
  } 
}</pre>
<p>The 10 trend trading scripts with the 10 different indicators remain unchanged, aside from now including <strong>TrendMMI.c</strong> instead of <strong>Trend.c</strong>. Trading is now dependent on a boolean variable <strong>DoTrade</strong>. The length of the MMI range is varied between 200, 300, 400, and 500 bars. As most parameters in a strategy, the MMI range is a compromise: It should be no less than 200 bars for getting any accuracy, but it should not be too long for preventing that different market regimes fall in the same MMI range. At the default range of 0, no MMI is applied and trading is not filtered. This way we&#8217;re including all the previous systems in the test. This is required for properly detecting Data Mining Bias, which must consider all systems that were discarded based on their result.</p>
<p>We&#8217;re running the MMI return value through a lowpass filter that uses the same period as the MMI range. This gives us a smooth MMI value that does not jump around. This value is now used for trade filtering: trades are opened and closed only when the smoothed MMI is falling, meaning that the market has entered trending mode within the last 200 to 500 bars. The MMI is only applied to one of the systems resulting from the prior period variation (the <strong>optimize</strong> function automatically selects the parameter of the &#8220;most robust&#8221; system before optimizing the next parameter). So now we&#8217;re testing in fact not 900, but 1260 systems: 900 without MMI and each 90 with MMI ranges of 200, 300, 400, and 500 bars. The systems with not enough trades or a too-long lookback period are again removed from the pool, so the real number of tested systems is about 1100.</p>
<p>Depending on the speed of your PC, Zorro will need about 1 hour to test all systems. At the end of every system test, Zorro produces the parameter histograms. We have now two parameters. The histogram of the first one, the price smoothing filter period, looks as before because MMI was switched off during optimization. The second histogram displays the MMI range in combination with the best value from the first histogram. &#8220;Best&#8221; is here not the highest bar from the previous histogram, but the value that Zorro deems the most robust and least sensitive to market changes. A typical MMI histograms look like this:</p>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_SPX500MM15_p2.png"><img loading="lazy" decoding="async" class="wp-image-405 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_SPX500MM15_p2.png" alt="" width="244" height="201" /></a></p>
<p>The first bar, marked &#8220;100&#8221;, is the best system without MMI. We can see that it is unprofitable: The profit factor (left scale) is only about 0.8. Using the MMI with a range of 200 and 300 makes the system in fact worse, and reduces the profit factor t0 0.7. However the last two MMI ranges, 400 and 500, shift the system into the profit zone. This was just a random example, but how does the MMI affect all the other systems? Here are the statistics from the MMI experiment:</p>
<table>
<tbody>
<tr>
<td>Asset, Period, Indicator</td>
<td style="text-align: right;">Success Rate</td>
<td style="text-align: right;">Winning</td>
<td style="text-align: right;">Losing</td>
</tr>
<tr>
<td><strong>EUR/USD</strong></td>
<td style="text-align: right;"><strong>46% (+8%)</strong></td>
<td style="text-align: right;"><strong>154</strong></td>
<td style="text-align: right;"><strong>185</strong></td>
</tr>
<tr>
<td><strong>S&amp;P 500</strong></td>
<td style="text-align: right;"><strong>4% (+3%)</strong></td>
<td style="text-align: right;"><strong>15</strong></td>
<td style="text-align: right;"><strong>318</strong></td>
</tr>
<tr>
<td><strong>Silver</strong></td>
<td style="text-align: right;"><strong>27% (+7%)</strong></td>
<td style="text-align: right;"><strong>87</strong></td>
<td style="text-align: right;"><strong>240</strong></td>
</tr>
<tr>
<td><strong>15 Minutes</strong></td>
<td style="text-align: right;"><strong>18% (+7%)</strong></td>
<td style="text-align: right;"><strong>71</strong></td>
<td style="text-align: right;"><strong>322</strong></td>
</tr>
<tr>
<td><strong>1 Hour</strong></td>
<td style="text-align: right;"><strong>27% (+9%)</strong></td>
<td style="text-align: right;"><strong>92</strong></td>
<td style="text-align: right;"><strong>251</strong></td>
</tr>
<tr>
<td><strong>4 Hours</strong></td>
<td style="text-align: right;"><strong>35% (+2%)</strong></td>
<td style="text-align: right;"><strong>93</strong></td>
<td style="text-align: right;"><strong>170</strong></td>
</tr>
<tr>
<td><strong>ALMA</strong></td>
<td style="text-align: right;"><strong>22% (+6)%</strong></td>
<td style="text-align: right;"><strong>22</strong></td>
<td style="text-align: right;"><strong>79</strong></td>
</tr>
<tr>
<td><strong>Decycle</strong></td>
<td style="text-align: right;"><strong>21% (+8%)</strong></td>
<td style="text-align: right;"><strong>23</strong></td>
<td style="text-align: right;"><strong>89</strong></td>
</tr>
<tr>
<td><strong>EMA</strong></td>
<td style="text-align: right;"><strong>23% (+5%)</strong></td>
<td style="text-align: right;"><strong>24</strong></td>
<td style="text-align: right;"><strong>79</strong></td>
</tr>
<tr>
<td><strong>HMA</strong></td>
<td style="text-align: right;"><strong>34% (+9%)</strong></td>
<td style="text-align: right;"><strong>33</strong></td>
<td style="text-align: right;"><strong>66</strong></td>
</tr>
<tr>
<td><strong>Laguerre</strong></td>
<td style="text-align: right;"><strong>33% (+3%)</strong></td>
<td style="text-align: right;"><strong>20</strong></td>
<td style="text-align: right;"><strong>38</strong></td>
</tr>
<tr>
<td><strong>LinearReg</strong></td>
<td style="text-align: right;"><strong>29% (+6%)</strong></td>
<td style="text-align: right;"><strong>31</strong></td>
<td style="text-align: right;"><strong>77</strong></td>
</tr>
<tr>
<td><strong>Lowpass</strong></td>
<td style="text-align: right;"><strong>24% (+5%)</strong></td>
<td style="text-align: right;"><strong>26</strong></td>
<td style="text-align: right;"><strong>82</strong></td>
</tr>
<tr>
<td><strong>SMA</strong></td>
<td style="text-align: right;"><strong>26% (+5%)</strong></td>
<td style="text-align: right;"><strong> 27</strong></td>
<td style="text-align: right;"><strong> 76</strong></td>
</tr>
<tr>
<td><strong>Smooth</strong></td>
<td style="text-align: right;"><strong>26% (+7%)</strong></td>
<td style="text-align: right;"><strong>23</strong></td>
<td style="text-align: right;"><strong>67</strong></td>
</tr>
<tr>
<td><strong>ZMA</strong></td>
<td style="text-align: right;"><strong>22% (+8)%</strong></td>
<td style="text-align: right;"><strong>27</strong></td>
<td style="text-align: right;"><strong>90</strong></td>
</tr>
</tbody>
</table>
<p>The <strong>Rate</strong> column shows the percentage of successful systems, and in parentheses the difference to the percentage without MMI. We can see that the MMI increased the number of successful systems in all markets, time frames, and indicators. However the numbers are not really representative: the MMI only affected a quarter of the tested systems, but the upper quarter, so some increase in the number of profitable systems was to be expected anyway. A more meaningful measure is the WRC. We&#8217;re using the same <strong>Bootstrap.c</strong> script as in the <a href="http://www.financial-hacker.com/whites-reality-check/">previous experiment</a>, we only need to increase the CURVES number to 1260. This is the WRC histogram of systems with MMI (again, best system vs. bootstrapped returns of all systems):</p>
<figure id="attachment_439" aria-describedby="caption-attachment-439" style="width: 833px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/trendmmi.png"><img loading="lazy" decoding="async" class="wp-image-439 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/trendmmi.png" alt="" width="833" height="251" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/trendmmi.png 833w, https://financial-hacker.com/wp-content/uploads/2015/09/trendmmi-300x90.png 300w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a><figcaption id="caption-attachment-439" class="wp-caption-text">900 trend systems (with MMI)</figcaption></figure>
<p>The MMI filter now shifted the best system (black) far to the right side of the histogram. It got a <strong>p-value of 0.02</strong>, meaning that it is better than 98% of the best randomized systems, and thus well above the 95% significance level. Using the MMI for filtering trades, the method of trading on curve peaks and valleys passed White&#8217;s Reality Check. In fact two of the 1260 systems got p-values above the significance level.</p>
<p>The best systems of the experiment had some things in common: They traded with silver and used either the ALMA or the lowpass filter. This is a surprising result, because neither silver nor ALMA and  lowpass had the highest number of profitable systems. From the above table, one would assume that EUR/USD and the HMA or Laguerre filter are the most promising. They indeed produced many apparently good systems with profit factors above 2 (without trade costs), but none of them passed the WRC.</p>
<h3>Conclusion</h3>
<ul style="list-style-type: square;">
<li>The MMI improved trend following systems by 5%&#8230;10% average with all tested markets, time frames, and indicators. Best systems were improved by more than 50%.</li>
<li>Trend following systems using the MMI can pass White&#8217;s Reality Check.</li>
<li>From the 10 tested smoothing indicators, <a href="http://www.financial-hacker.com/trend-delusion-or-reality/">ALMA</a> produced the best results, although within a relatively small parameter range.</li>
<li>To do: Test more trend filters, f.i. the Hurst Exponent or Ehlers&#8217; Trend/ Cycle decomposition.</li>
<li>To do: Create a real trading system by combining the best trend systems and adding the usual system components such as stop loss, trailing algorithm, profit lock, money management, and so on.</li>
</ul>
<p>I&#8217;ve added the scripts to the 2015 scripts collection.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/boosting-systems-by-trade-filtering/feed/</wfw:commentRss>
			<slash:comments>34</slash:comments>
		
		
			</item>
		<item>
		<title>The Market Meanness Index</title>
		<link>https://financial-hacker.com/the-market-meanness-index/</link>
					<comments>https://financial-hacker.com/the-market-meanness-index/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 21 Sep 2015 05:00:40 +0000</pubDate>
				<category><![CDATA[Indicators]]></category>
		<category><![CDATA[Ehlers]]></category>
		<category><![CDATA[Mandelbrot]]></category>
		<category><![CDATA[Market Meanness Index]]></category>
		<category><![CDATA[Mean Reversion]]></category>
		<category><![CDATA[Momentum]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=250</guid>

					<description><![CDATA[This indicator can improve &#8211; sometimes even double &#8211; the profit expectancy of trend following systems. The Market Meanness Index tells whether the market is currently moving in or out of a &#8220;trending&#8221; regime. It can this way prevent losses by false signals of trend indicators. It is a purely statistical algorithm and not based on volatility, &#8230; <a href="https://financial-hacker.com/the-market-meanness-index/" class="more-link">Continue reading<span class="screen-reader-text"> "The Market Meanness Index"</span></a>]]></description>
										<content:encoded><![CDATA[<p>This indicator can improve &#8211; sometimes even double &#8211; the profit expectancy of trend following systems. The <strong>Market Meanness Index</strong> tells whether the market is currently moving in or out of a &#8220;trending&#8221; regime. It can this way prevent losses by <strong>false signals</strong> of trend indicators. It is a purely statistical algorithm and not based on volatility, trends, or cycles of the price curve.<span id="more-250"></span></p>
<p>There are already several methods for differentiating trending and nontrending market regimes. Some of them are rumored to really work, at least occasionally. John Ehlers proposed the <strong>Hilbert Transform</strong> or a <strong>Cycle / Trend decomposition</strong>, Benoit Mandelbrot the <strong>Hurst Exponent</strong>. In comparison, the source code of the Market Meanness Index is relatively simple:</p>
<pre class="prettyprint">// Market Meanness Index
double MMI(double *Data,int Length)
{
  double m = Median(Data,Length);
  int i, nh=0, nl=0;
  for(i=1; i&lt;Length; i++) {
    if(Data[i] &gt; m &amp;&amp; Data[i] &gt; Data[i-1]) // mind Data order: Data[0] is newest!
      nl++;
    else if(Data[i] &lt; m &amp;&amp; Data[i] &lt; Data[i-1])
      nh++;
  }
  return 100.*(nl+nh)/(Length-1);
}</pre>
<p>This code is in C for Zorro, but meanwhile also versions for MT4, Amibroker, Ninja Trader, and other platforms have been programmed by users. As the name suggests, the indicator measures the meanness of the market &#8211; its tendency to revert to the mean after pretending to start a trend. If that happens too often, all trend following systems will bite the dust.</p>
<h3>The Three-Quarter Rule</h3>
<p>Any series of independent random numbers reverts to the mean &#8211; or more precisely, to their median &#8211; with a probability of 75%. Assume you have a sequence of random, uncorrelated daily data &#8211; for instance, the daily rates of change of a random walk price curve. If Monday&#8217;s data value was above the median, then in 75% of all cases Tuesday&#8217;s data will be lower than Monday&#8217;s. And if Monday was below the median, 75% chance is that Tuesday will be higher. The proof of the 75% rule is relatively simple and won&#8217;t require integral calculus. Consider a data series with median <strong>M</strong>. By definition, half the values are less than <strong>M</strong> and half are greater (for simplicity&#8217;s sake we&#8217;re ignoring the case when a value is exactly <strong>M</strong>). Now combine the values to pairs each consisting of a value <strong>Py</strong> and the following value <strong>Pt</strong>. Thus each pair represents a change from <strong>Py</strong> to <strong>Pt</strong>. We now got a lot of changes that we divide into four sets:</p>
<ol>
<li><strong>(Pt &lt; M, Py &lt; M)</strong></li>
<li><strong><span style="line-height: 1.75;">(Pt &lt; M, Py &gt; M)</span></strong></li>
<li><strong><span style="line-height: 1.75;">(Pt &gt; M, Py &lt; M)</span></strong></li>
<li><strong><span style="line-height: 1.75;">(Pt &gt; M, Py &gt; M) </span></strong></li>
</ol>
<p><span style="line-height: 1.75;">These four sets have obviously the same number of elements &#8211; that is, 1/4 of all <strong>Py-&gt;Pt</strong> changes &#8211; when <strong>Pt</strong> and <strong>Py</strong> are uncorrelated, i.e. completely independent of one another. The value of <strong>M</strong> and the kind of data in the series won&#8217;t matter for this. Now how many data pairs revert to the median? All pairs that fulfill this condition:</span> <strong>(Py &lt; M and Pt &gt; Py) or (Py &gt; M and Pt &lt; Py)</strong> <span style="line-height: 1.75;">The condition in the first bracket is fulfilled for half the data in set 1 (in the other half is <strong>Pt</strong> less than<strong> Py</strong>) and in the whole set 3 (because <strong>Pt</strong> is always higher than <strong>Py</strong> in set 3). So the first bracket is true for </span><span style="line-height: 1.75;">1/2 * 1/4 + 1/4 = 3/8 of all data changes. Likewise,  the second bracket is true in half the set 4 and in the whole set 2, thus also for 3/8 of all data changes. 3/8 + 3/8 yields 6/8, i.e. <strong>75%</strong>. This is the three-quarter rule for random numbers.</span></p>
<p><span style="line-height: 1.75;">The <strong>MMI</strong> function just counts the number of data pairs for which the conditition is met, and returns their percentage. The <strong>Data</strong> series may contain prices or price changes. Prices have always some serial correlation: If EUR / USD today is at 1.20, it will also be tomorrow around 1.20. That it will end up tomorrow at 70 cents or 2 dollars per EUR is rather unlikely. This serial correlation is also true for a price series calculated from random numbers, as not the prices themselves are random, but their changes. Thus, the MMI function should return a smaller percentage, such as 55%, when fed with prices.</span></p>
<p><span style="line-height: 1.75;"> </span><span style="line-height: 1.75;">Unlike prices, price changes have not necessarily serial correlation. A one hundred percent efficient market has no correlation between the price change from yesterday to today and the price change from today to tomorrow. If the MMI function is fed with perfectly random price changes from a perfectly efficient market, it will return a value of about 75%. The less efficient and the more trending the market become</span><span style="line-height: 1.75;">s, the more the MMI decreases. Thus a falling MMI is a indicator of an upcoming trend. A rising MMI hints that the market will get nastier, at least for trend trading systems.</span></p>
<h3>Using the MMI in a trend strategy</h3>
<p>One could assume that MMI predicts the price direction. A high MMI value indicates a high chance of mean reversion, so when prices were moving up in the last time and MMI is high, can we expect a soon price drop? Unfortunately it doesn&#8217;t work this way. The probability of mean reversion is not evenly distributed over the <strong>Length</strong> of the <strong>Data</strong> interval. For the early prices it is high (since the median is computed from future prices), but for the late prices, at the very time when MMI is calculated, it is down to just 50%. Predicting the next price with the MMI would work as well as flipping a coin.</p>
<p>Another mistake would be using the MMI for detecting a cyclic or mean-reverting market regime. True, the MMI will rise in such a situation, but it will also rise when the market becomes more random and more effective. A rising MMI alone is no promise of profit by cycle trading systems.</p>
<p>So the MMI won&#8217;t tell us the next price, and it won&#8217;t tell us if the market is mean reverting or just plain mean, but it can reveal information about the success chance of trend following. For this we&#8217;re making an assumption: <strong>Trend itself is trending</strong>. The market does not jump in and out of trend mode suddenly, but with some inertia. Thus, when we know that MMI is rising, we assume that the market is becoming more efficient, more random, more cyclic, more reversing or whatever, but in any case bad for trend trading. However when MMI is falling, chances are good that the next beginning trend will last longer than normal.</p>
<p>This way the MMI can be an excellent trend filter &#8211; in theory. But we all know that there&#8217;s often a large gap between theory and practice, especially in algorithmic trading. So I&#8217;m now going to test what the Market Meanness Index does to the collection of the <a href="http://www.financial-hacker.com/trend-and-exploiting-it/">900 trend following systems</a> that I&#8217;ve accumulated. For a first quick test, this was the equity curve of one of the systems, <strong>TrendEMA</strong>, without MMI (44% average annual return):</p>
<figure id="attachment_375" aria-describedby="caption-attachment-375" style="width: 1079px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD.png"><img loading="lazy" decoding="async" class="wp-image-375 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD.png" alt="" width="1079" height="301" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD.png 1079w, https://financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD-300x84.png 300w, https://financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD-1024x286.png 1024w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-375" class="wp-caption-text">EMA strategy without MMI</figcaption></figure>
<p>This is the same system with MMI (55% average annual return):</p>
<figure id="attachment_377" aria-describedby="caption-attachment-377" style="width: 1079px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD1.png"><img loading="lazy" decoding="async" class="wp-image-377 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD1.png" alt="" width="1079" height="301" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD1.png 1079w, https://financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD1-300x84.png 300w, https://financial-hacker.com/wp-content/uploads/2015/09/TrendEMA_EURUSD1-1024x286.png 1024w" sizes="auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px" /></a><figcaption id="caption-attachment-377" class="wp-caption-text">EMA strategy with MMI</figcaption></figure>
<p>We can see that the profit has doubled, from $250 to $500. The profit factor climbed from 1.2 to 1.8, and the number of trades (green and red lines) is noticeable reduced. On the other hand, the equity curve started with a drawdown that wasn&#8217;t there with the original system. So MMI obviously does not improve all trades. And this was just a randomly selected system. If our assumption about trend trendiness is true, the indicator should have a significant effect also on the other 899 systems.</p>
<p>This experiment will be the topic of the next article, in about a week. As usually I&#8217;ll include all the source code for anyone to reproduce it. Will the MMI miserably fail? Or improve only a few systems, but worsen others? Or will it light up the way to the Holy Grail of trend strategies? Let the market be the judge.</p>
<p><a href="http://www.financial-hacker.com/boosting-systems-by-trade-filtering/">Next: Testing the Market Meanness Index</a></p>
<hr />
<p><strong>Addendum (2022).</strong> I thought my above proof of the 3/4 rule was trivial and no math required, but judging from some comments, it is not so. The rule appears a bit counter-intuitive at first glance. Some comments also confuse a random walk (for example, prices) with a random sequence (for example, price differences). Maybe I have just bad explained it &#8211; in that case, read up the proof anywhere else. I found the two most elaborate proofs of the 3/4 rule, geometrical and analytical, in this book:</p>
<p>(1)  Andrew Pole, Statistical Arbitrage, Wiley 2007</p>
<p>And with no reading and no math: Take a dice, roll it 100 times, write down each result, get the median of all, and then count how often a pair reverted to the median.</p>
<p>Below you can see the MMI applied to a synthetic price curve, first sidewards (black) and then with added trend (blue). For using the MMI with real prices or price differences, read the next article.</p>
<p><img decoding="async" src="http://financial-hacker.com/images/Regime.png " alt="MMI" /></p>
<p>The code:</p>
<pre class="prettyprint">function run()
{
	BarPeriod = 60;
	MaxBars = 1000;
	LookBack = 500;
	asset(""); // dummy asset
	ColorUp = ColorDn = 0; // don't plot a price curve
	set(PLOTNOW);
	
	if(Init) seed(1000);
	int TrendStart = LookBack + 0.4*(MaxBars-LookBack);
	vars Signals = series(1 + 0.5*genNoise());
	if(Bar &gt; TrendStart) 
		Signals[0] += 0.003*(Bar-TrendStart);
	int Color = RED;
	int TimePeriod = 0.5*LookBack;
	if(Bar &lt; TrendStart)
		plot("Sidewards",Signals,MAIN,BLACK);
	else
		plot("Trending",Signals,MAIN,BLUE);
	plot("MMI",MMI(Signals,TimePeriod),NEW|LINE,Color);
}</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/the-market-meanness-index/feed/</wfw:commentRss>
			<slash:comments>139</slash:comments>
		
		
			</item>
	</channel>
</rss>
