<?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 Gil-Arnaud Coche on Medium]]></title>
        <description><![CDATA[Stories by Gil-Arnaud Coche on Medium]]></description>
        <link>https://medium.com/@quantitative-modelling-for-fun?source=rss-1087a410ef00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-baPO11MdMgiDQo7p61gw.jpeg</url>
            <title>Stories by Gil-Arnaud Coche on Medium</title>
            <link>https://medium.com/@quantitative-modelling-for-fun?source=rss-1087a410ef00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:22:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@quantitative-modelling-for-fun/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[A physicist view on Finance (VII) — Optimal Execution, let’s revisit two years later…]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-finance-vii-optimal-execution-lets-revisit-two-years-later-ece479221785?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece479221785</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[optimal-execution]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 02:19:34 GMT</pubDate>
            <atom:updated>2025-12-23T18:17:03.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on Finance (VII) — Optimal Execution, let’s revisit two years later…</h3><p>Say you are trading on your own and want to clarify, once and for all, optimal execution. What execution profile should you choose?<br><a href="https://github.com/Gilt0/optimexec"><em>Link to the GitHub</em></a></p><p><strong>This article is for educational purposes only. Numerical examples rely on strong assumptions about liquidity and participation rates and are not trading recommendations.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRR_O2sOEPvY0IgyBmTy-g.png" /><figcaption>ロジェ (Roje) wondering how to execute his trade.</figcaption></figure><p>A bit more than two years ago, I discussed models of optimal executions in <a href="https://medium.com/@quantitative-modelling-for-fun/optimal-execution-yet-another-theory-d6b6b0f8fc68"><em>this blog article</em></a>. Here I’ll pursue the research with this additional context:</p><ul><li>meet ロジェ (Roje), a solo trader. He has hands-on experience on trading impact as, on occasion, executed price has moved away during trades,</li><li>he is familiar with foundational work of <a href="https://static1.squarespace.com/static/5df018ec4c9d61288094246c/t/5e39db229a16b072d97fce9b/1754575862869/Optimal+Execution+of+Portfolio+Transaction+_+Almgren%26Chriss+1999.pdf">Almgren Chris</a> or Bouchaud — always advises his trader peers to start <a href="https://arxiv.org/pdf/cond-mat/0307332">here</a> and pull the thread from there,</li><li>he does not have large trade datasets to calibrate impact functions of any shape or form,</li><li>he mainly trades crypto so he has access to usual API’s.</li></ul><p>Because ロジェ does not have a massive enough trade dataset, traditional models are simply unavailable, and he sets on building a naive step-by-step approach with available data: klines and order book snapshots from Binance.</p><p><strong>Objective:</strong> derive an algorithm that computes the optimal trading profile to be used in his trading.</p><h3>ロジェ the solo trader</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-6EyxTJKfnVLW_VD8C55A.png" /></figure><p>ロジェ trades every <em>t = n.𝛕,</em> a quantity <em>qₙ = 𝛚ₙ.Q </em>and<em> Q</em> is the total quantity to be traded — note that the sum of <em>𝛚ₙ</em>’s is thus 1… He will be posting both aggressively and passively, but a conservative estimate of trading costs is easily done with an aggressive only approach.</p><p>If the order book offers a liquidity <em>𝝌(𝜹)</em>¹<em> </em>at price <em>b + 𝜹 </em>where <em>b</em> is the best price and <em>𝜹 </em>the depth on the side of interest of the order book, then trading <em>q</em> has an impact of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*QfA2UDjMjqG4v_h1-Ewcnw.png" /></figure><blockquote>Note that this impact is only mechanical and related to order book depletion. Informational impact requires the existence of a trade dataset that ロジェ cannot get access to.<br>Additionally, order books do not indicate hidden orders therefore computed impact may be over-estimated, but in a worst case scenario, this is still acceptable.</blockquote><p>Considering all trades done at time intervals where the mid price is <em>mₙ </em>and the spread is <em>s</em>, the executed price is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uoZbgQQb5BgYMLW2B0pIBA.png" /></figure><p>In optimal execution trading, performance is assessed against a price benchmark. Institutions use 4 classical benchmarks and ロジェ wants to see if one should be more exclusively used than the others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUnMYQ_u3D-2izLVUOuyZw.png" /></figure><blockquote>Note that the Volume In-Line and the VWAP executions are strictly equivalent using the formula 𝛎 𝚺 vₙ = Q. In the following focus is on VWAP, even if the implementation of these strategies is not exactly the same, the VWAP has an end of life, the In-Line has rate constraint.</blockquote><p>After a trade, ロジェ wants to know how much he slipped from the benchmark and this slip<em> </em>is measured by the s<em>lippage</em>², which mathematically is expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kee0N77-nMRSocowWvZCaA.png" /></figure><p>The slippage <em>𝓢 </em>is the sum of a random term accounting for market variability and a second term directly related to the mechanical impact my trades have.</p><p>¹ <em>𝝌(𝜹) was referred to as the depth distribution fₙ(δ) in my earlier post.<br></em>² <em>The slippage 𝓢 is usually dimensionless, but monetary quantities to simplify the maths. Would the slippage be dimensionless, that the denominator 𝓑(N) would far increase mathematical complexities…</em></p><h3>The Optimization Problem</h3><p>Now ロジェ moves on to the trading profile or, in more layman terms, the trading strategy, he needs for his execution. Mathematically, it is symbolized by the vector <strong><em>𝛚</em></strong> and its components <em>𝛚ₙ</em>.</p><p>That strategy needs to balance a trade-off between market risk and price impact.</p><h4>The intuition of the trade-off</h4><p>The slippage is the contribution of two terms very different in nature as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGW7hFmFNh3qpS-nXVIPsQ.png" /></figure><p>On the one hand, the market exposure can have a dramatic effect on trade performance when prices move adversely, <em>i.e.</em> the price suddenly rises (drops) as you buy (sell). Therefore as a trade lasts, it increases the probability of such an event, making it desirable to trade as fast as possible.</p><p>On the other hand, liquidity is limited as <em>𝜹(𝝌) </em>offers limited supply of participants willing to exchange with us at every time step. And as <em>𝜹(𝝌) </em>increases with <em>𝝌</em>, the more we trade at each interval, the more costly it gets. These two reasons make it desirable to trade as slow as possible.</p><p>And therefore, ロジェ needs to find a mathematical formulation that encompasses this trade-off and outputs a trading strategy that balances between these two extremes.</p><h4>Impact function</h4><p>The liquidity contribution effectively measures the price impact of the trade. It requires no work at all as it is the sum of the spread crossing and all of the order book consumptions at every trading step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF4FdnKtcuXXnhuai2dfug.png" /></figure><p>The minimum of this function, under budget constraint, is straightforward. The TWAP profile is actually its optimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sy5PbDb06IIYncMx_DLgRg.png" /></figure><p>This gives the optimal impact execution profile which we will note as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3Ai29Vs1m1VIRdVT-uvRg.png" /></figure><h4>Risk function</h4><p>The market exposure requires a little work as, in itself, it is a random quantity that can take an infinite amount of values.</p><p>When it comes to risk assessment, the worst case scenario is the one ロジェ wants to be covered from. But, the worst case scenarii are subjective and ロジェ’s worst case is not your worst case.</p><p>Often a quantile of level <em>𝛂</em> is considered on PnL. The philosophy behind is that a ratio <em>𝛂</em> of bad scenarii will be covered by the model. The higher the value of <em>𝛂</em>, the more risk averse is the calculation.</p><p>So let’s do the exact same thing here and define</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBhfsZJO1wBpNpzA-g-VtQ.png" /></figure><p>Note that the optimum under budget constraint is also easy to find and requires the trading profile to be equal to the benchmark profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-w-xBMnjKv3pDYwr16sxw.png" /></figure><p>This gives the optimal risk execution profile which we will note as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90W8x2nxSthJRdI7oxj0Jw.png" /></figure><p>This profile should not really be a surprise as by choosing to trade like the benchmark, effectively the market exposure becomes 0…</p><h4>Optimization Problem</h4><p>Now that we have the two terms central to our tradeoff, the simplest optimization problem is to minimize the sum of these two terms. From an accounting perspective, we are minimizing the costs related to trading, <em>i.e.</em> the Value at Risk or VaR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_Ni6S09XvnfYT5nqhOTzg.png" /></figure><p>When using scipy on the problem above, ロジェ found instabilities and far too many iterations. He could have switched to a different approach where the Variance is minimized under controlled the costs, as he had seen it in brokerage firms where he worked, but he always preferred clear accounting models to optimize, so he wants to stick to the model.</p><p>Instead he decides to look for an optimum on the convex set made by the two solutions introduced earlier. <br>His thinking is rather straight forward, both terms are optima of individual cost contributions. Then for sure a convex combination of these two will ensure:</p><ul><li>that the sum of all terms in the profile is one</li><li>an execution profile that is at least as good as the best of both profiles.</li></ul><p>Therefore, he focuses his search on a profile in the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tN2irDTFEOlQjU-fI2Hqtg.png" /></figure><h4>The tool suite</h4><p>If you clone the repo, there is one script of great importance and it is script/run_pipeline.py .</p><p>Calling other scripts in the folder it essentially</p><ul><li>gets the klines from Binance API for volume profile generation (30m klines) and those for the actual trading profile computation (5m klines) ;</li><li>gets the order book snapshot (5000 levels) from Binance API at the time of the run to extract the impact curves ;</li><li>plots the volume and liquidity profiles (for illustration purposes only), volume profiles ;</li><li>runs the optimization to obtain the optimal.</li></ul><pre>python script/run_pipeline.py \<br>  --ticker &lt;TICKER&gt; \<br>  --lookback-days 90 \<br>  --intervals 5m,30m \<br>  --limit 5000 \<br>  --slot-start 5 \<br>  --slot-end 40 \<br>  --optimizer-side buy \<br>  --optimizer-N 288 \<br>  --optimizer-Q 75000 \<br>  --optimizer-benchmark vwap \<br>  --optimizer-alpha 0.51 \<br>  --optimizer-xatol 1e-8 \<br>  --show-plot</pre><p>ロジェ focused on both BTC and ETH. And here are the results.</p><p><em>Please refer to the </em><a href="https://github.com/Gilt0/optimexec"><em>GitHub</em></a><em> page if you wish to have more details on the other scripts and want to test them independently.</em></p><h4>Liquidity Profile</h4><p>The liquidity profiles for both the buy (ask) and sell (bid) sides are suprisingly similar and noticeably linear at the begining of the profiles. In the depth of both books, the price impact increases at higher rates: for each extra unit of token traded, the impact premium gets higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPjegfKFl8vKE-4Vd7QpcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypCbTHj9xTx-48Vy6VDRPg.png" /><figcaption>BTCUSDT generated on 2025–12–19 at 21:24:37 UTC (left) — ETHUSDT generated on 2025–12–19 at 21:28:00 UTC (right)</figcaption></figure><h4>Volume Profile</h4><p>Looking at volume profiles is of no other interest than gaining some intuition on what VWAP trading profiles could look like when they focus on risk only¹.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKP7C6EnZw7OqhHU5FJfSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REJrvz4C1edga58AaPFNwg.png" /><figcaption>BTCUSDT 30m 2025–09–20 to 2025–12–19 (slots: 5–40) (left) — ETHUSDT 30m 2025–09–20 to 2025–12–19 (slots: 5–40) (right)</figcaption></figure><p>An interesting fact is the importance of the American Markets on the BTC and ETH trading activity. The spike of slot 29 (therefore about 14:30 UTC) corresponds to the beginning of trading over the Atlantic. The volumes are about 6% of the total volumes traded in a single day while during most European markets activity, the volumes are 2–3% of the ADV.</p><p>¹ <em>In practice, these profiles are extremly important for the implementation of the execution: they are a central part in the estimation of volumes as we discussed in this </em><a href="https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-ai-ii-time-series-in-finance-e868f7462d74"><em>post</em></a><em> on Shallow Neural Networks for liquidity prediction.</em></p><h4>Trading Profiles</h4><h4>TWAP</h4><p>This benchmark, under this model, is always optimal! This is because both Risk and Impact are minimized by a constant profile.</p><p>So not much to report here…</p><h4>VWAP</h4><p>VWAP on the other hand, because it encourages slots with higher impact, it necessarily will have to compensate elsewhere for these high impact slots.</p><p>Below we can see few graphs where optima have been found for input parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*r0bOu01A7EI-DiOEvzPyLg.png" /><figcaption>Optimized schedule for BTCUSDT with OB of depth 5000, fetched on 2025–12–19 at 07–22–28 UTC, and klines of 5m with a lookback of 90d starting on 2025–09–20 at 00:00:00 and ending on 2025–12–19 at 23:55:00, for a aggressive buy order of Q=25000 BTC over <em>N = 288</em> slots (one full day) for the VWAP with a quantile of 51%.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*TH9bzUxdDEJjYHG87d851w.png" /><figcaption>Optimized schedule for ETHUSDT with OB of depth 5000, fetched on 2025–12–19 at 21–28–00 UTC , and klines of 5m with a lookback of 90d starting on 2025–09–20 at 00:00:00 and ending on 2025–12–19 at 23:55:00, for an aggressive buy order of Q=120000 ETH over N = 288 slots (one full day) for the VWAP with a quantile of 51%.</figcaption></figure><h4>Implementation Shortfall</h4><p>Implementation Shortfall ends up having profiles that indeed convexely mix the benchmark with the TWAP. As a reminder, the profile that suppresses the risk on the IS benchmark is a spike at <em>t = 0 </em>with everything traded in one go<em>. </em>Therefore, solutions here will be considering a profile where some is traded immediately, the rest is traded at constant rate over the trading horizon.</p><p>Have a look at the graphs below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*RjSS4BlCTbzck00N-zuh_A.png" /><figcaption>Optimized schedule for BTCUSDT with OB of depth 5000, fetched on 2025–12–20 at 10–25–23 UTC , and klines of 5m with a lookback of 90d starting on 2025–09–21 at 00:00:00 and ending on 2025–12–20 at 23:55:00, for an aggressive buy order of Q=500 BTC over N = 288 slots (one full day) for the IS with a quantile of 99.9%.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*RgLuy9f0Bs2mLnoLw0LSwQ.png" /><figcaption>Optimized schedule for ETHUSDT with OB of depth 5000, fetched on 2025–12–19 at 21–28–00 UTC , and klines of 5m with a lookback of 90d starting on 2025–09–20 at 00:00:00 and ending on 2025–12–19 at 23:55:00, for an aggressive buy order of Q=1000 ETH over N = 288 slots (one full day) for the IS with a quantile of 51%.</figcaption></figure><h4>Critics about the profiles</h4><p>Before moving on… ロジェ tuned the parameters to be able to show visually convincing solutions, but</p><ul><li>amounts are grotesque for him as he will never trade, on his own account 500 BTC — which is about 44 million USDT, or even less 25000 BTC — as it is about 2.2 trillion USDT…</li><li>quantiles are unstable, while VWAP requires a level close to 50% for the optimizer to output something else than a VWAP profile, for the involved amounts IS requires on the other hand levels close to 100% to have some penetration on the first trade like the benchmark profile suggests…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Q7S2jzpHtU371KdXm45wLg.png" /><figcaption>Optimized schedule for BTCUSDT with OB of depth 5000, fetched on 2025–12–20 at 10–37–12 UTC, and klines of 5m with a lookback of 90d starting on 2025–09–21 at 00:00:00 and ending on 2025–12–20 at 23:55:00, for a aggressive buy order of Q=500 BTC over <em>N = 288</em> slots (one full day) for the <strong>VWAP</strong> with a quantile of <strong>95%</strong>.</figcaption></figure><p>From looking at this profiles and computation results, ロジェ realizes that:</p><p>(i) unless he would be extremely risk taking, there are no reason to not follow the VWAP strategy exactly like the benchmark;</p><p>(ii) although the VWAP or the TWAP is an interesting approach for institutional brokers as it gives them the upper hand on risk exposure, he is more interested in not loosing the value of his position;</p><p>(iii) as most other of his solo trader friends, he marks his positions with the mid-price at the moment of his decision making, so really an IS benchmark should be the way to approach the problem.</p><p><strong>ロジェは「IS it shall be!」と考えました。</strong></p><h3>IS and optimal horizon</h3><p>One last question persists in ロジェ’s mind. If IS with its optimal profile is the best assumption for him, what would be the optimal horizon then? Is there even one?</p><h4>VWAP’s and TWAP’s optimal horizons</h4><p>TWAP and VWAP do not have optimal horizons from a risk or impact perspectives as we defined them. This is because VWAP and TWAP profiles cannot reach an optimal impact: only an inifinite horizon allows for minimal impact. But an infinite horizon is not aceptable.</p><p>Therefore the only other option is to control something else: the trading rate (as in In-Line) or set an horizon based on price volatility. In the latter, accepting a price variation of about <em>x</em> sets the horizon as <em>(xm₀/𝝈)²…</em></p><p>That is all really one can do in that regard.</p><h4>IS benchmark with a TWAP schedule</h4><p>ロジェ plugs, just out of curiosity, a TWAP schedule in the risk and impact costs functions for a IS benchmark. He gets the following mathematical expressions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1y8oOKwCVPossLU_9Us8ZQ.png" /></figure><p>By taking the derivatives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7gdTzMCc8X1ONVN_yJ9Vw.png" /></figure><p>it becomes apparent that the risk function is strictly increasing while the impact function is strictly decreasing. The figure below will help in understanding that the sum of both functions necessarily have a minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*jwLdHES6qQJhc3i0PEwRfw.png" /><figcaption>Principles behind the existence of an optimal horizon for a TWAP schedule with an IS benchmark.</figcaption></figure><p>Surely, with a more generic profile shape mixing immediate sell and TWAP like ロジェ found earlier, there could be an optimum as well. At least it’s worth the try.</p><h4>How many intervals to trade 10 BTC (~0.0005% Binance ADV)?</h4><p>ロジェ usually has positions of about 100,000 USDT and running the program for 10 BTC. A priori, this is a really tiny share of the ADV therefore the number of slots should be very close to 1 if not equal to 1.</p><p>Unsurprisingly, the cost impact is negligible and the optimal schedule is with only one slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*D3M1M8IXuS5BYHASYm1goA.png" /><figcaption>Optimal number of 5 min trading slots for BTCUSDT (buy Q = 10 𝜶 = 95%)</figcaption></figure><h4>How many intervals to trade 500 BTC (~2.5% Binance ADV)?</h4><p>Out of curiosity, what would happen for 500 BTC? This is much larger chunk of the ADV and thus there can be expectations for a longer thrading schedule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*1MqSuH1iRaHIcQn8RA4MDg.png" /><figcaption>Optimal number of 5 min trading slots for BTCUSDT (buy Q = 500 𝜶 = 95%)</figcaption></figure><p>And indeed, the optimal scedule indicate that 4 slots would be necessary. By diminishing the risk aversion, the impact cost become more preponderant and results in 5 slots being optimal for 𝜶 = 75% and 8 slots of 5 min for 𝜶 = 60%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*j4zPdr8vnOIOtyuAB1Ovxg.png" /><figcaption>Optimal number of 5 min trading slots for BTCUSDT (buy Q = 500 𝜶 = 75%)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*RzujDz8cw3v3UG8c_ccEpA.png" /><figcaption>Optimal number of 5 min trading slots for BTCUSDT (buy Q = 500 𝜶 = 60%)</figcaption></figure><h4>And to trade 100,000,000 MEME (~4.7% Binance ADV)?</h4><p>Now for a far less liquid token like MEME, on the MEMEUSDT order book, 100,000 USDT is about 5% of the ADV. For a risk aversion of <em>𝜶 = 95%</em>, 4 slots will be necessary, while for <em>𝜶 = 60%</em>, 7 slots are optimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*Ie7rG1_Q6yPp9_uTG0cCrg.png" /><figcaption>Optimal number of 5 min trading slots for MEMEUSDT (buy Q = 100,000,000 𝜶 = 95%)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*qhxk9N0Jg4ylGCfx_pBFuQ.png" /><figcaption>Optimal number of 5 min trading slots for MEMEUSDT (buy Q = 100,000,000 𝜶 = 60%)</figcaption></figure><p>Notice however that the optimal slippage is estimated at 0.000,02 USDT . It seems small, however for 100,000,000 tokens, it adds up to 2000 USDT!</p><h3>Concluding remarks and further work</h3><p>With this toy model, despite its simplicity, ロジェ found many interesting facts:</p><ul><li>even without a huge trade data set, some care can be provided to execution;</li><li>constant OB liquidity means TWAP is always optimal;</li><li>pure VWAP and TWAP schedules, although justified mainly for sell side firms, mitigate completely the risk if well executed;</li><li>for buy side, IS is of more interest and provides an optimal duration with its optimal schedule;</li><li>for small investors, for illiquid asset substantial funds can be saved with careful execution — see the MEME example above.</li></ul><p>Nonetheless, because of its simplicity, it is full of limitations</p><ul><li>Orderbook snapshot is unique! A first improvement would be to average over a long enough period of time (about 90 days) to get a more accurate estimate of OB depth.</li><li><em>𝜹(𝝌) </em>is a constant in the model and in reality and it most probably is not — see figures below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnkrbqYVaXw-VSbHAei84w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-D7B-8ggxG291QWBwkZ9g.png" /><figcaption>BTCUSDT OB fetched on 2025–12–20 at 10:25:23 UTC (left) —BTCUSDT OB fetched on 2025–12–20 at 10:37:12Z</figcaption></figure><ul><li>With a varying liquidity profile, as the profile may have coherent variations with the volume profile (<em>i.e. </em>more volume, less rate of impact) and the VWAP may be more advantageous instead of a TWAP.</li><li>Impact is usually more subtle than this.<br>(1) — There are self interacting effects from the trade on the price impact. In other words, the actions performed at time <em>n𝛕</em> will affect any ulterior time <em>n’𝛕 </em>liquidity and potentially increase price impact.<br>(2) — There are hidden orders on the order book and thus impact may be dampened by this hidden liquidity.</li></ul><p>Whether the two effects offset each other is an interesting project however, it requires significant trade data. Without said data, it is beyond the scope of this work1.</p><p>Two important improvements should be considered before using the module in a production environment:<br>(i) orderbook data should be collected so <em>𝝌ₙ(δ) </em>may be estimated for all <em>n</em>’s,<br>(ii) the profile start time should be an input and not defaulted to 12:00…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece479221785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist Vue on Full-Stack development — Fun with Percolation Theory]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-vue-on-full-stack-development-fun-with-percolation-theory-aa6196530225?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6196530225</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[percolation-theory]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 02:26:18 GMT</pubDate>
            <atom:updated>2024-06-04T22:59:08.632Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist Vue on Full-Stack development — Fun with Percolation Theory</h3><p>When Vue.js gives us the tools to explore percolation theory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmaUG6opzJzWtN4hSu0ouQ.png" /><figcaption>“Murugan percolat[ing] life through dimensional planes” (Dall.e)</figcaption></figure><p>2019 was sort of a year of spiritual quest. I had never been much of a believer in the supernatural and I still am not that much of a believer. However, as I was investigating on different religions across the world, I discovered that religions were an incredible lens into civilisation interconnections. As a keen wonderer of the Human Evolution and History, I read about Sumerianism, Abrahamic religions, Zoroastrian — I even have a copy of the Avesta!, Hinduism, Jainism, Buddhism, Tengrism, Taoism, Shintoism… And I was mesmerized how myths could travel and be the source of other myths in other parts of the world.</p><p>As a student of an <a href="https://muaythaisangha.com/">Hindu Martial School in the North of Chiang Mai Thailand</a>, Murugan was the main deity students had to bow to in order to show gratitude to the teachings they were receiving. Of course, I looked into Murugan… He is a formidable War Deity, son of Shiva and Shakti, who happens, according to some accounts, to have <a href="https://qr.ae/psIsno">travelled through the ages and times to other mythologies</a>.</p><blockquote>The latter link is not a scientific investigation but an interesting starting point if you are motivated to do your own research.<br>(Spoiler alert) One of my favourite account is <a href="https://www.quora.com/The-East-Africans-worship-a-god-called-Murungu-who-is-the-exact-counterpart-of-the-Tamil-god-Murugan-Both-have-phallic-aspects-Both-reside-in-mountains-Are-they-related"><strong>Murungu</strong></a><strong>:</strong> as a pure product of western education, I find it mind blowing, enchanting, humbling, fascinating to realize that Dravidians possibly had trade relationships with Eastern Africa. History of the World and the Human race is full of wonders and it certainly did not start in 1789, 1492, 476 or 1...</blockquote><p>What does all of this have to do with our current post?</p><p>Well… Not much to be quite fair! I only mention it because back then, I remember reading somewhere that “Murugan percolates life through the dimensional planes”. The phrase stayed with me, it just sounded too good to be forgotten. And as I was writing this blog post, the phrase came back to me and would not leave me. It had to be my illustration.</p><p>Why am I doing all of this? A physicist friend of mine is thinking to leave academia for Full Stack development. We had a chat and I thought that a write up on a topic he loves would help him. And he loves Percolation Theory… So I thought I would write a webapp displaying dynamic percolation in a grid using Vue.js and Golang.</p><p>My friend, you know who you are, this is for you. 行くぞ！</p><h3>Percolation theory</h3><h4>Some basics</h4><p>If you check <a href="https://en.wikipedia.org/wiki/Percolation_theory">Wikipedia</a> up, the first sentence of the percolation theory page</p><p><em>“In statistical physics and mathematics, percolation theory describes the behavior of a network when nodes or links are added.”</em></p><p>not very insightful… It becomes a little more helpful later when transition phase is brought up. When you have a medium that can be described locally as a binary node connected to other binary nodes, and if these nodes can take the values 0 or 1 randomly, collective effect can occur where below some threshold parameter (often temperature in the context of entropy-energy systems) most nodes have a value of 0 and above that threshold, most nodes take on the value 1.</p><p>In terms of applications, networks are very useful to model conductive metals, porous rocks or even trading agents or social groups.</p><p>One thing that always comes back is the critical probability. Critical probability is a probability value of being a dark nodes (value <em>1</em>) above which, a cluster connects the left side of the grid to its right side. Below that probability, spanning clusters usually do not form — hence the phase transition at a macro scale: the metal becomes conductive, the well starts producing oil, agents start selling massively, etc.</p><p>As pictures are worth a thousand word, see the grid belows to illustrate that point. In two dimensions, know that the critical probability is <em>0.5</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Cc4DMY_zOk1o3CHBNnyig.png" /><figcaption>Below critical probability, spanning clusters <strong>do not</strong> form</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tzY-f1i2eSnNnHUxR7wSw.png" /><figcaption>Above critical probability, spanning clusters <strong>do</strong> form</figcaption></figure><h4>Dynamic transition matrix</h4><p>To spice things up a little, let’s consider a dynamic situation where at every time step <em>Δt</em>, each node is either switched from light to dark or remains in its state. In other words we introduce the probabilities</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Scahgbt7MWqz7yxk6IMaQ.png" /></figure><p>which we can gather in a matrix called the Transition Matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKIfYxfDTr-ena1pRd8e4A.png" /></figure><p>The transition matrix can be extended to compute the probability for a node to be light or dark after <em>n</em> iterations. This is obtained through a recurrence like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUOlR_c09nINmY33eVcblw.png" /></figure><p>This recurrence is very handy to compute (if it exists) the equilibrium probability distribution for that transition matrix. If that equilibrium exists, then surely it will satisfy the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qGAkIRiW7OBydkONLQDGQ.png" /></figure><p>which leads to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a95iH6F2fq6d6pYTD3sEQg.png" /></figure><p><em>π₁</em> can then be compared to the critical probability we introduced above to assess whether a full connexion can be possible at every time step.</p><p>Before moving on to the website implementation This type of dynamics is often referred to as a <strong>Markovian dynamics</strong>.</p><h3>Backend</h3><p>The backend is there to run computations and manage data accesses when it is required. In our case, it will only be running computations as no DB is included in the system.</p><p>I chose Golang because it is a common choice for backend development. It will be convenient when writing multithreading code: it was designed for these kinds of tasks and performs really well. And I want you, my friend, to not think that “Just knowing python is enough for backend developement.” :)</p><h4>Markovian Updates</h4><p>The most critical part of the backend is the computing function for the status updates in the grid.</p><pre>func (s *Server) updateLoop() {<br> for {<br>  s.Mutex.Lock()    // Here to avoid data races<br>  changes := make(map[string]int)<br>  for i := 0; i &lt; s.Grid.Size; i++ {<br>   for j := 0; j &lt; s.Grid.Size; j++ {<br>    currentState := s.Grid.Data[i][j]<br>    newState := currentState<br>    // Markovian dynamics<br>    // 0 -&gt; 1<br>    if currentState == 0 &amp;&amp; rand.Float64() &lt; s.Matrix.P01 {<br>     newState = 1<br>    }<br>    // 1 -&gt; 0<br>    else if currentState == 1 &amp;&amp; rand.Float64() &lt; s.Matrix.P10 {<br>     newState = 0<br>    }<br>    if newState != currentState {<br>     s.Grid.Data[i][j] = newState<br>     changes[fmt.Sprintf(&quot;%d,%d&quot;, i, j)] = newState<br>    }<br>   }<br>  }<br>  s.Mutex.Unlock()  // Don&#39;t forget to release the mutex - Deadlock otherwise!<br>  // Broadcast to client (only) the updated nodes<br>  if len(changes) &gt; 0 {<br>   log.Printf(&quot;[INFO] broadcasting changes: %v&quot;, changes)<br>   s.broadcastChanges(changes)<br>  }<br>  // Sleep for Delta_t (here one second)<br>  time.Sleep(time.Second)<br> }<br>}</pre><p>Two things to highlight</p><ul><li>In the main function, when starting the updating loop, I use a goroutine, a light weight thread, to run the update described above.</li></ul><pre>func main() {<br> // Setting up stuff<br><br> go server.updateLoop() // &lt;- This is my goroutine!go<br><br> port := os.Getenv(&quot;PORT&quot;)<br> log.Printf(&quot;[INFO] Server started on :%s&quot;, port)<br> log.Fatal(http.ListenAndServe(fmt.Sprintf(&quot;:%s&quot;, port), router))<br>}</pre><ul><li>As a result, I need to introduce a mutex in the updateTransitionMatrix method, but also in other methods accessing the TransitionMatrix instance field. Without the mutex, the server could, for example, send the transition matrix data through the get_matrix endpoint while updating at the same time… This could result in partially updated — and thus corrupted — data to be sent to the client.</li></ul><h4>CORS</h4><p>CORS (Cross-Origin Resource Sharing) restricts the requests that a browser can make to other resources (defined by domain, host, port). Since the backend will not have the same port as the frontend and the browser will first be requesting data from the frontend server first, unless CORS middleware is implemented, the browser will not accept the response from the backend.</p><p>Here is how it looks.</p><pre>corsMiddleware := func(next http.Handler) http.Handler {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)<br>        w.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, OPTIONS, GET&quot;)<br>        w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type&quot;)<br>        if r.Method == http.MethodOptions {<br>            w.WriteHeader(http.StatusOK)<br>            return<br>        }<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><p>Note that for this application, I did not constrain at all, but in production setups where security is a much greater concern, you would specify the allowed origins with this header Access-Control-Allow-Origin and further tighten accesses by specifying methods and headers.</p><h3>Frontend</h3><p>The Frontend provides the data that will be used in the browser to display the web site content. It is now generally separated from the backend but it does not have to be. In general size and seperation of concerns will decide whether a Backend is indispensable.</p><h4>Some Basics</h4><p>As subtely indicated in the title of the article, Vue.js has been chosen to write the frontend. Why?</p><ul><li>Vue.js has a gentle learning curve so that would provide my friend with an easier set up.</li><li>Vue.js is designed to be incrementally adoptable in any project making it a great choice for scaling up.</li><li>The component-based architecture promotes code reuse, modularity, and better maintainability.</li><li>It’s a very performant single page web app.</li></ul><p>Here is how a .vue file is organised.</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;hello&quot;&gt;<br>    &lt;h1&gt;{{ message }}&lt;/h1&gt;<br>    &lt;button @click=&quot;toggleMessage&quot;&gt;Toggle Message&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &#39;HelloWorld&#39;,<br>  data() {<br>    return {<br>      message: &#39;Hello, Vue!&#39;<br>    };<br>  },<br>  methods: {<br>    toggleMessage() {<br>      this.message = (<br>        this.message === &#39;Hello, Vue!&#39; ? <br>        &#39;Hello, World!&#39; : <br>        &#39;Hello, Vue!&#39;<br>      );<br>    }<br>  }<br>};<br>&lt;/script&gt;<br><br>&lt;style scoped&gt;<br>.hello {<br>  text-align: center;<br>  margin-top: 40px;<br>}<br>button {<br>  margin-top: 20px;<br>  padding: 10px 20px;<br>  font-size: 16px;<br>}<br>&lt;/style&gt;:</pre><p>There are three sections in a .vue file.</p><ul><li>The &lt;template&gt; section defines the HTML structure of the component.</li><li>The &lt;script&gt; section defines the component&#39;s logic.</li><li>The &lt;style&gt; section defines the component&#39;s styles.</li></ul><h4>Chosen display</h4><p>Simplicity is always key. So I kept the display as minimal as possible. what was needed is</p><ul><li>the possibility to change the transition matrix,</li><li>information on the equilibrium probability, and</li><li>the grid with clear highlights of switched nodes — initially I had kept gray/black as colors, but black/green gave better results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_q_KX4sp1RUpJnW7jXEKw.png" /><figcaption>Chosen display of a dynamically changing percolating grid</figcaption></figure><p>In the code, I have seperated these three aspect into three components which are available on Github. But in a nutshell, the frontend code stack structure is very straight forward.</p><pre>├── App.vue<br>├── components<br>│   ├── FormulaDisplay.vue<br>│   ├── NetworkGrid.vue<br>│   └── ProbabilityControl.vue<br>└── main.js</pre><h3>Kubernetes</h3><p>When comes the moment to make your application publicly available a lot of work as to be done to ensure its availability. Huge traffic, as it can happen on popular sites, require tools to manage duplication of resources in case of failure or simply to increase the capacity. Kubernetes, developed by Google, is a such a tool and relies on containerization of applications.</p><h4>Docker files</h4><p>Docker was released before Kubernetes — often shortened to k8 — and it revolutionized the way applications are packaged and deployed by introducing the concept of containers. Containers are lightweight, portable, and self-sufficient unit that hosts and runs an application with its dependencies. The environment being set once and for all, it allows the application to run consistently across different computing environments.</p><p>Here two Dockerfiles are required.</p><p><strong>Backend </strong><strong>Dockerfile.</strong></p><pre>FROM golang:latest AS builder<br>WORKDIR /app<br>COPY go.mod ./<br>COPY go.sum ./<br>RUN go mod download<br>COPY main.go ./<br>RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o go-backend main.go<br><br><br>FROM alpine:latest<br>WORKDIR /root/<br>COPY --from=builder /app/go-backend .<br>RUN chmod +x go-backend<br>ENV PORT=7070<br>EXPOSE $PORT<br>CMD [&quot;./go-backend&quot;]</pre><p>Note that there are two images in this Dockerfile, one image used as a builder — it will not be stored — and another one acting as the final product of the containerization. This pattern ensures that the binaries’ source codes, necessary for the compilation, do not exist on the packaged container. Instead, only the binary exists. For that purpose, and as I wanted the built image to use alpine, one the lightest so-called <em>containerizing units</em>, I chose to compile all the dependencies inside the output binary. This is achieved in the builder image with the use of that command</p><p>RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix ego -o go-backend main.go .</p><p>Without the dependencies, the binary will not work as it will not find the necessary libraries in the containerizing unit.</p><p><strong>Frontend </strong><strong>Dockerfile.</strong></p><p>For the Frontend, nginx is a tool of choice to handle production requests. It was not necessary here, but it is so easy to use it that I thought it would be a shame not to use it as a learning experience.</p><pre># Build stage<br>FROM node:latest AS builder<br><br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build<br><br><br>FROM nginx:alpine<br>ENV FRONTEND_PORT=8080<br>COPY --from=builder /app/dist /usr/share/nginx/html<br>EXPOSE $FRONTEND_PORT<br>RUN sh -c &#39;echo &quot;server { \<br>    listen ${FRONTEND_PORT}; \<br>    server_name localhost; \<br>    location / { \<br>        root /usr/share/nginx/html; \<br>        index index.html index.htm; \<br>        try_files \$uri \$uri/ /index.html; \<br>    } \<br>}&quot; &gt; /etc/nginx/conf.d/default.conf&#39;<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>With these Dockerfiles defined, we could run the application using docker. To do so, we would have to first build the images by running in the folder of the Dockerfile the commands</p><pre>cd vue-frontend<br>docker build -t vue-frontend . <br>cd ../go-backend<br>docker build -t go-backend . </pre><p>Second, we would be able to run the created images in containers with the commands</p><pre>docker run -e PORT=7070 -p 7070:7070 go-backend</pre><pre>docker run -e FRONTEND_PORT=8080 -p 8080:8080 vue-frontend</pre><p>in seperated shells. However, k8 is such a powerful management tool for these containers that we will be using it. Brace yourself my friend, we are almost there.</p><h4>k8 files</h4><p>k8 orchestrates a cluster of nodes — or machines physical or virtual, where each node can host multiple pods. Pods are the smallest deployable units and they contain one or more containers. These containers share the same network namespace and storage.</p><p>k8 services enable communication between pods and external clients by providing stable IP addresses and DNS names.</p><p>In the k8 files we will thus define pods and services for the frontend and the backend. I did not really have to define nodes although I could have if I wanted to ensure that backend and frontend are on different machines.</p><p><strong>Backend </strong><strong>k8file</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: go-backend<br>  labels:<br>    app: go-backend<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: go-backend<br>  template:<br>    metadata:<br>      labels:<br>        app: go-backend<br>    spec:<br>      containers:<br>        - name: go-backend<br>          image: go-backend:latest<br>          imagePullPolicy: IfNotPresent<br>          ports:<br>            - containerPort: 7070<br>          env:<br>            - name: PORT<br>              value: &quot;7070&quot;<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: go-backend-service<br>spec:<br>  selector:<br>    app: go-backend<br>  ports:<br>    - protocol: TCP<br>      port: 7070<br>      targetPort: 7070<br>  type: LoadBalancer</pre><p><strong>Frontend </strong><strong>k8file</strong></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: vue-frontend<br>  labels:<br>    app: vue-frontend<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: vue-frontend<br>  template:<br>    metadata:<br>      labels:<br>        app: vue-frontend<br>    spec:<br>      containers:<br>        - name: vue-frontend<br>          image: vue-frontend:latest<br>          imagePullPolicy: IfNotPresent<br>          ports:<br>            - containerPort: 8080<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: vue-frontend-service<br>spec:<br>  selector:<br>    app: vue-frontend<br>  ports:<br>    - protocol: TCP<br>      port: 8080<br>      targetPort: 8080<br>  type: LoadBalancer</pre><p>As explained in intro, the services provides the communication endpoint while the pods provide the computing space for the containers to be loaded in pods.</p><p>These files may look complex, they really are just elaborate config files. As for all config files, the main difficulty is to be aware of that one parameter you need that is hidden behind pages of doc. In this project one of these parameters is imagePullPolicy which dictates where k8 goes to get the containers. The default is to be looking in remote repositories. But since I wanted to keep everything local, setting that parameter to IfNotPresent tells k8 that it should be looking in the local docker repository for the image before looking remotely. It could otherwise be set to Always — look in the remote repository, or Never — look in the remote repository.</p><p>Also, I used deployments instead of pods as k8 deployments provide higher levels of abstractions in the managements of the pods — replicas being the one I use here.</p><p>Finally, to run the pods and services just enter</p><pre>kubectl apply -f backend-deployment.yaml<br>kubectl apply -f frontend-deployment.yaml</pre><h3>Wrapping up</h3><p>Alright… We made it dear friend. I hope this way, you have a broader view on Full Stack Development, it can be tedious at times, but it is always rewarding to see your product exist — an such product can have some serious science in the backend! I have skipped the last stage which is deployment on the cloud, but I am sure that for a starter, you’ll be happy with these quick pointers.</p><p>I will make the Github available shortly and when it is, feel free to drop comments, questions, critics or even pull request for changes you think should be made. On the top of my head, the percolation logic could be refined with more realistic dynamics and refinements on the frontend could be welcomed.</p><p>Thank you for reading this far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6196530225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on gRPC — Simulating the Sun-Earth-Moon three-body system]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-grpc-simulating-the-sun-earth-moon-three-body-system-32ee1bb12e45?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/32ee1bb12e45</guid>
            <category><![CDATA[runge-kutta]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[three-body-problem]]></category>
            <category><![CDATA[cosmology]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 00:43:28 GMT</pubDate>
            <atom:updated>2024-03-21T08:00:57.403Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on gRPC — Simulating the Sun-Earth-Moon three-body system</h3><p>Leveraging distributed computing to simulate celestial bodies</p><p><em>All codes are available on </em><a href="https://github.com/Gilt0/taiyoukei"><em>GitHub</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_ZV8UYwsG39ORMVXizjgQ.png" /><figcaption>Amaterasu, Sun Goddess in Shintoism, with the Moon and the Earth, connected in a gRPC network (Dall.e)</figcaption></figure><p>It is very frequent, in trading system to define proprietary protocols and implement them using proprietary RPC frameworks.</p><p>Recently, I was told about gRPC. And upon hearing about gRPC,</p><p>(i) I was surprised that the trading systems I worked on until not long ago, not so many were leveraging the technology;</p><p>(ii) I just wanted to implement something to try it out.</p><p>Why? What is gRPC? If you ask my new best coding partner (chatGPT), he’ll say this</p><blockquote>gRPC is a high-performance, open-source framework for RPC (Remote Procedure Call) developed by Google. It enables client and server applications to communicate transparently and efficiently across different environments and languages.</blockquote><p>In a nutshell, gRPC allows you to write applications across multiple processes as it provides the communication protocols as well as the server/client codes.</p><p>There is often a lot of boilerplate code that you can avoid with the right abstractions and that is what gRPC is: <strong>a great abtraction of RPC’s</strong>.</p><p>For those of you who have read some of my former publications, you may be aware that Rust has taken a lot of my interest lately. There are crates to use gRPC with Rust. I will probably be using these crates in the near future but as they are non official, and to get introduced to gRPC, I thought I would take the opportunity to gain some programming experience in another language that is fully supported by gRPC dev’ teams.</p><p>Since Golang is available with an official support in gRPC and I have always been found of the language, I threw myself in without looking back.</p><p>As for the project, and as the name of this blog states, it had to be about some form of mathematical modeling. Recently, I had been publishing a lot about Quant Finance, so my heart felt like doing something else.</p><p>Thus, a little out of nowhere, I figured I would simulate the whole Solar System: one gRPC client per celestial body. I was thrilled about that idea.</p><p>However, while working on the project, I resized it as I realized that I had to carefully design server and clients using gRPC, but also the Ordinary Differential Equation solver. The latter ended up taking more time than initially planned. So I decided to focus on the classical three body system made of the Sun, the Earth and the Moon. I can always come back to the full Solar System later on.<br>(Hint… Hint…)</p><p>So we’ll build a gRPC system with a central server that shares informations amongst clients: each of these representing either the Sun, the Earth or the Moon.</p><p>This project was very pleasant as it threw me back in space and the wonderful mechanical physics that goes with it. I should say though, this post is mainly about gRPC rather than celestial mechanics. As you shall see, all I have done here is coherent from a physcial stand point, but the main take away is that <strong>you can solve the Sun-Earth-Moon three body system using gRPC. </strong>And I find that very cool…</p><p>I even think that it could make a lot of sense to systematically use gRPC for complex physical calculations. gRPC offers a very convenient way to define whatever celestial system you like!</p><p>First we’ll go through the maths: you don’t really need a proper experience in mechanics to understand the rough idea — if you disagree with me on that point, I am sorry, and please tell me how I failed to make that material accessible.</p><p>Second, I’ll get into the details of the implementation. Although I used chatGPT (obviously) to learn about gRPC and debug my Golang doodles, the codes are really mine as I don’t think one can properly learn anything without doing things themselves.</p><p>Third, we’ll have a look at the results. Initially, I was having really crazy results and thought something was wrong with my programs… Turns out it was the initial conditions! They are extremely important. It is now obvious why, but initially, I really thought I could just throw some rough numbers, but it turns out that I actually had to be very careful with these initial parameters!</p><p>行くぞ！</p><h3>Background Maths</h3><p>Let’s go back to undergrad physics and write down the equations of motion for the three body system made of the Sun, the Earth and the Moon.</p><h4>Center of Mass is the center of the simulation</h4><p>On the figure below, a non-scaled diagram of the Sun (point <em>S</em>), the Earth (point <em>E</em>) and the Moon (point <em>M</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_JgURavx3fWg8j5e4Vqog.png" /><figcaption>Geometry of the Sun, Earth &amp; Moon system</figcaption></figure><p>Each of these points has a mass and classical mechanics defines the center of mass <em>G</em> of these points with the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEcOb9UXsry3Iw_wJOmZcQ.png" /></figure><p>assuming that <em>O</em> is a fixed point in space. Now if we assume that <em>i</em> (either <em>S</em>, <em>E</em>, <em>M) </em>exerts a force on <em>j</em> (either <em>S</em>, <em>E</em>, <em>M, </em>but not<em> i) </em>and we write it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxTp-sw-jQuLvt2Bd6maaA.png" /></figure><p>we could also draw a more detailed diagram with the interactions between the bodies as shown on the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6fNLZyKxH3UgZsUT0LB-A.png" /><figcaption>Forces exerted on all bodies in the Sun, Earth &amp; Moon system</figcaption></figure><p>The <a href="https://en.wikipedia.org/wiki/Newton%27s_laws_of_motion">2nd law of Newton</a> applied to each of the bodies gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXFgeP636ti1vlSmgIz0vQ.png" /></figure><blockquote>In English, the 2nd law of Newton states that the rate of change of velocity of each of the bodies (Sun, Earth or Moon) is equal to the forces applied on each of them.</blockquote><p>And thus, by taking the second order derivatives in the definition of the center of mass, we find that the second order derivative of <strong><em>OG </em></strong>is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOcxrDmYjY00qAN9ORF9Og.png" /></figure><p>The <a href="https://en.wikipedia.org/wiki/Newton%27s_laws_of_motion">3rd law of Newton</a> now states that necessarily for every couples of <em>i</em> and <em>j</em> such that <em>i</em> is not equal to <em>j</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XAnAnO-DZcThX_SVix6ww.png" /></figure><blockquote>In English, the force exerted by the Moon on the Earth is exactly the opposite of the force exerted by the Earth on the Moon. And his statement remains true for any pair in the three body system.</blockquote><p>The result of all these statements is that the right hand side of the equation on the second order derivative of <strong><em>OG </em></strong>is equal to 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgBOGavDCyiw17xALVpYNQ.png" /></figure><blockquote>In English, the center of Gravity has <strong>uniform motion in a right line</strong>: it never accelerates.</blockquote><p>And that is why <strong>we can set the center of mass as the center of the frame</strong> used in the calculations — I am voluntarily not mentionning Galilean Frames but for those of you who are familiar with these concepts, that is what the center of mass <em>G</em> defines.</p><h4>Equations of Motion</h4><p>Now that we have our center of frame, let us delve deeper into the geometry and state the equations we will use to simulate the motion of each body.</p><p>Let’s start with the position vectors of each celestial body. We write them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqTQy6Fsc4H5FJ6NyCMKeg.png" /></figure><p>which can be shown on the diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y91hVx3y-pGOpFFRvZMOzQ.png" /><figcaption>Geometry and forces of one of the bodies i<em> </em>with the center of Mass G.</figcaption></figure><p>where <em>i </em>is any of <em>S</em>, <em>E</em> or <em>M</em>. If we introduce the vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRQVoM2tdeEupw4wVF4_Jg.png" /></figure><p>that represents the position of <em>j</em> relative to <em>i</em>, according to Newton’s law of universal gravitation, the gravitational pull of <em>j</em> on <em>i is</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GqEdagdWC1fZwC2B_Hfsw.png" /></figure><p>which implies that the 2nd of Newton on body <em>i</em> may be stated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkMNVtE7zom9dXoi4t2Rpw.png" /></figure><p>And introducing a cartesian frame that is centered in <em>G</em>, we find that the equations of motions are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1v1etxrb-Z0EWsSAwJjJg.png" /></figure><p>where <em>xᵢ</em> and <em>yᵢ</em> are the coordinates of <em>i.</em></p><h4>Dimensionless Equations of Motion</h4><p>A common practice in physics computations, is to render equations dimensionless to avoid over- or underflows. Physics equations can have quantities with very great values (like in this case) or very little values (like in molecular dynamics or quantum physics).</p><p>Here <em>G</em> is extremly small as <em>G = 6,67430e−11</em> and distances are extremely big as the Sun-Earth distance is about <em>1.5e+08 </em>kilometers… Some of you may notice that there seems to be a compensation between <em>G</em> and the distances. So yes maybe it is not necessary to rely on dimensionless equations, but it has the merit to remove that worry, so let’s do it anyway.</p><p>To get to the dimensionless equation, one has to introduce scaling parameters and dimensionless variables. In our Sun-Earth-Moon three body system, I chose to introduce the scaling parameters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSBD1elc_fT4bSYKsekkTQ.png" /></figure><p>where <em>D</em> is the minimal distance between the Sun and the Earth and <em>T</em> is of the order of magnitude of the orbital period of the Earth around the Sun — there should be a <em>2π</em> for the full formula.</p><p>I then naturally chose the dimensionless variables as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUYa9SPYWTV5uwhRW88Q_A.png" /></figure><p>If you use the scaled masses</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHOXCcUrUAxH1mMm0XI4fg.png" /></figure><p>you eventually find that the dimensionless equations are (I dropped the <em>~</em>’s for clarity) in cartesian coordinates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfjOaSla4yfbPdxQg-eFCg.png" /></figure><p>or more formally (dropping this time the <em>i</em>’s for clarity)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6i1IBliK4J9v_1SfJY1bEQ.png" /><figcaption>Equations of motion as a Hamiltonian system</figcaption></figure><p>Before moving on to the implementation section, it will be convenient to state the above equation in an even more reduced form using the vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omSrvWMnw7p-A_aUSjHSMA.png" /></figure><p>Indeed, with the right definition for the function <em>f</em>, the equations of motion become</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64r1V5zCbjWexSBoG_gibQ.png" /></figure><p>(assuming that all other bodies’ positions are paremeters of <em>f).</em></p><h3>Implementing the system</h3><p>Let’s get real now, shall we? 🤓</p><p><strong>What we want</strong> — An implementation of a central server that shares across the clients the computations done by all.</p><blockquote>In English, the computational system will be made of clients running the mechanical computations. One client per celestial body. Each client will then send the update to the central server that will in turn broadcast the new information to every client.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FvgEQpPTgPr0-ROEGWgZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJSPa20qK3VEd9ov8iD6nw.png" /><figcaption>The init phase and subsequent update phases, the central server receives updated data from the clients (left). During the broadcast phase, the central server sends to all clients the data from all clients (right). With the broadcasted data, clients compute the new positions of celestial bodies.</figcaption></figure><p>First I will talk about the use of gRPC to generate the Golang files necessary for the implementations, second I will give an overview of the implementation of the server, and third, an overview of the client.</p><h4>The gRPC protocol</h4><p>Defined in a .proto file, the protocol states what the transmitted data is like, as well as the services available in the server.</p><pre>syntax = &quot;proto3&quot;;<br><br>package taiyoukei;<br><br>option go_package = &quot;./proto&quot;;<br><br>message CelestialBody {<br>    uint64 sequence = 1; // Seqwuence in stream<br>    string name     = 2; // Name of the celestial body<br>    double mass     = 3; // Mass of the celestial body<br>    double x        = 4; // x-position<br>    double y        = 5; // y-position<br>    double vx       = 6; // x-speed<br>    double vy       = 7; // x-speed<br>}<br><br>message CelestialBodiesPositionRequest {}<br><br>service CelestialService {<br>    rpc CelestialUpdate(stream CelestialBody) returns (stream Data) {}<br>    rpc CelestialBodiesPositions(CelestialBodiesPositionRequest) returns (stream Data) {}<br>}<br><br>message Data {<br>    bool success = 1;<br>    map&lt;string, CelestialBody&gt; content = 2;<br>}</pre><p>There is only one message being sent around: it contains the kinematic information of the body as well as its mass, its name and a sequence number. The sequence number is there to ensure that the flow of messages remains consistent.</p><p>As you can see, there are two services defined with the keyword rpc:</p><ul><li>CelestialUpdate, to be used between the server and the computing clients</li><li>CelestialBodiesPositions, to be used between the server and an outside watcher used for the analysis of the results.</li></ul><p>We will concentrate on the first one as it is the most interesting feature of this server. The second one was straight forward and does not bear any interesting aspects.</p><p>To generate the gRPC code I used the command</p><pre>protoc --go_out=. --go-grpc_out=. --proto_path=proto/ proto/celestial.proto</pre><p>which produced the files</p><pre>% tree proto<br>proto<br>├── celestial.pb.go             # GENERATED<br>├── celestial.proto             # Source file - NOT GENERATED<br>└── celestial_grpc.pb.go        # GENERATED</pre><p>celestial.pb.go and celestial_grpc.pb.go contain the boilerplate code for the server and clients infrastructures. The specialized logic for the application we are writting is, however, completely absent.</p><p>And that is what I present below.</p><h4>The Server</h4><p>Here are the requirements for the server</p><p>(i) — it waits for all updates from the clients</p><p>(ii) — once all update data is received, it broadcasts it to all clients</p><p>When the clients receive the broadcast, they have the positions of all other bodies and they can, in turn, update their position using the equations of motion and resend an update to the server, that resends a broadcast once all updates are received again, etc.</p><p>The mental image I have of the data flow between the server and each client is similar to this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DL9k9cqyLCpblzpSnH8R3g.png" /><figcaption>Diagram of the data flow between the server and each client (one level per client)</figcaption></figure><p>The general structure of the CelestialUpdate program is given below.</p><pre>/* <br>  SERVICE -- bidirectional streaming with clients: reception of updates <br>  and broadcast of these updates to all clients.<br>*/<br><br>func (s *server) CelestialUpdate(stream pb.CelestialService_CelestialUpdateServer) error {<br><br> /* Connection object definition and storage in map */<br><br> stop := make(chan bool) // -&gt; Channel to ensure smooth stop<br><br> if n_connections == ONE {<br>  go func() {<br>   /* <br>      Handles the emission of broadcasts <br>      - only started when there is at least one connected client <br>      - killed when the number of clients drops to zero<br>    */<br>    err := s.sendData(&amp;data)<br>    if err != nil {<br>     stop &lt;- true   // Stops the loop forloop in the parent routine<br>     break<br>    }<br>  }()<br> }<br><br> log.Printf(&quot;Initiating data reception for id %v&quot;, id)<br>forloop:<br> for {<br>  select {<br>  case &lt;-stop:<br>   break forloop<br>  default:<br>    /* <br>      Handles the reception of client updates <br>    */<br>  }<br> }<br> return nil<br>}</pre><p>CelestialUpdate is a method of an interface generated from the .proto file. And in the generic code shown above, I basically implement the interface for a server struct that I defined myself.</p><p>The most important feature of this method is the go-routine started under the condition if n_connection == ONE. This go-routine will be in charge with the broadcast of the received data. Without this simple design, I was literally banging my head trying to find an easy way to ensure the synchronicity between client threads and the broadcast…</p><p>Having a dedicated go-routine made everything a lot easier, even if I have to admit that, in terms of design, it is not ideal.</p><p>Now that I am writing these lines, I wonder if it would not have been better to have both client- and server-streams instead a single bi-directional stream*…</p><p>* I’ll let you tell me in the comments what you think would have been a better solution.</p><h4>The Client</h4><p>As for the client, there is nothing particularly difficult with regards to the gRPC communications. The interesting part was in the solver that I implemented to simulate the orbits.</p><p><strong>Numerical Solver </strong>— Runge-Kutta of order 4 (RK4), a <em>go-to</em> solver stable enough to have a coherent system and easy enough to not loose your hair with endless stability algebra.</p><p>Using the previously introduced generic equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64r1V5zCbjWexSBoG_gibQ.png" /></figure><p>the RK4 algorithm states that for a discrete step <em>Δt</em> the sequence of discrete vectors <em>σₙ </em>is given by the following recursion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uH9RF3rgkH6IZ1POonBWuA.png" /></figure><p>Now here is the fantastic part: using a strategy design pattern in Go, I was able to very easily implement the RK4. I did not even have to debug the algorithm, from the get-go, it was correct — which is rare! Not that I am particularly amazing at writing all of this, nor that ChatGPT gave me the answer (I made a point of honor to implement things myself), but by staying as close as possible to the mathematical statements, chances of mistake are greatly reduced. So,</p><p>(i) — I introduced an implementation of vector <em>σ</em>, hamiltonVector below, with all the algebraic necessary tools (addition and scalar multiplications)</p><p>(ii) — I introduced a rateFunction type in the signature of my solver, providing a <em>strategy</em> like design pattern for the rate function</p><p>(iii) — I introduced a Solver interface providing another <em>strategy</em>-like design pattern for the solver this time.</p><pre>/* <br>    STRATEGY PATTERN 1 TO SOLVE THE ODE ON RATE FUNCTION<br> */<br>type rateFunction func(hamiltonVector) hamiltonVector<br><br>/* <br>    STRATEGY PATTERN 2 TO SOLVE THE ODE ON SOLVER<br> */<br>type Solver interface {<br> step(sigma hamiltonVector, f rateFunction, dt float64) hamiltonVector<br>}<br><br>type RungeKutta4Solver struct {<br>}<br><br>/* <br>    Implementation of RK4<br> */<br>func (rks *RungeKutta4Solver) step(sigma hamiltonVector, f rateFunction, dt float64) hamiltonVector {<br> F1 := f(sigma)<br> F2 := f(sigma.Add(F1.scalarMultiply(dt / 2.0)))<br> F3 := f(sigma.Add(F2.scalarMultiply(dt / 2.0)))<br> F4 := f(sigma.Add(F3.scalarMultiply(dt)))<br> sum_F := F1.Add(F2.scalarMultiply(2.0))<br> sum_F = sum_F.Add(F3.scalarMultiply(2.0))<br> sum_F = sum_F.Add(F4)<br> return sigma.Add(sum_F.scalarMultiply(dt / 6.0))<br>}<br><br>type celestialRateFunctionHandler struct {<br> bodies []hamiltonVector<br> masses []float64<br>}<br><br>/* <br>    Equations of motion -- specific implementation of the rate function<br> */<br>func (fh *celestialRateFunctionHandler) evaluate(sigmai hamiltonVector) hamiltonVector {<br> rate := hamiltonVector{<br>  x:  sigmai.vx,<br>  y:  sigmai.vy,<br>  vx: 0.,<br>  vy: 0.,<br> }<br> for j, sigmaj := range fh.bodies {<br>  muj := fh.masses[j]<br>  d_ij := math.Sqrt((sigmaj.x-sigmai.x)*(sigmaj.x-sigmai.x) + (sigmaj.y-sigmai.y)*(sigmaj.y-sigmai.y))<br>  Fx := muj * (sigmaj.x - sigmai.x) / (d_ij * d_ij * d_ij)<br>  Fy := muj * (sigmaj.y - sigmai.y) / (d_ij * d_ij * d_ij)<br>  rate.vx += Fx<br>  rate.vy += Fy<br>  log.Printf(&quot;mu = %v d = %v, F = %v&quot;, muj, d_ij, math.Sqrt(Fx*Fx+Fy*Fy))<br> }<br> return rate<br>}</pre><p><strong>Going further</strong> — You ought to know that RK4 eventually diverges. State of the art orbital computations are now performed with the <a href="https://www.neilbickford.com/blog/2020/10/11/the-gauss-jackson-ode-solver/">Gauss-Jackson</a> algorithm.</p><p>But…</p><ul><li>It is a lot harder and it would have to be an blogpost by itself.</li><li>RK4 is perfect for a first version of the computing system.</li><li>With the strategy pattern, it will be a breeze to modify the algorithm used to propagate the orbits in the clients.</li></ul><h3>Results</h3><p>Now, after all this hardworking, the results. At first, here are the initial conditions I gave to the the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kn6uH6P7AsWniED-uQ1e_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuF-RWLdmI_POAgwHc3yUA.png" /></figure><ul><li>I assumed that the Sun, Earth and Moon are all in the same plane. This assumption was there from the beginning. It is actually wrong because there is a 5 degree incline between the Earth Orbital Plane and the Moon orbital plane. But we (secretly) neglected that.</li><li>There has to be a starting point when all three are aligned — <em>e.g.</em> during an eclipse. And I chose the alignment <em>SME</em>. And this allowed me to set all the <em>y</em> values to 0.</li><li>Because of the masses, the Sun is about a million times more massive than the Earth which is in turn about a hundred times more massive than the Moon. So it seemed fair that <em>G</em> would be the same as <em>S, </em>leading to the values</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8ztWR2dwAq7gJebfd9XAw.png" /></figure><ul><li>As for the velocities, the masses were again such that in first approximations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5vZzH6KHOPcxjGOkRZzsg.png" /></figure><p>These initial conditions were plain wrong. Way too approximative! I would always get a divergence of the Moon as it would get to close to Earth. Which would happen everytime because of their initial position and speed. Eventually the Moon would even have its own orbit around the Sun. 😇</p><p>So I took my pen, stopped being lazy and rederived appropriate initial conditions. Here is what I got (in adimensional form).</p><ul><li>For the initial positions:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5EAYt0hTBkPTzZ3NOTbew.png" /></figure><ul><li>For the initial velocities</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztfTkXd9iaVf7FLSVuwj5w.png" /></figure><p>As the Earth and the Moon both orbit counter-clockwise from a North Pole view point. The Moon’s velocity above is set to the orbital velocity of the Earth <strong>minus</strong> the orbital velocity of the Moon around the Earth. This is because the initial state is in <em>SME</em> configuration.</p><p>Had it been in <em>SEM</em> configuration (the Sun, then the Earth, and finally the Moon), the velocities would have been added and not subtracted!</p><p>Back when I was preparing for the Ecole Polytechnique, getting Numerical Values of Theoretical Formulae was always a nightmare. I would always mess up something. But thank god, ChatGPT is here to the rescue.</p><p>Here is a screenshot of my request and his response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*RHYrlCekXuIUGZNFk318aQ.png" /><figcaption>Letting chatGPT provide me with the numerical input values</figcaption></figure><p>Using these values as input, I enter these commands (in different tabs of my terminal)</p><pre># To start the server<br>go run server/run.go<br><br># To start the capture client -- not detailed in the text but use it<br># to generate the orbit graphs<br>go run capture/main.go<br><br># To start the Sun<br>go run client/run.go -name S -mass 1 -x -0.0000030393 -y 0 -vx 0 -vy 0<br><br># To start the Earth<br>go run client/run.go -name E -mass 0.0000030025 -x 0.999997 -y 0 -vx 0 -vy 1<br><br># To start the Moon<br>go run client/run.go -name M -mass 0.000000036938 -x 0.997427 -y 0 -vx 0 -vy 0.965816</pre><p>The computations will only start once all the expected clients are connected — here 3 clients are expected.</p><p>Now let’s look ate the plots generated by capture/main.go to assess whether or not the simulation makes sense.</p><p>Scroll down a little more….</p><p>ET VOILÀ!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYjZgpTPdCA8I7cve2Cieg.png" /><figcaption>Note: the Sun barely moves and therefore its orbital trajectory could not be plotted.</figcaption></figure><p>This output looked extremly promising as you could see that the Earth <em>E </em>orbits around the Sun <em>S</em> and so does the Moon <em>M</em>. In my first trials the Moon was just wrongly being thrown into a different orbit around the Sun than the Earth’s one.</p><p>Also, note how the Moon orbit (in green) seems to be crossing back and forth the Earth Orbit (in red). This is a possible indication that the Moon is, as expected from observations, orbiting around the Earth as well.</p><p>So let’s check this by centering the graphs on the Earth.</p><p>Scroll down a little more….</p><p>(Yes I am that annoying)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4wW_H052x0PKoWNJUDpvw.png" /><figcaption>Note: The Moon seems to have a deformed orbit. It could be because of Numerical errors or because of the Sun’s gravitational pull. I have not conducted the investigation, but my gut feeling is that it could be from the Sun’s gravitational pull… What do you think?</figcaption></figure><p>やったあああああああああああああああああ！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaMM2csJprKHXIHpR7owtg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32ee1bb12e45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on Design Patterns in Rust — the good ol’Matrix exercise]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-design-patterns-in-rust-the-good-olmatrix-exercise-785a3a1c2400?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/785a3a1c2400</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[numerical-methods]]></category>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 08:38:56 GMT</pubDate>
            <atom:updated>2024-03-04T08:38:56.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on Design Patterns in Rust — the good ol’Matrix exercise</h3><p>Revisiting a classic to investigate Design Patterns in Rust.</p><p><em>Codes available on </em><a href="https://github.com/Gilt0/gyouretsu-no-otaku/tree/master"><em>GitHub</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otDUCwz7DlVV9S9gxO3eiw.png" /><figcaption>When design engineering will be back to its roots — dall.e.</figcaption></figure><p>I was chatting with a friend about software development not so long ago. I asked him</p><blockquote>If you were to recruit a guy like me, how could I convince you that I am actually a good senior software engineer?</blockquote><p>He replied with no hesitation</p><blockquote>Design Patterns. Just make sure people know you understand and know how to use the basic ones.</blockquote><p>I have been moving my career towards Software Engineering for the past few months, for zillion reasons. <br>I now live outside of my home country and my profile is 100% by-the-French-for-the-French — <em>i.e.</em> if you’re not French and acustomed to those crazy uncontrollable close-to-40 Polytechnicians, it’s kinda hard to have a good read on my experience.</p><p>I have been dabbling with programming as soon as I understood that it could level up my modelling skills. Because, yes… My drive is modelling, system building, putting equations and maths to good use. I started with Matlab, then R, then Python, then C/C++… And now Rust!</p><p>But there is still a bit of a gap between programming quantitative work and software engineering. I will try to fill that gap with you in that series of articles on Rust.</p><p>In a <a href="https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-market-microstructure-building-a-rust-program-to-match-a-trade-with-its-3bced14a5ce7">previous article</a> I wrote about reconciliation of Binance’s quotes and trades. I had a lot of fun discovering the borrow checker. I wish I had been part of the team of people who came up with that idea of ownership and borrowing. Initially, I was thinking that it was a bit of a weird, unexpected idea. But it forced me to think completely differently about the way I implement programs and once I got used to it, it’s quite addictive…</p><p>So now, I am back with another series of article. It will again be finance oriented because I had a computation project I had never really implemented in robust C or C++. I think I want to keep for myself the end goal to try and build up some mystery. But down the line we might be doing some fun continuous stochastic calculus. :)</p><p>The emphasis in these articles will be software engineering rather than the underlying math technics. However, I will for sure give bits here and there on the maths whenever it is necessary.</p><p>In this first article, we will need to implement some matrix algebra and use the opportunity to focus on Design Pattern — hence the boring personal anecdote above.</p><p>I am not going to delve too much in the details of what design patterns are, nor provide some form of academic presentation of the latter. Not that it is not interesting, it very much is. However other people speak far better than me about it:</p><ul><li><a href="https://refactoring.guru/design-patterns/what-is-pattern">Refactoring Guru</a></li><li><a href="https://rust-unofficial.github.io/patterns/">non-official Rust tutorial</a> on design patterns and anti-patterns.</li></ul><p>Together, we’ll focus on the practicalities of implementing Design Patterns in Rust, in particular:</p><ul><li>Builder Pattern,</li><li>Rich Error Reporting pattern, and</li><li>Strategy Pattern.</li></ul><p>行くぞ!</p><h3>Primers</h3><p>Before we dive in the implementation of our matrix algebra, let’s recall some key concepts first.</p><h4>Rust struct</h4><p>Rust does not have classes <em>per se</em>. It has structs like C and like C++, and methods can be <em>attached</em> to the struct but are not part of its definition like in C++. Attaching methods allows the dot syntax</p><pre>my_struct.its_method(args);</pre><p>the C syntax</p><pre>a_function(my_struct, args);</pre><p>is also available for struct methods in Rust, although not as used</p><pre>MyStruct::its_method(&amp;my_struct, args)</pre><p><em>Attaching</em> or rather implementing methods to a Rust struct feels very similar to implementing a class in C++. However, because Rust emphasizes composition over inheritance, the syntax for the implementation is quite different and provides a different programming paradigm.</p><pre>struct MyStruct {<br>  variable_1: Type_1,<br>  variable_2: Type_2,<br>  ...,<br>}<br><br>impl MyStruct {<br>  fn method_1(self, args_1: Types_1) -&gt; ReturnTypes_1 { /* method logic */ }<br>  fn method_2(&amp;self, args_2: Types_2) -&gt; ReturnTypes_2 { /* method logic */ }<br>  fn method_3(&amp;mut self, args_3: Types_3) -&gt; ReturnTypes_3 { /* method logic */ }<br>  ...<br>}</pre><p>Implementing the methods is done with the impl keyword. Notice that methods are not declared and certainly not defined inside the struct definition block. It is outside in the impl block. This is because of the focus on composition.</p><p>You could very much start implementing knowing only struct definition and implementation — this is what I did early in my previous publication. However, you would quickly realize that old habits of inheritance are unavailable and realize that you need to learn about Rust traits to fill the gap.</p><h4>Rust traits</h4><p>They are very similar to interfaces in Java, with some notable differences</p><ul><li>Rust allows default method implementations and static methods.</li><li>Rust does not support fields nor interface inheritance.</li></ul><p>and some other subtleties that are not that important at this stage.</p><p>Traits can be implemented for standard types char, bool, i32, etc, but also for structs. The syntax is a little similar to the implementation of struct methods, except that the implementation type has to be specified.</p><pre>trait MyTrait {<br>  method_1(args_1: Types_1) -&gt; ReturnTypes_1,<br>  ...<br>}<br><br>impl MyTrait for MyStruct {<br>  fn method_1(args_1: Types_1) -&gt; ReturnTypes_1 { /* method logic */ }<br>  ...<br>}</pre><p>Using the MyTrait trait by implementing it on MyStruct provides MyStruct instances with the functionalities of MyTrait. Instead of having multiple inheritances when implementing a struct with multiple abilities, the developer may as well define traits that are implemented for that struct.</p><p>Last words on traits, they can also be used as types… When you do so, you have to make sure that the dyn keyword is used to tell the compiler that you are using <em>a dynamic dispatch to a trait object</em>.</p><pre>fn my_function(argument: &amp;dyn MyTrait) -&gt; Box&lt;dyn OtherTrait&gt; { <br>  /* function logic */<br>}</pre><p>As you can see, it is not as straight forward though as you need to parse a reference and for the return object, you have to encapsulate the trait in a smart pointer type like Box.</p><p>I don’t want to over complicate for new comers by getting into the details of smart pointer, I just thought I’d mention it. For those of you who are curious about smart pointers, check <a href="https://doc.rust-lang.org/book/ch15-00-smart-pointers.html">this</a> or even <a href="https://rust-unofficial.github.io/patterns/idioms/deref.html">that</a> out for some further usage.</p><h4>Rust generics</h4><p>They are a lot less flexible than C++’s templates, with regards to memory manipulation, but they provide some added functionality with trait bounds. Now that said, we’ll be using them with an idea of polymorphism. They allow the developer to define functions, structs, methods or even traits with an unknown type.</p><pre>// For a function<br>fn function&lt;T&gt;(argument: T) -&gt; SomeGenericType&lt;T&gt; {<br>  /* function logic */<br>}<br><br>// For a struct<br>struct MyStruct&lt;T&gt; {<br>  variable: T,<br>  ...<br>}<br><br>impl&lt;T&gt; MyStruct&lt;T&gt; {<br>  /* implementation logic */<br>}<br><br>// For a Trait<br>trait MyTrait&lt;T&gt; {<br>    fn method(&amp;self, arg: T);<br>}<br><br>impl&lt;T&gt; MyTrait&lt;T&gt; for MyStruct&lt;T&gt; <br>where T: std::fmt::Display{ <br>    fn method(&amp;self, arg: T) {<br>        println!(&quot;Handling T: {}&quot;, arg); // Works because T implements Display<br>    }<br>}</pre><p>On the snippet above, you will see that I used trait bounds after the where keyword. In this particular case, the bound specifies that the trait std::fmt::Display must be implemented. This trait provides a type with the necessary methods for printing. In other words, without this trait bound, the line</p><pre>println!(&quot;Handling T: {}&quot;, arg);</pre><p>would not compile.</p><h4>Design Patterns</h4><p>As refactoring guru very well defines, design patterns are customizable blue-prints. Without getting to technical, let’s just give a quick outline of their implementation in Rust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gU5tfl0DBGLgeVG6cXVx-w.png" /><figcaption>Design Pattern definition by the refactoring Guru</figcaption></figure><p><strong>Builder Pattern — </strong>This pattern serves the construction of a specific struct instance, sometimes with default parameters.</p><pre>struct MyStruct {<br>  variable_1: Type_1,<br>  variable_2: Type_2<br>}<br><br>struct MyStructBuilder {<br>  variable_1: Option&lt;Type_1&gt;,<br>  variable_2: Option&lt;Type_2&gt;<br>}<br><br>enum MyStructDefinitionError {<br>  VariableOneIsIllDefined,<br>  VariableTwoIsIllDefined,<br>}<br><br>impl MyStructBuilder {<br><br>  fn new() -&gt; Self {<br>    MyStructBuilder{ variable_1: None, variable_2: None }<br>  }<br><br>  fn variable_1(mut self, variable_1: Type_1) -&gt; Self {<br>    // condition to accept the value<br>    self.variable_1 = if condition_1(variable_1) { <br>        Some(variable_1)<br>      } else {<br>        None<br>      };<br>    self // Useful for chaining !<br>  }<br><br>  /* Implement the same method for variable_2 */<br><br>  fn build(self) -&gt; Result&lt;MyStruct, MyStructDefinitionError&gt; {<br>        let variable_1 = self.variable_1.ok_or(<br>          MyStructDefinitionError::VariableOneIsIllDefined<br>        )?;<br>        let variable_2 = self.variable_2.ok_or(<br>           MyStructDefinitionError::VariableTwoIsIllDefined<br>        )?;<br>        Ok(MyStruct { variable_1, variable_2 })<br>  }<br> <br>}</pre><p>The snippet above shows the Builder Pattern with a dedicated struct MyStructBuilder that is dedicated to create an instance of MyStruct.</p><p>The builder struct contains more or less the same member fields to the execption that these fields are set to be optional. For those who do not know, Option is an enum specific to Rust that serves the implementation of the null concept while avoiding null pointer errors.</p><p>Using optional variables makes it very handy to handle errors in the build method of the builder as shown with the lines like</p><pre>let variable = self.variable.ok_or(Error)?;</pre><p>A very useful aspect of this kind of implementation of the builder is that you can chain the variable definitions as such</p><pre>let builder = MyStructBuilder::new();<br>let my_struct = builder<br>  .variable_1(var_1) // Assuming var_1 is already defined<br>  .variable_2(var_2) // Assuming var_1 is already defined<br>  .build();</pre><p>This is enabled by each method returning the builder instance with self at the end of the block.</p><p><strong>Rich Error Reporting pattern — </strong>As introduced in the previous code snippet, error handling is really handy in Rust. There is another enum called Result&lt;T, E&gt; which can be matched to an Ok(value) pattern if the method succeed and a Err(e) pattern if the method failed.</p><p>To abide to Rust’s Rich Error pattern, it is customary to add three other traits to complete the definition of an error:</p><ul><li>std::error::Error trait: convenient to be able to propagate the error using the ? operator and make a user defined error compatible with Result&lt;T, E&gt; where E is an error type,</li><li>std::fmt::Display trait: convenient to print the error in a user defined format, and</li><li>Debug trait: convenient to print the error in a debug format for developers. That last trait is often introduced with the derive macro.</li></ul><pre>use std::fmt::{ Result, Formatter, Display };<br>use std::error::Error;<br><br>#[derive(Debug)]<br>enum MyStructDefinitionError {<br>  VariableOneIsIllDefined,<br>  VariableTwoIsIllDefined,<br>}<br><br>impl Display for MyStructDefinitionError {<br>    fn fmt(&amp;self, f: &amp;mut Formatter) -&gt; fmt::Result {<br>        match *self {<br>            MyStructDefinitionError::VariableOneIsIllDefined =&gt; {<br>                write!(f, &quot;Variable one is ill-defined&quot;)<br>            },<br>            MyStructDefinitionError::VariableTwoIsIllDefined =&gt; {<br>                write!(f, &quot;Variable two is ill-defined&quot;)<br>            },<br>        }<br>    }<br>}<br><br>impl std::error::Error for MyStructDefinitionError {}</pre><p><strong>Strategy Pattern — </strong>This pattern is very handy in the context of Numerical Computations: it allows the user to introduce inter-changeable algorithmic blocks. For example, if a user wants to solve a particular differential equation, multiple methods and sub-methods are available:</p><ul><li>Finite Differences Methods with all the varieties of numerical schemes,</li><li>Finite Elements Methods with all the varieties of basis functions, and</li><li>In some cases, you may be inclined to consider Finite Volume Methods.</li></ul><p>Therefore having a Solver trait that could be implemented for different structs FDMSolver, FEMSolver or FVMSolver that would each have different implementations.</p><p>More generally the pattern is as such*.</p><pre>trait MyStrategy {<br>  fn run(&amp;self, arguments: Types) -&gt; Result&lt;ResultType, Error&gt;;<br>}<br><br>struct MyAction1 {<br>  /* Fields specific to MyAction1 */<br>}<br><br>impl Strategy for MyAction1 {<br><br>  fn run(&amp;self, arguments: Types) -&gt; Result&lt;ResultType, Error&gt; {<br><br>    /* Specific implementation of run for MyAction1 */<br><br>  }<br><br>}<br><br>struct MyAction2 {<br>  /* Fields specific to Action2 */<br>}<br><br>impl Strategy for MyAction2 {<br><br>  fn run(&amp;self, arguments: Types) -&gt; Result&lt;ResultType, Error&gt; {<br><br>    /* Specific implementation of run for MyAction2 */<br><br>  }<br><br>}<br><br>enum Action {<br>  MyAction1,<br>  MyAction2,<br>}<br><br>fn execute_strategy(action: Action, arguments: Types) { <br>  <br>    match action {<br>      <br>      Action::MyAction1 =&gt; MyStrategy::run(&amp;MyAction1, arguments)<br>      Action::MyAction2 =&gt; MyStrategy::run(&amp;MyAction2, arguments),<br><br>    }<br><br>}</pre><p>*Note the use of the C-like syntax</p><pre>MyStrategy::run(&amp;MyAction1, arguments)</pre><p>as it avoids the definition of a MyAction1 instance for concision.</p><h3>Implementing the library</h3><p>The library needs to do one and one thing only: computing the cholesky decomposition of positive definite matrix.</p><p>As a reminder the definition of a positive definite matrix with the Cholesky decomposition statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xh8mlDSgUdaKiJt2SrVt5A.png" /></figure><p>To achieve that end, the library needs to implement</p><ul><li>matrices,</li><li>squared matrices,</li><li>symmetric matrices, and</li><li>positive definite matrices</li></ul><p>before being able to compute a Cholesky decomposition.</p><h4>Defining a matrix object</h4><p>Ideally we want a matrix to contain any type* of data, in the mathematical sense, and we want the struct defining it to contain as little fields as possible, to avoid complexities.</p><p>* We will have to be more precise on that later.</p><p>Therefore a natural implementation would be as shown below (<a href="https://github.com/Gilt0/pathsim/blob/baa5b6232bbc4fadebba7f4c2fdb981f1674b3f2/src/matrix.rs#L23C5-L23C11">GitHub</a>).</p><pre>#[derive(Debug)]       // This is a macro rules for debug prints<br>pub struct Matrix&lt;T&gt; { // We use generics to ensure any type<br>    rows: usize,       // To rapidly access the first dimension<br>    cols: usize,       // To rapidly access the second dimension<br>    data: Vec&lt;T&gt;,      // Data is stored in 1D Vec&lt;T&gt; for performance<br>}</pre><p>The snippet above introduces two Rust specific syntaxes things.</p><ul><li>A specific type of Rust macro: macro-rules defined by the attribute#[macro_rules_name(...)] which <em>kinda</em> decorate in the code but really introduce additional code at compile-time. I did not say much in the primer as I would like it to be the topic of my next article. 😁</li><li>A Generic &lt;T&gt; in the definition of the struct to have control over the data type in the data field as it is a Vec&lt;T&gt; itself. Now this is going to cause a lot of extra implementations, because we want the generic type to be representative of Mathematical Numbers. Therefore we are going to have to introduce a Numeric trait*.</li></ul><p>So before introducing the implementation of the struct methods and the implementation of the different traits from the standard library that we will need, let’s take a dive in the implementation of the Numeric trait.</p><p>* There is an available crate that can do just that but as a learning exercise, I wanted to implement it myself. So yes… I will reinvent the wheel.</p><p><strong>Numeric trait implementation — </strong>The necessity of having a dedicated trait to enforce that the type used in generic would be some sort of a numeric, stems from the necessity of defining default matrices.</p><p>How do you define one or zero on an abstract type? Or how would make possible the conversion of type T to type S ?<br>In Rust you use traits that you implement on the types you are wishing to abstract.</p><p>Let’s say that we want to abstract i32, i64, f32 andf64 types. In plain terms, we are talking about 32/64 bit integers and 32/64 bit floats. Here is how you would introduce the trait and its implementation.</p><pre>use std::ops;<br>use std::cmp;<br><br>pub trait Numeric: <br>/* <br>  The Numeric Trait requires the types that implements it to also implement<br>  the list of traits below (explanation on the left)<br>*/<br>std::fmt::Debug +                              // Print in debug logs<br>std::fmt::Display +                            // Print <br>PartialEq + cmp::PartialOrd +                  // To use the == and &lt; or &gt; op.<br>Copy + Clone + Default +                       // To duplicate and default<br>ops::Add&lt;Output = Self&gt; +                      // Additions<br>ops::Sub&lt;Output = Self&gt; +                      // Substractions  <br>ops::Mul&lt;Output = Self&gt; +                      // Multiplications<br>ops::Div&lt;Output = Self&gt; {                      // Divisions<br>    /* <br>      When implementing the trait on a type, all these methods need to be <br>      implemented.<br>    */<br>    fn one() -&gt; Self;                          // Abstract notion of one<br>    fn zero() -&gt; Self;                         // Abstract notion of zero<br>    fn from_i32(value: i32) -&gt; Self;           // Conversion from i32 to T<br>    fn from_i64(value: i64) -&gt; Self;           // Conversion from i64 to T<br>    fn from_f32(value: f32) -&gt; Self;           // Conversion from f32 to T<br>    fn from_f64(value: f64) -&gt; Self;           // Conversion from f64 to T<br>    fn from_usize(value: usize) -&gt; Self;       // Conversion from usize to T<br>    fn to&lt;S&gt;(&amp;self) -&gt; S where S: Numeric;     // Conversion from T to S<br>}<br><br>// Implementation example for i32<br>impl Numeric for i32 {<br>    fn one() -&gt; Self {<br>        1i32<br>    }<br><br>    fn zero() -&gt; Self {<br>        0i32<br>    }<br><br>    fn from_i32(value: i32) -&gt; Self {<br>        value<br>    }<br><br>    fn from_i64(value: i64) -&gt; Self {<br>        value as i32<br>    }<br><br>    fn from_usize(value: usize) -&gt; Self {<br>        value as i32<br>    }<br><br>    fn from_f32(value: f32) -&gt; Self {<br>        value.trunc() as i32<br>    }<br><br>    fn from_f64(value: f64) -&gt; Self {<br>        value.trunc() as i32<br>    }<br><br>    fn to&lt;S&gt; (&amp;self) -&gt; S where S: Numeric {<br>        S::from_i32(*self)<br>    }<br><br>}<br><br>impl Numeric for i64 { /* Similar to i32 */ }<br><br>impl Numeric for f32 { /* Similar to i32 */ }<br><br>impl Numeric for f64 { /* Similar to i32 */ }</pre><p>We could, in a way, be tempted to mention the Decorator Pattern here. However: decorators are generally dynamically created while Rust’s traits are compile time features. 😈</p><p>Also, before moving on to the next section, keep in mind that some conversions might loose information — <em>e.g.</em> fxx to iyy of course but also from 64 bits to 32 bits…</p><p>You can check the full implementation on <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/master/src/numeric.rs">GitHub</a> too.</p><p><strong>Implementing standard libray’s traits and other methods — </strong>With these trait available, we can now implement the struct Matrix&lt;T&gt; making sure that the generic type has the Numeric trait implemented.</p><pre>#[derive(Debug)]<br>pub struct Matrix&lt;T&gt; where T: Numeric{ // &lt;- Note the where clause!<br>    rows: usize,<br>    cols: usize,<br>    data: Vec&lt;T&gt;,<br>}<br><br>/* <br>  Methods implementation for the struct:<br>    - public getters for the private fields<br>    - public copy method from Matrix&lt;T&gt; to Matrix&lt;S&gt; -- used in the algebra<br>    computations to ensure that i32/i64/f32 matrices are copied to f64 <br>    matrices to ensure smooth computations.<br>*/<br>impl&lt;T&gt; Matrix&lt;T&gt; where T: Numeric { <br>    pub fn rows(&amp;self) -&gt; usize { self.rows }<br>    pub fn cols(&amp;self) -&gt; usize { self.cols }<br>    pub fn data(&amp;self) -&gt; &amp;Vec&lt;T&gt; { &amp;self.data }<br><br>    /* Looks like we are going to define out very first Design Pattern! */<br>    pub fn copy_to&lt;S&gt;(&amp;self) -&gt; Result&lt;Matrix&lt;S&gt;, MatrixCopyToError&gt; where S: Numeric {<br>        MatrixBuilder::&lt;S&gt;::new()    // &lt;- What is that ???<br>        .from_vec(<br>            self.rows, <br>            self.cols, <br>            self.data.iter().map( |&amp;element| element.to::&lt;S&gt;() ).collect()<br>        )<br>        .build()<br>        .map_err(MatrixCopyToError::DefinitionError)<br>    }<br><br>}<br><br>impl&lt;T&gt; ops::Index&lt;(usize, usize)&gt; for Matrix&lt;T&gt; where T: Numeric {<br>    type Output = T;<br><br>    fn index(&amp;self, index: (usize, usize)) -&gt; &amp;Self::Output {<br>        /* To be able to use the element accessor (read-only) */<br>    }<br>}<br><br>impl&lt;T&gt; ops::IndexMut&lt;(usize, usize)&gt; for Matrix&lt;T&gt; where T: Numeric {<br>    fn index_mut(&amp;mut self, index: (usize, usize)) -&gt; &amp;mut Self::Output {<br>        /* To be able to use the element accessor (read-write) */<br>    }<br>}<br><br>impl&lt;T&gt; PartialEq for Matrix&lt;T&gt; where T: Numeric {<br>    fn eq(&amp;self, other: &amp;Self) -&gt; bool {<br>        /* To be able to use the &lt; or &lt;= or &gt; or &gt;= operator */<br>    }<br>}<br><br>impl&lt;T&gt; fmt::Display for Matrix&lt;T&gt; where T: Numeric {<br>    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;&#39;_&gt;) -&gt; fmt::Result {<br>        /* To be able to pretty-print the matrix */<br>    }<br>}</pre><p>I don’t provide the details of the trait implementations. There not really that important to understand the big picture. The details are of course on <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/f846ffe75f5a289d28bc094e92c7ce032590deb3/src/matrix.rs#L65">Github</a> if you wish to learn more.</p><p>Now if you look at the copy_to&lt;S&gt; method, I introduce the MatrixBuilder type which implementation is, so far, no where to be found! This is our first official use of a design pattern: the creational builder pattern. Let’s dive in.</p><p><strong>Builder Pattern to create matrices — </strong>Rust has in-built functions that act as constructor or even default constructor: the new method and a trait Default in the std::default module. A macro rules exist and the most straightforward way to define a default constructor would be</p><pre>#[derive(Default)]<br>struct MyStruct { /* field definitions */ }</pre><p>These method and trait are useful but having a dedicated builder allows more flexibility and seperate the construction concern. Rust not requiring a constructor for a struct, the code is also lighter.</p><p>First we define the struct for the builder MatrixBuilder&lt;T&gt; — we still have a generic in the definition!</p><pre>pub struct MatrixBuilder&lt;T&gt; {<br>    rows: Option&lt;usize&gt;,<br>    cols: Option&lt;usize&gt;,<br>    data: Option&lt;Vec&lt;T&gt;&gt;,<br>}</pre><p>You’ll notice that the fields are almost the same as those of Matrix&lt;T&gt;, except for the fact that they are defined using an Option generic just as they were introduced in the above primer. If you remember, Option enum is used to allow the None value in a <em>safe</em> with regards to the more common null pointers.</p><p>Then we can move on to the implementation: first some setters as the constructor sets the values to None by default. If the value being set is not appropriate we can reject it by setting or maintaining the value to None.</p><pre>impl&lt;T&gt; MatrixBuilder&lt;T&gt; where T: Numeric {<br>    pub fn new() -&gt; Self {<br>        MatrixBuilder {<br>            rows: None,<br>            cols: None,<br>            data: None,<br>        }<br>    }<br><br>    pub fn rows(mut self, rows: usize) -&gt; Self {<br>        self.rows = if rows &gt; 0 { Some(rows) } else { None };<br>        self<br>    }<br><br>    pub fn cols(mut self, cols: usize) -&gt; Self {<br>        self.cols = if cols &gt; 0 { Some(cols) } else { None };<br>        self<br>    }<br><br>    pub fn data(mut self, data: Vec&lt;T&gt;) -&gt; Self {<br>        self.data =  if !data.is_empty() { Some(data) } else { None };<br>        self<br>    }<br><br>    /* Other methods */<br><br>}</pre><p>Now we want to have the possibility to provide the data directly: either in the format of a one-dimensional array — and in such case with the number of rows and cols, or in the format of a two-dimensional array — no dimensional precision necessary in that case then.</p><pre>impl&lt;T&gt; MatrixBuilder&lt;T&gt; where T: Numeric {<br><br>    /* Constructor and setters */<br><br>    pub fn from_vec(self, rows: usize, cols: usize, data: Vec&lt;T&gt;) -&gt; Self {<br>        self.rows(rows).cols(cols).data(data)<br>    }<br><br>    pub fn from_mat(self, data: Vec&lt;Vec&lt;T&gt;&gt;) -&gt; Self {<br>        println!(&quot;data = {:?}&quot;, data);<br>        if let Some(first_row) = data.first() {<br>            let rows = data.len();<br>            let cols = first_row.len();<br>            let flat_data: Vec&lt;T&gt; = data.into_iter().flatten().collect();<br>            self.rows(rows).cols(cols).data(flat_data)<br>        } else {self}<br>    }<br><br>    /* Other methods */<br><br>}</pre><p>It will also be handy to have specific matrices builder: identity matrices and zero-only matrices.</p><pre>impl&lt;T&gt; MatrixBuilder&lt;T&gt; where T: Numeric {<br><br>    /* Constructor, setters and from_* */<br><br>    pub fn zeros(self, rows: usize, cols: usize) -&gt; Self {<br>        self.rows(rows).cols(cols).data(vec![T::default(); rows * cols])<br>    }<br><br>    pub fn identity(self, n: usize) -&gt; Self {<br>        let mut data = vec![T::default(); n * n];<br>        for k in 0..n { data[k * n + k] = T::one(); }<br>        self.rows(n).cols(n).data(data)<br>    }<br><br>    /* Other methods */<br><br>}</pre><p>Finally, assuming that MatrixBuilder’s fields are set, the build may be triggered.</p><pre>impl&lt;T&gt; MatrixBuilder&lt;T&gt; where T: Numeric {<br>  <br>    /* Constructor, setters, from_*, zeros and identity */<br><br>    pub fn build(self) -&gt; Result&lt;Matrix&lt;T&gt;, MatrixDefinitionError&gt; {<br>        let data = self.data.ok_or(MatrixDefinitionError::NoDataProvided)?;<br>        let rows = self.rows.ok_or(MatrixDefinitionError::UndefinedRows)?;<br>        let cols = self.cols.ok_or(MatrixDefinitionError::UndefinedCols)?;<br>        if data.len() != rows * cols {<br>            Err(MatrixDefinitionError::DataLengthDoesNotMatchRowsTimesCols)<br>        } else {<br>            Ok(Matrix { rows, cols, data })<br>        }<br>    }<br>}</pre><p>Note that the builder returns an error is one of the field is None.</p><p>(See the full implementation on <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/f846ffe75f5a289d28bc094e92c7ce032590deb3/src/matrix.rs#L176">GitHub</a>)</p><p><strong>Rich Error Reporting pattern — </strong>Now that we have implemented Matrix&lt;T&gt;, you’ll notice that we introduced three error types</p><ul><li>MatrixDefinitionError,</li><li>MatrixIndexOutOfBoundsError, and</li><li>MatrixCopyToError</li></ul><p>By doing so, we provide the user with as many details as possible. As presented in the primer above, we implemented std::fmt::Display and std::error::Error traits for these error types. See <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/f846ffe75f5a289d28bc094e92c7ce032590deb3/src/matrix.rs#L7">GitHub</a> for the details.</p><p><strong>Strategy pattern — </strong>Now that we have the base object, we need to bring about more specialisation. The end goal is to compute the Cholesky decomposition of a matrix if it is symmetrical and positive definite. And before getting there, we need to implement characteristics of Symmetry and eigen decomposition (<a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/master/src/symmetric.rs">GitHub</a>). Computing eigen values for symmetric matrices will allow:</p><ul><li>to check whether the matrix will be positive definite (eigen values have to be strictly positive) and also, much further down the road,</li><li>to make a covariance matrix definite positive when the dimension and the noise break that property empirically.</li></ul><pre>pub trait Symmetric {<br>    fn is_symmetric(&amp;self) -&gt; bool;<br>    fn eigen_decomposition(&amp;self, algorithm: Algorithm) -&gt; Result&lt;(Vec&lt;f64&gt;, Matrix&lt;f64&gt;), EigenDecompositionError&gt;;<br>}<br><br>impl&lt;T&gt; Symmetric for Matrix&lt;T&gt; where T: Numeric {<br>    fn is_symmetric(&amp;self) -&gt; bool {<br>        /* Symmetry checker */<br>    }<br><br>    fn eigen_decomposition(&amp;self, algorithm: Algorithm) -&gt; Result&lt;(Vec&lt;f64&gt;, Matrix&lt;f64&gt;), EigenDecompositionError&gt; {<br>        match algorithm {            // &lt;- Flow control<br>            Algorithm::Jacobi =&gt; {<br>                EigenDecomposition::&lt;T&gt;::decompose(&amp;JacobiDecomposition, self)<br>            },<br>        }<br>    }<br>}<br><br><br>#[derive(Debug)]<br>pub struct EigenDecompositionError;<br><br>/* Error&#39;s traits implementation */<br><br>pub enum Algorithm {<br>    Jacobi,<br>    // Other algorithms may come here<br>}      <br><br>pub trait EigenDecomposition&lt;T&gt; {<br>    fn decompose(&amp;self, m: &amp;Matrix&lt;T&gt;) -&gt; Result&lt;(Vec&lt;f64&gt;, Matrix&lt;f64&gt;), EigenDecompositionError&gt; where T: Numeric;<br>}<br><br>pub struct JacobiDecomposition;<br><br>impl&lt;T&gt; EigenDecomposition&lt;T&gt; for JacobiDecomposition where T: Numeric {<br>// Source: https://www.astro.umd.edu/~ricotti/NEWWEB/teaching/ASTR415/InClassExamples/NR3/code/eigen_sym.h<br>fn decompose(&amp;self, m: &amp;Matrix&lt;T&gt;) -&gt; Result&lt;(Vec&lt;f64&gt;, Matrix&lt;f64&gt;), EigenDecompositionError&gt; {<br><br>        // Return error if not symmetric!<br>        if !m.is_symmetric() { return Err(EigenDecompositionError) }<br><br>        /* Jacobi algorithm */<br>    }     <br>}<br><br>pub fn rot&lt;T: Numeric&gt;(a: &amp;mut Matrix&lt;T&gt;, s: T, tau: T, i: usize, j: usize, k: usize, l: usize)<br>{<br>    /* rotation logic */<br>}<br><br>pub fn eigen_sort&lt;T&gt; (eigen_values: &amp;mut [T], eigen_matrix: &amp;mut Matrix&lt;T&gt;) -&gt; Result&lt;(), EigenDecompositionError&gt;<br>where T: Numeric {<br>    /* Sort logic */<br>}</pre><p>The Jacobi Algorithm* is a Strategy that implements the EigenDecomposition trait. As there are multiple ways to compute the eigen decomposition of a matrix, adding a new algorithm will require to write a new strategy. Adding other algorithms will be achieved by:</p><ul><li>adding a variant to the Algorithm enum, and</li><li>adding a struct that implements the EigenDecomposition&lt;T&gt; trait with the new algorithm in the decompose method.</li></ul><p>Now in the implementation of decompose there is a check performed on the input matrix. If it is not symmetric, then the method returns an error. I kept the error messages simple and did not leverage on the Rich Error Pattern as there is only one algorithm. As the algorithms are added, the pattern should be used to provided more detailed errors.</p><p>(Full implementation <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/master/src/symmetric.rs">here</a>)</p><p>* I used Numerical Receipes’ implementation from <a href="https://www.astro.umd.edu/~ricotti/NEWWEB/teaching/ASTR415/InClassExamples/NR3/code/eigen_sym.h">that site</a> that I converted from C++ to Rust.</p><h4>Cholesky Decomposition</h4><p>To finish on the implementation, we need to provide a trait to Matrix&lt;T&gt; that checks whether a matrix is positive definite and exposes a method to compute the cholesky decomposition.</p><pre>pub trait PositiveDefinite {<br>    fn is_positive_definite(&amp;self) -&gt; bool;<br>    fn cholesky(&amp;self) -&gt; Result&lt;Matrix&lt;f64&gt;, CholeskyDecompositionError&gt;;<br>}<br><br>impl&lt;T&gt; PositiveDefinite for Matrix&lt;T&gt; where T: Numeric {<br>    fn is_positive_definite(&amp;self) -&gt; bool {<br>        if !self.is_symmetric() { return false }<br>        if let Ok((eigen_values, _)) = self.eigen_decomposition(Algorithm::Jacobi) {<br>            for value in &amp;eigen_values {<br>                if *value &lt;= Numeric::zero() { return false }<br>            }    <br>        } else { return false }<br>        true<br>    }<br><br>    // Source: https://www.astro.umd.edu/~ricotti/NEWWEB/teaching/ASTR415/InClassExamples/NR3/code/cholesky.h<br>    fn cholesky(&amp;self) -&gt; Result&lt;Matrix&lt;f64&gt;, CholeskyDecompositionError&gt; {<br>        if !self.is_positive_definite() { return Err(CholeskyDecompositionError::MatrixIsNotPositiveDefinite) }<br>        /* Cholesky algorithm */<br><br>    }<br>}</pre><p>Note that the eigen decomposition using Jacobi is used to determine the eigen values and if the matrix is positive definite. The Cholesky algorithm is, again, taken from <a href="https://www.astro.umd.edu/~ricotti/NEWWEB/teaching/ASTR415/InClassExamples/NR3/code/cholesky.h">this site</a> that implements Numerical Receipes in C++.</p><p>Just as in the Symmetry trait’s implementation, if the matrix is not positive definite, then the method cholesky returns an error that the user can then process.</p><p>(Full implementation <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/master/src/definite.rs">here</a>)</p><h3>Wrapping up</h3><p>So here we are. We have implemented ourselves a Matrix&lt;T&gt; Rust object that implements a trait PositiveDefinite with a method for computing the Cholesky decomposition. Along the way, multiple checks are performed to ensure that the computation goes smoothly:</p><ul><li>ensuring the matrix is square — we did not show it here in the article for brevity but <a href="https://github.com/Gilt0/gyouretsu-no-otaku/blob/master/src/square.rs">in the code you can see it</a>.</li><li>ensuring the matrix is symmetric, and</li><li>ensuring the matrix is positive definite.</li></ul><p>With regard to the mathematical properties of matrices, I had a bit of a dilemma.</p><p>(i) — Technically, it could have been better suited to use a Decorator Pattern for the different types of matrices. A first approach would have been to decorate structures all the way up to a Positive Definite matrix: after all, this is how mathematics are built. A second approach would have used specialized builder that build from a matrix of the previous step.</p><ul><li>A matrix can build a square matrix if the dimensions are equal.</li><li>A square matrix can build a symmetric matrix if coefficients are such that the symmetry condition is full filled.</li><li>A symmetric matrix can build a Positive Definite matrix if the eigen values are strictly positive.</li></ul><p>(ii) — Traits felt like a possible route to take as well. Because Rust is all about composition rather than inheritance. And I wanted to gain personal experience on traits, hence their use in this article and the subsequent code.</p><p>One could think that the Decorator Pattern would have been a little more efficient because the type of the object would ensure whether you can access a method or not. In the final application, I know that I will not be heavily calling the Cholesky Decomposition methods or the Eigen Decomposition ones — only once for a given matrix, therefore the small overhead due to characteristic check is not that big of a deal.</p><p>What would you have chosen?</p><p>I would really be curious of what you think and start, with you guys, a conversation about your favorite design for the above matrix definitions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785a3a1c2400" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on Market Microstructure — Building a Rust program to match a trade with its…]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-market-microstructure-building-a-rust-program-to-match-a-trade-with-its-3bced14a5ce7?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bced14a5ce7</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[market-microstructure]]></category>
            <category><![CDATA[binance]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 08:25:46 GMT</pubDate>
            <atom:updated>2024-01-01T08:25:46.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on Market Microstructure — Building a Rust program to match a trade with its corresponding order book event.</h3><p><em>Codes available on </em><a href="https://github.com/Gilt0/Shougoutaku"><em>Github</em></a></p><p><em>All the work presented here has been achieved with the help of a specialized GPT which I made public for those with the link below. It is tuned to produce rust code.<br></em><a href="https://chat.openai.com/g/g-6jn21r4yc-algo-trader">https://chat.openai.com/g/g-6jn21r4yc-algo-trader</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMhUwESsbVDe33URapTtjg.png" /><figcaption>When the physicist realizes that his rust superpowers will be handy (Generated by Dall.e)</figcaption></figure><p>Binance has revolutionized a lot of things when it comes to market data availability.</p><p>When I was a student, you simply could not get your hands on order book data. Or you knew someone (generally who knew someone)… When I was a young Quant, I had to wait to be assigned to the right project to receive what I perceived then as the most incredible data that ever existed. And I had to sweat to extract it… from the logs of the Smart Order Router!</p><p>Nowadays, you can freely connect to the Binance API to get very decent microstructure data. It is not perfect as you don’t get the full information — <em>Market By Price</em> (MBP) data and not <em>Market By Order </em>(MBO), check <a href="https://medium.com/@systemathics/market-by-order-vs-market-by-limit-7a5b6bcbbee2">this post</a> for more information, but it is already a really good place to start and you can have quite a bit of fun with it.</p><p>In today’s post, I will try and guide through one of the most challenging yet even more interesting problem of algoithmic trading (actual trading set aside of course!).</p><p>We will write a naive algorithm that matches order book event updates with trade updates.</p><p>The <em>what </em>with <em>what</em>? Yes I know, if you are not familiar with these terms, some clarifications are in order. These clarifications will be the object of the first part: we’ll have some memory refreshments on order books and trades.</p><p>In the second part, we’ll talk about the Data Sources. In our case, we will be sourcing our data from Binance using some scripts available in the GitHub repo.</p><p>In the third part, we’ll investigate a small data sample. In that investigation, we will, <em>by-hand*,</em> match trade updates with order book events. The task may seem hard at first, and it will have some caveats, but with simple rules we can get something to get us started with.</p><p>Fourth, we’ll get our hands dirty with an actual algorithm. The algorithm will achieve about 50% reconstruction. It is a small ratio and I will be able to explain most of the reasons leading to such reconstruction performance. And despite this small ratio, the investigation is still very insightful and a useful learning experience.</p><p>And you’ll see that achieving this results requires already quite a lot of work.</p><p>行くぞ！</p><p>*Of course I wrote a program to help…</p><h3>Order Book and Trades</h3><p>In order to buy or sell a financial instruments, a trader can enter an agreement with a person over the phone, this is an over-the-counter, or OTC, trade. They can also make an entry in a dedicated registry, called an <em>order book</em>, providing the price and quantity they are attempting to trade.</p><p>An order book can be sketched as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEHSCrrg3A1930-nOwkDcQ.png" /><figcaption>Sketch of an Order Book.</figcaption></figure><p>Each rectangle represents a price at which the asset can be agreed to be exchanged. The number inside the rectangle is the quantity of said asset that is waiting to be sold (<em>Ask</em> side — in red) or purchased (<em>Bid</em> side — in green). Behind each of these quantities, there may be multiple traders waiting for an execution.</p><p>When a trader submits an order, it may either be a passive order or an aggressive order.</p><h4>Passive Order</h4><p>Say that the trader places a buy order for 0.24 asset at 9.80. Their order will be placed on price level 9.80 of the bid side of the order book. The order book has now a configuration where the volume at price level 9.80 is at 1.5 + 0.24 = 1.74.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1Bgd2DZchlFf7gQA13STQ.png" /><figcaption>The same Order Book after a passive order for 0.24 asset at a price of 9.80.</figcaption></figure><p>Such an order is called a <em>passive order </em>because the trader is in a waiting queue to buy the asset at the price of 9.80. They have to passively wait for another trader to be willing to trade with them.</p><p>Earlier, I made a mention that ‘there may be multiple traders waiting for an execution’, and this is now justified. When traders decide to wait for an execution (buy or sell) by sending a passive order, their desired liquidity for the trade is added to the already available liquidity. And it is only executed once all prior liquidity in the queue has been consumed.</p><p><strong>When sending a passive order no trade occurs. There is only an order book event with an increase of liquidity.</strong></p><h4>Aggressive Order (and Trades!)</h4><p>Say that the trader now places a buy order for 0.35 asset at 10.20. Since the price corresponds to a rectangle on the ask side, the order is said to be <em>aggressive</em>. The Order Book now looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guO0-PLXiO9aqxUcuJbLCg.png" /><figcaption>The same Order Book after an aggressive buy order for 0.35 asset at a price of 20.20.</figcaption></figure><p>What happened?</p><p>Well, the trader was willing to pay up to 10.20 for 0.35 assets. As there was 0.25 asset available at 10.10, a <strong><em>trade</em> </strong>occurred at 10.10 for 0.25 assets. Since 0.10 asset were remaining to be executed, and since 0.67 asset were available at 10.20, the limit of the aggressive trader, there was <strong><em>another trade</em> </strong>at 10.20 for 0.10 asset.</p><p>Therefore <em>at least</em> two trades have to be reported:</p><ul><li>a trade for 0.25 asset at 10.10, and</li><li>a trade for 0.10 asset at 10.20.</li></ul><p>I used the word at least because there will actually be as many trades as passive participants provide the liquidity, <em>e.g.</em> if 3 people were waiting at ask price level 10.10 for an execution, then three trades would be recorded. And the same goes for the 0.10 asset consumed on price level 10.20. If more than one participant was waiting, then there will be as many trades as there were executed providers at that price level.</p><p><strong>Bonus — An aggressive trade is always more costly </strong>— We ought to take a bit of time here. In a <a href="https://medium.com/@quantitative-modelling-for-fun/optimal-execution-yet-another-theory-d6b6b0f8fc68">previous post</a> on optimal execution, I went very technical on how to execute according to industry standards without explaining key concepts. I’ll correct that wrong here.</p><p>First of all, an aggressive trader is said to <strong><em>cross the spread. </em></strong>The phrase is quite self explanatory: in its impatience, the trader decides to not wait for an aggressive seller and goes one or few more levels up the best bid to meet a patient seller at the best ask or above.</p><p>Second of all, for a broker, being able to avoid crossing the spread can make a a bit of a difference on the final PnL. Say for example that we take today’s spread on the order book BNB-BTC where BNB is the exchanged asset and BTC is the currency of transactions.</p><pre>% date &amp;&amp; \<br>curl -s &#39;https://api.binance.com/api/v3/depth?symbol=BNBBTC&amp;limit=1&#39; | \<br>jq -r &#39;&quot;\(.bids[0][0]) \(.asks[0][0])&quot;&#39; | \<br>awk &#39;{print 20000*($2 - $1)/($1 + $2)}&#39;<br><br>Sun Dec 24 06:55:05 JST 2023<br>1.6146</pre><p>As the bash snippet above shows, it is at 1.6146 bips just before 7. For those who don’t know, 1 bip is equal to 0.01%. Why does this number matter? If you trade a $ 1,000,000 aggressively, you would loose about $161.46. Not much might you say. But let’s scale things up a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uomb20NQWcqE-f_2gxAVPA.png" /><figcaption>Traded Volumes on the Nasdaq.</figcaption></figure><p>Above is a summary of <a href="https://ir.nasdaq.com/static-files/465d2157-c476-4546-a9f7-8d7ad0c9be77">the traded volumes on the Nasdaq</a>. On Nasdaq’s order books, European equity traded volume was between $ 50,000,000,000 to $ 70,000,000,000 every month. And that’s for Europe only!</p><p>So using that number to get a sense of the order of magnitude, 1.6146 bips on that volume is about $ 116,251,200!</p><p>Even if we scaled that number at the size of the traded volume of an execution desk of a big broker, this could amount in millions every year.</p><p>In a nutshell, with a back-of-an-envelop cross multiplication, we see that the stakes are rapidly high to favor passive trading over aggressive trading.</p><p>However, there is now another issue that arise from trading passively: you are not sure to be fully executed… But that is for another day…</p><h4>Two streams of data feeds for a complete information</h4><p>From a conceptual perspective, two continuous auction phenomena have to be distinguished, hence the two different data streams.</p><p>(i) — First, the order book is constantly changing because of passive traders as they add or cancel passive orders.</p><p>(ii) Second, aggressive orders trigger one or more trades between two parties.</p><p>Now the difficult part, in the context of an MBP feed is that the orderbook changes are tracked with aggregated view. And if for some reason, one wants to reconstruct the continuous auction in its entirety, some logic has to reverse engineer the two streams of data. Which what we are after here!</p><p>But first let7s talk about the data sources.</p><h3>The Data Sources</h3><p>There will be three data sources.</p><ul><li>One http endpoint from which the current order book is retrieved. We will call the output of such request a <em>Snapshot</em>. Simply because it is <em>de facto</em> a snapshot of the current order book’s state.</li><li>Two websocket endpoints: one to collect order book event updates, and another one to collect trade updates.</li></ul><h4>Order book snapshots</h4><p>Try this. It’s better than a 1000 words.</p><pre>% curl &#39;https://api.binance.com/api/v3/depth?symbol=BNBBTC&amp;limit=10&#39;   </pre><p>The output of that command is something like this,</p><pre>{<br>  &quot;lastUpdateId&quot;:3221409269,<br>  &quot;bids&quot;:[<br>    [&quot;0.00614900&quot;,&quot;32.92600000&quot;],<br>    [&quot;0.00614800&quot;,&quot;22.23300000&quot;],<br>    [&quot;0.00614700&quot;,&quot;13.73200000&quot;],<br>    [&quot;0.00614600&quot;,&quot;7.06500000&quot;],<br>    [&quot;0.00614500&quot;,&quot;27.11700000&quot;],<br>    ...<br>  ],<br>  &quot;asks&quot;:[<br>    [&quot;0.00615000&quot;,&quot;5.24200000&quot;],<br>    [&quot;0.00615100&quot;,&quot;28.26300000&quot;],<br>    [&quot;0.00615200&quot;,&quot;13.49900000&quot;],<br>    [&quot;0.00615300&quot;,&quot;14.58300000&quot;],<br>    [&quot;0.00615400&quot;,&quot;12.66600000&quot;],<br>    ...<br>  ]<br>}</pre><p>which we can plot using a cumulative sum on the volumes, and with a limit parameter in the curl high enough to cover sufficient depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BMBlhF4UeuANNlT_-pA0Q.png" /></figure><p>What you are looking at is the order book state when the query was made.</p><p>You can have a look at the current state of the order book too if you wish. After cloning the GitHub repo, from the root, run these bash commands.</p><pre>mkdir tmp<br>curl &#39;https://api.binance.com/api/v3/depth?symbol=BNBBTC&amp;limit=5000&#39; &gt; tmp/snapshot.json<br>python scripts/plot-orderbook.py --input-path tmp/snapshot.json --output-path tmp/</pre><h4>Binance Requirements</h4><p>This is an important point: the snapshot json response&#39;s lastUpdateId field is a very important field as it provides the index to synchronize the snapshot with Order Book event updates. Indeed, as you will see below, there are two fields U and u which are respectively the first update ID in the message and the final update ID in the message. As a message from the order book data stream can contain the outcome of multiple events.</p><p>These ID’s are used for two things:</p><ul><li>ensuring the correct sequencing of received messages as some could get lost on the way;</li><li>properly synchronize the snapshot by making sure that <br>U &lt;= lastUpdateId + 1 &amp;&amp; u &gt;= lastUpdateId + 1 .</li></ul><h4>Order book event updates</h4><p>You can try to connect to the order book event update with <a href="https://github.com/vi/websocat/releases">websocat</a> and the command below.</p><pre>websocat wss://stream.binance.com:9443/ws/bnbbtc@depth@100ms</pre><p>If you enter this into a terminal, you should be getting an output in the likes of :</p><pre>% websocat wss://stream.binance.com:9443/ws/bnbbtc@depth@100ms<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308358257,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277455,&quot;u&quot;:3221277456,&quot;b&quot;:[],&quot;a&quot;:[[&quot;0.00614700&quot;,&quot;17.63500000&quot;],[&quot;0.00615000&quot;,&quot;12.96600000&quot;]]}<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308358657,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277457,&quot;u&quot;:3221277458,&quot;b&quot;:[[&quot;0.00614400&quot;,&quot;13.66600000&quot;]],&quot;a&quot;:[]}<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308358757,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277459,&quot;u&quot;:3221277460,&quot;b&quot;:[[&quot;0.00612900&quot;,&quot;13.83700000&quot;]],&quot;a&quot;:[[&quot;0.00615700&quot;,&quot;126.01600000&quot;]]}<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308358957,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277461,&quot;u&quot;:3221277461,&quot;b&quot;:[],&quot;a&quot;:[[&quot;0.00614600&quot;,&quot;7.16900000&quot;]]}<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308359057,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277462,&quot;u&quot;:3221277464,&quot;b&quot;:[[&quot;0.00614400&quot;,&quot;18.22200000&quot;],[&quot;0.00614200&quot;,&quot;8.26400000&quot;]],&quot;a&quot;:[]}<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308359157,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277465,&quot;u&quot;:3221277467,&quot;b&quot;:[[&quot;0.00614300&quot;,&quot;4.81900000&quot;],[&quot;0.00614200&quot;,&quot;16.35600000&quot;]],&quot;a&quot;:[]}<br>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1703308359257,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;U&quot;:3221277468,&quot;u&quot;:3221277468,&quot;b&quot;:[[&quot;0.00614400&quot;,&quot;16.95600000&quot;]],&quot;a&quot;:[]}<br>^C</pre><p>These updates do not carry obvious abnormalities. As the Binance Requirements presented earlier requires, the value of field &quot;U&quot; at one line is exactly equal to the increment of 1 from the value of field &quot;u&quot; of the previous line.</p><p>Other fields of interest will be &quot;E&quot; , &quot;b&quot; and &quot;a&quot; as they are respectively a timestamp, the updated levels in the bid side of the book and the updated levels on the ask side of the book.</p><h4>Trade event updates</h4><p>The websocket endpoint is very similar to the order book event update one. Only the very end changes for a very expected &quot;trade&quot;.</p><pre>websocat wss://stream.binance.com:9443/ws/bnbbtc@trade</pre><p>It outputs the following messages.</p><pre>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328396500,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994585,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.09000000&quot;,&quot;b&quot;:1779378259,&quot;a&quot;:1779387173,&quot;T&quot;:1703328396499,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408630,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994586,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.49000000&quot;,&quot;b&quot;:1779378259,&quot;a&quot;:1779387210,&quot;T&quot;:1703328408607,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408630,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994587,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;2.00000000&quot;,&quot;b&quot;:1779381485,&quot;a&quot;:1779387210,&quot;T&quot;:1703328408607,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408630,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994588,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.69800000&quot;,&quot;b&quot;:1779385186,&quot;a&quot;:1779387210,&quot;T&quot;:1703328408607,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408632,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994589,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;1.30200000&quot;,&quot;b&quot;:1779385186,&quot;a&quot;:1779387211,&quot;T&quot;:1703328408608,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408632,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994590,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;1.10100000&quot;,&quot;b&quot;:1779385188,&quot;a&quot;:1779387211,&quot;T&quot;:1703328408608,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408633,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994591,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.89900000&quot;,&quot;b&quot;:1779385188,&quot;a&quot;:1779387212,&quot;T&quot;:1703328408608,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408633,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994592,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;1.00000000&quot;,&quot;b&quot;:1779386156,&quot;a&quot;:1779387212,&quot;T&quot;:1703328408608,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408633,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994593,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;2.00000000&quot;,&quot;b&quot;:1779387169,&quot;a&quot;:1779387212,&quot;T&quot;:1703328408608,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408653,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994594,&quot;p&quot;:&quot;0.00614200&quot;,&quot;q&quot;:&quot;0.83500000&quot;,&quot;b&quot;:1779377545,&quot;a&quot;:1779387218,&quot;T&quot;:1703328408632,&quot;m&quot;:true,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408702,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994595,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.65300000&quot;,&quot;b&quot;:1779387236,&quot;a&quot;:1779387219,&quot;T&quot;:1703328408689,&quot;m&quot;:false,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408735,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994596,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.63000000&quot;,&quot;b&quot;:1779387246,&quot;a&quot;:1779387219,&quot;T&quot;:1703328408718,&quot;m&quot;:false,&quot;M&quot;:true}<br>{&quot;e&quot;:&quot;trade&quot;,&quot;E&quot;:1703328408735,&quot;s&quot;:&quot;BNBBTC&quot;,&quot;t&quot;:230994597,&quot;p&quot;:&quot;0.00614300&quot;,&quot;q&quot;:&quot;0.02300000&quot;,&quot;b&quot;:1779387246,&quot;a&quot;:1779387221,&quot;T&quot;:1703328408718,&quot;m&quot;:false,&quot;M&quot;:true}<br>^C</pre><p>The fields of interest will mainly be &quot;E&quot; , &quot;p&quot; and &quot;q&quot; : the timestamp of the trade event, the price and the quantity of trade.</p><p>Matching any of the trades above will be tantamount to <strong>looking at the variations in the order book levels</strong> and trying to associate an order book event with that trade whenever there is a reasonable match in the timestamp, quantity and price numbers.</p><h4>Data collection</h4><p>For the data collection, nothing really fancy. To avoid having to start and stop multiple processes at the same time, I leveraged some asynchronous coding using python&#39;sasyncio module.</p><p>Here is the bash command to start a capture.</p><pre>python scripts/capture-depth-trades.py --symbol BTCUSDT --save-folder tmp</pre><p>In the script, the order book snapshot is requested 1 second after the start of the websockets’ collections.</p><pre>async def fetch_and_save_snapshot(symbol, folder):<br>    await asyncio.sleep(1)  # Delay for 1 second<br>    # <br>    # Rest of the code in the full snippet above<br>    #</pre><p>This is to ensure the Binance Requirements presented above would be respected when reconstructed the order book.</p><h3>Empirical Investigation on a small sample</h3><p>Before throwing myself into the implementation of an algorithm, I’ll investigate a small sample to see how I could reconcile them, was I to do it with a pen and paper.</p><p>Well… Almost as if i was to do it with a pen and paper. Because I did set up a small pygame interface. Because really, looking at lots of giberrishy lines can be cumbersome.</p><h4>The data</h4><p>The samples are located at the path data/capture/btcusdt/1702798595534677/.</p><pre>% ls data/capture/btcusdt/1702798595534677/                       <br>ask_trade.txt   bid_trade.txt   depth.txt       snapshot.txt</pre><p>The bid_trade.txt and the ask_trade.txt contain respectively 29 and 26 trades for a total of 45 trades. That’s not a lot! And that should not surprise you as the capture was from GMT Sunday, December 17, 2023 7:36:35.858 AM to GMT Sunday, December 17, 2023 7:36:44.862 AM, so exactly 9.004 seconds.</p><p>The snapshot has the event ID 41239690701 implying that the first depth update that will be considered is</p><pre>{&quot;e&quot;:&quot;depthUpdate&quot;,&quot;E&quot;:1702798596858,&quot;s&quot;:&quot;BTCUSDT&quot;,&quot;U&quot;:41239690697,&quot;u&quot;:41239690709, ...}</pre><p>implying that all trades with a timestamp inferior to 1702798596858 will be discarded because of the system implementation. This means that the trade with the tid (trade id) 3324705797 will be discarded as it happened a bit too early at 1702798596164 694 milliseconds too soon.</p><h4>PyGame script</h4><p>I am not going to present the script, it would be way too long and it would add information in this already very long post! If you wish to check the code (it is a little messy…), please check the file <a href="https://github.com/Gilt0/Shougoutaku/blob/master/scripts/message-viewer.py">scripts/message-viewer.py</a>.</p><p>But here is the final interface though (and you can also easily launch it with the command</p><pre>python scripts/message-viewer.py</pre><p>too!).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqRUCdYlXMUG8xfR6RT5oA.png" /><figcaption>User interface of the pygame tool</figcaption></figure><p>As you can see on the figure above, the interface is rather simple. It has the timestamp of the current order book event update — <em>e.g.</em> the timestamp of the orderbook, the trades appears with their timestamp under the corresponding side, volume variations between order book events are between brackets on the right of the corresponding side and finally a cursor is there to travel across time — forward to the right and backward to the left.</p><p>The trades are chosen so that they are within a range of -100ms and +100ms around the order book event timestamp.</p><p>Why this number? Because the websocket was open with a request for 100ms updates. This means that orderbook updates are batched by 100ms intervals. An orderbook event will necessarily have a corresponding trade, if it does, within that interval… Unless there are serious delays on the network, which I do not consider for now.</p><h4>Matched trades</h4><p>On the figure above, you should see also in green a double sided arrow that signals a matched trade. It is what we are looking for.</p><p>Why is it matched? Because the volumes are identical. And this what we hope for: negative order book volume variations that are equal in absolute value to the trade quantity.</p><h4>Edge cases</h4><p>Here we are going to look at edge cases that will break the logic.</p><p><strong>Multiple trade reports for the same order book event — </strong>A first issue occurs when multiple trades, add or cancels occur within 100ms. Usually these trades have the same timestamp and correspond to bigger trades split into smaller ones to avoid missing on liquidity.</p><p>(i) — Because the order book event update will have a newly added volume that does not correspond to the trade volume.</p><p>(ii) — Because the best bid might have changed during the trade.</p><p><strong>Iceberg orders— </strong>This issue arises when the some liquidity is not shown on the order book. Binance authorizes those and they can be quite deceptive.</p><p><strong>Example 1 — </strong>At timestamp 1702798603963, for example, there is a stack of trades that consumes the first level entirely, the second level and the third level, and at the second level there is a mismatch of quantities because of a hidden iceberg order!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17b4ty43a1BNA4tYEjuGHA.png" /><figcaption>Stack of trade that consumes multiple levels and an iceberg order.</figcaption></figure><p><strong>Example 2— </strong>At timestamp 1702798602905, there is a stack of 3 trades that consume a total of 0.28061 asset. However the level has decreased by 0.13334 asset. This mismatch indicates that there possibly was a cancellation. If you check the trade id’s in the raw data you’ll see that the sequence is accurate.</p><p>Therefore a cancellation is the only sound conclusion one can have. Of course, there could also be add events that we are not aware of as well, but we shall keep the dominant trait.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9Shv5lQhnjO8CWxyMIa2A.png" /></figure><h3>Rust implementation of the trade-book event matcher</h3><p>The code is organized between four files.</p><pre>% ls src <br>messages.rs   orderbook.rs   shougoutaku.rs   trade_matcher.rs</pre><p>messages.rs contains the serialization/deserialization logic.</p><p>orderbook.rs contains the logic for maintaining the flow of information from the order book event update webhook as well as the matching logic — yes… that’s two responsabilities and I would probably seperate it if I was to do it again)</p><p>shougoutaku.rs is the main file with the main loop. It contains also the construction logic of the trade candidates.</p><p>trade_matcher.rs maintains the flow of trade update from the webhook and its initiate the matching of trades with order book event updates when there are any. It also maintains a clean results of the overall process.</p><p>The general idea is to loop through the depth file and look at currently loaded trades to see if a match is possible.</p><h4>Serialization/Deserialization of messages and snapshots</h4><p>With regards to the serialization, I used Rust’s serde which is very convenient. However, one should keep in mind that an external library is used to parse the json. There could be a possibility that custom json parsing would be beneficial on such a critical part. Nonetheless, for our object of concern, serde will do the job just as well.</p><pre>// src/messages.rs<br><br>use rust_decimal::Decimal;<br>use serde::{Deserialize, Serialize};<br>use serde_json::Value;<br>/// Custom deserialization function for Decimal<br>/// Converts a string to a Decimal, returning an error if the string is not a valid representation.<br>fn deserialize_decimal&lt;&#39;de, D&gt;(deserializer: D) -&gt; Result&lt;Decimal, D::Error&gt;<br>where<br>    D: serde::Deserializer&lt;&#39;de&gt;,<br>{<br>    let s: String = Deserialize::deserialize(deserializer)?;<br>    s.parse::&lt;Decimal&gt;().map_err(serde::de::Error::custom)<br>}<br>/// Custom serialization function for Decimal<br>/// Converts a Decimal to a string representation.<br>fn serialize_decimal&lt;S&gt;(value: &amp;Decimal, serializer: S) -&gt; Result&lt;S::Ok, S::Error&gt;<br>where<br>    S: serde::Serializer,<br>{<br>    let s = value.to_string();<br>    serializer.serialize_str(&amp;s)<br>}<br>/// Custom deserialization function for trade_id<br>/// Supports deserializing a trade_id from either a string or a number in JSON.<br>fn deserialize_trade_id&lt;&#39;de, D&gt;(deserializer: D) -&gt; Result&lt;String, D::Error&gt;<br>where<br>    D: serde::Deserializer&lt;&#39;de&gt;,<br>{<br>    let value = Value::deserialize(deserializer)?;<br>    match value {<br>        Value::String(s) =&gt; Ok(s),<br>        Value::Number(num) =&gt; Ok(num.to_string()),<br>        other =&gt; Err(serde::de::Error::custom(format!(<br>            &quot;Invalid type for trade_id: expected string or number, found {:?}&quot;,<br>            other<br>        ))),<br>    }<br>}<br>/// Represents the JSON message format for depth updates via WebSockets.<br>#[derive(Debug, Serialize, Deserialize, Default)]<br>pub struct DepthUpdate {<br>    #[serde(rename = &quot;e&quot;)]<br>    pub event_type: String,<br>    #[serde(rename = &quot;E&quot;)]<br>    pub event_time: u64,<br>    #[serde(rename = &quot;s&quot;)]<br>    pub symbol: String,<br>    #[serde(rename = &quot;U&quot;)]<br>    pub first_update_id_in_event: u64,<br>    #[serde(rename = &quot;u&quot;)]<br>    pub final_update_id_in_event: u64,<br>    /// List of bid values to update; each bid is represented as a pair of Decimals [price, quantity].<br>    #[serde(rename = &quot;b&quot;)]<br>    pub bids_to_update: Vec&lt;(Decimal, Decimal)&gt;,<br>    /// List of ask values to update; each ask is represented as a pair of Decimals [price, quantity].<br>    #[serde(rename = &quot;a&quot;)]<br>    pub asks_to_update: Vec&lt;(Decimal, Decimal)&gt;,<br>}<br>/// Represents the JSON message format for an order book snapshot update via HTTP.<br>#[derive(Debug, Deserialize, Serialize, Default)]<br>pub struct SnapShotUpdate {<br>    #[serde(rename = &quot;lastUpdateId&quot;)]<br>    pub last_update_id: u64,<br>    /// List of bids; each bid is represented as a tuple of Decimals (price, quantity).<br>    pub bids: Vec&lt;(Decimal, Decimal)&gt;,<br>    /// List of asks; each ask is represented as a tuple of Decimals (price, quantity).<br>    pub asks: Vec&lt;(Decimal, Decimal)&gt;,<br>}<br>/// Represents the JSON message format for trade updates via WebSockets.<br>#[derive(Debug, Serialize, Deserialize, Default)]<br>pub struct TradeUpdate {<br>    #[serde(rename = &quot;e&quot;)]<br>    pub event_type: String,<br>    #[serde(rename = &quot;E&quot;)]<br>    pub event_time: u64,<br>    #[serde(rename = &quot;s&quot;)]<br>    pub symbol: String,<br>    #[serde(rename = &quot;t&quot;, deserialize_with = &quot;deserialize_trade_id&quot;)]<br>    pub trade_id: String,<br>    #[serde(rename = &quot;p&quot;, deserialize_with = &quot;deserialize_decimal&quot;, serialize_with = &quot;serialize_decimal&quot;)]<br>    pub price: Decimal,<br>    #[serde(rename = &quot;q&quot;, deserialize_with = &quot;deserialize_decimal&quot;, serialize_with = &quot;serialize_decimal&quot;)]<br>    pub quantity: Decimal,<br>    #[serde(rename = &quot;b&quot;)]<br>    pub buyer_order_id: u64,<br>    #[serde(rename = &quot;a&quot;)]<br>    pub seller_order_id: u64,<br>    #[serde(rename = &quot;T&quot;)]<br>    pub trade_time: u64,<br>    #[serde(rename = &quot;m&quot;)]<br>    pub is_market_maker: bool,<br>}</pre><p>The main point here is that I had to write specialized serialization/deserialization methods for the Decimal type. It is a very similar type to the decimal.Decimal object in python that avoids rounding float errors.</p><h4><strong>Order Book</strong></h4><p><strong>Snapshot synchronization — </strong>The order book is a rust struct as shown below. Much of the code is obfuscated for now as I don’t need to present it just yet.</p><p>However, if you take the time to look at it, you will notice the use of Binary Tree map to store both sides’ levels and two update methods.</p><p>Initially I went for a classic hash map — python reflexes — but my specialized GPT advised for that object instead.</p><pre>// src/orderbook.rs<br><br>// Order Book struct<br>pub struct OrderBook {<br>    last_update_id: u64,<br>    first_update_id_in_event: u64,<br>    final_update_id_in_event: u64,<br>    bids: BTreeMap&lt;Decimal, Decimal&gt;,<br>    asks: BTreeMap&lt;Decimal, Decimal&gt;,<br>    // ...<br>    // Some variables explained later<br>    // ...<br>}<br>impl OrderBook {<br>    pub fn new() -&gt; Self {<br>        // Nothing critical<br>    }<br>    // Getter methods for best bid and ask updated flags<br>    pub fn is_best_bid_updated(&amp;self) -&gt; bool {<br>        // Simple getter<br>    }<br>    pub fn is_best_ask_updated(&amp;self) -&gt; bool {<br>        // Simple getter<br>    }<br>    pub fn update(&amp;mut self, update: DepthUpdate) {<br>        // Skip if orderbok has not been loaded<br>        if self.last_update_id == 0 { return; }<br>        // Skip if final_update_id_in_event &lt;= last_update_id<br>        if update.final_update_id_in_event &lt;= self.last_update_id { return; }<br>        if self.first_update_id_in_event == 0 &amp;&amp; update.first_update_id_in_event &gt; self.last_update_id + 1 { <br>            warn!(&quot;Snapshot is a little too old - first_update_id_in_event = {:?}  last_update_id = {:?}&quot;, update.first_update_id_in_event, self.last_update_id);<br>        }<br>        if self.first_update_id_in_event != 0 &amp;&amp; update.first_update_id_in_event != self.final_update_id_in_event + 1 { <br>            warn!(&quot;Update sequence from websocket is mechakucha - update.first_update_id_in_event = {:?}  self.final_update_id_in_event = {:?}&quot;, update.first_update_id_in_event, self.final_update_id_in_event);<br>        }<br>        // ...<br>        // Some logic explained later<br>        // ...<br>    }<br>    pub fn update_with_snapshot(&amp;mut self, update: SnapShotUpdate) {<br>        self.last_update_id = update.last_update_id;<br>        // Nothing critical<br>    }<br>    pub fn match_and_process_trade(&amp;mut self, trade: &amp;TradeUpdate, trade_type: TradeType) -&gt; u64 {<br>        // ...<br>        // Some logic explained later<br>        // ...<br>    }<br>    pub fn print_orderbook(&amp;self, n: usize, title: &amp;str) {<br>        // Nothing critical<br>    }<br>}</pre><p>In the update method, the order book digests a message from the endpointbnbbtc@depth@100ms. With the satement</p><pre>if self.last_update_id == 0 { return; }</pre><p>it skips any line if the snapshot has not been loaded yet — self.last_update_id is still set to false.</p><p>To ensure that the sequencing requirement is enforced, we check that the event ID’s are in the right sequencing order as required by Binance.</p><pre>if self.first_update_id_in_event != 0 &amp;&amp; update.first_update_id_in_event != self.final_update_id_in_event + 1 { <br>    warn!(&quot;Update sequence from websocket is mechakucha - update.first_update_id_in_event = {:?}  self.final_update_id_in_event = {:?}&quot;, update.first_update_id_in_event, self.final_update_id_in_event);<br>}</pre><p>For this last filter, I chose to simply spit in the logs some warning and not halt the execution because I do not plan on having redundancies in my small program, nor is it critical to have the most accurate decriptions. Depending on my usage I might add a counter for these errors and exit the program if there are too many error. But at this stage, I prefer not to worry too much about that.</p><p><strong>You can skip this on a first read — </strong>Initially, I developped this struct for real-time purposes with frequents snapshot requests to bootstrap information. Therefore a couple of other filters were implemented.</p><ul><li>For ulterior snapshots that would be requested after the first one, in a real-time continuous set up, all order book updates that would somehow be older than the snapshot, would have to be dropped as they would mess up the information by updating with outdated messages.<br>Therefore I use this if statement to make sure otherwise.</li></ul><pre>if update.final_update_id_in_event &lt;= self.last_update_id { return; }</pre><ul><li>Similarly, if for some reason the snapshot message arrives a little too late, this condition at least shoots a warning.</li></ul><pre>if self.first_update_id_in_event == 0 &amp;&amp; update.first_update_id_in_event &gt; self.last_update_id + 1 { <br>            warn!(&quot;Snapshot is a little too old - first_update_id_in_event = {:?}  last_update_id = {:?}&quot;, update.first_update_id_in_event, self.last_update_id);<br>        }</pre><p><strong>Computing the volume variations — </strong>If you recall, to match the trade, we have to detect and compute volume variation on the order book levels. As shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*DAXSNszytDIGoeWwIEbojw.png" /></figure><p>To do so, whenever the Orderbook struct receives a depth update, we immediately compute the volume variations. And we have to do so for all the levels that could potentially be the best price <em>i.e.</em> whenever the current best price reaches zero, we compute the volume variation — level_delta in the snippet below — and we iterate for as many levels as necessary.</p><pre>pub fn update(&amp;mut self, update: DepthUpdate) {<br>    // ...<br>    // Checks presented earlier<br>    // ...<br>    <br>    // Store the current best bid and ask prices<br>    let current_best_bid = self.bids.keys().next_back().cloned();<br>    let current_best_ask = self.asks.keys().next().cloned();<br>    // Reset flags<br>    self.best_bid_updated = false;<br>    self.best_ask_updated = false;<br>    // Reset LevelDeltas before each update<br>    self.best_bid_deltas.clear();<br>    self.best_ask_deltas.clear();<br>    // Update bids<br>    let mut add_next_bid_level_delta: bool = false;<br>    for (price_level, quantity) in update.bids_to_update {<br>        // Check if the best bid price is updated<br>        if Some(&amp;price_level) == current_best_bid.as_ref() || add_next_bid_level_delta {<br>            if let Some(current_volume) = self.bids.get(&amp;price_level) {<br>                self.best_bid_updated = true;<br>                let volume_delta = *current_volume - quantity;<br>                if quantity.is_zero() {<br>                    add_next_bid_level_delta = true;<br>                } else {<br>                    add_next_bid_level_delta = false;<br>                }<br>                let level_delta = LevelDelta::new(price_level, volume_delta, update.event_time);<br>                self.best_bid_deltas.push(level_delta);<br>            }<br>        }<br>        if quantity.is_zero() { self.bids.remove(&amp;price_level); }<br>        else { self.bids.insert(price_level, quantity); }<br>    }<br><br>    // Update asks<br>    // ...<br>    // Same as bids<br>    // ...<br>}</pre><h4><strong>Constructing the trade candidates</strong></h4><p>The level update variations are computed and available. Now we need to focus on the trades. If you recall again, trades could be in a stack sequence. Usually having the same time stamp. And if you keep recalling, the selected level variation may not match all the trades of that timestamp and price level — like in example 2 above for price level 41926.85 where only one trade could actually be matched. Sometimes because of Iceberg orders, some other times because the level variation include an additional remove or add event.</p><p>In any case, it is wise to create from the stack sequence, a sequence of potential candidates using some — ideally all — subsets of possible subsequences of trades.</p><p>For example, say we have four trades of ids tid1,tid2,tid3,tid4. In such a case we would want to add the trades</p><ul><li>tid1 with volume V1</li><li>tid2 with volume V2</li><li>tid3 with volume V3</li><li>tid4 with volume V4</li><li>tid1-tid2 with volume V1+V2</li><li>tid1-tid3 with volume V1+V3</li><li>tid1-tid4 with volume V1+V4</li><li>tid2-tid3 with volume V2+V3</li><li>tid2-tid4 with volume V2+V4</li><li>tid3-tid4 with volume V3+V4</li><li>tid1-tid2-tid3 with volume V1+V2+V3</li><li>tid1-tid2-tid4 with volume V1+V2+V4</li><li>tid1-tid3-tid4 with volume V1+V3+V4</li><li>tid2-tid3-tid4 with volume V2+V3+V4</li><li>tid1-tid2-tid3-tid4 with volume V1+V2+V3+V4</li></ul><p>Now… This is the first version of my trade matcher and to be frank I did not want to add too much complexity so I stayed simple and only added these trades.</p><ul><li>tid1 with volume V1</li><li>tid1-tid2 with volume V1+V2</li><li>tid1-tid2-tid3 with volume V1+V2+V3</li><li>tid1-tid2-tid3-tid4 with volume V1+V2+V3+V4</li></ul><p>It provides better resuls but it is not perfect. To illustrate its imperfection, check timestamp 1702798604062 in the message-viewer.py interface, you will see that the trade stack below the bid side matches the volume variation if you remove the top trade of the stack…</p><p>But anyway, I wanted to stay simple so here it is in rust. The method is located in shougoutaku.rs.</p><pre>fn next_trades(trade_reader: &amp;mut Reader, prev_trade_info: &amp;mut PreviousTradeInfo, trade_matcher: &amp;mut TradeMatcher, trade_type: &amp;str) -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {<br>    if let Some(Ok(line)) = trade_reader.next() {<br>        let mut trade_update: TradeUpdate = serde_json::from_str(&amp;line)?;<br>        // Compare current and previous values<br>        if trade_update.event_time == prev_trade_info.prev_event_time &amp;&amp; trade_update.price == prev_trade_info.prev_price {<br>            trade_update.quantity += prev_trade_info.prev_quantity;<br>            trade_update.trade_id += &quot;-&quot;;<br>            trade_update.trade_id += &amp;prev_trade_info.prev_trade_id;<br>        }<br>        // Update the variables with current values for next iteration<br>        prev_trade_info.prev_event_time = trade_update.event_time;<br>        prev_trade_info.prev_price = trade_update.price.clone();<br>        prev_trade_info.prev_quantity = trade_update.quantity.clone();<br>        prev_trade_info.prev_trade_id = trade_update.trade_id.clone();<br>        trade_matcher.add_trade(trade_update);<br>        return Ok(());<br>    }<br>    Err(Box::new(TradeReadError::new(&quot;No more trades to read&quot;)))<br>}<br><br></pre><h4><strong>Matching trade candidates with volume variations</strong></h4><p>Finally, we are on the most crucial and desired aspect of the algorithm: the matching logic!</p><p>It’s actually two-fold.<br>(i) — First a method match_trades in the TradeMatcher struct that initiates the matching process. When it gets a result, it keeps a record of the result.</p><p>(ii) — Second a method match_and_process_trades in the Orderbook struct that compares a subset of known trades with the most recent order book update. When it finds a match, it returns the timestamp of the corresponding order book event update. If the trade is out dated — over 100 ms — then 1 is returned.</p><pre>pub fn match_trades(&amp;mut self, orderbook: &amp;mut OrderBook) -&gt; Vec::&lt;u64&gt; {<br>    let mut indices_to_remove = Vec::new();<br>    let mut event_times = Vec::&lt;u64&gt;::new();<br>    let mut trades_to_insert = Vec::new();<br>    for (index, trade) in self.trade_queue.iter().enumerate() {<br>        let te = match self.trade_type {<br>            TradeType::Bid =&gt; orderbook.match_and_process_trade(trade, TradeType::Bid),<br>            TradeType::Ask =&gt; orderbook.match_and_process_trade(trade, TradeType::Ask),<br>        };<br>        <br>        if te == 1 {<br>            info!(&quot;{:?} - Dropped Trade ID: {}&quot;, self.trade_type, trade.trade_id);<br>            indices_to_remove.push(index);<br>            trades_to_insert.push((trade.trade_id.clone(), trade.event_time, te));<br>        } else if te &gt; 1 {<br>            info!(&quot;{:?} - Matched Trade ID: {}, Event Time: {}&quot;, self.trade_type, trade.trade_id, te);<br>            indices_to_remove.push(index);<br>            event_times.push(te);<br>            trades_to_insert.push((trade.trade_id.clone(), trade.event_time, te));<br>        }<br>    }<br>    // Remove items in reverse order<br>    for index in indices_to_remove.into_iter().rev() {<br>        self.trade_queue.remove(index);<br>    }<br>    // Now that we are no longer borrowing `self.trade_queue`, insert the trades<br>    for (trade_id, trade_event_time, event_time) in trades_to_insert {<br>        self.insert_trade_ids(&amp;trade_id,trade_event_time, event_time);<br>    }        <br>    event_times<br>}</pre><pre>pub fn match_and_process_trade(&amp;mut self, trade: &amp;TradeUpdate, trade_type: TradeType) -&gt; u64 {<br>    let level_deltas = match trade_type {<br>        TradeType::Bid =&gt; &amp;mut self.best_bid_deltas,<br>        TradeType::Ask =&gt; &amp;mut self.best_ask_deltas,<br>    };<br>    for level_delta in level_deltas.iter_mut() {<br>        let trade_event_time = trade.event_time;<br>        if level_delta.event_time &gt; (trade_event_time + 100) {<br>            return 1;<br>        }<br>        if level_delta.volume &lt; Decimal::new(0, 0) { continue; }<br>        if trade.price == level_delta.price &amp;&amp; trade.quantity == level_delta.volume {<br>            // Here, you&#39;d perform the matching logic and return the trade_id if matched<br>            level_delta.volume -= trade.quantity;<br>            return level_delta.event_time;<br>        }<br>    }<br>    0<br>}</pre><h4><strong>Main loop</strong></h4><p>The main loop is actually quite straight forward. Lines in the depth file are read one by one and trade candidates are processed. As trades are matched or dropped, other trades are loaded. The loop is implemented as such.</p><pre>    loop {<br><br>        let depth_line = depth_reader.next();<br><br>        // Check if all files have reached EOF<br>        if depth_line.is_none() {<br>            break;<br>        }<br><br>        if next_ask_trade { // When trades are matched or dropped.<br>            next_ask_trade = false;<br>            loop {<br>                match next_trades(&amp;mut ask_trade_reader, &amp;mut prev_ask_info, &amp;mut ask_matcher, &quot;Ask&quot;) {<br>                    Ok(()) =&gt; { /* Normal processing */ },<br>                    Err(e) =&gt; {<br>                        error!(&quot;Error reading trade: {}&quot;, e);<br>                        break; // Break out of the loop<br>                    }<br>                }<br>                if ask_matcher.number_of_timestamps() == 5 {<br>                    break;<br>                }<br>            }<br>        }<br><br>        // ...<br>        // Same for bid trades<br>        // ...<br><br>        if let Some(Ok(line)) = depth_line {<br>            let depth_update: DepthUpdate = serde_json::from_str(&amp;line)?;<br>            debug!(&quot;{:?}&quot;, depth_update);<br>            orderbook.update(depth_update);<br>            if orderbook.is_best_ask_updated() {<br>                let event_times = ask_matcher.match_trades(&amp;mut orderbook);<br>                if event_times.len() != 0 {<br>                    next_ask_trade = true; // Matched or dropped trades.<br>                } <br>            }<br><br>        // ...<br>        // Same for bid trades<br>        // ...<br>        <br>        }<br>    }</pre><h4><strong>Purging at the end of execution</strong></h4><p>When reaching the end of the depth file, because the capture is such that there may be trade updates without possible depth updates to match with, these trades are tagged as <em>purged</em> with a value of 2 — as a reminder, for matched trade, the tag is the timestamp of the matched order book event while for dropped trade, the tag is .</p><h4><strong>Results</strong></h4><p>The algorithm is tested on two data set. The first very small sample that we investigated earlier; and a bigger one, spanning from GMT Tuesday, December 19, 2023 4:23:08.999 PM to GMT Tuesday, December 19, 2023 5:07:30.434 PM.</p><p><strong>Small sample — </strong>The command is rather long but quite self explanatory. After providing cargo with the necessary arguments to compile and run, you need to add and extra -- after which the programs arguments may be provided.</p><pre>RUST_LOG=info cargo run --bin shougoutaku -- --snapshot data/capture/btcusdt/1702798595534677/snapshot.txt --depth data/capture/btcusdt/1702798595534677/depth.txt --ask_trade data/capture/btcusdt/1702798595534677/ask_trade.txt --bid_trade data/capture/btcusdt/1702798595534677/bid_trade.txt</pre><p>The output is something like</p><pre>[2023-12-28T08:04:02Z INFO  shougoutaku::trade_matcher] Ask - Matching output<br>        Trade ID        Trade Time      Event Time<br>        3324705798      1702798597052   1702798597058<br>        3324705799      1702798597349   1702798597358<br>        3324705800      1702798597387   1702798597458<br>        3324705801      1702798598334   1702798598359<br>        3324705803      1702798598719   1702798598759<br>        3324705804      1702798598927   1702798598959<br>        3324705806      1702798600587   1              -&gt; additional add<br>        3324705808      1702798601388   1702798601460<br>        3324705809      1702798601549   1702798601560<br>        3324705811      1702798601752   1702798601761<br>        3324705814      1702798602154   1702798602161<br>        3324705815      1702798602319   1702798602361<br>        3324705816      1702798602905   1              -&gt; additional cancel<br>        3324705817      1702798602905   1              -&gt; additional cancel<br>        3324705818      1702798602905   1              -&gt; additional cancel<br>        3324705820      1702798603265   1702798603361<br>[2023-12-28T08:04:02Z INFO  shougoutaku::trade_matcher] Bid - Matching output<br>        Trade ID        Trade Time      Event Time<br>        3324705797      1702798596164   1              -&gt; snapshot delay<br>        3324705802      1702798598588   1702798598659<br>        3324705805      1702798599555   1702798599559<br>        3324705807      1702798600829   1702798600860<br>        3324705810      1702798601655   1702798601660<br>        3324705812      1702798601955   1702798601961<br>        3324705813      1702798602134   1702798602161<br>        3324705819      1702798603083   1702798603161<br>        3324705821      1702798603963   1702798604062<br>        3324705822      1702798603963   1702798604062<br>        3324705823      1702798603963   1702798604062<br>        3324705824      1702798603963   1702798604062<br>        3324705825      1702798603963   1702798604062<br>        3324705826      1702798603963   1702798604062<br>        3324705827      1702798603963   1702798604062<br>        3324705828      1702798603963   1              -&gt; iceberg order<br>        3324705829      1702798603963   1              -&gt; iceberg order<br>        3324705830      1702798603963   1              -&gt; iceberg order<br>        3324705831      1702798603963   1              -&gt; iceberg order<br>        3324705832      1702798603963   1              -&gt; iceberg order<br>        3324705833      1702798603963   1              -&gt; iceberg order<br>        3324705834      1702798603963   1              -&gt; iceberg order<br>        3324705835      1702798603963   1              -&gt; iceberg order<br>        3324705836      1702798603963   1              -&gt; iceberg order<br>        3324705837      1702798603963   1702798604062<br>        3324705838      1702798604087   1              -&gt; iceberg order<br>        3324705839      1702798604087   1              -&gt; logic limitation<br>        3324705840      1702798604087   1              -&gt; logic limitation<br>        3324705841      1702798604087   1              -&gt; logic limitation</pre><p><em>If you wish to check the explanation of particular trade, use </em>ctrl+c-&gt;ctrl+f<em> on the trade timestamp to be pointed to the right paragraph below.</em></p><p>As you can see 17 trades out of a total of 45 has been dropped. The xclusion reasons is shown at the end of the line with the format <br>-&gt; &lt;reason for being dropped&gt;</p><p>Let’s have a look in more details using the message-viewer.py script.</p><p><strong>Ask trade of timestamp </strong><strong>1702798600587 — </strong>As shown in the image sequence below, there actually are multiple order book events that could be potentially matched with the trade. None have a volume variation that exactly match the trade quantity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acVN0KXR_ln1ifyVZIOpXA.png" /><figcaption>First match possibility for ask trade of timestamp 1702798600587</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-KdeLcylCeXybWFDi7iBQ.png" /><figcaption>Second match possibility for ask trade of timestamp 1702798600587</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxfSX9wOuUTz_BpUL7LBkA.png" /><figcaption>Third match possibility for ask trade of timestamp 1702798600587</figcaption></figure><p>The second event seems to be the most likely events and its absolute volume variation is smaller than expected therefore there probably has been at least one additional add event on that level.</p><p><strong>Ask trade of timestamp </strong><strong>170279860587 — </strong>This trade has been dealt with in example 2 above in the paragraph on Edge cases.</p><p><strong>Bid trade of timestamp </strong><strong>1702798596164— </strong>In this particular case, the trade could not be matched because its timestamp is anterior to the snapshot event. And if you recall, I coded the order book to wait for a snapshot before it starts processing order book event updates.</p><p><strong>Bid trade of timestamp </strong><strong>1702798603963— </strong>This trade has been dealt with in example 1 above in the paragraph on Edge cases.</p><p><strong>Bid trade of timestamp </strong><strong>1702798604087— </strong>This trade is interesting as it shows a clear short coming of the implemented logic. If you recall, I mentionned that, for simplicity’s sake, I was reducing the set of trade candidates with a very simple subsequence of the trade stack — a pyramidal like construct. I also said that it could produce matching weaknesses. And here is a perfect example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U09cIM6t-c_JBStjhJaWEA.png" /></figure><p>Basically, if you sum only the last three quantities you find</p><pre>&gt;&gt;&gt; 0.00681000+0.00681000+0.02730000<br>0.04092</pre><p>which is a perfect match with the level volume variation.</p><p>The logic should thus build other trade candidate combinations. A brute force approach would be to get all the possible ones, while a more heuristical one would require the quant-devlopper to add combinations has they occur. Here they would have to include pyramidal sequences starting from the last trade of the stack.</p><p><strong>Big sample — </strong>For the big sample, the command is the following.</p><pre>RUST_LOG=info cargo run --release --bin shougoutaku -- --snapshot data/capture/btcusdt/1702970588517503/snapshot.txt --depth data/capture/btcusdt/1702970588517503/depth.txt --ask_trade data/capture/btcusdt/1702970588517503/ask_trade.txt --bid_trade data/capture/btcusdt/1702970588517503/bid_trade.txt &gt; tmp/debug.log 2&gt;&amp;1</pre><p>You’ll notice that this time I have used the --release flag to have an optimized compilation.</p><p>(i) — 9,311 ask trades were dropped out of 19,416 ask trades.<br>(ii) — 14,548 bid trades were dropped out of a total of 23,016 bid trades.<br>(iii) —23,859 trades on both sides were dropped out of a total of 42,432 trades.</p><p>Clearly the program has shortcomings as about 56% of trades were either dropped or purged.</p><p>Now that is if you see the glass as half empty. If you see it as half full, and although it may sound very obvious to say, almost 50% of trades were matched with an order book event update that is within 100 ms and has the exact same volume variation as the trade quantity!</p><p>I think this is a very encouraging benchmark with such a naive system, which, if ever you want to put into production, you would still have few deployment hurdles you would entrust to your Dev’Ops — or if your as curious as I am, to yourself!</p><p>I believe this first version to be an acceptable step towards production, so I will stop this already very long post here.</p><h3>Wrapping Up</h3><p>So… In a nutshell, with this study and naive algorithm:</p><p>A — We can match ~1/2 of the trades with order book events.</p><p>B — We gained a better understanding of the data provided by Binance through the websocket streams.</p><p>C — The road ahead would consist in investigating further the large data capture to improve the quality of the event matching algorithm.</p><p>D — I chose the pair BTC-USDT which is very active, or <em>liquid</em> in the jargon. Possibly, and I have not checked, the algorithm could behave a lot better on less liquid pairs where event collisions are more unlikely.</p><p>E — People discovering microstructure today are very lucky, they have access to ressources I would never have dreamt of when I first got acquainted with this field of Finance. Ladies, Gents, if you are reading this, I envy you. :)</p><p><strong><em>Get your hands dirty — </em></strong><em>If you are really motivated and want to give some of your personal education time to the wonders of Microstructure, you could investigate for yourself the shortcomings on the large data capture.<br>If you have any questions, you can ping me on the comments below or on GitHub. I’ll happily assist you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bced14a5ce7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on Data Mining (I) — Minimum Spanning Tree and Clustering]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-data-mining-i-minimum-spanning-tree-and-clustering-d6e40cbf52d1?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e40cbf52d1</guid>
            <category><![CDATA[binance]]></category>
            <category><![CDATA[minimum-spanning-tree]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 23:52:21 GMT</pubDate>
            <atom:updated>2023-12-28T15:01:53.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on Data Mining (I) — Minimum Spanning Tree and Clustering</h3><p>Digging up an old clustering method a new.</p><p><em>Scripts and notebook available on </em><a href="https://github.com/Gilt0/kurasutaku/tree/master"><em>GitHub</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0z1g-D7oqzyTUiExKtFzQ.png" /><figcaption>If Thorin and his subjects mined data (generated by GPT).</figcaption></figure><p>I have had few discussions recently in my professional activity with recurring focus on clustering. In the context of finance but not only.</p><p>Some years ago, clustering was a huge philosophical quest for me. There are a lot of methods all with their pros and cons. Very quickly I got interested in Affinity Propagation. I thought the method to be elegant and close to what I would have expected to do myself to cluster data points, had I been given the time to come up with my own methodology.</p><p>It had some draw backs though. First, I felt like I had no real control over the clusters that affinity propagation creates. I had to twick the distance matrix myself with the instabilities that may arise from doing so.</p><p>At some point, I was on a quest for a methodology that would be my <em>go-to-method</em> to explore some data rapidly with full control of the cluster designs.</p><p>After a lot of trial an error, I realized that the method I was after already existed (as most of the times!) and it beared the technical name of the Minimum Spanning Tree (MST).</p><p>That method looks for the smallest connection graph between all nodes of a distance matrix. If you wish to then concentrate on clusters with a certain bond strength, you simply have to cut your graph depending on what you are after. It is not a perfect method but it is a very flexible one. And that is why I like it a lot.</p><p>In this post, I’ll try, as usual, to give you simple yet explanatory explanations and examples. I’ll start with some mathematical details on the Kruskal method to compute the MST of a distance matrix, as it is the algorithm implemented in scipy . Second, I will say few words on the data collection: I use crypto-asset data as it is very easily accessible and in great quantity, however the methodology presented here can be used in many other set ups (marketing, geospatial tasks, corporate strategy, etc). Then in a third section, we’ll have a look at how the MST is used to clean a universe of stock from most of its correlation.</p><h3>Minimum Spanning Tree (MST) and Kruskal’s algorithm</h3><p>It’s a rather simple algorithm which we will illustrate with an example. Understanding pure maths behind every tool at the disposal of a physicist is very much like filling the Danaids’s leaking bathtub: it takes a lot of time, energy, good will and never ends!</p><p>I did it. A lot. I thought that it was part of my responsibilities of the physicist. I still do, although now I try to take shortcuts to construct my intuitions on good examples and good figures.</p><p>Let’s work through the Kruskal algorithm for a small distance matrix made out of 6 points. I’ll present the initial state and iterate over the algorithm until it reaches its end.</p><h4>Initial State</h4><p>We have a fully connected graph with nodes and weighted edges as shown in the figure below. Nodes are called A, B, C, D, E, F and weights are shown both on the graph and in a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RbVs-ewyOzB6pYh9i4UQg.png" /></figure><h4>First Iteration</h4><p>We choose the lowest weight value in the table and store the corresponding edge. In the context of our figure, storing an edge is displayed as changing the edge color to green. The weight value of that edge is also green-ized in the table for ease of spotting the row-column pair in the table.</p><p>In our case, the first edge is B — C as its weight is 25, the lowest value in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rngT0ey3tcEX_Nf0lGudFw.png" /></figure><h4>Second Iteration</h4><p>Then we pick the second lowest weight… Nothing really difficult or surprising here and the second edge in the MST is A — F, with a weight of 29.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ii1dFeryXa7HyBz-J5lmJw.png" /></figure><h4>Third Iteration</h4><p>Again, the third lowest weight is very straight forward. We pick thus edge C— E as its weight is 30.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXDMTUZ9an6-Szc1Y9Vhng.png" /></figure><h4>Fourth Iteration</h4><p>This iteration shows exactly the kind of edge case that the algorithm deals with in a really good way. If we pick the next smallest weight, we should choose the edge E — B. However, selecting this edge would create the cycle B — C — E. And, by construction, the MST is precisely not made of cycles.</p><p>Therefore, that edge cannot be selected, it is instead put aside, thus red-ized, and we move on for the next smallest value.</p><p>The next smallest weight is 53 for edge D — E. We thus choose that edge and make it green, while B — C remains red: we want to know that this edge should never be visited again in the following iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsgn19sIPJbYpiy_1PngZA.png" /></figure><h4>Fifth Iteration</h4><p>At that last iteration, no surprise again and we pick the smallest edge value. No need to worry about possible cycles.</p><p>The next edge to pick is A — D with a weight of 57.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6bYQ1GfpLm1PMPUqyYACA.png" /></figure><h4>Final State</h4><p>After that last iteration, selecting any of the remaining edges would create a cycle. You can verify yourself, you really cannot select any other edge without creating a cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X55hBBQmTaqTt-qrV3EHLw.png" /></figure><p>Therefore the algorithm stops here and the MST is the green subgraph displayed below.</p><h4>Using the MST as a clustering algorithm</h4><p>Say that now you decide to prune the MST for all values that are above a threshold weight, say, 35. What will you get?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80djNvWOmTELDpVNZxtetw.png" /></figure><p>Three clusters! <br>(1) — cluster {A, F}<br>(2) — cluster {D}<br>(3) — cluster {B, C, E}.</p><p>Note that all pairs of elements in a cluster do not necessarily respect the cutoff value. It is one of the drawbacks of this clustering method which we explain a bit further below.</p><h4>Limits of the MST as a clustering algorithm</h4><p>As already mentionned, all edges’ weights are not necessarily below the cutoff value of 35. Just look at the edge B — E, its weight is 40 which is clearly above the threshold.</p><p>Is that an issue? No. The underlying structure of the problem at hand will generally ensure that weights are not way off the cutoff value.</p><p>For example, in the context of correlations of gaussian vectors, the constraint of definite matrix will generally insure sufficient coherence so that outlier edges will never be really too far off. Similarly, in the context of geospatial localisations, the Cauchy–Schwarz inequality, inherent to any distance measurement will sufficiently constraint the matrix to ensure coherence within clusters.</p><p><strong>However, if one use distance matrix that do not have an underlying structure from its computation methodology, one have clusters with edges that violate the cutoff constraint significatively.</strong></p><h3>The Data</h3><p>A Crypto-Exchange like Binance provides incredible amounts of data to play with, so I will demonstrate my thoughts with crypto-financial data, but this article is <strong>not</strong> a financial engineering article, although its output would definitely be of great use to asset managers.</p><p>The retrieval of data is performed with the script below. I indicate the full script for those looking for such a script and would be visiting this page with that purpose in mind only. :)</p><pre>import argparse<br>import requests<br>import csv<br>import os<br>import glob<br>import time<br>from datetime import datetime, timedelta, timezone<br>from tqdm import tqdm<br><br>DURATIONS = {<br>        &quot;1d&quot;: timedelta(days=1),<br>        &quot;6h&quot;: timedelta(hours=6),<br>        &quot;1h&quot;: timedelta(hours=1),<br>        &quot;30m&quot;: timedelta(minutes=30),<br>        &quot;5m&quot;: timedelta(minutes=5),<br>    }<br>TIMESTAMP = int(datetime.now().timestamp()*1000000)<br><br><br>def get_klines(symbol, start_time, end_time, interval=&#39;1d&#39;):<br>    url = &quot;https://api.binance.com/api/v3/klines&quot;<br>    limit = 500  # API limit<br>    interval_duration = DURATIONS[interval]<br>    max_duration = limit * interval_duration<br>    all_data = []<br>    while start_time &lt; end_time:<br>        current_end_time = min(start_time + max_duration, end_time)<br>        params = {<br>            &quot;symbol&quot;: symbol,<br>            &quot;interval&quot;: interval,<br>            &quot;startTime&quot;: int(start_time.timestamp() * 1000),<br>            &quot;endTime&quot;: int(current_end_time.timestamp() * 1000),<br>            &quot;limit&quot;: limit<br>        }<br>        response = requests.get(url, params=params)<br>        if response.status_code == 200:<br>            data = response.json()<br>            if not data:<br>                break  # Break the loop if no data is returned<br>            print(&quot;URL:&quot;, response.request.url)<br>            all_data.extend(data)<br>            # Update start_time: Use the close time of the last kline plus 1 millisecond<br>            last_kline_close_time = data[-1][6]<br>            start_time = (datetime.utcfromtimestamp((last_kline_close_time + 1) / 1000)).replace(tzinfo=timezone.utc)<br>            # Safety check to avoid infinite loops<br>            if current_end_time &gt;= end_time:<br>                break<br>        else:<br>            print(f&quot;Error fetching data for {symbol}: {response.status_code}&quot;)<br>            break<br>        time.sleep(0.5)  # To respect API rate limits<br>    return all_data<br><br><br>def save_to_csv(data, symbol, save_folder):<br>    save_folder = f&#39;{save_folder}/raw/{TIMESTAMP}/&#39;<br>    os.makedirs(save_folder, exist_ok=True)<br>    filename = f&quot;{save_folder}/klines_{symbol}.csv&quot;<br>    <br>    headers = [<br>        &quot;symbol&quot;, &quot;kline_open_time&quot;, &quot;open_price&quot;, &quot;high_price&quot;, &quot;low_price&quot;, <br>        &quot;close_price&quot;, &quot;volume&quot;, &quot;kline_close_time&quot;, &quot;quote_asset_volume&quot;, <br>        &quot;number_of_trades&quot;, &quot;taker_buy_base_asset_volume&quot;, &quot;taker_buy_quote_asset_volume&quot;<br>    ]<br>    with open(filename, &#39;w&#39;, newline=&#39;&#39;) as file:<br>        writer = csv.writer(file)<br>        writer.writerow(headers)<br>        for line in data:<br>            writer.writerow([symbol] + line[:-1])  # Add symbol and exclude the last element<br><br><br>def concatenate_csv(save_folder):<br>    save_folder = f&#39;{save_folder}/combined/{TIMESTAMP}/&#39;<br>    os.makedirs(save_folder, exist_ok=True)<br>    all_filenames = glob.glob(os.path.join(f&#39;{save_folder}/../../raw/{TIMESTAMP}&#39;, &quot;klines_*.csv&quot;))<br>    combined_csv = os.path.join(save_folder, &quot;klines.csv&quot;)<br>    with open(combined_csv, &#39;w&#39;, newline=&#39;&#39;) as outfile:<br>        for i, fname in enumerate(all_filenames):<br>            with open(fname, &#39;r&#39;) as infile:<br>                if i != 0:<br>                    infile.readline()  # Skip the header for all but the first file<br>                outfile.write(infile.read())<br>    print(f&quot;Combined CSV file created at {combined_csv}&quot;)<br><br><br>def main():<br>    parser = argparse.ArgumentParser(description=&quot;Fetch Kline/Candlestick Data for given symbols&quot;)<br>    parser.add_argument(&quot;--symbols&quot;, nargs=&#39;+&#39;, type=str, required=True, help=&quot;List of symbols&quot;)<br>    parser.add_argument(&quot;--start-date&quot;, type=str, required=True, help=&quot;Start date in YYYY-MM-DD format&quot;)<br>    parser.add_argument(&quot;--end-date&quot;, type=str, required=True, help=&quot;End date in YYYY-MM-DD format&quot;)<br>    parser.add_argument(&quot;--save-folder&quot;, &quot;-sf&quot;, type=str, required=True, help=&quot;Folder to save output CSV files&quot;)<br>    parser.add_argument(&quot;--interval&quot;, type=str, required=True, choices=[&#39;5m&#39;, &#39;30m&#39;, &#39;1h&#39;, &#39;6h&#39;, &#39;1d&#39;], help=&quot;Interval for klines&quot;)<br>    args = parser.parse_args()<br>    # Parsing start and end dates (assuming input dates are in UTC)<br>    start_date = datetime.strptime(args.start_date, &quot;%Y-%m-%d&quot;).replace(tzinfo=timezone.utc)<br>    end_date = datetime.strptime(args.end_date, &quot;%Y-%m-%d&quot;).replace(tzinfo=timezone.utc) if args.interval == &#39;5d&#39; else (datetime.strptime(args.end_date, &quot;%Y-%m-%d&quot;).replace(tzinfo=timezone.utc) - DURATIONS[args.interval])<br>    print(start_date, end_date)<br>    for symbol in tqdm(args.symbols, desc=&quot;Processing symbols&quot;):<br>        data = get_klines(symbol, start_date, end_date, args.interval)<br>        if data:<br>            save_to_csv(data, symbol, args.save_folder)<br>    print(&#39;Almost done - concatenating data&#39;)<br>    concatenate_csv(args.save_folder)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>This script ensures that the request size limits of Binance’s API are respected by looping over the period, as well as the frequency limits by throttling the requests every 0.5 seconds.</p><p>I generated the data for the month of November 2023 with the following command (from the root of the GitHub repo).</p><pre>python scripts/kline_fetcher.py --interval 5m --start-date 2023-11-01 --end-date 2023-12-01 --save-folder ./data/5m/ --symbols BTCFDUSD BTCUSDT ETHUSDT SOLUSDT JTOUSDT ADAUSDT XRPUSDT AVAXUSDT USDCUSDT ORDIUSDT DOGEUSDT BNBUSDT FDUSDUSDT MATICUSDT LINKUSDT ARBUSDT DOTUSDT OPUSDT MEMEUSDT TIAUSDT LUNCUSDT NEARUSDT USDTTRY JTOTRY FTMUSDT PEPEUSDT ATOMUSDT RUNEUSDT SHIBUSDT FILUSDT GALAUSDT IMXUSDT ETHBTC ALGOUSDT FTTUSDT ETCUSDT LTCUSDT DYDXUSDT BTCTUSD BEAMXUSDT AKROUSDT ETHFDUSD ADABTC UNIUSDT TUSDUSDT SANDUSDT SOLBTC GFTUSDT INJUSDT RNDRUSDT SUIUSDT APTUSDT TRXUSDT QIUSDT USTCUSDT EGLDUSDT STMXUSDT RAYUSDT BUSDUSDT LUNAUSDT UNFIUSDT FETUSDT EOSUSDT WRXUSDT SEIUSDT APEUSDT BAKEUSDT BCHUSDT AVAXTRY FLOWUSDT TRBUSDT BLURUSDT BTCUSDC AAVEUSDT OGUSDT GASUSDT ETHUSDC XRPBTC WLDUSDT ICPUSDT CAKEUSDT AVAXBTC GMTUSDT JOEUSDT CFXUSDT STXUSDT MANAUSDT BNBBTC SUPERUSDT MASKUSDT CHZUSDT XLMUSDT MEMETRY HOOKUSDT SOLBUSD BTTCUSDT LDOUSDT WAVESUSDT GRTUSDT AXSUSDT LUNCTRY HBARUSDT ORDITRY WBTCBTC NEOUSDT AGIXUSDT SNXUSDT IDUSDT VETUSDT CYBERUSDT MKRUSDT MAGICUSDT VITEUSDT SUSHIUSDT SOLFDUSD CTXCUSDT DOTBTC HIGHUSDT ETHBUSD ILVUSDT YFIUSDT XMRUSDT CRVUSDT ZILUSDT MINAUSDT ADATRY NTRNUSDT DOGEBTC ENSUSDT XVSUSDT RDNTUSDT FIDAUSDT PEPETRY ONEUSDT BEAMXTRY KAVAUSDT SCUSDT PYRUSDT COMPUSDT EDUUSDT FLOKIUSDT MATICBTC SLPUSDT LQTYUSDT THETAUSDT ROSEUSDT AUCTIONUSDT SSVUSDT LOOMUSDT YGGUSDT ASTRUSDT CELOUSDT STGUSDT ARKMUSDT SOLETH GMXUSDT FTMBTC IOTAUSDT OGTRY MAVUSDT KLAYUSDT POWRUSDT QNTUSDT XRPTRY 1INCHUSDT BNBFDUSD LINAUSDT USDTBRL DREPUSDT MDTUSDT KSMUSDT KP3RUSDT BETAUSDT CHESSUSDT ETHTUSD AEURUSDT C98USDT BLZUSDT RVNUSDT STORJUSDT HOTUSDT ACHUSDT BELUSDT GLMRUSDT LINKBTC FDUSDBUSD TIATRY BTCTRY QTUMUSDT JASMYUSDT SXPUSDT REEFUSDT SHIBTRY TWTUSDT SOLTRY ENJUSDT USTCTRY HFTUSDT STRAXUSDT ARUSDT</pre><p>It produced numerous files (one for each symbol) in the target folder ./data/5m/raw/&lt;timestamp&gt;/raw/ where the &lt;timestamp&gt; folder is automatically generated with the timestamp of the time at which it was created. It also produced a data file in ./data/5m/raw/&lt;timestamp&gt;/combined/ with all the data concatenated together.</p><h3>The Clustering</h3><h4>Objective</h4><p>I have 200 stocks. I want to be able to select the <strong><em>least correlated</em></strong> stocks so that I can best diversify my investments.</p><p>That is very much a financial engineering objective. And yes, I am sort of contradicting myself. :)</p><h4>Non Financial Engineering example of use</h4><p>So here is an example of use of the MST clustering approach on sales data. It’s actually take from a real consulting job I did few years ago. However, I o not have the data, which is very private (sadly!).</p><p>Say for example that you wish to cluster clients or products: the following methodology will work if you have a table like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6rEPKWfPW9EBlOBoTWrVg.png" /></figure><p>where the columns represent clients and the lines represent products. The elements <em>sᵢⱼ</em> are sales in currency ($,￥, €, …).</p><p>If one has such a table, they can cluster both clients and products using an MST technic on a distance matrix built with some scalar product.</p><p>For clustering clients, we could use the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf9UdXqYHOmW5auEhB68_Q.png" /></figure><p>to compute the distance matrix, while for clustering products, we could use instead the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXP0qoGzKHK2bYq99oMA5Q.png" /></figure><h4>Choosing the appropriate edge weights, from MST to MxST</h4><p>I need to be able to group together the most correlated crypto-assets. So I need to have a <strong><em>Maximum Spanning Tree</em></strong> (MxST) instead of a a minimum spanning tree. To achieve this while using the Kruskal Algorithm, I could implement a dual algorithm where the highest weight is chosen, making sure that no cycle is introduced in the final output tree.</p><p>However, I want to use scipy.sparse.csgraph.minimum_spanning_tree which outputs the MST. Therefore, I will tweak the distance matrix to ensure that the output of the MST is exactly the same as the desired output from a MxST algorithm.</p><p>Using the distance matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o__SSxMAld8-jYUbZ1uTnA.png" /></figure><p>ensures that. Indeed, when picking the smallest available element in <strong>D</strong>, we effectively choose the largest available element in <strong>|C|</strong>.</p><p>As you have noticed, I discarded the sign of the correlation. This is because I only want to know if there is a correlation link between two crypto-assets, whether it be positive or negative. A negative sign indicates only the possibility of a long-short strategy to maximize chances of gain.</p><h4>The code for the clustering</h4><p>To store the MST, scipy.sparse.csgraph.minimum_spanning_tree returns a numpy.array that will be stored in anetworkx.Graph instance. With this object it will be very easy to then plot the pruned output MST — don’t forget we will prune it for clustering purposes!</p><pre>def create_mst_graph(C, cutoff):<br>    &quot;&quot;&quot;<br>    Creates a graph representing the minimum spanning tree from a correlation matrix with a given cutoff.<br><br>    Parameters:<br>    C (pd.DataFrame): Correlation matrix.<br>    cutoff (float): Cutoff value for edge weights.<br><br>    Returns:<br>    networkx.Graph: The graph object representing the minimum spanning tree.<br>    &quot;&quot;&quot;<br>    columns = C.columns<br>    # Convert to distance matrix<br>    D = 1 - np.abs(C.values)<br><br>    # Compute the minimum spanning tree<br>    mst = minimum_spanning_tree(D)<br><br>    # Create a NetworkX graph<br>    G = nx.Graph()<br><br>    # Add edges and weights to the graph, applying the cutoff<br>    for i, j in zip(*mst.nonzero()):<br>        weight = 1 - mst[i, j]<br>        if weight &gt; cutoff:<br>            G.add_edge(columns[i], columns[j], weight=weight)<br><br>    return G</pre><p>The loop over the values in the numpy.array clearly shows the pruning of edges with correlation values below the cutoff value.</p><p>Let’s analyse the results for several cutoff values.</p><h4>Initial Correlation Matrix</h4><p>Initially, we have the following correlation matrix with its corresponding Maximum Spanning Tree (MxST). As anyone can see, the matrix is very rich with a lot of redundant information shown by the darker shades of green. The lighter the area, the lower the correlation between the variables represented by the column and the row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v99EqEG0yiPSOUSuBYoSCw.png" /></figure><p>The MxST is also difficult to exploit as there are way too many branches and too many nodes that are very close to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJzm2APaNzyfWRY92CMttw.png" /></figure><p>To start with, let’s isolate the clusters of crypto-assets with a correlation threshold above 80% (0.8).</p><h4>Cutoff at 80%</h4><p>With a cutoff at 80%, the MxST is very sparse with many clusters. A closer inspection shows something which is, once observed, very obvious. If you click on the image, you should be able to zoom a bit and see that these clusters are those of the same crypto-asset quoted in different crypto-currency or FIAT currency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTA7bn6GdA6_k14OSCPCNw.png" /></figure><p>For example, the top cluster is the BTC cluster with the following symbols:<br>- BTCDUSD<br>- BTCUSDT<br>- BTCTUSD<br>- BTCTRY<br>- BTCUSDC<br>where DUSD, USDT, TUSD and USDC are crypto-assets and TRY is the Turkish Lira (FIAT).</p><p>After pruning the tree, I update the correlation matrix by keeping a representatives of the cluster — favouring a USDT quoted symbol, excluding all other cluster members and keeping the symbols that were not clustered with other assets because the correlation level was below 80%.</p><pre>cutoff = .8<br>G = create_mst_graph(C, cutoff=cutoff)<br># ...<br>clusters = list(nx.connected_components(G))<br>representatives = []<br>for cluster in clusters:<br>    # Sort nodes to favor &#39;USDT&#39; in names<br>    sorted_cluster = sorted(list(cluster), key=lambda x: &#39;USDT&#39; not in x)<br>    representatives.append(sorted_cluster[0])<br>excluded_symbols = set()<br>for cluster in clusters:<br>    for symbol in cluster:<br>        excluded_symbols.add(symbol)<br>symbols = representatives + [ symbol for symbol in C.columns if not symbol in excluded_symbols ]<br>C = C.loc[symbols, symbols]</pre><p>The correlation matrix plot output is given below. It may not be extremly obvious yet but with a close look you will see that very dark clusters have disappeared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sqDUiBttThY1X4Wq0Gslg.png" /></figure><h4>Cutoff at 60%</h4><p>Pursuing further and computing a pruned MxST with 60% a correlation displays more diverse clusters. Take for example the branch spanning from GMXUSDT (bottom left) to BNBBTC (bottom center) via ETHUSDT and BNBUSDT.</p><p>GMX is a decentralized exchange, BNB is a crypto-asset offered by Binance for their users and ETH is the token of the most famous smart contract blockchain for which Binance is the nunber 1 plateform. So, in way, there is absolutely nothing surprising when you wee that these symbols are interconnected. If you look closely, BTCUSDT is connected to ETHUSDT which is, again not a suprise as BTC and ETH are generally accepted as very correlated crypto-assets, no matter the quoting (crypto-)asset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rdlcvcs_NqPZx2n9BpZCjQ.png" /></figure><p>By running the same logic and only keeping representatives of clusters with pruned nodes, I get the much brighter correlation matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kfNEucjt5HTdEJaaJUK_A.png" /></figure><p>The correlation matrix appears as a lot more brighter. So let’s dig in further, it seems that the direction taken is promising.</p><h4>Cutoff at 40%</h4><p>With a cutoff at 40%, once the clustering information has been juiced out with a 60% cutoff MxST, we obtain two clusters. The central clusters has a an average correlation of about 50% which is still quite high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxQh6LNgY7jrTcRABlSvpA.png" /></figure><p>The correlation matrix appears as always brighter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wX54xRP6p6mZEKQYdQrvMQ.png" /></figure><h4>Cutoff at 20%</h4><p>Now at 20%, we get three clusters which are showed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUCTUEmpa2esy_iCkjHrhA.png" /></figure><p>At that point, the correlation matrix becomes very close to a unit matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6znIArWdnqPHbKKyFOGBg.png" /></figure><p>We stop here. Mainly because, from my experience, financial noise is such that with correlation below 20% you’re close to not correlated. Of course, there should be a proper statistical test to understand the correctness of my statement, but this post is about clustering, not asset management. :)</p><h4>Final MxST</h4><p>The final correlation matrix is very promising. And as visual proof of the correlation reduction, let’s plot the MxST of the remaining symbols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A60WrofIBgFcnmkedr0IVA.png" /></figure><p>The tree happens to have 18 symbols, so we reduced by more than 90% the universe. By checking the maximum correlation value of each column, we get the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAHKpGoS6JKoAC73fKCXjw.png" /></figure><p>It shows that all non diagonal elements are below 20%. Remember that having all pairs with less than 20% correlation is not an absolute necessity! The explanatory example showed, in the beginning of this post, that odd cases may happen. However, as I was explaining earlier, most real life examples will have constraints that maintain some coherence with the end selection. As this example shows.</p><p>Further considerations into the selected symbols show that multiple stable coins were selected, which is not a great surprise. And in an asset management focused post, more work should be put into which asset we keep or exclude. But this is not the objective of this post…</p><p>Maybe I’ll write an article about that!</p><p>(Or you could do it and let us know in the comments your findings…)</p><h3>Wrapping Up</h3><p>To wrap up the work, I would like to come back to what I think physics teaches us. Physics teaches us to keep it simple and clear. Physics teaches to focus on the most fundamental aspects of a phenomenon to extract clarity from entropic situations.</p><p>Here I tried to focus on clustering and how to build a simple clustering algorithm for fast Data Mining. There are many methods available and I have used most of them in the past, whether it be in Financial Engineering, Marketing, Manufacturing, Operations Research…</p><p>But the MxST has never let me down. And I use it no matter what as I know exactly how it works and how I can tune it. Additionally, the MST/MxST method is the one method I think every Data Miner should know how to implement quickly as it forces you actually drill into the data.</p><p>Other methods (DBScan, HDBScan, Affinity Propagation, K-Means, etc…) are fantastic, but IMHO, nothing beats MST/MxST drilling. To conduct the study well, you just have to put your nose in the data. Nothing beats that.</p><blockquote>What do you think? Would you agree with me? Or do you have another preferred method?</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e40cbf52d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on AI (II) — Time Series in Finance]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicist-view-on-ai-ii-time-series-in-finance-e868f7462d74?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/e868f7462d74</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[high-frequency-trading]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[binance]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 02:32:57 GMT</pubDate>
            <atom:updated>2023-11-16T01:56:04.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on AI (II) — Time Series in Finance</h3><p>Using Empirical insights to build a Neural Network</p><p><em>Codes on </em><a href="https://github.com/Gilt0/liquotaku"><em>Github</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVznbFPuz5bKl71ITzVj3Q.png" /><figcaption>A physicist at his desk in the style of my favourite French comics, Asterix and Obelix (by Dall.e)</figcaption></figure><p>For this second post on AI, I chose a theme that is very dear to me: Econometrics. I remember that learning Econometrics at the Ecole Polytechnique sparked massive questioning for me.</p><p>An important one was: why are all econometrical models linear? In Natural Science, there are plenty of laws and relationships that are non linear. So why would economics be more inclined towards linear models?</p><p>There are no valid reasons to justify this statement, unless we accept that at the time (in 2006… hmmm… hmmm…), these were the easiest and most understood methods. Then in about 2015 and the rise of scikit-learn, I discovered Random Forests which revolutionized my world. Until Neural Nets came about in a more systematic way for anything, time series prediction included.</p><p>From the beginning, I saw neural networks as wonderful calibration functions. Later on I learned the term<em> Universal Approximators</em> and the <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem">theorem</a> that goes with it. And although there capabilities are surprising me regularly even more, that is all they are to be: parametrized functions that fit anything. And if you keep that in mind, you may be able to leverage your understanding of underlying dynamics to profit from the improvements from the non linearities that Neural Networks can fit.</p><p>Using a data set from Binance API’s: the traded volumes on the platform for Bitcoin — BTCUSDT instrument for the afficionados, I will argue in favour of my statement.</p><p>First we’ll have a look on basic empirical features that traded volume show. Second, based on these features, we’ll train two pseudo-linear models (more on the use of <em>pseudo</em> below) and an LSTM network, showing that with a bit of insights, we can achieve decent perfomance models without training for hours.</p><p>And as in the previous post, we’ll also ask ourselves in the back of our mind, what should the physicist worry about when using Neural Networks to predict time series.</p><h3>The Data</h3><p>So, as introduced, we will get interested in traded volumes of Bitcoin on the <a href="https://www.binance.com/">Binance</a> platform. Binance is a crypto-exchange where users can trade their crypto-currencies on order book during what is called <em>a continuous auction</em>.</p><h4>Traded Volumes</h4><p>The traded volume is the amount of crypto-currencies, in our case Bitcoins which I will now refer to as BTC, that are exchanged during a certain period of time. It is an important metric for practitioners, and in particular for those who are mainly interested in liquidity, like brokers and Execution Services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UKghmqU-KOcNL-1YVA0bg.png" /></figure><p><strong>Average Daily Volumes —</strong> I did a couple of posts not so long ago about <a href="https://medium.com/@quantitative-modelling-for-fun/optimal-execution-yet-another-theory-d6b6b0f8fc68">Quantitative Models in Execution Services</a>, in which I mentioned the Square Root Law below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kzgmqwmKuawpdLBDJwcIw.png" /></figure><p>In this formula, there is the term ADV which stands for Average Daily Volume: it is the average traded Volume over a period of 1 day.</p><p>Taking the example of BTC, over a period stemming from 01/01/2018 to 31/10/2023, the ADV is 78 863 BTC per day.</p><p><strong>Data sampling — </strong>Being willing to leverage Neural Networks, it is necessary to have a lot of data. Since the <a href="https://www.binance.com/fr/binance-api">Binance API</a> offers to download traded volumes from 1 minute, meaning that we could have half a million points per year. From 01/01/2018 to 31/10/2023, it could mean about 3 million points. Since I am still working on a small machines, I prefer to reduce that size by using <em>30 minute samples</em>.</p><p>This means that we will have about 100 000 data points. It is a <strong>LOT</strong> less which means that we will have to build smaller models, but that was the idea in the first: keep it simple for learning sakes.</p><p><strong>Train set/Test set</strong> — The train set will be constituted of the data points spanning from 2018–01–01 to 2021–11–20 for 68 156 samples. While the test set will be made from the data points going from 2021–11–21 to 2023–10–31, accounting for 34 078 samples.</p><h3>Empirical Features of Traded Volumes</h3><p>The traded volumes show two main important features that we want to include in the statistical model we want to build.</p><p><strong>Traded Volumes are seasonal</strong> — They display intraday seasonality as well as week/month seasonality. For simplicity we will focus on the intraday seasonality which is the most influential on 30 minute sample data.</p><p><strong>The innovation on seasonality is autoregressive</strong>— When looking at the difference between the realized volumes and the corresponding average for that time period, the statistics that we obtain has an autoregressive property.</p><h4>Seasonality</h4><p>To empricially demonstrate the seasonality, we have to compute the average volumes for each binned in the period of seasonality. The profile is a function of the bin and can be mathematically expressed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuAh0gSJhdudATp3KHGDdw.png" /></figure><p>where, here, I use the Kronecker symbol to be one when <em>t</em> is in bin <em>b</em> and zero otherwise.</p><p>Provided that at least two values of the averages are statistically different, the profile above will be not constant. And to show that points are different, it is necessary to indicate the confidence intervals of each value. We will use the intervals below to plot the profile with error bars.</p><p>In the code you’ll see that I did not use pandas for that one. Instead I used a for loop which ends up having the merit of clearly showing how to compute the average.</p><pre>def plot_profile(year=&#39;&#39;, color=&#39;grey&#39;, labels=False, ylabel=False, title=False):<br>    total_volumes = []<br>    total_volumes_squared = []<br>    counter = []<br>    first_file = True<br>    for filename in os.listdir(RAW_PATH):<br>        if year and filename.split(&#39;_&#39;)[1][:4] != year: continue<br>        file_path = f&#39;{RAW_PATH}{filename}&#39;<br>        for n, line in enumerate(open(file_path)):<br>            line = line.strip()<br>            [_, volumes] = tuple(line.split(&#39;,&#39;))<br>            volumes = float(volumes)<br>            # Here I compute the sums for the average and the variance<br>            if first_file:<br>                total_volumes.append(volumes)<br>                total_volumes_squared.append(volumes**2)<br>                counter.append(1)<br>            else:<br>                total_volumes[n] += volumes<br>                total_volumes_squared[n] += volumes**2<br>                counter[n] += 1<br>        first_file = False<br>        total_volumes = np.array(total_volumes)<br>        total_volumes_squared = np.array(total_volumes_squared)<br>        counter = np.array(counter)<br>    # Here I divide by the number of points and compute the error of on the mean using<br>    # the average and the average of the square.<br>    profile = total_volumes/counter<br>    error = np.sqrt(total_volumes_squared/counter - (total_volumes/counter)**2)/np.sqrt(counter)<br>    t = np.arange(48)<br>    plt.errorbar(t, profile, yerr=error, fmt=&#39;o&#39;, capsize=5, color=color, markersize=4, label=year)<br>    if labels:<br>        plt.xlabel(r&#39;$\delta_b$&#39;)<br>        plt.xticks([0, 2 * 4, 2 * 8, 2 * 12, 2 * 16, 2 * 20, 2 * 24], [&#39;00:00&#39;, &#39;04:00&#39;, &#39;08:00&#39;, &#39;12:00&#39;, &#39;16:00&#39;, &#39;20:00&#39;, &#39;24:00&#39;])<br>    else:<br>        plt.xlabel(&#39;&#39;)<br>        plt.xticks([], [])<br>    if ylabel:<br>        plt.ylabel(r&#39;$\sum_b &lt;V_t&gt;_b\cdot \delta_b$&#39;)<br>    else:<br>        plt.ylabel(&#39;&#39;)<br>    if title:<br>        plt.title(&#39;Average daily profile in log scale&#39;)<br>    else:<br>        plt.title(&#39;&#39;)</pre><p>The output of this code is given on the figure below. The times are UTC times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gxd9FcGYUh2IxAFgMFiDjw.png" /></figure><p>There are three peaks, one being much higher than the others.</p><ul><li>Around 00:00 UTC, Asian markets open, starting with the Japanese one.</li><li>Around 08:00 UTC, most European markets open.</li><li>After 12:00, the US markets open, creating the highest peak in the profile.</li></ul><p>In any case, the errors bars do not all overlap and therefore there are statistically significant differences between the plotted values. Thus proving empirically the seasonality of the Traded Volumes in intraday.</p><h4>Auto-Regressive properties of the seasonality innovation</h4><p>Now that we have established the seasonality of the traded volumes, we will focus our attention on the linear innovation on the profile which is written mathematically as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_xEK8VgPMx9q6Pba8xICw.png" /></figure><p>This innovation represents, somehow the volatility and behaves a bit like it. Indeed, at a time <em>t</em> where trading activity is suddenly very high, the innovation is positive as volumes are higher than their expected value from the seasonality. That activity is not going to die off just like that at the end of the period. Instead, it is highly probable that for some time, the innovation will remain positive.</p><p>And the same applies for a sudden negative value.</p><p>Therefore to prove that the data displays this expected feature, we will estimate the following model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHt4O4V7okT4oxDCQvkESg.png" /></figure><p>If it is significant, it proves that, up to some order, the data behaves in an autoregressive fashion.</p><p>The output from statsmodel provides the summary below…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwGQ1DTkFAmFpgyk0G_bXw.png" /></figure><p>… which we can display with the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXZhNX6LqSolR7yJh1a0tw.png" /></figure><blockquote><strong>Non Gaussian statistics</strong> <strong>in Finance</strong>— Note that the output from the statistics are simply dirty: when using financial data, the assumption of gaussian distribution on the residuals is plain wrong — look at the JB statistics!</blockquote><blockquote>Therefore these numbers are to be read accordingly.</blockquote><p>I usually read the student t-test because its statistics is very simple: it measures the ratio between the estimated parameter and the estimated standard error of that parameter. It has thus some meaning that we can trust: the greater the noise, the lower we should trust the estimation and thus the lower the value of the t-test should be.</p><p>In this current case, the intercept is not statistically significant and we can remove it from the model, to only keep the slope.</p><p>Visual confirmation on the above plot — it is always good practice to see the results when possible! — shows that there is a correlation between previous and the current value of <em>I</em>. The shape of the scatter plot indicates also that there might be some other dependency between the current value and its past, that were not extracted in the regression. But, at this stage, we have what we needed: proof of a significant dependency.</p><p>Finally, on the plot above, notice the mention of a correlation term. It can be convenient to view the R² as the square of the correlation term between the estimator and the statistics we are trying to predict. It talks more to be referring to a correlation rather than the R².</p><h4>Hints on the dynamics</h4><p>Adding this two pieces together, we are invited to consider that the traded volumes dynamics follow a linearized law like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywNsefp32-_tx7-Jdz1-1A.png" /></figure><p>and of course, it will be the starting point of our modeling!</p><h3>Models</h3><p>Now that we have derived what seems to be a linear law for the traded volumes dynamics, let’s switch hat and get our data scientist gear.</p><p>To predict the traded volume at time <em>t</em> we will propose three models, each generalizing the last.</p><p><strong>(i)</strong> — We will start from the law derived in the previous paragraph, replacing all averages with optimizable parameters.</p><p><strong>(ii)</strong> — To complete the “…”, we will introduce more past values, going back until <em>P</em> values.</p><p><strong>(iii)</strong> — After increasing the lookback of the linear regression in (ii), the second thing to do will be to introduce non linearities using a Neural Network. In this post I decided to use LSTM units, even if other units seem to perform better now.</p><h4>AR(1) Pseudo-Linear Model</h4><p>As introduced just above, we will generalize the law for the trade volumes dynamics by parametrizing the terms in the sum for the profile. This gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY0S4Q-2aAAY7HzXZENyLw.png" /></figure><p>where we introduce the endogeneous latent variable <em>z</em> for the clarity of the equations.</p><p>Note that this model is linearized, but in the statistical sense, it is <strong>not a linear model</strong>. This is due to the multiplication of parameters <em>α </em>and <em>β₁.</em> This is why I coined it as <em>pseudo-linear</em>. The addition of the AR(1) term is a reference to the fact that <em>z</em> is taken at <em>t-1</em>.</p><p>To fit the model, we will use keras as the model can easily be written in this library. It goes as follow, below.</p><pre>def create_pseudo_linear_1(num_bins):<br>    # Inputs<br>    input_bins_current = layers.Input(shape=(num_bins,), name=&quot;Bins_Input_Current&quot;)  # Binary indicators for each bin at time t<br>    input_bins_prev = layers.Input(shape=(num_bins,), name=&quot;Bins_Input_Prev&quot;)  # Binary indicators for each bin at time t-1<br>    input_v_prev = layers.Input(shape=(1,), name=&quot;Previous_V&quot;)  # Previous value of V(t)<br>    # Shared layer for the same weights for delta_b(t) and delta_b(t-1)<br>    shared_dense = layers.Dense(1, activation=&#39;linear&#39;, use_bias=False, name=&quot;Shared_Weights&quot;)<br>    weighted_current = shared_dense(input_bins_current)<br>    weighted_prev = shared_dense(input_bins_prev)<br>    # Contribution of the previous delta to profile<br>    delta_layer = layers.Dense(1, activation=&#39;linear&#39;, use_bias=False, name=&quot;Delta_Layer&quot;)(input_v_prev - weighted_prev)<br>    # Sum up the components<br>    output_v = layers.Add(name=&quot;Output_V&quot;)([weighted_current, delta_layer])<br>    model = models.Model(inputs=[input_bins_current, input_bins_prev, input_v_prev], outputs=output_v)<br>    model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;, metrics=[r_squared])<br>    return model</pre><p>Note the used of the shared_dense layer for both <em>z</em> and first sum for the first occurence of the profile. This layer contains the <em>α</em>’s and ensures that they are the same in both profiles.</p><p>The result of the prediction on test set, we come to this cloud of points in log-scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1-HIOYtMU3lv9FhgREqeA.png" /></figure><h4>AR(P) Pseudo-Linear Model</h4><p>The next step would be to increase the lookback for the lag, meaning that if we introduce the integer <em>P</em>, we aim to fit the following model on the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opmd-PbGw5_TE_KHS9onfg.png" /></figure><p>Nothing very fancy here, we a have baseline with the previous model, so we naively increase the lookback from 1 to some value <em>P</em>.</p><p>The model has to be adapted and include entries for the lags <em>1</em> to <em>P</em>.</p><pre>def create_pseudo_linear_P(num_bins, P=P):<br>    # Inputs<br>    input_bins_current = layers.Input(shape=(num_bins,), name=&quot;Bins_Input_Current&quot;)  # Binary indicators for each bin at time t<br>    input_bins_prev = { p: layers.Input(shape=(num_bins,), name=f&#39;Bins_Input_Prev_{p}&#39;) for p in range(1, P + 1) }  # Binary indicators for each bin at time t-1<br>    input_v_prev = { p: layers.Input(shape=(1,), name=f&#39;Previous_V_{p}&#39;) for p in range(1, P + 1) }  # Previous value of V(t)<br>    # Shared layer for the same weights for I_b(t) and I_b(t-1)<br>    shared_dense = layers.Dense(1, activation=&#39;linear&#39;, use_bias=False, name=&quot;Shared_Weights&quot;)<br>    weighted_current = shared_dense(input_bins_current)<br>    # Weighted previous value of V(t)<br>    delta_outputs = []<br>    # Loop to create layers and collect their outputs<br>    for p in range(1, P + 1):<br>        # The output of each layer is subtracted by another layer&#39;s output<br>        difference = layers.Subtract()([input_v_prev[p], shared_dense(input_bins_prev[p])])<br>        # A dense layer is applied to the difference<br>        delta = layers.Dense(1, activation=&#39;linear&#39;, use_bias=False, name=f&#39;Delta_Layer_{p}&#39;)(difference)<br>        # Collect the output<br>        delta_outputs.append(delta)<br>    # If you want to sum the outputs of the created Dense layers<br>    delta_layer = layers.Add()(delta_outputs) if len(delta_outputs) &gt; 1 else delta_outputs[0]<br>    # Sum up the components<br>    output_v = layers.Add(name=&quot;Output_V&quot;)([weighted_current, delta_layer])<br>    inputs = [ input_bins_current ]<br>    inputs += [ input_bins_prev[p] for p in range(1, P + 1) ]<br>    inputs += [ input_v_prev[p] for p in range(1, P + 1) ]<br>    model = models.Model(inputs=inputs, outputs=output_v)<br>    model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;, metrics=[r_squared])<br>    return model</pre><p>Choosing <em>P = 5, </em>the results are as follow.</p><blockquote>It may seem random to have the value of 5, but I did some tests first. And if I want to keep it simple, <em>P = 5</em> is a reasonable choice.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-67NL7h_-2T7aZUAPYhxeQ.png" /></figure><p>There is an increase in the test score, however that increase is not that important. The figure above shows the results of this second model (orange) on top of the results of the baseline (in grey). The cloud of points has more or less the same shape and performs hardly better when it does not perform worse like in the case of these two single points with predictions around 1 for realized volumes of about 4000.</p><p>Therefore if choosing between the first model and the second, choosing simplicity is probably best.</p><h4>Seasonal LSTM</h4><p>Another extension to the initial model is to use a non linear fitting functions for the seasonality innovation. I chose to use LSTM units because every AI engineer out there knows them by now.</p><blockquote>I want to show the usefulness of the non linear calibration, not argue who is the best and latest non linear fitting approximator. :)</blockquote><p>So the mathematical model I want to fit is as such</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gb8793dDzjgTZks7OV0vhA.png" /></figure><p>and the LSTM<em>(…)</em> function is a stack of 100 and 50 units with a relu activation — I really want that non-linear fit!</p><p>The new model is defined below with some new adjustements on the previous model.</p><pre>def create_LSTM(num_bins, P=P):<br>    # Inputs<br>    input_bins_current = layers.Input(shape=(num_bins,), name=&quot;Bins_Input_Current&quot;)  # Binary indicators for each bin at time t<br>    input_bins_prev = { p: layers.Input(shape=(num_bins,), name=f&#39;Bins_Input_Prev_{p}&#39;) for p in range(1, P + 1) }  # Binary indicators for each bin at time t-1<br>    input_v_prev = { p: layers.Input(shape=(1,), name=f&#39;Previous_V_{p}&#39;) for p in range(1, P + 1) }  # Previous value of V(t)<br>    # Shared layer for the same weights for I_b(t) and I_b(t-1)<br>    shared_dense = layers.Dense(1, activation=&#39;linear&#39;, use_bias=False, name=&quot;Shared_Weights&quot;)<br>    weighted_current = shared_dense(input_bins_current)<br>    # Weighted previous value of V(t)<br>    delta_outputs = []<br>    # Loop to create layers and collect their outputs<br>    for p in reversed(range(1, P + 1)):<br>        # The output of each layer is subtracted by another layer&#39;s output<br>        delta = layers.Subtract()([input_v_prev[p], shared_dense(input_bins_prev[p])])<br>        # Collect the output<br>        delta_outputs.append(delta)<br>    delta_outputs = backend.stack(delta_outputs, axis=1)<br>    # If you want to sum the outputs of the created Dense layers<br>    # x = layers.LSTM(15, return_sequences=False)(delta_outputs)<br>    x = layers.LSTM(100, activation=&#39;relu&#39;, return_sequences=True)(delta_outputs)<br>    x = layers.Dropout(.1)(x)<br>    x = layers.LSTM(50, activation=&#39;relu&#39;, return_sequences=False)(x)<br>    x = layers.Dropout(.1)(x)<br>    x = layers.Dense(1, activation=&#39;linear&#39;)(x)<br>    # Sum up the components<br>    output_v = layers.Add(name=&quot;Output_V&quot;)([weighted_current, x])<br>    inputs = [ input_bins_current ]<br>    inputs += [ input_bins_prev[p] for p in range(1, P + 1) ]<br>    inputs += [ input_v_prev[p] for p in range(1, P + 1) ]<br>    model = models.Model(inputs=inputs, outputs=output_v)<br>    model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;, metrics=[r_squared])<br>    return model</pre><p>I keep a lookback of <em>P = 5</em>to be able to compare directly with the previous model and the baseline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3unAlyOPmjxbZNAezQaURg.png" /></figure><p>The outcome is a lot more promising. As one can see above, the new cloud of points (in pink) is a bit thinner than the baseline cloud (in grey) and it even predicts a lot better the outlier that stands in the vicinity of (4000, 1).</p><p>The final correlation is 84.24% so about 1.5% more than in previous examples. This not a tremendous amount however, for brokers that deal with high volumes of transactions, this could be quite a substantial operational gain over the course of several months!</p><h3>Wrapping up</h3><p>I have been lucky to work on an extensive amount of diverse time series: capital markets data, CAC40 companies’ revenues, industrial production, radio listenership or even website activity.</p><p>The one thing that these studies had in common is that no matter the approximators I was using (linear, random forest, neural network), the project always took off much faster when I did some thinking on the underlying dynamics, because I had a baseline.</p><p>Coming back to our current project, using well known (for execution services practionners) experimental features of the traded volumes, we can achieve very decent results leveraging the non linear capacities of neural networks. let’s not forget that I did all of this on a MacBook Air in reasonnably decent amount of time.</p><p>Further steps could be to include exogeneous variables to bring in more information. At this stage, as I often work in a setup where I am the first to build a model, I would consider that the endogeneous information has been sufficiently squeezed out to move on to other things.</p><blockquote>And of course, anyone who has access to much greater firing power should make the best of it and start many trainings of much larger models on much higher frequency data, <strong>with or without </strong>the insights here.</blockquote><blockquote>If you do and want to share your results, let me know in the comments!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e868f7462d74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist’s view on AI (I) — the case of Anomaly Detection in Computer Vision]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/a-physicists-view-on-ai-i-the-case-of-anomaly-detection-in-computer-vision-cffc3a8e5238?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/cffc3a8e5238</guid>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 05:17:28 GMT</pubDate>
            <atom:updated>2023-11-11T09:50:02.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist’s view on AI (I) — the case of Anomaly Detection in Computer Vision</h3><p><em>Github repo of this work: </em><a href="https://github.com/Gilt0/ijoutaku.git">https://github.com/Gilt0/ijoutaku.git</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ57dAcdLz6tIs8JpmJMew.png" /><figcaption>Illustrative image generated by dall.e</figcaption></figure><p>My deep belief is that physics teaches us to have a combined view of maths and the phenomenon to be modeled. The phenomenon is the maths, the maths are the phenomenon. Both get entangled in a physicist’s mind to become a unified entity bringing new ideas and understandings.</p><p>In Natural Sciences, physicists are historically interested in fluxes of matter, momentum, energy and entropy. In Finance, physicists are mainly focused on cash flows and their uncertainties. In Artificial Intelligence, what should physicists be mainly concerned about?</p><p>In these series of articles, I will try and share with you what I believe to be what should be the focus of a physicist willing to use AI technologies.</p><p>In this first article, I am focusing on anomaly detection: part because I had to get interested in it for my professional projects, part because I simply really enjoyed working on it. I am using the very well known UCSD 1 Anomaly Detection Dataset. <a href="https://www.kaggle.com/datasets/karthiknm1/ucsd-anomaly-detection-dataset">Here</a> is a data source on Kaggle.</p><h3>LSTM Convolutional Autoencoders — benchmark</h3><p>After I asked ChatGPT for the state-of-the-art technologies for Anomaly Detection, I found out that LSTM Convolutional Autoencoders are one the hot technologies to detect anomalies on videos. So I searched on Google and I ended up on that <a href="https://towardsdatascience.com/prototyping-an-anomaly-detection-system-for-videos-step-by-step-using-lstm-convolutional-4e06b7dcdd29">gentleman’s post</a>, who goes by the name of <a href="https://medium.com/@hashemsellat">Hashem Sellat</a>, on Towards Data Science. A great post that munched really well the fundamentals of what I should know before I get started.</p><p>Autoencoders are trained to reconstruct information and used in anomaly detection to predict what should be. In our case, it is made of two types of neuronal layers.</p><ul><li>Convolutional layers: to build the visual features.</li><li>LSTM: to capture the temporal features.</li></ul><h3>Benchmarking with Hashem’s model</h3><p>To get my hands dirty, I started by using Hashem’s model, to get a taste for its performance. I had memory issues so I had to write a data generator, as suggested by Hasem himself.</p><h4>Data Generator</h4><p>I did not want to copy paste his work entirely, for learning purposes, so I wrote my own stuff to load the data: the data policy might be a little different.</p><pre>class SequenceDataGenerator(keras.utils.Sequence):<br>    <br>    _IMAGE_WIDTH = 128<br>    _IMAGE_HEIGHT = 88<br>    _TIF_EXTENSION = &#39;.tif&#39;<br>    _STRIDE_KERNEL = 5<br>    _BATCH_SIZE = 3<br>    _SEQUENCE_SIZE = 200<br><br>    def __init__(self, data_path):<br>        self._data_path = data_path<br>        self._sequences = list()<br>        self._batches = list()<br>        self._len = 0<br>        self.__load__()<br><br>    def __make_batches__(self, ):<br>        strided = list()<br>        for sequence in self._sequences:<br>            if not os.path.isdir(sequence): continue<br>            image_files = [ f&#39;{sequence}{image_file}&#39; for image_file in sorted(os.listdir(sequence)) ]<br>            if not image_files: continue<br>            for stride in range(self._STRIDE_KERNEL):<br>                strided.append(image_files[stride::self._STRIDE_KERNEL])<br><br>        self._batches = [ strided[b:b+self._BATCH_SIZE] for b in range(0, len(strided), self._BATCH_SIZE) ]<br>        self._len = len(self._batches)<br><br>    def __load__(self, ):<br>        self._sequences = sorted([ f&#39;{self._data_path}{data_folder}/&#39; for data_folder in os.listdir(self._data_path) ])<br>        self.__make_batches__()<br><br>    def __len__(self, ):<br>        return self._len<br><br>    def __getitem__(self, index):<br>        X = np.zeros((self._BATCH_SIZE, int(self._SEQUENCE_SIZE/self._STRIDE_KERNEL), self._IMAGE_HEIGHT, self._IMAGE_WIDTH, 1), dtype=np.float16)<br>        batch = self._batches[index]<br>        for b, image_paths in enumerate(batch):<br>            for t, image_path in enumerate(image_paths):<br>                image = np.array(pil.Image.open(image_path).resize((self._IMAGE_WIDTH, self._IMAGE_HEIGHT)), dtype=np.float16)/256<br>                X[b, t, :, :, 0] = image<br>        return X, X<br><br>    def on_epoch_end(self, ):<br>        random.shuffle(self._sequences)<br>        self.__make_batches__()</pre><p>In a nutshell, I strided the sequences by five, meaning that for a sequence like</p><pre>s = [img_1, img_2, img_3, img_4, img_5, img_6, img_7, img_8, img_9, ...]</pre><p>I produce five sequences like</p><pre>s_1 = [img_1, img_6, img_11, img_16, img_21, img_26, img_31, img_36, ...]<br>s_2 = [img_2, img_7, img_12, img_17, img_22, img_27, img_32, img_37, ...]<br>s_3 = [img_3, img_8, img_13, img_18, img_23, img_28, img_33, img_38, ...]<br>s_4 = [img_4, img_9, img_14, img_19, img_24, img_29, img_34, img_39, ...]<br>s_5 = [img_5, img_10, img_15, img_20, img_25, img_30, img_35, img_40, ...]</pre><p>By doing so, I decreased the amount of memory necessary when loading a batch of sequences, while preserving the amount of training information. With regards to the images themselves, I resized them with fewer pixel than in Hashem’s work.</p><h4>Training the model</h4><p>I almost copy-pasted Hashem’s model. It is, after all, the benchmark I wanted to use, but I had to change the model size, my available memory being limited... Please also note that I had to use legacy optimizers as I am currently using a mac with an M chip. I trained over 10 epochs to ensure that I was squeezing out the most information, my model being somewhat smaller.</p><pre>EPOCHS = 10<br><br>CONV_FILTERS = 32<br>CONV_KERNEL = 4, 4<br>LSTM_FILTERS = 16<br>LSTM_KERNEL = 3, 3<br><br>PADDING = &#39;same&#39;<br>SIGMOID = &#39;sigmoid&#39;<br>RELU = &#39;relu&#39;<br>STRIDES = 2<br>LOSS = &#39;mse&#39;<br><br>LEARNING_RATE = 1e-4<br>EPSILON = 1e-6<br><br>model = keras.models.Sequential()<br>model.add(keras.layers.TimeDistributed(keras.layers.Conv2D(CONV_FILTERS, CONV_KERNEL, activation=RELU, strides=STRIDES, padding=PADDING), batch_input_shape=(SequenceDataGenerator._BATCH_SIZE, int(SequenceDataGenerator._SEQUENCE_SIZE/SequenceDataGenerator._STRIDE_KERNEL), SequenceDataGenerator._IMAGE_HEIGHT, SequenceDataGenerator._IMAGE_WIDTH, 1)))<br>model.add(keras.layers.LayerNormalization())<br># # # # #<br>model.add(keras.layers.ConvLSTM2D(LSTM_FILTERS, LSTM_KERNEL, padding=PADDING, return_sequences=True))<br>model.add(keras.layers.LayerNormalization())<br># # # # #<br>model.add(keras.layers.TimeDistributed(keras.layers.Conv2DTranspose(CONV_FILTERS, CONV_KERNEL, activation=RELU, strides=STRIDES, padding=PADDING)))<br>model.add(keras.layers.LayerNormalization())<br>model.add(keras.layers.TimeDistributed(keras.layers.Conv2D(1, CONV_KERNEL, activation=SIGMOID, padding=PADDING)))<br>print(model.summary())<br>model.compile(loss=LOSS, optimizer=keras.optimizers.legacy.Adam(learning_rate=LEARNING_RATE, epsilon=EPSILON))</pre><p>Training the model was reasonably fast, considering that I did not train on GPU’s. It took ~100 minutes for an average <em>MSE</em> ~0.002.<br>For those who did not read <a href="https://towardsdatascience.com/prototyping-an-anomaly-detection-system-for-videos-step-by-step-using-lstm-convolutional-4e06b7dcdd29">Hashem’s post</a> yet, the training is performed on sequences of people walking up and down an alley in the University of California San Diego. Vehicles driving up or down, skateboards and other bicycles or by-standers walking in odd fashion have been removed. The normal behaviour the autoencoder learns is that people ought to be walking and nothing else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*CtO7p-DKJlR0hCBA6308yQ.png" /></figure><p>Now we can move on to the testing and the goal is to detect any behavioural anomalies: vehicles, skateboards, bicycles, passerby walking in unexpected ways…</p><h4><strong>Testing on sequence 24.</strong></h4><p>In that sequence, there is a single notable anomaly: a cart drives down the alley. So as the cart takes more and more surface on the camera, we expect the reconstruction error to become huge: it’s a cart and it rolling down fast!</p><p>So let’s see what we get…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*C8O_Un7rBG8JYrAFEnHFrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*Rel1AL5esbrZPZpWCza1FQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*R3Mjhay5t2nJzxQ_s406oA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*f7Eyu2pUj-S4wSJ6fd9lCA.png" /><figcaption>In sequence 24, a cart goes through the image from to right to bottom left.</figcaption></figure><ul><li>First, let’s have a look at the MSE across the sequence. Which at a first glance seems to have the right aspect. At the begining, the MSE is higher: this is because of the LSTM layers not having completely had the time to process all the information the sequence, which is why I should have used a burn in period, like in Hashem’s post.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*wZEBH-jiEWSKiNkYmGkTqw.png" /><figcaption>The result is similar to Hashem’s — he used a transformation on MSE that inverts the shape</figcaption></figure><ul><li>Second, let’s have a closer look at an image in the sequence. The one I chose is in the ~150th. It looks like the algorithm does not reconstruct well the cart as shown in the error image right at the bottom. The rest of the picture is comparatively well reconstructed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*46nLqaZmVGxQ2clnRRuR5Q.png" /><figcaption>At the bottom, the error image plot shows that the cart reconstruction did not go well.</figcaption></figure><h4>Testing on<strong> sequence 32.</strong></h4><p>Now another sequence where two cyclists go down the alley and a passerby walks in a diagonal fashion towards the end. Just like before, let’s have a look at the MSE across the sequence and analyse closer an image in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*ylsKkV_3EzHlJKpl6kNRwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*DcX-PmtZyruj228iFDKYVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*i6jEACPZOGCvMSefME01Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*KdzLIGsXcmx1c3pabWv9Yw.png" /><figcaption>In sequence 32, two bikes pass by at high speed and at the end a passerby walks diagonally at a good pace.</figcaption></figure><ul><li>The MSE of the sequence clearly shows two bumps relative to the first and second bicycle, and the bystander. However, the cool off period, or burn-in if I had removed it, at the begining tends to overshadow the reconstruction error. To the naked eye of a statical physicist, this could very well be noise… But let’s not be too picky, and below, by circling the appropriate areas, it tends to look like the algorithm detects something.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*i-XjshoEhrrNsttOMSTFzw.png" /></figure><ul><li>When having a closer look, for example, around the ~100th frame, the error seems to arise from the reconstructed bicycle. Once more, the vehicle is not well reconstruted. However, the surface the bicycle occupies on the image is too small to have enough impact on the MSE. That is why it is overshadowed by the cool off period.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*lGB5rz_P28f-GQ0WqGtuAg.png" /><figcaption>The second cyclist’s bike seems to not be well reconstructed.</figcaption></figure><h4>Remarks on this benchmark.</h4><p>As shown here, the autoencoder has successes in detecting abnormal events in the flow of people and objects on the alley. However, the autoencoder is trained on the overall sequence. By doing so, we could expect that velocity effects on anomaly detection to be decreased. Indeed, future frames increase the accuracy of the predicted position. And this is probably why anomalies end up being detected from the shape of objects or trajectories and not from speed.</p><p>If I want to focus on detecting fast moving objects, I need to change the prediction paradigm.</p><h3>Forward prediction using a lookback</h3><p>I spent many years predicting time series of financial data, industrial production data, sales result data, etc. And usually, there is one thing that I have done over and over again: predicting the next value using as much information as possible from the past. So, naturally, I thought</p><blockquote>If I train a model that predicts the next frame using a short lookback on slow walking people, when I test it on frames with fast moving vehicles, I should have greater errors, right?</blockquote><p>Of course, it was a hunch and there were great chances that I could be wrong in thinking that the anomaly detection would be more obvious than in the previous model. Only way to prove me right or wrong was to do it… So that’s what I did.</p><p>Let’s see what I got…</p><h4><em>Forward</em> autoencoder</h4><p>I am not sure how to qualify a model that would tweak an autoencoder to reconstruct a future frame. I am pretty sure it exists in the academic literature, but instead of biasing my idea with existing work, I want to remain naive. So I’ll simply add the term <em>forward</em> to indicate that we are reconstructing a frame in the future.</p><h4>Data generator</h4><p>The data generator has to be completely modified. Earlier, the generator was returning a two dimensional tuple with the input batch of images in both elements of the tuple. Now, we have to return a tuple with the input batch and the batch of next frame.</p><pre>class ForwardDataGenerator(keras.utils.Sequence):<br>    <br>    _IMAGE_WIDTH = 128<br>    _IMAGE_HEIGHT = 88<br>    _TIF_EXTENSION = &#39;.tif&#39;<br>    _LOOKBACK = 5<br>    _BATCH_SIZE = 3<br>    _SEQUENCE_SIZE = 200<br><br>    def __init__(self, data_path, shuffle_at_start=False):<br>        self._data_path = data_path<br>        self._shuffle_at_start = shuffle_at_start<br>        self._sequences = list()<br>        self._batches = list()<br>        self._len = 0<br>        self.__load__()<br><br>    def __make_batches__(self, ):<br>        self._batches = [ self._sequences[i:i+self._BATCH_SIZE] for i in range(0, len(self._sequences), self._BATCH_SIZE) ]<br>        self._len = len(self._batches)<br><br>    def __load__(self, ):<br>        tmp_sequences = sorted([ f&#39;{self._data_path}{data_folder}/&#39; for data_folder in os.listdir(self._data_path) ])<br>        for sequence in tmp_sequences:<br>            if not os.path.isdir(sequence): continue<br>            image_files = sorted([ f&#39;{sequence}{image_file}&#39; for image_file in os.listdir(sequence) if image_file.find(&#39;.tif&#39;) &gt; -1 ])<br>            if not image_files: continue<br>            for n in range(len(image_files) - self._LOOKBACK):<br>                predictors = image_files[n:n+self._LOOKBACK]<br>                predicted = image_files[n+self._LOOKBACK]<br>                self._sequences.append((predictors, predicted))<br>        if self._shuffle_at_start: random.shuffle(self._sequences)<br>        self.__make_batches__()<br><br>    def __len__(self, ):<br>        return self._len<br><br>    def __getitem__(self, index):<br>        X = np.zeros((self._BATCH_SIZE, self._LOOKBACK, self._IMAGE_HEIGHT, self._IMAGE_WIDTH, 1), dtype=np.float16)<br>        y = np.zeros((self._BATCH_SIZE, self._IMAGE_HEIGHT, self._IMAGE_WIDTH, 1), dtype=np.float16)<br>        batch = self._batches[index]<br>        for b, (predictors, predicted) in enumerate(batch):<br>            for l, predictor in enumerate(predictors):<br>                X[b, l, :, :, 0] = np.array(pil.Image.open(predictor).resize((self._IMAGE_WIDTH, self._IMAGE_HEIGHT)), dtype=np.float16)/256<br>            y[b, :, :, 0] = np.array(pil.Image.open(predicted).resize((self._IMAGE_WIDTH, self._IMAGE_HEIGHT)), dtype=np.float16)/256<br>        return X, y<br><br>    def on_epoch_end(self, ):<br>        random.shuffle(self._sequences)<br>        self.__make_batches__()</pre><h4>ChatGPT’s model suggestion</h4><p>Next, I had to write a model that complies with my intuition. And as always (at least since gpt 4), I submit my desires to ChatGPT, because I know I’ll get something in line with his training data set which is rich, huge and quite often rather accurate.</p><p>ChatGPT suggests that I pile up ConvLSTM2D layers. First three layers act as an encoder, the last three layers act as a decoder.</p><pre>EPOCHS = 10<br><br>LSTM_FILTERS_1 = 16<br>LSTM_FILTERS_2 = 8<br>LSTM_FILTERS_3 = 4<br>LSTM_KERNEL = 3, 3<br><br>PADDING = &#39;same&#39;<br>SIGMOID = &#39;sigmoid&#39;<br>RELU = &#39;relu&#39;<br>STRIDES = 2<br>LOSS = &#39;mse&#39;<br><br>LEARNING_RATE = 1e-4<br>EPSILON = 1e-6<br><br>model = keras.models.Sequential()<br># Input layer<br>model.add(keras.layers.Input(batch_shape=(ForwardDataGenerator._BATCH_SIZE, ForwardDataGenerator._LOOKBACK, ForwardDataGenerator._IMAGE_HEIGHT, ForwardDataGenerator._IMAGE_WIDTH, 1)))<br># Encoder<br>model.add(keras.layers.ConvLSTM2D(filters=LSTM_FILTERS_1, kernel_size=LSTM_KERNEL, padding=PADDING, return_sequences=True, activation=RELU))<br>model.add(keras.layers.ConvLSTM2D(filters=LSTM_FILTERS_2, kernel_size=LSTM_KERNEL, padding=PADDING, return_sequences=True, activation=RELU))<br>model.add(keras.layers.ConvLSTM2D(filters=LSTM_FILTERS_3, kernel_size=LSTM_KERNEL, padding=PADDING, return_sequences=False, activation=RELU))<br># Decoder<br>model.add(keras.layers.Reshape((1, ForwardDataGenerator._IMAGE_HEIGHT, ForwardDataGenerator._IMAGE_WIDTH, LSTM_FILTERS_3)))<br>model.add(keras.layers.ConvLSTM2D(filters=LSTM_FILTERS_2, kernel_size=LSTM_KERNEL, padding=PADDING, return_sequences=True, activation=RELU))<br>model.add(keras.layers.ConvLSTM2D(filters=LSTM_FILTERS_1, kernel_size=LSTM_KERNEL, padding=PADDING, return_sequences=False, activation=RELU))<br>model.add(keras.layers.Conv2DTranspose(filters=1, kernel_size=LSTM_KERNEL, padding=PADDING, activation=SIGMOID))<br>print(model.summary())<br>model.compile(loss=LOSS, optimizer=keras.optimizers.legacy.Adam(learning_rate=LEARNING_RATE, epsilon=EPSILON))</pre><p>Training the model was, contrary to the first one, <strong>really really slow</strong>. It took ~7 hours for an average <em>MSE</em> ~0.0005. Because the train set was much bigger, but also because I stacked many LSTM-like networks. And they are famously slow to train! And in 2D I might add…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*FIR-ZQ3DDdZdEBzEgE2rPg.png" /></figure><p>Nonetheless, the MSE was reduced by a significant factor and it looked like information was squeezed out. So I was hopeful to get something out of it.</p><p>Let’s have a look at the test sequences. I kept the sequences 24 and 32 to compare with the performance of Hashem’s model.</p><h4>Test sequence 24 &amp; 32.</h4><p>On the test sequences, the results are actually very encouraging, with some unexpected limitations due to an optical effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*HlvJY0MfylLLWa9z4mEuyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*rfugYBT9-dRXnnqLHZHqlg.png" /><figcaption>Sequence 24 on the left, sequence 32 on the right, the detection is more accurate close to the camera with clear spikes indicating an anomaly.</figcaption></figure><ul><li>On Sequence 24, there is a clear spike indicating the cart driving down the alley. The ramp up is, a little slower than the ramp down, but detection is unquestionable close to the camera. I believe that is because of a parallax effect: the closer to the camera, the greater solid angle on the picture and the more velocity effect appear.</li><li>On Sequence 32, both cyclists are detected by the algorithm with a good precision. Towards the end, a passerby walks in a diagonal trajectory and a little faster, increasing locally the <em>MSE</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*AP33CxWIZ6Gz0yrPsthBEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*nR4pXt6wQB1_nD5h1DWQMQ.png" /></figure><h4>Remarks on this model</h4><p>This model provides a lot more details and detects fast moving objects on the frames, whether it be a cart, a bicycle or a fast walker. However, it took too long to train… Wayyyyyyyy too long.</p><p>This is mainly due to the LSTM units that increase significantly training time.</p><p>So let’s try to improve that!</p><h4>Tweaking Hashem’s model</h4><p>My next thought was to trust Hashem’s model further and simply adapt it so that I could train a forward autoencoder, because it only has one . The only line to change is the one of ConvLSTM2D where the parameter</p><pre>return_sequences=False</pre><p>has to be set to false instead of true. This parameter decides whether the output of the layer is as long as the input or if only one dimension is returned.</p><p>The model is as follows.</p><pre>EPOCHS = 10<br><br>CONV_FILTERS = 32<br>CONV_KERNEL = 4, 4<br>LSTM_FILTERS = 16<br>LSTM_KERNEL = 3, 3<br><br>PADDING = &#39;same&#39;<br>SIGMOID = &#39;sigmoid&#39;<br>RELU = &#39;relu&#39;<br>STRIDES = 2<br>LOSS = &#39;mse&#39;<br><br>LEARNING_RATE = 1e-4<br>EPSILON = 1e-6<br><br>model = keras.models.Sequential()<br># Input layer<br>model.add(keras.layers.InputLayer(input_shape=(ForwardDataGenerator._LOOKBACK, ForwardDataGenerator._IMAGE_HEIGHT, ForwardDataGenerator._IMAGE_WIDTH, 1)))<br># TimeDistributed Conv2D layer<br>model.add(keras.layers.TimeDistributed(keras.layers.Conv2D(CONV_FILTERS, CONV_KERNEL, activation=RELU, strides=STRIDES, padding=PADDING)))<br>model.add(keras.layers.LayerNormalization())<br># ConvLSTM2D layer<br>model.add(keras.layers.ConvLSTM2D(LSTM_FILTERS, LSTM_KERNEL, padding=PADDING, return_sequences=False))  # return_sequences=False because we want only the last frame representation<br>model.add(keras.layers.LayerNormalization())<br># Conv2DTranspose layers and output layer<br>model.add(keras.layers.Conv2DTranspose(CONV_FILTERS, CONV_KERNEL, activation=RELU, strides=STRIDES, padding=PADDING))<br>model.add(keras.layers.LayerNormalization())<br>model.add(keras.layers.Conv2D(1, CONV_KERNEL, activation=SIGMOID, padding=PADDING))<br># Model compilation and training<br>print(model.summary())<br>model.compile(loss=LOSS, optimizer=keras.optimizers.legacy.Adam(learning_rate=LEARNING_RATE, epsilon=EPSILON))</pre><p>Training the model was more reasonable. It took ~200 minutes for an average <em>MSE</em> ~0.0005. There is a lot more training data than in the initial Hashem’s model, so it is not surprising that it still took a little longer to train than its initial definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*XpzzEs4hcyaEGzlJYY3-JA.png" /></figure><p>Training reached a slightly better value but nothing that could be statistically really significant, the order of magnitude is the same. Before finishing up by looking at</p><h4>Test sequence 24 &amp; 32.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*LeL6fNmUcpeJVc1VVf_stg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*33Yy7Q1G-KzP1ZYfp0yQ-Q.png" /><figcaption>Sequence 24 on the left, sequence 32 on the right, the detection is as accurate as in the previous model suggested by ChatGPT.</figcaption></figure><p>The test data shows <em>MSE</em> curves are very similar to the ones obtained with stacked ConvLSTM2D layers, for a training time twice smaller! So about same performance for far less training time, I would say that the objective of improving the model is there. :)</p><h4>Visualizing — Are we really detecting faster moving objects?</h4><p>It seems that forward models tend to perform better. So that is encouraging. However, are there performing better because they detect faster moving objects? Or is it something different?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*p-EaA6L3FX8akE7mYWaHPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*hy7-7ByrAMxYrLuVHH2iKw.png" /><figcaption>Sequence 24 on the left, sequence 32 on the right, the error figures show indeed that faster moving object are predicted to move slower by forward autoencoders.</figcaption></figure><p>Pictures are worth a thousand words as we say in French. So all is said, just by looking at the images above. We should also note that in the case of the cyclist, there is a <em>phantom</em> rider behind the reconstructed rider for which I cannot, at the moment, provide an explanation.</p><h3>What should physicists be mainly concerned about?</h3><p>The final result is promising as forward autoencoders are able to detect better fast moving objects close to the camera. However, as already mentioned, further from the camera, the performance diminishes, because of optic physics.</p><ul><li>An experimentalist would increase the model size. By stacking up more layers and possibly using GPU’s, in the hope that more trainable parameters would increase detection capacities at smaller solid angles, further away from the camera. Another complementary strategy would be to increase acquisition with finer images at higher sampling rates.</li><li>A theoretician would probably try to preprocess data with the proper transformation to diminish optical effects due to distance and angles — called parallax. The further from the camera, the less perceived distance is covered by a moving object between frames. With the appropriate geometrical transformation, visible distance at lower angles could be magnified.</li></ul><p>So as always, most probably, a bit of both would probably provide the best results for the least efforts.</p><h3>Wrapping Up</h3><p>First of all, I should emphasize again, that I was very constrained by memory. Training on a Mac with an M chip is definitely achievable, but the size of the model as to be kept as low as possible.</p><p>Hashem’s model was a great starting point and it gave me, without looking further into Anomaly Detection academic sources, all the necessary elements for me to try new approaches.</p><p>Coming from a physics background, I immediately thought about the motion aspects of the detection. After stumbling a little, I realized that fast movings objects would be probably not as well reconstructed by an algorithm trained on slow moving object data, if I added some autoregressive design into the LSTM Convolutional Autoencoder. It proved to be fruitful.</p><p>And no… I don’t think to have revolutionized anything here, I am pretty sure that these algorithms already exist. If you guys have proper academic sources on these algorithms, please share it in comments.</p><p>Finally, I believe that a physicist, when engaging in Vision AI task, should keep in mind two aspects:</p><p>(i) — As shown here, and in many other publications, Deep Learning is extremely powerful and useful. <a href="https://pubs.aip.org/aapt/ajp/article-abstract/78/6/648/1042069/Drawing-an-elephant-with-four-complex-parameters?redirectedFrom=fulltext">They fit any elephant</a> with a, sometimes, almost unbelievable accuracy. At least to me… And in most applications, having enough data and a big enough model, provides already fantastic results.</p><p>(ii) — Keeping a focus on building a big enough model might add up unnecessary costs and it could be useful to have theoretical optical considerations to improve the design of Vision Neural Nets. For example, one thing I might explore in a next publication is to preprocess images to smooth out parallax effects.</p><p>What’s your take on all of this?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffc3a8e5238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on Finance (VI) — Optimal Execution, now time to experiment!]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/optimal-execution-ii-get-your-hands-dirty-46007980bc4d?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/46007980bc4d</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[optimal-execution]]></category>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 05:50:39 GMT</pubDate>
            <atom:updated>2023-11-04T12:12:04.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on Finance (VI) — Optimal Execution, now time to experiment!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*DuozygwqAWQ89ifPE4ABvw.png" /></figure><p><em>Disclaimer: This is not investment advice, this is merely for educational purposes and definitely an expression of personal thoughts. Investing is </em><strong><em>always</em></strong><em> a risky endeavour.</em></p><blockquote><strong>Advice: Use chatgpt! I did… :)</strong></blockquote><p>In a <a href="https://medium.com/@quantitative-modelling-for-fun/optimal-execution-yet-another-theory-d6b6b0f8fc68">previous article</a>, I presented some thoughts on execution. I gave some thoughts on whether I should be giving it a more hands-on follow-up and came up with that idea: how about, you do it?</p><p>Here is the plan, I start with what could be the most difficult task for someeone who is not familiar with the matter: gathering the data. I wrote the program in Go (that language has gotten my attention recently) that accesses Binance’s public data and it’s available on <a href="https://github.com/Gilt0/optimal-execution">GitHub</a>.</p><p>Then, you do the work!</p><ul><li>Create the calculator for the optimal strategy.</li><li>Create a backtesting tool using Binance.</li></ul><p>You can:: do that project your own way using your own language, or you can contribute by providing the solution (writing your own stories about it). Just create a branch and get going!</p><h3>Data Extractor</h3><p>The data extractor usage is explained on the <a href="https://github.com/Gilt0/optimal-execution/blob/master/README.md">GitHub</a>, but let us quickly link the data output with the notations used here.</p><p>To run the code without building it, it is very simple</p><p>(i) on the first run, create the data folder from the root</p><pre>mkdir -p data/json</pre><p>then run the script (you can build it to if you wish — check the GitHub readme)</p><pre>go run cmd/dataextractor/dataextractor.go -symbol=BTCUSDT -json_path=data/json/ -throttle=5</pre><p>-symbol specifies the symbol to request the data for, using Binance formattings. On the example, I queried for BTCUSDT but you could query for any other symbol available on the API.</p><p>-json_path specifies where the output data is to be stored. You have to create it manually before running the script.</p><p>-throttle specifies the time intervals at which the orderbooks are queried via the http API interface. <br>The trades are obtained through the websocket stream. Some may notice that there is an orderbook websocket stream, but unfortunately, it only has up to 20 levels, and it would have been way too little to have a good snapshot of the liquidity. <br>To have more level live, a local orderbook has to be maintained. It is a wonderful exercise for any aspiring Quant-Trader, but it would have taken too much time of my time (I am working on other things I’ll start publishing soon). So instead, I throttled the capture to query 5000 levels of the orderbook at regularly spaced time intervals the user can specify. For highly liquid symbols like BTCUSDT, a short throttle is good enough (like 5 seconds). As the liquidity decreases, the throttle has to increase to ensure the occurrence of trades. Otherwise, NaNs will be produced.</p><p>Here is an example of output I got running the script</p><pre>{<br>  &quot;Spread&quot;: 0.007543766220855038,<br>  &quot;OrderSize&quot;: 0.006236945827489481,<br>  &quot;OrderAmount&quot;: 165.35367702397087,<br>  &quot;BidOrderSize&quot;: 0.005939920430722318,<br>  &quot;BidOrderAmount&quot;: 157.47893286249285,<br>  &quot;BidTotalQty&quot;: 395.6825525000046,<br>  &quot;BidMaxDelta&quot;: 327.0700000000006,<br>  &quot;AskOrderSize&quot;: 0.0049890625,<br>  &quot;AskOrderAmount&quot;: 132.269875328125,<br>  &quot;AskTotalQty&quot;: 235.42801750000615,<br>  &quot;AskMaxDelta&quot;: 338.02500000000146,<br>  &quot;CumBids&quot;: [<br>    [<br>      0,<br>      0<br>    ],<br>    [<br>      0.0001,<br>      0.04905527602005688<br>    ],<br>    [<br>      0.0002,<br>      0.04934029523169036<br>    ],<br>    ...<br>  ],<br>  &quot;CumAsks&quot;: [<br>    [<br>      0,<br>      0<br>    ],<br>    [<br>      0.0001,<br>      0.01546911719944717<br>    ],<br>    ...<br>  ]<br>}</pre><p>Spread is the quantity <em>s</em> used in all the maths. CumBids and CumAsks are normalized versions of <em>(δ, F(δ))</em> for <em>δ </em>taking finite values (101 uniformly spaced points between 0 and 0.01 and then another 100 point between 0.01 and 1).</p><p>For any non-normalized value <em>δ,</em> <em>F(δ)</em> is obtained with the formulae</p><pre>F_bid := BidTotalQty * CumBids[int((delta - Spread / 2.0) / BidMaxDelta)]<br>F_ask := AskTotalQty * CumAsks[int((delta - Spread / 2.0) / AskMaxDelta)]</pre><p>And this really is all you need to know to be able to use the output of that script to write your optimal execution strategy!</p><blockquote>One last thing: I have not mentionned at all the reconstruction time τ that I introduced in the previous article. Theoretically one way to access this time of reconstruction would be to compute the typical time of the autocorrelation function of the spread… And to do so, I would need a local orderbook with enough depth to estimate robustly the spread.<br>Instead, I introduced the throttle parameter and we’ll assume that this throttle is equal to τ.</blockquote><h3>Optimal Strategy Engine</h3><p>In the previous article, I introduced the performance of the trade as being</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*gtB1AsPxAVa51CHUlJlB4Q.png" /></figure><p>To achieve a good trade performance, it boils down to minimising the variable part above according to some utility function with the constraint that <strong>all is executed.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*EAQjFkTcz4KbL3rYK7A-fQ.png" /></figure><p>As a simple starter, you will consider that the middle price is not impacted by the trade and thus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*mavYQ6MbAXuVZ9ShJNrnAA.png" /></figure><p>Assuming a simple risk minimisation approach, we can consider the utility function to be minimised as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*zwxcllKRE_LyOZWJTWcZ9w.png" /></figure><p>with the constraint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*8DFkdh56Dh96DzAbS4GUPg.png" /></figure><p>And once you have the optimal strategy, you can compute its price making sure that the trade performance plus the commission remains positive…</p><p>So write a solver the liquidity parameters: <em>F, σ, τ</em> as entries and compute for multiple values of <em>N</em> the optimal <em>qₙ</em>’s and choose <em>N</em> such that the objective function above is minimal: <em>N, q₀, …, qₙ, …</em> is your trading strategy!</p><h3>Backtesting the optimal strategy</h3><p>Now that you have a coputing engine for the optimal strategy, write a proper strategy, and backtest it on the stream of quotes and trades coming from binance!</p><p>This should be at least two different scripts. One for the strategy itself with the behaviour that you wish, let’s call it a trading agent, and another one for the backtesting engine. It should be connecting to the streams, and accept one or more trading agents.</p><p>Let’s roughly present how the backtesting engine should be designed.</p><h4>Immediate availability hypothesis</h4><p>Since we assume that an action is taken once the order book is reconstructed, we can consider that every time you take an action, the liquidity is simply just there.</p><p>It is a rather optimistic hypothesis, but it has the merit of being simple. Many real life events invalidate that hypothesis: the liquidity is snatched away from you, the underlying order is cancelled, the connection is lost…</p><h4>Aiming for aggressive and passive execution</h4><p>When I was in the French army, instructors had this phrase</p><blockquote>Qui peut le plus, peut le moins.</blockquote><p>which literally means “If you train to do more, you’ll be able to do less”. Sounds a little obvious in english, but the idea is that by aiming for higher objectives will definitely make you able to pass through lower ones. Which is a good thing if the lower ones are the ones you’re aiming for in the first place.</p><p>So here is another suggestion. If the throttle allows you, have some of the target liquidity executed passively. This has one main drawback: you may not execute all the scheduledd quantity. By not executing all, you expose yourself to the market.</p><p>(i) When trading aggressivelly, assume that the liquidity is yours. Of course, there will be some misses, and you could simulate it. But as a starter, it is easier that way.</p><p>(ii) When trading passively, assume that you are second in line. This means that in the backtesting engine, you have to keep a memory of what is posted first and execute with trading events. Then, as it is your turn to be executed, <em>i.e.</em> you become first in line and you have to wait for your order to be completely depleted.</p><p>(iii) At the end of the period, you should have executed all the quantities required, to make sure that you are not building up inventory and thus exposing yourself more to the market risk.</p><h4>There possibly are other hypotheses to make</h4><p>As you proceed, there will possibly be other hypothesis to make, feel free to take the initiatives that feel realistic to you!</p><h3>Wrapping up</h3><p>So… Here it is. I am making you work. Of course, you can get in touch either with comments below or on GitHub with questions I will try to reply ASAP.</p><p>You can contribute too and after making your own branch, you can ask for a pull request. I will try to have a look at it and add the code for others to use!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46007980bc4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A physicist view on Finance (VI) — Optimal Execution, yet another theory!]]></title>
            <link>https://quantitative-modelling-for-fun.medium.com/optimal-execution-yet-another-theory-d6b6b0f8fc68?source=rss-1087a410ef00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b6b0f8fc68</guid>
            <category><![CDATA[quantitative-strategies]]></category>
            <category><![CDATA[quantitative-research]]></category>
            <category><![CDATA[optimal-execution]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Gil-Arnaud Coche]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 12:20:35 GMT</pubDate>
            <atom:updated>2023-11-04T12:21:43.249Z</atom:updated>
            <content:encoded><![CDATA[<h3>A physicist view on Finance (VI) — Optimal Execution, yet another theory!</h3><p><em>Disclaimer: This is not investment advice, this is merely for educational purposes and definitely an expression of personal thoughts. Investing is </em><strong><em>always</em></strong><em> a risky endeavour.</em></p><p>Asset Managers are responsible for funds and generate wealth by investing them in the right sectors of the economy. Generally holding substantial amounts of assets, some of their trades can be so big that they may represent most of the Average Daily Volume (ADV) on a given day. Therefore, they cannot enter such buy or sell trades without anticipating a potential adverse market move on the price</p><p>This is where Execution Services of Brokerage firms come into play. These providers take charge of high volume trades and ensure that the liquidity of traded assets is not impacted too much by the investment decisions of the Asset Manager. By ensuring a stable liquidity, they consequently reduce the Market Impact on the price during the trade.</p><p>Market Impact is used industry wide to describe the move of the price during a large trade, it may be:</p><ul><li>upward for a buy trade</li><li>downward for a sell trade.</li></ul><p>Scientific literature is very rich on the matter and has extensively investigated the best ways to handle execution with as little price move as possible. Some thought leaders have established key results on the topic: Almgren and Chris [1], Bouchaud [2] and Gatheral [3] being probably amongst the earliest ones.</p><p>In this article, I do not wish to say again things that have been widely researched by academics. Instead, I would like to focus on pragmatic descriptions of the cash fows to focus on simple understanding of the underlying mechanics of optimal execution.</p><p>To do so, I will</p><ul><li>discuss the <em>Execution Puzzle</em> that the broker has to manage ; when taking on a trade, the broker has to choose wisely between liquidity and market risk ;</li><li>introduce the reconstruction time of the order book as a discretization step <em>τ</em> for the trading execution; the reconstruction time of the order book was introduced by Bouchaud [2] and it will be useful in the mathematical descriptions ;</li><li>keep a hands-on approach to the maths: the idea is not mesmerize you with some fancy algebra or numerical computation tricks ; I wish to provide you with simple description of optimal trading and I believe that maths is the best tool to describe flows, no matter their nature (cash flows, matter flows, energy flows, etc). <br><strong>As long as it remains simple.</strong></li></ul><p>You may have to take a pen and go through the steps. But, IMHO, it is worth it…</p><p>行くぞ！</p><h3>The optimal <em>Execution Puzzle</em></h3><p>I use the term <em>Execution Puzzle </em>because when receiving a trading mandate, a broker has to face a harsh reality: either they ruin the liquidity and impact the price by trading too fast, or they expose themselves to a volatily-driven market move by holding the position, even in part, for too long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*fg2BUExn5mq1L7kzPxABgw.png" /><figcaption>When buying (selling), either the trader is <strong>aggressive </strong>and meets the ask (bid) on the other side, mechanically increasing the price and inciting other participants to post higher asks (bids), or the trader is <strong>passive </strong>and posts on the bid (ask) increasing the volume on best levels and indicating ask (bid) participants to go higher (lower).</figcaption></figure><p>They are as many trading tactics to try and keep the market impact as low as possible. One of them is for the broker to garantee a benchmark price for the execution: the Asset Manager pays the broker the realised benchmark at the end of the trading period.</p><p>There can be as many bechmarks as one may feel like engineering, however, some standard ones have emerged.</p><p>In the following we will consider a trading period from <em>t = 0</em> to <em>t = T</em>, the asset price <em>p(t) </em>at time <em>t</em> and the cumulated traded volume on the market <em>V(t)</em> from the start of trade with its derivative <em>v(t).</em></p><ul><li><strong>Volume Weighted Average Price</strong> — the average price over the trading period, weighted by the traded volume on that same period, is the benchmark.<br><em>By considering the price obtained for the actual traded volume, the broker ensures some parity with the market activity. <br>What the market does is what the Asset Managers gets as an execution price.</em><br>One caveats: for really huge trades, this benchmark does not necessarily favours the Asset Managers as the market maybe dominated by their own trade. And so the broker could obtain an execution price very close to the VWAP but the Asset Manager would potentially loose part its wealth because of the possible impact.<br>Mathematically, the VWAP is given by</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*2ZuYBis6sFT7TCYOKxVPMg.png" /></figure><ul><li><strong>Time Weighted Average Price (TWAP) </strong>— the average price over the trading period is the benchmark.<br>This benchmark is useful over very long periods of time (when the trade spans over multiple days or even weeks). As the time increases the importance of volumes in the calculation of VWAP decreases and eventually, only the exposure to volatility-driven market moves matters. Therefore the VWAP becomes a TWAP. Although this benchmark appears from upscaling the VWAP, market practices have made it an acceptable benchmark for shorter time periods. Afterall, it is a very rapid way to filter out volatility from the execution price.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*Ty-iNg0PtEf8pPh4TeQzUw.png" /></figure><p>It has been proven, on a database of <em>sensible VWAP and TWAP trades</em> (see Gatheral) that the shape of the absolute variation from the inital price, throughout the trade, follows the trajectory below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*CgjtW4_90KozR1bbUsCCAw.png" /><figcaption>Above the absolute variation from the inital price (source: Bouchaud [3]).</figcaption></figure><p>The pic of the curve ℐ<em>(Q)</em> has empirically been found to follow a Square Root Law such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*aheVc6WiG0EoqgIi6bfLig.png" /><figcaption>Square Root Law on the maximum Implementation Shortfall (or peak of the curve)</figcaption></figure><p>This means that for reasonable VWAP- and TWAP-benchmarked executions, it is expected that the price will move, <strong>no matter what</strong>. The amplitude of this move is dependant on the liquidity of the asset only (volatility <em>σ</em> and ADV). Therefore the Asset Manager always pays a price for the execution, even in well executed trades.</p><p>Naturally, brokers eventually offered Asset Managers to benchmark the execution to the inital price which clearly shows whether the execution has preserved the Asset Manager’s wealth. This is called the Implementation Shortfall.</p><ul><li><strong>The Implementation Shortfall</strong> — the initial price over the trading period is the benchmark.<br>As explained above, the VWAP and TWAP can be detriemental to the Asset Manager. By benchmarking with the initial price, the broker is bound to offer the best performance possible for the Asset Manager. With the initial price as a benchmark, the broker is exposed to both impact and risk.</li></ul><h3>The orderbook reconstruction time</h3><p>In Bouchaud [2], orderbooks (OB) are characterized by their mid price, the depth on the bid and on the ask, the spread and their reconstruction time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*xa6s9hPuYSt29aNtXMWVMg.png" /></figure><p>The above figure shows these aspects. On the left, the OB at equilibrium, the spread measures the distance between the bid side and the ask side, while the depths measure the available liquidity on one side. To quantify further the available liquidity, an element of volumetry represented by the curve inserted on the left of the OB has to be explicitly added to the model. The mid price gives the position of the overall book along the price axis.</p><p>I should also mention the tick and lot (price size and volume size), although it would add unnecessary complexity to my presentation. Just keep in mind it is there as well!</p><p>The reconstruction time is a <strong>dynamical </strong>liquidity characteristics. It quantifies the time taken for the OB to come back to its stable state (defined by a spread equal to its equilibrium value). Say, for example and as shown on the sketch above, that an event occurs and three levels of the OB are depleted on the ask side. It has now a new spread, a new mid price, and new depths. But this is not a local equilibrium and depending on the market conditions, market participants may place new orders on the ask but also on the bid (as shown on the sketch) or only on the ask or only on the bid. Eventually, the OB gets back to having about the same spread, but potentially a new depths and mid price.</p><p>This time taken for the spread to come back to its equilibrium value, is the <strong>reconstruction time </strong>and we will name it <em>τ</em>.</p><h4>Time discretized benchmarks</h4><p>Coming back to our earlier definitions of the VWAP and TWAP, we can now discretize on the reconstruction time <em>τ</em> so that <em>T = Nτ</em>.</p><p>The philosophy behind this choice is that we assume that when the broker takes action on the order book, they wait exactly for a duration <em>τ</em> until they take another action. It is of course assumed that <em>τ &lt;&lt; T</em> and therefore discretising the above integrals makes sense.</p><p>The above formulae become thus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*AFXOSCSSIuKLbomKwV04iA.png" /></figure><p>Now, in this discrete form it is straight forward to write benchmarks as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*ZkPqYTwZC6utcLzrFP0Y7w.png" /></figure><p>with the weights</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*ChvAj5zshwg2M_nZoM-Pgg.png" /></figure><h3>The Maths! 🏞️</h3><p>To me, <em>the maths</em> cannot be correctly derived without an accurate description of flows. It needs a proper understanding of the geometries involved to come to life (in a way…).</p><p>Here the flows will be ones of orders and cash on the geometry of the OB.</p><h4>General Formula for the trading costs</h4><p>And below is how I see them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*_CufjGSi-eHYe9JcU8_7Dw.png" /></figure><p>Let’s spend some time describing the sketch of the figure above. At every trading interval of duration <em>τ</em>, equal to the OB’s recontruction time, liquidity is consumed by the broker along the OB’s depth on the ask side (we will assume a buy trade from now on). The liquidity could be consumed passively on the bid side, however, in order to have the most thorough estimate of costs, better provide the most conservative scenario for the broker: an aggressive only trade.</p><p>At each trading interval <em>n</em>, a quantity <em>qₙ</em> is consumed, represented by the blue arrows, along the depth distribution <em>fₙ(δ),</em> represented by the curves on the sketch. <em>δ </em>is he depth from the best ask.</p><p>Mathematically this boils down to considering that the acquisition cost of the position is obtained from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*EV0sAT5BFLAxdm2xMeIpaQ.png" /></figure><p>Because of the overall stability of the OB over short periods of time, it is fair to assume that <em>fₙ(δ)</em> is a constant of time <em>n</em> and thus is equal to <em>f(δ)</em> at all trading interval. Also since</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*Q-pmvBCmafeuvy9ri5GFVw.png" /></figure><p>the trading costs simplify to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*pLaJbb8ApjIYjkp--gu8ow.png" /></figure><p>and with the change of variable <em>χ = F(δ)</em> we get to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*p2g3V_gmpJ-Zdg4LWsEbwQ.png" /></figure><h4>General Formula for the Trade Performance</h4><p>The trade performance is the difference between the trading costs garanteed to the client and the realized costs. Using the formulae for the general benchmark we have that the trade performance is equal to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*-vYT5pRQCGtu1Kr6OCsDwQ.png" /></figure><p>if we assume that the reference price is the best bid. Again as we are pricing the worst outcomes, we remain conservative and assume that the ideal broker would garantee the most favourable price to the Asset Manager.</p><p>Assuming that the spread is constant at each trading interval (I could have mentioned this fact earlier…), the above formula becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*7CngATHhDAai59sS_V_7yQ.png" /></figure><p>This last result is interesting.</p><p>(i) — In a conservative framework, there is a incompressible negative performance due to the spread.</p><p>(ii) — If one wants to completely remove the market risk, one could naively set the trading objective at each trading interval to be <em>qₙ = ωₙQ. </em>In the context of the IS benchmark, this is completely ridiculous as one would have a maximum impact by trading everything from the get-go.<br>For TWAP and VWAP, this is more reasonable and reduces the costs to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*UhDEPdyaCo2Er-E4Dt_nwg.png" /></figure><p>Although this formula is quite accurate for the TWAP as <em>ωₙ </em>is a constant equal to <em>1/N, </em>for the VWAP, this performance is not accurate as <em>ωₙ </em>is random and all one can do prior to the trading interval <em>n</em> is to provide an estimate which will be more or less accurate.</p><h4>Case of the TWAP</h4><p>For the TWAP, the trade performance is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*LtSNBz9xFjx78gGlCjfsDg.png" /></figure><p>and thus an optimal horizon may be derived as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*yV_SAPtg-7lrdy4h6p7IKg.png" /></figure><p>and obtained from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*Ii39EJeSvaXDPgzWeArcow.png" /></figure><p>To find the optimal horizon would require numerical computations which we will not get into now (hopefully in a next article!). And at the optimal the trade performance is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*gjdj_Lbz3LoFb1nC5N4Oxg.png" /></figure><p>Which sets the price of the trade at a minimum of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*zfQtjVkitzDJGYoC10gR1w.png" /></figure><p>For a duration set by the Asset Manager, the price in bips is simply</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*6FtugMLGCVLsv-48--H3MA.png" /></figure><h4>Case of the VWAP</h4><p>The general formula for the minimum price in bps of the VWAP is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*eE7WqKF7XEUAG1_Jz2U77g.png" /></figure><p>and holds asymptotically (when <em>N </em>tends to infinity) if the estimate of <em>ωₙ</em> is non-biased. In case of a biais (meaning the broker is systematically off by a fixed value), the minimum price ought to be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*odKrtCOiFyIos4Hlg2fwpA.png" /></figure><p>if the price follows a random walk.</p><p>To obtain the optimal execution horizon, the volume profile <em>(ωₙ) </em>needs to be computed. However the idea is the same and eventually, the minimum of the equation below has to be found for <em>N.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*JIAgBY5wu1uzbJ8Wk1xhjA.png" /></figure><p>Assuming that an appropriate estimate of <em>ωₙ</em> has been computed.</p><h4>Case of the IS</h4><p>In this case, it should be an article all by itself, which I may write now that I think about it. I’ll simply state that there is no naive way to mitigate the market risk from the trading performance and thus one has to pick an objective function suited to their needs. Given the random nature of the the trade performance, it may be wise to consider some risk minimising function which will provide the optimal trading horizon and then the average will provide the value of the trade (traditional actuarial like approach).</p><p><em>Edit: Now that I read this paragraph two weeks later, I find it to be not so clear. Here is why this particular case is rather different.</em></p><p>The trade performance for an IS benchmark is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*gtB1AsPxAVa51CHUlJlB4Q.png" /></figure><p>and as mentionned earlier, the market component cannot be removed by an heuristics where <em>ωₙ = 1</em> for <em>n = 0</em> and <em>0</em> otherwise: the impact would be maximum on the orderbook.</p><p><em>mₙ</em> is random and morevover, as explained by the authors I mentionnedd ([1]-[3]), the price is self-impacted by the trade itself meaning that the price dynamics could very well be described by something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*eYlsh1bSm9PxiWnvtvR4Yw.png" /></figure><p>where <em>G(n,p)</em> is a response function — see [2] or [3].</p><p>Because of that random nature, risk should be considered!</p><h3>Wrapping up</h3><p>Well , well… Looks like I got a little excited. 😹</p><p>When it comes to quantitative modelling, I usually get into another world and let the maths speak. In any case, the message here is very clear:</p><ul><li>Optimal execution can be obtained through heuristics to mitigate market risk. This is what brokers have been doing for decades, using the VWAP and/or TWAP when engaging in huge trades for big investors and asset managers.</li><li>But these heuristic may be a at disadvantage for the latter when the trade represents a consequent share of the ADV. On such cases, more actuarial like approaches should be considered. And as the last paragraph on IS has started to mention, variance considerations on the expected performance may be a good way to go.</li></ul><p>In a following article, I will most probably have an empirical analysis of what I am claiming here. Not sure if I will be focusing on TWAP, VWAP or IS. I might as well be the most general possible and develop a pricer for generic strategy with a generic benchmark and then compare with the specificities of TWAP, VWAP… We’ll see.</p><p>Until then, happy to hear your thoughts on this post!</p><p><strong>Edit: </strong><a href="https://medium.com/@quantitative-modelling-for-fun/optimal-execution-ii-get-your-hands-dirty-46007980bc4d">Here </a>is a follow up on this article where you get to work!</p><h3>References</h3><p>[1] Almgren and Chris — <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=53501">https://papers.ssrn.com/sol3/papers.cfm?abstract_id=53501</a></p><p>[2] Bouchaud — <a href="https://books.google.co.jp/books/about/Trades_Quotes_and_Prices.html?id=u45LDwAAQBAJ&amp;redir_esc=y">https://books.google.co.jp/books/about/Trades_Quotes_and_Prices.html?id=u45LDwAAQBAJ&amp;redir_esc=y</a></p><p>[3] Gatheral — <a href="https://mfe.baruch.cuny.edu/wp-content/uploads/2017/05/Chicago2016OptimalExecution.pdf">https://mfe.baruch.cuny.edu/wp-content/uploads/2017/05/Chicago2016OptimalExecution.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b6b0f8fc68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>