<?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>Aronson &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/aronson/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Thu, 12 May 2022 05:32:10 +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>Aronson &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Hacker&#8217;s Tools</title>
		<link>https://financial-hacker.com/hackers-tools-zorro-and-r/</link>
					<comments>https://financial-hacker.com/hackers-tools-zorro-and-r/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Sat, 03 Oct 2015 08:01:30 +0000</pubDate>
				<category><![CDATA[3 Most Useful]]></category>
		<category><![CDATA[Introductory]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Aronson]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[TSSB]]></category>
		<category><![CDATA[Vector-based test]]></category>
		<category><![CDATA[Zorro]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=89</guid>

					<description><![CDATA[For our financial hacking experiments (and for harvesting their financial fruits) we need some software machinery for research, testing, training, and live trading financial algorithms. There are many tools for algo trading, but no existing software platform today is really up to all those tasks. You have to put together your system from different software &#8230; <a href="https://financial-hacker.com/hackers-tools-zorro-and-r/" class="more-link">Continue reading<span class="screen-reader-text"> "Hacker&#8217;s Tools"</span></a>]]></description>
										<content:encoded><![CDATA[<p>For our financial hacking experiments (and for harvesting their financial fruits) we need some software machinery for research, testing, training, and live trading financial algorithms. There are many <a href="https://zorro-project.com/algotradingtools.php" target="_blank" rel="noopener">tools for algo trading</a>, but no existing software platform today is really up to all those tasks. You have to put together your system from different software packages. Fortunately, two are normally sufficient. I&#8217;ll use <strong>Zorro</strong> and <strong>R</strong> for most articles on this blog, but will also occasionally look into other tools.<span id="more-89"></span></p>
<h3>Choice of languages</h3>
<p>Algo trading systems are normally based on a script in some programming language. You can avoid writing scripts entirely by using a visual &#8216;strategy builder&#8217;, &#8216;code wizard&#8217; or spreadsheet program for defining your strategy. But this is also some sort of programming, just in a different language that you have to master. And visual builders can only create rather simple &#8216;indicator soup&#8217; systems that are unlikely to produce consistent trading profit. For serious algo trading sytems, real development, and real research, there&#8217;s no stepping around &#8216;real programming&#8217;.</p>
<p>You&#8217;re also not free to select the programming language with the nicest or easiest syntax. One of the best compromises of simplicity and object orientation is probably <strong>Python</strong>. It also offers libraries with useful statistics and indicator functions. Consequently, many strategy developers start with programming their systems in Python&#8230; and soon run into serious limitations. There&#8217;s another criterion that is more relevant for system development than syntax: <strong>execution speed</strong>.</p>
<p>Speed mostly depends on whether a computer language is <strong>compiled </strong>or <strong>interpreted</strong>. <strong>C</strong>,<strong> Pascal</strong>, and <strong>Java </strong>are compiled languages, meaning that the code runs directly on the processor (C, C++, Pascal) or on a &#8216;virtual machine&#8217; (Java). <strong>Python</strong>, <strong>R</strong>, and <strong>Matlab </strong>is interpreted: The code won&#8217;t run by itself, but is executed by an interpreter software. Interpreted languages are much slower and need more CPU and memory resources than compiled languages. It won&#8217;t help much for trading strategies that they have fast C-programmed libraries. All backtests or optimization processes must still run through the bottleneck of interpreted trading logic. Theoretically the slowness can be worked around with &#8216;vectorized coding&#8217; &#8211; see below &#8211; but that has little practical use.</p>
<p>R and Python have other advantages. They are <strong>interactive</strong>: you can enter commands directly at a console. This allows quick code or function testing. Some languages, such as <strong>C#</strong>, are inbetween: They are compiled to a machine-independent interim code that is then, dependent on implementation, either interpreted or converted to machine code. C# is about 4 times slower than C, but still 30 times faster than Python.</p>
<p>Here&#8217;s a benchmark table of the same two test programs written in several languages: a sudoku solver and a loop with a 1000 x 1000 matrix multiplication (in seconds):</p>
<table>
<tbody>
<tr>
<td>Language</td>
<td>Sudoku</td>
<td>Matrix</td>
</tr>
<tr>
<td>C, C++</td>
<td>1.0</td>
<td>1.8</td>
</tr>
<tr>
<td>Java</td>
<td>1.7</td>
<td>2.6</td>
</tr>
<tr>
<td>Pascal</td>
<td>&#8212;</td>
<td>4</td>
</tr>
<tr>
<td>C#</td>
<td>3.8</td>
<td>9</td>
</tr>
<tr>
<td>JavaScript</td>
<td>18.1</td>
<td>16</td>
</tr>
<tr>
<td>Basic (VBA)</td>
<td>&#8212;</td>
<td>25</td>
</tr>
<tr>
<td>Erlang</td>
<td>18</td>
<td>31</td>
</tr>
<tr>
<td>Python</td>
<td>119</td>
<td>121</td>
</tr>
<tr>
<td>Ruby</td>
<td>98</td>
<td>628</td>
</tr>
<tr>
<td>Matlab</td>
<td>&#8212;</td>
<td>621</td>
</tr>
<tr>
<td>R</td>
<td>&#8212;</td>
<td>1738</td>
</tr>
</tbody>
</table>
<p>Speed becomes important as soon as you want to develop a short-term trading system. In the development process you&#8217;re all the time testing system variants. A 10-years backtest with M1 historical data executes the strategy about 3 million times. If a C-written strategy needs 1 minute for this, the same strategy in EasyLanguage would need about 30 minutes, in Python 2 hours, and in R more than 10 hours! And that&#8217;s only a backtest, no optimization or WFO run. If I had coded the <a href="http://www.financial-hacker.com/trend-and-exploiting-it/">trend experimen</a>t in Python or R, I would today still wait for the results. You can see why trade platforms normally use a C variant or a proprietary compiled language for their strategies. <a href="http://www.financial-hacker.com/hacking-hft-systems/">HFT systems</a> are anyway written in C or directly in machine language.</p>
<p>Even compiled languages can have large speed differences due to different implementation of trading and analysis functions. When we compare not Sudoku or a matrix multiplication, but a real trading system &#8211; the small RSI strategy from <a href="http://manual.zorro-project.com/conversion.htm">this page</a> &#8211; we find very different speeds on different trading platforms (10 years backtest, ticks resolution):</p>
<ul style="list-style-type: square;">
<li>Zorro: ~ 0.5 seconds (compiled C)</li>
<li>MT4:  ~ 110 seconds (MQL4, a C variant)</li>
<li>MultiCharts: ~ 155 seconds (EasyLanguage, a C/Pascal mix)</li>
</ul>
<p>However, the differences are not as bad as suggested by the benchmark table. In most cases the slow language speed is partically compensated by fast vector function libraries. A script that does not go step by step through historical data, but only calls library functions that process all data simultaneously, would run with comparable speed in all languages. Indeed some trading systems can be coded in this <strong>vectorized</strong> method, but <b>u</b>nfortunately this works only with simple systems and requires entirely different scripts for backtests and live trading.</p>
<h3>Choice of tools</h3>
<p><strong>Zorro</strong> is a software for financial analysis and algo-trading &#8211; a sort of Swiss Knife tool since you can use it not only for live trading, but also for all sorts of quick tests. It&#8217;s my software of choice for financial hacking because:</p>
<ul style="list-style-type: square;">
<li>It&#8217;s free (unless you&#8217;re rich).</li>
<li>Scripts are in C, event driven and very fast. You can code a system or an idea in 5 minutes.</li>
<li>Open architecture &#8211; you can add anything with DLL plugins.</li>
<li>Minimalistic &#8211; just a frontend to a programming language.</li>
<li>Can be automatized for experiments.</li>
<li>Very stable &#8211; I rarely found bugs and they were fixed fast.</li>
<li>Very accurate, realistic trading simulation, including HFT.</li>
<li>Supports also options and futures, and portfolios of multiple assets.</li>
<li>Has a library with 100s of indicators, statistics and machine learning functions, most with source code.</li>
<li>Is continuously developed and supported (new versions usually come out every 2..3 months).</li>
<li>Last but not least: I know it quite well, as I&#8217;ve written its tutorial&#8230;</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/Zorro.png"><img fetchpriority="high" decoding="async" class="aligncenter wp-image-117 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470.png" alt="Zorro" width="294" height="582" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470.png 294w, https://financial-hacker.com/wp-content/uploads/2015/09/Zorro-e1441536629470-152x300.png 152w" sizes="(max-width: 294px) 85vw, 294px" /></a></p>
<p>A strategy example coded in C, the classic SMA crossover:</p>
<pre class="prettyprint">void run()
{
  double* Close = series(priceClose());
  double* MA30 = series(SMA(Close,30));	
  double* MA100 = series(SMA(Close,100));
	
  Stop = 4*ATR(100);
  if(crossOver(MA30,MA100))
    enterLong();
  if(crossUnder(MA30,MA100))
    enterShort();
}</pre>
<p>More code can be found among the <a href="https://zorro-project.com/code.php" target="_blank" rel="noopener">script examples</a> on the Zorro website. You can see that Zorro offers a relatively easy trading implementation. But here comes the drawback of the C language: You can not as easy drop in external libraries as in Python or R. Using a C/C++ based data analysis or machine learning package involves sometimes a lengthy implementation. Fortunately, Zorro can also call R and Python functions for those purposes.</p>
<p><strong>R</strong> is a script interpreter for data analysis and charting. It is not a real language with consistent syntax, but more a conglomerate of operators and data structures that has grown over 20 years. It&#8217;s harder to learn than a normal computer language, but offers some unique advantages. I&#8217;ll use it in this blog when it comes to complex analysis or machine learning tasks. It&#8217;s my tool of choice for financial hacking because:</p>
<ul style="list-style-type: square;">
<li>It&#8217;s free. (&#8220;Software is like sex: it&#8217;s better when it&#8217;s free.&#8221;)</li>
<li>R scripts can be very short and effective (once you got used to the syntax).</li>
<li>It&#8217;s the global standard for data analysis and machine learning.</li>
<li>Open architecture &#8211; you can add modules for almost anything.</li>
<li>Minimalistic &#8211; just a console with a language interpreter.</li>
<li>Very stable &#8211; I found a few bugs in external libraries, but so far never in the main program.</li>
<li>Has tons of &#8220;packages&#8221; for all imaginable mathematical and statistical tasks, and especially for machine learning.</li>
<li>Is continuously developed and supported by the global scientific community (about 15 new packages usually come out every day).</li>
</ul>
<p><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/r.jpg"><img decoding="async" class="alignnone wp-image-115 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531.jpg" alt="r" width="693" height="576" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531.jpg 693w, https://financial-hacker.com/wp-content/uploads/2015/09/r-e1441536432531-300x249.jpg 300w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a></p>
<p>This is the SMA crossover in R for a &#8216;vectorized&#8217; backtest:</p>
<pre class="prettyprint">require(quantmod)
require(PerformanceAnalytics)

Data &lt;- xts(read.zoo("EURUSD.csv", tz="UTC", format="%Y-%m-%d %H:%M", sep=",", header=TRUE))
Close &lt;- Cl(Data)
MA30 &lt;- SMA(Close,30)
MA100 &lt;- SMA(Close,100)
 
Dir &lt;- ifelse(MA30 &gt; MA100,1,-1) # calculate trade direction
Dir.1 &lt;- c(NA,Dir[-length(Dir)]) # shift by 1 for avoiding peeking bias
Return &lt;- ROC(Close)*Dir.1 
charts.PerformanceSummary(na.omit(Return))</pre>
<p>You can see that the vectorized code just consists of function calls. It runs almost as fast as the C equivalent. But it is difficult to read, it can not be used for live trading, and many parts of a trading logic &#8211; even a simple stop loss &#8211; cannot be coded for a vectorized test. Thus, so good R is for interactive data analysis, so hopeless is it for writing trade strategies &#8211; although some R packages (for instance, <strong>quantstrat</strong>) even offer rudimentary optimization and test functions. They all require an awkward coding style and do not simulate trading very realistically, but are still too slow for serious backtests.</p>
<p>Although R can not replace a serious backtest and trading platform, Zorro and R complement each other perfectly: <a href="http://www.financial-hacker.com/build-better-strategies-part-5-developing-a-machine-learning-system/" target="_blank" rel="noopener noreferrer">Here</a> is an example of a machine learning system build together with a deep learning package from R and the training and trading framework from Zorro.</p>
<h3>More hacker&#8217;s tools</h3>
<p>Aside from languages and platforms, you&#8217;ll often need auxiliary tools that may be small, simple, cheap, but all the more important since you&#8217;re using them all the time. For editing not only scripts, but even short CSV lists I use <a href="https://notepad-plus-plus.org/" target="_blank" rel="noopener noreferrer"><strong>Notepad++</strong></a>. For interactive working with R I recommend <a href="https://www.rstudio.com" target="_blank" rel="noopener noreferrer"><strong>RStudio</strong></a>. Very helpful for strategy development is a <strong>file comparison</strong> tool: You often have to compare trade logs of different system variants and check which variant opened which trade a little earlier or later, and which consequences that had. For this I use <a href="http://www.scootersoftware.com/" target="_blank" rel="noopener noreferrer"><strong>Beyond Compare</strong></a>.</p>
<p>Aside from Zorro and R, there&#8217;s also a relatively new system development software that I plan to examine closer at some time in the future, <strong><a href="http://www.tssbsoftware.com/" target="_blank" rel="noopener noreferrer">TSSB</a></strong> for generating and testing bias-free trading systems with advanced machine learning algorithms. David Aronson and Timothy Masters were involved in its development, so it certainly won&#8217;t be as useless as most other &#8220;trade system generating&#8221; software. However, there&#8217;s again a limitation: TSSB can not trade or export, so you can not really use the ingenious systems that you developed with it. Maybe I&#8217;ll find a solution to combine TSSB with Zorro.</p>
<h3>References</h3>
<p><a href="https://www.tiobe.com/tiobe-index/">TIOBE index</a> of top programming languages</p>
<p><a href="http://attractivechaos.github.io/plb/">Speed comparison</a> of programming languages</p>
<hr />
<p><strong>Update (November 2017).</strong> The release of new deep learning packages has made TSSB sort of obsolete. For instance, the H2O package natively supports several ways of features filtering and dimensionality reduction, as well as ensembles, both so far the strength of TSSB. H2O is supported with Zorro&#8217;s <strong>advise</strong> function. Still, the TSSB book by Davin Aronson is a valuable source of methods, approaches, and tips about machine learning for financial prediction.</p>
<p>Download links to the latest versions of Zorro and R are placed on the side bar. A brief tutorial to both Zorro an R is contained in the Zorro manual; a more comprehensive introduction into working with Zorro can be found in the <a href="https://www.createspace.com/7147886" target="_blank" rel="noopener noreferrer">Black Book</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/hackers-tools-zorro-and-r/feed/</wfw:commentRss>
			<slash:comments>19</slash:comments>
		
		
			</item>
		<item>
		<title>White&#8217;s Reality Check</title>
		<link>https://financial-hacker.com/whites-reality-check/</link>
					<comments>https://financial-hacker.com/whites-reality-check/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Mon, 14 Sep 2015 08:48:17 +0000</pubDate>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[System Evaluation]]></category>
		<category><![CDATA[Aronson]]></category>
		<category><![CDATA[Data mining bias]]></category>
		<category><![CDATA[Detrending]]></category>
		<category><![CDATA[Momentum]]></category>
		<category><![CDATA[White's reality check]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=188</guid>

					<description><![CDATA[This is the third part of the Trend Experiment article series. We now want to evaluate if the positive results from the 900 tested trend following strategies are for real, or just caused by Data Mining Bias. But what is Data Mining Bias, after all? And what is this ominous White&#8217;s Reality Check? Suppose you &#8230; <a href="https://financial-hacker.com/whites-reality-check/" class="more-link">Continue reading<span class="screen-reader-text"> "White&#8217;s Reality Check"</span></a>]]></description>
										<content:encoded><![CDATA[<p>This is the third part of the <a href="http://www.financial-hacker.com/trend-delusion-or-reality/" target="_blank" rel="noopener noreferrer">Trend Experiment</a> article series. We now want to evaluate if the positive results from the 900 tested trend following strategies are for real, or just caused by <strong>Data Mining Bias</strong>. But what is Data Mining Bias, after all? And what is this ominous <strong>White&#8217;s Reality Check</strong>?<span id="more-188"></span></p>
<p>Suppose you want to trade by moon phases. But you&#8217;re not sure if you shall buy at full moon and sell at new moon, or the other way around. So you do a series of moon phase backtests and find out that the best system, which opens positions at any first quarter moon, achieves 30% annual return. Is this finally the proof that astrology works?</p>
<p>A trade system based on a nonexisting effect has normally a profit expectancy of zero (minus trade costs). But you won&#8217;t get zero when you backtest variants of such a system. Due to statistical fluctuations, some of them will produce a positive and some a negative return. When you now pick the best performer, such as the first quarter moon trading system, you might get a high return and an impressive equity curve in the backtest. Sadly, its test result is not necessarily caused by clever trading. It might be just by clever selecting the random best performer from a pool of useless systems.</p>
<p>For finding out if the 30% return by quarter moon trading are for real or just the fool&#8217;s gold of Data Mining Bias, <strong>Halbert White</strong> (1959-2012) invented a test method in 2000.  <strong>White&#8217;s Reality Check </strong>(aka <strong>Bootstrap Reality Check</strong>) is explained in detail in the book &#8216;Evidence-Based Technical Analysis&#8217; by <strong>David Aronson</strong>. It works this way:</p>
<ol>
<li>Develop a strategy. During the development process, keep a record of all strategy variants that were tested and discarded because of their test results, including all abandoned algorithms, ideas, methods, and parameters. It does not matter if they were discarded by human decision or by a computer search or optimizing process.</li>
<li>Produce balance curves of all strategy variants, using detrended trade results and no trade costs. Note down the profit <strong>P</strong> of the best strategy.</li>
<li>Detrend all balance curves by subtracting the mean return per bar (not to be confused with detrending the trade results!). This way you get a series of curves with the same characteristics of the tested systems, but zero profit.</li>
<li>Randomize all curves by bootstrap with replacement. This produces new curves from the random returns of the old curves. Because the same bars can be selected multiple times, most new curves now produce losses or profits different from zero.</li>
<li>Select the best performer from the randomized curves, and note down its profit.</li>
<li> Repeat steps 4 and 5 a couple 1000 times.</li>
<li>You now have a list of several 1000 best profits. The median <strong>M</strong> of that list is the Data Mining Bias by your strategy development process.</li>
<li>Check where the original best profit <strong>P</strong> appears in the list. The percentage of best bootstrap profits greater than <strong>P</strong> is the so-called <strong>p-Value</strong> of the best strategy. You want the p-Value to be as low as possible. If <strong>P</strong> is better than 95% of the best bootstrap profits, the best strategy has a real edge with 95% probability.</li>
<li><strong>P</strong> minus <strong>M</strong> minus trade costs is the result to be expected in real trading the best strategy.</li>
</ol>
<p>The method is not really intuitive, but mathematically sound. However, it suffers from a couple problems that makes WRC difficult to use  in real strategy development:</p>
<ul style="list-style-type: square;">
<li>You can see the worst problem already in step 1. During strategy development you&#8217;re permanently testing ideas, adding or removing parameters, or checking out different assets and time frames. Putting aside all discarded variants and producing balance curves of all combinations of them is a cumbersome process. It gets even more diffcult with machine learning algorithms that optimize weight factors and usually do not produce discarded variants. However, the good news are that you can easily apply the WRC when your strategy variants are produced by a transparent mechanical process with no human decisions involved. That&#8217;s fortunately the case for our trend experiment.</li>
<li>WRC tends to type II errors. That means it can reject strategies although they have an edge. When more irrelevant variants &#8211; systems with random trading and zero profit expectancy &#8211; are added to the pool,  more positive results can be produced in steps 4 and 5, which reduces the probability that your selected strategy survives the test. WRC can determine rather good that a system is profitable, but can not as well determine that it is worthless.</li>
<li>It gets worse when variants have a negative expectancy.  WRC can then over-estimate Data Mining Bias (see paper 2 at the end of the article). This could theoretically also happen with our trend systems, as some variants may suffer from a phase reversal due to the delay by the smoothing indicators, and thus in fact trade against the trend instead of with it.</li>
</ul>
<h3>The Experiment</h3>
<p>First you need to collect daily return curves from all tested strategies. This requires adding a few lines to the <strong>Trend.c</strong> script from the <a href="http://www.financial-hacker.com/trend-and-exploiting-it/">previous article</a>:</p>
<pre class="prettyprint"><span style="color: #0000ff;">// some global variables</span>
int Period;
var Daily[3000];
...
<span style="color: #0000ff;">// in the run function, set all trading costs to zero</span>
 Spread = Commission = RollLong = RollShort = Slippage = 0;<span style="color: #0000ff;">
...
// store daily results in an equity curve</span>
  Daily[Day] = Equity;
}
...
<span style="color: #0000ff;">// in the objective function, save the curves in a file for later evaluation</span>
string FileName = "Log\\TrendDaily.bin";
string Name = strf("%s_%s_%s_%i",Script,Asset,Algo,Period);
int Size = Day*sizeof(var); 
file_append(FileName,Name,strlen(Name)+1);
file_append(FileName,&amp;Size,sizeof(int));
file_append(FileName,Daily,Size);</pre>
<p>The second part of the above code stores the equity at the end of any day in the <strong>Daily</strong> array. The third part stores a string with the name of the strategy, the length of the curve,  and the equity values itself in a file named <strong>TrendDaily.bin</strong> in the <strong>Log</strong> folder. After running the 10 trend scripts, all 900 resulting curves are collected together in the file.</p>
<p>The next part of our experiment is the <strong>Bootstrap.c</strong> script that applies White&#8217;s Reality Check. I&#8217;ll write it in two parts. The first part just reads the 900 curves from the <strong>TrendDaily.bin</strong> file, stores them for later evaluation, finds the best one and displays a histogram of the profit factors. Once we got that, we did already 80% of the work for the Reality Check. This is the code:</p>
<pre class="prettyprint">void _plotHistogram(string Name,var Value,var Step,int Color)
{
  var Bucket = floor(Value/Step);
  plotBar(Name,Bucket,Step*Bucket,1,SUM+BARS+LBL2,Color);
}

typedef struct curve
{
  string Name;
  int Length;
  var *Values;
} curve;

curve Curve[900];
var Daily[3000];

void main()
{
  byte *Content = file_content("Log\\TrendDaily.bin");
  int i,j,N = 0;
  int MaxN = 0;
  var MaxPerf = 0.0;
	
  while(N&lt;900 &amp;&amp; *Content)
  {
<span style="color: #0000ff;">// extract the next curve from the file</span>
    string Name = Content;
    Content += strlen(Name)+1;
    int Size = *((int*)Content);
    int Length = Size/sizeof(var); // number of values
    Content += 4;
    var *Values = Content;
    Content += Size;

<span style="color: #0000ff;">// store and plot the curve</span>		
    Curve[N].Name = Name;
    Curve[N].Length = Length;
    Curve[N].Values = Values;
    var Performance = 1.0/ProfitFactor(Values,Length);
    printf("\n%s: %.2f",Name,Performance);
    _plotHistogram("Profit",Performance,0.005,RED);

<span style="color: #0000ff;">// find the best curve</span>		
    if(MaxPerf &lt; Performance) {
      MaxN = N; MaxPerf = Performance;
    }
    N++;
  }
  printf("\n\nBenchmark: %s, %.2f",Curve[MaxN].Name,MaxPerf); 
}</pre>
<p>Most of the code is just for reading and storing all the equity curves. The indicator <strong>ProfitFactor </strong>calculates the profit factor of the curve, the sum of all daily wins divided by the sum of all daily losses. However, here we need to consider the array order. Like many platforms, Zorro stores time series in reverse chronological order,  with the most recent data at the begin. However we stored the daily equity curve in straight chronological order. So the losses are actually wins and the wins actually losses, which is why we need to inverse the profit factor. The curve with the best profit factor will be our benchmark for the test.</p>
<p>This is the resulting histogram, the profit factors of all 900 (or rather, 705 due to the trade number minimum) equity curves:</p>
<figure id="attachment_244" aria-describedby="caption-attachment-244" style="width: 833px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/trend_s.png"><img decoding="async" class="wp-image-244 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/trend_s.png" alt="" width="833" height="201" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/trend_s.png 833w, https://financial-hacker.com/wp-content/uploads/2015/09/trend_s-300x72.png 300w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a><figcaption id="caption-attachment-244" class="wp-caption-text">Profit factor distribution (without trade costs)</figcaption></figure>
<p>Note that the profit factors are slightly different to the parameter charts of the previous article because they were now calculated from daily returns, not from trade results. We removed trading costs, so the histogram is centered at a profit factor 1.0, aka zero profit. Only a few systems achieved a profit factor in the 1.2 range, the two best made about 1.3. Now we&#8217;ll see what White has to say to that. This is the rest of the <strong>main</strong> function in <strong>Bootstrap.c</strong> that finally applies his Reality Check:</p>
<pre>plotBar("Benchmark",MaxPerf/0.005,MaxPerf,50,BARS+LBL2,BLUE);	
printf("\nBootstrap - please wait");
int Worse = 0, Better = 0;
for(i=0; i&lt;1000; i++) {
  var MaxBootstrapPerf = 0;
  for(j=0; j&lt;N; j++) {
    randomize(BOOTSTRAP|DETREND,Daily,Curve[j].Values,Curve[j].Length);
    var Performance = 1.0/ProfitFactor(Daily,Curve[j].Length);
    MaxBootstrapPerf = max(MaxBootstrapPerf,Performance);
  }
  if(MaxPerf &gt; MaxBootstrapPerf)
    Better++;
  else
    Worse++;
  _plotHistogram("Profit",MaxBootstrapPerf,0.005,RED);
  progress(100*i/SAMPLES,0);
}
printf("\nBenchmark beats %.0f%% of samples!",
  (var)Better*100./(Better+Worse));
</pre>
<p>This code needs about 3 minutes to run; we&#8217;re sampling the 705 curves 1000 times. The <strong>randomize</strong> function will shuffle the daily returns by bootstrap with replacement; the <strong>DETREND</strong> flag tells it to subtract the mean return from all returns before. The number of random curves that are better and worse than the benchmark is stored, for printing the percentage at the end. The <strong>progress</strong> function moves the progress bar while Zorro grinds through the 705,000 curves. And this is the result:</p>
<figure id="attachment_245" aria-describedby="caption-attachment-245" style="width: 703px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2015/09/bootstrap_s.png"><img loading="lazy" decoding="async" class="wp-image-245 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2015/09/bootstrap_s.png" alt="" width="703" height="201" srcset="https://financial-hacker.com/wp-content/uploads/2015/09/bootstrap_s.png 703w, https://financial-hacker.com/wp-content/uploads/2015/09/bootstrap_s-300x86.png 300w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px" /></a><figcaption id="caption-attachment-245" class="wp-caption-text">Bootstrap results (red), benchmark system (black)</figcaption></figure>
<p>Hmm. We can see that the best system &#8211; the black bar &#8211; is at the right side of the histogram, indicating that it might be significant. But only with about 80% probability (the script gives a slightly different result every time due to the randomizing). 20% of the random curves achieve better profit factors than the best system from the experiment. The median of the randomized samples is about 1.26. Only the two best systems from the original distribution (first image) have profit factors above 1.26 &#8211; all the rest is at or below the bootstrap median.</p>
<p>So we have to conclude that this simple way of trend trading does not really work. Interestingly, one of those 900 tested systems is a system that I use for myself since 2012, although with additional filters and conditions. This system has produced good live returns and a positive result by the end of every year so far. And there&#8217;s still the fact that EUR/USD and silver in all variants produced better statistics than S&amp;P500. This hints that some trend effect exists in their price curves, but the profit factors by the simple algorithms are not high enough to pass White&#8217;s Reality Check. We need a better approach for trend exploitation. For instance, a filter that detects if trend is there or not. This will be the topic of the <a href="http://www.financial-hacker.com/the-market-meanness-index/" target="_blank" rel="noopener noreferrer">next articl</a>e of this series. We will see that a filter can have a surprising effect on reality checks. Since we now have the <strong>Bootstrap </strong>script for applying White&#8217;s Reality Check, we can quickly do further experiments.</p>
<p>The <strong>Bootstrap.c</strong> script has been added to the 2015 script collection downloadable on the sidebar.</p>
<h3>Conclusion</h3>
<ul style="list-style-type: square;">
<li>None of the 10 tested low-lag indicators, and none of the 3 tested markets shows significant positive expectancy with trend trading.</li>
<li>There is evidence of a trend effect in currencies and commodities, but it is too weak or too infrequent for being effectively exploited with simple trade signals by a filtered price curve.</li>
<li>We have now a useful code framework for comparing indicators and assets, and for further experiments with trade strategies.</li>
</ul>
<h3>Papers</h3>
<ol>
<li>Original paper by Dr. H. White:  <a href="http://www.ssc.wisc.edu/~bhansen/718/White2000.pdf" target="_blank" rel="noopener noreferrer">White2000</a></li>
<li>WRC modification by P. Hansen: <a href="http://www-siepr.stanford.edu/workp/swp05003.pdf" target="_blank" rel="noopener noreferrer">Hansen2005</a></li>
<li>Stepwise WRC Testing by J. Romano, M. Wolf: <a href="http://www.ssc.wisc.edu/~bhansen/718/RomanoWolf2005.pdf" target="_blank" rel="noopener noreferrer">RomanoWolf2005</a></li>
<li>Technical Analysis examined with WRC, by P. Hsu, C. Kuan: <a href="http://front.cc.nctu.edu.tw/Richfiles/15844-930305.pdf" target="_blank" rel="noopener noreferrer">HsuKuan2006</a></li>
<li>WRC and its Extensions by V. Corradi, N. Swanson: <a href="http://econweb.rutgers.edu/nswanson/papers/corradi_swanson_whitefest_1108_2011_09_06.pdf" target="_blank" rel="noopener noreferrer">CorradiSwanson2011</a></li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/whites-reality-check/feed/</wfw:commentRss>
			<slash:comments>32</slash:comments>
		
		
			</item>
	</channel>
</rss>
