<?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>Python &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/python/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>Python &#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>
	</channel>
</rss>
