<?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 Brett Harrison on Medium]]></title>
        <description><![CDATA[Stories by Brett Harrison on Medium]]></description>
        <link>https://medium.com/@brett_17026?source=rss-eefb5dfb14cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ee_Ne9bRWqWvQK4goRnpQA.png</url>
            <title>Stories by Brett Harrison on Medium</title>
            <link>https://medium.com/@brett_17026?source=rss-eefb5dfb14cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:21:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brett_17026/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 taxonomy of arbitrage trading]]></title>
            <link>https://medium.com/@brett_17026/a-taxonomy-of-arbitrage-trading-f6df2bc7abaa?source=rss-eefb5dfb14cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6df2bc7abaa</guid>
            <category><![CDATA[arbitrage]]></category>
            <category><![CDATA[hedge-funds]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[high-frequency-trading]]></category>
            <dc:creator><![CDATA[Brett Harrison]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 06:08:07 GMT</pubDate>
            <atom:updated>2024-06-12T06:08:07.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpFA9O8jVZTU2qaDXG3auA.jpeg" /></figure><p><strong>Classical arbitrage:</strong> simultaneously trading two or more fungible instruments and converting between them to capture price differentials. At least one leg of the trade typically involves derivatives, as in ETF arbitrage (e.g. buying an ETF while selling its constituent basket, and then redeeming the ETF), ADR arbitrage (e.g. selling an ADR while buying its underlying foreign stock and foreign currency, and then creating the ADR), futures arbitrage (e.g. buying a future while selling its underlying, and holding both until futures expiration), and triangle arbitrage (e.g. buying FX or crypto pairs A/B, B/C, and C/A).</p><p><strong>Latency arbitrage: </strong>leveraging speed advantages to be the first to complete a trade triggered by a discrete event. The simplest example is racing to take a stale bid or offer on one US equity exchange based on observing or executing a trade in the same equity on a different exchange. A more esoteric case is using your own private fill prices to trade the same or related instruments ahead of other market participants based on what is available in public market data. In the last five years, many exchanges have made infrastructure upgrades to remove these opportunities by decreasing the time between private and public data dissemination.</p><p><strong>Time arbitrage:</strong> capturing spreads between buyers and sellers who demand liquidity at different time periods. US equity and options wholesalers engage in a form of time arbitrage by e.g. guaranteeing a retail buy order with the expectation that, assuming flow is random, a retail sell order will follow shortly. Another time arbitrage opportunity occurs when instruments would normally be linked by classical arbitrage, but the exchanges on which they trade are open at different times.</p><p><strong>Microstructure arbitrage:</strong> capturing price dislocations using idiosyncrasies of a particular exchange’s operations, such as matching semantics, fee treatment, and specialized order types. The most common opportunities arise from non-continuous matching mechanisms such as opening and closing auctions and the exchange-specific order types used to interact with them (limit-on-open, imbalance-only, etc.).</p><p><strong>Statistical arbitrage: </strong>trading the spread between two or more instruments based on probabilistic estimations of convergence (mean reversion) or divergence (momentum). One example in the news lately is the “dispersion trade,” betting that on average the price of an index option should converge to a weighted basket of options on the index’s underlyings. Many don’t consider statistical arbitrage to be arbitrage in the classical sense, although almost all of the other types of arbitrages above involve some elements of statistical arbitrage in practice.</p><p>NAA (not arbitrage advice)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6df2bc7abaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs and Algorithmic Trading]]></title>
            <link>https://medium.com/@brett_17026/llms-and-algorithmic-trading-0df34383187b?source=rss-eefb5dfb14cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0df34383187b</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Brett Harrison]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 02:32:16 GMT</pubDate>
            <atom:updated>2023-10-09T02:32:16.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3m6rDzFjHzvoq0tG2eDeog.jpeg" /></figure><p>In the past year, the profound successes of Transformer Neural Networks, especially Generative Pre-trained Transformers like OpenAI’s GPT-4 and Meta’s LLaMA2, have sparked the imagination of those in the financial industry. During recent traditional finance conferences I’ve attended, participants have been abuzz with speculation about how these state-of-the-art AI models could disrupt conventional investing and trading. This post aims to provide insights on how advanced machine learning models might integrate into the world of algorithmic<strong> </strong>trading, drawing from my experience in the fields of computer science, machine learning, and quantitative finance.</p><p>I received my bachelor’s and master’s degrees in computer science from Harvard with focuses on artificial intelligence and electronic commerce in 2010<strong>, </strong>and I spent the following eleven years designing algorithmic trading systems at high-frequency trading firms. My thesis at Harvard dealt with applying machine learning to predict future moves in the game of Go<strong>, </strong>the ancient turn-based strategy board game (https://www.semanticscholar.org/paper/Move-Prediction-in-the-Game-of-Go-Harrison/8731cf873d36171e0d2ec895184aaf659e315abe).<strong> </strong>At the time I began my research, AI had notorious difficulties with Go. The landmark achievement of AlphaGo defeating a lower-ranking professional human player without any handicap was still seven years away.</p><p>Compared to the general problem of designing artificial intelligence to play the game of Go, the problem of move prediction is a more straightforward supervised learning task. Several prevailing machine learning algorithms existed, but all had a similar flavor:</p><ol><li><strong>Feature Selection: </strong>Hand-pick a set of features based on knowledge of Go game rules and strategy (approximate territory counts, chain liberty counts, stones captured, etc.).</li><li><strong>Model Assumption. </strong>Select a probabilistic estimator that evaluates the strength of a board position given the computed feature vector.</li><li><strong>Training and Backtesting: </strong>Compute the empirical values of the estimator using a training set of actual professional Go game records, and evaluate how the model performs on an unseen portion of the data set.</li></ol><p>At the time, the strongest-performing methods for the second step were a combination of Bradley-Terry scoring of feature vectors (a ranking algorithm similar to Elo), and Monte-Carlo simulations of game outcomes from the given board position. These models, although achieving modest move prediction accuracies of about 35%, were computationally demanding and suffered from overfitting as the cardinality of the feature vectors increased.</p><p>My approach to the problem was different. By considering the curated set of features to be linearly independent and using a sort-of inverted Naive Bayes algorithm, I achieved similar accuracies but with significantly less computational strain.</p><p>A year later, when I began developing automated trading systems for Jane Street Capital, I saw parallels between the most effective models in quantitative finance and those that produced the best results in Go move prediction. Most algorithmic (and even non-algorithmic) trading approaches hinge on very similar core principles:</p><ol><li><strong>Feature Selection:</strong> Traders choose a set of features they believe will predict the movement of a financial instrument. These could be based on expressions of fungible relationships, such as the relationship between an ADR, its underlying foreign stock, and relevant FX rate. Or they could be derived from statistical relationships between time series of related instruments in a similar sector or index. Or they can even be based on instrument-agnostic microstructure features, such as the imbalance of resting sizes in the central limit order book.</li><li><strong>Model Assumption:</strong> A mathematical relationship is assumed between the chosen features and the expected market movement, either directly through understanding the fundamental composition of the instrument, or indirectly through choice of some kind of statistical or machine learning model.</li><li><strong>Training and Backtesting:</strong> Weights are assigned to the selected features either manually or through techniques like regression or hill climbing. The model is then back-tested on unseen data, and if deemed fit, is deployed.</li><li><strong>Continuous Monitoring:</strong> If the model falters or ceases to perform, traders delve deep into the data to ascertain the reasons. This step is crucial to ensure adaptability and long-term performance.</li></ol><p>Aside from the clear overlap between these principles and those that guide supervised machine learning, I observed another surprising connection between the two fields that is hard to appreciate from outside the secure walls of HFT: the most profitable trading models tended to be extremely simple. They relied on a small number of intuitive features, expressed intuitive linear relationships between instruments, and produced intuitive trading decisions, in a way that was analogous to my Naive Bayes move predictor. To the extent that larger numbers of features were explored in the model design process, many were cut by the time the models were deployed in production, or the dimensionality was reduced through techniques such as PCA.</p><p>These two unique but ultimately related set of experiences have informed how I view the possibilities of Large Language Models (LLMs) like GPT either enhancing or replacing various processes in algorithmic trading.</p><p><em>Due to the fundamental mismatch between the natures of financial market data and linguistically-derived data, the LLM will not be the machine learning model that achieves self-trained, fully-autonomous trading capabilities. Instead, LLMs will primarily be used to amplify the abilities of humans to perform the core tasks needed for algorithmic trading: feature selection; model assumption; trading and backtesting; and continuous monitoring.</em></p><p>Without technical background in artificial neural networks and quantitative trading, it might be easy to envision that something akin to GPT4 could function in a financial context as an omniscient oracle, a magical black box that combines all the above steps into one, with marketdata flowing through the ingress, and execution decisions and profits dispatched from the egress.</p><p>LLMs, however, are exactly what they say they are on the tin: useful at tokenizing corpi of data that have language-like properties. That encompasses a vast amount of naturally occurring data domains, whether Yoruba or English, C++ or Nim, political treatises or poetry, or even descriptions of games like Chess or Go (for fun, go ask ChatGPT to play Go with you).</p><p>But the pseudo-random time-series of financial instruments do not behave like language. They are dynamic, stochastic systems that are more fractal in nature in that they rarely show self-similarity. Time-series prediction accuracies are often highly sensitive to small perturbations in model outputs, compared to LLMs which are often operating under the assumption of a large space of acceptable answers. Also, LLMs famously make continuous monitoring requirements of trading difficult — if a billion-parameter model fails to achieve desired market performance, how do you “fix” it? And at present, LLMs aren’t always ready to handle arithmetic, let alone the precise formulae involved in high-risk investment scenarios (cf. <a href="https://x.com/littmath/status/1708327886866862202).">https://x.com/littmath/status/1708327886866862202).</a></p><p>With all of these limitations understood, LLMs <em>can </em>be immediately employed in many of the individual processes that make up successful algorithmic trading strategies. The core principles of trading model generation described above are almost all inherently language-based, and so LLMs are a natural fit to amplify existing workflows in these areas. Here are several examples:</p><ul><li><strong>Feature Selection:</strong> LLMs can delve into the granular complexities of data, assisting in identifying and authenticating potential predictive variables, often on a qualitative rather than quantitative basis due to the precision required for the latter.</li><li><strong>Data Scrubbing:</strong> LLMs can be adept and pinpointing irregularities and anomalies in vast quantities of data, suggesting refinements to ensure data purity and consistency.</li><li><strong>Sentiment Analysis: </strong>Capitalizing on their core strength, which is parsing and understanding language, LLMs can derive market sentiment from news articles, corporate filings, tweets, and other textual data sources.</li><li><strong>Code Generation:</strong> For actual practitioners of automated or semi-automated trading, the art and science of writing correct and efficient programs for computing live and historical trading decisions can be as or more difficult than model selection, and LLMs are already highly useful in this area.</li><li><strong>Production reporting: </strong>LLMs can quickly summarize portfolio positions, execution histories, and even trading system error messages to produce human-readable reports rather than rely on either manual work or time-consuming scripting tasks.</li></ul><p>While the potential of Transformers in capital markets is significant, it’s essential to appreciate them not as a panacea but as sophisticated tools that, combined with human ingenuity, can elevate trading strategies and provide operational leverage to those employing them. As with move prediction in Go, or traditional HFT, the simple, intuitive uses of mathematics and computer science have more pragmatic value than any attempt to throw the newest technology available at a well-understood problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0df34383187b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How fast is it, really?]]></title>
            <link>https://medium.com/@brett_17026/how-fast-is-it-really-1a7928c58888?source=rss-eefb5dfb14cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a7928c58888</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Brett Harrison]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 05:41:54 GMT</pubDate>
            <atom:updated>2023-09-06T05:41:54.564Z</atom:updated>
            <content:encoded><![CDATA[<h3>How fast is it, really? — On latency, measurement, and optimization in algorithmic trading systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_hgl5-HVI3i8IiTk_Pz0Q.png" /></figure><p><em>“The speed of light sucks.” — John Carmack</em></p><p>Software engineers within the world of low-latency automated trading (colloquially known as “high-frequency trading” or HFT) obsess over speed. From purchasing private bandwidth between microwave towers to analyzing x86 instructions from different compiler versions, those with experience in this industry have seen colossal time and expense committed to the problem of optimizing code and network paths for minimal execution times.</p><p>But how does one actually measure how fast a program is? To the uninitiated, it sounds like a simple task. However there are many layers of complexity in measuring the true latency of a trading system, or even defining what to measure in the first place. Understanding latencies in algorithmic trading systems can present Heisenberg-esque dilemmas, where the more code you write to measure latency the more overhead you add to your program and therefore the more inaccurate your measurements become.</p><p>At Architect we have been using a combination of techniques to measure the latency of various codepaths and processes that comprise our institutional trading technology suite. Let’s explore some solutions to these problems.</p><p>—</p><p>Let’s say you’ve written an algorithmic trading strategy. Your strategy reacts to market trades in an instrument, perhaps by computing a proprietary model valuation, and sends an order in that instrument provided certain conditions are met. You would like to measure the time that this reaction takes, so that you can reduce the time as much as possible. Let’s use Python-style pseudocode to describe the program (although in practice it is most common to use languages like, C, C++, and Rust where optimal program latencies are required):</p><pre>def on_market_trade(self, instrument, market_trade):<br>  model_value = self.compute_model_value(instrument, market_trade)<br>  order = self.compute_order_decision(instrument, model_value)<br>  if order is not None:<br>    self.send_order(order)</pre><p>A reasonable place to start in understanding the latency of your critical codepath is to wrap timers around the functions doing the heavy lifting:</p><pre>def on_market_trade(self, instrument, market_trade):<br>  start_time = datetime.now()<br>  model_value = self.compute_model_value(instrument, market_trade)<br>  order = self.compute_order_decision(instrument, model_value)<br>  end_time = datetime.now()<br>  self.add_time_sample(end_time - start_time)<br>  if order is not None:<br>    self.send_order(order)</pre><p>The function self.add_time_sample would add the elapsed time to a histogram that you could print statistics for at the end of your program’s lifecycle, or on some regular basis based on time or number of samples observed.</p><p>There are many issues with the above approach:</p><ol><li>It measures the time required to compute the order decision, but does not include the time it takes to send the actual order.</li><li>It observes computation time on every market trade, rather than just the trades that result in orders — this can bias results because the most interesting times to send orders may be the ones where your program is running the slowest due to volume of market events or other factors.</li><li>datetime.now() itself is a slow, expensive function that can impact the runtime speed and memory profile of the code above, which adds up if your program is already operating on a microsecond-timescale. The typical way to fix this last issue is to use native performance counters that most programming language have primitives to access.</li></ol><p>Here’s a new code sample that attempts to fix the above:</p><pre>def on_market_trade(self, instrument, market_trade):<br>  start_time = time.perf_counter_ns()<br>  model_value = self.compute_model_value(instrument, market_trade)<br>  order = self.compute_order_decision(instrument, model_value)<br>  if order is not None:<br>    self.send_order(order)<br>    end_time = time.perf_counter_ns()<br>    self.add_time_sample(end_time - start_time)</pre><p>This is an improvement, but are we really getting at the full latency of the trading system? The above doesn’t include significant elements of the critical path, including the time to parse the market trade update, or anything involving network I/O. Let’s take a step back and trace a market data update through the complete critical path of the automated trading system (ATS):</p><ol><li>Network packet containing the market trade hits the network card of the box where the ATS is running (sent from the exchange)</li><li>The packet is passed to the runtime of the ATS</li><li>The ATS parses the bytes of the packet to pull out necessary fields (such as trade price or trade size)</li><li>The ATS computes a model value and makes a decision to send an order</li><li>The internal memory representation of the order is converted to the protocol of the exchange that the order is being sent to</li><li>The ATS makes function calls to pass the order bytes to the network card of the box for sending</li><li>The network card of the box sends the order bytes to the exchange</li></ol><p>(There are many details missing from the above, such as the multiple methods of going from steps 1 to 2 and 6 to 7, but we are omitting those for simplicity for now.)</p><p>The code sample above is only measuring steps 4, 5, and 6. I have seen many real-world instances where 90% or more of the full latency profile was present in 1, 2, 6, and 7. A large chunk of latency could be incurred in step 3 if performed uncarefully, or if there is any order-book-building necessary in steps 3 and 4.</p><p>To truly capture all seven steps, you can set up this alternative method for measuring latency:</p><ul><li>Write a program that simulates the exchange marketdata, by sending random market trade events on a timer</li><li>Have that same program simulate the exchange itself by receiving orders in the exchange’s native protocol</li><li>Have the simulator timestamp the market trades with the current time right before sending</li><li>Configure the ATS to receive data from the simulator and send orders to the simulator. Have the ATS attach the exchange trade timestamp on the order it sends to the exchange, or if that’s not possible in the protocol have it record a mapping from order id to exchange trade timestamp</li><li>Have the simulator write down the timestamp when it receives orders from the ATS. From either the data on the order itself or from the ATS’s mapping of order id to exchange trade timestamp, compute the difference between market trade send time and order receive time.</li></ul><p>While the above does completely capture the full critical path, it provides too conservative an estimate of latency: it also captures a similar codepath for the simulator itself! To get closer to the right answer, you can write <em>another</em> simulation Exchange and also a simulation ATS that just ping/pongs a single timestamp back and forth without any protocol translation, model building, order sending, etc. This provides a baseline for inter-program latency that could be subtracted from the above experiment.</p><p>The as-close-as-possible-to-perfect solution involves a much more advanced setup, where modern switching hardware is used to replicate packet traffic in and out of the box and the raw network packets are parsed and correlated for timestamping. But I’ll leave those details for a future post.</p><p>Writing fast algorithmic trading system code is hard. Measuring it properly is even harder. At Architect we have created institutional-grade low-latency trading software for both regulated derivatives and digital assets, so that you can let us do the work for you. For more information, visit us at <a href="https://architect.xyz/">https://architect.xyz</a> or contact us at <em>hello </em>at<em> architect.xyz</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a7928c58888" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>