<?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>MxNet &#8211; The Financial Hacker</title>
	<atom:link href="https://financial-hacker.com/tag/mxnet/feed/" rel="self" type="application/rss+xml" />
	<link>https://financial-hacker.com</link>
	<description>A new view on algorithmic trading</description>
	<lastBuildDate>Sat, 01 Jun 2019 15:31:13 +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>MxNet &#8211; The Financial Hacker</title>
	<link>https://financial-hacker.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Deep Learning Systems for Bitcoin 1</title>
		<link>https://financial-hacker.com/deep-learning-systems-for-bitcoins-part-1/</link>
					<comments>https://financial-hacker.com/deep-learning-systems-for-bitcoins-part-1/#comments</comments>
		
		<dc:creator><![CDATA[jcl]]></dc:creator>
		<pubDate>Wed, 27 Dec 2017 10:51:27 +0000</pubDate>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[No Math]]></category>
		<category><![CDATA[System Development]]></category>
		<category><![CDATA[Autoencoder]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[Blockchain]]></category>
		<category><![CDATA[Boltzmann machine]]></category>
		<category><![CDATA[Cryptocurrency]]></category>
		<category><![CDATA[Deepnet]]></category>
		<category><![CDATA[Economy]]></category>
		<category><![CDATA[H2O]]></category>
		<category><![CDATA[Keras]]></category>
		<category><![CDATA[Money]]></category>
		<category><![CDATA[MxNet]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[Tensorflow]]></category>
		<guid isPermaLink="false">http://www.financial-hacker.com/?p=2899</guid>

					<description><![CDATA[Since December 2017, bitcoins can not only be traded at more or less dubious exchanges, but also as futures at the CME and CBOE. And already several trading systems popped up for bitcoin and other cryptocurrencies. None of them can claim big success, with one exception. There is a very simple strategy that easily surpasses &#8230; <a href="https://financial-hacker.com/deep-learning-systems-for-bitcoins-part-1/" class="more-link">Continue reading<span class="screen-reader-text"> "Deep Learning Systems for Bitcoin 1"</span></a>]]></description>
										<content:encoded><![CDATA[<p>Since December 2017, bitcoins can not only be traded at more or less dubious exchanges, but also as futures at the CME and CBOE. And already several trading systems popped up for bitcoin and other cryptocurrencies. None of them can claim big success, with one exception. There is a very simple strategy that easily surpasses all other bitcoin systems and probably also all known historical trading systems. Its name: <strong>Buy and Hold</strong>. In the light of the extreme success of that particular bitcoin strategy, do we really need any other trading system for cryptos?<span id="more-2899"></span></p>
<h3>Bitcoin &#8211; hodl??</h3>
<p>A buy and hold strategy works extremely well when a price bubble grows, and extremely bad when it bursts. And indeed, apparently all finance and economy gurus (well, all but <a href="https://www.rt.com/news/411379-john-mcafee-bitcoin-prediction/" target="_blank" rel="noopener noreferrer">John McAfee</a>) tell you that the cryptocurrency market, and especially bitcoin, is a bubble, even a &#8220;scam with no substantial worth&#8221;, and will soon experience a crash &#8220;worse than the 17th century tulip mania&#8221; or the &#8220;18th century South Sea Company fraud&#8221;.</p>
<figure id="attachment_2917" aria-describedby="caption-attachment-2917" style="width: 681px" class="wp-caption alignnone"><a href="http://www.financial-hacker.com/wp-content/uploads/2017/12/bitcoin.png"><img fetchpriority="high" decoding="async" class="wp-image-2917 size-full" src="http://www.financial-hacker.com/wp-content/uploads/2017/12/bitcoin.png" alt="" width="681" height="321" srcset="https://financial-hacker.com/wp-content/uploads/2017/12/bitcoin.png 681w, https://financial-hacker.com/wp-content/uploads/2017/12/bitcoin-300x141.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-2917" class="wp-caption-text">Bubble or not?</figcaption></figure>
<p>By definition, a bubble is a price largely above the &#8216;real value&#8217; or &#8216;fair value&#8217; of an asset, and it bursts when people realize that. So what is the fair value of a bitcoin? Obviously not zero, since blockchain based currencies have (aside from their disadvantages) several advantages over traditional currencies, on the economy level as well as on the private level. Such as:</p>
<ul style="list-style-type: square;">
<li>They break the <a href="http://www.financial-hacker.com/money-and-how-to-get-it/" target="_blank" rel="noopener noreferrer">link of money and debt</a>. Cryptocurrencies don&#8217;t require the bank credit mechanism for money creation.</li>
<li>They can be used where normal money would be impractical, such as fee transfers between machines or trading in multiplayer games.</li>
<li>They allow low-cost and anonymous money transactions. At least in theory.</li>
<li>They replace banks for storing and mattresses for stashing money.</li>
</ul>
<p>I&#8217;m ready to believe that blockchain is the future of money transfer and storage. But that does not mean an ever-rising bitcoin price. Hundreds of cryptocurrencies came out in the last two years, any single of them with a better blockchain technology than bitcoin, and any good programmer can add a new coin anytime. Few will survive. Countries or big companies might sooner or later issue their own crypto tokens, as Venezuela already is attempting. The release of an official blockchain Dollar, Yuan, or Euro would leave the old bitcoin with its energy hungry transaction algorithm in thin air. Thus, when investing in bitcoin, we should not hope for a rosy future, but look for its present &#8216;real value&#8217;.</p>
<p>Due to its extreme volatility, bitcoin can not replace bank tresors. But it is already used in some situations for reducing money transfer costs, since the miners get any transaction rewarded in bitcoin. And above all, anonymity can be a substantial motive to own it. When you need a hacker to delete your drunk driving record, pay her in bitcoin. But how big is the online market for illegal hacker jobs, kill contracts, money laundering, drugs, weapons, or pro-Trump facebook advertisements? No one knows, but when we compare it with cash, another form of anonymous payment, we get interesting results.</p>
<p>The current cash in circulation in the US is approximately $1.5 trillion dollars. And the current bitcoin supply, about 17 million bitcoins, represents a total value of about $250 billion. Which means that you can already replace 15% of all US cash with bitcoin! Not to mention all the other cryptos. I fear that this supply already exceeds the demand of anonymous online payment for today and also the next future.</p>
<p>For those reasons, a bitcoin &#8220;hodl&#8221; system, despite its extreme historical performance, is high risk. We don&#8217;t know when and how the bubble will burst &#8211; maybe bitcoin will go up to $100,000 before &#8211; but we have some reason to suspect that at some point sooner or later the bitcoin price might drop like a stone down to its &#8216;real value&#8217;. Which is unknown, but for practical purposes is probably not in the $15,000 area, but more like $15.</p>
<p>So we need some other method to tackle the cryptocurrency trading problem. The first question: Has the crypto market already developed price curve inefficiencies that can be exploited in a trading system? In <strong>(1)</strong> we see some tests with basic bitcoin strategies. Our own tests came to the same results. Momentum based strategies can work, and <a href="http://www.financial-hacker.com/get-rich-slowly/" target="_blank" rel="noopener noreferrer">mean-variance optimizing</a>&nbsp;portfolio systems can achieve even extreme returns with crytrocurrencies &#8211; up to 10 times higher than &#8220;hodl&#8221;. But that&#8217;s not really surprising due to the high momentums and volatilities of crypto coins. The problem is that all crypto portfolios are exposed to high risk. Other conventional model-based strategies don&#8217;t work well anyway with cryptos.</p>
<p>When we concentrate on bitcoin, our proposed system must be a fast trading, trend-agnostic strategy. That means it holds positions only a few minutes, and is not exposed to the bubble risk. I can already tell that short-term mean reversion &#8211; even with a more sophisticated system as in <strong>(1)</strong> &#8211; produces no good result with cryptos. So only a few possibilities remain. One of them is exploiting short-term price patterns. This is the strategy that we will develop. And I can already tell that it works. But for this we&#8217;ll need a deep machine learning system for detecting the patterns and determining their rules.</p>
<h3>Selecting a machine learning library</h3>
<p>The basic structure of such a machine learning system is described <a href="http://www.financial-hacker.com/build-better-strategies-part-5-developing-a-machine-learning-system/" target="_blank" rel="noopener noreferrer">here</a>. Due to the low signal-to-noise ratio and to ever-changing market conditions, analyzing price series is one of the most ambitious tasks for machine learning. Compared with other AI algorithms, deep learning systems have the highest success rate. Since we can connect any <a href="http://www.financial-hacker.com/hackers-tools-zorro-and-r/" target="_blank" rel="noopener noreferrer">Zorro</a> based trading script to the data analysis software R, we&#8217;ll use a R based deep learning package. There are meanwhile many available. Here&#8217;s the choice:</p>
<ul style="list-style-type: square;">
<li><strong>Deepnet</strong>, a lightweight and straightforward neural net library with a stacked autoencoder and a Boltzmann machine. Produces good results when the feature set is not too complex. The basic train and predict functions for using a deepnet autoencoder in a Zorro strategy:<!--?prettify linenums=true?-->
<pre class="prettyprint">library('deepnet') 

neural.train = function(model,XY) 
{
  XY &lt;- as.matrix(XY)
  X &lt;- XY[,-ncol(XY)]
  Y &lt;- XY[,ncol(XY)]
  Y &lt;- ifelse(Y &gt; 0,1,0)
  Models[[model]] &lt;&lt;- sae.dnn.train(X,Y,
      hidden = c(30), 
      learningrate = 0.5, 
      momentum = 0.5, 
      learningrate_scale = 1.0, 
      output = "sigm", 
      sae_output = "linear", 
      numepochs = 100, 
      batchsize = 100)
}

neural.predict = function(model,X) 
{
  if(is.vector(X)) X &lt;- t(X)
  return(nn.predict(Models[[model]],X))
}
</pre>
</li>
<li><strong>H2O</strong>, an open-source software package with the ability to run on distributed computer systems. Coded in Java, so the latest version of the JDK is required. Aside from deep autoencoders, many other machine learning algorithms are supported, such as random forests. Features can be preselected, and ensembles can be created. Disadvantage: While batch training is fast, predicting a single sample, as usually needed in a trading strategy, is relatively slow due to the server/client concept. The basic <strong>H2O</strong> train and predict functions for Zorro:<!--?prettify linenums=true?-->
<pre class="prettyprint">library('h2o') 
# also install the Java JDK

neural.train = function(model,XY) 
{
  XY &lt;- as.h2o(XY)
  Models[[model]] &lt;&lt;- h2o.deeplearning(
    -ncol(XY),ncol(XY),XY,
    hidden = c(30),  seed = 365)
}

neural.predict = function(model,X) 
{
  if(is.vector(X)) X &lt;- as.h2o(as.data.frame(t(X)))
  else X &lt;- as.h2o(X)
  Y &lt;- h2o.predict(Models[[model]],X)
  return(as.vector(Y))
}</pre>
</li>
<li><strong>Tensorflow</strong> in its <strong>Keras</strong> incarnation, a neural network kit by Google. Supports CPU and GPU and comes with all needed modules for tensor arithmetics, activation and loss functions, covolution kernels, and backpropagation algorithms. So you can build your own neural net structure. <strong>Keras</strong> offers a simple interface for that.
<p>Keras is available as a R library, but installing it requires also a Python environment. First install Anaconda from <a href="https://www.anaconda.com">www.anaconda.com</a>. Open the Anaconda Navigator and install the RStudio application (installing Keras outside an Anaconda environment fails on some PCs with an error message). Then open Rstudio inside the Navigator, install the Keras package, then finally execute library(&#8216;keras&#8217;) and install_keras(). These steps usually succeed.</p>
<p>The <strong>Keras</strong> train and predict functions for Zorro:<!--?prettify linenums=true?--></p>
<pre class="prettyprint">library('keras')
#needs Python 3.6 and Anaconda
#call install_keras() after installing the package

neural.train = function(model,XY) 
{
  X &lt;- data.matrix(XY[,-ncol(XY)])
  Y &lt;- XY[,ncol(XY)]
  Y &lt;- ifelse(Y &gt; 0,1,0)
  Model &lt;- keras_model_sequential() 
  Model %&gt;% 
    layer_dense(units=30,activation='relu',input_shape = c(ncol(X))) %&gt;% 
    layer_dropout(rate = 0.2) %&gt;% 
    layer_dense(units = 1, activation = 'sigmoid')
  
  Model %&gt;% compile(
    loss = 'binary_crossentropy',
    optimizer = optimizer_rmsprop(),
    metrics = c('accuracy'))
  
  Model %&gt;% fit(X, Y, 
    epochs = 20, batch_size = 20, 
    validation_split = 0, shuffle = FALSE)
  
  Models[[model]] &lt;&lt;- Model
}

neural.predict = function(model,X) 
{
  if(is.vector(X)) X &lt;- t(X)
  X &lt;- as.matrix(X)
  Y &lt;- Models[[model]] %&gt;% predict_proba(X)
  return(ifelse(Y &gt; 0.5,1,0))
}
</pre>
</li>
<li><strong>MxNet</strong>, Amazon&#8217;s answer on Google&#8217;s Tensorflow. Offers also tensor arithmetics and neural net building blocks on CPU and GPU, as well as high level network functions similar to Keras (the next Keras version will also support MxNet). Just as with Tensorflow, CUDA is supported, but not (yet) OpenCL, so you&#8217;ll need a Nvidia graphics card to enjoy GPU support. In direct comparison <strong>(2)</strong>, MxNet was reported to be less resource hungry and a bit faster than Tensorflow, but so far I could not confirm this. The standard train and predict functions:<!--?prettify linenums=true?-->
<pre class="prettyprint"># how to install the CPU version:
#cran &lt;- getOption("repos")
#cran["dmlc"] &lt;- "https://s3-us-west-2.amazonaws.com/apache-mxnet/R/CRAN/"
#options(repos = cran)
#install.packages('mxnet')
library('mxnet')

neural.train = function(model,XY) 
{
  X &lt;- data.matrix(XY[,-ncol(XY)])
  Y &lt;- XY[,ncol(XY)]
  Y &lt;- ifelse(Y &gt; 0,1,0)
  Models[[model]] &lt;&lt;- mx.mlp(X,Y,
       hidden_node = c(30), 
       out_node = 2, 
       activation = "sigmoid",
       out_activation = "softmax",
       num.round = 20,
       array.batch.size = 20,
       learning.rate = 0.05,
       momentum = 0.9,
       eval.metric = mx.metric.accuracy)
}

neural.predict = function(model,X) 
{
  if(is.vector(X)) X &lt;- t(X)
  X &lt;- data.matrix(X)
  Y &lt;- predict(Models[[model]],X)
  return(ifelse(Y[1,] &gt; Y[2,],0,1))
}
</pre>
</li>
</ul>
<p>By replacing the <strong>neural.train</strong> and <strong>neural.predict</strong> functions, and other functions for saving and loading models that are not listed here, you can run the same strategy with different deep learning packages and compare. We&#8217;re currently using Keras for most machine learning strategies, and I&#8217;ll also use it for the short-term bitcoin trading system presented in the upcoming 2nd part of this article. There is no bitcoin futures data available yet, so tick based price data from several bitcoin exchanges will have to do for the backtest.</p>
<p>I&#8217;ve uploaded the interface scripts for Deepnet, H2O, Tensorflow/Keras, and MxNet to the 2018 script repository, so you can run your own deep learning experiments and compare the packages. Here&#8217;s a Zorro script for downloading bitcoin prices from Quandl &#8211; EOD only, though, since the exchanges demand dear payment for their tick data.</p>
<pre class="prettyprint">void main()
{
  assetHistory("BITFINEX/BTCUSD",FROM_QUANDL);
}</pre>
<p>You can also get Bitcoin M1 data from Kaggle in CSV format. Here&#8217;s a Zorro script for converting it to a Zorro T6 dataset:</p>
<pre class="prettyprint">void main()
{
	string InName = "History\\bitstampUSD_1-min_data_2012-01-01_to_2019-03-13.csv";
	string Format = "+%t,f3,f1,f2,f4,f6";
	dataParse(1,Format,InName); 
	dataSave(1,"History\\BTCUSD.t6");
}</pre>
<h3>Further reading</h3>
<p>(1) Nicolas Rabener, <a href="https://www.factorresearch.com/research-quant-strategies-in-the-cryptocurrency-space" target="_blank" rel="noopener noreferrer">Quant Strategies in the Cryptocurrency Space</a></p>
<p>(2) Julien Simon, <a href="https://medium.com/@julsimon/keras-shoot-out-tensorflow-vs-mxnet-51ae2b30a9c0" target="_blank" rel="noopener noreferrer">Tensorflow vs MxNet</a></p>
<p>(3) Zachary Lipton et al, <a href="https://github.com/zackchase/mxnet-the-straight-dope" target="_blank" rel="noopener noreferrer">MxNet &#8211; The Straight Dope</a><br />
(Good introduction in deep learning with MxNet / Gluon examples)</p>
<p>(4) F.Chollet/J.J.Allaire, Deep Learning with R<br />
(Excellent introduction in Keras)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://financial-hacker.com/deep-learning-systems-for-bitcoins-part-1/feed/</wfw:commentRss>
			<slash:comments>42</slash:comments>
		
		
			</item>
	</channel>
</rss>
