<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maks Ivanov on Medium]]></title>
        <description><![CDATA[Stories by Maks Ivanov on Medium]]></description>
        <link>https://medium.com/@maks.ivanov?source=rss-af72e8ccb37d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*gJ6Gbuyoet2Ej8w0U7Q5eQ.jpeg</url>
            <title>Stories by Maks Ivanov on Medium</title>
            <link>https://medium.com/@maks.ivanov?source=rss-af72e8ccb37d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 13:49:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maks.ivanov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Financial Machine Learning Part 1: Labels]]></title>
            <link>https://medium.com/data-science/financial-machine-learning-part-1-labels-7eeed050f32e?source=rss-af72e8ccb37d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eeed050f32e</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Maks Ivanov]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 00:23:20 GMT</pubDate>
            <atom:updated>2019-04-02T20:30:54.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEzsHb2OmhrN1E9wdL9RPA.jpeg" /></figure><h4>Setting up a supervised learning problem</h4><h4>Introduction</h4><p>In the <a href="https://towardsdatascience.com/financial-machine-learning-part-0-bars-745897d4e4ba">previous post</a>, we’ve explored several approaches for aggregating raw data for a financial instrument to create observations called bars. In this post, we will focus on the next crucial stage of the machine learning pipeline — labeling observations. As a reminder, labels in machine learning denote the outcomes of the random variable that we would like to predict.</p><p>Just like in the rest of this series, the techniques shown in this post are based on <a href="https://www.amazon.com/Advances-Financial-Machine-Learning-Marcos/dp/1119482089"><strong>Advances in Financial Machine Learning</strong></a> by <a href="http://www.quantresearch.org/"><strong>Marcos Lopez de Prado</strong></a>. I recommend checking out the book for a much more detailed treatment of the subject. With that said, it’s time to jump in and swim around.</p><h3>Labeling Observations</h3><p>In the financial context, a simple approach for a supervised learning problem is to try to predict the price of an instrument at some fixed horizon in the future. Note that this is a regression task, i.e. we’d attempt to predict a continuous random variable. This is a hard problem to solve because prices are notoriously noisy and serially correlated, and the set of all possible price values is technically infinite. On the other hand, we can approach this as a classification problem — instead of predicting the exact price, we can predict discretized returns.</p><p>Most financial literature uses fixed-horizon labeling methods, i.e. the observations are labeled according to returns some fixed number of steps in the future. The labels are discretized by profit and loss thresholds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*frd89b50RUZGNw1EfVunMg.jpeg" /></figure><p>This labeling method is a good start, but it has two addressable problems.</p><ol><li>The thresholds are fixed, but volatility isn’t — meaning that sometimes our thresholds are too far apart and sometimes they are too close together. When the volatility is low (e.g. during the night trading session) we will get mostly <em>y=</em>0 labels even though the low returns are predictable and statistically significant.</li><li>The label is path-independent, meaning that it only depends on the return at the horizon and not the intermediate returns. This is a problem because the label doesn’t accurately reflect the reality of trading — every strategy has a stop-loss threshold and a take-profit threshold which can close the position early. If an intermediate return hits the stop-loss threshold, we will realize a loss, and holding the position or profiting from it is unrealistic. Conversely, if an intermediate return hits a take-profit threshold we will close it to lock in the gain, even if the return at the horizon is zero or negative.</li></ol><p><strong>Computing Dynamic Thresholds</strong></p><p>To address the first problem, we can set dynamic thresholds as a function of rolling volatility. We’re assuming that we already have OHLC bars at this point. I use the dollar bars of <a href="https://www.bitmex.com/app/seriesGuide/XBT">BitMex:XBT</a>, the bitcoin perpetual swap contract from the previous post — this <a href="https://gist.github.com/maks-ivanov/e668c47addfa69e86da5a44e3f634dd5">code snippet</a> will help you catch up if you are starting from scratch.</p><p>Here we will estimate hourly volatility of returns to compute profit and loss thresholds. Below you’ll find a slightly modified function directly from Lopez De Prado, with comments added for clarity:</p><pre>def get_vol(prices, span=100, delta=pd.Timedelta(hours=1)):<br>  # 1. compute returns of the form p[t]/p[t-1] - 1</pre><pre>  # 1.1 find the timestamps of p[t-1] values<br>  df0 = prices.index.searchsorted(prices.index - delta)<br>  df0 = df0[df0 &gt; 0]</pre><pre>  # 1.2 align timestamps of p[t-1] to timestamps of p[t]<br>  df0 = pd.Series(prices.index[df0-1],    <br>           index=prices.index[prices.shape[0]-df0.shape[0] : ])</pre><pre>  # 1.3 get values by timestamps, then compute returns<br>  df0 = prices.loc[df0.index] / prices.loc[df0.values].values - 1</pre><pre>  # 2. estimate rolling standard deviation<br>  df0 = df0.ewm(span=span).std()<br>  return df0</pre><p><strong>Adding Path Dependency: Triple-Barrier Method</strong></p><p>To better incorporate the stop-loss and take-profit scenarios of a hypothetical trading strategy, we will modify the fixed-horizon labeling method so that it reflects which barrier has been touched first — upper, lower, or horizon. Hence the name: the triple-barrier method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Gi4gkPd33iJNh6kp.png" /><figcaption><strong><em>Triple-Barrier Label y=0</em> | </strong>Source: quantresearch.org</figcaption></figure><p>The labeling schema is defined as follows:</p><p><em>y=</em>1<em> : top barrier is hit first</em></p><p><em>y=</em>0<em> : right barrier is hit first</em></p><p><em>y=</em>-1<em> : bottom barrier is hit first</em></p><p><strong>What about the side of the bet?</strong></p><p>The schema above works fine for long-only strategies, however things get more complicated when we allow for both <a href="https://www.investopedia.com/video/play/explaining-long-and-short-position/">long and short bets</a>. If we are betting short, our profit/loss is inverted relative to the price action — we profit if the price goes down and we lose when the price goes up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JkCVZrdUI067g0as.jpg" /><figcaption>“Because I was inverted” — Maverick | Top Gun</figcaption></figure><p>In order to account for this, we can simply represent <em>side</em> as 1 for long and -1 for short. Thus we can multiply our returns by the side, so whenever we’re betting short the negative returns become positive and vice-versa. Effectively, we flip the <em>y</em>=1 and <em>y</em>=-1 labels if <em>side</em>=-1.</p><p>Let’s take a shot at the implementation (based on MLDP’s code).</p><p>First, we define the procedure for getting the timestamps of the horizon barriers:</p><pre>def get_horizons(prices, delta=pd.Timedelta(minutes=15)):<br>    t1 = prices.index.searchsorted(prices.index + delta)<br>    t1 = t1[t1 &lt; prices.shape[0]]<br>    t1 = prices.index[t1]<br>    t1 = pd.Series(t1, index=prices.index[:t1.shape[0]])<br>    return t1</pre><p>Now that we have our horizon barriers, we define a function to set upper and lower barriers based on the volatility estimates computed earlier:</p><pre>def get_touches(prices, events, factors=[1, 1]):<br>  &#39;&#39;&#39;<br>  events: pd dataframe with columns<br>    t1: timestamp of the next horizon<br>    threshold: unit height of top and bottom barriers<br>    side: the side of each bet<br>  factors: multipliers of the threshold to set the height of <br>           top/bottom barriers<br>  &#39;&#39;&#39;</pre><pre>  out = events[[&#39;t1&#39;]].copy(deep=True)<br>  if factors[0] &gt; 0: thresh_uppr = factors[0] * events[&#39;threshold&#39;]<br>  else: thresh_uppr = pd.Series(index=events.index) # no uppr thresh<br>  if factors[1] &gt; 0: thresh_lwr = -factors[1] * events[&#39;threshold&#39;]<br>  else: thresh_lwr = pd.Series(index=events.index)  # no lwr thresh</pre><pre>  for loc, t1 in events[&#39;t1&#39;].iteritems():<br>    df0=prices[loc:t1]                              # path prices<br>    df0=(df0 / prices[loc] - 1) * events.side[loc]  # path returns<br>    out.loc[loc, &#39;stop_loss&#39;] = \<br>      df0[df0 &lt; thresh_lwr[loc]].index.min()  # earliest stop loss<br>    out.loc[loc, &#39;take_profit&#39;] = \<br>      df0[df0 &gt; thresh_uppr[loc]].index.min() # earliest take profit<br>  return out</pre><p>Finally, we define a function to compute the labels:</p><pre>def get_labels(touches):<br>  out = touches.copy(deep=True)<br>  # pandas df.min() ignores NaN values<br>  first_touch = touches[[&#39;stop_loss&#39;, &#39;take_profit&#39;]].min(axis=1)<br>  for loc, t in first_touch.iteritems():<br>    if pd.isnull(t):<br>      out.loc[loc, &#39;label&#39;] = 0<br>    elif t == touches.loc[loc, &#39;stop_loss&#39;]: <br>      out.loc[loc, &#39;label&#39;] = -1<br>    else:<br>      out.loc[loc, &#39;label&#39;] = 1<br>  return out</pre><p>Putting it all together:</p><pre>data_ohlc = pd.read_parquet(&#39;data_dollar_ohlc.pq&#39;)<br>data_ohlc = \<br>  data_ohlc.assign(threshold=get_vol(data_ohlc.close)).dropna()<br>data_ohlc = data_ohlc.assign(t1=get_horizons(data_ohlc)).dropna()<br>events = data_ohlc[[&#39;t1&#39;, &#39;threshold&#39;]] <br>events = events.assign(side=pd.Series(1., events.index)) # long only<br>touches = get_touches(data_ohlc.close, events, [1,1])<br>touches = get_labels(touches)<br>data_ohlc = data_ohlc.assign(label=touches.label)</pre><h3>Meta-Labeling</h3><p>On a conceptual level, our goal is to place bets where we expect to win and not to place bets where we don’t expect to win, which reduces to a binary classification problem (where the losing case includes both betting on the wrong direction and not betting at all when we should have). Here’s another way to look at the labels we just generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*lXZsAais5VWGjiL0VwwcUw.png" /></figure><p>A binary classification problem presents a trade-off between type-I errors (false positives) and type-II errors (false negatives). Increasing the true positive rate usually comes at the cost of increasing the false positive rate.</p><p>To characterize this more formally, let us first define:</p><p><em>ŷ ∈ </em>{0, 1, -1} : <em>prediction of the primary model for the observation</em></p><p><em>r : price return for the observation</em></p><p>Then at prediction time the confusion matrix of the primary model looks like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*tsKJ15R-D6Fc0RcMKJM_UQ.jpeg" /></figure><p>We are not too worried about the false negatives — we might miss a few bets but at least we’re not losing money. We are most concerned about the false positives — this is where we lose money.</p><p>To reflect this, our meta-labels <em>y*</em> can be defined according to the diagram:</p><p><em>y*=</em>1<strong>:</strong><em>true positive</em></p><p><em>y*=</em>0<strong>:</strong><em>everything but true positive</em></p><p>In effect, the primary model should have high <a href="https://en.wikipedia.org/wiki/Precision_and_recall">recall</a> — it should identify more of the true positives correctly at the expense of many false positives. The secondary model will then filter out the false positives of the first model.</p><h4>Meta-Labeling Implementation</h4><p>First, we create a primary model. Before we do so, an important preprocessing step is to make sure that our training data has balanced labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*HGzHW8CZ8a_Mtb6sWI_4lA.png" /></figure><p>The labels in the original dataset are heavily dominated by 0 values, so if we train on those, we get a degenerate model that predicts 0 every time. We deal with this by applying the <a href="https://arxiv.org/pdf/1106.1813.pdf">synthetic minority over-sampling technique</a> to create a new training dataset where the label counts are roughly equal.</p><pre>from imblearn.over_sampling import SMOTE<br>X = data_ohlc[[&#39;open&#39;, &#39;close&#39;, &#39;high&#39;, &#39;low&#39;, &#39;vwap&#39;]].values<br>y = np.squeeze(data_ohlc[[&#39;label&#39;]].values)<br>X_train, y_train = X[:4500], y[:4500]<br>X_test, y_test = X[4500:], y[4500:]<br>sm = SMOTE()<br>X_train_res, y_train_res = sm.fit_sample(X_train, y_train)</pre><p>Next we fit a logistic regression model to our resampled training data. Note that at this point we should not expect our model to do well because we haven’t generated any features, but we should still see an improved F1 score when using meta-labeling over the baseline model.</p><pre>from sklearn.linear_model import LogisticRegression<br>clf = LogisticRegression().fit(X_train_res, y_train_res)<br>y_pred = clf.predict(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*xX08O3sPFXUQ8czePX4gqw.png" /></figure><p>We can see that our model predicts more 1’s and -1’s than there are in our test data. The blue portions of the leftmost and rightmost columns represent the false positives, which we intend to eliminate by meta-labeling and training the secondary model.</p><p>Let’s map our triple-barrier predictions into binary positive/negative meta-labels introduced earlier and check the confusion matrix:</p><pre>def true_binary_label(y_pred, y_test):<br>    bin_label = np.zeros_like(y_pred)<br>    for i in range(y_pred.shape[0]):<br>        if y_pred[i] != 0 and y_pred[i]*y_test[i] &gt; 0:<br>            bin_label[i] = 1  # true positive<br>    return bin_label</pre><pre>from sklearn.metrics import confusion_matrix<br>cm= confusion_matrix(true_binary_label(y_pred, y_test), y_pred != 0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*-FjBnnHBKBLHMWIPltvZdw.png" /><figcaption>primary model</figcaption></figure><p>As expected, we see no false negatives and a lot of false positives. We will try to reduce the false positives without adding too many false negatives.</p><p>.</p><p>.</p><pre># generate predictions for training set<br>y_train_pred = clf.predict(X_train) <br># add the predictions to features <br>X_train_meta = np.hstack([y_train_pred[:, None], X_train])<br>X_test_meta = np.hstack([y_pred[:, None], X_test])<br># generate true meta-labels<br>y_train_meta = true_binary_label(y_train_pred, y_train)<br># rebalance classes again<br>sm = SMOTE()<br>X_train_meta_res, y_train_meta_res = sm.fit_sample(X_train_meta, y_train_meta)<br>model_secondary = LogisticRegression().fit(X_train_meta_res, y_train_meta_res)<br>y_pred_meta = model_secondary.predict(X_test_meta)<br># use meta-predictions to filter primary predictions<br>cm= confusion_matrix(true_binary_label(y_pred, y_test), (y_pred * y_pred_meta) != 0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*0uJHaKXgoDUHGThG-2TZ7Q.png" /><figcaption>secondary model</figcaption></figure><p>The results in the secondary model show that we introduce a few false negatives, but we eliminate over 30% of false positives from the primary model. While it isn’t always a worthy trade-off, remember the context of trading — we miss out on some trading opportunities (false negatives), but that is a cheap price to pay for cutting down many trades that blow up in our faces (false positives). The classification report confirms our intuition that the efficiency of the classifier improves as measured by the <a href="https://en.wikipedia.org/wiki/F1_score">F1 score</a>.</p><pre># WITHOUT META-LABELING</pre><pre>       label    precision    recall  <strong>f1-score</strong>   support<br><br>           0       1.00      <strong>0.66</strong>      <strong>0.79</strong>      1499<br>           1       0.14      1.00      <strong>0.24</strong>        81<br><br>   micro avg       0.67      0.67      <strong>0.67</strong>      1580<br>   macro avg       0.57      0.83      <strong>0.52</strong>      1580<br>weighted avg       0.96      0.67      <strong>0.76</strong>      1580</pre><pre># WITH META-LABELING</pre><pre>       label    precision    recall  f1-score   support<br>       <br>           0       0.97      <strong>0.76</strong>      <strong>0.85</strong>      1499<br>           1       0.12      0.59      0.20        81<br><br>   micro avg       0.75      0.75      <strong>0.75</strong>      1580<br>   macro avg       0.55      0.68      <strong>0.53</strong>      1580<br>weighted avg       0.93      0.75      <strong>0.82</strong>      1580</pre><p>While neither model is great, remember that we are merely demonstrating a technique for improving classifier efficiency, which can conceivably work well on a larger dataset, better model, and more powerful features.</p><h4>Meta-Labeling: Quantamental Approach</h4><p>In general, the interpretation of meta-labeling + secondary model is to predict the confidence level of the primary model. In our example, both the primary and the secondary models were data-driven, but this doesn’t always have to be the case.</p><p>In addition to improving F1 scores, meta-labeling has another extremely powerful application — it can add a machine learning layer on top of non-ML models, including econometric forecasts, fundamental analysis, technical signals, and even discretionary strategies. This offers a powerful combination of human intuition/expertise and quantitative edge that is favored by many asset managers for its explainability and robustness.</p><h3>Summary</h3><p>Labeling observations is a crucial component for supervised learning. In this demo, we’ve developed an approach for labeling observations of a financial asset, as well as a meta-labeling technique to help achieve better F1 scores in classification problems. I encourage you to combine these labeling techniques with other datasets and parameters, and share your results. Thanks for reading and feel free to reach out with comments/suggestions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eeed050f32e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/financial-machine-learning-part-1-labels-7eeed050f32e">Financial Machine Learning Part 1: Labels</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Financial Machine Learning Part 0: Bars]]></title>
            <link>https://medium.com/data-science/financial-machine-learning-part-0-bars-745897d4e4ba?source=rss-af72e8ccb37d------2</link>
            <guid isPermaLink="false">https://medium.com/p/745897d4e4ba</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Maks Ivanov]]></dc:creator>
            <pubDate>Wed, 27 Feb 2019 11:02:19 GMT</pubDate>
            <atom:updated>2019-02-27T11:02:19.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preface</h3><p>Recently, I got my copy of <a href="https://www.amazon.com/dp/1119482089/ref=cm_sw_r_tw_dp_U_x_VXFACbQSY9MCN">Advances in Financial Machine Learning</a> by <a href="http://quantresearch.org/">Marcos Lopez de Prado</a>. Lopez de Prado is a renowned quant researcher who has managed billions throughout his career. The book is an amazing resource to anyone interested in data science and finance, and it offers valuable insights into how advanced predictive techniques are applied to financial problems.</p><p>This post is the first of a series dedicated to applying the approaches introduced by Lopez de Prado to real (and occasionally, synthetic) datasets. My hope is that by writing these posts I can solidify my understanding of the material and share some lessons learned along the way.</p><p>Without further ado, let’s proceed to the main subject of this post: bars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*YAR4F9GP_jJSxkstYTvlrg.jpeg" /><figcaption>wrong kind of bar</figcaption></figure><h3>What are bars?</h3><p>The first step to building a great model is aggregating the data into a convenient format for further analysis. “<a href="https://www.investopedia.com/terms/b/bar.asp">Bars</a>” refer to a data representation that contains the most basic information about price movements of a financial asset. A typical bar may contain features like the timestamp, peak price, opening and closing prices, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*EdyZvHqsBUU-p-9MapOapg.png" /><figcaption>HLC bar chart (stockcharts.com)</figcaption></figure><p>Bars are typically the data format used as the input for training and testing your ML predictor. One can easily imagine that the way the raw data is aggregated can have a significant downstream effect on the entire model.</p><h3><strong>Motivation</strong></h3><p>Although it may seem intuitive to work with price observations at fixed time intervals, e.g. every day/hour/minute/etc., it is not a good idea. Information flow through markets is not uniformly distributed over time, and there are some periods heightened activity, e.g. in the hour following the market open, or right before a futures contract expires.</p><p>We must aim for a bar representation in which each bar contains the same amount of information, however time-based bars will oversample slow periods and undersample high activity periods. To avoid this problem, the idea is to sample observations as a function of market activity.</p><h3><strong>Setup</strong></h3><p>Using a trade book dataset, we will construct multiple types of bars for an actual financial instrument. I will use the data for BitCoin perpetual swap contract listed on <a href="https://www.bitmex.com/app/trade/XBTUSD">BitMex</a> as <a href="https://www.bitmex.com/app/contract/XBTUSD">XBT</a>, because talking about BitCoin is the exciting thing to do these days and also because the trade book data is available <a href="https://public.bitmex.com/">here</a>. We will compare time bars vs. tick bars, volume bars, dollar bars, and dollar imbalance bars. Python 3 snippets are provided to follow along.</p><p>First, a bit of setup:</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import matplotlib.dates as mdates<br>from datetime import datetime</pre><pre># raw trade data from <a href="https://public.bitmex.com/?prefix=data/trade/">https://public.bitmex.com/?prefix=data/trade/</a> <br>data = pd.read_csv(‘data/20181127.csv’)<br>data = data.append(pd.read_csv(‘data/20181128.csv’)) # add a few more days<br>data = data.append(pd.read_csv(‘data/20181129.csv’))<br>data = data[data.symbol == ‘XBTUSD’]<br># timestamp parsing<br>data[‘timestamp’] = data.timestamp.map(lambda t: datetime.strptime(t[:-3], “%Y-%m-%dD%H:%M:%S.%f”))</pre><h3>Time Bars</h3><p>We’ve now loaded a few days worth of trade data for the XBTUSD ticker on BitMex. Let’s see what the <a href="https://www.investopedia.com/terms/v/vwap.asp">volume weighted average price</a> looks like when computed in 15 minute intervals. As previously mentioned, this representation isn’t synchronized to market information flow — however, we will use it as a benchmark to compare against.</p><pre>def compute_vwap(df):<br>    q = df[&#39;foreignNotional&#39;]<br>    p = df[&#39;price&#39;]<br>    vwap = np.sum(p * q) / np.sum(q)<br>    df[&#39;vwap&#39;] = vwap<br>    return df</pre><pre>data_timeidx = data.set_index(&#39;timestamp&#39;)<br>data_time_grp = data_timeidx.groupby(pd.Grouper(freq=&#39;15Min&#39;))<br>num_time_bars = len(data_time_grp) # comes in handy later<br>data_time_vwap = data_time_grp.apply(compute_vwap)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*65efQePYVPW95ExqpCkXOg.png" /><figcaption>XBT time bars</figcaption></figure><p>Note that we saved the number of bars in the final series. For comparing different methods, we want to make sure that we have roughly the same resolution so that the comparison is fair.</p><h3>Tick Bars</h3><p>The idea behind tick bars is to sample observations every N transactions, aka “ticks”, instead of fixed time buckets. This allows us to capture more information at times when many trades take place, and vice-versa.</p><pre>total_ticks = len(data)<br>num_ticks_per_bar = total_ticks / num_time_bars<br>num_ticks_per_bar = round(num_ticks_per_bar, -3) # round to the nearest thousand<br>data_tick_grp = data.reset_index().assign(grpId=lambda row: row.index // num_ticks_per_bar)</pre><pre>data_tick_vwap =  data_tick_grp.groupby(&#39;grpId&#39;).apply(compute_vwap)<br>data_tick_vwap.set_index(&#39;timestamp&#39;, inplace=True)</pre><p><strong>How does this compare to the time bar series?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*OQNkdTVWK6o23jiQFmGMyg.png" /><figcaption>XBT time and tick bars</figcaption></figure><p>Plotting the two together, you may notice a flash rally and a flash crash (yellow) of ~10% that were hidden in the time bar representation (blue). Depending on your strategy, these two events could mean a huge trading opportunity (mean reversion) or a trading cost (slippage).</p><h3>Volume Bars</h3><p>One shortcoming of tick bars is that not all trades are equal. Consider that an order to buy 1000 contracts is executed as one transaction, and 10 orders for 100 contracts will count for 10 transactions. In light of this somewhat arbitrary distinction, it may make sense to sample observations for every N contracts exchanged independent of how many trades took place. Since XBT is a BTC swap contract, we will measure the volume in terms of BTC.</p><pre>data_cm_vol = data.assign(cmVol=data[&#39;homeNotional&#39;].cumsum()) <br>total_vol = data_cm_vol.cmVol.values[-1]<br>vol_per_bar = total_vol / num_time_bars<br>vol_per_bar = round(vol_per_bar, -2) # round to the nearest hundred</pre><pre>data_vol_grp = data_cm_vol.assign(grpId=lambda row: row.cmVol // vol_per_bar)</pre><pre>data_vol_vwap =  data_vol_grp.groupby(&#39;grpId&#39;).apply(compute_vwap)<br>data_vol_vwap.set_index(&#39;timestamp&#39;, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*d47o9FKPZh-1-LztLo-Law.png" /><figcaption>XBT time and volume bars</figcaption></figure><p>Note that the volume representation shows an even sharper rally and crash than the tick one (4100+ vs 4000+ peak and ~3800 vs 3900+ trough). By now it should become apparent that the method of aggregation chosen for your bars can affect the way your data is represented.</p><h3>Dollar Bars</h3><p>Even with the tiny dataset used here, you might notice that sampling the data as a function of number of BTC traded doesn’t make sense when the value of BTC relative to USD moves more than 20% in just 3 days. Buying 1 BTC on the morning of 11–27 was a significantly different decision than buying 1 BTC the night of 11–29. Such price volatility is the rationale behind dollar bars — sampling as a function of dollars (or a currency of your choice) exchanged should in theory make the frequency more robust to value fluctuations.</p><pre># code omitted for brevity<br># same as volume bars, except using data[&#39;foreignNotional&#39;] instead of data[&#39;homeNotional&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Ndy88M0kEyKGU1G2hsPKeg.png" /><figcaption>XBT dollar bars</figcaption></figure><p>Note that the BTC volume bars show nearly identical jumps around 11–28 00 and 11–29 00, however the initial spike in dollar bars on 11–28 00 looks relatively mild compared to the later one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*4cXXZ4DZi5AIiOkTWzY7ug.png" /><figcaption>dollar bars vs BTC volume bars</figcaption></figure><p>This is a prime example of differences induced by sampling — even though many bitcoins have changed hands around 11–28 01, their dollar value was relatively lower at that time and so the event is represented as less severe.</p><h3>Imbalance bars</h3><p>Imbalance bars are the type of bars MLDP calls “information-driven”. These extend the ideas of alternative bars to more advanced approaches. Imbalance bars in particular try to sample when there is an unusual imbalance of buying/selling activity, which may imply information asymmetry between market participants. The rationale is that informed traders either buy or sell in large quantities, but rarely do both at the same time. Sampling when imbalance events occur allows us to focus on large moves and ignore less interesting periods.</p><p><strong>Implementing Dollar Imbalance Bars</strong></p><p>Implementing imbalance bars warrants a more detailed explanation. Given dollar volume and prices for each tick, the process is:</p><ol><li>Compute signed flows:</li></ol><ul><li>Compute tick direction (the sign of change in price).</li><li>Multiply tick direction by tick volume.</li></ul><p>2. Accumulate the imbalance bars :</p><ul><li>Starting from the first datapoint, step through the dataset and keep track of the cumulative signed flows (the imbalance).</li><li>Take a sample whenever the absolute value of imbalance exceeds the expected imbalance threshold.</li><li>Update the expectations of imbalance threshold as you see more data.</li></ul><p>Let’s expand each of these steps further.</p><p><strong>1.1 Compute tick direction:</strong></p><p>Given a sequence of <em>N</em> ticks { (<em>p</em>[<em>i</em>], v[<em>i</em>]) } for <em>i </em>∈ 1…<em>N</em> where <em>p</em>[<em>i</em>] is the associated price and <em>v</em>[<em>i</em>] is the dollar volume, we first compute change in price from tick to tick, and then define the sequence {<em>b</em>[<em>i</em>]} for <em>i</em> ∈ 1…<em>N</em>:</p><p>Δ<em>p</em>[i] := <em>p</em>[<em>i</em>]-<em>p</em>[<em>i</em>-1]</p><p><em>b</em>[<em>i</em>] := b[<em>i</em>-1] if Δ<em>p</em>[i] = 0</p><p><em>b</em>[<em>i</em>] := sign(Δ<em>p</em>[i]) otherwise</p><p>Luckily in our dataset the tick directions are already given to us, we just need to convert them from strings to integers.</p><pre>def convert_tick_direction(tick_direction):<br>    if tick_direction in (&#39;PlusTick&#39;, &#39;ZeroPlusTick&#39;):<br>        return 1<br>    elif tick_direction in (&#39;MinusTick&#39;, &#39;ZeroMinusTick&#39;):<br>        return -1<br>    else:<br>        raise ValueError(&#39;converting invalid input: &#39;+ str(tick_direction))</pre><pre>data_timeidx[&#39;tickDirection&#39;] = data_timeidx.tickDirection.map(convert_tick_direction)</pre><p><strong>1.2 Compute signed flows at each tick:</strong></p><p>Signed Flow[<em>i</em>] := <em>b</em>[<em>i</em>] *<em> v</em>[<em>i</em>] is the dollar volume at step <em>i</em></p><pre>data_signed_flow = data_timeidx.assign(bv = data_timeidx.tickDirection * data_timeidx.size)</pre><p><strong>2. Accumulate dollar imbalance bars</strong></p><p>To compute dollar imbalance bars, we step forward through the data, tracking the imbalance since the last sample, and take a sample whenever the magnitude of the imbalance exceeds our expectations. The rule is expanded below.</p><p><em>Sample bar when:</em></p><p><em>|Imbalance| ≥ Expected imbalance</em></p><p><em>where</em></p><p><em>Exp. imbalance := (Expected # of ticks per bar) * |Expected imbalance per tick|</em></p><p>We define the imbalance for a subset of <em>t</em> ticks as<em> θ</em>[<em>t</em>] <em>:= ∑ b</em>[<em>i</em>] <em>* v</em>[<em>i</em>] <em>for i∈1…t</em></p><p>Let <em>T </em>denote the number of ticks per bar, which is not constant. Then, Eₒ[<em>T</em>] is the expected number of ticks per bar, which we estimate as the <a href="https://www.investopedia.com/terms/e/ema.asp">exponentially weighted moving average</a> of <em>T </em>values from prior bars.</p><p>Finally, we estimate the expected imbalance per tick, Eₒ[<em>b*v</em>]<em>, </em>as the exponentially weighted moving average of b[i]*v[i] values from prior bars.</p><p>Putting it all together, we must step iterate over the dataset, and take samples every <em>T* </em>ticks, defined as</p><p><em>T* := argmin( t ) s.t. |θ</em>[<em>t</em>]<em>| ≥ </em>Eₒ[<em>T</em>]<em> * |</em>Eₒ[<em>b*v</em>]<em>|</em></p><p>Important caveats of this procedure:</p><ul><li>At the start, we don’t have any previous bars to base our estimates on, so we must come up with initial values for computing the first threshold.</li><li>As the algorithm accumulates more bars, the EWMA estimates “forget” the initial values in favor of more recent ones. Make sure you set a high enough initial values so that the algorithm has a chance to “warm up” the estimates.</li><li>The algorithm can be quite sensitive to the hyperparameters used for EWMA. Because there is no straightforward way to get the same number of bars as in the previous demos, we will just pick the most convenient/reasonable hyperparameters.</li></ul><p>With that in mind, let’s put the logic into code. I use a <a href="https://gist.github.com/maks-ivanov/24022b2be6c83220b47143bab88619c7">fast implementation</a> of EWMA sourced from <a href="https://stackoverflow.com/a/51392341">stackexchange.</a></p><pre>from fast_ewma import _ewma</pre><pre>abs_Ebv_init = np.abs(data_signed_flow[&#39;bv&#39;].mean())<br>E_T_init = 500000 # 500000 ticks to warm up</pre><pre>def compute_Ts(bvs, E_T_init, abs_Ebv_init):<br>    Ts, i_s = [], []<br>    i_prev, E_T, abs_Ebv  = 0, E_T_init, abs_Ebv_init<br>    <br>    n = bvs.shape[0]<br>    bvs_val = bvs.values.astype(np.float64)<br>    abs_thetas, thresholds = np.zeros(n), np.zeros(n)<br>    abs_thetas[0], cur_theta = np.abs(bvs_val[0]), bvs_val[0]</pre><pre>    for i in range(1, n):<br>        cur_theta += bvs_val[i]<br>        abs_theta = np.abs(cur_theta)<br>        abs_thetas[i] = abs_theta<br>        <br>        threshold = E_T * abs_Ebv<br>        thresholds[i] = threshold<br>        <br>        if abs_theta &gt;= threshold:<br>            cur_theta = 0<br>            Ts.append(np.float64(i - i_prev))<br>            i_s.append(i)<br>            i_prev = i<br>            E_T = _ewma(np.array(Ts), window=np.int64(len(Ts)))[-1]<br>            abs_Ebv = np.abs( _ewma(bvs_val[:i], window=np.int64(E_T_init * 3))[-1] ) # window of 3 bars</pre><pre>    return Ts, abs_thetas, thresholds, i_s</pre><pre>Ts, abs_thetas, thresholds, i_s = compute_Ts(data_signed_flow.bv, E_T_init, abs_Ebv_init)</pre><p>Let’s plot |θ[<em>t</em>]| and the imbalance threshold (Eₒ[<em>T</em>] * |Eₒ[<em>b*v</em>]|) to see what’s going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*VYy4PfTZYOlD86DIKWWIoA.png" /><figcaption>Threshold vs. magnitude of imbalance</figcaption></figure><p>Seems like the sampling frequency is high near where the upward trend picks up and and also near where that same trend reverses. Before we can visualize the bars, we need to group the ticks accordingly.</p><p><strong>Aggregate the ticks into groups based on computed boundaries</strong></p><pre>n = data_signed_flow.shape[0]<br>i_iter = iter(i_s + [n])<br>i_cur = i_iter.__next__()<br>grpId = np.zeros(n)</pre><pre>for i in range(1, n):<br>    if i &lt;= i_cur:<br>        grpId[i] = grpId[i-1]<br>    else:<br>        grpId[i] = grpId[i-1] + 1<br>        i_cur = i_iter.__next__()</pre><p><strong>Putting it all together: Dollar Imbalance Bars</strong></p><pre>data_dollar_imb_grp = data_signed_flow.assign(grpId = grpId)<br>data_dollar_imb_vwap = data_dollar_imb_grp.groupby(&#39;grpId&#39;).apply(compute_vwap).vwap</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*CLgoUwJRTEiy9kR4gqVWmw.png" /><figcaption>Dollar imbalance bars</figcaption></figure><p>We see that DIBs tend to sample when a change in trend is detected. It can be interpreted as DIBs containing the same amount of information about trend changes, which may help us to develop a model for trend following.</p><h3>Summary</h3><p>We’ve used a trade book dataset to compute time, tick, dollar, volume, and dollar imbalance bars on a BTC swap contract. Each alternative approach tells a slightly different story, and each has advantages that depend on the market microstructure and particular use cases.</p><p>To explore this further, consider measuring the statistical properties of each bar series such as kurtosis and serial correlation to see which bars would be easier to model with an ML algorithm. I hope you enjoyed this demo and please reach out if you catch a mistake or have any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745897d4e4ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/financial-machine-learning-part-0-bars-745897d4e4ba">Financial Machine Learning Part 0: Bars</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>