Files
catalyst/beginner-tutorial.html
T
2017-11-06 16:42:19 -07:00

802 lines
52 KiB
HTML

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Catalyst Beginner Tutorial &mdash; Catalyst 0.3 documentation</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="top" title="Catalyst 0.3 documentation" href="index.html"/>
<link rel="next" title="Catalyst &amp; Jupyter Notebook" href="jupyter.html"/>
<link rel="prev" title="Install" href="install.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-nav-search">
<a href="index.html" class="icon icon-home"> Catalyst
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="install.html">Install</a><ul>
<li class="toctree-l2"><a class="reference internal" href="install.html#installing-with-pip">Installing with <code class="docutils literal"><span class="pre">pip</span></code></a><ul>
<li class="toctree-l3"><a class="reference internal" href="install.html#gnu-linux">GNU/Linux</a></li>
<li class="toctree-l3"><a class="reference internal" href="install.html#osx">OSX</a><ul>
<li class="toctree-l4"><a class="reference internal" href="install.html#osx-virtualenv-matplotlib">OSX + virtualenv + matplotlib</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="install.html#windows">Windows</a></li>
<li class="toctree-l3"><a class="reference internal" href="install.html#amazon-linux-ami">Amazon Linux AMI</a></li>
<li class="toctree-l3"><a class="reference internal" href="install.html#troubleshooting-pip-install">Troubleshooting <code class="docutils literal"><span class="pre">pip</span></code> Install</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="install.html#installing-with-conda">Installing with <code class="docutils literal"><span class="pre">conda</span></code></a><ul>
<li class="toctree-l3"><a class="reference internal" href="install.html#troubleshooting-conda-install">Troubleshooting <code class="docutils literal"><span class="pre">conda</span></code> Install</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="install.html#getting-help">Getting Help</a></li>
</ul>
</li>
<li class="toctree-l1 current"><a class="current reference internal" href="">Catalyst Beginner Tutorial</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#basics">Basics</a></li>
<li class="toctree-l2"><a class="reference internal" href="#my-first-algorithm">My first algorithm</a></li>
<li class="toctree-l2"><a class="reference internal" href="#running-the-algorithm">Running the algorithm</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#ingesting-data">Ingesting data</a></li>
<li class="toctree-l3"><a class="reference internal" href="#command-line-interface">Command line interface</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="#access-to-previous-prices-using-history">Access to previous prices using <code class="docutils literal"><span class="pre">history</span></code></a><ul>
<li class="toctree-l3"><a class="reference internal" href="#working-example-dual-moving-average-cross-over">Working example: Dual Moving Average Cross-Over</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="#conclusions">Conclusions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="jupyter.html">Catalyst &amp; Jupyter Notebook</a><ul>
<li class="toctree-l2"><a class="reference internal" href="jupyter.html#install">Install</a></li>
<li class="toctree-l2"><a class="reference internal" href="jupyter.html#running-algorithms">Running Algorithms</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="live-trading.html">Live Trading</a><ul>
<li class="toctree-l2"><a class="reference internal" href="live-trading.html#supported-exchanges">Supported Exchanges</a></li>
<li class="toctree-l2"><a class="reference internal" href="live-trading.html#authentication">Authentication</a></li>
<li class="toctree-l2"><a class="reference internal" href="live-trading.html#currency-symbols">Currency Symbols</a></li>
<li class="toctree-l2"><a class="reference internal" href="live-trading.html#trading-an-algorithm">Trading an Algorithm</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="naming-convention.html">Naming Convention</a></li>
<li class="toctree-l1"><a class="reference internal" href="videos.html">Videos</a><ul>
<li class="toctree-l2"><a class="reference internal" href="videos.html#installation-macos">Installation: MacOS</a></li>
<li class="toctree-l2"><a class="reference internal" href="videos.html#installation-windows">Installation: Windows</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="resources.html">Resources</a><ul>
<li class="toctree-l2"><a class="reference internal" href="resources.html#related-3rd-party-apis">Related 3rd Party APIs</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="development-guidelines.html">Development Guidelines</a><ul>
<li class="toctree-l2"><a class="reference internal" href="development-guidelines.html#creating-a-development-environment">Creating a Development Environment</a></li>
<li class="toctree-l2"><a class="reference internal" href="development-guidelines.html#git-branching-structure">Git Branching Structure</a></li>
<li class="toctree-l2"><a class="reference internal" href="development-guidelines.html#contributing-to-the-docs">Contributing to the Docs</a></li>
<li class="toctree-l2"><a class="reference internal" href="development-guidelines.html#commit-messages">Commit messages</a></li>
<li class="toctree-l2"><a class="reference internal" href="development-guidelines.html#formatting-docstrings">Formatting Docstrings</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="releases.html">Release Notes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3-6">Version 0.3.6</a><ul>
<li class="toctree-l3"><a class="reference internal" href="releases.html#bug-fixes">Bug Fixes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3-5">Version 0.3.5</a><ul>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id1">Bug Fixes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3-4">Version 0.3.4</a><ul>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id2">Bug Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="releases.html#build">Build</a></li>
<li class="toctree-l3"><a class="reference internal" href="releases.html#documentation">Documentation</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3-3">Version 0.3.3</a><ul>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id4">Bug Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id5">Build</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3-2">Version 0.3.2</a><ul>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id6">Bug Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id7">Build</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3-1">Version 0.3.1</a><ul>
<li class="toctree-l3"><a class="reference internal" href="releases.html#id8">Bug Fixes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-3">Version 0.3</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-2-dev5">Version 0.2.dev5</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-2-dev4">Version 0.2.dev4</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-2-dev3">Version 0.2.dev3</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-2-dev2">Version 0.2.dev2</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-2-dev1">Version 0.2.dev1</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-1-dev9">Version 0.1.dev9</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-1-dev8">Version 0.1.dev8</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-1-dev7">Version 0.1.dev7</a></li>
<li class="toctree-l2"><a class="reference internal" href="releases.html#version-0-1-dev6">Version 0.1.dev6</a></li>
</ul>
</li>
</ul>
</div>
&nbsp;
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="index.html">Catalyst</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="index.html">Docs</a> &raquo;</li>
<li>Catalyst Beginner Tutorial</li>
<li class="wy-breadcrumbs-aside">
<a href="_sources/beginner-tutorial.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document">
<div class="section" id="catalyst-beginner-tutorial">
<h1>Catalyst Beginner Tutorial<a class="headerlink" href="#catalyst-beginner-tutorial" title="Permalink to this headline"></a></h1>
<div class="section" id="basics">
<h2>Basics<a class="headerlink" href="#basics" title="Permalink to this headline"></a></h2>
<p>Catalyst is an open-source algorithmic trading simulator for crypto
assets written in Python.</p>
<p>The source can be found at: <a class="reference external" href="https://github.com/enigmampc/catalyst">https://github.com/enigmampc/catalyst</a></p>
<p>Some benefits include:</p>
<ul class="simple">
<li>Support for several of the top crypto-exchanges by trading volume.</li>
<li>Realistic: slippage, transaction costs, order delays.</li>
<li>Stream-based: Process each event individually, avoids look-ahead
bias.</li>
<li>Batteries included: Common transforms (moving average) as well as
common risk calculations (Sharpe).</li>
<li>Developed and continuously updated by
<a class="reference external" href="https://www.enigma.co">Enigma MPC</a> which is building the Enigma
data marketplace protocol as well as Catalyst, the first application
that will run on our protocol. Powered by our financial data
marketplace, Catalyst empowers users to share and curate data and
build profitable, data-driven investment strategies.</li>
</ul>
<p>This tutorial assumes that you have Catalyst correctly installed, see the
<a class="reference internal" href="install.html"><em>installation instructions</em></a> if you haven&#8217;t set up
Catalyst yet.</p>
<p>Every <code class="docutils literal"><span class="pre">catalyst</span></code> algorithm consists of at least two functions you have to
define:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">initialize(context)</span></code></li>
<li><code class="docutils literal"><span class="pre">handle_data(context,</span> <span class="pre">data)</span></code></li>
</ul>
<p>Before the start of the algorithm, <code class="docutils literal"><span class="pre">catalyst</span></code> calls the
<code class="docutils literal"><span class="pre">initialize()</span></code> function and passes in a <code class="docutils literal"><span class="pre">context</span></code> variable.
<code class="docutils literal"><span class="pre">context</span></code> is a persistent namespace for you to store variables you
need to access from one algorithm iteration to the next.</p>
<p>After the algorithm has been initialized, <code class="docutils literal"><span class="pre">catalyst</span></code> calls the
<code class="docutils literal"><span class="pre">handle_data()</span></code> function once for each event. At every call, it passes
the same <code class="docutils literal"><span class="pre">context</span></code> variable and an event-frame called <code class="docutils literal"><span class="pre">data</span></code>
containing the current trading bar with open, high, low, and close
(OHLC) prices as well as volume for each crypto asset in your universe.</p>
</div>
<div class="section" id="my-first-algorithm">
<h2>My first algorithm<a class="headerlink" href="#my-first-algorithm" title="Permalink to this headline"></a></h2>
<p>Lets take a look at a very simple algorithm from the <code class="docutils literal"><span class="pre">examples</span></code>
directory: <a class="reference external" href="https://github.com/enigmampc/catalyst/blob/master/catalyst/examples/buy_btc_simple.py">buy_btc_simple.py</a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">catalyst.api</span> <span class="kn">import</span> <span class="n">order</span><span class="p">,</span> <span class="n">record</span><span class="p">,</span> <span class="n">symbol</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">context</span><span class="p">):</span>
<span class="n">context</span><span class="o">.</span><span class="n">asset</span> <span class="o">=</span> <span class="n">symbol</span><span class="p">(</span><span class="s">&#39;btc_usd&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">handle_data</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
<span class="n">order</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">record</span><span class="p">(</span><span class="n">btc</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">current</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="s">&#39;price&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>As you can see, we first have to import some functions we would like to
use. All functions commonly used in your algorithm can be found in
<code class="docutils literal"><span class="pre">catalyst.api</span></code>. Here we are using <code class="xref py py-func docutils literal"><span class="pre">order()</span></code> which takes two
arguments: a cryptoasset object, and a number specifying how many assets you would
like to order (if negative, <code class="xref py py-func docutils literal"><span class="pre">order()</span></code> will sell/short
assets). In this case we want to order 1 bitcoin at each iteration.</p>
<p>Finally, the <code class="xref py py-func docutils literal"><span class="pre">record()</span></code> function allows you to save the value
of a variable at each iteration. You provide it with a name for the variable
together with the variable itself: <code class="docutils literal"><span class="pre">varname=var</span></code>. After the algorithm
finished running you will have access to each variable value you tracked
with <code class="xref py py-func docutils literal"><span class="pre">record()</span></code> under the name you provided (we will see this
further below). You also see how we can access the current price data of
a bitcoin in the <code class="docutils literal"><span class="pre">data</span></code> event frame.</p>
</div>
<div class="section" id="running-the-algorithm">
<h2>Running the algorithm<a class="headerlink" href="#running-the-algorithm" title="Permalink to this headline"></a></h2>
<p>To can now test this algorithm on crypto data, <code class="docutils literal"><span class="pre">catalyst</span></code> provides three
interfaces:</p>
<ul class="simple">
<li>A command-line interface,</li>
<li><code class="docutils literal"><span class="pre">IPython</span> <span class="pre">Notebook</span></code> magic,</li>
<li>and <code class="xref py py-func docutils literal"><span class="pre">run_algorithm()</span></code>.</li>
</ul>
<div class="section" id="ingesting-data">
<h3>Ingesting data<a class="headerlink" href="#ingesting-data" title="Permalink to this headline"></a></h3>
<p>In previous versions of Catalyst you needed to manually ingest data before running
your algorithm to make it available at runtime. Starting with version 0.3, the
algorithm will automagically ingest the data it needs the first time that encounters
a data request for data that it doesn&#8217;t have.</p>
<p>Still, we believe it is important for you to have a high-level understanding
of how data is managed:</p>
<ul class="simple">
<li>Pricing data is split and packaged into <code class="docutils literal"><span class="pre">bundles</span></code>: chunks of data organized
as time series that are kept up to date daily on Enigma&#8217;s servers. Catalyst
downloads the bundles that needs at any given time, and reconstructs the whole
dataset in your hard drive.</li>
<li>Pricing data is provided in <code class="docutils literal"><span class="pre">daily</span></code> and <code class="docutils literal"><span class="pre">minute</span></code> resolution. Those are different
bundle datasets, and are managed separately.</li>
<li>Bundles are exchange-specific, as the pricing data is specific to the trades that
happen in each exchange. You can optionally specify which exchange you want pricing
data from.</li>
<li>Catalyst keeps track of all the downloaded bundles, so that it only has to download
them once, and will do incremental updates as needed.</li>
<li>When running in <code class="docutils literal"><span class="pre">live</span> <span class="pre">trading</span></code> mode, Catalyst will first look for historical
pricing data in the locally stored bundles. If there is anything missing, Catalyst will
hit the exchange for the most recent data, and merge it with the local bundle to make
it available for future iterations.</li>
</ul>
<p>If you want to learn more, check out the <a class="reference internal" href="bundles.html#ingesting-data"><span>ingesting data</span></a> section
for more detail.</p>
</div>
<div class="section" id="command-line-interface">
<h3>Command line interface<a class="headerlink" href="#command-line-interface" title="Permalink to this headline"></a></h3>
<p>After you installed Catalyst you should be able to execute the following
from your command line (e.g. <code class="docutils literal"><span class="pre">cmd.exe</span></code> on Windows, or the Terminal app
on OSX). Displaying here a simplified output for eductional purposes:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span>catalyst --help
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre>Usage: catalyst [OPTIONS] COMMAND [ARGS]...
Top level catalyst entry point.
Options:
--version Show the version and exit.
--help Show this message and exit.
Commands:
ingest-exchange Ingest data for the given exchange.
live Trade live with the given algorithm.
run Run a backtest for the given algorithm.
</pre></div>
</div>
<p>There are three main modes you can run on Catalyst. The first being <code class="docutils literal"><span class="pre">ingest-exchange</span></code>
for data ingestion, which we have summarized in the previous section. The second
is <code class="docutils literal"><span class="pre">live</span></code> to use your algorithm to trade live against a given exchange, and the
third mode <code class="docutils literal"><span class="pre">run</span></code> is to backtest your algorithm before trading live with it.</p>
<p>Let&#8217;s start with backtesting, so run this other command to learn more about
the available options:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span>catalyst run --help
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre>Usage: catalyst run [OPTIONS]
Run a backtest for the given algorithm.
Options:
-f, --algofile FILENAME The file that contains the algorithm to run.
-t, --algotext TEXT The algorithm script to run.
-D, --define TEXT Define a name to be bound in the namespace
before executing the algotext. For example
&#39;-Dname=value&#39;. The value may be any python
expression. These are evaluated in order so
they may refer to previously defined names.
--data-frequency [daily|minute]
The data frequency of the simulation.
[default: daily]
--capital-base FLOAT The starting capital for the simulation.
[default: 10000000.0]
-b, --bundle BUNDLE-NAME The data bundle to use for the simulation.
[default: poloniex]
--bundle-timestamp TIMESTAMP The date to lookup data on or before.
[default: &lt;current-time&gt;]
-s, --start DATE The start date of the simulation.
-e, --end DATE The end date of the simulation.
-o, --output FILENAME The location to write the perf data. If this
is &#39;-&#39; the perf will be written to stdout.
[default: -]
--print-algo / --no-print-algo Print the algorithm to stdout.
-x, --exchange-name [poloniex|bitfinex|bittrex]
The name of the targeted exchange
(supported: bitfinex, bittrex, poloniex).
-n, --algo-namespace TEXT A label assigned to the algorithm for data
storage purposes.
-c, --base-currency TEXT The base currency used to calculate
statistics (e.g. usd, btc, eth).
--help Show this message and exit.
</pre></div>
</div>
<p>As you can see there are a couple of flags that specify where to find your
algorithm (<code class="docutils literal"><span class="pre">-f</span></code>) as well as a parameter to specify which exchange to use.
There are also arguments for the date range to run the algorithm over
(<code class="docutils literal"><span class="pre">--start</span></code> and <code class="docutils literal"><span class="pre">--end</span></code>). Finally, you&#8217;ll want to save the performance
metrics of your algorithm so that you can analyze how it performed. This is
done via the <code class="docutils literal"><span class="pre">--output</span></code> flag and will cause it to write the performance
<code class="docutils literal"><span class="pre">DataFrame</span></code> in the pickle Python file format. Note that you can also define
a configuration file with these parameters that you can then conveniently pass
to the <code class="docutils literal"><span class="pre">-c</span></code> option so that you don&#8217;t have to supply the command line args
all the time (see the .conf files in the examples directory).</p>
<p>Thus, to execute our algorithm from above and save the results to
<code class="docutils literal"><span class="pre">buy_btc_simple_out.pickle</span></code> we would call <code class="docutils literal"><span class="pre">catalyst</span> <span class="pre">run</span></code> as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">catalyst</span> <span class="n">run</span> <span class="o">-</span><span class="n">f</span> <span class="n">buy_btc_simple</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">x</span> <span class="n">bitfinex</span> <span class="o">--</span><span class="n">start</span> <span class="mi">2016</span><span class="o">-</span><span class="mi">1</span><span class="o">-</span><span class="mi">1</span> <span class="o">--</span><span class="n">end</span> <span class="mi">2017</span><span class="o">-</span><span class="mi">9</span><span class="o">-</span><span class="mi">30</span> <span class="o">-</span><span class="n">o</span> <span class="n">buy_btc_simple_out</span><span class="o">.</span><span class="n">pickle</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre>INFO: run_algo: running algo in backtest mode
INFO: exchange_algorithm: initialized trading algorithm in backtest mode
INFO: Performance: Simulated 639 trading days out of 639.
INFO: Performance: first open: 2016-01-01 00:00:00+00:00
INFO: Performance: last close: 2017-09-30 23:59:00+00:00
</pre></div>
</div>
<p><code class="docutils literal"><span class="pre">run</span></code> first calls the <code class="docutils literal"><span class="pre">initialize()</span></code> function, and then
streams the historical asset price day-by-day through <code class="docutils literal"><span class="pre">handle_data()</span></code>.
After each call to <code class="docutils literal"><span class="pre">handle_data()</span></code> we instruct <code class="docutils literal"><span class="pre">catalyst</span></code> to order 1
bitcoin. After the call of the <code class="docutils literal"><span class="pre">order()</span></code> function, <code class="docutils literal"><span class="pre">catalyst</span></code>
enters the ordered stock and amount in the order book. After the
<code class="docutils literal"><span class="pre">handle_data()</span></code> function has finished, <code class="docutils literal"><span class="pre">catalyst</span></code> looks for any open
orders and tries to fill them. If the trading volume is high enough for
this asset, the order is executed after adding the commission and
applying the slippage model which models the influence of your order on
the stock price, so your algorithm will be charged more than just the
asset price. (Note, that you can also change the commission and
slippage model that <code class="docutils literal"><span class="pre">catalyst</span></code> uses).</p>
<p>Let&#8217;s take a quick look at the performance <code class="docutils literal"><span class="pre">DataFrame</span></code>. For this, we
use <code class="docutils literal"><span class="pre">pandas</span></code> from inside the IPython Notebook and print the first ten
rows. Note that <code class="docutils literal"><span class="pre">catalyst</span></code> makes heavy usage of
<a class="reference external" href="http://pandas.pydata.org/">pandas</a>, especially for data input and
outputting so it&#8217;s worth spending some time to learn it.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">pandas</span> <span class="kn">as</span> <span class="nn">pd</span>
<span class="n">perf</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">&#39;buy_btc_simple_out.pickle&#39;</span><span class="p">)</span> <span class="c"># read in perf DataFrame</span>
<span class="n">perf</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
<div style="max-height:1000px;max-width:1500px;overflow:auto;">
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>algo_volatility</th>
<th>algorithm_period_return</th>
<th>alpha</th>
<th>benchmark_period_return</th>
<th>benchmark_volatility</th>
<th>beta</th>
<th>btc</th>
<th>capital_used</th>
<th>ending_cash</th>
<th>ending_exposure</th>
<th>...</th>
<th>short_exposure</th>
<th>short_value</th>
<th>shorts_count</th>
<th>sortino</th>
<th>starting_cash</th>
<th>starting_exposure</th>
<th>starting_value</th>
<th>trading_days</th>
<th>transactions</th>
<th>treasury_period_return</th>
</tr>
</thead>
<tbody>
<tr>
<th>2016-01-01 23:59:00+00:00</th>
<td>NaN</td>
<td>0.000000e+00</td>
<td>NaN</td>
<td>-0.010937</td>
<td>NaN</td>
<td>NaN</td>
<td>433.979999</td>
<td>0.000000</td>
<td>1.000000e+07</td>
<td>0.00</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>NaN</td>
<td>1.000000e+07</td>
<td>0.00</td>
<td>0.00</td>
<td>1</td>
<td>[]</td>
<td>0.0227</td>
</tr>
<tr>
<th>2016-01-02 23:59:00+00:00</th>
<td>0.000011</td>
<td>-9.536708e-07</td>
<td>-0.000170</td>
<td>-0.006480</td>
<td>0.173338</td>
<td>-0.000062</td>
<td>432.700000</td>
<td>-442.236708</td>
<td>9.999558e+06</td>
<td>432.70</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>-11.224972</td>
<td>1.000000e+07</td>
<td>0.00</td>
<td>0.00</td>
<td>2</td>
<td>[{u'order_id': u'7869f7828fa140328eb40477bb7de...</td>
<td>0.0227</td>
</tr>
<tr>
<th>2016-01-03 23:59:00+00:00</th>
<td>0.000011</td>
<td>-2.328842e-06</td>
<td>-0.000176</td>
<td>-0.026512</td>
<td>0.197857</td>
<td>0.000009</td>
<td>428.390000</td>
<td>-437.831716</td>
<td>9.999120e+06</td>
<td>856.78</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>-12.754262</td>
<td>9.999558e+06</td>
<td>432.70</td>
<td>432.70</td>
<td>3</td>
<td>[{u'order_id': u'be62ff77760c4599abaac43be9cc9...</td>
<td>0.0227</td>
</tr>
<tr>
<th>2016-01-04 23:59:00+00:00</th>
<td>0.000011</td>
<td>-2.380954e-06</td>
<td>-0.000139</td>
<td>-0.008640</td>
<td>0.269790</td>
<td>0.000020</td>
<td>432.900000</td>
<td>-442.441116</td>
<td>9.998677e+06</td>
<td>1298.70</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>-11.287205</td>
<td>9.999120e+06</td>
<td>856.78</td>
<td>856.78</td>
<td>4</td>
<td>[{u'order_id': u'd6dca79513214346a646079213526...</td>
<td>0.0224</td>
</tr>
<tr>
<th>2016-01-05 23:59:00+00:00</th>
<td>0.000011</td>
<td>-3.650729e-06</td>
<td>-0.000158</td>
<td>-0.021426</td>
<td>0.245989</td>
<td>0.000024</td>
<td>431.840000</td>
<td>-441.357754</td>
<td>9.998236e+06</td>
<td>1727.36</td>
<td>...</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>-12.333847</td>
<td>9.998677e+06</td>
<td>1298.70</td>
<td>1298.70</td>
<td>5</td>
<td>[{u'order_id': u'505275d6646a41f3856b22b16678d...</td>
<td>0.0225</td>
</tr>
</tbody>
</table>
</div><div class="line-block">
<div class="line"><br /></div>
</div>
<p>There is a row for each trading day, starting on the first day of our
simulation Jan 1st, 2016. In the columns you can find various
information about the state of your algorithm. The column
<code class="docutils literal"><span class="pre">btc</span></code> was placed there by the <code class="docutils literal"><span class="pre">record()</span></code> function mentioned earlier
and allows us to plot the price of bitcoin. For example, we could easily
examine now how our portfolio value changed over time compared to the
bitcoin price.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="o">%</span><span class="n">load_ext</span> <span class="n">catalyst</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="o">%</span><span class="n">pylab</span> <span class="n">inline</span>
<span class="n">figsize</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">12</span><span class="p">)</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>
<span class="n">ax1</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplot</span><span class="p">(</span><span class="mi">211</span><span class="p">)</span>
<span class="n">perf</span><span class="o">.</span><span class="n">portfolio_value</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ax</span><span class="o">=</span><span class="n">ax1</span><span class="p">)</span>
<span class="n">ax1</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s">&#39;portfolio value&#39;</span><span class="p">)</span>
<span class="n">ax2</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplot</span><span class="p">(</span><span class="mi">212</span><span class="p">,</span> <span class="n">sharex</span><span class="o">=</span><span class="n">ax1</span><span class="p">)</span>
<span class="n">perf</span><span class="o">.</span><span class="n">btc</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ax</span><span class="o">=</span><span class="n">ax2</span><span class="p">)</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s">&#39;bitcoin price&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre>Populating the interactive namespace from numpy and matplotlib
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre>&lt;matplotlib.text.Text at 0x10eaeadd0&gt;
</pre></div>
</div>
<img alt="https://s3.amazonaws.com/enigmaco-docs/github.io/buy_btc_simple_graph.png" src="https://s3.amazonaws.com/enigmaco-docs/github.io/buy_btc_simple_graph.png" />
<p>Our algorithm performance as assessed by the <code class="docutils literal"><span class="pre">portfolio_value</span></code> closely
matches that of the bitcoin price. This is not surprising as our algorithm
only bought bitcoin every chance it got.</p>
</div>
</div>
<div class="section" id="access-to-previous-prices-using-history">
<h2>Access to previous prices using <code class="docutils literal"><span class="pre">history</span></code><a class="headerlink" href="#access-to-previous-prices-using-history" title="Permalink to this headline"></a></h2>
<div class="section" id="working-example-dual-moving-average-cross-over">
<h3>Working example: Dual Moving Average Cross-Over<a class="headerlink" href="#working-example-dual-moving-average-cross-over" title="Permalink to this headline"></a></h3>
<p>The Dual Moving Average (DMA) is a classic momentum strategy. It&#8217;s
probably not used by any serious trader anymore but is still very
instructive. The basic idea is that we compute two rolling or moving
averages (mavg) &#8211; one with a longer window that is supposed to capture
long-term trends and one shorter window that is supposed to capture
short-term trends. Once the short-mavg crosses the long-mavg from below
we assume that the stock price has upwards momentum and long the stock.
If the short-mavg crosses from above we exit the positions as we assume
the stock to go down further.</p>
<p>As we need to have access to previous prices to implement this strategy
we need a new concept: History</p>
<p><code class="docutils literal"><span class="pre">data.history()</span></code> is a convenience function that keeps a rolling window of
data for you. The first argument is the number of bars you want to
collect, the second argument is the unit (either <code class="docutils literal"><span class="pre">'1d'</span></code> for <code class="docutils literal"><span class="pre">'1m'</span></code>
but note that you need to have minute-level data for using <code class="docutils literal"><span class="pre">1m</span></code>). This is
a function we use in the <code class="docutils literal"><span class="pre">handle_data()</span></code> section:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="o">%</span><span class="n">load_ext</span> <span class="n">catalyst</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="o">%%</span><span class="n">catalyst</span> <span class="o">--</span><span class="n">start</span> <span class="mi">2016</span><span class="o">-</span><span class="mi">4</span><span class="o">-</span><span class="mi">1</span> <span class="o">--</span><span class="n">end</span> <span class="mi">2017</span><span class="o">-</span><span class="mi">9</span><span class="o">-</span><span class="mi">30</span> <span class="o">-</span><span class="n">x</span> <span class="n">bitfinex</span>
<span class="kn">from</span> <span class="nn">catalyst.api</span> <span class="kn">import</span> <span class="n">order</span><span class="p">,</span> <span class="n">record</span><span class="p">,</span> <span class="n">symbol</span><span class="p">,</span> <span class="n">order_target</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">context</span><span class="p">):</span>
<span class="n">context</span><span class="o">.</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">context</span><span class="o">.</span><span class="n">asset</span> <span class="o">=</span> <span class="n">symbol</span><span class="p">(</span><span class="s">&#39;btc_usd&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">handle_data</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
<span class="c"># Skip first 150 days to get full windows</span>
<span class="n">context</span><span class="o">.</span><span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">if</span> <span class="n">context</span><span class="o">.</span><span class="n">i</span> <span class="o">&lt;</span> <span class="mi">150</span><span class="p">:</span>
<span class="k">return</span>
<span class="c"># Compute averages</span>
<span class="c"># data.history() has to be called with the same params</span>
<span class="c"># from above and returns a pandas dataframe.</span>
<span class="n">short_mavg</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">history</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="s">&#39;price&#39;</span><span class="p">,</span> <span class="n">bar_count</span><span class="o">=</span><span class="mi">50</span><span class="p">,</span> <span class="n">frequency</span><span class="o">=</span><span class="s">&quot;1d&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
<span class="n">long_mavg</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">history</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="s">&#39;price&#39;</span><span class="p">,</span> <span class="n">bar_count</span><span class="o">=</span><span class="mi">150</span><span class="p">,</span> <span class="n">frequency</span><span class="o">=</span><span class="s">&quot;1d&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
<span class="c"># Trading logic</span>
<span class="k">if</span> <span class="n">short_mavg</span> <span class="o">&gt;</span> <span class="n">long_mavg</span><span class="p">:</span>
<span class="c"># order_target orders as many shares as needed to</span>
<span class="c"># achieve the desired number of shares.</span>
<span class="n">order_target</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">short_mavg</span> <span class="o">&lt;</span> <span class="n">long_mavg</span><span class="p">:</span>
<span class="n">order_target</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="c"># Save values for later inspection</span>
<span class="n">record</span><span class="p">(</span><span class="n">btc</span><span class="o">=</span><span class="n">data</span><span class="o">.</span><span class="n">current</span><span class="p">(</span><span class="n">context</span><span class="o">.</span><span class="n">asset</span><span class="p">,</span> <span class="s">&#39;price&#39;</span><span class="p">),</span>
<span class="n">short_mavg</span><span class="o">=</span><span class="n">short_mavg</span><span class="p">,</span>
<span class="n">long_mavg</span><span class="o">=</span><span class="n">long_mavg</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">analyze</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">perf</span><span class="p">):</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>
<span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span><span class="mi">12</span><span class="p">))</span>
<span class="n">ax1</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">211</span><span class="p">)</span>
<span class="n">perf</span><span class="o">.</span><span class="n">portfolio_value</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ax</span><span class="o">=</span><span class="n">ax1</span><span class="p">)</span>
<span class="n">ax1</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s">&#39;portfolio value in $&#39;</span><span class="p">)</span>
<span class="n">ax2</span> <span class="o">=</span> <span class="n">fig</span><span class="o">.</span><span class="n">add_subplot</span><span class="p">(</span><span class="mi">212</span><span class="p">)</span>
<span class="n">perf</span><span class="p">[</span><span class="s">&#39;btc&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ax</span><span class="o">=</span><span class="n">ax2</span><span class="p">)</span>
<span class="n">perf</span><span class="p">[[</span><span class="s">&#39;short_mavg&#39;</span><span class="p">,</span> <span class="s">&#39;long_mavg&#39;</span><span class="p">]]</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ax</span><span class="o">=</span><span class="n">ax2</span><span class="p">)</span>
<span class="n">perf_trans</span> <span class="o">=</span> <span class="n">perf</span><span class="o">.</span><span class="n">ix</span><span class="p">[[</span><span class="n">t</span> <span class="o">!=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">perf</span><span class="o">.</span><span class="n">transactions</span><span class="p">]]</span>
<span class="n">buys</span> <span class="o">=</span> <span class="n">perf_trans</span><span class="o">.</span><span class="n">ix</span><span class="p">[[</span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="s">&#39;amount&#39;</span><span class="p">]</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">perf_trans</span><span class="o">.</span><span class="n">transactions</span><span class="p">]]</span>
<span class="n">sells</span> <span class="o">=</span> <span class="n">perf_trans</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span>
<span class="p">[</span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="s">&#39;amount&#39;</span><span class="p">]</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">perf_trans</span><span class="o">.</span><span class="n">transactions</span><span class="p">]]</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">buys</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">perf</span><span class="o">.</span><span class="n">short_mavg</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="n">buys</span><span class="o">.</span><span class="n">index</span><span class="p">],</span>
<span class="s">&#39;^&#39;</span><span class="p">,</span> <span class="n">markersize</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">&#39;m&#39;</span><span class="p">)</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">sells</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">perf</span><span class="o">.</span><span class="n">short_mavg</span><span class="o">.</span><span class="n">ix</span><span class="p">[</span><span class="n">sells</span><span class="o">.</span><span class="n">index</span><span class="p">],</span>
<span class="s">&#39;v&#39;</span><span class="p">,</span> <span class="n">markersize</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">&#39;k&#39;</span><span class="p">)</span>
<span class="n">ax2</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s">&#39;price in $&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">loc</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
<p>Here we are explicitly defining an <code class="docutils literal"><span class="pre">analyze()</span></code> function that gets
automatically called once the backtest is done.</p>
<p>Although it might not be directly apparent, the power of <code class="docutils literal"><span class="pre">history()</span></code>
(pun intended) can not be under-estimated as most algorithms make use of
prior market developments in one form or another. You could easily
devise a strategy that trains a classifier with
<a class="reference external" href="http://scikit-learn.org/stable/">scikit-learn</a> which tries to
predict future market movements based on past prices (note, that most of
the <code class="docutils literal"><span class="pre">scikit-learn</span></code> functions require <code class="docutils literal"><span class="pre">numpy.ndarray</span></code>s rather than
<code class="docutils literal"><span class="pre">pandas.DataFrame</span></code>s, so you can simply pass the underlying
<code class="docutils literal"><span class="pre">ndarray</span></code> of a <code class="docutils literal"><span class="pre">DataFrame</span></code> via <code class="docutils literal"><span class="pre">.values</span></code>).</p>
<p>We also used the <code class="docutils literal"><span class="pre">order_target()</span></code> function above. This and other
functions like it can make order management and portfolio rebalancing
much easier.</p>
</div>
</div>
<div class="section" id="conclusions">
<h2>Conclusions<a class="headerlink" href="#conclusions" title="Permalink to this headline"></a></h2>
<p>We hope that this tutorial gave you a little insight into the
architecture, API, and features of <code class="docutils literal"><span class="pre">catalyst</span></code>. For next steps, check
out some of the
<a class="reference external" href="https://github.com/enigmampc/catalyst/tree/master/catalyst/examples">examples</a>.
The natural next step would be too look into the
<a class="reference external" href="https://github.com/enigmampc/catalyst/blob/master/catalyst/examples/buy_and_hodl.py">buy_and_hodl</a>
example, which is a more elaborated and realistic version of the <code class="docutils literal"><span class="pre">buy_btc_simple</span></code> example presented in this tutorial.</p>
<p>Feel free to ask questions on the <code class="docutils literal"><span class="pre">#catalyst_dev</span></code> channel of our
<a class="reference external" href="https://discord.gg/SJK32GY">Discord group</a> and report
problems on our <a class="reference external" href="https://github.com/enigmampc/catalyst/issues">GitHub issue tracker</a>.</p>
</div>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="jupyter.html" class="btn btn-neutral float-right" title="Catalyst &amp; Jupyter Notebook" accesskey="n">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="install.html" class="btn btn-neutral" title="Install" accesskey="p"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
&copy; Copyright 2017, Enigma MPC, Inc..
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'./',
VERSION:'0.3',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html>