<?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 Trevor McGuire on Medium]]></title>
        <description><![CDATA[Stories by Trevor McGuire on Medium]]></description>
        <link>https://medium.com/@trevormcguire?source=rss-412745870be9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*umnWUdf8TDJRMJZ8p2DbFQ.jpeg</url>
            <title>Stories by Trevor McGuire on Medium</title>
            <link>https://medium.com/@trevormcguire?source=rss-412745870be9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:45:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trevormcguire/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[Introducing the Stock Market AI Research Tool (SMART)]]></title>
            <link>https://trevormcguire.medium.com/introducing-the-stock-market-ai-research-tool-smart-59bde3ffcec7?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/59bde3ffcec7</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 02:01:30 GMT</pubDate>
            <atom:updated>2026-08-06T02:01:30.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-e09p9ief0DrX8SDt1iWA.png" /></figure><p>The <strong>Stock Market AI Research Tool (SMART)</strong> is a family of AI models built into the <a href="https://empiricalmarkets.com/markets">Empirical Markets</a> platform. Each model produces daily, actionable trading signals, and every signal comes with a transparent backtest so you know exactly what you’re getting into before you trade.</p><p>Most AI tools give you a prediction with no context. SMART gives you the prediction <em>and</em> the historical track record attached to it: win rate, average return, profit factor, and a full return distribution — all computed on hold-out test data not seen during training. These metrics are calculated using well-defined trading strategies, so you don’t have to guess how to use the predictions.</p><p>In this post, we’ll walk through how to navigate the SMART interface, what each model predicts, and how to interpret the performance metrics.</p><h3>SMART Models</h3><p>SMART currently includes four models, each targeting a different market phenomenon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqVjS3pRkgxIztd4q5WweQ.png" /></figure><p>Over time, more models will be added, and others may be deprecated.</p><h3>Actionable Trading Signals</h3><p>First, after logging in to <a href="https://empiricalmarkets.com/markets">Empirical Markets</a>, navigate to the SMART model interface and select a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhT0C1KFDx1hjCCRW-kkhQ.png" /></figure><p>Then, select a model variant. Model variants may have one or more trading strategies associated with them. Each of these strategies have associated historical return metrics attached to them, along with details about the backtest. Inspecting these metrics gives you an understanding of the risk-reward profile for the strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKEwffe17Q1xSv1H50yQrQ.png" /></figure><p>Each signal is directional. Variants are labeled <strong>↑ Long</strong> or <strong>↓ Short</strong>, indicating which direction the model expects the edge to favor.</p><h3>Understanding the Backtest Metrics</h3><p>Every SMART strategy card shows the following metrics, all computed on hold-out test data (meaning data not seen during training):</p><h3>Entry &amp; Exit Strategy</h3><p>Before reading any number, understand <em>how</em> the trade was simulated:</p><ul><li><strong>Entry Strategy</strong>: Signals are entered at the <strong>next day’s open</strong> after a signal fires — this is a realistic, implementable assumption. There’s no look-ahead.</li><li><strong>Exit Strategy</strong>: The default is <strong>First Profitable Exit</strong> — if there is a profitable close within the horizon, exit there; otherwise hold to the end of the horizon.</li><li><strong>Horizon</strong>: The number of trading days the strategy looks forward (e.g., 10 days).</li></ul><p>For each model, new strategies will be added over time, alongside their performance stats.</p><h3>Performance Statistics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMUdZ2h-BB1MH634twPsHA.png" /></figure><h3>Return Distribution Chart</h3><p>Below the headline stats, a bar chart shows the <strong>strategy return distribution by percentile</strong> (the forward return at each percentile of all signals). This tells you the full shape of outcomes:</p><ul><li><strong>Green bars (above zero)</strong>: percentiles where signals produced gains</li><li><strong>Red bars (below zero)</strong>: percentiles where signals produced losses</li><li>The wider the green portion, the more consistently the strategy generated positive returns</li></ul><p>A strategy where even the 25th percentile bar is positive is meaningfully different from one where only the top half is green.</p><h3>Get Started</h3><p>The Stock Market AI Research Tool (SMART) is available now on <a href="https://empiricalmarkets.com/markets">Empirical Markets</a>. Sign up for a free account to access SMART predictions with a limited number of AI credits, or upgrade to a paid plan for unlimited access.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59bde3ffcec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Built Empirical Markets, and Why You Should Try It]]></title>
            <link>https://trevormcguire.medium.com/why-i-built-empirical-markets-and-why-you-should-try-it-11bb48040e10?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/11bb48040e10</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 13:37:00 GMT</pubDate>
            <atom:updated>2026-06-29T13:46:56.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZWuSpzyE-7WkKekSl6PFw.png" /></figure><p>There is no shortage of market data online.</p><p>You can get prices almost anywhere. You can find financial statements, economic calendars, SEC filings, insider trades, and an endless stream of chart screenshots and market commentary. If you’re technical, you can stitch together APIs from half a dozen providers and build your own workflows. If you’re a trader, you can bounce between dashboards, research platforms, and social feeds trying to form a view.</p><p>The problem is not access to information.</p><p>The problem is turning all of that information into something coherent, actionable, and actually useful.</p><p>That is why I built <strong>Empirical Markets</strong>.</p><p><a href="https://empiricalmarkets.com/">Empirical Markets</a> is a <strong>markets intelligence platform</strong> for people who want more than a chart and more than a news feed. It combines <strong>market data, macro data, insider activity, SEC filings, quantitative anomaly detection, and AI-driven prediction systems</strong> into one place so you can spend less time gathering information and more time understanding what actually matters.</p><p>If you’re a trader, analyst, quant researcher, or developer building market tools, the goal is simple: <strong>help you find high-probability setups faster, with more context and less noise.</strong></p><h3>The problem with most market tools</h3><p>Most financial tools solve one narrow part of the workflow.</p><p>One product gives you charts. Another gives you fundamentals. Another gives you macro data. Another gives you insider transactions. Another gives you raw APIs. Another gives you “AI,” usually with very little transparency into its historical effectiveness and current performance.</p><p>So what happens?</p><p>You end up doing the integration work yourself, mentally or technically.</p><p>You are the one trying to connect:</p><ul><li>a sudden move in a stock</li><li>an unusual change in trading activity</li><li>a shift in Treasury yields</li><li>a fresh SEC filing</li><li>insider buying or selling</li><li>some indicator that may or may not matter</li><li>and a market regime that changes how you should interpret all of the above</li></ul><p>That fragmentation is expensive. It costs time, it creates friction, and it makes it harder to consistently spot good opportunities.</p><p>I wanted to build something different: a platform that sits <strong>between raw market data and actual decision-making</strong>.</p><p>Not a generic “AI stock picker.”<br>Not a glorified charting app.<br>Not just another data feed.</p><p>A system that helps answer a more useful question:</p><p><strong>What is happening in this market, what is unusual, and where should I look next?</strong></p><h3>Empirical Markets is built around signal, not just data</h3><p>The core idea behind <a href="https://empiricalmarkets.com/">Empirical Markets</a> is that <strong>raw information becomes much more valuable when it is organized around signals</strong>.</p><p>That means the platform is not just a place to <em>view</em> data. It is designed to help you <strong>surface what is statistically interesting, structurally unusual, or worth deeper investigation</strong>.</p><p>Depending on what you are looking at, that can include:</p><ul><li><strong>AI prediction systems</strong> designed to identify statistically favorable opportunities</li><li><strong>Quant anomaly detection</strong> that highlights unusual market behavior</li><li><strong>Insider trading activity</strong> to spot where management or major holders are acting</li><li><strong>SEC filings and company fundamentals</strong> to add business context to price action</li><li><strong>Treasury and macro data</strong> to understand the broader regime around a trade</li><li><strong>Ticker-level research views</strong> that combine multiple layers of context in one place</li></ul><p>The point is not to replace your judgment. The point is to improve it.</p><p>A good market workflow should help you move from <strong>“there is too much information”</strong> to <strong>“these are the 5 things worth paying attention to right now.”</strong></p><p>That is the role Empirical Markets is designed to play.</p><h3>Why AI alone is not enough</h3><p>“AI for markets” has become a very crowded category, and a lot of it sounds the same.</p><p>Everyone promises smarter trades. Everyone promises predictions. Everyone promises an edge.</p><p>But market intelligence is not just about asking a model for a direction. In practice, useful market work is usually a combination of:</p><ol><li><strong>A predictive signal</strong></li><li><strong>A framework for interpreting it</strong></li><li><strong>Supporting context around why it may matter</strong></li><li><strong>A way to evaluate whether it has been useful</strong></li></ol><p>That is the philosophy behind Empirical Markets.</p><p>The AI side of the platform is important, but it is only one layer. A model output by itself is rarely enough. What matters is whether that output can be combined with things like:</p><ul><li>market structure</li><li>anomaly signals</li><li>volatility context</li><li>insider behavior</li><li>macro backdrop</li><li>and company-specific developments</li></ul><p>That is when a signal becomes interesting.</p><p>A bullish model output on its own is just a number. A bullish model output <strong>alongside unusual capital flow behavior, improving relative strength, supportive macro conditions, and no obvious fundamental red flags</strong> is much more compelling.</p><p>Empirical Markets is built around that second idea.</p><h3>A platform for both traders and builders</h3><p>One of the things I wanted to avoid was forcing users into a single workflow.</p><p>Some people want a research interface. Some want a dashboard they can check every day. Some want an API they can plug directly into their own systems.</p><p>So Empirical Markets supports both.</p><h3>If you are a trader or analyst</h3><p>The application is designed to help you:</p><ul><li>monitor the broader market environment</li><li>identify unusual setups across a large universe of tickers</li><li>drill into individual names with more context</li><li>combine AI signals, quant anomalies, technical context, insider activity, and filings in one workflow</li><li>spend less time tab-hopping and more time evaluating actual opportunities</li></ul><p>The goal is not just “more data.” It is <strong>faster trade discovery and better filtering</strong>.</p><h3>If you are a quant, developer, or builder</h3><p>The API gives you programmatic access to the same broader ecosystem of market intelligence:</p><ul><li>historical market data</li><li>fundamentals</li><li>insider data</li><li>macro and Treasury data</li><li>AI-powered outputs and signal layers</li></ul><p>That matters if you are building:</p><ul><li>your own dashboards</li><li>research pipelines</li><li>screening systems</li><li>internal tools</li><li>or trading workflows that need more than just OHLCV</li></ul><p>A lot of products make you assemble this stack from multiple vendors. <a href="https://empiricalmarkets.com/">Empirical Markets</a> is designed to reduce that integration burden and give you a more unified foundation.</p><h3>What Empirical Markets is actually trying to do</h3><p>At a high level, I think of Empirical Markets as solving three jobs.</p><h3>1) Help you understand the market environment</h3><p>Markets are not just collections of individual tickers. They are systems shaped by rates, liquidity, macro releases, sector rotations, positioning, and regime shifts.</p><p>If you are only looking at a single chart, you are often missing the context that determines whether a signal matters.</p><p>That is why Empirical Markets includes macro, Treasury, and broader market intelligence tools alongside ticker-level analysis. A setup in a risk-on liquidity environment is not the same as a setup during a defensive unwind or a rate shock. The surrounding context changes the trade.</p><h3>2) Help you find where something unusual is happening</h3><p>This is where signal generation matters most.</p><p>There are thousands of tickers and only so much attention to go around. You need a way to narrow the field. The most useful systems are not the ones that tell you to look at everything — they are the ones that help you identify <strong>where something abnormal, asymmetric, or statistically interesting may be happening.</strong></p><p>That is why Empirical Markets emphasizes:</p><ul><li>AI signals</li><li>quant anomalies</li><li>capital flow and activity-based insights</li><li>screeners and signal-driven discovery workflows</li></ul><p>The goal is to help you find the names worth investigating before the move is obvious to everyone else.</p><h3>3) Help you do deeper work on the names that matter</h3><p>Once a ticker is on your radar, the next question is whether it deserves capital.</p><p>That requires more than a single indicator. You want to understand:</p><ul><li>how price is behaving</li><li>whether the move is confirmed by broader signal layers</li><li>whether insiders are active</li><li>whether there are fresh filings or company developments</li><li>how the setup fits into the macro backdrop</li><li>and whether the trade thesis still makes sense if the market regime changes</li></ul><p>Empirical Markets is built to make that second stage easier too.</p><h3>Why “market intelligence” is the right frame</h3><p>I don’t think of Empirical Markets as just a market data product, and I don’t think of it as a pure AI product either.</p><p>The better framing is <strong>market intelligence</strong>.</p><p>That means taking raw market information and organizing it into a workflow that helps people:</p><ul><li>prioritize attention</li><li>generate ideas</li><li>evaluate setups</li><li>and make better decisions with more context</li></ul><p>There is a big difference between <em>having data</em> and <em>having a useful view</em> of the market.</p><p>A spreadsheet of insider transactions is data.<br>A chart is data.<br>A list of earnings dates is data.<br>A probability score from a model is data.</p><p>Intelligence is what happens when those things are combined in a way that improves judgment.</p><p>That is what I want Empirical Markets to be.</p><h3>Who should use Empirical Markets?</h3><p>Empirical Markets is a good fit if you are any of the following:</p><h3>Active traders</h3><p>If you want a better way to find setups, track market conditions, and research names beyond basic chart patterns, Empirical Markets is designed for exactly that use case.</p><h3>Quant-minded investors</h3><p>If you care about signals, anomalies, regime context, and systematic ways of narrowing the opportunity set, the platform gives you a more structured research workflow than most retail tools.</p><h3>Developers and quants</h3><p>If you are building your own research stack, dashboards, or trading infrastructure, the API gives you a unified way to access market intelligence inputs without sourcing every category from a different vendor.</p><h3>People who are tired of noisy financial content</h3><p>If you are not interested in hype, hot takes, or generic “AI stock picks,” and you would rather work from actual signals and supporting evidence, <a href="https://empiricalmarkets.com/">Empirical Markets</a> will probably feel more useful than most finance content products.</p><h3>What I care about building</h3><p>I did not build Empirical Markets to produce more market noise.</p><p>I built it because I think there is room for a product that is:</p><ul><li><strong>more data-driven than financial media</strong></li><li><strong>more integrated than a collection of standalone APIs</strong></li><li><strong>more signal-oriented than a generic charting platform</strong></li><li><strong>and more practical than “AI” products that stop at a prediction score</strong></li></ul><p>The ambition is straightforward:</p><p>Build a platform that helps traders, investors, and developers <strong>find better opportunities, understand them faster, and make decisions with more context.</strong></p><p>That is the standard I want Empirical Markets to meet.</p><h3>If that sounds useful, try it</h3><p>If your current market workflow involves bouncing between charts, filings, macro dashboards, social media, and multiple APIs just to form a single view, Empirical Markets was built for you.</p><p>If you want a more unified way to combine:</p><ul><li><strong>AI signals</strong></li><li><strong>quant anomalies</strong></li><li><strong>macro context</strong></li><li><strong>insider activity</strong></li><li><strong>fundamentals</strong></li><li><strong>and deeper ticker-level research</strong></li></ul><p>then give Empirical Markets a try.</p><p>The entire point of the platform is to help you cut through noise and focus on what matters.</p><p>Because in markets, the edge is rarely having access to <em>more</em> information.</p><p>It is being able to recognize the <strong>right</strong> information, at the <strong>right time</strong>, in the <strong>right context</strong>.</p><p>That is what Empirical Markets is trying to help you do.</p><p>Available for free today: <a href="https://empiricalmarkets.com/">empiricalmarkets.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11bb48040e10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding High-Probability Trades with Empirical Markets]]></title>
            <link>https://trevormcguire.medium.com/finding-high-probability-trades-with-empirical-markets-a68a9f31eef1?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a68a9f31eef1</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 20:35:25 GMT</pubDate>
            <atom:updated>2026-04-23T14:43:06.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0YgifNoxtNsrJKq-iDcPQ.png" /></figure><p><a href="https://empiricalmarkets.com/">Empirical Markets</a> is a market intelligence platform that combines AI-driven signals, quantitative anomaly detection, sentiment analysis, SEC filings, insider activity, and price data across 1,000+ tickers.</p><p>This post walks through a systematic workflow for identifying high-probability opportunities — starting with market-level signals and narrowing down to ticker-level analysis.</p><p>The only prerequisite is to <a href="https://empiricalmarkets.com/register">create an account</a>, which is <strong>free</strong>. In an effort to fight bots, you will also need to verify your email.</p><p>Once logged in, you’ll be directed to the <strong>Markets Intelligence Platform</strong>, which is organized into two layers:</p><ul><li><strong>Market-level tools</strong> for discovering opportunities</li><li><strong>Ticker-level tools</strong> for in-depth analysis</li></ul><p>We’ll begin with the market-level view, which surfaces potential trade candidates.</p><p>The market-level data spans 4 tabs, each serving a distinct purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2o-FLm0u1yRrIBQdtrS2A.png" /></figure><h3>Reading the Market Risk Profile</h3><p>On the <strong>Overview</strong> tab, you’ll find the <strong>Market Risk Profile</strong>, which is an interactive scatter plot of <strong>alpha</strong> <strong><em>(α)</em></strong> vs <strong>beta <em>(β)</em></strong> for 900+ tickers.</p><p>If you’re not familiar with these terms:</p><ul><li><strong>Beta (β):</strong> measures a stock’s sensitivity to movements in the overall market (systematic risk)</li><li><strong>Alpha (α):</strong> measures how much a stock outperforms or underperforms its expected return given its beta</li></ul><p>These concepts come from the Capital Asset Pricing Model (CAPM), which can be summarized as:</p><blockquote><em>Expected Return = Risk-Free Rate + β × (Market Return − Risk-Free Rate)</em></blockquote><h3>Alpha Interpretation</h3><ul><li><strong>α &gt; 0</strong> → the stock is outperforming its expected return</li><li><strong>α &lt; 0</strong> → the stock is underperforming its expected return</li></ul><h3>Beta Interpretation</h3><ul><li><strong>β &gt; 1</strong> → the stock amplifies market movements</li><li><strong>β = 1</strong> → the stock moves with the market</li><li><strong>0 &lt; β &lt; 1</strong> → the stock follows the market, but more gently</li><li><strong>β ≈ 0</strong> → the stock moves largely independently of the market</li><li><strong>-1 &lt; β &lt; 0</strong> → the stock moves opposite the market, but less aggressively</li><li><strong>β ≤ -1</strong> → the stock moves opposite the market and amplifies those moves</li></ul><p>So, <strong>beta (β)</strong> captures both the <strong>strength</strong> and <strong>direction</strong> of a stock’s relationship to the market. And together, <strong>alpha (<em>α)</em></strong> and <strong>beta (β)</strong> tell us whether a stock’s <strong><em>reward</em></strong> is worth its <strong><em>risk.</em></strong></p><p>Each point on the plot represents a ticker. Hovering over a point reveals the ticker, and clicking it opens the <strong>Ticker Intelligence Dashboard</strong>, where you can perform a deeper analysis (covered later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWiUrOR75Xt2e5TeSL53cA.png" /></figure><p>As mentioned in the panel’s description, the individual points are color-coded based on their current <strong>alpha</strong> (their excess return). As a rule of thumb:</p><ul><li>The more green a stock is, the more it is outperforming</li><li>The more red a stock is, the more it is underperforming</li></ul><p>To effectively use this tool, you need to decide what type of exposure you’re looking for. First, ask:</p><blockquote><strong>Do you want market exposure, or independence from the market?</strong></blockquote><ul><li>If you want stocks that move largely independently of the market, focus on names with <strong>β ≈ 0.</strong></li><li>If you want exposure to the market, look at stocks with larger absolute <strong>beta</strong> values.</li></ul><p>If you do want market exposure, the next question is:</p><blockquote><strong>Do you want to amplify market movements, or dampen them?</strong></blockquote><ul><li>For <strong>amplified exposure</strong>, look to the right side of the plot <strong>(β &gt; 1)</strong></li><li>For <strong>dampened exposure</strong>, focus on stocks with <strong>0 &lt; β &lt; 1</strong></li></ul><p>Finally, the left side of the plot <strong>(β &lt; 0)</strong> highlights a class of stocks that tend to move <strong><em>opposite</em></strong> the market. Note that strongly negative beta (<strong>β &lt; -1</strong>) represent stocks that amplify this inverse behavior.</p><p>Once you’ve identified the type of exposure you want, the final step is positioning:</p><ul><li>If you’re looking for <strong>longs</strong>, focus on stocks with <strong>high alpha</strong> (green)</li><li>If you’re looking for <strong>shorts</strong>, focus on stocks with <strong>low alpha</strong> (red)</li></ul><p>The goal is to align market exposure <strong>(beta)</strong> with performance <strong>(alpha)</strong>, in order to find stocks that behave the way you want.</p><p>Of course, <strong>alpha</strong> and <strong>beta</strong> are not static — they evolve over time, and shifts in market regimes can change these relationships. But in the absence of perfect foresight, <strong>CAPM</strong> provides a practical framework for evaluating how risk is being rewarded.</p><h3>AI Signals: High-Probability Predictions</h3><p>The <strong>AI tab</strong> is split into two views: <strong>Events</strong> and <strong>Sentiment</strong>.</p><p>The <strong>AI Events</strong> view highlights high-confidence predictions across 1,000+ tickers, spanning equities and ETFs. Each prediction set is generated by a different model, with each model trained to identify a specific type of outcome.</p><p>Tickers appear within a panel when the model assigns a <strong>high probability</strong> to that event. As a result, these signals are <strong>filtered for strength</strong>, surfacing only the most confident opportunities at a given point in time.</p><h4>Example: High Reclaimed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35Ul0mGiLmAp2HkL4zOzfQ.png" /></figure><p>The <strong>High Reclaimed</strong> model predicts whether a stock will recapture recent highs. In practical terms, tickers shown here have a significant probability of upward movement.</p><h4>Example: Downside Risk Elevated</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-M57cAdwtsmp6p3xatIODw.png" /></figure><p>Another model, <strong>Downside Risk Elevated</strong>, identifies tickers with a high probability of downside movement — making them potentially risky for long positions.</p><p>This model, along with its counterpart <strong>Upside Risk Elevated</strong>, explicitly accounts for volatility. As a result, these signals tend to appear less frequently, but are often more selective.</p><h4>Model Evaluation &amp; Metrics</h4><p>Each prediction includes evaluation metrics that can be viewed by hovering over a ticker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40Evyzwp3E3DHPnLIn5ZwA.png" /></figure><p>For example, hovering over $ETR reveals a precision of <strong>75.9%</strong> for the predicted event. This metric is calculated on a <strong>hold-out test dataset (</strong>data the model never saw during training) spanning over multiple years and all covered tickers.</p><p>To prevent data leakage, evaluation is performed using <strong>time-based splits</strong>, ensuring that only past data is used to predict future outcomes.</p><p>Some models provide additional metrics. For instance, the <strong>Bullish Pattern Detected</strong> model includes forward return statistics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9e0WScBjkBpLnAlkAYu6Cw.png" /></figure><p>All reported metrics are derived from out-of-sample data. Over time, these metrics will be standardized across models.</p><h3>How to Use AI Signals</h3><p>These signals are best used as a <strong>starting point for exploration</strong>, not as standalone decisions.</p><p>The goal is not to follow signals blindly, but to identify where the models see <strong>asymmetric opportunities</strong>.</p><p>When using this view:</p><ul><li>Look for <strong>clusters</strong> (e.g., multiple semiconductors appearing together)</li><li>Cross-reference with the <strong>Market Risk Profile</strong> to understand exposure</li><li>Click into tickers to analyze price action, supporting signals, technicals, correlations, filings, and insider activity</li></ul><h4>Important Considerations</h4><p>As with any model-driven signal, outcomes are not guaranteed. Market conditions evolve, and probabilities may not fully capture sudden shifts in regime or sentiment.</p><p>However, by focusing on <strong>high-probability events</strong>, this view is designed to surface the most actionable opportunities identified by the models at any given time.</p><h3>Quant Signal Anomaly Detection</h3><p>The <strong>Quant tab</strong> aggregates signals derived from cross-sectional methods. These are not predictions, but <strong>measurements of unusual activity</strong> within the market. One of the most useful of these signals is <strong>Flow Ratio.</strong></p><p>Flow Ratio measures how much capital is flowing into or out of a stock relative to both the broader market and the stock’s own history. It allows you to quickly identify when a stock is experiencing <strong>unusually concentrated trading activity</strong>.</p><p>A <strong>high flow ratio (e.g., 3σ, 5σ, 7σ)</strong> indicates that significantly more capital is flowing into the stock than normal — providing a direct view into where liquidity is concentrating in the market.</p><p>If you’re a <em>“follow the money”</em> type of trader, then flow ratio is an indispensable tool.</p><p>Extreme flow ratio values are rare by definition, which is what makes them useful for surfacing unusual market behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBvbJiDLrXQ2-RCl1nftyw.png" /></figure><p>Flow Ratio is best used as a discovery and confirmation tool:</p><ul><li>Identify stocks with <strong>extreme values (high σ)</strong></li><li>Look for <strong>clusters within sectors or themes</strong></li><li>Combine with AI events and price analysis to determine whether flow is <strong>supporting or diverging from the trend</strong></li></ul><p>Because flow ratio is agnostic to direction, it can be used in both bullish and bearish contexts.</p><h3>Ticker Level Intelligence</h3><p>After identifying opportunities using the Market Risk Profile, AI Signals, or Quant indicators, you can click any ticker to navigate to the <strong>Ticker Intelligence Dashboard</strong>. This is where the workflow shifts from <strong>discovery to in-depth analysis</strong>.</p><p>At the center of the dashboard is the price chart, which can be enhanced with overlays from three categories:</p><ul><li><strong>AI Signals</strong></li><li><strong>Quant Anomalies</strong></li><li><strong>Technical Indicators</strong></li></ul><p>Users familiar with technical analysis will feel at home here. AI signals and quant anomalies are presented in a similar visual format, allowing you to layer multiple signals directly onto price. These layers can be combined to build higher-conviction setups through cross-validation.</p><h3>AI Signal Overlays</h3><p>AI overlays plot model-generated events directly on the price chart. Current signals include:</p><ul><li>High Reclaimed <em>(bullish)</em></li><li>Low Reclaimed <em>(bearish)</em></li><li>Upside Risk Elevated <em>(bullish)</em></li><li>Downside Risk Elevated <em>(bearish)</em></li><li>Bullish Pattern Detected <em>(bullish)</em></li></ul><p>These are <strong>discrete events</strong>, marking points in time where the model identified a high-probability setup. As additional models are deployed, more prediction sets will be added.</p><p>Because these signals can be layered, you can effectively build an <strong>ensemble of model outputs</strong>.</p><p>As an example, consider Toyota (<strong><em>$TM</em></strong>) with multiple overlays enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzyCdVCWXFACGPy-pq5w-A.png" /></figure><p>Combining signals in this way allows you to construct a multi-signal view of the market:</p><ul><li>cross-validate individual predictions</li><li>see how signals align with price turning points</li><li>visually evaluate historical model performance</li></ul><h3>Quant Anomaly Overlays</h3><p>In addition to AI signals, you can overlay quant anomalies such as <strong>Flow Ratio (capital flow anomalies)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUo_FmZdSl0KEGLUl4944Q.png" /></figure><p>This adds another dimension to the analysis:</p><ul><li>Is a buy signal followed by unusually large capital inflow?</li><li>Does a flow anomaly precede a reversal?</li></ul><p>These signals help reveal underlying activity that may not be obvious from price alone.</p><h3>Technical Overlays</h3><p>Traditional technical indicators can also be layered onto the chart. For example, below is the same chart with Bollinger Bands and a 20-day EMA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4s1e8mDqK0UVkl83ZbDP3g.png" /></figure><h3>Combining Signals</h3><p>The real strength of the dashboard comes from combining these layers.</p><p>Instead of relying on a single signal, you can:</p><ul><li>validate AI signals with quant anomalies</li><li>confirm trends with technical indicators</li><li>identify alignment, or divergence, across signals</li></ul><p>This multi-layered approach helps separate noise from meaningful signals.</p><h3>Cross-Asset Similarity</h3><p>The dashboard also includes a <strong>Cross-Asset Similarity</strong> view, which highlights securities with similar price behavior.</p><p>This is useful for:</p><ul><li>identifying peer groups or substitutes</li><li>understanding sector or macro exposure</li><li>spotting divergences between related assets</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yev3gVct6deCKiTGCodvKA.png" /></figure><p>For example, in the case of <strong><em>$TM</em></strong>, we can see that <strong><em>$VIK</em></strong>, <strong><em>$VEA</em></strong>, <strong><em>$URA</em></strong>, and others have exhibited similar behavior. However, <strong><em>$TM</em></strong> has lagged this group, suggesting <strong>relative weakness compared to its peers</strong>.</p><p>This allows you to move beyond single-ticker analysis and evaluate performance <strong>in a broader market context</strong>.</p><h3>Fundamentals</h3><p>The <strong>Fundamentals</strong> section provides a snapshot of the company’s financial position, including:</p><ul><li>earnings (EPS)</li><li>net income</li><li>shareholders’ equity</li><li>retained earnings and cash</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XgRaDVUKv2MAr8-oqW-dA.png" /></figure><p>These metrics serve as a baseline layer for analysis. While price and signals reflect market behavior, fundamentals help answer a different question: <strong><em>“Is this behavior supported by the underlying business?”</em></strong></p><p>For example:</p><ul><li>Strong price momentum with weak earnings may suggest <strong>speculative movement</strong></li><li>Improving financials alongside bullish signals can reinforce <strong>longer-term conviction</strong></li></ul><p>Looking ahead, the platform will expand the fundamentals layer significantly — allowing you to explore a broader set of fundamental metrics over time, as well as incorporate <strong>model-driven forecasts and predictions</strong> on fundamental data.</p><h3>Insider Activity &amp; SEC Filings</h3><p>Beyond price and model-driven signals, the dashboard also provides visibility into <strong>insider activity</strong> and <strong>recent SEC filings</strong> — offering a direct link to real-world corporate behavior.</p><h4>Insider Transactions</h4><p>The <strong>Insider Transactions</strong> view tracks buying and selling activity by company insiders over time. Take, for instance, the insider activity for <strong><em>$AMD</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezSYTGBL4g4USwVfnwWkyA.png" /></figure><p>This can provide additional context around price action. In the case of <strong><em>$AMD</em></strong>, we can see consistent insider selling activity over time, with occasional spikes. This doesn’t necessarily imply a directional view on the stock, but it does highlight periods of <strong>increased insider activity</strong>, which can be useful when analyzed alongside price and model signals.</p><p>It should be noted that the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a> also offers anomaly detection for insider trades. This will soon be available as another overlay to plot directly on top of price, allowing you to directly align unusual levels of insider trading.</p><h4>Recent Filings</h4><p>The <strong>Recent Filings</strong> section provides direct access to the latest SEC disclosures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQfwpmJCPy06zA07HmbUag.png" /></figure><p>Each entry includes the filing date, form type, and a direct link to the filing (the <strong>view</strong> button). This allows you to move seamlessly from quantitative analysis to primary source documents. Filings are often the source of new information before it is fully reflected in price.</p><p>Together, these layers connect signals, price action, and real-world activity, ultimately allowing you to move from idea generation to fully informed decision-making.</p><h3>Trading with an Edge</h3><p>Better trades come from better information — and better ways of interpreting that information. At its core, trading is a game of probabilities, where long-term success depends on consistently putting the odds in your favor.</p><p>Empirical Markets is designed to do exactly that: surface where the most compelling opportunities exist, and provide the tools to validate them from multiple angles. Many of the AI models output probabilities directly, giving you a measurable sense of confidence behind each signal, rather than relying on intuition alone.</p><p>By combining model-driven signals, quantitative anomalies, price action, and fundamental context, the platform helps you move beyond guesswork. Instead of reacting to noise, you’re working with aligned signals and data — allowing you to act with greater clarity, discipline, and edge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a68a9f31eef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking Capital Flow in the Stock Market]]></title>
            <link>https://trevormcguire.medium.com/tracking-capital-flow-in-the-stock-market-5224eb2a9f1c?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5224eb2a9f1c</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 18:15:58 GMT</pubDate>
            <atom:updated>2026-04-17T18:15:58.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rUB8E7z66JIXB_j_USG_w.png" /></figure><p>While analyzing a stock’s price action is useful for identifying trends, it does not provide the full picture of how capital is moving through the market. Price reflects where a stock has traded, but not the intensity of participation behind those moves. Some securities make large price moves on relatively ordinary volume, while others see significant capital flow with little change in price. If you focus on price alone, you are missing an important part of the story.</p><p><strong>Flow Ratio</strong> is designed to capture this missing piece of information.</p><p>In this post, we explore flow ratio, a quantitative signal available through the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a>. At a high level, flow ratio measures a security’s dollar volume relative to both the broader market and its own history, helping identify where trading activity is unusually concentrated on a cross-sectional basis.</p><h3>Flow Ratio</h3><p>Because information is distributed unevenly across the market, many traders try to “follow the money” under the assumption that unusual trading flow may reflect informed positioning.</p><p><strong>Flow Ratio</strong> builds on this idea by contextualizing a stock’s trading activity. Rather than focusing on raw volume alone, it highlights when a security is absorbing an unusually large share of market-wide trading activity relative to its own baseline. While this does not confirm the presence of informed buying or selling, it surfaces periods where market participation is unusually concentrated — making those moments worth closer inspection.</p><p>With the intuition behind flow ratio in place, we can now move from concept to implementation. Using the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a>, we will fetch historical Flow Ratio values alongside price data, merge the two series, and then visualize how unusual trading flow evolves through time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHBw8dkIr6WvSU7pLnXNmQ.png" /></figure><p>One thing that should stand out to you is that the flow ratio signal exhibits some large spikes. As you will see, this is behavior we can take advantage of.</p><p><strong>Flow Ratio</strong> is expressed as a deviation from the mean, so under a normal distribution we would expect most observations to fall roughly between -2 and 2. In practice, however, market data rarely follows a clean normal distribution, and this signal is no exception. The distribution tends to exhibit a pronounced right tail, with infrequent but significant positive outliers.</p><p>This behavior is expected. Because the signal is designed to capture abnormal bursts of traded dollar flow relative to the market, large spikes correspond to periods where a stock is absorbing a disproportionate share of trading activity. These tail events represent moments of concentrated participation, and they are the primary focus of the analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDvgU08Ru_f3RgDiqDeZiw.png" /></figure><p>We refer to these tail events as <strong>anomalies</strong>. They represent trading sessions where a stock’s trading activity is unusually large relative to the broader market. Using the <a href="https://api.empiricalmarkets.com/">API</a>, we can retrieve these anomalies directly and plot them against price to see how periods of concentrated trading flow align with price action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgL_I_lkV9tuZsOOaUe7mg.png" /><figcaption>$AAPL Flow Ratio Anomalies</figcaption></figure><p>Because flow ratio captures periods of unusually concentrated trading activity relative to the broader market, its behavior can vary across different types of securities and market conditions. To illustrate this, we examine several examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIE-TeVBP2vdluu6VDxlzg.png" /><figcaption>$SPY Flow Ratio Anomalies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CvbPVx4iULtl5ALmOQMpw.png" /><figcaption>$NVDA Flow Ratio Anomalies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTI-fSqryCcNwHgjbsYMfA.png" /><figcaption>$GLD Flow Ratio Anomalies</figcaption></figure><p>From the above images, we can see that flow ratio anomalies tend to align with periods of concentrated capital flow. Their interpretation, however, is regime-dependent. In range-bound markets, anomalies often occur near local extremes and can signal short-term exhaustion and mean reversion. In contrast, during strong trends, anomalies frequently cluster as price advances, reflecting sustained participation and trend acceleration.</p><h3>Conclusion</h3><p>Flow Ratio is useful because it highlights abnormal trading activity within a security relative to both the broader market and its own history. This makes it an effective way to surface names where something unusual may be happening, particularly since price alone does not capture the full picture.</p><p>Flow Ratio does not explain who is trading or why, nor does it constitute a complete trading system on its own. Instead, it provides a structured way to identify periods of unusually concentrated market participation. In practice, this makes it a valuable complement to price analysis, event-driven research, and as an input feature in machine learning models.</p><p>👉 To read the full article (with code), see the original post here: <a href="https://research.empiricalmarkets.com/flow_ratio">https://research.empiricalmarkets.com/flow_ratio</a></p><p><em>The information presented in this analysis is for educational and informational purposes only. It does not constitute financial, investment, or trading advice, and should not be interpreted as a recommendation to buy, sell, or hold any securities. The methods shown in this article are for analysis only and should not be used for live trading. Past performance does not indicate future results.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5224eb2a9f1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Market Regimes, Sentiment Analysis, and the Federal Reserve]]></title>
            <link>https://trevormcguire.medium.com/market-regimes-sentiment-analysis-and-the-federal-reserve-60c7f62aab8a?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/60c7f62aab8a</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 01:54:28 GMT</pubDate>
            <atom:updated>2026-04-15T12:27:25.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TMocKjnQkcMSovjEYOn8w.png" /></figure><p>Market regime detection is usually presented as a black box: some hidden model labels the market as bullish, bearish, or neutral, and you are asked to trust the output. In this post, I want to take a different approach.</p><p>Using sentiment scores derived from Federal Reserve statements and publications, we will build a simple and inspectable regime indicator for sector ETFs. We will show how policy language can be converted into a structured macro signal, and align this with historical prices.</p><p>The <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a> is useful here because it provides both price data and sentiment scores.</p><h3>Sentiment Data</h3><p>The sentiment dataset used here is the fed-market-sectors topic from the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a>. It provides a historical time series of sector-level scores derived from Federal Reserve publications, along with a short reasoning field for each observation. The available dimensions include overall, financials, energy, technology, and other major sectors. The scores are mapped on a discrete scale from strongly bearish (1) to strongly bullish (5).</p><p>This matters because raw macro text is hard to use directly. A score lets us work with the data statistically, while the reasoning field preserves interpretability. This combination is more useful than either one alone: a score without rationale is opaque, but rationale without a structured series is difficult to analyze empirically.</p><p>In this post, the workflow is straightforward. We use the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a> to pull historical sentiment for each sector, align it with the price history of a corresponding ETF, and then build a simple regime detection model.</p><h3>Obtaining Sector Level Sentiment</h3><p>The steps to collect sector-level sentiment are straightforward:</p><ol><li>Authenticate to the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a></li><li>Make a GET request to https://api.empiricalmarkets.com/v1/ai/sentiment/fed-market-sectors to get a list of available <strong>dimensions</strong> (sectors) for the fed-market-sectors sentiment <strong>topic</strong>.</li><li>For each sector, make a GET request to https://api.empiricalmarkets.com/v1/ai/sentiment/fed-market-sectors/dimensions/{sector} to obtain a time series of historical sentiment scores and rationales.</li></ol><h3>Obtaining Historical Prices</h3><p>After collecting the historical sentiment scores for each sector, the next step is to align those scores with historical prices for further analysis. For this, too, we can utilize the <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a> by making some GET requests to the https://api.empiricalmarkets.com/v1/ohlc/tickers/{ticker} endpoint.</p><h3>Exploring the Sentiment Data</h3><p>Before building the algorithm to detect regimes, it helps to inspect the data a bit. A regime model is only as credible as the data going into it. To do this, we’ll join the price data we collected with the sentiment scores.</p><p>This is not meant to prove causality. It is more of a diagnostic step. If the sentiment series is useful for trading purposes, then periods of unusually bearish language should cluster around well-known stress episodes. Conversely, periods of more constructive language should appear during healthier risk environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlkZvV_KAasTAOFWMLn66g.png" /></figure><h3>Interpretable Snapshots</h3><p>One of the more useful features of this dataset is that each observation includes a short reasoning statement. This makes the series easier to validate. Instead of treating the sentiment score as an unexplained label, we can inspect the dates with the most bearish readings and ask whether the explanation matches the macro backdrop.</p><p>For example, the most bearish observation for Financials was during the 2008 crisis, with language centered on tightening credit conditions and deteriorating loan quality. For Technology, the most bearish reading appears during the post-dot-com downturn, with the rationale pointing to weakness in computers, semiconductors, and telecommunications.</p><pre>{&#39;date&#39;: Timestamp(&#39;2008-10-15 00:00:00&#39;),<br> &#39;model_name&#39;: &#39;Newton&#39;,<br> &#39;model_version&#39;: &#39;1.0.0&#39;,<br> &#39;dimension&#39;: &#39;Financials&#39;,<br> &#39;score&#39;: 1,<br> &#39;reasoning&#39;: &#39;Severely tightened credit conditions and deteriorating loan quality across districts pose a significant threat to financial sector stability, indicating a strongly bearish sentiment.&#39;,<br> &#39;score_name&#39;: &#39;Strongly Bearish&#39;}</pre><pre>{&#39;date&#39;: Timestamp(&#39;2001-08-08 00:00:00&#39;),<br> &#39;model_name&#39;: &#39;Newton&#39;,<br> &#39;model_version&#39;: &#39;1.0.0&#39;,<br> &#39;dimension&#39;: &#39;Technology&#39;,<br> &#39;score&#39;: 1,<br> &#39;reasoning&#39;: &#39;The decline in manufacturing activity, particularly in computers, semiconductors, and telecommunications, suggests strong bearish sentiment for the technology sector.&#39;,<br> &#39;score_name&#39;: &#39;Strongly Bearish&#39;}</pre><h3>Sentiment Regime Detection</h3><p>With the raw data validated, we can define a regime model. The goal is not to optimize a trading system. It is to create a transparent state variable that summarizes the policy-language backdrop of the Federal Reserve.</p><p>The pipeline is intentionally simple:</p><ol><li>Smooth the sentiment series with an exponential moving average to reduce one-off noise.</li><li>Standardize the smoothed series with a rolling z-score so that extreme sentiment is measured relative to its own history.</li><li>Label each date as risk on, risk off, or neutral based on a z-score threshold.</li></ol><p>I like this approach because every step is interpretable. There is no hidden classifier, no latent-state estimation, and no optimization routine fitting itself to a specific backtest window. If the model behaves oddly, you can inspect the exact series and threshold that produced the label.</p><p>In the charts below, green shading marks risk on periods, red marks risk off, and gray marks neutral periods. These labels should be interpreted as macro sentiment regimes, not direct buy or sell signals. The main use case is contextual, as it characterizes the backdrop in which price action is unfolding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCMCqC-f95fCCx4e96ZTTQ.png" /><figcaption>Overall Sentiment vs $SPY</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jS0DKxGwXP1Jn1rZ3m7-4g.png" /><figcaption>Financial Sector Sentiment vs $XLF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJcQdWWpfS62nJed5lW8SQ.png" /><figcaption>Energy Sector Sentiment vs $XLE</figcaption></figure><h3>Conclusion</h3><p>Policy language is often treated as something qualitative, subjective, and difficult to use systematically. This analysis shows that it can be turned into a structured, interpretable signal that is useful for regime classification. By combining historical sentiment scores with price data, we can build a transparent framework for identifying when the macro backdrop is becoming more supportive or more adverse.</p><p>The <a href="https://api.empiricalmarkets.com/">Empirical Markets API</a> makes that workflow practical by exposing both historical sentiment scores and the rationale behind them in a format that is easy to query. If you already think in terms of market regimes, this kind of sentiment series is a good complement to price-based or macro-based indicators. And if you are skeptical of text-derived signals, that skepticism is exactly why an interpretable workflow matters: you can inspect the history, challenge the assumptions, and decide whether the signal earns a place in your process.</p><p>👉 To read the full article, see the original post (with code) here: <a href="https://research.empiricalmarkets.com/fed_sentiment_regimes">https://research.empiricalmarkets.com/fed_sentiment_regimes</a></p><p><em>The information presented in this analysis is for educational and informational purposes only.</em> <em>It does not constitute financial, investment, or trading advice, and should not be interpreted as a recommendation to buy, sell, or hold any securities.</em> <em>The methods shown in this article are for analysis only and should not be used for live trading.</em> <em>Past performance does not indicate future results.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60c7f62aab8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tour of the Empirical Markets API]]></title>
            <link>https://trevormcguire.medium.com/a-tour-of-the-empirical-markets-api-9e4672ecdcfb?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e4672ecdcfb</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 18:51:34 GMT</pubDate>
            <atom:updated>2026-04-14T18:52:50.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkL8h807MJG7AFunCsjj2A.png" /></figure><p><a href="https://empiricalmarkets.com/">Empirical Markets</a> is an all-in-one financial data platform built for quantitative researchers, data scientists, and developers.</p><p>Instead of stitching together data from a dozen different providers, it gives you a single, consistent interface to a full financial data ecosystem — covering market data, company fundamentals, macroeconomic indicators, Federal Reserve operations, insider activity, and more.</p><p>But what makes it different isn’t just the data.</p><p>At the core of the platform is a suite of proprietary <strong>AI-powered predictions and signals</strong>, designed to surface actionable insights that traditional data providers simply don’t offer. These models are continuously evaluated and updated, with transparent performance metrics available.</p><p>The platform consists of two parts:</p><ul><li><a href="https://api.empiricalmarkets.com/">a <strong>REST API</strong></a> for programmatic access to market data, AI predictions, and signals</li><li><a href="https://empiricalmarkets.com/">a <strong>web-based UI</strong></a> for exploring that data to find high-probability trades</li></ul><p>Whether you’re building models, running backtests, analyzing markets, or exploring new ideas, both are powered by the same underlying data and infrastructure.</p><p>The key advantage is simplicity: you can query a wide range of financial data domains through a <strong>single unified API</strong>, with consistent schemas and endpoints — rather than managing multiple vendors, formats, and integrations.</p><p>This post serves as a “welcome guide” to <a href="https://api.empiricalmarkets.com/">the API</a>, demonstrating what it can do and how to start using it.</p><p>We’ll cover:</p><ul><li><strong>Market data</strong>: prices, technical indicators, and quant signals</li><li><strong>AI predictions</strong></li><li><strong>Sentiment Analysis</strong></li><li><strong>SEC Filings</strong> and F<strong>undamentals</strong></li><li><strong>Macroeconomic data</strong></li><li><strong>Federal Reserve activity</strong></li><li><strong>Insider trading</strong></li><li><strong>Anomaly Detection</strong></li></ul><p>👉 For the full walkthrough (including complete code examples), see the original post here:<br><a href="https://research.empiricalmarkets.com/api_welcome_tour">https://research.empiricalmarkets.com/api_welcome_tour</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e4672ecdcfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Patterns With Self-Organizing Maps]]></title>
            <link>https://trevormcguire.medium.com/finding-patterns-with-self-organizing-maps-08015c73605f?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/08015c73605f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 03:43:53 GMT</pubDate>
            <atom:updated>2024-11-05T03:46:09.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tt2j-3vYzRQsxE3Bq3nm1A.gif" /></figure><p>The <em>Self-Organizing Map</em> (<strong><em>SOM</em></strong>) is an unsupervised learning algorithm developed in the 1980s by Teuvo Kohonen (for this reason, it is also known as the <em>Kohonen map</em>). It is primarily useful for finding patterns in high-dimensional data. In a nutshell, the algorithm works by mapping data to a lower dimensional space, while also preserving the data’s topology.</p><p>Usually, the result is two-dimensional or three-dimensional. The reason for this is so that the results can be visualized in a way that (us) humans can understand.</p><p>Although SOMs are often said to perform <strong><em>dimensionality reduction</em></strong>, this term can be somewhat misleading. In contrast to techniques like Principal Component Analysis (<strong><em>PCA</em></strong>), which directly reduce the number of features, SOMs <strong>fully retain</strong> the dimensionality of the feature space. Instead, they arrange the data into a lower-dimensional structure that makes patterns more apparent.</p><p>Under the hood, the algorithm utilizes a randomly-initiated neural network that is assembled into a grid. The size of this grid is a user-defined parameter. Each element in the grid is called a <strong><em>node</em></strong> (or <strong><em>neuron</em></strong>), and each node has a vector of weights associated with it. The size of the weight vector is equal to the dimensionality of the input data.</p><p>For example, let’s say our dataset consists of 30,000 samples, where each sample has 128 features associated with it. If we choose to assemble a 10x10 grid, then we will have 100 nodes, each with an associated vector of 128 floating point numbers. As mentioned before, these floating point numbers will start out as random. And throughout the course of training, they will be adjusted in a way that represents the dataset in question. The result can be thought of as a 100-point “summary” of our 30,000-point dataset.</p><p>It should be noted that the terminology associated with SOMs conflict a bit with traditional neural nets. For instance, a “neuron” usually refers to a single computational unit (a single value in a weight vector). In SOMs, however, a neuron refers to an element on the grid, and thus is represented by an entire weight vector.</p><p>In order to train, SOMs utilize something called <strong><em>competitive learning</em></strong>. In this class of learning algorithms, neurons fight for the right to “activate”. And the way neurons “compete” is through their similarity to a given input. In other words, the more similar a node is to the input data, the more it responds.</p><p>There are many ways to score similarity. For this post, we will use euclidean distance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*ypqcMtLWUa-ivXzyPSzhJg.png" /></figure><p>During training, neurons will learn to respond to inputs with certain properties. Whether a neuron responds or not is based on how similar it is to the input. The node with the weight vector that is most similar to the input is called the <strong><em>Best Matching Unit (BMU)</em></strong>. The weights of the BMU, and its nearest neighbors, are adjusted <strong>towards</strong> the input vector.</p><p>To govern which nodes are nearest to the BMU, we use something called a <strong>neighborhood function</strong>. This function will score nodes based on their proximity to a radius surrounding the BMU. The size of the radius decreases with time, so that the weight updates gradually become more and more localized. It is common to use a <a href="https://en.wikipedia.org/wiki/Gaussian_function">Gaussian</a> neighborhood function, but there are many to choose from.</p><p>Lastly, the adjustment also considers a learning rate, which decays over time.</p><p>To throw all of this together, let’s define how a node is updated. For a given node <strong><em>v, </em></strong>the<strong><em> </em></strong>rule is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*qzBhqV0w2RdOvCfLmwvSIQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Self-organizing_map">https://en.wikipedia.org/wiki/Self-organizing_map</a></figcaption></figure><p>Here:</p><ul><li><strong><em>W </em></strong>is the weight vector</li><li><strong><em>s</em></strong> is the step (or <em>iteration</em>)</li><li><strong><em>α</em></strong>(<em>s</em>) is the learning rate at step <em>s</em></li><li><strong>D</strong>(<em>t</em>) is the input vector (where <em>t </em>is the index of that vector in the dataset).</li><li><strong><em>u</em></strong> is the index of the BMU</li><li><strong><em>θ</em></strong>(<em>u</em>, <em>v</em>, <em>s</em>) is the <a href="https://en.wikipedia.org/wiki/Neighbourhood_(mathematics)">neighborhood</a> function which gives the distance between the node <em>u</em> and the node <em>v</em> in step <em>s</em>.</li></ul><p>So, a node is updated by taking into account <strong>three</strong> things:</p><ol><li>its proximity to the BMU</li><li>the learning rate</li><li>its distance to (or error against) the input.</li></ol><p>This update rule ensures that the grid self-organizes to capture the structure of the input data. It does this by forcing similar data points to activate nodes nearest to the BMU. Ultimately, after many iterations, this process will form clusters of nodes that preserve the topology of the original data.</p><h3>Building a Self-Organizing Map for Images</h3><p>To see how this works, we will build a Self-Organizing Map to capture the patterns in the MNIST dataset. If you’re not familiar, MNIST consists of 28x28 images of hand-written digits (0 through 9). The goal is usually to classify these images by training a model to predict which digit is present in the image.</p><p>However, for our purposes, the goal will be to utitlize a SOM to visualize the underlying relationships in the dataset.</p><p>To do this, I implemented the SOM algorithm using numpy, trained it on MNIST for 10,000 iterations, and visualized the weights of each node in the grid. Out of curiosity, I tried this for many different grid-sizes. The code can be found <a href="https://github.com/trevormcguire/blog/blob/main/som/SOM.ipynb">here</a>.</p><p>Some results can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBb2sS9KzP0YDEEukiT0dw.png" /><figcaption>10x10 Grid</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*LsiZ0B9vvc4VTYeoiat9rA.png" /><figcaption>12x12 Grid</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MwRntCR_Bdld02mGXFz9Q.png" /><figcaption>15x15 Grid</figcaption></figure><p>In the images above, each box represents a node (or neuron) in the SOM. What you’re looking at here is the actual data inside each node. So, each node learned to represent a portion of the overall dataset. And since MNIST is a dataset of digits, each node resembles a digit.</p><p>It is worth noting how similar nodes are clustered together. The grid has distinctive regions of recognizable digits. For this reason, Self-Organizing Maps can be used as a clustering technique, and are capable of capturing relationships that other algorithms (like K-Means) cannot.</p><p>Moreover, it is interesting to observe how these regions are arranged. For instance, in the <em>15x15</em> grid, the region of <em>0s</em> is near both the region of <em>8s</em> and the region of <em>6s</em>. So, the SOM decided that (from a handwriting perspective) <em>0</em>, <em>6</em>, and<em> 8</em> are all similar. Pretty legit.</p><p>Lastly, as you can see, the grid size (which is a proxy for the number of nodes), directly impacts the resolution of the resulting map. The smaller grids seem to yield fuzzier images (due to <em>fuzzier nodes</em>). Intuition would suggest that the “best” grid size is both problem-dependent and data-dependent.</p><p>So, if you were to ever utilize a SOM, the choice of grid-size would be a key design decision (and would likely require domain knowledge, trial-and-error, or both).</p><p>To improve the results shown above, I increased the number of training iterations to 50,000 on the 15x15 grid. The nodes of the resulting SOM can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVwU6eXVKn_ctkt58kdJtg.png" /><figcaption>15x15 Grid for 50,000 Iterations</figcaption></figure><h3>Final Thoughts</h3><p>Self-Organizing Maps are a pretty cool application of neural networks. Their ability to preserve topology makes them an extremely viable solution for visualizing high-dimensional patterns. This is evident in the MNIST example above.</p><p>However, their usefulness goes beyond this. For instance, if you’ve ever spent time labeling data, you know how much time and effort this requires. Well, it isn’t a stretch to imagine a system that utilizes a SOM to automatically label some of this data based on the distance to the BMU for any given data point.</p><p>Likewise, since SOMs can perform clustering, they also have the ability to highlight data that doesn’t “fit” into any region on the map. This means they can be useful for anomaly detection.</p><p>While we only talked about images in this post, SOMs can be applied to virtually any kind of data. In the future, I plan on exploring this a bit.</p><p>I think it could be interesting to apply SOMs to some NLP problems (clustering word/document embeddings, for example). Moreover, there are several applications in the realm of time series analysis in which I can see this technique being extremely useful.</p><p>Evidently, I’m sure this won’t be my last post on this topic. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08015c73605f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On the Effectiveness of Moving Averages]]></title>
            <link>https://trevormcguire.medium.com/on-the-effectiveness-of-moving-averages-fb31b0c1ab6f?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb31b0c1ab6f</guid>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 04:21:02 GMT</pubDate>
            <atom:updated>2024-06-17T12:16:19.291Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of <em>Technical Analysis</em>, moving averages are commonly used for analyzing price. They are employed by traders for various functions, including:</p><ul><li>Identifying trends</li><li>Finding support and resistance levels</li><li>Generating trade signals</li></ul><p>Despite their widespread use, their effectiveness remains murky. As such, this post aims to answer the following questions:</p><ul><li>Can moving averages produce profitable trading signals?</li><li>Which moving average works best?</li><li>What is the optimal moving average strategy?</li></ul><h3>What is a Moving Average?</h3><p>There are many types of moving averages, and some are more complex than others. However, for our purposes, the most basic type will serve as a good definition. Generally speaking, a moving average is defined as the running mean over some number of previous timesteps. This calculation is often referred to as a <em>Simple Moving Average</em>, or <strong>SMA</strong>.</p><h3>Simple Moving Average (SMA)</h3><p>Not much is known about the origins of the SMA and its relation to finance. This is a testament to how ubiqutous its use has become. However, we do know that the term “moving average” dates back to 1901, and is often credited to English statistician and meteorologist <a href="https://en.wikipedia.org/wiki/Reginald_Hawthorn_Hooker">R.H Hooker</a>.</p><p>As its name suggests, the calculation for the SMA is easy: at any given timestep, add up the prices from the previous <strong><em>N</em> </strong>timesteps and then divide the result by <strong><em>N</em></strong>.</p><p>This is done on a <em>“rolling”</em> basis, so all information beyond <strong><em>N</em></strong> periods ago is lost forever (the same is true for all moving averages). For that reason, most people choose to analyze prices by using several different moving averages simultaneously.</p><p>Further, the SMA has some issues. Namely, it weighs prices from any number of periods ago equally to the most recent price. This creates a <strong><em>lag</em></strong> between the actual price and the moving average values. This lag is a feature of all moving averages. Likewise, many people have come up with ways to reduce the effect of this lag, with hopes to produce better trading signals.</p><h3>Exponentially-Weighted Moving Average (EWMA)</h3><p>Pete Haurlan, who worked for NASA’s Jet Propulsion Labratory (JPL) in the 1960s, is the first known trader to apply exponential smoothing to stock prices. Today, this is commonly referred to as the <em>Exponentially-Weighted Moving Average</em> (<strong><em>EWMA</em></strong>, or sometimes <strong><em>EMA</em></strong> for short).</p><p>Prior to employing EWMA’s for trading stocks, Haurlan applied them in rocketry design. Specifically, he used them in the steering mechanism for rockets, in an attempt to smooth out the calculated error between the rocket’s current and desired trajectories. That being said, even though the calculation for the EWMA is more complex than the SMA, it isn’t exactly rocket science.</p><p>In a nutshell, the EWMA gives more weight to recent prices. For that reason, its values are always closer to the actual price when compared to an SMA of the same look-back period.</p><p>The SMA and EWMA are the two most commen moving averages used to analyze financial markets. Of course, being popular doesn’t mean being useful. Later on in this post, we will determine just how useful they are.</p><p>There are a plethora of other moving average calculations out there. For the purposes of this article, however, we will only use the mainstream ones.</p><h3>Linearly-Weighted Moving Average (LWMA)</h3><p>The <em>Linearly-Weighted Moving Average</em> is similar to the EWMA in that it weighs recent prices more heavily. However, unlike the EWMA, it does so in a linear fashion. That is, the latest price is multiplied by <strong><em>N</em></strong> (Where <strong><em>N</em></strong> is the look-back window) and the earliest price is multipled by<strong><em> 1</em></strong>. The result is then divided by the sum of all numbers <strong><em>1</em></strong> through <strong><em>N</em></strong>.</p><p>Because it weighs prices linearly, it lags more than the EWMA, but less than the SMA.</p><h3>Triangular Moving Average (TMA)</h3><p>The <em>Triangular Moving Average</em> is unique in that it weighs the middle of the look-back window the heaviest. For this reason, it lags a lot more than its counterparts. It is essentially a doubly-smoothed SMA with two different (but related) window sizes. The calculation can be expressed simply as:</p><pre>TMA = SMA(SMA(price, N), N // 2)</pre><p>Above, <strong><em>N</em></strong> is the look-back period. Note that the <strong><em>//</em></strong> operator is performing floor division.</p><h3>Kaufman Adaptive Moving Average (KAMA)</h3><p>The <em>Kaufman Adaptive Moving Average</em>, developed by Perry Kaufman, aims to account for volatility. Later on, we will talk about why this is important. The details of this calculation would take a few paragraphs to write about, and I don’t want to bore you anymore than I already have. Instead, I will provide <a href="https://school.stockcharts.com/doku.php?id=technical_indicators:kaufman_s_adaptive_moving_average">this handy link</a> which lays it out pretty well.</p><h3>Wilder Moving Average</h3><p>Developed by Welles Wilder in 1978, this variation also weighs recent prices more heavily, and is therefore faster than an SMA. Like the Kaufman Adaptive Moving Average, the calculation isn’t worth talking about for our purposes.</p><p>However, what you <strong>should</strong> know is this: Welles Wilder is the person responsible for developing several popular technical indicators; the most popular being the <em>Relative Strength Index</em><strong><em> (RSI)</em></strong>. Naturally, he decided to use his own moving average in those calculations. This is often forgotten by people who write Technical Analysis software.</p><h3>Moving Averages In Practice</h3><p>As mentioned earlier, moving averages can be used in a lot of different ways — from identifying trends to generating trading signals. But, when it comes to generating signals, which moving average works best?</p><p>This question was my motive for writing this article. And to answer it, we must start from the ground up.</p><p>So, to start, we’ll briefly compare the different moving averages just described. To do that, I plotted each of the aforementioned moving averages using <strong><em>$SPY</em></strong> and a window of 50 days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1CtH9ntAGflTwD-9aJ4hA.png" /><figcaption>Demonstration of Different Moving Average Types</figcaption></figure><p>One takeaway from this chart is that the type of moving average you use is important. To demonstrate this, let’s look at an example.</p><p>Shortly after the October 2023 low, we can see that most of the moving averages began to turn upwards — beginning with the <em>KAMA</em>, and followed by the rest. At the time, this should have indicated that the bearish move was losing momentum, thus increasing the risk of a reversal.</p><p>However, as you can see, the Triangular Moving Average (<em>TMA</em>) took nearly two months to reverse its direction. This means that if you were solely depending on the TMA as an indicator of market strength, you would have been very late to the party.</p><p>When it comes to identifying trends, a single moving average might be all we need. For trading signals, however, it is better to use multiple.</p><h3>The Moving Average Crossover Strategy</h3><p>Broadly speaking, a crossover strategy consists of two different moving averages: one <strong><em>faster</em></strong> and one <strong><em>slower</em></strong>. A <strong>bullish</strong> signal is generated when the faster average crosses <strong><em>above</em></strong> the slower one. A <strong>bearish</strong> signal, on the other hand, occurs when the when the faster average crosses <strong><em>beneath</em></strong> the slower.</p><p>The idea behind this is simple:</p><ul><li>The faster average represents the shorter-term trend, while the slower average represents the longer-term trend</li><li>When the faster average crosses beneath the slower, it signals a loss of momentum to the upside, which may lead to a short-term reversal</li><li>Likewise, when the faster average crosses above the slower, it can be interpreted as a loss of momentum to the downside, which could make it easier for the bulls to regain control</li></ul><p>Notice the hesitance in my use of words like <strong><em>could</em></strong> or <strong><em>may</em></strong>. These words reflect the fact that conventional crossover strategies, although tried and tested, aren’t always reliable. We will touch upon a few reasons for this shortly.</p><p>The most common types of crossover strategies usually require a 20, 30, or 50 period window for the faster average, and a 50, 100, or 200 period window for the longer average. However, some people want a more frequent trading signal. Among this group, it is common for a 9 or 10 period window to be used.</p><p>In terms of which moving average to utilize, the <em>SMA</em> and <em>EWMA</em> are the two most common.</p><p>To demonstrate the effectiveness of a moving average crossover strategy, I ran a few tests using the<strong><em> technical-analysis</em></strong> library in python. This is an open-source library I’ve been working on that aims to provide useful utilities for analyzing stock prices. If you’d like to install or contribute, more info can be found here: <a href="https://pypi.org/project/technical-analysis/">https://pypi.org/project/technical-analysis/</a>.</p><p>Below are the returns of an EMA 20/50 strategy (with 20 being the period for the faster average, and 50 being the period for the slower).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*7UXVbwjNlNndrQFDLHgZFQ.png" /></figure><p>This choice of moving average and period is particularly common. As we can see above, it yielded over 175% over ~170 trades.</p><p>However, as previously mentioned, there are many types of moving averages. So, which one works best?</p><h3>Finding the Optimal Moving Average Crossover Strategy</h3><p>The optimal crossover strategy really depends on three things:</p><ol><li>The size of the window</li><li>The type of moving average</li><li>The asset in question</li></ol><p>The “<em>asset in question”</em> is important for several reasons. First, while some assets are highly volatile, others are not. And because prices can undergo heavy swings in volatile environments, it wouldn’t make sense to rely on the same moving average used in calm, stable ones.</p><p>To make matters worse, the volatility of a singular asset, or even the entire market, can rapidly change over time. So, the optimal moving average used for <strong><em>$TSLA</em></strong> 7 or 8 years ago most likely wouldn’t be optimal today. The same can be said for the <strong><em>SPY</em></strong>, <strong><em>BTCUSD</em></strong>, and even the dollar.</p><p>To say this differently, volatility itself is volatile. Benoit Mandelbrot, the famed mathematician, related this concept to <strong><em>market time</em></strong> — which is a phrase he used to describe how trading activity isn’t evenly distributed throughout time. To quote directly from his book, <strong><em>The Misbehavior of Markets</em></strong><em>:</em></p><blockquote>“On occasion, trading is fast. Scores of news items are flitting across the electronic “crawl” on the bottom of the screen. Phones are ringing. Customers are zapping electronic orders. The volume of trades is climbing, and prices are flying by. On such days are fortunes won or lost. Time flies. Then there are the slow times. No news, only tired reports from the in-house financial analysts to chew over. The customers seem to be on holiday. Trading is thin. Prices are quiet. No big money to be made here; might as well go for a long lunch. Time hangs heavy.”</blockquote><p>To find out which moving average type performs best, I performed a search over different combinations of moving average types and window sizes. The results of this experiment can be visualized below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpsoKNBaWweloOSGAM18yA.png" /></figure><p>This chart shows the results of the backtests. The data used was historical <strong><em>$SPY</em></strong> daily data ranging from January 1993 until June 2024. The benchmark for this experiment was the buy-and-hold strategy, which yielded 2,057%.</p><p>From looking at the chart, we can conclude that the best results occured when using longer look-back periods. Logically, this makes sense, as using a shorter window will increase the frequency of trade signals. The increased number of signals is a product of increased noise, so it decreases the trustworthiness of the signal.</p><p>The best performing crossover strategy was the Triangular Moving Average (TMA), which yielded 432% using a 150 day window for the faster average, and a 200 day window for the slower.</p><p>It is important to note that even the top-performing strategy couldn’t beat the buy-and-hold benchmark.</p><p>Of course, some would argue that maybe <em>“beating the market”</em> isn’t the best metric of success. Depending on your risk appetite, there are other things you may want to consider, too. For instance: how long were you exposed in the market? How much money did you risk losing? Ultimately, how “safe” was your money?</p><p>For those who care about risk (which you should), another stat we can interpret is <strong>Maximum Drawdown</strong> (MDD) — which we can define as the performance of the worst losing trade. There are definitely better, more complicated metrics we could look at. But for our purposes, MDD can act as a cheap proxy for how much downside risk we exposed ourselves to.</p><p>Let’s take a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByOXOD5at1oqCUHGZw9wfw.png" /></figure><p>As you can see above, the MDD of crossover strategies generally isn’t great. If you’ve ever lost 15–20% on a trade before, you know how that feels. Yet, there were a few exceptions to this, namely the <em>EWMA</em> and <em>TMA</em> strategies with longer look-back windows.</p><p>The best performing strategy in terms of MDD was the EWMA 100/150. This strategy’s max-drawdown was +24.4%. I should note that this strategy also yielded the second highest return, at 403%. Given this, one could argue that the EWMA 100/150 is a better stratetgy than the TMA 150/200, as your historical risk-of-loss is lesser.</p><p>So, why is it that the best performing strategies (from both a risk-motivated and profit-motivated standpoint) were the ones that utilized longer look-back horizons?</p><p>Well, one reason for this is the fact that a longer lookback yields less frequent trading signals. Likewise, less frequent trading signals could mean more time in the market. And, since <strong><em>$SPY</em></strong> has historically had heavy bias to the upside, spending more time in the market has meant a convergence towards the buy-and-hold benchmark strategy (which yielded over 2,000%).</p><p>From this we can derive a general truth about moving average crossover strategies: the less we trade, the more we’ll profit. Of course, this assumes a bias to the upside, as we see in <strong><em>$SPY</em></strong>.</p><p>We can visualize this below by plotting the the number of trades vs the total return for each EWMA strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*QhMZvYyFSapmFFcql_b5Vg.png" /></figure><p>In the above, you can see I included the line of best fit, which clearly trends downwards. So, as the number of trades increased, the total return decreased.</p><p>To get an overall sense of how the look-back window will affect the number of trades for each moving average type, you can take a look at the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUxwNs1XsfrLXjMTS6Gj1w.png" /></figure><p>To recap:</p><ul><li>The best performing strategy in terms of both MDD and total return was one that used a longer horizon to produce fewer trades.</li><li>Despite the positive max-drawdown associated with the best strategy, its total return was substantially lower than our buy-and-hold baseline.</li></ul><p>So, can we do any better?</p><h3>Multiflavored Moving Average Strategies</h3><p>As previously mentioned, the basic moving average strategy involved two moving averages, one fast and one slow. But who says these two moving averages have to be of the same type?</p><p>To test the effectiveness of strategies consisting of multiple types of moving averages, I performed a grid-search across different periods, moving averages, and combinations thereof. In total, there were 1,128 combinations searched. The results can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*6gwjGMbSsvvhtitWwgkT4w.png" /></figure><p>Note that this chart shows only the top ranked strategies.</p><p>The best performing strategy utilized a 150-day Simple Moving Average for the faster average, and a 200-day Triangular Moving Average for the slower. This strategy yielded a 466% return with a +20% max drawdown. Notably, it also yielded the highest average return, at 93% per trade. Bear in mind though, that only 5 trades were executed.</p><h3>Conclusion</h3><p>Moving averages can be effective tools for risk management. Strategies that employ moving averages can help risk-adverse traders shield themselves from downturns, while still providing sizable upside profits.</p><p>However, the profit returned will be substantially smaller (to put it mildly) than the profit returned from a basic buy-and-hold strategy. Of course, this is assuming that the prices of the underlying asset have upward bias over time, as most major stocks do.</p><p>It is important to note that the volatility of the stock will also affect how well a moving average strategy works. If a stock is bouncing around, range-bound, then shorter-term moving averages will produce a larger number of faulty signals. Longer-term moving averages, however, are more resiliant to noise, and so the number of faulty signals will remain low. This is another reason why the longer term strategies outperformed the shorter-term ones in the results provided here.</p><p>What I’ve shared here only scratches the surface. There are many things we can do improve the moving average crossover strategy; the most important being the underlying moving average used.</p><p>All moving averages are lagged indicators. This is inherent in the math behind them, as we need to use the previous <strong><em>N</em></strong> values to calculate the current value. Ideally, we want to reduce this lag in order to create more signals to profit from. However, there is a trade off between the lag used and the resulting noise of the signal. So, in order to improve this strategy, you need to find ways to optimize the balance between lag and noise.</p><p>In the future, I plan to share some custom moving averages I’ve created that produce significantly better results than the traditional ones decribed here.</p><p>The notebook for this post <a href="https://github.com/trevormcguire/blog/blob/main/technical-analysis/moving_averages.ipynb">can be found here</a>, if you’d like to replicate these results. In the code, you will notice that the <strong><em>technical-analysis</em></strong> library did all the heavy lifting, including the backtesting and strategy creation! If you’d like to install this library, or if you’d like to contribute, check out the links the below:</p><ul><li><a href="https://pypi.org/project/technical-analysis/">https://pypi.org/project/technical-analysis/</a></li><li><a href="https://github.com/trevormcguire/technical-analysis">https://github.com/trevormcguire/technical-analysis</a></li></ul><p>Jupyter Notebook for this post:</p><ul><li><a href="https://github.com/trevormcguire/blog/blob/main/technical-analysis/moving_averages.ipynb">https://github.com/trevormcguire/blog/blob/main/technical-analysis/moving_averages.ipynb</a></li></ul><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb31b0c1ab6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolution and Neural Networks]]></title>
            <link>https://trevormcguire.medium.com/artificial-selection-evolution-and-neural-networks-96cb2b7b9db4?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/96cb2b7b9db4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 03:29:06 GMT</pubDate>
            <atom:updated>2024-08-18T13:52:49.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pw9Du9POt4OlEHoiwxNxlQ.png" /><figcaption>Darwin’s Finches (source: <a href="https://en.wikipedia.org/wiki/Darwin%27s_finches">https://en.wikipedia.org/wiki/Darwin%27s_finches</a>)</figcaption></figure><p>With the recent explosion in the popularity of AI, there has been a ton of focus placed upon the ability of Neural Networks to solve a variety of tasks. From cancer detection to ChatGPT, these blackbox systems can sometimes feel like magic. But under the hood, the power of Neural Networks really boils down to how they’re trained.</p><p>In traditional Deep Learning, Neural Networks are trained using something called <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation</a>, which calculates the gradient of a loss function with respect to the network’s weights. In other words, it determines how much each weight contributed to the error (called the <strong><em>loss</em></strong>).</p><p>Backpropagation is used together with an optimization algorithm that aims to minimize the error. Nowadays, these optimization algorithms are almost always a variant of <strong><em>Stochastic Gradient Descent</em></strong> <strong><em>(SGD)</em></strong>. Perhaps the most common variant is called <a href="https://arxiv.org/pdf/1412.6980.pdf">Adaptive Moment Estimation</a>, commonly referred to as <strong><em>Adam</em></strong>.</p><p>Because these algorithms have been wildly successful in a wide variety of domains, they have become the de-facto way to train a Neural Network. And as a consequence, alternative methods have seemingly been forgotten.</p><p>In this post, we will be exploring one such method — one that takes remarkable influence from the biological processes that created you, me, and every other living thing on this planet.</p><h3>Evolutionary Algorithms</h3><p>Evolutionary Algorithms (to which <a href="https://en.wikipedia.org/wiki/Genetic_algorithm">Genetic Algorithms</a> are a subset) use the principles of natural selection, reproduction, and genetic mutation to solve a given task. Given that these ideas are popularly known, these algorithms tend to be extremely intuitive and easy to implement.</p><p>Like Stochastic Gradient Descent, we can use Evolutionary Algorithms to optimize the parameters (weights and biases) of a neural network. With an Evolutionary Algorithm, the main difference is the fact that we don’t need to calculate the gradients. Of course, the model still completes its forward pass; but, there is no backpropagation involved.</p><p>Instead, Evolutionary Algorithms depend on a <strong><em>population</em></strong> of neural networks (called <strong><em>organisms</em></strong>). The organisms that make up our population live in an <strong><em>environment</em></strong> (commonly referred to as an <strong><em>ecosystem</em></strong>). In this way, an organism is akin to the concept of an <strong><em>agent</em></strong> in Reinforcement Learning.</p><p>The environment produces data, which is used by organisms to make predictions. These predictions are compared to target values to calculate the rewards, which are stored for each member of the population. Then, the environment performs selection by ranking each organism according to the rewards it received. Organisms that received higher rewards are said to have a higher fitness, and are thus given better odds when it comes to reproductive success.</p><p>This reproductive protocol can be best summarized by Herbert Spencer’s phrase, <em>“the survival of the fittest”</em> — which he coined while describing Charles Darwin’s ideas regarding natural selection.</p><p>The organisms that are chosen to reproduce create children, which form the next generation of estimators. The mating process is done by blending the weights and biases of each parent. The easiest way to do this is by giving each parent a 50% chance of success at passing on their genes.</p><p>Lastly, after each child is created, it undergoes <strong><em>random mutation</em></strong>. This is accomplished by adding gaussian noise to the child’s weights, where the amount of noise can be fixed or variable.</p><p>After being randomly mutated, each child is ready to take on its environment, which occurs when the environment once again generates data. This whole process is repeated for some number of <strong>generations</strong> (which is the same concept as <strong><em>epochs</em></strong> in traditional Deep Learning).</p><p>We should pause here, and take a moment to reflect on how the weight updates are performed. In traditional Deep Learning, each weight is updated by calculating its contribution to the loss. In Evolutionary Algorithms, however, the weights are adjusted by randomly replacing 50% of the values with the weights of another network, and then adding in some noise.</p><p>Since the weights of both networks are randomly initiated, this means we are replacing randomness with other randomness, and then finally adding in more randomness as the cherry on top.</p><p>So why does this work? As you probably guessed, the answer is: randomness.</p><p>By chance, the randomness of one network will outperform the randomness of another. And since our environment only allows the best-performing organisms to reproduce, this randomness will eventually converge into a solution.</p><p>The key to all of this is the selection mechanism. It is responsible for choosing which “genes” (weights) survive, and which do not. In nature, selective pressure can come from many things, such as predators or the climate. In this <strong><em>“Artificial Selection”</em></strong>, however, the selection mechanism is a function of fitness, which is calculated by comparing an organism’s predictions to the targets.</p><p>The fitness function is akin to the loss function in traditional Deep Learning. The main difference is that Evolutionary Algorithms tend to optimize through maximization, while traditional Deep Learning tends to optimize through minimization. For this reason, the fitness function can often be a negated version of a traditional Deep Learning loss function.</p><p>With that, let’s take a look at how Evolutionary Algorithms perform on some common Machine Learning tasks.</p><h3>Regression</h3><p>Evolutionary Algorithms can be used for regression tasks by choosing the appropriate selection mechanism. To show this, I trained organisms to approximate a sine curve, with values ranging between -1 and 1. Each organism consisted of a simple neural network with the following architecture:</p><ul><li>Two dense layers with 32 neurons, each followed by ReLU activation</li><li>A final dense layer with 1 neuron, with no activation</li></ul><p>Each organism ingested 128 data points from the environment to produce an equal number of predictions. The fitness function used to evaluate these predictions was negative mean squared error. Finally, the population size was set to 200.</p><p>The results of the best organism after 500 generations can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1TltvNBTZB3ZEiftwBVnw.png" /></figure><p>Not too shabby.</p><p>While not perfect, the best organism was able to approximate the sine curve reasonably well. Of course, estimating the sine function is a rather trivial task. So, in that vein, let’s take a look at a <em>slightly</em> harder problem.</p><h3>Classification</h3><p>To demonstrate how Evolutionary Algorithms can be used for classification, I chose to use the MNIST dataset, which is quite famous in the Machine Learning community. The dataset consists of 60,000 28x28 images of handwritten digits, labeled with an integer in the range 0–9. The goal is to predict which digit is present in the image.</p><p>Below are three different samples from the MNIST dataset. The target data for these three samples are 5, 2, and 1, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*2LNWvEX8pHWpR1dQDLCfEg.png" /></figure><p>I used 70% of the data for training and 30% for testing (evaluation).</p><p>Each organism consisted of:</p><ul><li>A dense layer with 256 neurons, followed by ReLU activation</li><li>A final dense layer with 10 neurons, followed by softmax activation to produce a probability distribution</li></ul><p>Moreover, each member of the population was given 256 randomly selected samples to predict in order to calculate fitness. The fitness function itself was a negated version of categorical cross-entropy, and the population size was 200.</p><p>Evaluation was completed by taking the best performing organism in each generation and calculating its accuracy on the test dataset. The simulation lasted for 900 generations. However, the best performing organism lived in the 820th generation, achieving an accuracy of 78% on the test dataset. The results for each generation can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhdhB66Aw-zKnslVBU1Mfg.png" /></figure><p>This is a pretty low score for MNIST. However, it should be noted that I didn’t spend too much time experimenting, so this result can definitely be improved. For example, we can use a <strong><em>Convolutional Neural Network (CNN) </em></strong>to process the 2D images, rather than using a dense network to process the flattened images.</p><p>Nonetheless, the fact that we were able to achieve 78% with minimal effort gives some credence to the effectiveness of Evolutionary Algorithms.</p><h3>Conclusion</h3><p>Because Evolutionary Algorithms are said to approximate the gradient, they are usually classified as <strong>near</strong>-optimal solutions. They are able to explore a wide range of possibilities, allowing for an increased chance at obtaining optimality.</p><p>To me, Evolutionary Algorithms are extremely interesting. Perhaps I have some user bias, though, considering they mimic the same processes that allow me to exist. Regardless, the fact that a population of randomness can converge towards a solution — through the very familiar processes of selection, reproduction, and mutation — is pretty cool.</p><p>If you’re interested, the code for these experiments can be found here: <a href="https://github.com/trevormcguire/blog/blob/main/neuroevolution/neuroevolution.ipynb">https://github.com/trevormcguire/blog/blob/main/neuroevolution/neuroevolution.ipynb</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96cb2b7b9db4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention, Transformers, and GPT]]></title>
            <link>https://trevormcguire.medium.com/attention-transformers-and-gpt-b3adbbb4a950?source=rss-412745870be9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3adbbb4a950</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Trevor McGuire]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 13:20:49 GMT</pubDate>
            <atom:updated>2023-07-26T16:06:24.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9x29UUbQlZaHMAQl36Dgw.png" /><figcaption>Scaled Dot-Product Attention and Multi-Head Attention, as originally shown in the paper “Attention Is All You Need”</figcaption></figure><p>By now, you’ve surely <a href="https://openai.com/blog/chatgpt">heard of ChatGPT</a>. This model, developed by OpenAI, has changed the game not only in AI circles, but also in the world at large. Within two months of its release, it crossed 100 million active users, making it the fastest-growing consumer application in history.</p><p>As of writing, the model itself is fine-tuned from the GPT-3.5 series, which is a <a href="https://platform.openai.com/docs/model-index-for-researchers">series of language models</a> trained on data from before Q4 2021.</p><p>But, things move fast in the world of AI. Just weeks ago, <a href="https://openai.com/research/gpt-4">OpenAI released GPT-4</a>, which “exhibits human-level performance on various professional and academic benchmarks.” Moreover, OpenAI says that: “GPT-4 is more reliable, creative, and able to handle much more nuanced instructions than GPT-3.5.” In fact, by the time you read this, you’ll probably be able to interact with GPT-4 via the ChatGPT interface (where you can test out their claims out for yourself).</p><p>But what is it about these models that make them so powerful?</p><p>The answer to this is complicated, especially since OpenAI is no longer commited to being “open” (pun intended) about sharing their source code. That being said, we do know the basics; which includes things like the data, the underlying model architecture, and the training procedure.</p><p>In this blog post, we’ll only focus on one of those things — and arguably the most interesting. That is, we’ll discuss the fundamental component of the GPT models: the Transformer architecture.</p><p>Lets start with the name itself: <strong>GPT</strong> stands for <strong><em>Generative Pre-trained Transformer</em></strong>.</p><p><strong><em>“Generative”</em></strong> here tells us that we are dealing with sequences. In the case of the GPT models, these sequences are usually in the domain of natural language. However, this approach can be applied to any type of sequential data.</p><p><strong><em>“Pre-trained”</em></strong> implies the use of tranfer learning. If you’re not familiar with transfer learning, it usually goes like this:</p><ol><li>First, a gigantic, generalized language model is trained on a huge amount of data</li><li>Then, this model is fine-tuned (trained briefly) to perform some specific task.</li></ol><p>Lastly, <strong><em>“Transformer”</em></strong> is referring to the Transformer architecture. This architecture was first introduced in a paper called <em>Attention Is All You Need</em> (2017), which <a href="https://arxiv.org/pdf/1706.03762.pdf">can be found here</a>. This paper has become one of the most consequential (and cited) in the history of AI.</p><p>In this post, we’ll take a closer look at the underlying architecture of the Transformer, and what makes it so powerful.</p><p>The Jupyter notebook version of this post can be <a href="https://github.com/trevormcguire/blog/blob/main/transformer/Attention%2C%20Transformers%2C%20and%20GPT.ipynb">found here</a>.</p><h3>The Attention Mechanism</h3><p>At the heart of the Transformer architecture is the Attention mechanism, introduced in a paper called <a href="https://arxiv.org/pdf/1409.0473.pdf"><em>Neural Machine Translation By Jointly Learning to Align and Translate</em>, by Bahdanau et al</a>. It is a sequence-to-sequence operation; meaning, a sequence of vectors goes in, and a sequence of vectors comes out. So, although originally designed for machine translation, it can be applied to any task involving sequential data.</p><p>There are many variations of Attention, but we’ll be focusing on the flavor defined in <a href="https://arxiv.org/pdf/1706.03762.pdf"><em>Attention Is All You Need</em></a>. Here, the authors define attention in the following way:</p><blockquote>“An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.”</blockquote><p>The attention mechanism described in the paper is called <em>Scaled Dot-Product Attention</em>, and is defined as the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*WhdGyGOqkrA4_IQxFWzt2Q.png" /></figure><p>To make things even more clear, the authors gave us the following image, which shows us the individual operations that make up Scaled Dot-Product Attention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*AXcxC9oCvYfKGK-_6m-MIQ.png" /></figure><p>Let’s briefly focus on each of these operations, and then implement this in code.</p><h4>Step 1: Create the Query, Keys, and Values (Q, K, V)</h4><p>The attention mechanism has 3 inputs: the <strong>query</strong>, the <strong>keys</strong>, and the <strong>values</strong> (denoted as <strong>Q, K,</strong> and <strong>V</strong>, respectively). At this point, the meaning behind these names is not important. What <strong><em>is</em></strong> important, however, is where these values are coming from:</p><p><strong>The query, keys, and values are each a seperate linear transformation of the same exact input.</strong></p><p>This is known as <strong>self-attention</strong>, and is the bedrock of the Transformer architecture.</p><p>So, in order to get (<strong>Q, K, V</strong>), we take our input (<strong>X</strong>) and apply three seperate linear transformations to it. In practice, these “linear transformations” consist of multiplying our input by some weight matrix, <strong>W</strong>.</p><p>Now, in large language models, such as GPT, these inputs are usually the output of an embedding layer. If you’re not familiar with what an embedding layer is, you can think of it as a lookup table, where each word (or sub-word) is mapped to a fixed-sized vector. Throughout the course of training, the values resulting from this mapping are optimized, ultimately creating a rich representation of the underlying text.</p><p>As such, take a look at the below (crude) code example, which processes and embeds a sentence by doing the following:</p><ol><li>splitting it into words</li><li>assigning each word a unique integer value</li><li>mapping that integer value to a fixed-size vector.</li></ol><pre>from typing import List<br><br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>np.random.seed(42)<br><br>sentence = &quot;The New York Rangers beat the Pittsburgh Penguins last night&quot;<br><br>words = sentence.lower().split()<br><br>int2word = {k: v for (k, v) in enumerate(set(words))}<br>word2int = {v: k for (k, v) in int2word.items()}<br><br>vocab_size = len(word2int)<br><br>embedding_dim = 3<br>embedding_layer = np.random.randn(vocab_size, embedding_dim)<br><br>tokens = [word2int[w] for w in words]<br><br>embeddings = np.asarray([embedding_layer[idx] for idx in tokens])<br><br>print(sentence)<br>print(tokens)<br>print(embeddings)</pre><pre>The New York Rangers beat the Pittsburgh Penguins last night<br>[1, 0, 8, 4, 5, 1, 6, 7, 2, 3]<br>[[ 1.52302986 -0.23415337 -0.23413696]<br> [ 0.49671415 -0.1382643   0.64768854]<br> [-0.54438272  0.11092259 -1.15099358]<br> [ 0.24196227 -1.91328024 -1.72491783]<br> [-0.56228753 -1.01283112  0.31424733]<br> [ 1.52302986 -0.23415337 -0.23413696]<br> [-0.90802408 -1.4123037   1.46564877]<br> [-0.2257763   0.0675282  -1.42474819]<br> [ 1.57921282  0.76743473 -0.46947439]<br> [ 0.54256004 -0.46341769 -0.46572975]]</pre><p>Now that we have our word embeddings, we can calculate our query, keys, and values (Q, K, V). To do so, we’ll create three distinct weight matrices. Each one of these weight matrices are multiplied to our embeddings, resulting in Q, K, and V.</p><pre># weights to calculate (Q, K, V)<br>w_q = np.random.random((embedding_dim, 3))<br>w_k = np.random.random((embedding_dim, 3))<br>w_v = np.random.random((embedding_dim, 3))<br><br># calculate (Q, K, V), each as a seperate linear transform of the same input<br>Q = embeddings @ w_q<br>K = embeddings @ w_k<br>V = embeddings @ w_v<br><br>print(&quot;Embeddings&quot;)<br>print(embeddings)<br>print(&quot;Query&quot;)<br>print(Q)<br>print(&quot;Keys&quot;)<br>print(K)<br>print(&quot;Values&quot;)<br>print(V)</pre><pre>Embeddings<br>[[ 1.52302986 -0.23415337 -0.23413696]<br> [ 0.49671415 -0.1382643   0.64768854]<br> [-0.54438272  0.11092259 -1.15099358]<br> [ 0.24196227 -1.91328024 -1.72491783]<br> [-0.56228753 -1.01283112  0.31424733]<br> [ 1.52302986 -0.23415337 -0.23413696]<br> [-0.90802408 -1.4123037   1.46564877]<br> [-0.2257763   0.0675282  -1.42474819]<br> [ 1.57921282  0.76743473 -0.46947439]<br> [ 0.54256004 -0.46341769 -0.46572975]]<br>Query<br>[[ 0.82251338  0.81159993  1.00373091]<br> [ 0.789867    0.66368101  0.84142144]<br> [-1.2204644  -0.97983602 -1.2912466 ]<br> [-2.03923402 -1.0427095  -2.47982019]<br> [-0.64944775 -0.30323953 -0.9789908 ]<br> [ 0.82251338  0.81159993  1.00373091]<br> [-0.21436719  0.0748143  -0.68296169]<br> [-1.21676708 -0.93554805 -1.25058156]<br> [ 1.15742847  0.83511444  1.58651721]<br> [-0.17729782  0.02908763 -0.20822642]]<br>Keys<br>[[ 0.59710626  0.69727221  0.52472329]<br> [ 0.65395643  0.44833603  0.53741555]<br> [-0.99849853 -0.63442084 -0.81462134]<br> [-1.02690968 -0.62218315 -0.8339267 ]<br> [-0.10341011 -0.30441642 -0.11241646]<br> [ 0.59710626  0.69727221  0.52472329]<br> [ 0.44847632 -0.166294    0.31278091]<br> [-1.01649541 -0.55861308 -0.81899144]<br> [ 0.50053747  0.76072393  0.46053719]<br> [-0.04026118  0.08721022 -0.01945467]]<br>Values<br>[[ 1.13749446  0.28835778  0.38932376]<br> [ 0.53400406  0.19661354  0.79535395]<br> [-0.74375788 -0.29589616 -1.28494259]<br> [-1.72578167 -0.65552917 -1.65163902]<br> [-1.1845054  -0.32124445 -0.01656584]<br> [ 1.13749446  0.28835778  0.38932376]<br> [-1.46648602 -0.31320206  0.88125363]<br> [-0.56670885 -0.27053368 -1.41204147]<br> [ 1.8770459   0.49358388  0.27068979]<br> [ 0.00732767 -0.04585867 -0.24600433]]</pre><h4>Step 2: Calculate Attention Scores</h4><p>After obtaining the query, keys, and values, the next step is to calculate something called the <strong><em>“attention scores”</em></strong>. These scores represent the relevance of each word in the input sequence. Specifically, the attention scores measure the similarity between the query and each key in the sequence, resulting in a weight for each word.</p><p>This is done in three steps:</p><ol><li>Take the dot product of Q and K.</li><li>Divide the result by the square root of the dimensionality of K (which has the same dimensionality as Q and V, since they’re generated from the same input). This is done to help keep gradients stable during training.</li><li>Then, we pass the result through a softmax operation to produce a probability distribution.</li></ol><pre>def softmax(x: np.ndarray, axis: int) -&gt; np.ndarray:<br>    x = np.exp(x - np.amax(x, axis=axis, keepdims=True))<br>    return x / np.sum(x, axis=axis, keepdims=True)<br><br># calculate attention scores as dot product between Q and K<br>scores = Q @ K.T  # (n x n) matrix<br>print(scores.shape)<br><br># divide by dimensionality of K, and pass through softmax operation<br>scores = softmax(scores / K.shape[1]**0.5, axis=1)<br>print(&quot;Attention Scores:&quot;)<br>print(scores)</pre><pre>(10, 10)<br>Attention Scores:<br>[[0.18243745 0.16802514 0.02108437 0.02068868 0.05655159 0.18243745<br>  0.1003192  0.02160608 0.17296424 0.0738858 ]<br> [0.1734229  0.16278623 0.02623697 0.02577806 0.06298736 0.1734229<br>  0.10501411 0.02673269 0.16481552 0.07880325]<br> [0.01481013 0.01622602 0.26281878 0.27014354 0.06875659 0.01481013<br>  0.03139258 0.25583144 0.01604364 0.04916716]<br> [0.0030721  0.00327762 0.30496995 0.32180184 0.03189181 0.0030721<br>  0.0083367  0.29947226 0.00363189 0.02047372]<br> [0.04102871 0.04165262 0.20088451 0.20482428 0.09114326 0.04102871<br>  0.05688238 0.20007179 0.04362594 0.07885779]<br> [0.18243745 0.16802514 0.02108437 0.02068868 0.05655159 0.18243745<br>  0.1003192  0.02160608 0.17296424 0.0738858 ]<br> [0.07340867 0.07175437 0.1431818  0.14486066 0.09856377 0.07340867<br>  0.07831247 0.14422004 0.07640466 0.0958849 ]<br> [0.01571131 0.01711131 0.26024725 0.26744658 0.06993562 0.01571131<br>  0.0324035  0.25378401 0.01701834 0.05063077]<br> [0.19979083 0.18620737 0.01061357 0.01029198 0.04305956 0.19979083<br>  0.09824306 0.01083363 0.18209713 0.05907205]<br> [0.0879328  0.08692513 0.11893237 0.11958049 0.10028884 0.0879328<br>  0.0902663  0.11936616 0.08958967 0.09918545]]</pre><p>These scores can also be visualized with a heatmap.</p><pre>labels = [int2word.get(x) for x in tokens]<br>ticks = list(range(len(tokens)))<br><br>plt.figure(figsize=(15,6))<br>plt.imshow(scores, cmap=&quot;hot&quot;)<br>plt.xticks(ticks, labels, rotation=20)<br>plt.yticks(ticks, labels, rotation=20)<br>plt.title(&quot;Attention Scores&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMkV7Y1Mb27ptPKz96IJMw.png" /></figure><h4>Step 3: Apply Attention Scores to Values</h4><p>Lastly, we multiply the values by the attention scores. The intuition here is to keep intact the values of the words we want to focus on, and drown-out irrelevant words (by multiplying them by tiny numbers).</p><pre># multiple attention scores with our valuese (V)<br># this tells us how much to &quot;attend&quot; to our values<br>attention_output = scores @ V<br>attention_output</pre><pre>array([[ 0.55223997,  0.14500153,  0.30003606],<br>       [ 0.48364594,  0.12473938,  0.26719983],<br>       [-0.861311  , -0.33858932, -1.10192064],<br>       [-0.98619227, -0.39179351, -1.33847273],<br>       [-0.6096025 , -0.24516223, -0.77282733],<br>       [ 0.55223997,  0.14500153,  0.30003606],<br>       [-0.32037601, -0.14277565, -0.44817878],<br>       [-0.85209962, -0.3350942 , -1.08908994],<br>       [ 0.66932345,  0.18158397,  0.378357  ],<br>       [-0.19828427, -0.09888715, -0.30353304]])</pre><p>Let’s pause for a second and think about what we’re doing here.</p><p>We took a sentence, broke it apart, and calculated which parts to focus on. This is where the name <em>Attention</em> comes from — we are determining which words to <em>pay attention</em> to.</p><p>Take this sentence, for example:</p><blockquote><strong><em>The dog didn’t chase the ball because it was tired.</em></strong></blockquote><p>What does <strong><em>“it”</em></strong> refer to here? The dog or the ball? As humans, it’s pretty obvious that <strong><em>“it”</em></strong> is referring to the dog. But how do we teach that to an algorithm? It turns out that self-attention is a pretty remarkable way of doing this.</p><p>As the model processes each word, self-attention allows it to look at other words in the input sequence for clues about what a word truly means.</p><p>Of course, self-attention isn’t the only mechanism capable of doing this. Recurrent models (RNNs, LSTMs, GRUs, …etc.), for example, can do this by maintaining a hidden state and iterating over each word.</p><p>Self-attention, however, does it in a (generally) more efficient way — so efficient, in fact, that one might say <em>Attention Is All You Need</em>.</p><h3>Multi-Head Attention</h3><p>Hopefully you’re still with me up until this point, as there is one more “trick” we need to discuss. In the Transformer architecture, self-attention is actually used in a slightly different way.</p><p>Instead of calculating self-attention for the entire input sequence, the query, keys, and values are projected into a number of smaller parts. These parts are called “feature heads”.</p><p>Each one of these feature heads consist of a smaller Q, K, and V, which all get treated as they would in regular self-attention. The only difference here is that the dimensionality is smaller. This is because we project our input sequence into smaller pieces, where the number of pieces is equal to the number of heads.</p><p>After each piece is passed through the attention mechanism, the results are concatenated back together. This entire process is called <strong>Multi-Head Attention</strong>, and is the standard way that Transformer-based architectures compute attention.</p><p>Let’s see what this looks like in code:</p><pre>def attention(q: np.ndarray, k: np.ndarray, v: np.ndarray) -&gt; np.ndarray:<br>    scores = np.dot(q, k.T)<br>    scores = softmax(scores / k.shape[1]**0.5, axis=1)<br>    return np.dot(scores, v)<br><br>num_heads = 2<br><br># split each of Q, K, V into &#39;num_heads&#39; chunks<br># in reality, Q, K, V are projected &#39;num_heads&#39; times,<br># with each having a dimensionality of d_K / num_heads<br>Q_heads = np.array_split(Q, num_heads)<br>K_heads = np.array_split(K, num_heads)<br>V_heads = np.array_split(V, num_heads)<br><br>mha = []  # multi_headed_attention<br>for q, k, v in zip(Q_heads, K_heads, V_heads):<br>    mha.append(attention(q, k, v))<br><br>mha = np.concatenate(mha)<br><br>print(f&quot;Multi-Head Attention With {num_heads} Heads:&quot;)<br>print(mha)</pre><pre>Multi-Head Attention With 2 Heads:<br>[[ 0.60953835  0.01358341  0.13193092]<br> [ 0.73296062  0.26665053  0.2208828 ]<br> [ 0.75949672  0.31877813  0.239563  ]<br> [ 0.5748434  -0.04915518  0.10892594]<br> [ 0.70931645  0.21137786  0.20226688]<br> [-0.7476555  -0.14789445 -0.186506  ]<br> [-2.0856066  -0.29344913 -0.45671552]<br> [-2.57472182 -0.40726148 -0.57480416]<br> [-1.48388317 -0.24861617 -0.337241  ]<br> [-2.34642163 -0.42059472 -0.53500223]]</pre><p>So, why do we do this? Well, in the words of the authors of <em>Attention Is All You Need</em>:</p><blockquote>“Due to the reduced dimension of each head, the total computational cost [of multi-head attention] is similar to that of single-head attention with full dimensionality.”</blockquote><p>What this means is that by projecting our input sequence into smaller components, we can calculate a richer representation of the same input for essentially the same cost.</p><h3>Transformers</h3><p>So, how exactly is self-attention used in Transformers? What does this looks like?</p><p>The transformer architecture is typically composed of an encoder-decoder structure, followed by a task-specific classification or regression layer. In <em>Attention Is All You Need</em>, this looks like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*SOKMl-MI8WsdMXmdoJSYJQ.png" /></figure><p>Let’s break this down piece-by-piece.</p><p>On the left, we have our <strong>Encoder</strong>. And on the right, we have our <strong>Decoder</strong>. If you’re not familiar with this type of architecture, I would recommend <a href="https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html">this quick blog post</a>.</p><p>Both the Encoder and Decoder are comrpised of only a few basic building blocks: Multi-Head Attention, “Add &amp; Norm”, and a feed-forward neural network. Since we already discussed Multi-Head Attention, we can briefly focus on the other two.</p><p>First, let’s tackle “<strong>Add &amp; Norm</strong>”. As its name suggests, this consists of two different operations: addition and layer normalization. Layer normalization is similar to batch normalization, except it occurs over the feature dimension.</p><p>To understand the purpose of the addition operation, take another look at the diagram. Did you notice how there is an arrow connecting each sub-layer’s input to its output? This is called a <strong>residual connection</strong>, and is a popular trick in the AI world. To be clear, a residual connection is when a layer’s input is added back to its output. By doing this, we are providing the model another way to route information.</p><p>So, using what we know so far, we can begin to piece together what is happening here:</p><ol><li>First, our input undergoes three seperate linear transformations to create our query, keys, and values (Q, K, V).</li><li>Then, the query, keys, and values are projected into smaller pieces. Each one of these pieces is used to calculate self-attention seperately, and the results are concatenated back together.</li><li>Lastly, we add back the original input and normalize</li></ol><p>For clarity’s sake, let’s write some code demonstrating everything we’ve talked about up until this point:</p><pre>sentence = &quot;The New York Rangers beat the Pittsburgh Penguins last night&quot;<br><br>words = sentence.lower().split()<br><br>int2word = {k: v for (k, v) in enumerate(set(words))}<br>word2int = {v: k for (k, v) in int2word.items()}<br><br>vocab_size = len(word2int)<br><br>embedding_dim = 3<br>embedding_layer = np.random.randn(vocab_size, embedding_dim)<br><br>tokens = [word2int[w] for w in words]<br><br>embeddings = np.asarray([embedding_layer[idx] for idx in tokens])</pre><pre>def attention(q: np.ndarray, k: np.ndarray, v: np.ndarray) -&gt; np.ndarray:<br>    scores = np.dot(q, k.T)<br>    scores = softmax(scores / k.shape[1]**0.5, axis=1)<br>    return np.dot(scores, v)<br><br>def multi_headed_attention(q: np.ndarray,<br>                           k: np.ndarray,<br>                           v: np.ndarray,<br>                           num_heads: int) -&gt; np.ndarray:<br>    q_heads = np.array_split(Q, num_heads)<br>    k_heads = np.array_split(K, num_heads)<br>    v_heads = np.array_split(V, num_heads)<br>    mha = []  # multi_headed_attention<br>    for query, keys, values in zip(q_heads, k_heads, v_heads):<br>        mha.append(attention(query, keys, values))<br>    mha = np.concatenate(mha)<br>    return mha<br><br># weights to calculate (Q, K, V)<br>w_q = np.random.random((embedding_dim, 3))<br>w_k = np.random.random((embedding_dim, 3))<br>w_v = np.random.random((embedding_dim, 3))<br><br># calculate (Q, K, V), each as a seperate linear transform of the same input<br>Q = embeddings @ w_q<br>K = embeddings @ w_k<br>V = embeddings @ w_v<br><br>mha_output = multi_headed_attention(Q, K, V, num_heads=3)<br><br># add back the original input embeddings<br>mha_output = mha_output + embeddings<br><br>print(f&quot;MHA Input (shape={embeddings.shape}):&quot;)<br>print(embeddings)<br>print(f&quot;MHA Output (shape={mha_output.shape}):&quot;)<br>print(mha_output)</pre><pre>MHA Input (shape=(10, 3)):<br>[[-2.89625538  2.0883747  -0.13958963]<br> [ 0.91632767  0.34648848  0.99801011]<br> [ 0.63873022 -1.14300491  1.63343153]<br> [-0.1906824   0.21743287  0.87006773]<br> [ 0.49568189  0.15041891  0.364961  ]<br> [-2.89625538  2.0883747  -0.13958963]<br> [ 2.40341559 -0.0576188   0.20109905]<br> [ 1.0506544   1.10552593  1.18703031]<br> [ 1.10818282 -1.03990593  0.61277391]<br> [-1.05341556 -0.62376896  1.91403135]]<br>MHA Output (shape=(10, 3)):<br>[[-2.78893211  2.04578129 -0.23032928]<br> [ 1.18303646  0.87416007  1.38036089]<br> [ 0.86905636 -0.65230919  1.96749529]<br> [-0.01424929  0.62255251  1.11317113]<br> [ 1.37666534  1.148573    1.57974241]<br> [-2.60455381  2.1013331  -0.0412284 ]<br> [ 3.46920801  1.19249537  1.72110217]<br> [ 2.28276012  2.53630545  2.75553923]<br> [ 1.63643914 -0.272355    1.31308437]<br> [-0.42670497  0.23689275  2.74198423]]</pre><p>To continue, the Feed-Forward Neural Network is comprised of two linear transformations with a non-linear transformation in between. The non-linear activation function used is the Rectified Linear Unit (ReLU).</p><p>In <em>Attention Is All You Need</em>, the initial layer expands the data by a degree of four, while the output layer compresses the data back to its original dimension. While this is not a set-in-stone rule, this is also what we’ll be doing.</p><p>The below code takes the output of our Multi-Head Attention operation, and passes it through the feed-forward net. Then, it adds back the feed-forward net’s input (which is attention’s output).</p><p>Note that we are leaving out the layer normalization and bias terms to keep things simple.</p><pre>def relu(a):<br>    return np.maximum(0, a)<br><br>ffn_input_shape = mha_output.shape[-1]<br>ffn_weights_1 = np.random.randn(ffn_input_shape, ffn_input_shape*4)<br>ffn_weights_2 = np.random.randn(ffn_input_shape*4, ffn_input_shape)<br><br>ffn_out = relu(np.dot(mha_output, ffn_weights_1))<br>ffn_out = np.dot(ffn_out, ffn_weights_2)<br><br>ffn_out = ffn_out + mha_output<br><br>print(f&quot;FFN Input Shape: {mha_output.shape}&quot;)<br>print(f&quot;FFN Output Shape: {ffn_out.shape}&quot;)</pre><pre>FFN Input Shape: (10, 3)<br>FFN Output Shape: (10, 3)</pre><p>And that’s it! Aside from some minor things, we just coded the forward-pass of the Transformer Encoder.</p><p>Well, except for one thing…</p><h3>Positional Encodings</h3><p>Before the input embeddings are transformed into the query, keys, and values, they undergo a process called <em>positional encoding. </em>This is something we need to touch upon, as it is an important topic.</p><p>Transformers dont have any temporal/spatial awareness. Other architectures, like RNNs, do have temporal awareness by default, as they process data in a sequence.</p><p>So, in order to give our model a notion of time and space, we have to inject extra information into its input. This information should represent a particular input’s position relative to its overall sequence.</p><p>Positional Encodings aren’t anything new, and there are many different ways to calculate them. For instance, we could encode our first timestep as the integer 1, and increase this integer by a fixed increment after every timestep.</p><p>The authors, however, chose a more complicated approach involving trigonometric functions. Essentially, this method generates sinusoidal waves at different frequencies, allowing the model to attend to the relative positions of its inputs.</p><p>An implementation can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*gIBtfe0Oc8EfJC_8Fd5A9g.png" /></figure><pre>def positional_encoding(length: int, depth: int):<br>    &quot;&quot;&quot;<br>    Positional Encoding as described in &#39;Attention Is All You Need&#39;<br>    <br>    NOTE: 10000 is a user defined scalar.<br>    &quot;&quot;&quot;<br>    assert depth % 2 == 0, &quot;&#39;depth&#39; must be even&quot;<br>    depth = depth / 2<br><br>    positions = np.arange(length)[:, np.newaxis]     # (seq, 1)<br>    depths = np.arange(depth)[np.newaxis, :] / depth   # (1, depth)<br><br>    angle_rates = 1 / (10000**depths)         # (1, depth)  10,000 chosen because its sufficiently large<br>    angle_rads = positions * angle_rates      # (pos, depth)<br><br>    pos_encoding = np.concatenate([np.sin(angle_rads), np.cos(angle_rads)], axis=-1) <br>    return pos_encoding<br><br>plt.figure(figsize=(10,6))<br>plt.plot(positional_encoding(64, 16))<br>plt.title(&quot;Positional Encoding Example&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acsnOaVfpP-lZ1xeH-Hw3Q.png" /></figure><p>Before we use our input embeddings to generate the query, keys, and values, we need add in this positional encoding. The following code demonstrates this.</p><pre>sentence = &quot;The New York Rangers beat the Pittsburgh Penguins last night&quot;<br><br>words = sentence.lower().split()<br><br>int2word = {k: v for (k, v) in enumerate(set(words))}<br>word2int = {v: k for (k, v) in int2word.items()}<br><br>vocab_size = len(word2int)<br><br>embedding_dim = 4<br>embedding_layer = np.random.randn(vocab_size, embedding_dim)<br><br>tokens = [word2int[w] for w in words]<br><br>embeddings = np.asarray([embedding_layer[idx] for idx in tokens])<br><br>embeddings = embeddings + positional_encoding(*embeddings.shape)<br>embeddings.shape</pre><pre>(10, 4)</pre><h3>Teacher Forcing</h3><p>So, what exactly are the inputs to the Encoder and Decoder? To understand this, you need to understand a concept called <strong>teacher forcing</strong>.</p><p>The Transformer, much like the attention mechanism, was originally designed for sequence-to-sequence modeling. Specifically, it was developed with machine translation in mind, which is the task of taking text in one language and automatically translating it to another. It is common to use the Encoder-Decoder structure for this type of task, as it provides a natural way to handle variable-length sequences.</p><p>Take the below, for example, which shows how an LSTM Encoder-Decoder model is trained to translate text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*2j7GLPIx1xwy3AJcHg1l5g.png" /></figure><p>Here, the encoder takes in an english sentence, processes it, and returns its internal state. Simple enough, right?</p><p>The decoder, on the other hand, is slightly more complex.</p><p>To properly understand it, you need to understand that these types of models are autoregressive. This means that the model’s own predictions are fed back into it as inputs. Said differently, the model uses its predictions to make further predictions.</p><p>So, how do we train an autoregressive model?</p><p>The best way to do this is to predict the next tokens in a sequence, given the current and previous tokens in that same sequence. And this is exactly what the decoder does: given targets[…t], the decoder learns to predict targets[t+1…].</p><p>Using the targets at timestep (t) to predict the targets at timestep (t+1) is what’s known as <em>teacher forcing</em>.</p><p>During inference, however, the model’s predictions are fed back into the model as inputs. This looks like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*P27-hP6J1IF3h_H2MJOttA.png" /></figure><p>In the Transformer, this whole flow can be summarized like this (excluding residual connections and layer normalization):</p><p><strong>Encoder</strong></p><ul><li>The input is transformed into the query, keys, and values (Q, K, V)</li><li>Q, K, V is used to calculate self-attention</li><li>The output is passed through a feed forward net and returned</li></ul><p><strong>Decoder</strong></p><ul><li>The previous predictions are used as input, being transformed into the query, keys, and values (Q, K, V)</li><li>Q, K, V is used to calculate self-attention</li><li>The output is used as a new query, while the encoder’s output is used as the keys and values. Attention is once again computed</li><li>The output is passed through a feed forward net and returned</li></ul><h3>Building a Transformer (Tensorflow)</h3><p>We now have all the building blocks we need to build a Transformer model. For the remainder of this post, we’ll be using Tensorflow, a popular deep learning library.</p><p>We will start off by extending tensorflow’s embedding layer to include a positional encoding (through the addition operation).</p><pre>import tensorflow as tf<br><br><br>class PositionalEmbedding(tf.keras.layers.Embedding):<br>    def __init__(self, vocab_size: int, d_model: int, **kwargs):<br>        super().__init__(input_dim=vocab_size, output_dim=d_model, mask_zero=True, **kwargs)<br>        self.vocab_size = self.input_dim<br>        self.d_model = self.output_dim<br>        self.pos_encoding = tf.cast(positional_encoding(length=vocab_size, depth=d_model), dtype=tf.float32)<br><br>    def call(self, inputs: tf.Tensor) -&gt; tf.Tensor:<br>        length = tf.shape(inputs)[1]<br>        inputs = super().call(inputs)<br>        inputs *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))  # sets the relative scale of the embedding and positonal_encoding.<br>        inputs = inputs + self.pos_encoding[tf.newaxis, :length, :]<br>        return inputs</pre><p>Then, we can extend tensorflow’s Multi-Head Atttention to include the layer normalization and residual connection. After, we create three different objects representing the three attention mechanisms in our model.</p><p>The <strong><em>SelfAttention</em></strong> class processes the input to the encoder, while <strong><em>MaskedSelfAttention</em></strong> processes the input to the decoder. Both are identical, with one exception: in <em>MaskedSelfAttention</em>, a mask is used to tell the model to ignore targets[t+1…], as those are the values we are trying to predict.</p><p>The <strong><em>CrossAttention</em></strong> class represents the attention mechanism that connects the encoder and decoder. The caveat with cross attention is that the encoder’s output is used as the keys and values, while the output of the decoder’s masked self-attention is used for the query.</p><pre>class AttentionBase(tf.keras.layers.MultiHeadAttention):<br>    &quot;&quot;&quot;<br>    args:<br>        num_heads: Number of attention heads.<br>        key_dim: Size of each attention head for query and key.<br>                 Dimensionality of the linearly projected queries and keys<br>        value_dim: Size of each attention head for value.<br>                   Dimensionality of the linearly projected values<br>    &quot;&quot;&quot;<br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br>        self.layer_norm = tf.keras.layers.LayerNormalization()<br>        self.add = tf.keras.layers.Add()<br><br><br>class SelfAttention(AttentionBase):<br>    &quot;&quot;&quot;<br>    Processes the &#39;context&#39; sequence (input to the encoder)<br>    &quot;&quot;&quot;<br>    def call(self, x, use_causal_mask: bool = False):<br>        attention = super().call(query=x,<br>                                 value=x,<br>                                 key=x,<br>                                 use_causal_mask=use_causal_mask)<br>        return self.layer_norm(self.add([x, attention]))<br><br><br>class MaskedSelfAttention(SelfAttention):<br>    &quot;&quot;&quot;<br>    Processes the output sequence into the decoder layer<br>    Same as SelfAttention, except with a mask<br>    &quot;&quot;&quot;<br>    def call(self, x):<br>        return super().call(x, use_causal_mask=True)<br><br><br>class CrossAttention(AttentionBase):<br>    &quot;&quot;&quot;<br>    Connects the Encoder and Decoder in the following way:<br>        - keys, values from encoder are used<br>        - quereies: shifted inputs (1 to the right) are used<br>    Output length is the length of the query sequence, not the key-value sequence<br>    &quot;&quot;&quot;<br>    def call(self, prev_target, encoder_output):<br>        attention_output, attention_scores = super().call(query=prev_target,<br>                                                          key=encoder_output,<br>                                                          value=encoder_output,<br>                                                          return_attention_scores=True)<br>        self.last_attention_scores = attention_scores  # cache for plotting<br>        return self.layer_norm(self.add([prev_target, attention_output]))</pre><p>Next up is the Feed Forward Neural Network. In Tensorflow, this is composed of two dense layers, the first of which uses ReLU activation.</p><p>Note that we are also adding in some dropout. In the Transformer, this is applied to the output of each sub-layer, prior to it being added back to the input. This is called residual dropout.</p><pre>class FeedForward(tf.keras.layers.Layer):<br>    def __init__(self, d_model: int, dff: int, dropout: float = 0.1):<br>        super().__init__()<br>        self.ffn = tf.keras.Sequential([<br>            tf.keras.layers.Dense(dff, activation=&quot;relu&quot;),<br>            tf.keras.layers.Dense(d_model),<br>            tf.keras.layers.Dropout(dropout)<br>        ])<br>        self.add = tf.keras.layers.Add()<br>        self.layer_norm = tf.keras.layers.LayerNormalization()<br>    <br>    def call(self, x):<br>        return self.layer_norm(self.add([x, self.ffn(x)]))<br></pre><p>With our attention mechanisms and feed forward net defined, we can now begin coding the Encoder and Decoder. The transformer stacks both the encoder and decoder 6 times. In this spirit, we define a helper function “get_clones” to duplicate its input <strong><em>n</em></strong> times.</p><pre>from typing import Any<br>from copy import deepcopy<br><br>def get_clones(obj: Any, n: int) -&gt; List[Any]:<br>    &quot;&quot;&quot;clones &#39;obj&#39; &#39;n&#39; times &quot;&quot;&quot;<br>    assert n &gt; 0, &quot;&#39;n&#39; must be &gt; 0&quot;<br>    clones = []<br>    for _ in range(n):<br>        clones.append(deepcopy(obj))<br>    return clones</pre><p>If you recall from earlier, the Encoder is comprised of self-attention, followed by a feed forward net. We duplicate this structure <em>num_layers</em> times. Lastly, remember that the inputs undergo a positional encoding before being broken up into the query, keys, and values.</p><p>It might be useful to compare the code to the Encoder diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*GYzVQJ903uiGjH7NAMMZ6Q.png" /></figure><pre>class Encoder(tf.keras.layers.Layer):<br>    &quot;&quot;&quot;Consists of a Positional Embedding and a stack of (self attention + ffn) models&quot;&quot;&quot;<br>    def __init__(self,<br>                 num_layers: int,<br>                 vocab_size: int,<br>                 d_model: int,<br>                 dff: int,<br>                 num_heads: int,<br>                 dropout: float = 0.1):<br>        if num_layers &lt; 1:<br>            return ValueError(&quot;&#39;num_layers&#39; must be &gt;= 1&quot;)<br>        super().__init__(name=&quot;TransformerEncoder&quot;)<br>        self.pos_embed = PositionalEmbedding(vocab_size=vocab_size, d_model=d_model)<br>        self.sub_layers = []<br>        for _ in range(num_layers):<br>            self.sub_layers.append(<br>                tf.keras.Sequential([<br>                    SelfAttention(num_heads=num_heads, key_dim=d_model, value_dim=d_model, dropout=dropout),<br>                    FeedForward(d_model=d_model, dff=dff, dropout=dropout)<br>                ])<br>            )<br>        self.num_layers = num_layers<br>    <br>    def call(self, x):<br>        x = self.pos_embed(x)<br>        for layer in self.sub_layers:<br>            x = layer(x)<br>        return x</pre><p>As you can see, the Encoder is pretty straightforward. The Decoder, on the other hand, is slightly more complicated.</p><p>After the inputs are processed by masked self-attention, the output flows to a second attention mechanism called cross-attention. This layer uses the output from masked self-attention as the query, and the output from the encoder model as the keys and values. Lastly, the output of cross-attention is passed to the feed forward net.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*CCclObbvXCqe-W59sD860g.png" /></figure><pre>class DecoderLayer(tf.keras.layers.Layer):<br>    def __init__(self, num_layers: int, d_model: int, dff: int, num_heads: int, dropout: float = 0.1):<br>        super().__init__()<br>        self.masked_attn = MaskedSelfAttention(num_heads=num_heads, key_dim=d_model, value_dim=d_model, dropout=dropout)<br>        self.cross_attn = CrossAttention(num_heads=num_heads, key_dim=d_model, value_dim=d_model, dropout=dropout)<br>        self.ffn = FeedForward(d_model=d_model, dff=dff, dropout=dropout)<br>    <br>    def call(self, prev_target, encoder_output):<br>        prev_target = self.masked_attn(prev_target)<br>        out = self.cross_attn(prev_target, encoder_output)<br><br>        self.scores = self.cross_attn.last_attention_scores<br><br>        return self.ffn(out)<br>        <br>class Decoder(tf.keras.layers.Layer):<br>    def __init__(self, num_layers: int, vocab_size: int, d_model: int, dff: int, num_heads: int, dropout: float = 0.1):<br>        super().__init__(name=&quot;TransformerDecoder&quot;)<br>        self.pos_embed = PositionalEmbedding(vocab_size=vocab_size, d_model=d_model)<br>        self.sub_layers = []<br>        for _ in range(num_layers):<br>            self.sub_layers.append(<br>                DecoderLayer(num_layers=num_layers, num_heads=num_heads, d_model=d_model, dff=dff, dropout=dropout)<br>            )<br>        self.num_layers = num_layers<br>    <br>    def call(self, prev_target, encoder_output):<br>        x = self.pos_embed(prev_target)<br>        for layer in self.sub_layers:<br>            x = layer(prev_target=x, encoder_output=encoder_output)<br>        self.scores = self.sub_layers[-1].scores<br>        return x<br></pre><p>The decoder outputs a vector of floats. But how do we turn that into a word? That is the job of a final output layer, which takes our decoder values and turns them into a probability distribution. We implement this by using a dense (linear) layer with softmax activation.</p><p>But how exactly does that work?</p><p>The dense layer linearly projects the decoder outputs into a much larger vector, called a logits vector. Now, if our model knows 5,000 unique words (our model’s <em>“output vocabulary”</em>), the logits vector will be 5,000 values long. Each value in this vector corresponds to a unique word. The softmax layer then turns those values into probabilities that, when summed, add up to 1. The word with the highest probability is the winner, and is outputted by the model.</p><p>As a reminder, Transformers are autoregressive. So, this output can be fed back into the model to help predict the next token in the sequence.</p><pre>class Transformer(tf.keras.Model):<br>    &quot;&quot;&quot;<br>    Seq-to-Seq Encoder/Decoder Transformer model described in<br>    &#39;Attention Is All You Need&#39;<br>    The model used in the paper:<br>        num_layers = 6<br>           d_model = 512<br>               dff = 2048<br>         num_heads = 8<br>    &quot;&quot;&quot;<br>    def __init__(self,<br>                 src_size: int,<br>                 tgt_size: int,<br>                 num_layers: int,<br>                 d_model: int,<br>                 dff: int,<br>                 num_heads: int,<br>                 dropout: float = 0.1):<br>        super().__init__(name=&quot;Transformer&quot;)<br>        self.encoder = Encoder(num_layers=num_layers,<br>                               vocab_size=src_size,<br>                               d_model=d_model,<br>                               dff=dff,<br>                               num_heads=num_heads,<br>                               dropout=dropout)<br><br>        self.decoder = Decoder(num_layers=num_layers,<br>                               vocab_size=src_size,<br>                               d_model=d_model,<br>                               dff=dff,<br>                               num_heads=num_heads,<br>                               dropout=dropout)<br><br>        self.output_layer = tf.keras.layers.Dense(tgt_size, activation=&quot;softmax&quot;)<br>    <br>    def call(self, x, prev_target):<br>        x = self.decoder(prev_target=prev_target, encoder_output=self.encoder(x))<br>        logits = self.output_layer(x)<br>        try:  # drop keras mask so it doesn&#39;t scale the losses/metrics<br>            del logits._keras_mask<br>        except AttributeError:<br>            pass<br>        return logits<br><br></pre><p>And that’s it!</p><p>In the paper they used 6 encoder layers, 6 decoder layers, an embedding dimensionality of 512, and 8 feature heads (meaning the query, keys, and values get split into 8 smaller pieces).</p><p>We can use these specs to build our Transformer and print the summary:</p><pre>transformer = Transformer(num_layers=6,<br>                          num_heads=8,<br>                          d_model=512,<br>                          dff=512*4,<br>                          src_size=2048,<br>                          tgt_size=2048,<br>                          dropout=0.1)<br><br># pass fake input through the model to build its graph<br>fake_input = np.arange(2048).reshape(1,-1)<br>transformer(fake_input, fake_input)<br><br># now we can check out the summary<br>transformer.summary()</pre><pre>Model: &quot;Transformer&quot;<br>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> TransformerEncoder (Encoder  multiple                 64067584  <br> )                                                               <br>                                                                 <br> TransformerDecoder (Decoder  multiple                 114482176 <br> )                                                               <br>                                                                 <br> dense_24 (Dense)            multiple                  1050624   <br>                                                                 <br>=================================================================<br>Total params: 179,600,384<br>Trainable params: 179,600,384<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>That’s a lot of params!</p><p>Note that these large language models, like GPT, are using dozens of these Transformer blocks stacked on top of each other.</p><h3>GPT and The Future of AI</h3><p>Back in the good ‘ol days, OpenAI released their models to the public. Of course, this was short-lived and ultimately stopped with GPT-3. Likewise, we don’t know for sure what advances have been made in regards to the GPT architecture. Despite this, we can look at the older, open-source versions of GPT for some clarity, as it is unlikely the general architecture has strayed <em>that</em> much.</p><p>So, in that case, let’s talk about the original GPT (the OG-GPT, if you will).</p><p>In the <a href="https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf">original GPT paper</a>, called <em>Improving Language Understanding by Generative Pre-Training</em>, the authors describe their model like this:</p><blockquote>“Our model largely follows the original transformer work. We trained a 12-layer decoder-only transformer with masked self-attention heads”</blockquote><p>The part that should stand out here is “<strong><em>12-layer decoder-only</em></strong>”. Instead of using 6 encoder layers and 6 decoder layers — like the original model in <em>Attention Is All You Need — </em>OpenAI chose to cut out the encoder altogether, and instead favor using 12 decoders.</p><p>In their paper, they give us the below image, representing this 12-layer decoder-only structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*JAbgaFjqfTV34rN4vu7tLg.png" /></figure><p>The model is comprised entirely of masked self-attention and a feed forward net (as well as residual connections and some layer normalization). All in all, this is the same architecture as our decoder model, excluding the extra cross-attention layer that would normally process the encoder’s output.</p><p>Soon after GPT-1, OpenAI released a <a href="https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">paper about GPT-2</a>, titled <em>Language Models are Unsupervised Multitask Learners</em>. And in this paper, they say that GPT-2 is essentially the same as GPT-1, barring a few tweaks.</p><p>The key differences are the following:</p><ul><li>the Layer Normalization was moved to the input of each sub-layer</li><li>the dimensionality was increased from 512 to 1024</li><li>the vocabulary size was increased from 40,000 to over 50,000</li></ul><p>Then, in 2020, a group of OpenAI engineers released the preprint for <a href="https://arxiv.org/pdf/2005.14165.pdf">their GPT-3 paper</a>, titled <em>Language Models are Few-Shot Learners</em>. In this paper, the authors say that GPT-3 is structurally identical to GPT-2, except for the introduction of some tricks to reduce the space/time complexity of the model. In other words, they made it faster. If you’re interested, those tricks can be <a href="https://arxiv.org/pdf/1904.10509.pdf">read about here</a>.</p><p>So, if the architecture for GPT, GPT-2, and GPT-3 are all virtually identical, then where are the advances coming from? Why is each GPT model so much better than its predecessors? The answer to this question can be found in the table below, <a href="https://en.wikipedia.org/wiki/Generative_pre-trained_transformer">taken from wikipedia</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*bm4Yc16lk8HCOMltaBHLHg.png" /></figure><p>If you didn’t already know, the parameter count is a proxy for the size of the model. This means that GPT-2 is over 10 times larger than GPT-1. And further, GPT-3 is a staggering <strong><em>116 times</em> </strong>larger than GPT-2!</p><p>If these numbers are hard to comprehend, maybe this will help put things in perspective: It is estimated that it would take <strong><em>355 years</em></strong> to <a href="https://lambdalabs.com/blog/demystifying-gpt-3">train GPT-3 on a single GPU</a>. So, if you started today, hopefully your great-great-great-great-great grandkid would be able to see it complete (assuming GPT-20 hasn’t rendered humanity extinct by then…kidding).</p><p>For each successive model, the increase in parameters is a direct result of the increase in dataset size, which can be seen in the table above. Generally speaking, the larger the dataset, the larger the model. And it is in this relationship where we can begin to grasp why these GPT models are so powerful.</p><p>In short: As GPT’s dataset grows, it is becoming closer and closer to an ultra-compressed version of the Internet.</p><p>Think about it: when you want to know more about a topic, where do you go? Wikipedia? GPT is trained on Wikipedia. What about Google? Well, Google’s dataset is a privatized version of CommonCrawl — which GPT is also trained on.</p><p>Do you see the theme here? GPT is not just a language model. Rather, it is something more. In fact, it isn’t a stretch to say that GPT (and others like it) are human-knowledge models.</p><p>To elaborate, let’s think about what GPT is actually doing.</p><p>GPT is trained to predict the next token in a sequence. On a simplistic level, you can think of these tokens as the characters or words in a body of text. By doing this over hundreds of millions of web pages (probably even <em>billions</em> at this point), it is not only modeling language; but rather, it is also modeling <em>ideas</em>.</p><p>After all, that is how we as humans express our ideas: through language. So, by training GPT on the very medium in which we express thought, it makes sense how it is ultimately able to capture our collective ideas. And by doing so, it has become capable of some truly mind-numbing things.</p><p>Of course, this conversation always has the tendency to gradually boil down to the question: <em>What is intelligence?</em> So, since we were bound to get there eventually, let’s just get on with it.</p><p>Is ChatGPT or GPT-4 the first form of Artificial General Intelligence (AGI)? How would we even know that? How do we even measure intelligence? Better yet, <em>what is</em> intelligence? (<em>queue the existential angst</em>)</p><p>I obviously don’t know the answer to that question, nor does anyone. However, it is often useful to approach it like so: If you were to train a true Artificial General Intelligence, how would you go about it? How would you teach it? And what would be the benchmark for success?</p><p>It is in this vein that I would argue that a true AGI would need to display several different things.</p><p>First, it would need to have a capability to communicate with humans in a familiar way — that is, through language. Score one for GPT. Most people would agree with this. However, the next criterion — which is entirely dependent on the first — is where the majority of the debate is actually held.</p><p>The Turing Test is the classical defintion of what would define a true Aritificial Intelligence. This proposition, posed by the legendary Alan Turing in 1950, evaluates an AI based on its ability to display intelligent behavior that is indistinguishable from a human being. Only then, many people say, can we say that a system is truly intelligent.</p><p>If you’re anything like me, there is probably a voice in the back of your head, saying “Should we really evaluate intelligence in this manner? Is human intelligence the only definition of intelligence we should consider?”</p><p>Unfortunately, the answer <em>has to be </em><strong><em>yes</em></strong>.</p><p>What other forms of intelligence do we know? Sure, some might say: <em>“oh, dolphins show high degrees of intelligence”</em>, or <em>“cephalopods have been shown to have extremely high problem-solving abilities”</em>, or even <em>“certain birds have been shown to plan ahead”</em>. But, while these traits are certainly signs of <em>intelligent behavior</em>, our collective bar for what actually defines <em>intelligence</em> seems to be quite higher.</p><p>And so, we have no choice but to define a true Artificial Intelligence as something equal to, or better than, ourselves.</p><p>Now, does GPT fall into this category? By itself, it certainly does not, as it is incapable of intelligently communicating with a human. ChatGPT, on the other hand, is a different story.</p><p>The best way to think about ChatGPT is to consider that GPT is really the “brain” behind the whole operation. That is, ChatGPT is really the result of teaching GPT how to communicate. Imagine if you were born with all of the knowledge you will ever have. Now, imagine if you didn’t have the ability to speak or write. How would you get your thoughts across?</p><p>This is why ChatGPT in particular has changed the game. By teaching GPT how to communicate, the engineers at OpenAI have opened up the “brain” that is GPT, to mere mortals like you and me. From fixing a developer’s code to helping a student with their homework, ChatGPT has unequivecolly passed our first test. Now, the only question is: <strong><em>Can it pass the Turing Test?</em></strong></p><p>At the time of writing, we don’t know how many parameters are used in GPT-4, nor do we know the size of the dataset involved. However, it is safe to say that it will be larger than GPT-3 (most likely <strong>a lot</strong> larger). There are many reports from “anonymous sources” placing it at over 1 trillion parameters, but this has yet to be confirmed. That being said, given the exponential increase in parameters between GPT models thus far, this is indeed the probable case.</p><h3>References</h3><ul><li><a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a></li><li><a href="https://peterbloem.nl/blog/transformers">https://peterbloem.nl/blog/transformers</a></li><li><a href="https://storrs.io/attention/">https://storrs.io/attention/</a></li><li><a href="https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html">https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3adbbb4a950" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>