<?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 Mirko Savasta on Medium]]></title>
        <description><![CDATA[Stories by Mirko Savasta on Medium]]></description>
        <link>https://medium.com/@savastamirko?source=rss-9fff65a0aeb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*14TrWrCpAo2Un60980zyFA.jpeg</url>
            <title>Stories by Mirko Savasta on Medium</title>
            <link>https://medium.com/@savastamirko?source=rss-9fff65a0aeb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:43:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@savastamirko/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[Generating synthetic financial time series with WGANs]]></title>
            <link>https://medium.com/data-science/generating-synthetic-financial-time-series-with-wgans-e03596eb7185?source=rss-9fff65a0aeb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e03596eb7185</guid>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Mirko Savasta]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 18:20:28 GMT</pubDate>
            <atom:updated>2023-03-12T09:07:17.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEgQ7upxeGtEiGEaAMFfgw.jpeg" /><figcaption>Looking for a stable equilibrium — Photo by Tyler Milligan on Unsplash</figcaption></figure><h4>A first experiment with Pytorch code</h4><h3>Introduction</h3><p>Overfitting is one of the problems researchers encounter when they try to apply machine learning techniques to time series. This problem occurs because we train our models using the only time series path we know of: the <strong>realized</strong> history. After all, we have only seen one state of the world for our entire life: boring isn’t it? =)</p><p>In particular, not every possible market regime or event can be well represented in our data. In fact, very unlikely events, such as periods of unusually high volatility, are normally underrepresented and this prevents models from being trained well enough. So, when these trained algorithms face new scenarios, they may fail; and this happens especially if we keep them in production for sufficient time without any precaution.</p><p>Now, what if we could teach a model to generate new data for the same asset? What if we had a tool that produced alternative realistic time series that share the same statistical properties of the original ones? With such a tool, we could augment our training set with data about unlikely events or rare market regimes; therefore researchers would be able to build models that generalize better and practitioners would perform superior simulations and trading backtests. In this regard, the authors of a recently published <a href="https://jfds.pm-research.com/content/2/1/76.short">paper</a> in the Journal of Financial Data Science show how training deep models on synthetic data mitigates overfitting and improves performance.</p><p>It turns out that Generative Adversarial Networks (GANs) could do the trick. GANs are a machine learning framework where two neural nets, a generator (G) and a discriminator (D), play a game against each other where the former tries to trick the latter generating fake data that resemble the real thing. When I say “game” I am referring to game theory here!</p><p>No player should win, however: GAN researchers are always looking for a Nash equilibrium between G and D where hopefully — GANs can be hard to train — <strong>the generator has learnt how to produce fake but realistic samples</strong> and the discriminator’s best choice is to guess randomly.</p><h3>Objective of this article</h3><p>My purpose here is not to dive into GANs theory (there are great papers and resources online) but rather to briefly touch the basics and share the results of the experiments I am carrying on with my teammate and friend <a href="https://medium.com/u/802e9b15f86d">Andrea Politano</a>.</p><p>Though our final objective is using one or more trained generators to produce many time series at once, we choose to start simple and proceed gradually. In this respect, we first check if GANs can learn series whose data generating process (DGP) we fully understand. Of course, only a few — if any — understand the DGP of financial asset returns; hence we start generating fake sine waves.</p><h3>Our model</h3><p>We first code a Pytorch dataset to produce different sine functions. Pytorch datasets are convenient utilities which make data loading easier and improve code readability. Check them out <a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a78390f2f8a78cd233d53747205e64b/href">https://medium.com/media/5a78390f2f8a78cd233d53747205e64b/href</a></iframe><p>We then opt for a <a href="https://arxiv.org/abs/1701.07875">Wasserstein GAN</a> (WGAN) as this particular class of models have solid theoretical foundations and significantly improve training stability; in addition, the loss correlates with the generator’s convergence and sample quality — this is extremely useful because researchers do not need to constantly check the generated samples to understand if the model is improving or not. Finally, WGANs are more robust to mode collapse and architectural changes than standard GANs.</p><h4>How do WGANs differ from GANs?</h4><p>The loss function in a standard GAN quantifies the distance between the training and the generated data distributions. In fact, GANs are based on the idea that as the training advances, the model’s parameters are gradually updated and the distribution learnt by G converges to the real data distribution. This convergence must be as smooth as possible and it is essential to remember that <strong>the way this sequence of distributions converges depends on how we compute the distance between each pair of distributions.</strong></p><p>Now, WGANs differ from standard GANs in how they quantify this distance. Regular GANs do so by <a href="https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence">Jensen–Shannon divergence</a> (JS) whereas WGANs use the <a href="https://en.wikipedia.org/wiki/Wasserstein_metric">Wasserstein distance</a>, which is characterized by nicer properties. In particular, the Wasserstein metric is continuous, has well behaved gradients everywhere and therefore allows a smoother convergence in distribution <strong>even when the supports of the true and generated distributions lie in non-overlapping low dimensional manifolds. </strong>Check out this good <a href="https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html">article</a> to explore more details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Pi2FITdbilNceVMU_2H98Q.png" /><figcaption>Image taken directly from the WGANs original paper. It shows how the discriminator of a standard GAN saturates and results in vanishing gradients whereas the WGAN critic provides very clean gradients on all parts of the space.</figcaption></figure><h4>Lipschitz constraint</h4><p>The plain Wasserstein Distance is rather intractable; hence the need to apply a smart trick — Kantorovich-Rubinstein duality — to overcome the obstacle and obtain the final form of our problem. As the theory goes, the function <em>f_w</em> in the new form of our Wasserstein metric must be <a href="https://en.wikipedia.org/wiki/Lipschitz_continuity">K-Lipschitz continuous</a>. <em>f_w </em>is learnt by our critic and belongs to a sequence of parametrized functions; <em>w </em>represents the set of parameters i.e., the weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*cZZRX1lL0Yh-6zXkLwB2nQ.png" /><figcaption>Final form of the objective function — the Wasserstein metric. The first expectation is computed with respect to the real distribution whereas the second expectaction is computed with respect to the noise distribution. z is the latent tensor and g_theta(z) represents the fake data produced by G. This objective function shows that t<em>he critic does not directly attribute a probability. Instead, it is trained to learn a K-Lipschitz continuous function to help compute the the final form of our Wasserstein distance.</em></figcaption></figure><p>We say that a differentiable function is K-Lipschitz continuous if and only if it has gradients with norm at most K everywhere. K is called Lipschitz constant.</p><p>Lipschitz continuity is a promising technique for improving GANs training. Unfortunately, its implementation remains challenging. In fact, this is an active area of research and there are several ways to enforce the constraint. The original WGAN paper proposes weight clipping but we adopt a “<a href="https://arxiv.org/abs/1704.00028">gradient penalty</a>” (GP) approach as weight clipping can cause capacity problems and requires additional parameters to define the space where the weights lie. On the other hand, the GP approach enables stabler training with almost no hyper-parameter tuning.</p><h4>A first architecture</h4><p>Our first architecture comes from this <a href="https://repository.tudelft.nl/islandora/object/uuid%3A51d69925-fb7b-4e82-9ba6-f8295f96705c">thesis</a> which, among other things, presents a WGAN-GP architecture to produce univariate synthetic financial time series — it’s always a good idea not to start from scratch. The proposed architecture is a mix of linear and convolutional layers in both G and D and it works out of the box. Unfortunately, with this setting the training does not look very stable and D is implemented with batch normalization (BN) despite the original WGAN-GP paper clearly prescribes <strong>“No critic batch normalization”</strong>.</p><p>So we get rid of BN and go for spectral normalization (SN). In simple terms, SN ensures D is K-Lipschitz continuous. To do so, it progressively acts on each layer of your critic to bound its Lipschitz constant. Refer to this great <a href="https://christiancosgrove.com/blog/2018/01/04/spectral-normalization-explained.html">article</a> and this <a href="https://arxiv.org/abs/1802.05957">paper</a> for further details.</p><p>Though with SN one could theoretically get rid of the GP term in the loss — SN and GP should be considered alternative ways to enforce Lipschitz continuity — our tests did not support this proposition. Nevertheless, SN improves training stability and makes convergence faster. We, therefore, adopt it both in G and D.</p><p>Finally, the original WGAN-GP paper suggests to use Adam optimizers for both G and D but we empirically found that RMSprop better suited our needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/407aa6a507716645ab501be51da132b7/href">https://medium.com/media/407aa6a507716645ab501be51da132b7/href</a></iframe><p>To give it a try you will also need a piece of code that computes losses, does the backward pass, updates model weights, saves logs, training samples etc… You will find it below. If you need more details about how to use this code please refer to this <a href="https://github.com/mirkosavasta/GANetano">repo</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55cf351f5770aff71b890e2362dcd167/href">https://medium.com/media/55cf351f5770aff71b890e2362dcd167/href</a></iframe><h3>Results</h3><p>The good news is that our model learns to generate realistic sine samples; the bad news is that sines are not asset returns! =) So, what’s the next step to increase our trust in this model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjIuXGzrmSqVAJGnO3mx4g.png" /><figcaption>Different realistic sine waves generated with a trained model</figcaption></figure><p>Why don’t we get rid of simple sines and feed the GAN with samples coming from an <a href="https://en.wikipedia.org/wiki/Autoregressive%E2%80%93moving-average_model">ARMA</a> process whose parameters we know?!</p><p>We choose a simple ARMA(1, 1) process with <strong>p</strong>=0.7 and <strong>q</strong>=0.2, generate real samples with a new Pytorch dataset and train the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c3bbae3b2d88921791970cb94e8adb/href">https://medium.com/media/42c3bbae3b2d88921791970cb94e8adb/href</a></iframe><p>We now generate a hundred of fake samples, estimate <strong>p </strong>and<strong> q </strong>and<strong> </strong>have a look at the results below. <strong><em>p</em></strong><em> and </em><strong><em>q</em></strong><em> are the only parameters of our DGP.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIiP7Q5nj19KF_DrrudYuQ.png" /><figcaption>Synthetic ARMA(1, 1) samples generated with a trained model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cl6M94PySqurHQg67_ux0w.png" /><figcaption>Distributions of the parameter estimates done on synthetic ARMA samples. As it can be seen, the model learns the DGP quite well. In fact, the modes of these distributions are near the true parameters of the DGP, p and q, which are respectively 0.7 and 0.2.</figcaption></figure><p>These results strengthen our trust and encourage further research.</p><h3>Bonus Section</h3><h4>How should losses look?</h4><p>During our first experiments, we kept asking ourselves what to expect from our losses. Of course, everything depends on the training data, the optimization algorithm and the learning rate you choose but we empirically found that successful trainings are characterized by losses that, though not stable in the beginning, then converge gradually towards lower values. All other things being equal, lowering the learning rate may stabilize training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yU--iZhMnno9gD0gKZmPvg.png" /><figcaption>Generator’s loss example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTm7dBF2BIiwXgj3wP2Mdg.png" /><figcaption>Critic’s loss example</figcaption></figure><h4>How to check for mode collapse?</h4><p>To check for mode collapse we use a different latent tensor each time we generate fake samples during training. With such a procedure we can check what happens when sampling different portions of the noise space. If you sample different random tensors and G keeps producing the same series then you are experiencing mode collapse. =(</p><h4>Do GANs provide an advantage over other generating mechanisms?</h4><p>This is an important question I would like to answer with further experiments: GANs complexity must be justified by significantly better performance to be tolerated.</p><h4>GP Limits</h4><p>We have to mention that, according to the authors of this <a href="https://arxiv.org/abs/1904.01184">paper</a>, the standard GP approach may not be the best implementation of Lipschitz regularization. In addition, spectral normalization may unnecessarily constrain the critic and impair its ability to provide sound gradients to G. The authors propose an alternative method to use when the standard approaches fail. We will experiment with their suggestions soon.</p><h4>Why should we train D more than G?</h4><p>A well trained D is vital in a WGAN setting because the critic estimates the Wasserstein distance between the real and fake distributions. An optimal critic will provide good estimates of our distance metric and this, in turn, will cause the gradients to be healthy!</p><h4>Bibliography</h4><ul><li><em>[2019] Towards Efficient and Unbiased Implementation of Lipschitz Continuity in GANs — Zhou, Shen et al</em></li><li><em>[2019] Enriching Financial Datasets with Generative Adversarial Networks, de Meer Pardo</em></li><li><em>[2018] Spectral Normalization for Generative Adversarial Networks — Miyato, Kataoka et al</em></li><li><em>[2017] Improved Training of Wasserstein GANs — Gulrajani, Ahmed et al</em></li><li><em>[2017] Wasserstein GAN — Arjovsky, Chintala et al</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e03596eb7185" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/generating-synthetic-financial-time-series-with-wgans-e03596eb7185">Generating synthetic financial time series with WGANs</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[Information-Driven Bars for Finance]]></title>
            <link>https://medium.com/data-science/information-driven-bars-for-finance-c2b1992da04d?source=rss-9fff65a0aeb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2b1992da04d</guid>
            <category><![CDATA[information-driven-bars]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[de-prado-advances-in-ml]]></category>
            <category><![CDATA[financial-data-sampling]]></category>
            <dc:creator><![CDATA[Mirko Savasta]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 18:50:08 GMT</pubDate>
            <atom:updated>2020-07-23T02:27:24.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hor57pXvQR42QmW-mIS5ew.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@lorenzocafaro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Lorenzo </a>from <a href="https://www.pexels.com/photo/black-and-white-business-chart-computer-241544/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>An informal review of Tick Imbalance Bars</h4><h3>Introduction</h3><p>As you may know, raw financial data is made of ticks, which represent market transactions. Every market transaction is characterized, among other things, by a date, a time, a price and the number of contracts or shares that have been exchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*6mQVlGmZV5e21ZzeSungyQ.png" /><figcaption>An example of raw tick data taken from a securities database</figcaption></figure><p>To represent financial time series you normally use bars, which are aggregations of ticks. But there are several ways to aggregate information; for this reason, many kinds of bars exist (time bars are the most common).</p><p>Observe the market for 5 minutes, note down the first observed price (open), the lowest price (low), the highest price (high) and the price of the last tick that belongs to the chosen time interval (close) and you will have built a 5 minute bar!</p><p>However, markets, unlike humans, do not follow a time clock. They do not process information at constant time intervals. They rather do so event by event, transaction by transaction. So, what if we abandoned the time clock and started sampling market prices using a different logic? We could use the <strong>volume clock</strong> to build volume bars for example; or we could build tick bars and sample prices every time we observe a given amount of new transactions. Volume and tick bars are known sampling methods and I do not think they deserve an entire article as you can find plenty of information on the web.</p><p>But, what happens if we use an <strong>information clock?</strong> What if we sampled prices every time an <em>unexpected</em> amount of information comes to the market? Well, this is precisely the idea behind information-driven bars. Interesting, isn’t it? We are going to introduce the simplest kind of information-driven bars: tick imbalance bars. Marcos Lopez De Prado presents them in his book <a href="https://www.amazon.com/dp/1119482089">Advances in Financial Machine Learning</a> (AFML).</p><h3>What are Tick Imbalance Bars?</h3><p>In a few words, to build this kind of bars we assume that tick imbalance represents informed trading (tick imbalance will be defined soon). So, whenever we observe an unexpected amount of imbalance we sample market prices and create a new bar. Using De Prado’s words:</p><blockquote>The purpose of information-driven bars is to sample more frequently when new information arrives to the market. In this context, the word “information” is used in a market microstructural sense. […] By synchronizing sampling with the arrival of informed traders, we may be able to make decisions before prices reach a new equilibrium level.</blockquote><h4>Definition given in AFML</h4><p>Consider a sequence of ticks {(p_t, v_t)} for t=1, …, T, where p_t and v_t represent price and volume at time t. The tick-rule defines a sequence of tick signs {b_t} for t=1, …, T where b_t can either be 1 or -1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*bTH9Q9Ad88lSYm-x9K9V7A.png" /><figcaption>Definition of tick sign given in AFML</figcaption></figure><p>Next, the tick imbalance can be defined as a partial sum of tick signs over T ticks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*KPQgPFLS0A7pTzyUgNHOWg.png" /><figcaption>Definition of Tick Imbalance given in AFML</figcaption></figure><p>Now, we should sample bars whenever tick imbalances exceed our expectations. This means we must compute a <em>running</em> <em>imbalance</em> for each bar and compare it with our expectation. We will close the bar when the absolute value of the current imbalance is greater than the absolute expected imbalance.</p><p>The book defines <strong>expected imbalance at the beginning of each bar</strong> as the product between the expected number of ticks per bar (T) and the unconditional expectation of the tick sign (b_t). Furthermore, the book states that we can estimate these moments using exponentially weighted moving averages (EWMAs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*82PKW_r7HbHqccQgAtVvyA.jpeg" /><figcaption>Definition of expected imbalance at the beginning of each bar given in AFML</figcaption></figure><p>In particular:</p><ul><li>we can estimate the <strong>expected number of ticks per bar </strong>using an EWMA of the actual number of ticks T of previous bars</li><li>we can estimate the <strong>unconditional expectation of the tick sign</strong> using an EWMA of the tick signs of the previous ticks</li></ul><h3>Review</h3><p>Marcos Lopez De Prado points out that we should use the information clock to sample market prices. Tick Imbalance bars are just the simplest application of this concept and we should build on that to uncover interesting insights. We should come up with new definitions of information and expected information. After all, Marcos Lopez De Prado has just shown us the way and, probably, we should not take his implementation details too seriously. Why?</p><p>First of all, <strong>the proposed bar generating mechanism is heavily affected by how you initialize its parameters </strong>— to produce imbalance bars you must initialize the expected number of ticks per bar (init_T below), the unconditional expectation of the tick sign (E[b_t]) and the alphas that define the two exponential averages used to update our expectations.</p><p>The following plot represents results obtained with more than a thousand simulations. It shows that the number of bars produced for the same time interval decreases as the alpha that defines EWMA(T) increases. In addition, the number of bars decreases when we increase the value of T used to initialize the mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NueC-GIyr7NX5-sol-oaJA.png" /><figcaption>Scatter Plot of the number of generated bars in each simulation VS initialization parameters. The x axis represents the alpha used to update the expected number of ticks. init_T is the value we use to initialize EWMA(T). The EWMA(b_t)’s alpha has been kept constant at 0.005. The unconditional expectation of the tick sign is always initialized with 0.5. Example: If you initialize the mechanism using an EWMA(T)’s alpha slightly greater than 0.2 and an init_T near 2000 you get less than 10 bars for a month of data.</figcaption></figure><p>Naturally enough, the higher is the number of resulting bars, the lower is the amount of information we incorporate in each bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASIcRk9051ujRWwybr-FHA.png" /><figcaption>Scatter Plot of the median imbalance at which bars have been closed in each simulation. Example: If your median imbalance is 2000, 50% of the bars created in a given simulation have been closed with an imbalance ≤ 2000 and 50% of the bars have been closed with an imbalance ≥ 2000. On the x axis you find the number of created bars. The greater the number of bars, the lower the median information content of each bar.</figcaption></figure><p>This means that when we choose how to initialize the bar generating mechanism we are roughly choosing the imbalance threshold we will use to close our bars.</p><p>The plots above only show cases in which the mechanism produced at least 3 bars. It’s important to acknowledge that if the initialized expected imbalance is too high the mechanism will produce only a few bars or will even have a hard time generating a single bar; if it is too low we will instead produce too many bars. Our mechanism does not automatically adjust when your choice of initial parameters is completely wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zI0PZhAbWEdufWTDQFmmPg.png" /><figcaption>In this example, the first expected imbalance threshold has been set too high and no bars have been generated for an entire month of data.</figcaption></figure><p>Secondly, although I like the idea that our expectations are dynamic<em>, </em>I do not really understand the suggested implementation. If we sample the market following AFML, we get heterogeneous bars: each bar has a different information content. And this may be great but <strong>the point is that the amount of information we enclose in each bar and its dynamics are almost out of our control.</strong></p><p>Have another look at the definition of expected imbalance above. The absolute value of the unconditional expectation of b_t can assume values in [0, 1] so what really defines the expected imbalance is the expected number of ticks. This means that the expected imbalance of the next bar could be higher (lower) if it took more (less) ticks to form the last bars. But how can you justify this idea? Why should your imbalance expectations increase if it just took a lot of ticks to reach the imbalance level you were expecting before closing the last bar?</p><p><strong>The threshold at which you close a bar should be determined by other things.</strong> Ideally, I would like to close a bar when the current imbalance reaches a significant threshold, a threshold that tells me that prices will be somehow affected in the next X volume bars for example. Whether this significant threshold should be constant or not is a matter of research.</p><h3>Conclusions</h3><p>In light of the points mentioned above, I decided (for now) to stick with an implementation characterized by constant imbalance expectations. This means that every time I want to build TIBs I must specify the imbalance threshold that will be used to close every bar.</p><p>As Gerald Martinez wrote in his <a href="https://towardsdatascience.com/information-driven-bars-for-financial-machine-learning-imbalance-bars-dda9233058f0">interesting article</a> about imbalance bars, <strong>“the objective of imbalance bars is to early detect a shift in the directionality of the market before a new equilibrium is reached”</strong>. With this objective in mind, I will keep studying to understand how to improve my understanding of the concept. In particular, I would like to understand if significant thresholds exist and whether or not they can be specified dynamically.</p><p>I wrote this article to share my thoughts and start a discussion. Hence, if you have any question or doubt your comments are welcome.</p><h3>Bonus Section</h3><p>The probability of achieving an imbalance level depends on the tick horizon (the number of ticks you are calculating your imbalance on). The plot below shows the empirical distributions of rolling imbalances for different tick horizons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvXITa7J_41-U7kSuxEIGw.png" /><figcaption>Rolling Absolute Imbalance Distributions over different tick horizons. It’s likely to observe an absolute imbalance of 50–100 over an horizon of 5000 ticks. The same imbalance is not likely to be observed over 100 ticks.</figcaption></figure><p>Below you find a plot of TIBs created with a constant expected imbalance paradigm. The blue dots are prices sampled with a volume clock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9rmjQExGRYvirJr2zj9ng.png" /><figcaption>Example of Tick Imbalance bars (candlesticks in the plot) created using a constant expectation paradigm. DAX futures contract. Blue dots are volume bars’ closes.</figcaption></figure><h3>Appendix and code</h3><p>Every plot is based on tick data for the DAX futures contract with expiration December 2019. I used one month of ticks from 01/11/19 to 30/11/19. You may obtain different results with different data.</p><p>Below you find some spaghetti code to replicate my analysis and even create imbalance bars with your tick data. If you modify the spaghetti script a bit, you will be able to create bar ids using a constant expected imbalance paradigm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be289565d558df0ea7659eb81905b895/href">https://medium.com/media/be289565d558df0ea7659eb81905b895/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2b1992da04d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/information-driven-bars-for-finance-c2b1992da04d">Information-Driven Bars for Finance</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[PCA: A Linear Transformation]]></title>
            <link>https://medium.com/analytics-vidhya/pca-a-linear-transformation-f8aacd4eb007?source=rss-9fff65a0aeb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8aacd4eb007</guid>
            <category><![CDATA[linear-transformation]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[apc]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mirko Savasta]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 11:35:00 GMT</pubDate>
            <atom:updated>2023-05-01T14:29:34.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzSCohIM5ABAFdKF3CwDTg.jpeg" /><figcaption><strong>A Rotation in Space</strong> — Photo by <a href="https://www.pexels.com/@kubiceknov?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Jakub Novacek</a> from <a href="https://www.pexels.com/photo/time-lapse-photo-of-stars-on-night-924824/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h3>Introduction</h3><p>Lately I have been trying to deepen my knowledge about Principal Component Analysis. In particular, I wanted to understand why <strong>principal components are the eigenvectors of the covariance matrix of our features </strong>(you will find an answer here).</p><p>In addition, as I really like to see PCA as a linear transformation I looked for a brief article that went straight to the point but I did not find it. So I eventually read an entire paper.</p><p>Not everyone has time for a long read; hence I decided to share what I learned with a brief article. My purpose is not to explain basic linear algebra concepts (there is plenty of good resources online) but rather to provide a concise article that offers you what you won’t likely find in other articles: I just want to fill a small gap.</p><p>If your linear algebra is a bit rusty I suggest going through <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab">The Essence of Linear Algebra</a>, a <strong>great</strong> YouTube series, before reading this piece.</p><h3>What is Principal Component Analysis?</h3><p>Principal component analysis lets us reduce the dimensionality of our data. But how? Well, it lets us discover the directions in which our features vary the most so that we can use them to transform our dataset. In other words, the goal of PCA is to find a new way to express the data so that <strong>feature redundancy is minimized</strong> and we can retain signal and filter out noise.</p><p>PCA assumes that <strong>signal = variance</strong> (i.e. we ignore the directions in which data varies the least) and that variance can be decomposed in <strong>orthogonal constituents </strong>(i.e. our new features will have zero covariance). Finally, PCA uses a <strong>linear</strong> transformation to re-express the data (i.e. PCA has nothing to do with nonlinear combinations of our features).</p><h3>PCA as a Linear Transformation</h3><p>Let’s start from our <strong>centered</strong> dataset <strong>X</strong>, an <em>m </em>times<em> n </em>matrix<em> </em>where<em> m </em>is the number of features and <em>n</em> is the number of instances.</p><p>With PCA we apply an orthogonal transformation <strong>P</strong> to <strong>X </strong>in order to get a new representation of our data. We call this representation <strong>Y</strong>. To transform <strong>X</strong> we just pre-multiply it by <strong>P </strong>as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*PAWrLWL9-AuIrR6XQElG4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*PuH0OdvJ9q5NHKCUQANX9Q.png" /></figure><p>But wait, what is an orthogonal transformation? <strong>Orthogonal transformations</strong> are linear transformations represented by <strong>orthogonal matrices </strong>whose rows and columns are orthogonal vectors with unit norm.</p><p>Ok, so we have just understood that PCA is a linear transformation that can be represented by a special matrix. But, why do we multiply <strong>P </strong>times <strong>X</strong>?</p><p>Let’s look at the matrices above. The rows of <strong>P</strong> are called principal components. Each column of <strong>Y </strong>contains elements that are a dot product between the <em>jth </em>row<em> </em>of <strong>P </strong>and the<strong> </strong><em>ith </em>column of <strong>X</strong>. Each dot product here represents a projection of a point from feature space onto a principal component (If you do not know what a projection is, I suggest you “The Essence of Linear Algebra”, which I sponsored above).</p><p>Hence, <strong>Y </strong>contains projections of the original features onto the space spanned by our principal components, which are unit vectors. In other words, multiplying <strong>P </strong>times <strong>X</strong> means projecting <strong>X</strong> onto the space spanned by the rows of <strong>P</strong>.</p><p>Note that <strong>once we know</strong> <strong>P we can choose how many components to use to span the new feature space</strong>. This determines how many transformed features we are going to retain (i.e. how many rows of <strong>Y </strong>we will use in our models or visualizations). Here comes the <strong>dimensionality reduction!</strong> But how should we choose the components to retain? According to our assumption signal IS variance. Hence we are going to retain the components with greater variance.</p><h3>How to find P?</h3><p>Remember that the objective of our transformation is <strong>minimizing redundancy to retain signal and filter out noise.</strong></p><p>What’s redundancy? Well, if we can express a set <strong>A</strong> of our features as a linear combination of a set <strong>B</strong> of other features then we say that features belonging to set <strong>A </strong>are redundant. We know that covariance measures the magnitude of linear relationship among features. Hence, to minimize redundancy we will minimize covariance (orthogonalizing our features will indeed bring covariance terms to zero).</p><p>To find <strong>P</strong> we need to start from <strong>C</strong>,<strong> </strong>the square symmetric covariance matrix of <strong>X </strong>whose diagonal terms are variances and whose off-diagonal terms are covariances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*9jzrN8yGJn7UMs9uRy_0Dg.png" /><figcaption>Covariance Matrix of X</figcaption></figure><p>Now, to minimize redundancy, our orthogonal matrix <strong>P</strong> will have to transform <strong>X </strong>so that<strong> D</strong>, the covariance matrix of <strong>Y, </strong>becomes<strong> </strong>diagonal (no covariance terms). But what’s <strong>D</strong>? It is a function of <strong>C</strong> and <strong>P </strong><em>(start from the covariance of Y - just use Y instead of X in the formula above - and use a pencil to derive it).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*8TAT0F8fnxVPHGmY2D5JCg.png" /><figcaption>Covariance Matrix of Y</figcaption></figure><p>Now, how can we choose <strong>P</strong> to<strong> </strong>diagonalize <strong>D</strong>?</p><p>It turns out that any symmetric matrix can be decomposed using an orthogonal matrix of its eigenvectors <strong>E </strong>and a diagonal matrix <strong>V </strong>filled<strong> </strong>with eigenvalues. This is related to the concept of <a href="https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix">eigendecomposition</a> of a matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*OSp9lLg9lXWtZK_e2EUZKA.png" /><figcaption>Eigendecomposition of a symmetric matrix</figcaption></figure><p>Now we can plug <strong>C</strong> into <strong>D</strong>’s formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*oPYlUukPkxomTCJuB3rNpw.png" /></figure><p>If we choose <strong>P</strong> = <strong>E</strong> <strong>transpose</strong> we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*XdJh9d24mbH5MAPkJceX2Q.png" /></figure><p>Remember that the product of orthogonal matrices is an identity matrix.</p><p>We have just discovered that <strong>P</strong>’s <strong>principal components are the eigenvectors of the covariance matrix of X</strong>.</p><p>As already mentioned, the most important principal components are the ones along whose axes our new features vary the most. If we want to rank our principal components using variance then we can use <strong>D</strong>. In fact, <strong>D</strong>’s diagonal contains variances of our new features along our new orthogonal axes (the principal components we choose the retain). I wrote “new axes”: yes this linear transformation implies a change of basis.</p><p>That’s it!</p><p>In case you are interested, the paper I read is <a href="https://arxiv.org/abs/1404.1100"><em>A Tutorial on Principal Component Analysis</em></a><em> </em>by Jonathon Shlens.</p><p>If you think something could be improved, please let me know.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8aacd4eb007" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/pca-a-linear-transformation-f8aacd4eb007">PCA: A Linear Transformation</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>