<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/introducing-ritch-parsing-itch-files-in-r-finance-market-microstructure/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datashenanigan.wordpress.com/2017/11/30/introducing-ritch-parsing-itch-files-in-r-finance-market-microstructure/"> R – Data Shenanigans</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Recently I was faced with a file compressed in NASDAQ’s ITCH-protocol, as I wasn’t able to find an R-package that parses and loads the file to R for me, I spent (probably) way to much time to write one, so here it is.</p>
<p>But you might wonder, what exactly is ITCH and why should I care?</p>
<p>Well, ITCH is the outbound protocol NASDAQ uses to communicate market data to its clients, that is, all information including market status, orders, trades, circuit breakers, etc. with nanosecond timestamps for each day and each exchange. Kinda a must-have if you are looking into market microstructure, a good-to-have-looked-into-it if you are interested in general finance and/or if you are interested in data analytics and large structured datasets.</p>
<p>If you are wondering where you might get some of these fancy datasets in the first place, I have good news for you. NASDAQ provides some sample datasets (6 days for 3 exchanges (NASDAQ, PSX, and BX), together about 25GBs gzipped) on its FTP server: <a rel="nofollow" target="_blank">ftp://emi.nasdaq.com/ITCH/</a></p>
<h2>The RITCH Package</h2>
<p>Now that I (hopefully) have your attention, let me represent to you <code>RITCH</code> an R package that parses ITCH-files (version 5.0).</p>
<p>Currently the package only lives on GitHub (<a rel="nofollow" href="https://github.com/DavZim/RITCH" target="_blank">https://github.com/DavZim/RITCH</a>), but it should find its way into CRAN eventually. Until then, you have to use devtools to install it</p>
<pre>
# install.packages(&quot;devtools&quot;)
devtools::install_github(&quot;DavZim/RITCH&quot;)
</pre>
<p>And you should be good to go (if not, please let me know! If you get a message related to make, you can safely ignore it for now).</p>
<p>RITCH so far has a very limited scope: extracting the messages from the ITCH-file plus some functions to count messages. The package leverages <code>C++</code> and the excellent <code>Rcpp</code> library to optimise parsing. RITCH itself does not contain any data as the datasets are too large for any repos and I have no copyright on the datasets in any way.</p>
<p>For the following code I will use the <code>20170130.BX_ITCH_50</code>-file from NASDAQ’s FTP-server, as its not too large at 714MB gzipped (1.6GB gunzipped), but still has almost 55 million messages. All functions can take the gzipped or unzipped files, but if you use the file more than once and hard-drive space is not of utmost concern, I suggest you gunzip the file by hand (i.e., use <code>R.utils::gunzip(file, new_file, remove = FALSE)</code> in R or <code>gunzip -k YYYYMMDD.XXX_ITCH_50.gz</code> in the terminal) and call the functions on the “plain”-file. I will address some concerns to size and speed later on.</p>
<p>To download and prepare the data in R, we can use the following code</p>
<pre>
# might take some time as it downloads 714MB
download.file(&quot;ftp://emi.nasdaq.com/ITCH/20170130.BX_ITCH_50.gz&quot;, &quot;20170130.BX_ITCH_50.gz&quot;, mode = &quot;wb&quot;)

# gunzip the file, but keep the original file
R.utils::gunzip(&quot;20170130.BX_ITCH_50.gz&quot;, &quot;20170130.BX_ITCH_50&quot;, remove = FALSE)
</pre>
<p>First, we want to get a general overview of the file, which we can do with <code>count_messages()</code></p>
<pre>
library(RITCH)
file &lt;- &quot;20170130.BX_ITCH_50&quot;

msg_count &lt;- count_messages(file, add_meta_data = TRUE) 
#> [Counting]   54473386 messages found
#> [Converting] to data.table

msg_count
#>     msg_type    count                                  msg_name                                    msg_group  doc_nr
#>  1:        S        6                      System Event Message                         System Event Message     4.1
#>  2:        R     8371                           Stock Directory                       Stock Related Messages   4.2.1
#>  3:        H     8401                      Stock Trading Action                       Stock Related Messages   4.2.2
#>  4:        Y     8502                       Reg SHO Restriction                       Stock Related Messages   4.2.3
#>  5:        L     6011               Market Participant Position                       Stock Related Messages   4.2.4
#>  6:        V        2                MWCB Decline Level Message                       Stock Related Messages 4.2.5.1
#>  7:        W        0                       MWCB Status Message                       Stock Related Messages 4.2.5.2
#>  8:        K        0                 IPO Quoting Period Update                       Stock Related Messages   4.2.6
#>  9:        J        0                       LULD Auction Collar                       Stock Related Messages   4.2.7
#> 10:        A 21142017                         Add Order Message                            Add Order Message   4.3.1
#> 11:        F    20648      Add Order - MPID Attribution Message                            Add Order Message   4.3.2
#> 12:        E  1203625                    Order Executed Message                        Modify Order Messages   4.4.1
#> 13:        C     8467 Order Executed Message With Price Message                        Modify Order Messages   4.4.2
#> 14:        X  1498904                      Order Cancel Message                        Modify Order Messages   4.4.3
#> 15:        D 20282644                      Order Delete Message                        Modify Order Messages   4.4.4
#> 16:        U  3020278                     Order Replace Message                        Modify Order Messages   4.4.5
#> 17:        P   330023                 Trade Message (Non-Cross)                               Trade Messages   4.5.1
#> 18:        Q        0                       Cross Trade Message                               Trade Messages   4.5.2
#> 19:        B        0                      Broken Trade Message                               Trade Messages   4.5.3
#> 20:        I        0                              NOII Message Net Order Imbalance Indicator (NOII) Message     4.6
#> 21:        N  6935487                   Retail Interest Message    Retail Price Improvement Indicator (RPII)     4.7
#>     msg_type    count                                  msg_name                                    msg_group  doc_nr
</pre>
<p>As you can see, there are a lot of different message types. Currently this package parses only messages from the group “Add Order Messages” (type ‘A’ and ‘F’), “Modify Order Messages” (type ‘E’, ‘C’, ‘X’, ‘D’, and ‘U’), and “Trade Messages” (type ‘P’, ‘Q’, and ‘B’). You can extract the different message-types by using the functions <code>get_orders</code>, <code>get_modifications</code>, and <code>get_trades</code>, respectively. The doc-number refers to the section in the <a rel="nofollow" href="https://www.nasdaqtrader.com/content/technicalsupport/specifications/dataproducts/NQTVITCHspecification.pdf" target="_blank">official documentation</a> (which also contains more detailed description what each type contains).</p>
<p>If you are annoyed by the feedback the function gives you (<code>[Counting] ... [Converting]...</code>), you can always turn the feedback off with the <code>quiet = TRUE</code> option (this applies to all functions).</p>
<p>Lets try to parse the first 10 orders</p>
<pre>
orders &lt;- get_orders(file, 1, 10) 
#> 10 messages found
#> [Loading]    .
#> [Converting] to data.table
#> [Formatting]

orders
#>     msg_type locate_code tracking_number    timestamp order_ref   buy shares stock   price mpid       date            datetime
#>  1:        A        7584               0 2.520001e+13     36132  TRUE 500000  UAMY  0.0001   NA 2017-01-30 2017-01-30 07:00:00
#>  2:        A        3223               0 2.520001e+13     36133  TRUE 500000  GLOW  0.0001   NA 2017-01-30 2017-01-30 07:00:00
#>  3:        A        2937               0 2.520001e+13     36136 FALSE    200   FRP 18.6500   NA 2017-01-30 2017-01-30 07:00:00
#>  4:        A        5907               0 2.520001e+13     36137  TRUE   1500   PIP  3.1500   NA 2017-01-30 2017-01-30 07:00:00
#>  5:        A        5907               0 2.520001e+13     36138 FALSE   2000   PIP  3.2500   NA 2017-01-30 2017-01-30 07:00:00
#>  6:        A        5907               0 2.520001e+13     36139  TRUE   3000   PIP  3.1000   NA 2017-01-30 2017-01-30 07:00:00
#>  7:        A        5398               0 2.520001e+13     36140  TRUE    200   NSR 33.0000   NA 2017-01-30 2017-01-30 07:00:00
#>  8:        A        5907               0 2.520001e+13     36141 FALSE    500   PIP  3.2500   NA 2017-01-30 2017-01-30 07:00:00
#>  9:        A        2061               0 2.520001e+13     36142 FALSE   1300  DSCI  7.0000   NA 2017-01-30 2017-01-30 07:00:00
#> 10:        A        1582               0 2.520001e+13     36143  TRUE    500  CPPL 17.1500   NA 2017-01-30 2017-01-30 07:00:00
</pre>
<p>The same works for trades using the <code>get_trades()</code> function and for order modifications using the <code>get_modifications()</code> function.</p>
<p>To speed up the <code>get_*</code> functions, we can use the message-count information from earlier. For example the following code yields the same results as above, but saves time.</p>
<pre>
orders &lt;- get_orders(file, 1, count_orders(msg_count))
trades &lt;- get_trades(file, 1, count_trades(msg_count))
</pre>
<p>If you want to get more information about each field, you can have a look at the<br>
<a rel="nofollow" href="https://www.nasdaqtrader.com/content/technicalsupport/specifications/dataproducts/NQTVITCHspecification.pdf" target="_blank">official ITCH-protocol specification manual</a> or you can get a small data.table about each message type by calling <code>get_meta_data()</code>.</p>
<h2>Having a Look at some the most traded ETFs</h2>
<p>To have at least one piece of eye-candy in this post, lets have a quick go at the orders and trades of SPY (an S&amp;P 500 ETF and one of the most traded assets, in case you didn’t know), IWO (Russel 2000 Growth ETF), IWM (Russel 2000 Index ETF), and VXX (S&amp;P 500 VIX ETF) on the BX-exchange.</p>
<p>In case you are wondering, I got these four tickers with</p>
<pre>
library(magrittr)

get_orders(file, 1, count_orders(msg_count), quiet = T) %>% 
  .$stock %>% 
  table %>% 
  sort(decreasing = T) %>% 
  head(4)
#> .
#>    SPY    IWO    IWM    VXX 
#> 135119 135016 118123 117395 
</pre>
<p>First we load the data (orders and trades) from the file, then we do some data munging, and finally plot the data using ggplot2.</p>
<pre>
library(ggplot2)

# 0. load the data
orders &lt;- get_orders(file, 1, count_orders(msg_count))
#> 21162665 messages found
#> [Loading]    ................
#> [Converting] to data.table
#> [Formatting]

trades &lt;- get_trades(file, 1, count_trades(msg_count))
#> 330023 messages found
#> [Loading]    ................
#> [Converting] to data.table
#> [Formatting]

# 1. data munging
tickers &lt;- c(&quot;SPY&quot;, &quot;IWO&quot;, &quot;IWM&quot;, &quot;VXX&quot;)
dt_orders &lt;- orders[stock %in% tickers]
dt_trades &lt;- trades[stock %in% tickers]

# for each ticker, use only orders that are within 1% of the range of traded prices
ranges &lt;- dt_trades[, .(min_price = min(price), max_price = max(price)), by = stock]

# filter the orders
dt_orders &lt;- dt_orders[ranges, on = &quot;stock&quot;][price >= 0.99 * min_price &amp; price &lt;= 1.01 * max_price]

# replace the buy-factor with something more useful
dt_orders[, buy := ifelse(buy, &quot;Bid&quot;, &quot;Ask&quot;)]
dt_orders[, stock := factor(stock, levels = tickers)]

# 2. data visualization
ggplot() +
  # add the orders to the plot
  geom_point(data = dt_orders,
             aes(x = datetime, y = price, color = buy), size = 0.5) +
  # add the trades as a black line to the plot
  geom_step(data = dt_trades,
            aes(x = datetime, y = price)) +
  # add a facet for each ETF
  facet_wrap(~stock, scales = &quot;free_y&quot;) +
  # some Aesthetics
  theme_light() +
  labs(title = &quot;Orders and Trades of the largest ETFs&quot;,
       subtitle = &quot;Date: 2017-01-30 | Exchange: BX&quot;,
       caption = &quot;Source: NASDAQ&quot;,
       x = &quot;Time&quot;, y = &quot;Price&quot;,
       color = &quot;Side&quot;) +
  scale_y_continuous(labels = scales::dollar) +
  scale_color_brewer(palette = &quot;Set1&quot;)
</pre>
<p><img data-orig-file="https://datashenanigan.files.wordpress.com/2017/11/etf_plot.png?w=456" data-orig-size="2100,1500" data-medium-file="https://datashenanigan.files.wordpress.com/2017/11/etf_plot.png?w=456?w=300" data-attachment-id="450" data-image-meta="{" data-image-description="" src="https://datashenanigan.files.wordpress.com/2017/11/etf_plot.png?w=456" data-permalink="https://datashenanigan.wordpress.com/2017/11/30/introducing-ritch-parsing-itch-files-in-r-finance-market-microstructure/etf_plot/" data-large-file="https://datashenanigan.files.wordpress.com/2017/11/etf_plot.png?w=456?w=809" alt="ETF_plot" data-image-title="ETF_plot" sizes="(max-width: 809px) 100vw, 809px" data-comments-opened="1" class="wp-image-450" data-recalc-dims="1"></p>
<p>Now its up to you to do something interesting with the data, I hope RITCH can help you with it.</p>
<h2>Speed &amp; RAM concerns</h2>
<p>If your machine struggles with some files, you can always load only parts of a file as shown above. And of course, make sure that you have only necessary datasets in your R-environment and that no unused programs are open (Chrome with some open tabs in the background happily eats your RAM).</p>
<p>If your machine is able to handle larger datasets, you can increase the buffersize of each function call to 1GB or more using the <code>buffer_size = 1e9</code> argument, increasing the speed with which a file is parsed.</p>
<h2>Addendum</h2>
<p>If you find this package useful or have any other kind of feedback, I’d be happy if you let me know. Otherwise, if you need more functionality for additional message types, please feel free to create an issue or a pull request on <a rel="nofollow" href="https://github.com/DavZim/RITCH" target="_blank">GitHub</a>.</p>
<p>Filed under: <a rel="nofollow" href="https://datashenanigan.wordpress.com/category/r/" target="_blank">R</a> Tagged: <a rel="nofollow" href="https://datashenanigan.wordpress.com/tag/finance/" target="_blank">Finance</a>, <a rel="nofollow" href="https://datashenanigan.wordpress.com/tag/r/" target="_blank">R</a>, <a rel="nofollow" href="https://datashenanigan.wordpress.com/tag/ritch/" target="_blank">RITCH</a>, <a rel="nofollow" href="https://datashenanigan.wordpress.com/tag/visualisation/" target="_blank">Visualisation</a> <a rel="nofollow" href="https://feeds.wordpress.com/1.0/gocomments/datashenanigan.wordpress.com/443/" target="_blank"><img border="0" alt="" src="https://feeds.wordpress.com/1.0/comments/datashenanigan.wordpress.com/443/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datashenanigan.wordpress.com/2017/11/30/introducing-ritch-parsing-itch-files-in-r-finance-market-microstructure/"> R – Data Shenanigans</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/yoDx5xybd4w" height="1"></a></div>