<?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>Cycles &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/cycles/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Sun, 12 Jan 2020 13:08:08 +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>Cycles &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Build Better Strategies! Part 3: The Development Process</title>
		<link>https://financial-hacker.com/build-better-strategies-part-3-the-development-process/</link>
					<comments>https://financial-hacker.com/build-better-strategies-part-3-the-development-process/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 22 Feb 2016 16:46:32 +0000</pubDate>
				<category><![CDATA[3 Most Useful]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[Cycles]]></category>
		<category><![CDATA[Detrending]]></category>
		<category><![CDATA[Drawdown]]></category>
		<category><![CDATA[Medallion fund]]></category>
		<category><![CDATA[Money management]]></category>
		<category><![CDATA[Spectral filter]]></category>
		<category><![CDATA[Walk forward analysis]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=1191</guid>

					<description><![CDATA[This is the third part of the Build Better Strategies series. In the previous part we&#8217;ve discussed the 10 most-exploited market inefficiencies and gave some examples of their trading strategies. In this part we&#8217;ll analyze the general process of developing a model-based trading system. As almost anything, you can do trading strategies in (at least) &#8230; <a href="https://financial-hacker.com/build-better-strategies-part-3-the-development-process/" class="more-link">Continue reading<span class="screen-reader-text"> "Build Better Strategies! Part 3: The Development Process"</span></a>]]></description>
										<content:encoded><![CDATA[<p>This is the third part of the <a href="http://www.financial-hacker.com/build-better-strategies/">Build Better Strategies</a> series. In the previous part we&#8217;ve discussed the 10 most-exploited market inefficiencies and gave some examples of their trading strategies. In this part we&#8217;ll analyze the general process of developing a model-based trading system. As almost anything, you can do trading strategies in (at least) two different ways: There&#8217;s the <strong>ideal way</strong>, and there&#8217;s the <strong>real way</strong>. We begin with the <strong>ideal development process</strong>, broken down to 10 steps.<span id="more-1191"></span></p>
<h3>The ideal model-based strategy development<br />
Step 1: The model</h3>
<p>Select one of the known market inefficiencies listed in the <a href="http://www.financial-hacker.com/build-better-strategies-part-2-model-based-systems/">previous part</a>, or discover a new one. You could eyeball through price curves and look for something suspicious that can be explained by a certain market behavior. Or the other way around, &nbsp;theoretize about a behavior pattern and check if you can find it reflected in the prices. If you discover something new, feel invited to post it here! But be careful: Models of non-existing inefficiencies (such as&nbsp;<a href="http://www.financial-hacker.com/seventeen-popular-trade-strategies-that-i-dont-really-understand/">Elliott Waves</a>) already outnumber real inefficiencies by a large amount. It is not likely that a real inefficiency remains unknown to this day.</p>
<p>Once you&#8217;ve decided for a model, determine which <strong>price curve anomaly</strong> it would produce, and describe it with a quantitative formula or at least a qualitative criteria. You&#8217;ll need that for the next step. As an example we&#8217;re using the <strong>Cycles Model</strong> from the previous part:</p>
<p>[latex display=&#8221;true&#8221;]y_t ~=~ \hat{y} + \sum_{i}{a_i sin(2 \pi t/C_i+D_i)} + \epsilon[/latex]</p>
<p>(Cycles are not to be underestimated. One of the most successful funds in history &#8211; Jim Simons&#8217; <strong>Renaissance Medallion</strong> fund &#8211; is rumored to exploit cycles in price curves by analyzing their lengths (<em><strong>C<sub>i</sub></strong></em>), phases (<em><strong>D<sub>i</sub></strong></em>) and amplitudes (<em><strong>a<sub>i</sub></strong></em>) with a Hidden Markov Model. Don&#8217;t worry, we&#8217;ll use a somewhat simpler approach in our example.)</p>
<h3>Step 2: Research</h3>
<p>Find out if the hypothetical anomaly really appears in the price curves of the assets that you want to trade. For this you first need enough historical data of the traded assets &#8211; D1, M1, or Tick data, dependent on the time frame of the anomaly. How far back? As far as possible, since you want to find out the lifetime of your anomaly and the market conditions under which it appears. Write a script to detect and display the anomaly in price data. For our Cycles Model, this would be the frequency spectrum:</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 fetchpriority="high" 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="(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 frequency spectrum, cycle amplitude vs. cycle length in bars</figcaption></figure>
<p>Check out how the spectrum changes over the months and years. Compare with the spectrum of random data (with <a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/" target="_blank" rel="noopener noreferrer">Zorro</a> you can use the <a href="http://zorro-project.com/manual/en/detrend.htm" target="_blank" rel="noopener noreferrer">Detrend</a> function for randomizing price curves). If you find no clear signs of the anomaly, or no significant difference to random data, improve your detection method. And if you then still don&#8217;t succeed, go back to step 1.</p>
<h3>Step 3: The algorithm</h3>
<p>Write an algorithm that generates the&nbsp;<strong>trade signals</strong> for buying in the direction of the anomaly. A market inefficiency has normally only a <strong>very weak effect</strong> on the price curve. So your algorithm must be really good in distinguishing it from random noise. At the same time it should be as simple as possible, and rely on as few free parameters as possible. &nbsp;In our example with the Cycles Model, the script reverses the position at every valley and peak of a sine curve that runs ahead of the dominant cycle:</p>
<pre class="prettyprint">function run()
{
  vars Price = series(price());
  var Phase = DominantPhase(Price,10);
  vars Signal = series(sin(Phase+PI/4));

  if(valley(Signal))
    reverseLong(1); 
  else if(peak(Signal))
    reverseShort(1);
}</pre>
<p>This is the core of the system. Now it&#8217;s time for a first backtest. The precise performance does not matter much at this point &#8211; just determine whether the algorithm has an edge or not. Can&nbsp;it produce a series of profitable trades at least in certain market periods or situations? If not, improve the algorithm or write a another one that exploits the same anomaly with a different method. But do not yet use any stops, trailing, or other bells and whistles. They would only distort the result, and give you the illusion of profit where none is there. Your algorithm must be able to produce positive returns either with pure reversal, or at least with a timed exit.</p>
<p>In this step you must also decide about the <strong>backtest data</strong>. You normally need M1 or tick data for a realistic test. Daily data won&#8217;t do. The data amount depends on the lifetime (determined in step 2) and the nature of the price anomaly. Naturally, the longer the period, the better the test &#8211; but more is not always better. Normally it makes no sense to go further back than 10 years, at least not when your system exploits some real market behavior. Markets change extremely in a decade. Outdated historical price data can produce very misleading results. Most systems that had an edge 15 years ago will fail miserably on today&#8217;s markets. But they can deceive you with a seemingly profitable backtest.</p>
<h3>Step 4: The filter</h3>
<p>No market inefficiency exits all the time. Any market goes through periods of random behavior. It is essential for any system to have a filter mechanism that detects if the inefficiency is present or not. The filter is at least as important as the trade signal, if not more &#8211; but it&#8217;s often forgotten in trade systems. This is our example script with a filter:</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));
  var Threshold = 1*PIP;
  ExitTime = 10*rDominantPeriod;
	
  if(Amplitude(Dominant,100) &gt; Threshold) {
    if(valley(Signal))
      reverseLong(1); 
    else if(peak(Signal))
      reverseShort(1);
  }
}</pre>
<p>We apply a bandpass filter centered at the dominant cycle period to the price curve and measure its amplitude. If the amplitude is above a threshold, we conclude that the inefficiency is there, and we trade. The trade duration is now also restricted to a maximum of 10 cycles since we found in step 2 that dominant cycles appear and disappear in relatively short time.</p>
<p>What can go wrong in this step is falling to the temptation to add a filter just because it improves the test result. Any filter must have a rational reason in the market behavior or in the used signal algorithm. If your algorithm only works by adding irrational filters: back to step 3.</p>
<h3>Step 5: Optimizing (but not too much!)</h3>
<p>All parameters of a system affect the result, but only a few directly determine entry and exit points of trades dependent on the price curve. These &#8216;adaptable&#8217; parameters should be identified and optimized. In the above example, trade entry is determined by the phase of the forerunning sine curve and by the filter threshold, and trade exit is determined by the exit time. Other parameters &#8211; such as the filter constants of the <strong>DominantPhase</strong> and the <strong>BandPass</strong> functions &#8211; need not be adapted since their values do not depend on the market situation.</p>
<p>Adaption is an optimizing procdure, and a big opportunity to fail without even noticing it. Often, genetic or brute force methods are applied for finding the &#8220;best&#8221; parameter combination at a profit peak in the parameter space. Many platforms even have &#8220;optimizers&#8221; for this purpose. Although this method indeed produces the best backtest result, it won&#8217;t help at all for the live performance of the system. In fact, a recent study (<a href="http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2745220">Wiecki et.al. 2016</a>) showed that the better you optimize your parameters, the worse your system will fare in live trading! The reason of this paradoxical effect is that optimizing to maximum profit fits your system mostly to the noise in the historical price curve, since noise affects result peaks much more than market inefficiencies.</p>
<p>Rather than generating top backtest results, correct optimizing has other purposes:</p>
<ul style="list-style-type: square;">
<li>It can determine the <strong>susceptibility</strong> of your system to its parameters. If the system is great with a certain parameter combination, but loses its edge when their values change a tiny bit: back to step 3.</li>
<li>It can identify the parameter&#8217;s <strong>sweet spots</strong>. The sweet spot is the area of highest parameter robustness, i.e. where small parameter changes have little effect on the return. They are not the peaks, but the centers of broad hills in the parameter space.</li>
<li>It can adapt the system to different assets, and enable it to trade a <strong>portfolio</strong> of assets with slightly different parameters.&nbsp;It can also extend the <strong>lifetime</strong> of the system by adapting it to the current market situation in regular time intervals, parallel to live trading.</li>
</ul>
<p>This is our example script with entry parameter optimization:</p>
<pre class="prettyprint">function run()
{
  vars Price = series(price());
  var Phase = DominantPhase(Price,10);
  vars Signal = series(sin(Phase+optimize(1,0.7,2)*PI/4));
  vars Dominant = series(BandPass(Price,rDominantPeriod,1));
  ExitTime = 10*rDominantPeriod;
  var Threshold = optimize(1,0.7,2)*PIP;
	
  if(Amplitude(Dominant,100) &gt; Threshold) {
    if(valley(Signal))
      reverseLong(1); 
    else if(peak(Signal))
      reverseShort(1);
  }
}</pre>
<p>The two <a href="http://manual.zorro-project.com/optimize.htm" target="_blank" rel="noopener noreferrer">optimize</a> calls use a start value (<strong>1.0</strong> in both cases) and a range (<strong>0.7..2.0</strong>) for determining the sweet spots of the two essential parameters of the system. You can identify the spots in the profit factor curves (red bars) of the two parameters that are generated by the optimization process:</p>
<figure id="attachment_1377" aria-describedby="caption-attachment-1377" style="width: 391px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p1.png"><img decoding="async" class="wp-image-1377 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p1.png" alt="" width="391" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p1.png 391w, https://financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p1-300x246.png 300w" sizes="(max-width: 391px) 85vw, 391px" /></a><figcaption id="caption-attachment-1377" class="wp-caption-text">Sine phase in pi/4 units</figcaption></figure>
<figure id="attachment_1376" aria-describedby="caption-attachment-1376" style="width: 391px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p2.png"><img decoding="async" class="wp-image-1376 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p2.png" alt="" width="391" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p2.png 391w, https://financial-hacker.com/wp-content/uploads/2016/02/CyclesDev_EURUSD_p2-300x246.png 300w" sizes="(max-width: 391px) 85vw, 391px" /></a><figcaption id="caption-attachment-1376" class="wp-caption-text">Amplitude threshold in pips</figcaption></figure>
<p>In this case the optimizer would select a parameter value of about 1.3 for the sine phase and about 1.0 (not the peak at 0.9) for the amplitude threshold for the current asset (EUR/USD). The exit time is not optimized in this step, as we&#8217;ll do that later together with the other exit parameters when risk management is implemented.</p>
<h3>Step 6: Out-of-sample analysis</h3>
<p>Of course the parameter optimization improved the backtest performance of the strategy, since the system was now better adapted to the price curve. So the test result so far is worthless. For getting an idea of the real performance, we first need to split the data into in-sample and out-of-sample periods. The in-sample periods are used for training, the out-of-sample periods for testing. The best method for this is <a href="http://manual.zorro-project.com/numwfocycles.htm" target="_blank" rel="noopener noreferrer">Walk Forward Analysis</a>. It uses a rolling window into the historical data for separating test and training periods.</p>
<p>Unfortunately, WFA adds two more parameters to the system: the training time and the test time of a WFA cycle. The test time should be long enough for trades to properly open and close, and small enough for the parameters to stay valid. The training time is more critical. Too short training will not get enough price data for effective optimization, training too long will also produce bad results since the market can already undergo changes during the training period. So the training time itself is a parameter that had to be optimized.</p>
<p>A five&nbsp;cycles walk forward analysis (add &#8220;<strong>NumWFOCycles = 5;</strong>&#8221; to the above script) reduces the backtest performance from 100% annual return to a more realistic 60%. For preventing that WFA still produces too optimistic results just by a lucky selection of test and training periods, it makes also sense to perform WFA several times with slightly different starting points of the simulation. If the system has an edge, the results should be not too different. If they vary wildly: back to step 3.</p>
<h3>Step 7: Reality Check</h3>
<p>Even though the test is now out-of-sample, the mere development process &#8211; selecting algorithms, assets, test periods and other ingredients by their performance &#8211; has added a lot of <strong>selection bias</strong> to the results. Are they caused by a real edge of the system, or just by biased development? Determining this with some certainty is the hardest part of strategy development.</p>
<p>The best way to find out is <a href="http://www.financial-hacker.com/whites-reality-check/">White&#8217;s Reality Check</a>. But it&#8217;s also the least practical because it requires strong discipline in parameter and algorithm selection. Other methods are not as good, but easier to apply:</p>
<ul>
<li><strong>Montecarlo</strong>. Randomize the price curve by shuffling without replacement, then train and test again. Repeat this many times. Plot a distribution of the results (an example of this method can be found in chapter 6 of the <a href="http://www.amazon.de/Das-B%C3%B6rsenhackerbuch-Finanziell-algorithmische-Handelssysteme/dp/1530310784" target="_blank" rel="noopener noreferrer">Börsenhackerbuch</a>). Randomizing removes all price anomalies, so you hope for significantly worse performance. But if the result from the real price curve lies not far east of the random distribution peak, it is probably also caused by randomness. That would mean: back to step 3.</li>
<li><strong>Variants.</strong> It&#8217;s the opposite of the Montecarlo method: Apply the trained system on variants of the price curve and hope for positive results. Variants that maintain most anomalies are <a href="http://www.financial-hacker.com/better-tests-with-oversampling/">oversampling</a>, detrending, or inverting the price curve. If the system stays profitable with those variants, but not with randomized prices, you might really have found a solid system.</li>
<li><strong>Really-out-of-sample (ROOS) Test</strong>. While developing the system, ignore the last year (2015) completely. Even delete all 2015 price history from your PC. Only when the system is completely finished, download the data and run a 2015 test. Since the 2015 data can be only used once this way and is then tainted, you can&nbsp;not modify the system anymore if it fails in 2015. Just abandon it. Assemble all your metal strength and go back to step 1.</li>
</ul>
<h3>Step 8: Risk management</h3>
<p>Your system has so far survived all tests. Now you can concentrate on reducing its risk and improving its performance. Do not touch anymore the entry algorithm and its parameters. You&#8217;re now optimizing the exit. Instead of the simple timed and reversal exits that we&#8217;ve used during the development phase, we can now apply various trailing stop mechanisms. For instance:</p>
<ul style="list-style-type: square;">
<li>Instead of exiting after a certain time, raise the stop loss by a certain amount per hour. This has the same effect, but will close unprofitable trades sooner and profitable trades later.</li>
<li>When a trade has won a certain amount, place the stop loss at a distance above the break even point. Even when locking a profit percentage does not improve the total performance, it&#8217;s good for your health. Seeing profitable trades wander back into the losing zone can cause serious ulcers.</li>
</ul>
<p>This is our example script with the initial timed exit replaced by a stop loss limit that rises at every bar:</p>
<pre class="prettyprint">function run()
{
  vars Price = series(price());
  var Phase = DominantPhase(Price,10);
  vars Signal = series(sin(Phase+optimize(1,0.7,2)*PI/4));
  vars Dominant = series(BandPass(Price,rDominantPeriod,1));
  var Threshold = optimize(1,0.7,2)*PIP;

  Stop = ATR(100);
  for(open_trades)
    TradeStopLimit -= TradeStopDiff/(10*rDominantPeriod);
	
  if(Amplitude(Dominant,100) &gt; Threshold) {
    if(valley(Signal))
      reverseLong(1); 
    else if(peak(Signal))
      reverseShort(1);
  }
}</pre>
<p>The&nbsp;<strong>for(open_trades)</strong> loop increases the stop level of all open trades by a fraction of the initial stop loss distance at the end of every bar.</p>
<p>Of course you now have to optimize and run a walk forward analysis again with the exit parameters. If the performance didn&#8217;t improve, think about better exit methods.</p>
<h3>Step 9: Money management</h3>
<p>Money management serves three purposes. First, reinvesting your profits. Second, distributing your capital among portfolio components. And third, quickly finding out if a trading book is useless. Open the &#8220;Money Management&#8221; chapter and read the author&#8217;s investment advice. If it&#8217;s &#8220;invest 1% of your capital per trade&#8221;, you know why he&#8217;s writing trading books. He probably has not yet earned money with real trading.</p>
<p>Suppose your trade volume at a given time <em><strong>t</strong></em> is&nbsp;<em><strong>V(t)</strong></em>. If your system is profitable, on average your capital <em><strong>C</strong></em> will rise proportionally to <b><i>V</i></b> with a growth factor <em><strong>c</strong></em>:</p>
<p>[latex display=&#8221;true&#8221;]\frac{dC}{dt} = c V(t)~~\rightarrow~~ C(t) = C_0 + c \int_{0}^{t}{V(t) dt}[/latex]</p>
<p>When you follow trading book advices and always invest a fixed percentage <em><strong>p</strong></em>&nbsp;of your capital, so that <em><strong>V</strong><strong><em>(t)</em> = p C(t)</strong></em>, your capital will grow exponentially with exponent&nbsp;<em><strong>p c</strong></em>:</p>
<p>[latex display=&#8221;true&#8221;]\frac{dC}{dt} ~=~ c p C(t)&nbsp;~~\rightarrow~~&nbsp;C(t) ~=~ C_0 e^{p c t}[/latex]</p>
<p>Unfortunately your capital will also undergo random fluctuations, named <strong>Drawdowns</strong>. Drawdowns are proportial to the trade volume <em><strong>V(t)</strong></em>. On leveraged accounts with no limit to drawdowns, it can be shown from statistical considerations that the maximum drawdown depth <em><strong>D<sub>max</sub></strong></em> grows proportional to the square root of time <em><strong>t</strong></em>:</p>
<p>[latex display=&#8221;true&#8221;]{D_{max}}(t) ~=~ q V(t) \sqrt{t}[/latex]</p>
<p>So, with the fixed percentage investment:</p>
<p>[latex display=&#8221;true&#8221;]{D_{max}}(t) ~=~ q p C(t) \sqrt{t}[/latex]</p>
<p>and at the time <em><strong>T = 1/(q p)<sup>2</sup></strong></em>:</p>
<p>[latex display=&#8221;true&#8221;]{D_{max}}(T) ~=~ q p C(T) \frac{1}{q p} ~=~ C(T)[/latex]</p>
<p>You can see that around the time <em><strong>T&nbsp;= 1/(q p)<sup>2</sup></strong></em> a drawdown will eat up all your capital <em><strong>C(T)</strong></em>, no matter how profitable your strategy is and how you&#8217;ve choosen&nbsp;<em><strong>p</strong></em>! That&#8217;s why the 1% rule is a bad advice. And why I advise clients not to raise the trade volume proportionally to their accumulated profit, but to its square root &#8211; at least on leveraged accounts. Then, as long as the strategy does not deteriorate, they keep a safe distance from a margin call.</p>
<p>Dependent on whether you trade a single asset and algorithm or a portfolio of both, you can calculate the optimal investment with several methods. There&#8217;s the OptimalF formula by <strong>Ralph Vince</strong>, the Kelly formula by <strong>Ed Thorp</strong>, or <a href="http://www.financial-hacker.com/get-rich-slowly/">mean/variance optimization</a> by <strong>Harry Markowitz</strong>. Usually you won&#8217;t hard code reinvesting in your strategy, but calculate the investment volume externally, since you might want to withdraw or deposit money from time to time. This requires the overall volume to be set up manually, not by an automated process. A formula for proper reinvesting and withdrawing can be found in the Black Book.</p>
<h3>Step 10: Preparation for live trading</h3>
<p>You can now define the <strong>user interface</strong> of your trading system. Determine which parameters you want to change in real time, and which ones only at start of the system. Provide a method to control the trade volume, and a &#8216;Panic Button&#8217; for locking profit or cashing out in case of bad news. Display all trading relevant parameters in real time. Add buttons for re-training the system, and provide a method for comparing live results with backtest results, such as the <a href="http://www.financial-hacker.com/the-cold-blood-index/">Cold Blood Index</a>. Make sure that you can supervise the system from whereever you are, for instance through an online status page. Don&#8217;t be tempted to look onto it every five minutes. But you can make a mighty impression when you pull out your mobile phone on the summit of Mt. Ararat and explain to your fellow climbers: &#8220;Just checking my trades.&#8221;</p>
<h3>The real strategy development</h3>
<p>So far the theory. All fine and dandy, but how do you really develop a trading system? Everyone knows that there&#8217;s a huge gap between theory and practice. This is the real development process as testified by many seasoned algo traders:</p>
<p><strong>Step 1.</strong>&nbsp;Visit trader forums and find the thread about the new indicator with the fabulous returns.</p>
<p><strong>Step 2.</strong>&nbsp;Get the indicator working with a test system after a long coding session. Ugh, the backtest result does not look this good. You must have made some coding mistake. Debug. Debug some more.</p>
<p><strong>Step 3.</strong>&nbsp;Still no good result, but you have more tricks up your sleeve. Add a trailing stop. The results now look already better. Run a week analysis. Tuesday is a particular bad day for this strategy? Add a filter that prevents trading on Tuesday. Add more filters that prevent trades between 10 and 12 am, and when the price is below $14.50, and at full moon except on Fridays. Wait a long time for the simulation to finish. Wow, finally the backtest is in the green!</p>
<p><strong>Step 4.</strong> Of course you&#8217;re not fooled by in-sample results. After optimizing all 23 parameters, run a walk forward analysis. Wait a long time for the simulation to finish. Ugh, the result does not look this good. Try different WFA cycles. Try different bar periods. Wait a long time for the simulation to finish. Finally, with a 19-minutes bar period and 31 cycles, you get a sensational backtest result! And this completely out of sample!</p>
<p><strong>Step 5.</strong> Trade the system live.</p>
<p><strong>Step 6.</strong> Ugh, the result does not look this good.</p>
<p><strong>Step 7.</strong> Wait a long time for your bank account to recover. Inbetween, write a trading book.</p>
<hr>
<p>I&#8217;ve added the example script to the 2016 script repository. In the next part of this series we&#8217;ll look into the data mining approach with machine learning systems. We will examine price pattern detection, regression, neural networks, deep learning, decision trees, and support vector machines.</p>
<p style="text-align: right;"><strong>⇒&nbsp;<a href="http://www.financial-hacker.com/build-better-strategies-part-4-machine-learning/">Build Better Strategies &#8211; Part 4</a></strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/build-better-strategies-part-3-the-development-process/feed/</wfw:commentRss>
			<slash:comments>61</slash:comments>
		
		
			</item>
		<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 loading="lazy" 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 loading="lazy" 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 loading="lazy" 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="(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="(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="(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>
	</channel>
</rss>
