<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Mathematics and Econometrics - Quantitative Finance & Algo Trading Blog by QuantInsti]]></title><description><![CDATA[Articles on skill development and individual success stories. Tutorials on trading indicators & strategies, portfolio & risk management, automated trading, Python programming and more.]]></description><link>https://blog.quantinsti.com/</link><image><url>https://blog.quantinsti.com/favicon.png</url><title>Mathematics and Econometrics - Quantitative Finance &amp; Algo Trading Blog by QuantInsti</title><link>https://blog.quantinsti.com/</link></image><generator>Ghost 3.15</generator><lastBuildDate>Sat, 02 May 2026 07:56:29 GMT</lastBuildDate><atom:link href="https://blog.quantinsti.com/tag/mathematics-econometrics/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Beyond the Hype: What "Independent Events" REALLY Mean for Your Trades]]></title><description><![CDATA[Explore how statistically independent events help cut through market noise and shape reliable trading strategies. Understand independence, correlation, and cointegration with practical examples and algorithmic use cases.]]></description><link>https://blog.quantinsti.com/independent-events/</link><guid isPermaLink="false">683ff74834b4462776ec1362</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Chainika Thakar]]></dc:creator><pubDate>Wed, 18 Jun 2025 12:58:59 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/aacashi-n-9a4533223/">Aacashi Nawyndder</a> and <a href="https://www.linkedin.com/in/chainika-bahl-thakar-b32971155/">Chainika Thakar</a></p><h3 id="tl-dr">TL;DR </h3><p>Understanding probability, independence, correlation, and cointegration is key to building robust trading strategies. While correlation shows short-term co-movements, cointegration captures long-term ties, and independence means no influence between variables. Visual tools and Python-based analysis help identify these relationships, supporting smarter diversification and precise hedging. Algorithms and AI further apply these ideas across strategies, but real-world shifts and human biases remind us that market relationships evolve. Mastering these concepts enables more adaptive, data-driven trading.</p><p>This blog covers:</p><!--kg-card-begin: html--><ul>
  <li><a href="#the-building-blocks">The Building Blocks</a></li>
  <li><a href="#what-is-independence-statistically">What is Independence, Statistically?</a></li>
  <li><a href="#understanding-the-concepts-independence-correlation-and-cointegration-defined">Understanding the Concepts: Independence, Correlation, and Cointegration Defined</a></li>
  <li><a href="#seeing-is-believing-visual-and-quantitative-tools">Seeing is Believing: Visual and Quantitative Tools</a></li>
  <li><a href="#from-brain-food-to-real-action-leveraging-independence-in-your-trading-arsenal">From Brain Food to Real Action: Leveraging Independence in Your Trading Arsenal</a></li>
  <li><a href="#the-human-factor-data-science-tools-and-our-own-brain-quirks">The Human Factor: Data Science Tools and Our Own Brain Quirks</a></li>
  <li><a href="#reality-check-limitations-and-caveats">Reality Check: Limitations and Caveats</a></li>
   <li><a href="#frequently-asked-questions">Frequently Asked Questions</a></li>
</ul>
<!--kg-card-end: html--><hr><p>Ever look at the stock market and feel like it’s just a blur of randomness—spikes, dips, and noise with no clear rhyme or reason? You’re not alone. But here’s the thing: beneath the chaos, there <em>are</em> patterns. And one of the most powerful tools for spotting them is a statistical gem called <strong>independent events</strong>.</p><p>Forget the dry textbook stuff for a moment. This concept isn’t just academic—it’s practical. It’s the key to recognising signals that truly stand apart from the usual market noise. It’s how you start building a portfolio where one bad day doesn’t wreck your entire plan. And it’s the secret behind smarter, sharper strategies that don’t just ride the market’s mood—they cut through it.</p><h3 id="prerequisites">Prerequisites</h3><p>To grasp the concepts of statistical independence, correlation, and cointegration in trading, it's important to start with foundational knowledge in probability and statistics. Begin with<a href="https://blog.quantinsti.com/probability-trading/"> Probability in Trading</a>, which introduces the role of probabilistic thinking in financial markets. Follow it with<a href="https://blog.quantinsti.com/statistics-probability-distribution/"> Statistics &amp; Probability Distribution</a>, where you’ll learn about key statistical measures and how they apply to market data. These concepts are critical for interpreting market relationships and designing robust trading strategies. You can further reinforce your foundation with the Statistics &amp; Probability for Trading Quantra course, which offers interactive content tailored for market practitioners.</p><p>Complement this understanding with<a href="https://blog.quantinsti.com/stock-market-data-analysis-python/"> Stock Market Data: Analysis in Python</a>, which walks through acquiring and processing real market data—a vital step before running statistical models. For coding fluency,<a href="https://blog.quantinsti.com/python-programming/"> Basics of Python Programming</a> and the<a href="https://quantra.quantinsti.com/course/python-trading-basic"> Python for Trading (Basic)</a> course offer hands-on experience with Python, ensuring you're equipped to analyze time series and build models effectively.</p><p>So, in this guide, we're going to take a journey together. Not just to define these terms, but to truly <em>internalize</em> them. We'll explore:</p><ul><li>The core idea of independence and what it means in trading</li><li>A little bit of simple math to keep us grounded (I promise, not too scary!).</li><li>Clear examples from everyday life and, of course, the financial battleground.</li><li>A good look at what independence, correlation, and cointegration actually <em>are</em>, and critically, how they’re <em>different</em>.</li><li>Actionable ways to weave this knowledge into robust trading strategies and risk management.</li><li>Expanded, real-world algorithmic trading examples, showing these concepts in action.</li><li>The essential caveats – because no concept is a magic bullet.</li></ul><p>Ready to move past just scratching the surface and get a real handle on this?</p><p>Let's dive in!</p><hr><h2 id="the-building-blocks">The Building Blocks</h2><p>Alright, before we dive deeper, let's make sure we're speaking the same language. Here are a few foundational concepts:</p><ul><li><strong>Probability:</strong> Simply put, this is the measure of how likely an event is to occur. It’s expressed on a scale from 0 (impossible) to 1 (it’s a sure thing!). <br>Mathematically, if A is any event, then P(A) is the probability that event A occurs.</li><li><strong>Random Variable:</strong> Think of this as a variable whose value is determined by the outcome of a random phenomenon.The daily price wiggle of a stock? A classic example.</li><li><strong>Conditional Probability:</strong> This is the chance of something happening <em>given that something else has already happened</em>. We write it as P(A|B) – "the probability of A, if B has occurred." This is super important for understanding events that <em>aren't</em> independent (dependent events). If A and B <em>are</em> dependent, then:</li></ul><p>P(A and B) = P(A) × P(B|A)</p><hr><h2 id="what-is-independence-statistically">What is Independence, Statistically?</h2><p>Two events are independent if one happens without changing the odds of the other happening. They're effectively in their own lanes.</p><p>Think: Event A is "Stock X goes up," and Event B is "It rains today." If they're independent, Stock X's rise (or fall) has zero impact on whether it rains, and the rain isn't bothered by what Stock X is doing.</p><p>Mathematically, this means knowing A happened doesn't change B's odds, so the probability of B given A (P(B|A)) is just the same as B's original probability (P(B)). Remember our conditional probability rule for any two events: P(A and B) = P(A) × P(B|A)? Well, for independent events, since P(B|A) simply equals P(B), the formula simplifies nicely to:</p><p>P(A and B) = P(A) × P(B)</p><p><br>Essentially, you just multiply their individual chances.</p><hr><h2 id="spotting-independence-from-daily-life-to-market-dynamics">Spotting Independence: From Daily Life to Market Dynamics</h2><p>It’s always easier to grasp these ideas when you see them in action. In everyday life, independent events show up in things like flipping two coins or rolling a pair of dice—where one outcome doesn’t affect the other.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/06/Independence-dice-image.jpg" class="kg-image" alt="Spotting Independence"></figure><p><a href="https://www.numberanalytics.com/blog/unveiling-chance-dice-cards-coins-experiments">Source</a></p><p>Extending this idea to Financial Markets and Trading:</p><ul><li><strong>Super Diversified Global Assets:</strong> Think about assets from totally different parts of the world and the economy. Say, bonds from a city in California and shares in a tech startup in Bangalore, India. They're likely operating under very different economic pressures and business drivers. Now, in our super-connected global market, are any two assets <em>perfectly</em>, 100% statistically independent? Probably not. But this kind of diversification aims to get them as close as possible, with low correlation <strong>(Markowitz, 1952)</strong>. A crisis hitting one is much less likely to wallop the other in the same way directly. True statistical independence is more of an ideal we shoot for.</li><li><strong>Unrelated Industry Performance (Usually):</strong> The stuff that makes cocoa bean prices jump (like weather in West Africa or crop diseases) is generally pretty separate from what drives the stock price of a big aerospace defense company (think government contracts or global political tensions).</li></ul><p><strong>A Quick Heads-Up on a Common Mix-Up:</strong><br><br>Sometimes you'll see two things react to the <em>same</em> event but in totally opposite ways.</p><p>Take the early days of the COVID-19 pandemic, for instance. E-commerce giants like Amazon saw demand skyrocket as we all started shopping online from our couches. Meanwhile, airline companies like Delta watched their revenues nosedive because no one was flying.<br>It's super tempting to look at that and think, "Aha! Independent events!" because their fortunes went in completely different directions. But hold on – this isn't actually statistical independence.<br>It’s a classic case of strong negative correlation. Both were reacting to the <em>same</em> global event (the pandemic), just in opposite ways because of how it hit their specific businesses. For example, <strong>Baker et al. (2020)</strong> reported a very strong negative correlation-around -0.82 between Amazon and Delta in mid-2020.</p><p>So, just because things move in polar opposite directions doesn't mean they're truly independent of each other. It's a subtle but important difference to keep in mind!</p><hr><h2 id="understanding-the-concepts-independence-correlation-and-cointegration-defined">Understanding the Concepts: Independence, Correlation, and Cointegration Defined</h2><p>Let's break down these crucial terms individually before we compare them.</p><p><strong>What is Statistical Independence?</strong><br>Independence, in a statistical sense, signifies a complete lack of predictive power between two events or variables. Variable X gives you no clues about Variable Y, and Y offers no hints about X. There's no hidden string connecting them, no shared underlying reason that would make them move together or apart in any predictable way.</p><p><strong>What is Correlation?</strong><br>Correlation is a number that tells us how much and in what direction the <em>returns</em> (like the daily percentage change) of two assets tend to move together. It’s a score from -1 to +1:</p><ul><li><strong>+1 (Perfect Positive Correlation):</strong> This means that the assets' returns move perfectly in the same direction. When one goes up, the other goes up by a proportional amount, and vice versa.</li><li><strong>-1 (Perfect Negative Correlation):</strong> This indicates that the assets' returns move perfectly in opposite directions.When one goes up, the other goes down by a proportional amount.</li><li><strong>0 (Zero Correlation): </strong>This shows there's no clear <em>linear</em> connection in how their returns change.</li></ul><p>Correlation is usually about how things co-move in the shorter term.<br>Craving the full scoop? <a href="https://blog.quantinsti.com/covariance-correlation/">This</a> blog’s got you covered.</p><p><strong>What is Cointegration?</strong><br>This one's a bit more nuanced and thinks long-term. It’s about when two or more time series (like the prices of assets) are individually wandering around without a clear anchor (we call this non-stationary – they have trends and don't snap back to an average). BUT, if you combine them in a certain linear way, that <em>combination</em> is stationary – meaning it tends to hang around a stable average over time. So, even if individual prices drift, cointegration means they're tethered together by some deep, long-run economic relationship <strong>(Engle &amp; Granger, 1987)</strong>.</p><p>Classic Example: Think crude oil and gasoline prices. Both might trend up or down over long stretches due to inflation or significant economic shifts. However, the <em>spread</em> (the difference) between their prices, which is related to refinery profits, often hovers around a historical average. They can't stray too far from each other for too long.</p><h3 id="comparing-these-terms-">Comparing these terms:</h3><p>Now, let's see how these concepts stand apart – a critical distinction for any serious trader.</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><span style="font-weight: 400;">Feature</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Independence</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Correlation</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Cointegration</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Nature of Link</span></p>
</td>
<td>
<p><span style="font-weight: 400;">No statistical relationship at all (beyond luck).</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Measures only linear co-movement of asset returns.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Describes a long-term equilibrium relationship between asset prices.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Time Horizon</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Not really about time, just the lack of a link.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Usually a shorter-term thing (days, weeks, months). Can change fast!</span></p>
</td>
<td>
<p><span style="font-weight: 400;">A longer-term property. They might stray short-term but should come back.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">What's Measured</span></p>
</td>
<td>
<p><span style="font-weight: 400;">The absence of any predictive power.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">The strength &amp; direction of a linear relationship in returns.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Whether prices are tethered in the long run.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Data Used</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Can apply to any events or variables.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Typically calculated on asset returns (e.g., % changes).</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Analyzed using asset price levels.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Trading Angle</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Awesome for true diversification (less likely to tank together).</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Good for short-term hedging, seeing near-future co-moves. Low correlation is good for diversification.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Basis for "pairs trading" &ndash; betting on the spread between two cointegrated assets returning to normal.</span></p>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p><!--kg-card-end: html--><p><strong>Super Important Point:  Zero Correlation ≠ Independence!</strong><br>This is a classic trip-up! Two assets can have zero <em>linear</em> correlation but still be dependent. Imagine Asset A does great when Asset B is either doing <em>really</em> well or <em>really</em> badly (picture a U-shape if you plotted them). The linear correlation might be near zero, but they're clearly not independent; knowing Asset B's extreme performance tells you something about Asset A.</p><hr><p><strong>Recap:</strong> <em>Independence means no relationship; correlation is about short-term linear return patterns; cointegration points to long-term price relationships. Understanding these nuances is vital for building robust strategies.</em></p><hr><h2 id="seeing-is-believing-visual-and-quantitative-tools">Seeing is Believing: Visual and Quantitative Tools</h2><p>Visualizing data and quantifying relationships can transform abstract concepts into actionable insights.</p><h3 id="price-charts-scatter-plots-"><strong>Price Charts &amp; Scatter Plots:</strong></h3><p>As mentioned, overlaying price charts (like the AMZN vs. DAL example) or creating scatter plots of returns can offer initial clues. A scatter plot of returns for two truly independent assets would look like a random cloud with no discernible pattern.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/06/No-correlation.png" class="kg-image" alt="No correlation"></figure><p>Left: Random scatter indicating no correlation (independent variables), Right: Pattern showing a non-linear relationship (non-linear dependent variables)<br><a href="https://www.geeksforgeeks.org/scatter-diagram-correlation-meaning-interpretation-example/">Source</a></p><p><strong>Beware!</strong> For reliable analysis, always use high-quality historical data from reputable providers like Yahoo Finance, Bloomberg, Refinitiv, or directly from the exchanges. Garbage in, garbage out!</p><h3 id="calculating-correlation-with-python-"><strong>Calculating Correlation with Python:</strong></h3><p>Don't worry if you're not a coder, but for those who are, a simple Python script can quickly show you the linear relationship</p><p><strong>Python code snippet:</strong></p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/0572c5bf17ca37b04e4da77d918760bf.js"></script><!--kg-card-end: html--><h3 id="output-"><br><strong>Output:</strong></h3><!--kg-card-begin: html--><pre>
yf.download() has changed argument auto_adjust default to True
Ticker       CVX       XOM
Ticker
CVX     1.000000  0.837492
XOM     0.837492  1.000000
Ticker      AAPL      MSFT
Ticker
AAPL    1.000000  0.547987
MSFT    0.547987  1.000000
Ticker       GLD       SPY
Ticker
GLD     1.000000  0.004044
SPY     0.004044  1.000000 </pre><!--kg-card-end: html--><p>The correlation matrix for XOM/CVX shows a high 0.837492, meaning these oil stocks’ returns move closely together, driven by similar market factors. AAPL/MSFT (0.547987, moderate) and GLD/SPY (0.004044, near-zero) indicate tech stocks have some co-movement, while gold and the S&amp;P 500 are, possibly, nearly independent, otherwise, they have a non-linear correlation.</p><hr><h2 id="from-brain-food-to-real-action-leveraging-independence-in-your-trading-arsenal">From Brain Food to Real Action: Leveraging Independence in Your Trading Arsenal</h2><p>This isn't just interesting theory; it's about giving you a real strategic advantage.</p><ul><li><strong>Next-Level Diversification:</strong> True diversification isn't just about owning many different assets; it's about owning assets whose price movements are, as much as possible, driven by <em>independent factors</em>. This is your best shield against unexpected shocks in one part of your portfolio.Want to learn more ? Check out <a href="https://blog.quantinsti.com/portfolio-management-strategy-python/">this</a> blog ! </li><li><strong>Precision Hedging:</strong> Hedging is about taking positions to protect against potential losses. Understanding independence (or the lack of it!) helps you pick better hedges – assets that are likely to move predictably (often negatively correlated) against your primary holdings under specific conditions, or assets that offer a safe haven due to their independent nature.</li><li><strong>Building Resilient Portfolios:</strong> By thoughtfully mixing asset classes (stocks, bonds, commodities, real estate, alternative stuff) that have historically shown low correlation and are affected by different big-picture economic drivers, you can build portfolios that are designed to handle a wider variety of market storms.<br></li><li><strong>Navigating Volatility Storms:</strong> When markets freak out, correlations often spike—everyone panics and does the same thing (herd behaviour). Knowing this and which assets <em>might</em> keep some independence (or even become negatively correlated, like some "safe-haven" assets) is key for quick-thinking risk management.</li></ul><h3 id="modern-tools-that-amp-up-these-ideas-">Modern Tools That Amp Up These Ideas:</h3><ul><li><strong>Risk Parity Models:</strong> These are smart allocation strategies that try to make sure each asset class in your portfolio contributes an equal amount of <em>risk</em>, not just an equal amount of money. This relies heavily on good estimates of volatility and, you guessed it, correlations between assets.<br>Keen to learn more ? <a href="https://blog.quantinsti.com/portfolio-management-strategy-python/">This</a> blog has you covered!</li><li><strong>AI and Machine Learning:</strong> Yep, AI can sift through massive piles of data to find complex, non-linear connections and fleeting moments of independence that a human might totally miss. This can lead to more dynamic and quick-to-adapt portfolio changes.</li><li><strong>The Rise of Alternative Data: </strong>We're talking info from unusual places—satellite pics of oil tankers, credit card spending data, real-time supply chain info, what people are saying on social media. This can give unique, potentially independent clues about what's happening with the economy or specific companies, giving you an edge if you know how to read it.</li></ul><hr><h2 id="algorithmic-trading-in-action-selected-examples-of-independence-at-play">Algorithmic Trading in Action: Selected Examples of Independence at Play</h2><p>The ideas of independence, dependence, correlation, and cointegration are the secret sauce in many fancy trading algorithms. Here’s a peek at some key examples, especially how they relate to these concepts:</p><h3 id="cross-asset-global-diversification-algorithms-">Cross-Asset &amp; Global Diversification Algorithms:</h3><ul><li><strong>How it works:</strong> These algorithms constantly juggle portfolios across diverse asset classes (stocks, bonds, commodities, currencies, real estate) and geographies. They continuously monitor correlations and volatility, trying to keep diversification at a target level.</li><li><strong>Relevance of Independence:</strong> The whole point is to mix assets with low, or ideally zero, correlation that comes from <em>independent</em> economic drivers. For example, an algo might buy more Japanese stocks if it thinks their performance is, for the moment, independent of what's happening in the US market due to Japan's specific local policies. The dream is that a dip in one area (say, US tech stocks) is balanced out or barely felt by others (like emerging market bonds or gold).</li></ul><h3 id="factor-based-investing-algorithms-">Factor-Based Investing Algorithms:</h3><ul><li><strong>How it works:</strong> These algorithms construct portfolios by targeting specific, well-studied "factors" that have historically driven returns– things like Value (cheap stocks), Momentum (stocks on a roll), Quality (solid companies), Low Volatility (less jumpy stocks), or Size (smaller companies). These factors were popularized in foundational work like <strong>Fama and French (1993)</strong>, which identified common risk factors influencing stock and bond returns.</li><li><strong>Relevance of Independence:</strong> The idea is that these different factors produce streams of returns that are, to some degree, independent of each other and of the overall market's general movement (beta) over the long haul. An algo might lean a portfolio towards factors expected to do well in the current economic climate or that offer diversification because they don't correlate much with other factors already in the portfolio.<br>Want to dig deeper? Check out the full breakdown in <a href="https://blog.quantinsti.com/factor-investing/">this</a> blog.</li></ul><h3 id="event-driven-strategies-focusing-on-specific-news-">Event-Driven Strategies (Focusing on Specific News):</h3><ul><li><strong>How it works:</strong> Algos are built to trade around specific, known corporate or economic events – earnings calls, merger announcements, FDA drug approvals, key economic data releases (like inflation or job numbers).</li><li><strong>Relevance of Independence:</strong> The strategy often banks on the market's immediate reaction to the <em>specific news</em> being somewhat independent of the broader market noise at that precise moment. For example, if Company A has a great earnings surprise, its stock might pop even if the overall market is blah or down, all thanks to info specific to Company A.</li></ul><h3 id="ai-driven-sentiment-analysis-alternative-data-integration-">AI-Driven Sentiment Analysis &amp; Alternative Data Integration:</h3><ul><li><strong>How it works:</strong> Machine learning models chew through tons of text from news, social media, and financial reports to gauge sentiment (positive, negative, neutral) towards specific assets or the market. Alternative data (like satellite pics of store parking lots, web scraping of job ads, geolocation data) is also used to find non-traditional trading signals.</li><li><strong>Relevance of Independence:</strong> The big idea here is that these data sources can offer insights or signals that are independent of traditional financial data (price, volume, company financials). For example, a sudden burst of negative online chatter about a product, spotted before any official sales numbers are out, could be an independent early warning sign for the company's stock.</li></ul><p>Want to dive deeper? Two more strategies that lean heavily on the principles of independence and correlation are <strong>Market-Neutral &amp; Statistical Arbitrage (StatArb)</strong> and <strong>Pairs Trading (based on Cointegration)</strong>. Check out how they work in these quick reads:<br><a href="https://blog.quantinsti.com/statistical-arbitrage/">https://blog.quantinsti.com/statistical-arbitrage/</a><br><a href="https://blog.quantinsti.com/pairs-trading-basics/">https://blog.quantinsti.com/pairs-trading-basics/</a></p><hr><p><strong>Recap:</strong> <em>Sophisticated algorithms leverage a deep understanding of independence, correlation, and cointegration to try and find that extra bit of profit (alpha), manage risk, and diversify effectively across all sorts of global markets and assets.</em></p><hr><h2 id="the-human-factor-data-science-tools-and-our-own-brain-quirks">The Human Factor: Data Science Tools and Our Own Brain Quirks</h2><p>Even though these concepts are statistical, it's humans doing the trading, and humans are, well, human – full of biases!</p><ul><li><strong>Data Science: Your Quantitative Lens:</strong> Spotting genuine independence in all the market noise is tough. Data scientists have a whole toolkit:</li><li><strong>Rigorous Statistical Tests:</strong> Formal tests like the Pearson correlation coefficient, Spearman rank correlation (for non-linear monotonic relationships), and specific tests for cointegration (e.g., Engle-Granger, <a href="https://blog.quantinsti.com/johansen-test-cointegration-building-stationary-portfolio/">Johansen</a>) are must-haves.</li><li><strong>Advanced Time Series Analysis:</strong> Techniques like <a href="https://blog.quantinsti.com/forecasting-stock-returns-using-arima-model/">ARIMA</a>, <a href="https://blog.quantinsti.com/value-at-risk/">VAR</a>, and <a href="https://blog.quantinsti.com/garch-gjr-garch-volatility-forecasting-python/">GARCH</a> models help to understand dependencies within and between time series data, separating real patterns from random noise.</li><li><strong>Machine Learning Power:</strong> AI algorithms can dig up subtle, non-linear patterns of dependence or conditional independence that simpler linear models would completely miss.</li><li><strong>Behavioral Finance: Mind Traps to Avoid:</strong> </li></ul><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/06/Behavioural-finance.jpg" class="kg-image" alt="Behavioural finance"></figure><p><a href="https://thedecisionlab.com/biases/gamblers-fallacy">Source</a><br><br>Our brains are wired to find patterns, sometimes even where none exist. Here are a few common mental traps that can mess up a trader's judgment about independence:</p><ul><li><strong>The Gambler's Fallacy:</strong> Wrongly believing that if an independent event (like a stock closing up) has happened a few times in a row, the opposite is now "due" to happen (Nope, each day is a new roll of the dice if they're truly independent</li><li><strong>Representative Bias: </strong>Judging how likely something is based on how much it looks like a pattern or stereotype you already have in your head, while ignoring the actual underlying stats. For example, assuming oil stocks XOM and CVX are independent in Jan 2024 because they’re different companies, despite a high 0.84 correlation in 2023 returns showing strong dependence.</li><li><strong>Confirmation Bias:</strong> We all do this – looking for, interpreting, and remembering information that confirms what we already believe about how assets are connected, and tuning out evidence that says otherwise. For instance, a trader might focus on a brief period of near-zero correlation (e.g., 0.05 between GLD and SPY in mid-2023) to assume independence, ignoring a longer-term 0.4 correlation indicating dependence.</li></ul><p>Just knowing these biases exist is the first huge step towards making more objective, data-driven trading decisions.</p><hr><h2 id="reality-check-limitations-and-caveats">Reality Check: Limitations and Caveats</h2><p>As incredibly useful as all this is, we need to apply the idea of statistical independence with a good dose of realism:</p><ul><li><strong>The Myth of Perfect Independence:</strong>  In our super-connected global financial world, finding assets that are <em>perfectly</em>, always independent is like finding a unicorn. Big systemic shocks – a global pandemic, a major financial meltdown, a widespread geopolitical crisis – can make correlations between seemingly unrelated assets suddenly shoot towards 1 (all move together) or -1 (all move opposite) as everyone rushes for (or away from) perceived safety at the same time.</li><li><strong>Models are Guides, Not Crystal Balls:</strong> All statistical models, including those used to check for independence or correlation, are simplifications of a far more complex reality. They rely on historical data and assumptions that may not hold true in the future. Market regimes shift, and relationships evolve.</li><li><strong>Dynamic, Not Static, Relationships:</strong> How independent or correlated assets are isn't set in stone. It's a moving target that changes over time thanks to evolving economies, tech breakthroughs, new rules, and what investors are feeling. What looks independent today might be strongly correlated tomorrow.</li></ul><hr><h3 id="conclusion">Conclusion</h3><p>Understanding independent events – and how this concept relates to yet differs from correlation and cointegration – is vital for enhancing your market perspective, portfolio building, and risk management. Consider it an ongoing journey of refinement.</p><p>By truly grasping these principles, you can:</p><ul><li><strong>Forge Resilient Portfolios:</strong> Move beyond simple diversification to build portfolios designed to handle a wider array of market shocks by seeking genuinely independent return sources.</li><li><strong>Execute Precise Hedging:</strong> Gain a clearer understanding of asset relationships to hedge unwanted risks more effectively.</li><li><strong>Uncover Hidden Opportunities:</strong> Recognize that many strategies are built on exploiting temporary deviations from statistical relationships or capitalizing on true independencies.</li><li><strong>Cultivate Adaptability:</strong> Acknowledge that market relationships are not static, encouraging continuous learning and strategy adjustments.</li></ul><p>Financial markets are vast, interconnected, and constantly evolving. While perfect prediction remains elusive, a solid grasp of concepts like statistical independence provides a better compass to navigate, distinguish signals from noise, and identify opportunities.</p><p>For those seeking a practical, hands-on learning experience, Quantra by QuantInsti offers excellent courses. The <a href="https://quantra.quantinsti.com/course/quantitative-portfolio-management">Quantitative Portfolio Management</a> Course covers techniques like Factor Investing and Risk Parity, while the <a href="https://www.quantinsti.com/epat">Executive Programme in Algorithmic Trading (EPAT)</a> provides a comprehensive path to mastering trading strategies.</p><p>Embracing this learning, questioning assumptions, and letting data guide you will significantly boost your ability to thrive in this ever-changing environment. The effort invested in understanding these concepts is a powerful independent variable in your journey to trading mastery.</p><hr><h3 id="references"><strong>References</strong></h3><ul><li>Baker, S. R., Bloom, N., Davis, S. J., &amp; Terry, S. J. (2020). COVID-Induced Economic Uncertainty. NBER Working Paper No. 26983. <br><a href="https://www.nber.org/papers/w26983">https://www.nber.org/papers/w26983</a></li><li>Markowitz, H. (1952). Portfolio Selection. The Journal of Finance, 7(1), 77–91.<br><a href="https://onlinelibrary.wiley.com/doi/10.1111/j.1540-6261.1952.tb01525.x">https://onlinelibrary.wiley.com/doi/10.1111/j.1540-6261.1952.tb01525.x</a></li><li>Engle, R. F., &amp; Granger, C. W. J. (1987). Co-Integration and Error Correction: Representation, Estimation, and Testing. Econometrica, 55(2), 251–276.<br><a href="https://www.jstor.org/stable/1913236?origin=crossref">https://www.jstor.org/stable/1913236?origin=crossref</a></li><li>Fama, E. F., &amp; French, K. R. (1993). Common Risk Factors in the Returns on Stocks and Bonds. Journal of Financial Economics, 33(1), 3–56. <a href="https://doi.org/10.1016/0304-405X(93)90023-5">https://doi.org/10.1016/0304-405X(93)90023-5</a></li></ul><hr><h3 id="next-steps">Next Steps</h3><p>Once the basics are in place, the next step is to understand how statistical relationships between assets can inform strategy design. <a href="https://blog.quantinsti.com/factor-investing/">Factor Investing</a> helps you recognise systematic return drivers and portfolio construction techniques based on factor exposure. Building on this,<a href="https://blog.quantinsti.com/covariance-correlation/"> Covariance vs Correlation</a> offers a deeper dive into how asset movements relate—fundamental for diversification and hedging.</p><p>You can then progress to<a href="https://blog.quantinsti.com/johansen-test-cointegration-building-stationary-portfolio/"> Johansen Test &amp; Cointegration</a> to understand how long-term equilibrium relationships can signal profitable trading opportunities. This blog pairs well with<a href="https://blog.quantinsti.com/stationarity/"> Stationarity in Time Series</a> and<a href="https://blog.quantinsti.com/hurst-exponent/"> Hurst Exponent</a>, both essential for assessing the stability and memory of financial data.</p><p>To apply these concepts practically, explore<a href="https://blog.quantinsti.com/statistical-arbitrage/"> Statistical Arbitrage</a>, which uses cointegration and mean reversion principles to build pair-based trading strategies. The Pairs Trading with Statistical Arbitrage course teaches you how to develop and test such strategies using Python. For those interested in broader strategy implementation,<a href="https://quantra.quantinsti.com/course/backtesting-trading-strategies"> Backtesting Trading Strategies</a> provides the tools to evaluate historical performance.</p><p>Quantitative traders can also benefit from Portfolio Optimization, which builds on correlation insights to construct efficient portfolios. For deeper modeling and predictive techniques, the<a href="https://quantra.quantinsti.com/learning-track/machine-learning-deep-learning-trading-1"> Machine Learning &amp; Deep Learning in Trading</a> track offers extensive coverage of ML algorithms for forecasting and classification.</p><p>Finally, if you're looking to tie all of this together into a comprehensive career-ready framework, the<a href="https://www.quantinsti.com/epat"> Executive Programme in Algorithmic Trading (EPAT)</a> provides in-depth training in statistical methods, machine learning, Python coding, portfolio theory, and real-world trading systems, making it ideal for serious professionals aiming to lead in quantitative finance.</p><hr><h2 id="frequently-asked-questions">Frequently Asked Questions </h2><h2 id="what-is-the-difference-between-correlation-and-cointegration"><strong>What is the difference between correlation and cointegration?</strong></h2><p>Correlation measures short-term co-movement between two variables, while cointegration identifies a long-term equilibrium relationship despite short-term deviations between two ore more non-stationary time series.</p><hr><h2 id="why-is-independence-important-in-trading"><strong>Why is independence important in trading?</strong></h2><p>Independence implies no influence between variables. Recognizing independent assets helps avoid false diversification and ensures that combined strategies aren't secretly overlapping.</p><hr><h2 id="how-does-cointegration-help-in-building-trading-strategies"><strong>How does cointegration help in building trading strategies?</strong></h2><p>Cointegration allows you to build pairs or mean-reversion strategies by identifying asset combinations that revert to a stable long-term relationship, even if each asset is volatile on its own.</p><hr><h2 id="can-correlation-be-used-for-portfolio-diversification"><strong>Can correlation be used for portfolio diversification?</strong></h2><p>Yes, but with caution. Correlation is dynamic and can break down during market stress. The conclusion is the following: the lower the correlation, the better for diversification in asset allocation. </p><hr><h2 id="how-can-python-be-used-to-identify-these-relationships"><strong>How can Python be used to identify these relationships?</strong></h2><p>Python libraries like statsmodels, scipy, and pandas provide tools to test for correlation, cointegration (e.g., Engle-Granger test), and independence, helping quants validate strategy assumptions.</p><hr><h2 id="how-do-ai-and-algorithms-leverage-these-concepts"><strong>How do AI and algorithms leverage these concepts?</strong></h2><p>AI models can automatically detect relationships like cointegration or conditional independence, improving strategy development, regime detection, and risk modeling.</p><hr><h2 id="what-are-the-risks-of-ignoring-these-concepts"><strong>What are the risks of ignoring these concepts?</strong></h2><p>Ignoring them can lead to overfitting, poor or wrong diversification, or failed hedges—ultimately resulting in unexpected drawdowns during market shifts.</p><hr><h2 id="are-these-relationships-stable-over-time"><strong>Are these relationships stable over time?</strong></h2><p>Not always. Market regimes, macro events, and structural shifts can alter statistical relationships. Continuous monitoring and model updates are essential.</p><hr><h3 id="acknowledgements">Acknowledgements</h3><p>This blog post draws heavily from the information and insights presented in the following texts:</p><p>Wasserman, L. (2004). All of Statistics: A Concise Course in Statistical Inference. Springer. <a href="https://link.springer.com/book/10.1007/978-0-387-21736-9">https://link.springer.com/book/10.1007/978-0-387-21736-9</a></p><p>1. Casella, G., &amp; Berger, R. L. (2002). Statistical Inference (2nd ed.). Duxbury. <a href="https://www.cengage.com/c/statistical-inference-2e-casella-berger/9780534243128/">https://www.cengage.com/c/statistical-inference-2e-casella-berger/9780534243128/</a></p><p>2. Ross, S. M. (2014). A First Course in Probability (9th ed.). Pearson.<br><a href="https://www.pearson.com/en-us/subject-catalog/p/first-course-in-probability-a/P200000006334/9780134753119">https://www.pearson.com/en-us/subject-catalog/p/first-course-in-probability-a/P200000006334/9780134753119</a></p><p>3. Rodgers, J. L., &amp; Nicewander, W. A. (1988). Thirteen Ways to Look at the Correlation Coefficient. The American Statistician, 42(1), 59–66 <a href="https://www.tandfonline.com/doi/abs/10.1080/00031305.1988.10475524">https://www.tandfonline.com/doi/abs/10.1080/00031305.1988.10475524</a></p><hr><!--kg-card-begin: html--><p><em><small>Disclaimer: This blog post is for informational and educational purposes only. It does not constitute financial advice or a recommendation to trade any specific assets or employ any specific strategy. All trading and investment activities involve significant risk. Always conduct your own thorough research, evaluate your personal risk tolerance, and consider seeking advice from a qualified financial professional before making any investment decisions.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[From Logistic to Random Forests: Mastering Non-linear Regression Models]]></title><description><![CDATA[Master non-linear regression: Logistic, Quantile, Decision Trees, Random Forests, SVR for finance. Tackle complex patterns, enhance predictive modeling with these machine learning tools.]]></description><link>https://blog.quantinsti.com/types-regression-finance/</link><guid isPermaLink="false">6808eb5efc68ac288210fb44</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Vivek Krishnamoorthy]]></dc:creator><pubDate>Fri, 02 May 2025 11:19:30 GMT</pubDate><content:encoded><![CDATA[<p><strong>By</strong>: <a href="https://in.linkedin.com/in/vivekkrishnamoorthy">Vivek Krishnamoorthy</a>, <a href="https://www.linkedin.com/in/aacashi-n-9a4533223/">Aacashi Nawyndder</a> and <a href="https://www.linkedin.com/in/udisha-alok">Udisha Alok</a><br><br>Ever wish you had a crystal ball for the financial markets? While we can't <em>quite</em> do that, <strong>regression</strong> is a super useful tool that helps us find patterns and relationships hidden in data – it's like being a data detective!</p><p>The most common starting point is <strong>linear regression</strong>, which is basically about drawing the best straight line through data points to see how things are connected. Simple, right?</p><p>In <strong><a href="https://blog.quantinsti.com/advanced-regression-models-finance/">Part 1</a></strong> of this series, we explored ways to make those line-based models even better, tackling things like curvy relationships (Polynomial Regression) and messy data with too many variables (using Ridge and Lasso Regression). We learned how to refine those linear predictions.</p><p>But what if a line (even a curvy one) just doesn't fit? Or what if you need to predict something different, like a "yes" or "no"?</p><p>Get ready for <strong>Part 2</strong>, my friend!<strong> </strong>Where we venture beyond the linear world and explore a fascinating set of regression techniques designed for different kinds of problems:</p><ol><li><strong>Logistic Regression:</strong> For predicting probabilities and binary outcomes (Yes/No).</li><li><strong>Quantile Regression:</strong> For understanding relationships at different points in the data distribution, not just the average (great for risk analysis!).</li><li><strong>Decision Tree Regression:</strong> An intuitive flowchart approach for complex, non-linear patterns.</li><li><strong>Random Forest Regression:</strong> Harnessing the "wisdom of the crowd" by combining multiple decision trees for accuracy and stability.</li><li><strong>Support Vector Regression (SVR):</strong> A powerful method using "margins" to handle complex relationships, even in high dimensions.</li></ol><p>Let's dive into these powerful tools and see how they can unlock new insights from financial data!</p><hr><h3 id="prerequisites"><strong>Prerequisites</strong></h3><p>Hey there! Before we get into the good stuff, it helps to be familiar with a few key concepts. You can still follow along intuitively, but brushing up on these will give you a much better understanding. Here’s what to check out:</p><p><strong>1. Statistics and Probability</strong><br> Know the essentials—mean, variance, correlation, and probability distributions. New to this? <a href="https://blog.quantinsti.com/probability-trading/"><em>Probability Trading</em></a> is a great intro.</p><p><strong>2. Linear Algebra Basics</strong><br> Basics like matrices and vectors are super useful, especially for techniques like Principal Component Regression.</p><p><strong>3. Regression Fundamentals</strong><br> Get comfy with linear regression and its assumptions. <em><a href="https://blog.quantinsti.com/linear-regression/">Linear Regression in Finance</a></em> is a solid starting point.</p><p><strong>4. Financial Market Knowledge</strong><br> Terms like stock returns, volatility, and market sentiment will come up a lot. <a href="https://www.quantinsti.com/epat/statistics-financial-markets"><em>Statistics for Financial Markets</em></a> can help you brush up.</p><p><strong>5. Explore <a href="https://blog.quantinsti.com/advanced-regression-models-finance/">Part 1</a> of This Series</strong><br> Check out <a href="https://blog.quantinsti.com/advanced-regression-models-finance/">Part 1</a> for an overview of Polynomial, Ridge, Lasso, Elastic Net, and LARS. It’s not mandatory, but it provides excellent context for different regression types.</p><p>Once you're good with these, you’ll be all set to dive deeper into how regression techniques reveal insights in finance. Let’s get started!</p><hr><h2 id="what-exactly-is-regression-analysis">What Exactly is Regression Analysis?</h2><p>At its core, regression analysis models the relationship between a dependent variable (the outcome we want to predict) and one or more independent variables (predictors).</p><p>Think of it as figuring out the connection between different things – for instance, how does a company's revenue (the outcome) relate to how much they spend on advertising (the predictor)? Understanding these links helps you make educated guesses about future outcomes based on what you know. <br><br>When that relationship looks like a straight line on a graph, we call it linear regression – nice and simple!</p><hr><h2 id="what-makes-these-models-non-linear-">What Makes These Models 'Non-Linear'?</h2><p>Good question! In <a href="https://blog.quantinsti.com/advanced-regression-models-finance/">Part 1</a>, we mentioned that 'linear' in regression refers to how the model's coefficients are combined. </p><p>Non-linear models, like the ones we're exploring here, break that rule. Their underlying equations or structures don't just add up coefficients multiplied by predictors in a simple way. Think about Logistic Regression using that S-shaped curve (sigmoid function) to squash outputs between 0 and 1, or Decision Trees making splits based on conditions rather than a smooth equation, or SVR using 'kernels' to handle complex relationships in potentially higher dimensions.</p><p>These methods fundamentally work differently from linear models, allowing them to capture patterns and tackle problems (like classification or modelling specific data segments) that linear models often can't.</p><hr><h2 id="logistic-or-logit-regression">Logistic (or Logit) regression </h2><p>You use Logistic regression when the dependent variable (here, a dichotomous variable) is binary (think of it as a "yes" or "no" outcome, like a stock going up or down). It helps predict the binary outcome of an occurrence based on the given data. </p><p>It is a non-linear model that gives a logistic curve with values limited to between 0 and 1. This probability is then compared to a threshold value of 0.5 to classify the data. So, if the probability for a class is more than 0.5, we label it as 1; otherwise, it is 0. </p><p>This model is generally used to <a href="https://ieeexplore.ieee.org/document/8328543">predict the performance of stocks</a>. <br><br><em>Note:</em> You can not use <strong>linear regression</strong> here because it could give values outside the 0 to 1 range. Also, the dependent variable can take only two values here, so the residuals won’t be normally distributed about the predicted line.</p><p>Want to learn more? Check out this blog for more on <a href="https://blog.quantinsti.com/machine-learning-logistic-regression-python/">logistic regression</a> and how to use Python code to predict stock movement.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Linear-and-logistic.png" class="kg-image" alt="Linear and logistic"></figure><p><a href="https://www.saedsayad.com/logistic_regression.htm">Source</a></p><hr><h2 id="quantile-regression-understanding-relationships-beyond-the-average">Quantile Regression: Understanding Relationships Beyond the Average</h2><p>Traditional <a href="https://blog.quantinsti.com/linear-regression-assumptions-limitations/">linear regression</a> models predict the <strong>mean</strong> of a dependent variable based on independent variables. However, financial time series data often contain <a href="https://quantra.quantinsti.com/glossary/Skewness">skewness</a> and outliers, making linear regression unsuitable.<br></p><p>To solve this problem, <strong>Koenker and Bassett (1978)</strong> introduced quantile regression. Instead of modeling just the mean, it helps us see the relationship between variables at different points (quantiles and percentiles) in the dependent variable's distribution, such as:</p><ul><li><strong>10th percentile (low gains/losses)</strong></li><li><strong>50th percentile (median returns)</strong></li><li><strong>99th percentile (high gains/losses)</strong></li></ul><p>It estimates different quantiles (like medians or quartiles) of the dependent variables for the given independent variables, instead of just the mean. We call these <em>conditional</em> quantiles.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Quantiles.png" class="kg-image" alt="Quantiles"></figure><p><a href="https://scikit-learn.org/stable/auto_examples/linear_model/plot_quantile_regression.html">Source</a></p><p>Like <a href="https://blog.quantinsti.com/linear-regression-assumptions-limitations/#:~:text=Ordinary%20Least%20Squares%20(OLS)">OLS regression coefficients</a>, which show the changes from one-unit changes of the predictor variables, <strong>quantile regression</strong> coefficients show the changes in the <em>specified quantile</em> from one-unit changes in the predictor variables.</p><p><strong>Advantages:</strong></p><ul><li><strong>Robustness to Outliers</strong>: According to <strong>Lim et al. (2020)</strong>, regular linear regression <em>assumes</em> errors in the data are normally distributed, but this isn't reliable when you have outliers or extreme values ("fat tails").  Quantile regression handles outliers better because it focuses on minimizing <em>absolute</em> errors, not the squared ones like regular regression. This way the influence of extreme values is reduced, providing more reliable estimates in datasets that aren’t really “well behaved” (with heavy tails or skewed distributions) ​</li><li><strong>Estimating Conditional Median:</strong> The conditional median is estimated using the median estimator, which minimizes the sum of absolute errors.</li><li><strong>Handling Heteroskedasticity</strong>: OLS assumes <strong>constant variance of errors</strong> (homoskedasticity), but this is often unrealistic. Quantile regression allows for <strong>varying error variances</strong>, making it effective when predictor variables influence different parts of the response variable’s distribution <strong>(Koenker &amp; Bassett, 1978)</strong>.</li></ul><p>Let’s look at an example to better understand how quantile regression works:</p><p>Let's say you're trying to understand how the overall "mood" of the market (measured by a sentiment index) affects the daily returns of a particular stock. Traditional regression would tell you the average impact of a change in sentiment on the average stock return.</p><p>But what if you're particularly interested in <em>extreme</em> movements? Quantile regression is used here:</p><ul><li><strong>Looking at the 10th percentile:</strong> You could use quantile regression to see how a negative shift in market sentiment affects the <em>worst</em> 10% of potential daily returns (the big losses). It might show that negative sentiment has a much stronger negative impact during these extreme downturns than it does on average.</li><li><strong>Looking at the 90th percentile:</strong> Similarly, you could see how positive sentiment affects the <em>best</em> 10% of daily returns (the big gains). It might reveal that positive sentiment has a different (possibly larger or smaller) impact on these significant upward swings compared to the average.</li><li><strong>Looking at the 50th percentile (median):</strong> You can also see the impact of sentiment on the typical daily return (the median), which might be different from the effect on the average if the return distribution is skewed.</li></ul><p>So, instead of just one average effect, quantile regression gives you a more complete picture of how market sentiment influences different parts of the stock's return distribution, especially the potentially risky extreme losses. Isn’t that great?</p><hr><h2 id="decision-trees-regression-the-flowchart-approach">Decision Trees Regression: The Flowchart Approach</h2><p>Imagine trying to predict a numerical value – like the price of something or a company's future revenue. A <strong>Decision Tree</strong> offers an intuitive way to do this, working like a flowchart or a game of 'yes/no' questions.</p><p>A decision tree is divided into smaller and smaller subsets based on certain conditions related to the predictor variables. Think of it like this:</p><p><a href="https://blog.quantinsti.com/use-decision-trees-machine-learning-predict-stock-movements/">Decision trees</a>  start with your entire dataset and progressively splits it into smaller and smaller subsets at the nodes, thereby creating a tree-like structure. Each of the nodes where the data is split based on a condition is called an <strong>internal/split node</strong>, and the final subsets are called the <strong>terminal/leaf nodes</strong>.<br><br>In finance, decision trees may be used for classification problems like <a href="https://blog.quantinsti.com/decision-tree/">predicting</a> whether the prices of a financial instrument will go up or down.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Decision-tree-regression.png" class="kg-image" alt="Decision tree regression"></figure><p><a href="https://blog.quantinsti.com/decision-tree/">Source</a></p><p><strong>Decision Tree Regression</strong> is when we use a decision tree to predict continuous values (like the price of a house or temperature) instead of categories (like predicting yes/no or up/down).</p><p>Here’s how it works in regression:</p><ul><li>The tree asks a series of questions based on the input features (like “Is square footage &gt; 1500?”).</li><li>Based on the answers, the data point moves down the tree until it reaches a <strong>leaf</strong>.</li><li>In that leaf, the prediction is the <strong>average</strong> (or sometimes the median) of the actual values from the training data that also landed there.</li></ul><p>So, the tree splits the data into groups, and each group gets a fixed number as the prediction.</p><p><strong>Things to Watch Out For:</strong></p><ul><li><strong>Overfitting:</strong> Decision trees can get too detailed and match the training data <em>too</em> perfectly, making them perform poorly on new, unseen data.</li><li><strong>Instability:</strong> Small changes in the training data can sometimes lead to significantly different tree structures. (Techniques like Random Forests and <a href="https://blog.quantinsti.com/ensemble-methods-bagging-boosting/#:~:text=the%20AdaBoost%20algorithm.-,Gradient%20Boosting,-Just%20like%20AdaBoost">Gradient Boosting</a> often help with this).</li></ul><p>You have a full description of the model in this <a href="https://blog.quantinsti.com/use-decision-trees-machine-learning-predict-stock-movements/">blog</a> and its use in trading in this <a href="https://blog.quantinsti.com/decision-tree/#:~:text=Decision%20Trees%20for%20Regression&amp;text=Basically%20refer%20to%20the%20parameters,some%20limits%20to%20create%20it.">blog</a>.</p><p>To learn more about decision trees in trading check out <a href="https://quantra.quantinsti.com/course/decision-trees-analysis-trading-ernest-chan">this</a> Quantra course.</p><p>Let’s see a situation where this might be a useful tool:</p><p>Imagine you're trying to predict a company's sales revenue for the next quarter. You have data on its past performance and factors like: marketing spend in the current quarter, number of salespeople, the company's industry sector (e.g., Tech, Retail, Healthcare), etc.</p><p>The tree might ask: </p><p>"Marketing spend &gt; $500k?" If yes, "Industry = Tech?". Based on the path taken, you land on a <strong>leaf</strong>. </p><p>The prediction for a new company following that path would be the average revenue of all past companies that fell into that same leaf (e.g., the average revenue for tech companies with high marketing spend).</p><hr><h2 id="random-forest-regression-wisdom-of-the-crowd-for-predictions">Random forest regression: Wisdom of the Crowd for Predictions</h2><p>Remember how individual Decision Trees can sometimes be a bit unstable or might overfit the training data? What if we could harness the power of <em>many</em> decision trees instead of relying on just one?</p><p>That's the idea behind <strong>Random Forest Regression</strong>!</p><p>It's an "ensemble" method, meaning it combines multiple models (in this case, decision trees) to achieve better performance than any single one could alone. You can think of it using the "wisdom of the crowd" principle: instead of asking one expert, you ask many, slightly different experts and combine their insights. Generally, Random Forests perform significantly better than individual decision trees<strong> (Breiman, 2001)</strong>.</p><p><strong>How does the forest get “random”?</strong></p><p>The "random" part of Random Forest comes from two key techniques used when building the individual trees:</p><ol><li><strong>Random Data Subsets (</strong><a href="https://blog.quantinsti.com/ensemble-methods-bagging-boosting/"><strong>Bootstrapping</strong></a><strong>):</strong> Each tree in the forest is trained on a slightly different random sample of the original training data. This sample can be chosen "with replacement" (meaning some data points might be selected multiple times, and some might be left out for that specific tree). This ensures each tree sees a slightly different perspective of the data.</li><li><strong>Random Feature Subsets:</strong> When deciding how to split the data at each step inside a tree, the algorithm can only consider a <em>random selection</em> of the input features, not all of them. This stops one or two powerful features from dominating all the trees and encourages diversity.</li></ol><p><strong>Making Predictions (Regression = Averaging)</strong></p><p>To predict a value for new data, you run it through <em>every</em> tree in the forest. Each tree gives its own prediction. The Random Forest's final prediction is simply the <strong>average</strong> of all those individual tree predictions. This averaging smooths things out and makes the model much more stable.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Random-forest-regressor.png" class="kg-image" alt="Random forest regressor"></figure><p>Image representation of a Random forest regressor</p><p><strong>Why Use Random Forest Regression?</strong></p><ul><li><strong>High Accuracy:</strong> Often provides very accurate predictions.</li><li><strong>Robustness:</strong> Less prone to overfitting compared to single decision trees and handles outliers reasonably well.<strong> (Breiman, L. , 2001)</strong></li><li><strong>Non-linearity:</strong> Easily captures complex, non-linear relationships.</li><li><strong>Feature Importance:</strong> Can provide estimates of which predictors are most important.</li></ul><p><strong>Things to Consider:</strong></p><ul><li><strong>Interpretability:</strong> It acts more like a "black box." It's harder to understand exactly <em>why</em> it made a specific prediction compared to visualizing a single decision tree.</li><li><strong>Computation:</strong> Training many trees can be computationally intensive and require more memory.</li></ul><p>Check out this <a href="https://blog.quantinsti.com/random-forest-algorithm-in-python/">post</a> if you want to learn more about random forests and how they can be used in trading.</p><p>Think we’d leave you hanging? No way!</p><p>Here’s an example to help you better understand how random forests work in practice:</p><p>You want to predict how much a stock's price will swing (its volatility) next month, using data like recent volatility, trading volume, and market fear (VIX index).</p><p>A single decision tree might latch onto a specific pattern in the past data and give a jumpy prediction. A <strong>Random Forest</strong> approach is more robust:</p><p>It builds hundreds of trees. Each tree sees slightly different historical data and considers different feature combinations at each split. Each tree estimates the volatility. The final prediction is the average of all these estimates, giving a more stable and reliable forecast of future volatility than one tree alone could provide.</p><hr><h3 id="support-vector-regression-svr-regression-within-a-margin-of-error"><strong>Support vector regression (SVR): Regression Within a 'Margin’ of Error</strong></h3><p>You might be familiar with <a href="https://blog.quantinsti.com/support-vector-machines-introduction/">Support Vector Machines</a> (SVM) for classification. <strong>Support Vector Regression (SVR)</strong> takes the core ideas of SVM and applies them to <strong>regression tasks</strong> – that is, predicting continuous numerical values.</p><p>SVR approaches regression a bit differently than many other methods. While methods like standard linear regression try to minimize the error between the predicted and actual values for <em>all</em> data points, SVR has a different philosophy.</p><p><strong>The Epsilon (ε) Insensitive Tube:</strong></p><p>Imagine you're trying to fit a line (or curve) through your data points. SVR tries to find a "tube" or "street" around this line with a certain width, defined by a parameter called <strong>epsilon (ε)</strong>. The goal is to fit as many data points as possible <em>inside</em> this tube.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Support-vector-regression.png" class="kg-image" alt="Support vector regression"></figure><p>Image representation of Support vector regression: <a href="https://www.educba.com/support-vector-regression/">Source</a></p><p>Here's the key idea: For any data points that fall <em>inside</em> this ε-tube, SVR considers the prediction "good enough" and <strong>ignores their error</strong>. It only starts penalizing errors for points that fall <em>outside</em> the tube. This makes SVR less sensitive to small errors compared to methods that try to get <em>every</em> point perfect. The regression line (or hyperplane in higher dimensions) runs down the middle of this tube.</p><p><strong>Handling Curves (Non-Linearity):</strong></p><p>What if the relationship between your predictors and the target variable isn't straight? SVR uses a "<strong>kernel</strong> trick". This is like projecting the data into a higher-dimensional space where a complex, curvy relationship might look like a simpler straight line (or flat plane). By finding the best "tube" in this higher dimension, SVR can effectively model non-linear patterns. Common kernels include linear, polynomial, and RBF (Radial Basis Function). The best choice depends on the data.</p><p><strong>Pros:</strong></p><ul><li>Effective in high-dimensional spaces.</li><li>Can model non-linear relationships using kernels.</li><li>The ε-margin offers some robustness to small errors/outliers <strong>(Muthukrishnan &amp; Jamila, 2020)</strong>.</li></ul><p><strong>Cons:</strong></p><ul><li>Can be computationally slow on large datasets.</li><li>Performance is sensitive to parameter tuning (choosing ε, a cost parameter C, and the right kernel).</li><li>Interpretability can be less direct than linear regression.</li></ul><p>The explanation for the whole model can be found <a href="https://blog.quantinsti.com/support-vector-machines-introduction/">here</a>.</p><p>And if you want to learn more about how support vector machines can be used in trading, be sure to check out <a href="https://quantra.quantinsti.com/course/trading-machine-learning-classification-svm">this</a> blog, my friend! </p><p>By now, you probably know how this works, so let’s look at a real-life example that uses SVR:</p><p>Think about predicting the price of a stock option (like a call or put). Option prices depend on several complex, non-linear factors: the underlying stock's price, time left until expiration, expected future volatility (implied volatility), interest rates, etc.</p><p>SVR (especially with a non-linear kernel like RBF) is suitable for this. It can capture these complex relationships using the kernel trick. The ε-tube focuses on getting the prediction within an acceptable small range (e.g., predicting the price +/- 5 cents), rather than stressing about tiny deviations for every single option.</p><hr><h3 id="summary">Summary</h3><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><strong>Regression Model</strong></p>
</td>
<td>
<p><strong>One-Line Summary</strong></p>
</td>
<td>
<p><strong>One-Line Use Case</strong></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Logistic Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicts the probability of a binary outcome.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting whether a stock will go up or down.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Quantile Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Models relationships at different quantiles of the dependent variable's distribution.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Understanding how market sentiment affects extreme stock price movements.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Decision Trees Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicts continuous values by partitioning data into subsets based on predictor variables.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting a company's sales revenue based on various factors.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Random Forest Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Improves prediction accuracy by averaging predictions from multiple decision trees.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting the volatility of a stock.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Support Vector Regression (SVR)</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicts continuous values by finding a "tube" that best fits the data.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting option prices, which depend on several non-linearly related factors.</span></p>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p><!--kg-card-end: html--><hr><h3 id="conclusion"><strong>Conclusion</strong></h3><p>And that concludes our tour through the more diverse landscapes of regression! We've seen how <strong>Logistic Regression</strong> helps us tackle binary predictions, how <strong>Quantile Regression</strong> gives us insights beyond the average, especially for risk, and how <strong>Decision Trees</strong> and <strong>Random Forests</strong> offer intuitive yet powerful ways to model complex, non-linear relationships. Finally, <strong>Support Vector Regression</strong> provides a unique, margin-based approach practical even in high-dimensional spaces.</p><p>From the refined linear models in <strong><a href="https://blog.quantinsti.com/advanced-regression-models-finance/">Part 1</a></strong> to the varied techniques explored here, you now have a much broader regression toolkit at your disposal. Each model has its strengths and is suited for different financial questions and data challenges.</p><p>The key takeaway? Regression is not a one-size-fits-all solution. Understanding the nuances of different techniques allows you to choose the right tool for the job, leading to more insightful analysis and powerful predictive models.</p><p>And as you continue learning my friend, <strong>don’t just stop at theory</strong>. Keep exploring, keep practicing with real data, and keep refining your skills. Happy modeling!</p><p>Perhaps you're keen on a complete, holistic understanding of regression applied directly to trading? In that case, check out <a href="https://quantra.quantinsti.com/course/trading-with-machine-learning-regression">this</a> Quantra course.</p><p>If you're serious about taking your skills to the next level, consider <strong>QuantInsti’s </strong><a href="https://www.quantinsti.com/epat"><strong>EPAT</strong></a><strong> program</strong>—a solid path to mastering financial algorithmic trading.<br><br><em>With the right training and guidance from industry experts, it can be possible for you to learn it as well as Statistics &amp; Econometrics, Financial Computing &amp; Technology, and Algorithmic &amp; Quantitative Trading. These and various aspects of Algorithmic trading are covered in this algo trading course. EPAT equips you with the required skill sets to build a promising career in algorithmic trading. Be sure to check it out.</em></p><hr><h3 id="references"><strong>References</strong></h3><ol><li>Koenker, R., &amp; Bassett, G. (1978). Regression quantiles. <em>Econometrica, 46</em>(1), 33–50. <a href="https://doi.org/10.2307/1913643">https://doi.org/10.2307/1913643</a></li><li>Lim, D., Park, B., Nott, D., Wang, X., &amp; Choi, T. (2020). Sparse signal shrinkage and outlier detection in high-dimensional quantile regression with variational Bayes. <em>Statistica Sinica, 13</em>(2), 1. <a href="https://archive.intlpress.com/site/pub/files/_fulltext/journals/sii/2020/0013/0002/SII-2020-0013-0002-a008.pdf">https://archive.intlpress.com/site/pub/files/_fulltext/journals/sii/2020/0013/0002/SII-2020-0013-0002-a008.pdf</a></li><li>Breiman, L. (2001). Random forests. <em>Machine Learning, 45</em>(1), 5–32. <a href="https://link.springer.com/article/10.1023/A:1010933404324">https://link.springer.com/article/10.1023/A:1010933404324</a></li><li>Muthukrishnan, R., &amp; Jamila, S. M. (2020). Predictive modeling using support vector regression. <em>International Journal of Scientific &amp; Technology Research, 9</em>(2), 4863–4875. Retrieved from <a href="https://www.ijstr.org/final-print/feb2020/Predictive-Modeling-Using-Support-Vector-Regression.pdf">https://www.ijstr.org/final-print/feb2020/Predictive-Modeling-Using-Support-Vector-Regression.pdf</a></li></ol><hr><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments, is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Beyond the Straight Line: Advanced Linear Regression Models for Financial Data]]></title><description><![CDATA[Master advanced linear regression models in finance: Polynomial, Ridge, Lasso, Elastic Net, LARS. Tackle multicollinearity, feature selection challenges for robust financial modeling. Learn key techniques now!]]></description><link>https://blog.quantinsti.com/advanced-regression-models-finance/</link><guid isPermaLink="false">680770e6fc68ac288210fa99</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Vivek Krishnamoorthy]]></dc:creator><pubDate>Thu, 01 May 2025 11:19:00 GMT</pubDate><content:encoded><![CDATA[<p><strong>By</strong>: <a href="https://in.linkedin.com/in/vivekkrishnamoorthy">Vivek Krishnamoorthy</a>, <a href="https://www.linkedin.com/in/aacashi-n-9a4533223/">Aacashi Nawyndder</a> and <a href="https://www.linkedin.com/in/udisha-alok">Udisha Alok</a></p><p>Ever feel like financial markets are just unpredictable noise? What if you could find hidden patterns? That's where a cool tool called <strong>regression</strong> comes in! Think of it like a detective for data, helping us spot relationships between different things.</p><p>The simplest starting point is <strong>linear regression</strong> – basically, drawing the best straight line through data points to see how things connect. (We assume you've got a handle on the basics, maybe from our intro blog linked in the prerequisites!).</p><p>But what happens when a straight line isn't enough, or the data gets messy? In <strong>Part 1</strong> of this two-part series, we'll upgrade your toolkit! We're moving beyond simple straight lines to tackle common headaches in financial modeling. We'll explore how to:</p><ol><li>Model <strong>non-linear trends</strong> using <strong>Polynomial Regression</strong>.</li><li>Deal with <strong>correlated predictors</strong> (multicollinearity) using <strong>Ridge Regression</strong>.</li><li>Automatically <strong>select the most important features</strong> from a noisy dataset using <strong>Lasso Regression</strong>.</li><li>Get the <strong>best of both worlds</strong> with <strong>Elastic Net Regression</strong>.</li><li>Efficiently find <strong>key predictors</strong> in high-dimensional data with <strong>Least Angle Regression (LARS)</strong>.</li></ol><p>Get ready to add some serious power and finesse to your linear modeling skills!</p><hr><h2 id="prerequisites"><strong>Prerequisites</strong></h2><p>Hey there! Before diving in, getting familiar with a few key concepts is a good ideawe dive in, it’s a good idea to get familiar with a few key concepts. You can still follow along without them, but having these basics down will make everything click much easier. Here’s what you should check out:</p><p><strong>1. Statistics and Probability</strong><br> Know the basics—mean, variance, correlation, probability distributions. New to this? <a href="https://blog.quantinsti.com/probability-trading/"><em>Probability Trading</em></a> is a solid starting point.</p><p><strong>2. Linear Algebra Basics</strong><br> Matrices and vectors come in handy, especially for advanced stuff like Principal Component Regression.</p><p><strong>3. Regression Fundamentals</strong><br> Understand how linear regression works and the assumptions behind it. <em><a href="https://blog.quantinsti.com/linear-regression/">Linear Regression in Finance</a></em> breaks it down nicely.</p><p><strong>4. Financial Market Knowledge</strong><br> Brush up on terms like stock returns, volatility, and market sentiment. <a href="https://www.quantinsti.com/epat/statistics-financial-markets"><em>Statistics for Financial Markets</em></a> is a great refresher.</p><p>Once you've got these covered, you're ready to explore how regression can unlock insights in the world of finance. Let’s jump in!</p><hr><h2 id="acknowledgements"><strong>Acknowledgements</strong></h2><p>This blog post draws heavily from the information and insights presented in the following texts:</p><ol><li>Gujarati, D. N. (2011). <em>Econometrics by example</em>. Basingstoke, UK: Palgrave Macmillan.</li><li>Fabozzi, F. J., Focardi, S. M., Rachev, S. T., &amp; Arshanapalli, B. G. (2014). <em>The basics of financial econometrics: Tools, concepts, and asset management applications</em>. Hoboken, NJ: Wiley.</li><li>Diebold, F. X. (2019). <em>Econometric data science: A predictive modeling approach</em>. University of Pennsylvania. Retrieved from <a href="http://www.ssc.upenn.edu/~fdiebold/Textbooks.html">http://www.ssc.upenn.edu/~fdiebold/Textbooks.html</a></li><li>James, G., Witten, D., Hastie, T., &amp; Tibshirani, R. (2013). <em>An introduction to statistical learning: With applications in R</em>. New York, NY: Springer.</li></ol><hr><p>Table of contents:</p><ul><li><a href="#what-exactly-is-regression-analysis">What Exactly is Regression Analysis?</a></li><li><a href="#so-why-do-we-call-these-linear-models">So, Why Do We Call These 'Linear' Models?</a></li><li><a href="#building-the-basics">Building the Basics</a></li><li><a href="#advanced-models">Advanced Models</a></li></ul><hr><h2 id="what-exactly-is-regression-analysis"><strong>What Exactly </strong><em><strong>is</strong></em><strong> Regression Analysis?</strong></h2><p>At its core, regression analysis models the relationship between a dependent variable (the outcome we want to predict) and one or more independent variables (predictors).</p><p>Think of it as figuring out the connection between different things – for instance, how does a company's revenue (the outcome) relate to how much they spend on advertising (the predictor)? Understanding these links helps you make educated guesses about future outcomes based on what you know. <br><br>When that relationship looks like a straight line on a graph, we call it linear regression—nice and simple, isn't it?</p><p>Before we dive deeper, let's quickly recap what linear regression is.</p><hr><h2 id="so-why-do-we-call-these-linear-models"><strong>So, Why Do We Call These 'Linear' Models?</strong></h2><p>Great question! You might look at something like Polynomial Regression, which models curves, and think, 'Wait, that doesn't look like a straight line!' And you'd be right, visually.</p><p>But here's the key: in the world of regression, when we say 'linear,' we're actually talking about the <em>coefficients</em> – those 'beta' values (β) we estimate. A model is considered linear if the equation used to predict the outcome is a simple sum (or linear combination) of these coefficients multiplied by their respective predictor terms. Even if we transform a predictor (like squaring it for a polynomial term), the <em>way the coefficient affects the outcome</em> is still direct and additive.</p><p>All the models in this post—polynomial, Ridge, Lasso, Elastic Net, and LARS—follow this rule even though they tackle complex data challenges far beyond a simple straight line.</p><hr><h2 id="building-the-basics"><strong>Building the Basics</strong></h2><h3 id="from-simple-to-multiple-regression"><strong>From Simple to  Multiple Regression</strong></h3><p>In our previous blogs, we’ve discussed linear regression, <a href="https://blog.quantinsti.com/linear-regression/">its use in finance</a>, <a href="https://blog.quantinsti.com/linear-regression-market-data-python-r/">its application to financial data,</a> and its <a href="https://blog.quantinsti.com/linear-regression-assumptions-limitations/">assumptions and limitations</a>. So, we'll do a quick recap here before moving on to the new material. Feel free to skip this part if you're already comfortable with it.</p><h4 id="simple-linear-regression"><strong>Simple linear regression</strong></h4><p>Simple linear regression studies the relationship between two continuous variables- an independent variable and a dependent variable.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Simple-linear-regression.png" class="kg-image" alt="Simple linear regression"></figure><p><a href="https://upload.wikimedia.org/wikipedia/commons/b/be/Normdist_regression.png">Source</a></p><p>The equation for this looks like:</p><!--kg-card-begin: html--><p>
  $$ y_i = \beta_0 + \beta_1 X_i + \epsilon_i \qquad \text{-(1)} $$
</p>

<p><strong>Where:</strong></p>
<ul>
  <li><span>\(\beta_0\)</span> is the intercept</li>
  <li><span>\(\beta_1\)</span> is the slope</li>
  <li><span>\(\epsilon_i\)</span> is the error term</li>
</ul>
<!--kg-card-end: html--><p>In this equation, ‘y’ is the dependent variable, and ‘x’ is the independent variable. <br>The error term captures all the other factors that influence the dependent variable other than the independent variable.</p><h4 id="multiple-linear-regression"><strong>Multiple linear regression</strong></h4><p>Now, what happens when <em>more</em> than one independent variable influences a dependent variable?  That's where multiple linear regression comes in. </p><p>Here's the equation with three independent variables:</p><!--kg-card-begin: html--><p>
  $$ y_i = \beta_0 + \beta_1 X_{i1} + \beta_2 X_{i2} + \beta_3 X_{i3} + \epsilon_i \qquad \text{-(2)} $$
</p>

<p><strong>Where:</strong></p>
<ul>
  <li><span>\(\beta_0, \beta_1, \beta_2, \beta_3\)</span> are the model parameters</li>
  <li><span>\(\epsilon_i\)</span> is the error term</li>
</ul>
<!--kg-card-end: html--><p>This extension allows modeling more complex relationships in finance, such as predicting stock returns based on economic indicators. You can read more about them <a href="https://blog.quantinsti.com/linear-regression/">here</a>.</p><hr><h2 id="advanced-models"><strong>Advanced Models</strong></h2><h3 id="polynomial-regression-modeling-non-linear-trends-in-financial-markets"><strong>Polynomial Regression: Modeling Non-Linear Trends in Financial Markets</strong></h3><p>Linear regression works well to model linear relationships between the dependent and independent variables. But what if the relationship is non-linear? </p><p>In such cases, we can add polynomial terms to the linear regression equation to get a better fit for the data. This is called polynomial regression. </p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Simple-and-polynomial.png" class="kg-image" alt="Simple and polynomial"></figure><p>So, polynomial regression uses a polynomial equation to model the relationship between the independent and dependent variables.</p><p>The equation for a kth order polynomial goes like:</p><!--kg-card-begin: html--><p>
  $$ y_i = \beta_0 + \beta_1 X_{i} + \beta_2 X_{i2} + \beta_3 X_{i3} + \beta_4 X_{i4} + \ldots + \beta_k X_{ik} + \epsilon_i \qquad \ $$
</p>
<!--kg-card-end: html--><p>Choosing the right polynomial order is super important, as a higher-degree polynomial could overfit the data. So we try to keep the order of the polynomial model as low as possible. </p><p>There are two types of estimation approaches to choosing the order of the model:</p><ul><li><strong>Forward selection procedure:</strong><br> This method starts simple, building a model by adding terms one by one in increasing order of the polynomial.<br>Stopping condition: The process stops when adding a higher-order term doesn't significantly improve the model's fit, as determined by a t-test of the iteration term.<br></li><li><strong>Backward elimination procedure:</strong><br>This method starts with the highest order polynomial and simplifies it by removing terms one by one.<br>Stopping condition: The process stops when removing a term significantly worsens the model's fit, as determined by a t-test.</li></ul><p><strong>Tip</strong>: The first- and second-order polynomial regression models are the most commonly used. Polynomial regression is better for a large number of observations, but it's equally important to note that it is sensitive to the presence of outliers.</p><p>The polynomial regression model can be used to predict non-linear patterns like what we find in stock prices. Do you want a stock trading implementation of the model? No problem, my friend! You can read all about it <a href="https://blog.quantinsti.com/polynomial-regression-adding-non-linearity-to-a-linear-model/">here</a>.</p><h3 id="ridge-regression-explained-when-more-predictors-can-be-a-good-thing"><strong>Ridge Regression Explained: When More Predictors Can Be a Good Thing</strong></h3><p>Remember how we talked about <strong>linear regression,</strong> assuming <a href="https://blog.quantinsti.com/linear-regression-assumptions-limitations/#:~:text=).-,No%20Multicollinearity,-Another%20assumption%20is">no multicollinearity</a> in the data? In real life though, many factors can move together. When multicollinearity exists, it can cause wild swings in the coefficients of your regression model, making it unstable and hard to trust. </p><p>Ridge regression is your friend here!<br>It helps reduce the <strong>standard error and prevent overfitting,</strong> stabilizing the model by adding a small "penalty" based on the size of the coefficients <strong>(Kumar, 2019)</strong>.</p><p>This penalty (called<strong> L2 regularization</strong>) discourages the coefficients from becoming too large, effectively "shrinking" them towards zero. Think of it like gently nudging down the influence of each predictor, especially the correlated ones, so the model doesn't overreact to small changes in the data.<br>Optimal penalty strength (lambda, λ) selection is important and often involves methods like cross-validation.</p><p><em>Caution:</em>  While the <a href="https://blog.quantinsti.com/linear-regression-assumptions-limitations/#:~:text=Ordinary%20Least%20Squares%20(OLS)">OLS</a> estimator is scale-invariant, the ridge regression is not. So, you need to <a href="https://www.statlect.com/fundamentals-of-statistics/ridge-regression">scale</a> the variables before applying ridge regression.</p><p>Ridge regression decreases the model complexity but doesn’t reduce the number of variables (as it can shrink the coefficients close to zero but doesn’t make them exactly zero).<br>So, it <em>cannot</em> be used for feature selection.</p><p>Let’s see an intuitive example for better understanding:</p><p>Imagine you're trying to build a model to predict the daily returns of a stock. You decide to use a whole bunch of technical indicators as your predictors – things like different moving averages, RSI, MACD, Bollinger Bands, and many more. The problem is that many of these indicators are often correlated with each other (e.g., different moving averages tend to move together).</p><p>If you used standard linear regression, these correlations could lead to unstable and unreliable coefficient estimates. But thankfully, you recall reading that QuantInsti blog on Ridge Regression – what a relief! It uses every indicator but dials back their individual influence (coefficients) towards zero. This prevents the correlations from causing wild results, leading to a more stable model that considers everything fairly.</p><p>Ridge Regression is used in various fields, one such example being <strong>credit scoring</strong>. Here, you could have many financial indicators (like income, debt levels, and credit history) that are often correlated. Ridge Regression ensures that all these relevant factors contribute to predicting credit risk without the model becoming overly sensitive to minor fluctuations in any single indicator, thus improving the reliability of the credit score.<br>Getting excited about what this model can do? We are too! That's precisely why we've prepared <a href="https://blog.quantinsti.com/linear-regression-models-scikit-learn/">this</a> blog post for you.</p><p><strong>Lasso regression: Feature Selection in Regression</strong></p><p>Now, what happens if you have <em>tons</em> of potential predictors, and you suspect many aren't actually very useful? Lasso (<strong>Least Absolute Shrinkage and Selection Operato</strong>r) regression can help. Like Ridge, it adds a penalty to prevent overfitting, but it uses a different type (called <strong>L1 regularization</strong>) based on the <em>absolute value</em> of the coefficients. (While Ridge Regression uses the square of the coefficients.)</p><p>This seemingly small difference in the penalty term has a significant impact. As the Lasso algorithm tries to minimize the overall cost (including this L1 penalty), it has a tendency to <strong>shrink the coefficients of less important predictors all the way to absolute zero.</strong></p><p>So, it <em>can</em> be used for feature selection, effectively identifying and removing irrelevant variables from the model.</p><p><em>Note</em>: Feature selection in Lasso regression is data-dependent (<strong>Fonti, 2017)</strong>.</p><p>Below is a really useful example of how Lasso regression shines!</p><p>Imagine you're trying to predict how a stock will perform each week. You've got tons of potential clues – interest rates, inflation, unemployment, how confident consumers are, oil and gold prices, you name it. The thing is, you probably only need to pay close attention to a few of these.</p><p>Because many indicators move together, standard linear regression struggles, potentially giving unreliable results. That's where Lasso regression steps in as a smart way to cut through the noise. While it considers all the indicators you feed it, its unique L1 penalty automatically shrinks the coefficients (influence) of less useful ones all the way to zero, essentially dropping them from the model. This leaves you with a simpler model showing just the key factors influencing the stock's performance, instead of an overwhelming list.</p><p>This kind of smart feature selection makes Lasso really handy in finance, especially for things like predicting stock prices. It can automatically pick out the most influential economic indicators from a whole bunch of possibilities. This helps build simpler, easier-to-understand models that focus on what really moves the market.</p><p>Want to dive deeper? Check out this <a href="https://ieeexplore.ieee.org/document/9417935">paper</a> on using Lasso for stock market analysis.</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><strong>Feature</strong></p>
</td>
<td>
<p><strong>Ridge Regression</strong></p>
</td>
<td>
<p><strong>Lasso Regression</strong></p>
</td>
</tr>
<tr>
<td>
<p><strong>Regularization Type</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">L2 (sum of squared coefficients)</span></p>
</td>
<td>
<p><span style="font-weight: 400;">L1 (sum of absolute coefficients)</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>Effect on Coefficients</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">Shrinks but retains all predictors</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Shrinks some coefficients to zero (feature selection)</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>Multicollinearity Handling</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">Shrinks correlated coefficients to similar values</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Keeps one correlated variable, others shrink to zero</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>Feature Selection?</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">❌ No</span></p>
</td>
<td>
<p><span style="font-weight: 400;">✅ Yes</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>Best Use Case</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">When all predictors are important</span></p>
</td>
<td>
<p><span style="font-weight: 400;">When many predictors are irrelevant</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>Works Well When</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">Large number of significant predictor variables</span></p>
</td>
<td>
<p><span style="font-weight: 400;">High-dimensional data with only a few key predictors</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>Overfitting Control</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">Reduces overfitting by shrinking coefficients</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Reduces overfitting by both shrinking and selecting variables</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>When to Choose?</strong></p>
</td>
<td>
<p><span style="font-weight: 400;">Preferable when multicollinearity exists and all predictors have some influence</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Best for simplifying models by selecting the most relevant predictors</span></p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><h3 id="elastic-net-regression-combining-feature-selection-and-regularization"><strong>Elastic net regression: Combining Feature Selection and Regularization </strong><br></h3><p>So, we've learned about Ridge and Lasso regression. Ridge is great at shrinking coefficients and handling situations with correlated predictors, but it doesn't zero out coefficients entirely (keeping all features) while Lasso is excellent for feature selection, but may struggle a bit when predictors are highly correlated (sometimes just picking one from a group somewhat randomly).</p><p>What if you want the best of both? Well, that's where <strong>Elastic Net regression</strong> comes in – an innovative hybrid, combining both Ridge and Lasso Regression.</p><p>Instead of choosing one or the other, it uses <em>both</em> the L1 penalty (from Lasso) and the L2 penalty (from Ridge) together in its calculations.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/Rdige-Lasso-Elastic.png" class="kg-image" alt="Elastic Net regression"></figure><p><a href="https://keremkargin.medium.com/elasticnet-regression-fundamentals-and-modeling-in-python-8668f3c2e39e">Source</a></p><p><strong>How does it work?</strong></p><p>Elastic Net adds a penalty term to the standard linear regression cost function that <em>mixes</em> the Ridge and Lasso penalties. You can even control the "mix" – deciding how much emphasis to put on the Ridge part versus the Lasso part. This allows it to:</p><ol><li>Perform feature selection like Lasso regression.</li><li>Provide regularization to prevent overfitting.</li><li>Handle Correlated Predictors: Like Ridge, it can deal well with groups of predictors that are related to each other. If there's a group of useful, correlated predictors, Elastic Net tends to keep or discard them together, which is often more stable and interpretable than Lasso's tendency to pick just one.</li></ol><p>You can read <a href="https://blog.quantinsti.com/linear-regression-models-scikit-learn/">this blog</a> to learn more about ridge, lasso and elastic net regressions, along with their implementation in Python.</p><p>Here's an example to make it clearer:</p><p>Let's go back to predicting next month's stock return using many data points (past performance, market trends, economic rates, competitor prices, etc.). Some predictors might be useless noise, and others might be related (like different interest rates or competitor stocks). Elastic Net can simplify the model by zeroing out unhelpful predictors (feature selection) <em>and</em> handle the groups of related predictors (like interest rates) together, leading to a robust forecast.</p><h3 id="least-angle-regression-an-efficient-path-to-feature-selection"><strong>Least angle regression: An Efficient Path to Feature Selection</strong></h3><p>Now, imagine you're trying to build a linear regression model, but you have a <em>lot</em> of potential predictor variables – maybe even more variables than data points! </p><p>This is a common issue in fields like genetics or finance. How do you efficiently figure out which variables are most important?</p><p><strong>Least Angle Regression (</strong><a href="https://hastie.su.domains/Papers/LARS/LeastAngle_2002.pdf"><strong>LARS</strong></a><strong>)</strong> offers an interesting and often computationally efficient way to do this. Think of it as a smart, automated process for adding predictors to your model one by one, or sometimes in small groups. It's a bit like <a href="https://www.statisticshowto.com/forward-selection/">forward stepwise regression</a>, but with a unique twist.</p><p><strong>How does LARS work?</strong></p><p>LARS builds the model piece by piece focusing on the correlation between the predictors and the part of the dependent variable (the outcome) that the model hasn't explained yet (the "residual"). Here’s the gist of the process:</p><ol><li><strong>Start Simple:</strong> Begin with all predictor coefficients set to zero. The initial "residual" is just the response variable itself.</li><li><strong>Find the Best Friend:</strong> Identify the predictor variable with the highest correlation with the current residual.</li><li><strong>Give it Influence:</strong> Start increasing the importance (coefficient) of this "best friend" predictor. As its importance grows, the model starts explaining things, and the leftover "residual" shrinks. Keep doing this <em>just until</em> another predictor perfectly matches the first one in how strongly it's linked to the current residual.</li><li><strong>The "Least Angle" Move:</strong> Now you have two predictors tied for being most correlated with the residual. LARS cleverly increases the importance of <em>both</em> these predictors together. It moves in a specific direction (called the "least angle" or "equiangular" direction) such that both predictors <em>maintain</em> their equal correlation with the shrinking residual.</li></ol><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/04/LARS-representation.png" class="kg-image" alt="Geometric representation of LARS"></figure><p>Geometric representation of LARS: <a href="https://www.researchgate.net/figure/LARS-algorithm-evolution-for-m-3-covariates_fig1_251670715">Source</a></p><ol><li><strong>Keep Going:</strong> Continue this process. As you go, a third (or fourth, etc.) predictor might eventually catch up and tie the others in its connection to the residual. When that happens, it joins the "active set" and LARS adjusts its direction again to keep all three (or more) active predictors equally correlated with the residual.</li><li><strong>Full Path:</strong> This continues until all predictors you're interested in are included in the model.</li></ol><p><strong>LARS and Lasso:</strong></p><p>Interestingly, LARS is closely related to Lasso regression. A slightly modified version of the LARS algorithm is actually a very efficient way to compute the <em>entire sequence</em> of solutions for Lasso regression across all possible penalty strengths (lambda values). So, while LARS is its own algorithm, it provides insight into how variables enter a model and gives us a powerful tool for exploring Lasso solutions.</p><p><strong>But, why use LARS?</strong></p><ul><li>It's particularly efficient when you have high-dimensional data (many, many features).</li><li>It provides a clear path showing the order in which variables enter the model and how their coefficients evolve.</li></ul><p><em><strong>Caution:</strong></em> Like other forward selection methods, LARS can be sensitive to noise.</p><p><strong>Use case: LARS can be used to identify Key Factors Driving Hedge Fund Returns:</strong></p><p>Imagine you're analyzing a hedge fund's performance. You suspect that various market factors drive its returns, but there are dozens, maybe hundreds, you could consider: exposure to small-cap stocks, value stocks, momentum stocks, different industry sectors, currency fluctuations, etc. You have way more potential factors (predictors) than monthly return data points.</p><p>Running standard regression is difficult here. LARS handles this "too many factors" scenario effectively.</p><p>Its real advantage here is showing you the <em>order</em> in which different market factors become essential for explaining the fund's returns, and exactly how their <em>influence</em> builds up.</p><p>This gives you a clear view of the primary drivers behind the fund's performance. And helps build a simplified model highlighting the <em>key</em> systematic drivers of the fund's performance, navigating the complexity of numerous potential factors efficiently.</p><hr><h2 id="summary"><strong>Summary</strong></h2><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><strong>Regression Model</strong></p>
</td>
<td>
<p><strong>One-Line Summary</strong></p>
</td>
<td>
<p><strong>One-Line Use Case</strong></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Simple Linear Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Models the linear relationship between two variables.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Understanding how a company's revenue relates to its advertising spending.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Multiple Linear Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Models the linear relationship between one dependent variable and multiple independent variables.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting stock returns based on several economic indicators.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Polynomial Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Models non-linear relationships by adding polynomial terms to a linear equation.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting non-linear patterns in stock prices.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Ridge Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Reduces multicollinearity and overfitting by shrinking the magnitude of regression coefficients.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting stock returns with many correlated technical indicators.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Lasso Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Performs feature selection by shrinking some coefficients to exactly zero.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Identifying which economic factors most significantly drive stock returns.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Elastic Net Regression</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Combines Ridge and Lasso to balance feature selection and multicollinearity reduction.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Predicting stock returns using a large number of potentially correlated financial data points.</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Least Angle Regression (LARS)</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Efficiently selects important predictors in high-dimensional data.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Identifying key factors driving hedge fund returns from a large number of potential market influences.</span></p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><hr><h2 id="conclusion"><strong>Conclusion</strong></h2><p>Phew! We've journeyed far beyond basic straight lines!</p><p>You've now seen how <strong>Polynomial Regression</strong> can capture market curves, how <strong>Ridge Regression</strong> stabilizes models when predictors move together, and how <strong>Lasso, Elastic Net, and LARS</strong> act like smart filters, helping you select the most crucial factors driving financial outcomes.</p><p>These techniques are essential for building more robust and reliable models from potentially complex and high-dimensional financial data.</p><p>But the world of regression doesn't stop here! We've focused on refining and extending <em>linear-based</em> approaches.</p><p>What happens when the problem itself is different? What if you want to predict a "yes/no" outcome, focus on predicting extreme risks rather than just the average, or model incredibly complex, non-linear patterns?</p><p>That's precisely what we'll tackle in <strong><a href="https://blog.quantinsti.com/types-regression-finance/">Part 2</a></strong>! Join us next time as we explore a different side of regression, diving into techniques like Logistic Regression, Quantile Regression, Decision Trees, Random Forests, and Support Vector Regression. Get ready to expand your predictive modeling horizons even further!</p><p>Getting good at this stuff really comes down to rolling up your sleeves and practicing! Try playing around with these models using Python or R and some real financial data – you'll find plenty of tutorials and projects out there to get you started.</p><p>For a complete, holistic view of regression and its power in trading, you might want to check out <a href="https://quantra.quantinsti.com/course/trading-with-machine-learning-regression">this</a> Quantra course.</p><p>And if you're thinking about getting serious with algorithmic trading, checking out something like <strong>QuantInsti’s </strong><a href="https://www.quantinsti.com/epat"><strong>EPAT</strong></a><strong> program</strong> could be a great next step to really boost your skills for a career in the field.</p><p>Understanding regression analysis is a <strong>must-have skill</strong> for anyone aiming to succeed in financial modeling or trading strategy development.</p><p>So, keep practicing—and soon you'll be making smart, data-driven decisions like a pro!</p><p><em>With the right training and guidance from industry experts, it can be possible for you to learn it as well as Statistics &amp; Econometrics, Financial Computing &amp; Technology, and Algorithmic &amp; Quantitative Trading. These and various aspects of Algorithmic trading are covered in this algo trading course. EPAT equips you with the required skill sets to build a promising career in algorithmic trading. Be sure to check it out.</em></p><hr><h2 id="references"><strong>References</strong></h2><ol><li>Fonti, V. (2017). Feature selection using LASSO. <em>Research Paper in Business Analytics</em>. Retrieved from <a href="https://vu-business-analytics.github.io/internship-office/papers/paper-fonti.pdf">https://vu-business-analytics.github.io/internship-office/papers/paper-fonti.pdf</a></li><li>Kumar, D. (2019). Ridge regression and Lasso estimators for data analysis. <em>Missouri State University Theses</em>, 8–10. Retrieved from <a href="https://bearworks.missouristate.edu/cgi/viewcontent.cgi?article=4406&amp;context=theses">https://bearworks.missouristate.edu/cgi/viewcontent.cgi?article=4406&amp;context=theses</a></li><li>Efron, B., Hastie, T., Johnstone, I., &amp; Tibshirani, R. (2003, January 9). <em>Least Angle Regression</em>. Statistics Department, Stanford University.<br><a href="https://hastie.su.domains/Papers/LARS/LeastAngle_2002.pdf">https://hastie.su.domains/Papers/LARS/LeastAngle_2002.pdf</a></li><li>Taboga, Marco (2021). "Ridge regression", Lectures on probability theory and mathematical statistics. Kindle Direct Publishing. Online appendix. <a href="https://www.statlect.com/fundamentals-of-statistics/ridge-regression">https://www.statlect.com/fundamentals-of-statistics/ridge-regression</a></li></ol><hr><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments, is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Exploring the Chain Rule with Step-by-Step Examples]]></title><description><![CDATA[In this blog on “Understanding the chain rule,” we will learn the math behind the application of chain rule with the help of an example.]]></description><link>https://blog.quantinsti.com/understanding-chain-rule/</link><guid isPermaLink="false">5cde9970bef68076bdae35ad</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[QuantInsti]]></dc:creator><pubDate>Fri, 11 Apr 2025 12:39:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: html--><p>By <a data-cke-saved-href="https://www.linkedin.com/in/varun-divakar-b862a667/" href="https://www.linkedin.com/in/varun-divakar-b862a667/" target="_blank" rel="noopener">Varun Divakar</a></p><p>In this blog on “Understanding the chain rule,” we will learn the math behind the application of chain rule with the help of an example.</p><h4><strong>Table of Contents</strong></h4><ul><li><a data-cke-saved-href="#derivative" href="#derivative">What is a derivative?</a></li><li><a data-cke-saved-href="#chainrule" href="#chainrule">What is the Chain Rule?</a></li><li><a data-cke-saved-href="#understand" href="#understand">Understanding the Chain Rule</a></li><li><a data-cke-saved-href="#example" href="#example">Example of Chain Rule</a></li></ul><p>For those of you who are interested in <a data-cke-saved-href="https://blog.quantinsti.com/introduction-deep-learning-neural-network" href="https://blog.quantinsti.com/introduction-deep-learning-neural-network" target="_blank" rel="noopener">Neural Networks and Deep Learning</a>, the process of <a data-cke-saved-href="https://blog.quantinsti.com/backpropagation" href="https://blog.quantinsti.com/backpropagation" target="_blank" rel="noopener">backpropagation</a> is a very important concept which is extensively used while creating these advanced models. While performing backpropagation, we use the concept of chain rule to backpropagate the error values in prediction to adjust the weights.</p><p>To be able to understand this unit, you should know what a derivative is.</p><h2><strong><img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22derivative%22%20name%3D%22derivative%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">What is a derivative?</strong></h2><p>Don’t sweat it, in case you don’t know or don’t remember the same, you can learn about it on the <a data-cke-saved-href="https://quantra.quantinsti.com/glossary" href="https://quantra.quantinsti.com/glossary" target="_blank" rel="noopener">glossary section of Quantra website</a>.</p><h2><strong><img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22chainrule%22%20name%3D%22chainrule%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">What is the Chain Rule?</strong></h2><p>The chain rule is basically a formula for computing the derivative of a composition of two or more functions.</p><h2><strong><img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22understand%22%20name%3D%22understand%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">Understanding the Chain Rule</strong></h2><p>Let us say that f and g are functions, then the chain rule expresses the derivative of their composition as<em> f ∘ g</em> (the function which maps <em>x</em> to <em>f(g(x))</em> ). The derivative of this composition is calculated as mentioned below.</p><p><img class="aligncenter wp-image-15790 size-full" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i1.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i1.png" alt="derivative" width="171" height="24"></p><p>Here <em>f</em> is the function of <em>g</em> and <em>g</em> is a function of variable <em>x</em>.</p><p>Another way of writing the above rule:</p><p><img class="aligncenter wp-image-15791 size-full" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i2.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i2.png" alt="derivative" width="179" height="24"></p><p>Where the function <em>F</em> represents the composite function <em>f(g(x))</em></p><p>Let us say that we have three variables <em>x, y</em> and <em>z</em> such that, the variable <em>z</em> depends on the variable <em>y</em>, which in turn depends on the variable <em>x</em>. So <em>y</em> and <em>z</em> are dependent variables, and <em>z</em>, via the intermediate variable of <em>y</em>, depends on <em>x</em>. Then the chain rule for differentiating the variable <em>z</em> may be written in the following manner.</p><p><img class="aligncenter wp-image-15792 size-full" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i3.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i3.png" alt="differentiate" width="123" height="47"></p><p>This is the final formula that we use in backpropagation.</p><p>Here <em>z</em> is the function of <em>y</em>,</p><p style="text-align: center;"><em><strong>z = f(y)</strong></em></p><p>and <em>y</em> is a function of <em>x</em>,</p><p style="text-align: center;"><em><strong>y= g(x)</strong></em></p><p>Using the previous formula, we can rewrite the differential equation as follows:</p><p><img class="size-full wp-image-15793 aligncenter" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i4.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i4.png" alt="differential equation" width="356" height="47"></p><p>Let us understand this better with the help of an example.</p><h2><strong><img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22example%22%20name%3D%22example%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">Example of Chain Rule</strong></h2><p>Let us understand the chain rule with the help of a well-known example from Wikipedia. Assume that you are falling from the sky, the atmospheric pressure keeps changing during the fall. Check out the graph below to understand this change.</p><p><img class="aligncenter wp-image-15789" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/bl.jpg" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/bl.jpg" alt="chain rule example" width="645" height="427"></p><p>At the time of your fall, 4000 meters above sea level, the initial velocity was zero, and the gravity is 9.8 meters per second squared. Now compare this situation to the previous chain rule equation. Let us say that the variable <em>x</em> in the equation is variable <em>t</em>, or time.</p><p>Then the variable <em>y</em> or <em>g(t)</em>, which is the distance travelled by you since the beginning of the fall is given by</p><p style="text-align: center;"><em><strong>g(t) = 0.5*9.8t<sup>2</sup></strong></em></p><p>So, the height from the mean sea level can be given by the variable <em>h</em>, which is</p><p style="text-align: center;"><em><strong>h = 4000 - g(t)</strong></em></p><p>Let us say that we also know, based on a model, the atmospheric pressure at a height <em>h</em> as:</p><p style="text-align: center;"><em><strong>f(h) = 101325 e<sup>−0.0001h</sup></strong></em></p><p>These two equations can be differentiated by their respective variable to get the following information:</p><p style="text-align: center;"><em><strong>g′(t) = −9.8t</strong></em>,</p><p>where,&nbsp;<em><strong>g′(t)&nbsp;</strong></em>is the velocity of you at time <em>t</em></p><p style="text-align: center;"><em><strong>f′(h) = −10.1325<sup>e−0.0001h</sup></strong></em></p><p>where,&nbsp;<em><strong>f′(h)</strong></em>&nbsp;is the rate of change in atmospheric pressure with respect to height <em>h</em></p><p>Now let us understand how we can combine these two equations to derive the</p><p>the rate of change in the atmospheric pressure with respect to time at <em>t</em> seconds after the skydiver's jump, using the chain rule:</p><p><img class="size-full wp-image-15794 aligncenter" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i5.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i5.png" alt="chain rule" width="218" height="24"></p><p><img class="size-full wp-image-15795 aligncenter" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i6.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i6.png" alt="chain rule calculation" width="408" height="29"></p><p>This equation gives us the rate of change of atmospheric pressure with respect to time since fall. In neural networks, we will need to calculate the change in weights at each neuron with respect to the errors in prediction. As you might have imagined by now, the chain rule helps adjusts these weights accordingly.</p><h2><strong>Conclusion</strong></h2><p>If we want to apply the chain rule to backpropagate the error in neural networks, then we will be using an equation such as this.</p><p><img class="size-full wp-image-15796 aligncenter" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i7.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2019/02/i7.png" alt="chain rule to backpropagate" width="455" height="70"></p><p><span style="font-weight: 400;">In the Quantra’s course on </span><a data-cke-saved-href="https://quantra.quantinsti.com/course/neural-networks-deep-learning-trading-ernest-chan" href="https://quantra.quantinsti.com/course/neural-networks-deep-learning-trading-ernest-chan" target="_blank" rel="noopener"><span style="font-weight: 400;">Deep Learning in Trading with Dr. E. P. Chan</span></a><span style="font-weight: 400;">, we will help you not only understand advanced concepts such as deep learning, but also apply them in the context of trading. </span></p><p style="text-align: center;"><br></p><p><em>Disclaimer:&nbsp;<span style="font-weight: 400;">All investments and trading in the stock market involve risk. Any decisions to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</span></em></p><p><strong>Suggested Reads:</strong></p><ul><li><a data-cke-saved-href="https://blog.quantinsti.com/forward-propagation-neural-networks" href="https://blog.quantinsti.com/forward-propagation-neural-networks" target="_blank" rel="noopener">Forward Propagation In Neural Networks</a></li><li><a data-cke-saved-href="https://blog.quantinsti.com/backpropagation" href="https://blog.quantinsti.com/backpropagation" target="_blank" rel="noopener">Understanding Backpropagation</a></li></ul><pre><code>    
</code></pre><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Bayesian Inference Methods and Formula Explained]]></title><description><![CDATA[To help develop a deeper understanding of statistical analysis by focusing on the methodologies adopted by frequentist statistics and Bayesian statistics.]]></description><link>https://blog.quantinsti.com/bayesian-inference/</link><guid isPermaLink="false">5cde9970bef68076bdae3597</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Vivek Krishnamoorthy]]></dc:creator><pubDate>Thu, 10 Apr 2025 12:52:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: html--><p>By&nbsp;<a data-cke-saved-href="https://www.linkedin.com/in/vivekkrishnamoorthy/" href="https://www.linkedin.com/in/vivekkrishnamoorthy/" target="_blank" rel="noopener">Vivek Krishnamoorthy</a></p><p>This post on Bayesian inference is the second of a multi-part series on Bayesian statistics and methods used in quantitative finance.</p><p>In my previous <a data-cke-saved-href="/introduction-to-bayesian-statistics-in-finance" href="https://blog.quantinsti.com/introduction-to-bayesian-statistics-in-finance" target="_blank" rel="noopener">post</a>, I gave a leisurely introduction to Bayesian statistics and while doing so distinguished between the frequentist and the Bayesian outlook of the world. I dwelt on how each of their underlying philosophies influenced their analysis of various probabilistic phenomena. I then discussed the Bayes' Theorem along with some illustrations to help lay the building blocks of Bayesian statistics.</p><h2><strong>Intent of this Post</strong></h2><p>My objective here is to help develop a deeper understanding of statistical analysis by focusing on the methodologies adopted by frequentist statistics and Bayesian statistics. I consciously choose to tackle the programming and simulation aspects using Python in my next post.</p><p>I now instantiate the previously discussed ideas with a simple coin-tossing example adapted from "Introduction to Bayesian Econometrics (2nd Edition)".</p><h3>Example: A Repeated Coin-Tossing Experiment</h3><p>Suppose we are interested in estimating the bias of a coin whose fairness is unknown. <strong>We define θ (the Greek letter 'theta') as the probability of getting a head after a coin is tossed.</strong> θ is the unknown parameter we want to estimate. We intend to do so by inspecting the results of tossing the coin multiple times. Let us denote y as a realization of the random variable Y (representing the outcome of a coin toss). Let <strong>Y=1</strong> if a coin toss results in heads and <strong>Y=0</strong> if a coin toss results in tails. Essentially, we are assigning 1 to heads and 0 to tails.</p><p>∴ <strong>P(Y=1|θ)=θ ; P(Y=0|θ)=1−θ</strong></p><p>Based on our above setup, Y can be modelled as a <a data-cke-saved-href="https://en.wikipedia.org/wiki/Bernoulli_distribution" href="https://en.wikipedia.org/wiki/Bernoulli_distribution" target="_blank" rel="noopener">Bernoulli distribution</a> which we denote as</p><p><strong>Y ∼ Bernoulli (θ)</strong></p><p>I now briefly view our experimental setup through the lens of the frequentist and the Bayesian before proceeding with our estimation of the unknown parameter <strong>θ</strong>.</p><h2><strong>Two Perspectives on the Experiment Setup</strong></h2><p>In classical statistics (i.e. the frequentist approach), our parameter <strong>θ</strong> is a fixed but unknown value lying between <strong>0</strong> and <strong>1</strong>. The data we collect is one realization of a recurrent (i.e. repeating this <strong>n</strong>-toss experiment say <strong>N</strong> times) experiment. Classical estimation techniques like the method of maximum likelihood are used to arrive at θ̄̂ (called 'theta hat'), an estimate for the unknown parameter <strong>θ</strong>. In statistics, we usually express an estimate by putting a hat over the name of the parameter. I dilate this idea in the next section. To restate what has been said previously, we observe that in the frequentist universe, the parameter is fixed but the data is varying.</p><p>Bayesian statistics is fundamentally different. Here, the parameter θ is treated as a random variable since there is uncertainty about its value. It, therefore, makes sense for us to regard our parameter as a random variable which will have an associated <a data-cke-saved-href="/statistics-probability-distribution/" target="_blank" href="https://blog.quantinsti.com/statistics-probability-distribution/">probability distribution</a>. In order to apply Bayesian inference, we turn our attention to one of the fundamental laws of probability theory, <a data-cke-saved-href="https://en.wikipedia.org/wiki/Bayes%27_theorem" href="https://en.wikipedia.org/wiki/Bayes%27_theorem" target="_blank" rel="noopener">Bayes' Theorem</a> that we had seen previously.</p><p>I use the mathematical form of Bayes' Theorem as a way to establish a connection with Bayesian inference.</p><p><img class="size-full wp-image-15010 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture1-3.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture1-3.png" alt="Formula for Bayes' Theorem" width="235" height="69">…….. <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22one%22%20name%3D%22one%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(1)</p><p>To repeat what I said in my previous post, what makes this theorem so handy is it allows us to <strong>invert a conditional probability</strong>. So if we observe a phenomenon and collect data or evidence about it, the theorem helps us analytically define the <em>conditional probability of different possible causes given the evidence.</em></p><p>Let's now apply this to our example by using the notations we had defined earlier. I label <strong>A = θ</strong> and <strong>B = y</strong>. In the field of Bayesian statistics, there are special names used for each of these terms which I spell out below and use subsequently. <a data-cke-saved-href="#one" href="#one">(1)</a> can be rewritten as:</p><p><img class="size-full wp-image-15016 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture2-4.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture2-4.png" alt="Bayes' Theorem revisited" width="241" height="67">…….. <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22two%22%20name%3D%22two%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(2)</p><p>where:</p><p><strong>P(θ)</strong> is the <strong>prior probability</strong>. We express our belief about the cause <strong>θ</strong> BEFORE observing the evidence <strong>Y</strong>. In our example, the prior would be quantifying our a priori belief on the fairness of the coin (here we can start with the assumption that it is an unbiased coin, so θ = 1/2). <strong>P(Y|θ)</strong> is the <strong>likelihood</strong>. Here is where the real action happens. This is the probability of the observed sample or evidence given the hypothesized cause. Let us, without loss of generality, assume that we obtain 5 heads in 8 coin tosses. Presuming the coin to be unbiased as specified above, the likelihood would be the probability of observing 5 heads in 8 tosses given that θ = 1/2. <strong>P(θ|Y)</strong> is the <strong>posterior probability</strong>. This is the probability of the underlying cause θ AFTER observing the evidence y. Here, we compute our updated or a posteriori belief on the bias of the coin after observing 5 heads in 8 coin tosses using Bayes' theorem. <strong>P(Y)</strong> is the <strong>probability of the data or evidence</strong>. We sometimes also call this the marginal likelihood. This is obtained by taking the weighted sum (or integral) of the likelihood function of the evidence across all possible values of θ. In our example, we would compute the probability of 5 heads in 8 coin tosses for all possible beliefs about θ. This term is used to normalize the posterior probability. Since it is independent of the parameter to be estimated θ, it is mathematically more tractable to express the posterior probability as:</p><p><strong>P(θ|Y) ∝ P(Y|θ) × P(θ) </strong>…….<img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22three%22%20name%3D%22three%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(3)</p><p><br></p><p><a data-cke-saved-href="#three" href="#three">(3)</a> <strong>is the most important expression in Bayesian statistics</strong> and bears repeating. For clarity, I paraphrase what I said earlier. Bayesian inference allows us to turnaround conditional probabilities i.e. use the prior probabilities and the likelihood functions to provide a connecting link to the posterior probabilities i.e. <strong>P(θ|Y)</strong> granted that we only know <strong>P(Y|θ)</strong> and the prior, <strong>P(θ</strong>). I find it helpful to view <a data-cke-saved-href="#three" href="#three">(3)</a> as:</p><p><strong>Posterior Probability ∝ Likelihood × Prior Probability</strong> ………. <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22four%22%20name%3D%22four%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(4)</p><p>The experimental objective is to get an estimate of the unknown parameter <strong>θ</strong> based on the outcome of <strong>n</strong> independent coin tosses. The coin tosses generate the sample or data y = (y1, y2, …,&nbsp;yn), where yi is 1 or 0 based on the result of the <strong>ith</strong> coin toss.</p><p>I now show the frequentist and Bayesian approaches to fulfilling this objective. Feel free to cursorily skim through the derivations I touch upon here if you are not interested in the mathematics behind it. You can still develop sufficient intuitions and learn to use Bayesian techniques in practice.</p><h2><strong>Estimating </strong>θ:<strong> The Frequentist Approach</strong></h2><p>We compute the joint probability function using the maximum likelihood estimation (MLE) approach. The probability of the outcome for a single coin toss can be elegantly expressed as:</p><p><img class="size-full wp-image-15018 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture3-4.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture3-4.png" alt="The Frequentist approach equation" width="230" height="43"></p><p>For a given value of <em>θ</em>, the joint probability of the outcome for n independent coin tosses is the product of the probability of each individual outcome:</p><p><img class="wp-image-15019 size-full alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture4-3.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture4-3.png" alt="modification of frequentist approach question" width="481" height="161">……. <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22five%22%20name%3D%22five%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(5)</p><p>As we can see in <a data-cke-saved-href="#four" href="#four">(4)</a>, the expression worked out is a function of the unknown parameter θ given the observations from our experiment. This function of θ is called the likelihood function and is usually referred to in the literature as:</p><p><img class="size-full wp-image-15020 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture5-2.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture5-2.png" alt="Frequentist approach 1" width="372" height="40">……….. <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22six%22%20name%3D%22six%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(6)</p><p>OR</p><p><img class="size-full wp-image-15022 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture6-3.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture6-3.png" alt="Frequentist approach 2" width="157" height="39">…………… <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22seven%22%20name%3D%22seven%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(7)</p><p>We would like to compute the value of <em>θ</em> which is most likely to have yielded the observed set of outcomes. This is called the <em>maximum likelihood estimate</em>, θ̄̂ ('theta hat'). For analytically computing it, we trivially take the first order derivative of <a data-cke-saved-href="#six" href="#six">(6)</a> with respect to the parameter and set it equal to zero. It is prudent to also take the second derivative and check the sign of its value at θ = θ̄̂&nbsp; to ensure that the estimate is indeed the maxima. We often customarily take the log of the likelihood function since it greatly simplifies the determination of the maximum likelihood estimator θ̄̂ . It should therefore not surprise you that the literature is replete with log likelihood functions and their solutions.</p><h2><strong>Estimating θ: The Bayesian Approach</strong></h2><p>I now change the notations we have used so far to make them a little more precise mathematically. I will use these notations throughout this series now. The reason for this alteration is so that we can suitably ascribe each term with symbols that remind us of their random nature. There is uncertainty over the values of θ, Y, etc., we, therefore, regard them as random variables and assign them corresponding probability distributions which I do below.</p><h2><strong>Notations for the Density and Distribution Functions</strong></h2><ul><li><strong>π(⋅)</strong> (the Greek letter 'pi') to denote the probability distribution function of the <strong>prior</strong> (this is pertaining to θ) and <strong>π(⋅|y)</strong> to denote the posterior density function of the parameter we attempt to estimate.</li><li><strong>f(⋅)</strong> to denote the probability density function (pdf) for continuous random variables and p(.) which is the probability mass function (pmf) of discrete random variables. However, for simplicity, I use <strong>f(⋅)</strong> irrespective of whether the random variable <strong>Y</strong> is continuous or discrete.</li><li>The joint density function will continue to be denoted as <strong>L(θ|⋅)</strong>. to denote the likelihood function which is the joint density of the sample values and is usually the product of the pdf's/pmf's of the sample values from our data.</li></ul><p>Remember that <strong><em>θ</em></strong> is the parameter we are trying to estimate.</p><p><a data-cke-saved-href="#two" href="#two">(2)</a> and <a data-cke-saved-href="#three" href="#three">(3)</a> can be rewritten as</p><p><strong>π(θ|y) = [f(y|θ)⋅π(θ)] / f(y)&nbsp; &nbsp;</strong>……<img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22eight%22%20name%3D%22eight%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(8)</p><p><strong>π(θ|y)∝f(y|θ)×π(θ)</strong>&nbsp; &nbsp; …………….<img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22nine%22%20name%3D%22nine%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(9)</p><p>Stated in words, <strong>the posterior distribution function is proportional to the likelihood function times the prior distribution function</strong>. I redraw your attention to <a data-cke-saved-href="#four" href="#four">(4)</a> and present it in congruence with our new notations.</p><p><strong>Posterior PDF ∝ Likelihood × Prior PDF</strong>&nbsp; ……….<img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22ten%22%20name%3D%22ten%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(10)</p><p>I now rewrite <a data-cke-saved-href="#eight" href="#eight">(8)</a> and <a data-cke-saved-href="#nine" href="#nine">(9)</a> using the likelihood function L(θ|Y) defined earlier in <a data-cke-saved-href="#seven" href="#seven">(7)</a>.</p><p><img class="size-full wp-image-15043 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture11-1.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture11-1.png" alt="modification of bayesian theorem" width="236" height="60">……… <img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22eleven%22%20name%3D%22eleven%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(11)</p><p><img class="size-full wp-image-15044 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture12-1.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture12-1.png" alt="modification of bayes theorem" width="223" height="48">………..<img class="cke_anchor" data-cke-realelement="%3Ca%20data-cke-saved-name%3D%22twelve%22%20name%3D%22twelve%22%3E%3C%2Fa%3E" data-cke-real-node-type="1" alt="Anchor" title="Anchor" align data-cke-saved-src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" data-cke-real-element-type="anchor">(12)</p><p>The denominator of <a data-cke-saved-href="#eleven" href="#eleven">(11)</a> is the probability distribution of the evidence or data. I reiterate what I have previously mentioned while inspecting <a data-cke-saved-href="#three" href="#three">(3)</a>: A useful way of considering the posterior density is using the proportionality approach as seen in <a data-cke-saved-href="#twelve" href="#twelve">(12)</a>. That way, we don't need to worry about the f(y) term on the RHS of <a data-cke-saved-href="#eleven" href="#eleven">(11)</a>.</p><p>For the mathematically curious among you, I now take you briefly down a needless rabbit hole to explain it incompletely. Perhaps, later in our journey, I may write a separate post brooding on these minutiae.</p><p>In <a data-cke-saved-href="#eleven" href="#eleven">(11)</a>, <strong>f(y)</strong> is the proportionality constant that makes the posterior distribution a proper density function integrating to 1. When we examine it more closely, we see that is, in fact, the unconditional (marginal) distribution of the random variable <strong>Y</strong>. We can determine it analytically by integrating over all possible values of the parameter <strong>θ</strong>. Since we are integrating out <strong>θ</strong>, we find that <strong>f(y)</strong> does not depend on <strong>θ</strong>.</p><p><img class="size-full wp-image-15024 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture9-1.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture9-1.png" alt="Integral for estimating theta" width="252" height="72"></p><p>OR</p><p><img class="size-full wp-image-15025 alignnone" data-cke-saved-src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture10-1.png" src="https://d1rwhvwstyk9gu.cloudfront.net/2018/11/Capture10-1.png" alt="Second equation for bayesian inference" width="209" height="63"></p><p><a data-cke-saved-href="#eleven" href="#eleven">(11)</a> and <a data-cke-saved-href="#twelve" href="#twelve">(12)</a> represent the <strong>continuous versions of the Bayes' Theorem</strong>.</p><p><em>The posterior distribution is central to Bayesian statistics and inference because it blends all the updated information about the parameter <strong>θ</strong> in a single expression. This includes information about <strong>θ</strong> before the observations were inspected and this is captured through the prior distribution. The information contained in the observations is captured through the likelihood function.</em></p><p>We can regard <a data-cke-saved-href="#eleven" href="#eleven">(11)</a> as a method of updating information and this idea is further exemplified by the prior-posterior nomenclature.</p><ul><li>The prior distribution of <strong>θ</strong>, <strong>π(θ)</strong> represents the information available about its possible values before recording the observations <strong>y</strong>.</li><li>The likelihood function <strong>L(θ|y)</strong> of <strong>θ</strong> is then determined based on the observations <strong>y</strong>.</li><li>The posterior distribution of <strong>θ</strong>, <strong>π(θ|y)</strong> summarizes all the available information about the unknown parameter θ after recording and incorporating the observations <strong>y</strong>.</li></ul><p><strong>The Bayesian estimate of θ would be the weighted average of the prior estimate and the maximum likelihood estimate, θ̄̂ </strong>&nbsp;. As the number of observations <strong>n</strong> increases and approached infinity, the weight on the prior estimate approaches zero and the weight on the MLE approaches one. This implies that the Bayesian and frequentist estimates would converge as our sample size gets larger.</p><p>To clarify, in a classical or frequentist setting, the usual estimator of the parameter, <strong>θ</strong> is the ML estimator, θ̄̂ &nbsp;. Here, the prior is implicitly treated as a constant.</p><h2><strong>Summary</strong></h2><p>I have devoted this post to deriving the fundamental result of Bayesian statistics, viz. <a data-cke-saved-href="#ten" href="#ten">(10)</a> . The essence of this expression is to represent uncertainty by combining the knowledge obtained from two sources - observations and prior beliefs. In doing so, I introduced the concepts of prior distributions, likelihood functions and posterior distributions as well as the comparison of the frequentist and Bayesian methodologies. In my next post, I intend to make good my promise of illustrating the above example with simulations in Python.</p><p>Bayesian statistics is an important part of <a href="https://quantra.quantinsti.com/course/quantitative-trading-strategies-models" target="_blank" rel="noopener">quantitative strategies</a> which are part of an algorithmic trader’s handbook.&nbsp;The&nbsp;<a data-cke-saved-href="https://www.quantinsti.com/epat/" href="https://www.quantinsti.com/epat/" target="_blank" rel="noopener">Executive Programme in Algorithmic Trading (EPAT™)</a>&nbsp;course by&nbsp;<a data-cke-saved-href="https://www.quantinsti.com/" href="https://www.quantinsti.com/" target="_blank" rel="noopener">QuantInsti®</a>&nbsp;covers training modules like Statistics &amp; Econometrics, Financial Computing &amp; Technology, and Algorithmic &amp; Quantitative Trading that equip you with the required skill sets for&nbsp;applying various trading instruments and platforms to be a successful trader.</p><p style="text-align: center;"><br></p><p><em>Disclaimer: All investments and trading in the stock market involve risk. Any decisions to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</em></p><p><br></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Introduction to Statistical Thinking for Smarter Choices and Analysis]]></title><description><![CDATA[Statistical thinking, a beginner's guide! Making decisions with limited information is a part of life. Get introduced to the way of making decisions using a structured approach through statistics.]]></description><link>https://blog.quantinsti.com/statistical-thinking/</link><guid isPermaLink="false">6215e82511773065706fabc8</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Ansh Tayal]]></dc:creator><pubDate>Thu, 10 Apr 2025 06:30:00 GMT</pubDate><content:encoded><![CDATA[<p>Statistical thinking is an approach to process information through the lens of probability and statistics so as to make informed decisions.</p><p>This series of blogs takes you through a journey where we begin with introducing statistical thinking, make a brief stopover to understand Bayesian statistics and then dwell on its applications in financial markets using Python.</p><p><em>“Statistical thinking will one day be as necessary for efficient citizenship as the ability to read and write!”</em><br>H.G. Wells (1866-1946), the father of science fiction</p><p>Making choices is a part of our daily lives, be it personal or professional. If you apply statistical thinking wherever possible, you can make better choices.</p><p>In this article, we’ll go step by step in deconstructing the decision-making process under limited information. We’ll look at some examples, the jargon and the importance of statistics in the process.</p><!--kg-card-begin: html--><pr>
   <ul>
<li style="font-weight: 400;" aria-level="1"><a href="#what-is-statistics"><span style="font-weight: 400;">What is statistics?</span></a></li>
<li style="font-weight: 400;" aria-level="1"><a href="#what-is-a-statistical-question"><span style="font-weight: 400;">What is a statistical question?</span></a></li>
<li style="font-weight: 400;" aria-level="1"><a href="#why-do-we-need-statistics"><span style="font-weight: 400;">Why do we need statistics?</span></a></li>
<li style="font-weight: 400;" aria-level="1"><a href="#descriptive-statistics-vs-inferential-statistics"><span style="font-weight: 400;">Descriptive statistics vs Inferential statistics</span></a></li>
<li style="font-weight: 400;" aria-level="1"><a href="#should-we-use-descriptive-or-inferential-statistics"><span style="font-weight: 400;">Should we use descriptive statistics or inferential statistics?</span></a></li>
<li style="font-weight: 400;" aria-level="1"><a href="#jargon-in-statistics"><span style="font-weight: 400;">Jargon in statistics</span></a></li>
<ul>
<li style="font-weight: 400;" aria-level="2"><a href="#population"><span style="font-weight: 400;">Population</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#sample"><span style="font-weight: 400;">Sample</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#observation"><span style="font-weight: 400;">Observation</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#statistic"><span style="font-weight: 400;">Statistic</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#parameter"><span style="font-weight: 400;">Parameter</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#hypothesis"><span style="font-weight: 400;">Hypothesis</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#hypothesis-testing"><span style="font-weight: 400;">Hypothesis testing</span></a></li>
<li style="font-weight: 400;" aria-level="2"><a href="#estimate"><span style="font-weight: 400;">Estimate</span></a></li>
</ul>
<li style="font-weight: 400;" aria-level="1"><a href="#why-should-we-spend-time-on-statistical-inference"><span style="font-weight: 400;">Why should we spend time on statistical inference?</span></a></li>
</ul>
    
</pr><!--kg-card-end: html--><hr><h2 id="what-is-statistics">What is statistics?</h2><p>There are two ways to define statistics. Formally statistics is defined as "<strong>The science of statistics deals with the collection, analysis, interpretation, and presentation of data.</strong>"</p><p>Intuitively, statistics is defined as "<strong>Statistics is the science of making decisions under uncertainty.</strong>"</p><p>That is, statistics is a tool that helps you make decisions when you don’t have complete information.</p><hr><h2 id="what-is-a-statistical-question">What is a statistical question?</h2><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/03/image.png" class="kg-image"><figcaption><a href="https://www.istockphoto.com/photos/four-cats">Source</a></figcaption></figure><p>Looking at the above image, let's address some questions!</p><p>How many cats does the above picture have?<br><em>4, right?</em></p><p>Do we have all the information to answer this question?<br><em>Yes.</em></p><p>Do all healthy cats have four legs?<br><em>Yes.</em></p><p>Do we have all the information to answer this question?<br><em>No. Because this is a picture of only 4 out of all the existing cats in the world!</em></p><p>But can we still answer it with certainty?<br><em>Yes.</em></p><p>So, is it a statistical question?<br><em>No.</em></p><p>Why?<br><em><strong>Because if you have all the information to answer the question or if you can answer this question with certainty, it’s not a statistical question.</strong></em></p><p>For a question to be a statistical question,</p><ul><li>The question has to go beyond the available information, and</li><li>The question shouldn’t be answerable with certainty.</li></ul><p>This concept will be reinforced repeatedly in this article, i.e., statistics is the science of decision making under <strong>uncertainty.</strong></p><hr><h2 id="why-do-we-need-statistics">Why do we need statistics?</h2><p>We now work with a toy example through this post to answer the above question.</p><p>Suppose we decide to design a <a href="https://quantra.quantinsti.com/">Quantra</a> course on Julia programming.</p><ul><li><em><em><em>How do we decide if we should put time and effort into building this course?</em></em></em></li><li><em>What if our designed course fails and doesn’t get many interested users?</em></li></ul><p>These are important business decisions that require substantial resources. Therefore, we decide to survey if such a course would sell.</p><p>Now, that raises the following questions:</p><ul><li>Who would our potential paid users be?</li><li>Who should we approach? Programmers? Data scientists? Researchers? College graduates? Quantitative Analysts?</li><li><em>Ideally, all of them, right?</em></li></ul><p>However,</p><ul><li>Can we get access to all of these people? <em>Unlikely.</em></li><li>So, what should we do?</li><li>Should we drop the idea of designing the new course?</li></ul><p><em>That doesn’t sound right.</em></p><p>If we had access to all the people, the process would have been simple. If the majority say that they would buy such a course, you create it. If not, then drop it.</p><p>However, since we can’t do it, we do the next best thing, i.e. we ask the maximum number of people we can reach out to, and, based on their response, we <strong>estimate</strong> the likelihood of this course being successful.</p><p>To calculate this <strong>estimate, </strong>we need<strong> statistics.</strong></p><p>To generalize this idea, in real-world scenarios, we rarely have complete information related to the decision we want to make, whether for individuals or businesses.</p><p>Hence, we need a tool that can help us decide with limited information. Statistics is one such tool, and making these decisions within a statistical framework is called statistical thinking.</p><p><strong>Statistical thinking</strong> is not just about using formulas to calculate p-values and z-scores; it’s a way to think about the world. Once you internalize this idea, it will change how you see the world. You’ll start thinking in terms of probabilities instead of certainties, which will help you make better decisions in your professional and personal life.</p><hr><h2 id="descriptive-statistics-vs-inferential-statistics">Descriptive statistics vs Inferential statistics</h2><p><a href="https://blog.quantinsti.com/statistics-probability-distribution/">Descriptive statistics</a> is the process of taking the data and describing its features using measures of central tendency (mean, median and mode), measures of dispersion (<a href="https://blog.quantinsti.com/standard-deviation/">standard deviations</a>, interquartile range ), etc.</p><p>However, inferential statistics is about working with the limited data and using it to infer something about a larger question we pose to ourselves a priori. This question cannot be answered with certainty.</p><p>Our article focuses on the latter, i.e. inferential statistics.</p><hr><h2 id="should-we-use-descriptive-or-inferential-statistics">Should we use descriptive or inferential statistics?</h2><p>It depends on the question you’re asking and the available data. A simple question to ask yourself while deciding which one to use is:</p><ul><li>Do we want to describe the existing data? OR</li><li>Do we want to draw inferences from the existing data (sample) to extrapolate about the population?</li></ul><p>We go with descriptive statistics for the former and inferential statistics for the latter.</p><hr><h2 id="jargon-in-statistics">Jargon in statistics</h2><p>Let’s look at some of the key terms used in statistics that will help you in understanding the concepts better.</p><h3 id="population">Population</h3><p>The universe of items we’re interested in. Going back to our Quantra course example, the population would be every person in this world who would be interested in the Julia course.</p><h3 id="sample">Sample</h3><p>It is a subset of the population, i.e. the amount of information we <em>can</em> get. This could be the Quantra or EPAT user base we have. We could frame our question as: <em>How likely are you to buy a course on Julia (on a scale of 1 to 10)?</em></p><h3 id="statistic">Statistic</h3><p>A summary measure of the data available, i.e. from the sample. Here, it could be the average score of say, 7 obtained from Quantra and EPAT users for the above question.</p><h3 id="parameter">Parameter</h3><p>A <a href="https://blog.quantinsti.com/statistics-probability-distribution/">parameter</a> is a summary measure of the population. Here, it could be the average score of say, 6 obtained from the population (as defined above).</p><p>A <strong>statistic</strong> is a summary measure of the existing data (sample), whereas a <strong>parameter</strong> is the same for the population.</p><h3 id="hypothesis">Hypothesis</h3><p>A description of how we think the world works. We hypothesize that EPAT and Quantra users are unlikely to buy a course on Julia (rating of 1). This is the assumption we start with that we call the null hypothesis.</p><h3 id="null-hypothesis">Null Hypothesis</h3><p>It’s crucial to have a null hypothesis before starting with any statistical analysis. And the null hypothesis is mostly status quo. The alternative hypothesis is the theory that you think could be true and are looking for evidence to verify it.</p><p>So to clarify, our null hypothesis \({H_0}\) and alternative hypothesis \({H_1}\) here are \({H_0}\): EPAT and Quantra users are unlikely to buy a course on Julia (Mean rating = 5)</p><p>\({H_1}\): EPAT and Quantra users are likely to buy the course (Mean rating &gt;=5)</p><h3 id="hypothesis-testing">Hypothesis testing</h3><p><a href="https://blog.quantinsti.com/hypothesis-testing-trading-guide/">Hypothesis testing</a> is a method to draw conclusion about the data from the sample i.e. to test whether a hypothesis is correct or not.</p><h3 id="estimate">Estimate</h3><p>And estimate can be defined as a variable that is the best guess of the actual value of the parameter.</p><hr><h2 id="why-should-we-spend-time-on-statistical-inference">Why should we spend time on statistical inference?</h2><p>Let’s consider two scenarios:</p><ul><li><strong>Scenario 1</strong> - We had access to only one user, and she rated 6 for the likelihood of buying the course.</li><li><strong>Scenario 2 </strong>- We had access to 10 users, and they gave an average rating of 8 for buying the course.</li></ul><p>These are our best estimates. However,</p><p><em>Which one is the better estimate?<br></em>The one with 10 users because it has more data.</p><p><em>Is the estimate of scenario 2 good enough to act on?<br>Should we create the course because 10 people have a high likelihood of buying the course?<br></em>Maybe not.</p><p><em>Why?<br></em>Because the response from 10 users is probably not enough, and so could lead to a poorly worked out decision.</p><p>This is where statistical inference comes in.</p><p>As we have mentioned before, If you want the correct answer, you <em>will</em> need <em>all</em> the data. No silver bullet can give you the right answer with limited data. But remember, as we discussed, statistics is the science of making decisions under <strong>uncertainty.</strong></p><p>We’re not interested in knowing the <strong>correct</strong> answer with statistical inference because we can’t!</p><p>Using inferential statistics, the question you want to answer is:</p><p><strong>Is the best guess good enough to change our minds?</strong></p><p>This forms the basis of everything we do in statistical inference. Notice that the question mentions “changing our mind”. This means that we would need to already have something in our minds in the first place, a decision, an opinion.</p><p>We can only change our minds if we have already decided to do something by default. Remember we mentioned the importance of having a null hypothesis?</p><p>The hypothesis could be that people are extremely unlikely to buy the Quantra course on Julia programming, so we will <strong>not create</strong> a new course if the best guess is <strong>not good enough to change our minds</strong>.</p><p>This is where the need to have a predefined hypothesis comes in. This is another fundamental concept in inferential statistics. Suppose we are to make statistical inferences.</p><p>In that case, we <em>need </em>to have a predefined decision or an opinion because, at the cost of being repetitive,  the question we’re asking using statistics is:</p><p><strong>Is the best guess good enough to change our minds?</strong></p><p><strong>The entire exercise of statistical inference makes sense if you have a default action. If you don’t have a default action, just go with your best guess from the sample data.</strong></p><p>Let’s take another example to understand this. Imagine if PepsiCo decides to change the colour of its logo to black or green. The responses of 1 million people are recorded as a sample.</p><p>Now, here’s the summary of which decision we can take based on our default action and data:</p><!--kg-card-begin: html--><pr>
   <table>
<tbody>
<tr>
<td>
<p><strong>Default action</strong></p>
</td>
<td>
<p><strong>Results from data</strong></p>
</td>
<td>
<p><strong>Decision</strong></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Not decided</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Data favours green.</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Go with the best guess. Green.&nbsp;</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Don&rsquo;t change</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Data marginally favours black</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Logo remains unchanged&nbsp;</span></p>
</td>
</tr>
<tr>
<td>
<p><span style="font-weight: 400;">Don&rsquo;t change</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Data overwhelmingly favours green</span></p>
</td>
<td>
<p><span style="font-weight: 400;">Change the logo to green.&nbsp;</span></p>
</td>
</tr>
</tbody>
</table>
</pr><!--kg-card-end: html--><p>The table above consists of 3 scenarios to explain to concepts presented above.</p><ul><li>In the first scenario, there’s no default action and the data supports green. So we go ahead and change the logo to green.</li><li>In the second scenario, the default action is “don’t change the color” and the data supports black but not strongly enough. So the logo color remains unchanged.</li><li>In the third scenario, the default action is “don’t change the color” but the data strongly supports green. So the logo is changed to green.</li></ul><hr><h3 id="resources-for-learning-about-statistical-thinking">Resources for learning about statistical thinking</h3><p>Here are a few resources that you can refer to for a detailed understanding of the topic:</p><ol><li><a href="https://allendowney.github.io/ThinkBayes2/">Think Bayes</a></li><li><a href="https://cpentalk.com/drive/index.php?download=true&amp;p=Statistics+Books%2FBooks%28+CPENTalk.com+%29&amp;dl=The+cartoon+guide+to+statistics+%28+CPENTalk.com+%29.pdf">The Cartoon Guide to Statistics</a></li><li><a href="https://www.amazon.in/Bayesian-Analysis-Python-Introduction-probabilistic-ebook/dp/B07HHBCR9G">Bayesian Analysis with Python</a></li></ol><hr><h3 id="conclusion">Conclusion</h3><p>We hope this write-up has piqued your interest in applying a statistical approach when  confronted with choices. Do share your thoughts and comments about the blog in the below section. Until next time!</p><p>If you're serious about building a data-driven edge in trading, understanding statistics is non-negotiable — and the Module 2: <a href="https://www.quantinsti.com/epat/statistics-financial-markets">Statistics for Financial Markets Course</a> from EPAT delivers exactly that. This module focuses on applying probability, risk metrics, hypothesis testing, and trading strategy development directly to financial markets using real-world tools like Excel.</p><p>To explore the full curriculum and gain skills across machine learning, financial computing, quant trading strategies, and more, check out the complete<a href="https://www.quantinsti.com/epat"> Executive Programme in Algorithmic Trading (EPAT)</a>. Whether you're just starting out or looking to level up, EPAT gives you the structure, depth, and practical expertise to succeed in today’s markets.</p><hr><p><strong>Authors:</strong> <a href="https://www.linkedin.com/in/vivekkrishnamoorthy/">Vivek Krishnamoorthy</a> and <a href="https://www.linkedin.com/in/tayal498">Anshul Tayal</a></p><hr><!--kg-card-begin: html--><p><small><em>Disclaimer: All data and information provided in this article are for informational purposes only. QuantInsti<sup>®</sup> makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information in this article and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis.</em></small></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Autoregression: Time Series, Models, Trading, Python and more]]></title><description><![CDATA[The autoregressive (AR) model is a key tool for time series forecasting in trading. This guide covers its formula, calculation, and step-by-step model building, including a Python implementation.]]></description><link>https://blog.quantinsti.com/autoregression/</link><guid isPermaLink="false">67a1c8929579133d13d2a630</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Jose Carlos Gonzales Tanaka]]></dc:creator><pubDate>Tue, 11 Feb 2025 09:19:07 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/jos%C3%A9-carlos-gonz%C3%A1les-tanaka-60859284/">José Carlos Gonzáles Tanaka</a> and <a href="https://www.linkedin.com/in/chainika-bahl-thakar-b32971155/">Chainika Thakar</a> (Originally written by <a href="https://www.linkedin.com/in/satyapriya-chaudhari-73976b16a/">Satyapriya Chaudhari</a>)</p><p>Autoregression is a powerful tool for anticipating future values in time-based data. This data, known as a time series, consists of observations collected at various timestamps, regularly or irregularly. By leveraging historical trends, patterns, and other hidden influences, autoregression models can forecast the value for the next time step.</p><p>These models (including various options beyond autoregression) predict future outcomes by analyzing and learning from past data. This article delves deeper into one particular type: the autoregression model, often abbreviated as the AR model.</p><h3 id="prerequisite-blogs"><strong>Prerequisite Blogs</strong><br></h3><p>Before delving into the this blog, it’s ideal to follow a structured learning track covering foundational to advanced topics. <br><br>Start with the basics in <a href="https://blog.quantinsti.com/time-series-analysis/">Introduction to Time Series</a> and a comparative deep-learning perspective in the<a href="https://blog.quantinsti.com/time-series-lstm-stock-price-prediction-project-ashish-jain/"> Time Series Vs LSTM Models</a>.</p><p>Next, establish the essentials of<a href="https://blog.quantinsti.com/stationarity/"> Stationarity</a>, the<a href="https://blog.quantinsti.com/hurst-exponent/"> Hurst Exponent</a>, and<a href="https://blog.quantinsti.com/mean-reversion-time-series/"> Mean Reversion</a> to understand how and why time‐series data exhibit long‐term memory.</p><p>Once you’re comfortable with these, progress to advanced or multivariate methods, including<a href="https://blog.quantinsti.com/vector-autoregression/"> Vector Autoregression (VAR)</a>,<a href="https://blog.quantinsti.com/johansen-test-cointegration-building-stationary-portfolio/"> Johansen Cointegration</a>, and<a href="https://blog.quantinsti.com/tvp-var-stochastic-volatility/"> Time-Varying-Parameter VAR</a>.</p><p>This comprehensive roadmap equips you with the necessary background to fully appreciate this Blog.<br><br>You are expected to know how to use these models to forecast time series. You should also have a basic understanding of R or Python for time series analysis.</p><p>This article covers:</p><!--kg-card-begin: html--><ul style="font-size: 20px;">
    <li><a href="#what-is-autoregression">What is Autoregression?</a></li>
    <li><a href="#formula-of-autoregression">Formula of Autoregression</a></li>
    <li><a href="#autoregression-calculation">Autoregression Calculation</a></li>
    <li><a href="#autoregression-model">Autoregression Model</a></li>
    <li><a href="#autoregression-models-of-order-2-and-generalise-to-order-p">Autoregression Models of Order 2 and Generalise to Order p</a></li>
    <li><a href="#autoregression-vs-autocorrelation">Autoregression vs Autocorrelation</a></li>
    <li><a href="#autoregression-vs-linear-regression">Autoregression vs Linear Regression</a></li>
    <li><a href="#autocorrelation-function-and-partial-autocorrelation-function">Autocorrelation Function and Partial Autocorrelation Function</a></li>
    <li><a href="#steps-to-build-an-autoregressive-model">Steps to Build an Autoregressive Model</a></li>
    <li><a href="#example-of-autoregressive-model-in-python-for-trading">Example of Autoregressive Model in Python for Trading</a></li>
    <li><a href="#applications-of-autoregression-model-in-trading">Applications of Autoregression Model in Trading</a></li>
    <li><a href="#common-challenges-of-autoregression-models">Common Challenges of Autoregression Models</a></li>
    <li><a href="#tips-for-optimizing-autoregressive-model-performance-algorithmically">Tips for Optimizing Autoregressive Model Performance Algorithmically</a></li>
    <li><a href="#expanding-on-the-ar-model">Expanding on the AR Model</a></li>
</ul>
<!--kg-card-end: html--><hr><h2 id="what-is-autoregression">What is Autoregression?</h2><p>Autoregression models <a href="https://blog.quantinsti.com/time-series-analysis/">time-series</a> data as a linear function of its past values. It assumes that the value of a variable today is a weighted sum of its previous values.</p><p>For example, analyzing the past month’s AAPL (APPLE) performance can help predict future performance.</p><hr><h2 id="formula-of-autoregression">Formula of Autoregression</h2><p>In simpler terms, first-order autoregression says: "Today's value depends on yesterday's value". We express this relationship mathematically using a formula:</p><!--kg-card-begin: html-->$$y_t = c + \phi_1 y_{t-1} + \epsilon_t$$<!--kg-card-end: html--><!--kg-card-begin: html--><!DOCTYPE html>
<html>
<div class="description">
  Where,
</div>

<div class="item">
  • X<sub>t</sub> is the current value in the time series.
</div>
<div class="item">
  • c is a constant or intercept term.
</div>
<div class="item">
  • &straightphi;<sub>1</sub> is the autoregressive coefficients.
</div>
<div class="item">
  • X<sub>t-1</sub> is the past value of the time series.
</div>
<div class="item">
  • &straightepsilon;<sub>t</sub> is the error term representing the random fluctuations or unobserved factors.
</div>


</html><!--kg-card-end: html--><hr><h2 id="autoregression-calculation">Autoregression Calculation</h2><!--kg-card-begin: html--><!DOCTYPE html>
<html>
<head>
    <p>The autoregressive coefficient, &straightphi;<sub>1</sub>, is estimated using statistical methods like maximum likelihood estimation, Yule-Walker estimation, two-step regression estimation, and conditional least squares.</p>

</head></html><!--kg-card-end: html--><p>In the context of <a href="https://blog.quantinsti.com/autoregressive-moving-average-arma-model/">autoregressive (AR) models</a>, the coefficients represent the weights assigned to the lagged values of the time series to predict the current value. These coefficients capture the relationship between the current observation and its past values.</p><p>The goal is to find the coefficients that best fit the historical data, allowing the model to capture the underlying patterns in the time series accurately. Once the coefficients are determined, they help forecast future values in the time series based on the observed values from previous time points. Hence, the autoregression calculation helps to create an autoregressive model for time series forecasting.</p><p>You can explore the video below to learn more about autoregression.</p><!--kg-card-begin: html--><iframe width="900" height="500" class="lazyload" data-src="https://www.youtube.com/embed/thNGygwnpKk?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html--><hr><h2 id="autoregression-model">Autoregression Model</h2><p>Before delving into autoregression, it's beneficial to revisit the concept of a <a href="https://blog.quantinsti.com/machine-learning-trading-predict-stock-prices-regression/">regression</a> model.</p><p>A regression model is a statistical method to determine the association between a dependent variable (often denoted as y) and an independent variable (typically represented as X). Thus, in regression analysis, the focus is on understanding the relationship between these two variables.</p><p>For instance, consider having the stock prices of Bank of America (ticker: BAC) and J.P. Morgan (ticker: JPM).</p><p>If the objective is to forecast the stock price of JPM based on BAC's stock price, then JPM's stock price would be the dependent variable, y, while BAC's stock price would act as the independent variable, X. Assuming a linear association between X and y, the regression equation would be:</p><!--kg-card-begin: html-->$$y=mX + c$$<!--kg-card-end: html--><p>Here,</p><p>m represents the slope, and c denotes the intercept of the equation.</p><!--kg-card-begin: html--><p>
    However, if you possess only one set of data, such as the stock prices of JPM, 
    and wish to forecast its future values based on its past values, you can employ the autoregression model explained in the previous section.
</p><!--kg-card-end: html--><!--kg-card-begin: html--><p>
    Like linear regression, the autoregressive model presupposes a linear connection between 
    <strong>y<sub>t</sub></strong> and <strong>y<sub>t−1</sub></strong>, termed autocorrelation. 
    A deeper exploration of this concept will follow subsequently.
</p>
<!--kg-card-end: html--><hr><h2 id="autoregression-models-of-order-2-and-generalise-to-order-p">Autoregression Models of Order 2 and Generalise to Order p</h2><p>Let's delve into autoregression models, starting with order 2 and then generalising to order <em>p</em>.</p><h3 id="autoregression-model-of-order-2-ar-2-">Autoregression Model of Order 2 (AR(2))</h3><!--kg-card-begin: html--><p>In an autoregression model of order 2 (AR(2)), the current value <span>y<sub>t</sub></span> is predicted based on its two most recent lagged values, that is, <span>y<sub>t-1</sub></span> and <span>y<sub>t-2</sub></span>.</p>
<!--kg-card-end: html--><!--kg-card-begin: html-->$$y_t = c + \phi_1 y_{t-1} + \phi_2 y_{t-2} + \epsilon_t$$<!--kg-card-end: html--><!--kg-card-begin: html--><!DOCTYPE html>
<html>
  
  <div>Where,</div>

  <div class="item">
    • c is a constant.
  </div>
  <div class="item">
    • &straightphi;<sub>1</sub> and &straightphi;<sub>2</sub> are the autoregressive coefficients for the first and second lags, respectively.
  </div>
  <div class="item">
    • &straightepsilon;<sub>t</sub> represents the error term.
  </div>

</html>
<!--kg-card-end: html--><h3 id="generalising-to-order-p-ar-p-">Generalising to order p (AR(p))</h3><p>For an autoregression model of order <em>p</em> (AR(p)), the current value <em>yt </em> is predicted based on its p most recent lagged values.</p><!--kg-card-begin: html-->$$y_t = c + \phi_1 y_{t-1} + \phi_2 y_{t-2} +...+ \phi_p y_{t-p} + \epsilon_t$$<!--kg-card-end: html--><!--kg-card-begin: html--><!DOCTYPE html>
<html>
  
  <div>Where,</div>

  <div class="item">
    • c is a constant.
  </div>
  <div class="item">
    • &straightphi;<sub>1</sub>, &straightphi;<sub>2</sub>,..., &straightphi;<sub>p</sub> are the autoregressive coefficients for the respective lagged terms y<sub>t-1</sub>,y<sub>t-2</sub>, ..., y<sub>t-p</sub>.
  </div>
  <div class="item">
    • &straightepsilon;<sub>t</sub> represents the error term.
  </div>

</html>
<!--kg-card-end: html--><p>In essence, an AR(p) model considers the influence of the p previous observations on the current value. The choice of p depends on the specific time series data and is often determined using methods like information criteria or examination of autocorrelation and partial autocorrelation plots.</p><p>The higher the order p, the more complex the model becomes, capturing more historical information but also potentially becoming more prone to overfitting. Therefore, it's essential to strike a balance and select an appropriate p based on the data characteristics and model diagnostics.</p><hr><h2 id="autoregression-vs-autocorrelation">Autoregression vs Autocorrelation</h2><p>Before determining the difference between autoregression and autocorrelation, you can find the introduction of autocorrelation in this video below. This video will help you learn about autocorrelation with some interesting examples.</p><!--kg-card-begin: html--><iframe width="900" height="500" class="lazyload" data-src="https://www.youtube.com/embed/oGS7YitoZDA?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html--><p>Now, let us find the difference between autoregression and <a href="https://blog.quantinsti.com/autocorrelation/">autocorrelation</a> in a simplified manner below.</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><strong>Aspect</strong></p>
</td>
<td>
<p><strong>Autoregression</strong></p>
</td>
<td>
<p><strong>Autocorrelation</strong></p>
</td>
</tr>
<tr>
<td>
<p>Modelling</p>
</td>
<td>
<p>Incorporates past observations to predict future values.</p>
</td>
<td>
<p>Describes the linear relationship between a variable and its lags.</p>
</td>
</tr>
<tr>
<td>
<p>Output</p>
</td>
<td>
<p>Model coefficients (lags) and forecasted values.</p>
</td>
<td>
<p>Correlation coefficients at various lags.</p>
</td>
</tr>
<tr>
<td>
<p>Diagnostics</p>
</td>
<td>
<p>ACF and PACF plots to determine model order.</p>
</td>
<td>
<p>ACF plot to visualise autocorrelation at different lags.</p>
</td>
</tr>
<tr>
<td>
<p>Applications</p>
</td>
<td>
<p>Stock price forecasting, weather prediction, etc.</p>
</td>
<td>
<p>Signal processing, econometrics, quality control, etc.</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><hr><h2 id="autoregression-vs-linear-regression">Autoregression vs Linear Regression</h2><p>Now, let us see the difference between autoregression and <a href="https://blog.quantinsti.com/linear-regression-assumptions-limitations/">linear regression</a> below. Linear regression can be learned better and more elaborately with this video below.</p><!--kg-card-begin: html--><iframe width="900" height="415" class="lazyload" data-src="https://www.youtube.com/embed/3fRV8iKlLRU?rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html--><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><strong>Aspect</strong></p>
</td>
<td>
<p><strong>Autoregression</strong></p>
</td>
<td>
<p><strong>Linear Regression</strong></p>
</td>
</tr>
<tr>
<td>
<p>Model Type</p>
</td>
<td>
<p>Specifically for time series data where past values predict the future.</p>
</td>
<td>
<p>Generalised for any data with independent and dependent variables.</p>
</td>
</tr>
<tr>
<td>
<p>Predictors</p>
</td>
<td>
<p>Past values of the same variable (lags).</p>
</td>
<td>
<p>Independent variables can be diverse (not necessarily past values).</p>
</td>
</tr>
<tr>
<td>
<p>Purpose</p>
</td>
<td>
<p>Forecasting future values based on historical data.</p>
</td>
<td>
<p>Predicting an outcome based on one or more input variables.</p>
</td>
</tr>
<tr>
<td>
<p>Assumptions</p>
</td>
<td>
<p>Time series stationarity, no multicollinearity among lags.</p>
</td>
<td>
<p>Linearity, independence, homoscedasticity, no multicollinearity.</p>
</td>
</tr>
<tr>
<td>
<p>Diagnostics</p>
</td>
<td>
<p>ACF and PACF mainly.</p>
</td>
<td>
<p>Residual plots, Quantile-Quantile plots, etc.</p>
</td>
</tr>
<tr>
<td>
<p>Applications</p>
</td>
<td>
<p>Stock price prediction, economic forecasting, etc.</p>
</td>
<td>
<p>Marketing analytics, medical research, machine learning, etc.</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><hr><h2 id="autocorrelation-function-and-partial-autocorrelation-function">Autocorrelation Function and Partial Autocorrelation Function</h2><p>Let's walk through how to create Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) plots using Python's statsmodels library and then interpret them with examples.</p><h3 id="step-1-install-required-libraries">Step 1: Install Required Libraries</h3><p>First, ensure you have the necessary libraries installed:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/976959fb5da9977ac91557c4e32b91dd.js"></script><!--kg-card-end: html--><h3 id="step-2-import-libraries">Step 2: Import Libraries</h3><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/c094d34437df63fae0627e7b9abe7b1e.js"></script><!--kg-card-end: html--><h3 id="step-3-create-sample-time-series-data">Step 3: Create Sample Time Series Data</h3><p>Let's create a simple synthetic time series for demonstration:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/11d32efedf6ddae97ca9f3b777422c2e.js"></script><!--kg-card-end: html--><h3 id="step-4-plot-acf-and-pacf">Step 4: Plot ACF and PACF</h3><p>Now, plot the ACF and PACF plots for the time series:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/8c7f771ad90020b624d5a17c759df8d9.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/02/ACF.png" class="kg-image" alt="Auto Correlation Function and Partial Auto Correlation Function in autoregressive model"></figure><h3 id="interpretation">Interpretation</h3><ul><li>The ACF measures the correlation between a time series and its lagged values. A decreasing ACF value suggests that past values from the time series affect today’s time series.</li><li>The higher the significance of very long lags’ ACF on the time series, the more distant past values greatly impact today’s time series. This is what we found in this plot. The ACF slowly decreases, and even at lag 40, the ACF keeps being high.</li><li>The PACF drops off at lag 1. So, whenever we have a slowly decreasing ACF and a PACF significant only at lag 1, it is a clear sign we have a random-walk process, i.e., the time series is not <a href="https://blog.quantinsti.com/stationarity/">stationary</a>.</li><li>By examining the ACF and PACF plots and their significant lags, you can gain insights into the temporal dependencies within the time series and make informed decisions about model specification in Python.</li><li>The example given is a price series following a random-walk process, i.e., is not stationary. </li></ul><p>Let’s see below how to estimate a stationary AR model.</p><hr><h2 id="steps-to-build-an-autoregressive-model">Steps to Build an Autoregressive Model</h2><p>Building an autoregressive model involves several steps to ensure that the model is appropriately specified, validated, and optimized for forecasting. Here are the steps to build an autoregressive model:</p><h3 id="step-1-data-collection">Step 1: Data Collection</h3><ul><li>Gather historical time series data for the variable of interest.</li><li>Ensure the data covers a sufficiently long period and is consistent in frequency (e.g., daily, monthly).</li></ul><h3 id="step-2-data-exploration-and-visualisation">Step 2: Data Exploration and Visualisation</h3><ul><li>Plot the time series data to visualize trends, seasonality, and other patterns.</li><li>Check for outliers or missing values that may require preprocessing.</li></ul><h3 id="step-3-data-preprocessing">Step 3: Data Preprocessing</h3><ul><li>Handle missing values using appropriate methods such as interpolation or imputation.</li><li>Ensure the data is stationary. Stationarity is important to model autoregressive models. If not, you must difference or de-trend the data.</li></ul><h3 id="step-4-model-specification">Step 4: Model Specification</h3><ul><li>Determine the appropriate lag order (p) based on the autocorrelation function (ACF) and partial autocorrelation function (PACF) plots.</li><li>Decide on including any exogenous variables or external predictors that may improve the model's forecasting ability.</li></ul><h3 id="step-5-model-estimation">Step 5: Model Estimation</h3><ul><li>Described above. However, in this computer age, Almost all statistical packages can estimate an ARMA model.</li></ul><h3 id="step-6-forecasting">Step 6: Forecasting</h3><ul><li>Split the data into training and test sets.</li><li>Fit the model on the training data.</li><li>Perform statistical metrics such as Mean Absolute Error (MAE) and root Mean Square Error (RMSE) to assess the model's predictive accuracy using the test data.</li></ul><h3 id="step-7-model-refinement">Step 7: Model Refinement</h3><ul><li>If the model performance is unsatisfactory for new data streams, consider returning to step 3.</li></ul><h3 id="step-8-documentation-and-communication-">Step 8: Documentation and Communication:</h3><ul><li>Document the model's specifications, assumptions, and validation results.</li><li>Communicate the model's findings, limitations, and implications to stakeholders or end-users.</li></ul><p>By following these steps systematically and iteratively refining the model as needed, you can develop a robust autoregressive model tailored to your time series data's specific characteristics and requirements.</p><hr><h2 id="example-of-autoregressive-model-in-python-for-trading">Example of Autoregressive Model in Python for Trading</h2><p>Below is a step-by-step example demonstrating how to build an autoregressive (AR) model for time series forecasting in trading using Python. We'll use historical stock price data for Bank of America Corp (ticker: BAC) and the statsmodels library to construct the AR model.</p><p>Let us now see the steps in Python below.</p><h3 id="step-1-install-required-packages">Step 1: Install Required Packages</h3><p>If you haven't already, install the necessary Python packages:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/18a728566f1a0de1f0838c46891287a4.js"></script><!--kg-card-end: html--><h3 id="step-2-import-libraries-1">Step 2: Import Libraries</h3><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/bc65bbf5698b2133850ba699eb41a803.js"></script><!--kg-card-end: html--><h3 id="step-3-load-historical-stock-price-data">Step 3: Load Historical Stock Price Data</h3><p>Some things to say:</p><ul><li>Use the Apple stock data from 2000 to January 2025.</li><li>Save the window size to be used as the train span to estimate the AR model as “rolling_window”. </li></ul><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/2f943112e7d1adbda4c288add2b6f8ed.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/02/AAPL-stock-prices.png" class="kg-image" alt="AAPL Stock prices"><figcaption>AAPL Stock prices</figcaption></figure><h3 id="step-4-find-the-order-of-integration-of-the-price-series">Step 4: Find the Order of Integration of the price series</h3><p>You need a stationary time series to estimate an AR model. Due to that, you’ll need to find the <a href="https://blog.quantinsti.com/autoregressive-moving-average-arma-model/">order of integration</a> of the price series, i.e., find the order “d” of integration of the prices, such that, to make it stationary, you’ll need to difference the data “d” times. To find that number “d”, you can apply an Augmented Dickey-Fuller test to the prices series, its first and second differences (the second difference is enough based on stylized facts). See below:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/32b22ebbbc6df2b2bf4a3fc938a80261.js"></script><!--kg-card-end: html--><p>We use the adfuller method provided in the statsmodels library and output its second result, the p-value. Whenever the p-value is less than 5%, it means the time series is stationary.</p><!--kg-card-begin: html--><pre>
Output:
(0.9987469346686696, 1.2195696223837154e-26, 0.0)
 </pre><!--kg-card-end: html--><p>As we can see, the price, its first difference, and the second difference are non-stationary, stationary, and stationary, respectively. This price series needs to be first differenced to make it stationary. This makes us understand that the price has an order of integration 1, i.e., I(1).</p><p>So, to run an AR model, we need to estimate it based on the first difference, which in the ARIMA method of the statsmodels, means d=1. Here we estimate a stationary AR(1), i.e., an ARIMA(1,1,0), as described below.</p><h3 id="step-5-train-the-ar-model-using-arima">Step 5: Train the AR model using ARIMA</h3><p>Let us train the AR(1) model using the ARIMA method from the statsmodels library.</p><p>The ARIMA method can be imported as shown below</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/dff9dc4c17a66cfc66a6492e62967448.js"></script><!--kg-card-end: html--><p>Using the ARIMA method, the autoregressive model can be trained as</p><p>ARIMA(data, (p, d, q))</p><p>where</p><ul><li>p is the AR parameter that needs to be defined.</li><li>d is the difference parameter. This will be zero in case we’re sure the time series is stationary, 1 in case the time series is I(1), 2 in case the time series is I(2), and so on. Since we found that our price series is I(1), we set d as 1.</li><li>q is the MA parameter. This will also be zero in the case of an AR model. You will learn about this later.</li></ul><p>Hence, the autoregressive model can be trained as</p><p>ARIMA(data, (p, 1, 0))</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/f375599702fae8b9a302a1dae213efb6.js"></script><!--kg-card-end: html--><!--kg-card-begin: html--><pre>
Output:
ar.L1     0.01
sigma2    0.05
dtype: float64
 </pre><!--kg-card-end: html--><p>From the output above, you can see that</p><!--kg-card-begin: html--><html>
  <body>
    <ul>
      <li>
        \( \phi_1 = 0.01 \)
      </li>
      <li>
        \( \text{Variance of the residuals} = \sigma^2 = sigma2 = 0.05 \)
      </li>
    </ul>
  </body>
</html><!--kg-card-end: html--><p>Therefore, the model becomes</p><!--kg-card-begin: html-->$$AR(1) = y_t = 0.01*y_{t-1}$$
<!--kg-card-end: html--><p>For the price, the first difference of the data. Remember that the AR model should have a stationary time series as input.</p><p>Let’s estimate an AR model for each day and forecast the next-day price. You can do it quickly using pandas.DataFrame.rolling.apply. Let’s create a function to estimate the model and return a forecast for the next day.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/770c9518e6e6797bcaf50b5edd0fed18.js"></script><!--kg-card-end: html--><p>And let’s run the model for each day using as the train span the rolling_window variable. Thus, the first rolling_window days will be NaN values.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/c5d9a7242d5a5d3453f4be6c800ce7c3.js"></script><!--kg-card-end: html--><p>The forecast of tomorrow will be saved today. Consequently, we shifted the predicted_price.</p><h3 id="step-6-evaluate-model-performance">Step 6: Evaluate model performance</h3><p>We compute, for a specific year, in this function:</p><ul><li>The Mean Absolute Error</li><li>The mean Squared Error</li><li>The Root Mean Squared Error</li><li>The Absolute Percentage Error</li><li>Plo the actual and forecasted prices</li><li>Plot the residuals</li><li>Plot the ACF</li><li>Plot the PACF</li></ul><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/c4509c632c9596518fd96c736d4e1474.js"></script><!--kg-card-end: html--><!--kg-card-begin: html--><pre>
Output:
The Mean Absolute Error is 2.63
The Mean Squared Error is 11.41
The Root Mean Squared Error is 3.38
The Mean Absolute Percentage Error is 1.74
 </pre><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2025/02/Output-for-model-performance.png" class="kg-image" alt="Model performance"><figcaption>Model performance</figcaption></figure><p>The first plot above shows that the predicted values are close to the observed value. However, the forecasted prices don’t exactly follow the actual prices.</p><p>Tip: Whenever you compare actual prices against forecasted prices, do not compare them for a big data span. People usually compare those prices, e.g., from 1990 to 2025. When you see those plots, you’ll tend to think the forecasted prices follow exactly the actual prices’ behavior. But that’s not a good way to go. If you want to compare them well, a zoom-in inspection will be needed, e.g., compare the two prices for a specific month if the data frequency is daily, and so on.</p><p>From the third and fourth plots above, you can see that the model captures almost entirely the price behavior because there are very few significant ACF and PACF across the lags. To formally choose the correct model, you can follow the Box-Jenkins methodology to do it graphically each day, or you can select the best model with an information criteria, as described below, to do it algorithmically.</p><p><strong>**Note: You can log into quantra.quantinsti.com and enroll in the course on  </strong><a href="https://quantra.quantinsti.com/course/financial-time-series-analysis-trading"><strong>Financial Time Series</strong></a><strong> to find out the detailed autoregressive model in Python.**</strong></p><p>Forecasting is a statistical process, so forecasting variance will be higher than zero, i.e., there can be errors in the forecasting prices with respect to actual prices.</p><p>Here are some reasons why your autoregressive model can have poor performance:</p><ul><li><strong>Model Misspecification:</strong> The AR model's assumptions or specifications may not align with the true data-generating process, leading to biased forecasts.</li><li><strong>Lag Selection:</strong> Incorrectly specifying the lag order in the AR model can result in misleading predictions. Including too many or too few lags may distort the model's predictive accuracy.</li><li><strong>Missed Trends or Seasonality: </strong>The AR model may not adequately capture underlying trends, seasonality, or other temporal patterns in the data, leading to inaccurate predictions.</li><li><strong>External Factors: </strong>Unaccounted external variables or events that influence the time series but are not included in the model can lead to discrepancies between predicted and actual prices.</li><li><strong>Data Anomalies: </strong>Outliers, anomalies, or sudden shocks in the data that were not accounted for in the model can distort the predictions, especially if the model is sensitive to extreme values.</li><li><strong>Stationarity Assumption:</strong> If the time series is not stationary, applying an AR model can produce unreliable forecasts. Stationarity is a key assumption for the validity of AR models.</li></ul><hr><h2 id="applications-of-autoregression-model-in-trading">Applications of Autoregression Model in Trading</h2><p>Autoregression (AR) models have been applied in various ways within trading and finance. Here are some applications of autoregression in trading:</p><ul><li><strong>Price prediction</strong>: As previously shown, traders often use autoregressive models to analyze historical price data and identify patterns to forecast prices or price direction. This is the most used case of AR models.</li><li><strong>Risk Management:</strong> Autoregression can model and forecast volatility in financial markets. However, we would need the AR model together with the <a href="https://quantra.quantinsti.com/glossary/GARCH">GARCH</a> model to forecast variance, and with both you can do proper risk management.</li><li><strong>Market Microstructure: </strong>Autoregression can be used to <a href="https://www.sciencedirect.com/science/article/pii/S0031320323008361">model</a> the behavior of market disturbances, such as in high-frequency trading.</li></ul><hr><h2 id="common-challenges-of-autoregression-models">Common Challenges of Autoregression Models</h2><p>The following are common challenges of the autoregression model:</p><ul><li><strong>Overfitting: </strong>Autoregressive models can become too complex and fit the noise in the data rather than the underlying trend or pattern. This can lead to poor out-of-sample performance and unreliable forecasts. That’s why a parsimonious model is the best choice for estimating AR models.</li><li><strong>Stationarity:</strong> Many financial time series exhibit non-stationary behavior, meaning their statistical properties (like mean and variance) change over time. Autoregressive models assume stationarity, so failure to account for non-stationarity can result in inaccurate model estimates.</li><li><strong>Model Specification: </strong>Determining an autoregressive model's appropriate lag order (p) is challenging. Too few lags might miss important information, while too many can introduce unnecessary complexity. A parsimonious model helps with this type of issue.</li><li><strong>Seasonality and Periodicity:</strong> Autoregressive models might not capture seasonal patterns or other periodic effects in the data, leading to biased forecasts. You might need to de-seasonalize the data before you apply the AR model.</li></ul><hr><h2 id="tips-for-optimizing-autoregressive-model-performance-algorithmically">Tips for Optimizing Autoregressive Model Performance Algorithmically</h2><p>Now, let us see some tips for optimizing the autoregressive model’s performance below.</p><ul><li><strong>Data Preprocessing:</strong> Ensure the data is stationary or apply techniques like differencing or de-trending to achieve stationarity before fitting the autoregressive model.</li><li><strong>Model Selection: </strong>Usually, you apply the Box-Jenkins methodology to select the appropriate number of lags of the AR model. This methodology uses a graphical inspection of the ACF and PACF to derive the best model. In algorithmic trading, you can just estimate multiple AR models and select the best using information criteria (e.g., Akaike Information Criteria, AIC; Bayesian Information Criteria, BIC, etc.).</li><li><strong>Include Exogenous Variables:</strong> It’s usually the case the AR models are estimated only with the time series lags. However, you can also incorporate relevant external factors or predictors that might improve the model's forecasting accuracy.</li><li><strong>Continuous Monitoring and Updating:</strong> Financial markets and economic conditions evolve over time, this is called regime changes. Regularly re-evaluate and update the model to incorporate new data and adapt to changing dynamics.</li></ul><p>By addressing these challenges and following the optimization tips, practitioners can develop more robust and reliable autoregressive models for forecasting and decision-making in trading and finance.</p><hr><h2 id="expanding-on-the-ar-model">Expanding on the AR Model</h2><p>We have talked about everything about autoregressive models. However, what about if we also lag the error term, i.e., we can do something like:</p><!--kg-card-begin: html-->$$y_t = c + \phi_1y_{t-1} + \epsilon_t + \theta \epsilon_{t-1} $$<!--kg-card-end: html--><p>This model is the so-called ARMA model; specifically, it’s an ARMA(1,1) model; because we have the first lag of the time series (The AR component) and we also have the first lag of the model error (The MA component).</p><p>In case you want to:</p><ul><li>Understand what ARMA/ARIMA model is thorougly.</li><li>Identify correctly the number of lags using the ACF and PACF graphically.</li><li>Learn how to estimate the ARMA model.</li><li>Learn how to choose the best number of lags for the AR and MA components.</li><li>Create a backtesting code using this model as a strategy.</li><li>Learn how to improve the model’s performance.</li></ul><p>I would suggest reading the following 3 blog articles, where you’ll have everything you need to know about this type of model:</p><ul><li><a href="https://blog.quantinsti.com/autoregressive-moving-average-arma-model/">AutoRegressive Moving Average (ARMA) models: A Comprehensive Guide</a></li><li><a href="https://blog.quantinsti.com/autoregressive-moving-average-arma-model-python/">AutoRegressive Moving Average (ARMA) models: Using Python</a></li><li><a href="https://blog.quantinsti.com/autoregressive-moving-average-arma-model-r/">AutoRegressive Moving Average (ARMA) models: Using R</a></li></ul><hr><h3 id="conclusion">Conclusion</h3><p>Utilizing time series modeling, specifically Autoregression (AR), offers insights into predicting future values based on historical data. We comprehensively covered the AR model, its formula, calculations, and applications in trading. </p><p>By understanding the nuances between autoregression, autocorrelation, and linear regression, traders can make informed decisions, optimize model performance, and navigate challenges in forecasting financial markets. Last but not least, continuous monitoring, model refinement, and incorporating domain knowledge are vital for enhancing predictive accuracy and adapting to dynamic market conditions.</p><p>You can learn more with our course on Financial Time Series Analysis for Trading for learning the <a href="https://quantra.quantinsti.com/course/financial-time-series-analysis-trading">analysis of financial time series</a> in detail.</p><p>With this course, you will learn the concepts of Time Series Analysis and how to implement them in live trading markets. Starting from basic AR and MA models to advanced models like SARIMA, ARCH, and GARCH, this course will help you learn it all. Also, after learning from this course, you can apply time series analysis to data exhibiting characteristics like seasonality and non-constant volatility.</p><p></p><h3 id="continue-learning">Continue Learning</h3><ol><li>Strengthen your grasp by looking into<a href="https://blog.quantinsti.com/autocorrelation-autocovariance/"> Autocorrelation &amp; Autocovariance</a> to see how data points relate over time, then deepen your knowledge with fundamental models such as<a href="https://blog.quantinsti.com/autoregression/"> Autoregression (AR)</a>,<a href="https://blog.quantinsti.com/autoregressive-moving-average-arma-model/"> ARMA</a>, <a href="https://blog.quantinsti.com/forecasting-stock-returns-using-arima-model/">ARIMA</a> and <a href="https://blog.quantinsti.com/arfima-model/">ARFIMA</a></li><li>If your goal is to discover alpha, you may want to experiment with a variety of techniques, such as<a href="https://blog.quantinsti.com/tag/technical-analysis/"> technical analysis, trading risk management, pairs trading basics,</a> and<a href="https://blog.quantinsti.com/market-microstructure/"> Market microstructure</a>. By combining these approaches, you can develop and refine trading strategies that better adapt to market dynamics.</li><li>For a structured approach to algo trading—and to master advanced statistics for quant strategies—consider the <a href="https://www.quantinsti.com/epat">Executive Programme in Algorithmic Trading (EPAT)</a>. This rigorous course covers time series fundamentals (stationarity, ACF, PACF), advanced modelling (ARIMA, ARCH, GARCH), and practical Python‐based strategy building, providing the in‐depth skills needed to excel in today’s financial markets.</li></ol><hr><p><strong>File in the download:</strong></p><ul><li>The Python code snippets for implementing the model are provided, including the installation of libraries, data download, create relevant functions for the model fitting and the forecasting performance.</li></ul><!--kg-card-begin: html--><p style="text-align: center;"><a href="https://blog.quantinsti.com/autoregression" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: html--><hr><!--kg-card-begin: html--><p><em><small>Note: The original post has been revamped on 11<sup>th</sup> Feb 2025 for recentness, and accuracy.</small></em></p><!--kg-card-end: html--><hr><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Ito's Lemma Applied to Stock Trading]]></title><description><![CDATA[Delve deeper into Ito's Lemma for trading with practical examples and use cases. Learn about Ito calculus and its application to stock prices.
]]></description><link>https://blog.quantinsti.com/itos-lemma-applied-stock-trading/</link><guid isPermaLink="false">67407f00da24e139f544d5d2</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Mahavir A. Bhattacharya]]></dc:creator><pubDate>Fri, 06 Dec 2024 11:17:49 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/mahavir-bhattacharya-1303b011b/">Mahavir A. Bhattacharya</a><br><br>This is the second part of the two-part blog where we explore how Ito’s Lemma extends traditional calculus to model the randomness in financial markets. Using real-world examples and Python code, we’ll break down concepts like drift, volatility, and geometric Brownian motion, showing how they help us understand and model financial data, and we’ll also have a sneak peek into how to use the same for trading in the markets.</p><p>In the first part, we saw how classical calculus cannot be used for modeling stock prices, and in this part, we’ll have an intuition of Ito’s lemma and see how it can be used in the financial markets. Here’s the link to part I, in case you haven’t gone through it yet: <a href="https://blog.quantinsti.com/itos-lemma-trading-concepts-guide/">Laying the Groundwork for Ito's Lemma and Financial Stochastic Models</a></p><p>This blog covers:</p><!--kg-card-begin: html--><ul style="font-size: 20px;">
  <li><a href="#pre-requisites">Pre-requisites</a></li>
  <li><a href="#quick-recap">Quick Recap</a></li>
  <li><a href="#ito-calculus">Ito Calculus</a></li>
  <li><a href="#ito-s-lemma-applied-to-stock-prices">Ito's Lemma Applied to Stock Prices</a></li>
  <li><a href="#use-case-i-of-ito-s-lemma">Use Case - I of Ito's Lemma</a></li>
  <li><a href="#important-considerations">Important Considerations</a></li>
  <li><a href="#use-case-ii-of-ito-s-lemma">Use Case - II of Ito's Lemma</a></li>
  <li><a href="#till-next-time">Till Next Time</a></li>
</ul><!--kg-card-end: html--><hr><h3 id="pre-requisites">Pre-requisites</h3><p>You will be able to follow the article smoothly if you have elementary-level proficiency in:</p><ul><li>Calculus</li><li>Python coding</li></ul><hr><h3 id="quick-recap">Quick Recap</h3><p>In part I of this two-blog series, we learned the following topics:</p><ol><li>The chain rule</li><li>Deterministic and stochastic processes</li><li>Drift and volatility components of stock prices</li><li>Weiner processes</li></ol><p>In this part, we shall learn about Ito calculus and how it can be applied to the markets for trading.</p><hr><h3 id="ito-calculus">Ito Calculus</h3><p>Remember  from part I? \( W_t \) is why Ito came up with the calculus he did. In classical calculus, we work with functions. However, in finance, we frequently work with stochastic processes, where \( W_t \) represents stochasticity.</p><p>Rewriting the equations from part I:</p><p>The equation for chain rule:</p><p>$$\frac{dy}{dx} = \frac{dy}{dz} \cdot \frac{dz}{dx}$$ <strong>–-------------- 1</strong></p><p>The equation for geometric Brownian motion (GBM):</p><p>$$dS_t = \mu S_t , dt + \sigma S_t , dW_t$$<strong>--------------- 2</strong></p><p>Equation 2 is a differential equation. The presence of \( W_t \) makes the GBM a stochastic differential equation (SDE).  What’s so special about SDEs?</p><p>Remember the chain rule discussed in part I? That’s only for deterministic variables. For SDEs, our chain rule is Ito’s lemma!</p><p>Let’s get down to business now.</p><hr><h3 id="ito-s-lemma-applied-to-stock-prices">Ito's Lemma Applied to Stock Prices</h3><p>The following equation is an expression of Ito’s lemma:</p><p>$$df(S_t) = f'(S_t) dS_t + \frac{1}{2} f''(S_t) d[S, S]_t$$<strong>--------------- 3</strong></p><p>Here,</p><p>f(x) is a function which can be differentiated twice, and</p><p>S is a continuous process, having bounded variation</p><p>What do we mean by bounded variation?</p><p>It simply means that the difference between St+1 and St, for any value of t, would never exceed a certain value. What this ‘certain value’ is, is not of much significance. What is significant is that the difference between two consecutive values of the process is finite.</p><p>Next question: What’s \( [S, S]_t \)?</p><p>It’s a notation.</p><p>Of what?</p><p>A notation to denote a quadratic variation process.</p><p>What’s that?</p><p>In this blog, we won’t get into the intuition of the quadratic variation. It would suffice to know that the quadratic variation of \( S_t \), i.e., \( [S, S]_t \) is as follows:</p><p>$$ \begin{matrix} \lim_{\Delta t \to 0} &amp; \sum_{0}^{t} \left(S_{t_{i+1}} - S_{t_i}\right)^2 \end{matrix} $$</p><p>If St follows a Brownian motion, the derivative of its quadratic variation is:</p><p>$$d[S, S]_t = \sigma^2 S_t^2 dt$$<strong>--------------- 4</strong></p><p>Substituting equation 4 in equation 3, we get:</p><!--kg-card-begin: html--><p>\[ df(S_t) = f'(S_t) dS_t + \frac{1}{2} f''(S_t) \sigma^2 S_t^2 dt \] </p>
<!--kg-card-end: html--><p><strong>--------------- 5</strong></p><p>How is this derived?</p><p>We can treat equation 5 as a Taylor series expansion till the second order. If you aren’t familiar with it, don’t worry; you can continue reading.</p><p>Still, what’s the intuition? Here, f is a function of the process S, which itself is a function of time t. The change in f depends on:</p><ol><li>The first-order partial derivative of f with respect to S,</li><li>The second-order partial derivative of f with respect to t,</li><li>The square of the volatility σ, and,</li><li>The square of S.</li></ol><p>The last three are multiplied and then added to the first one.</p><p>We saw earlier that stock returns follow a Brownian motion, so stock prices follow a GBM. Hence,  suppose we have a process \( R_t \) , which is equal to log(\( S_t \)).</p><p>If we take \( R_t \) = log(\( S_t \)) in the GBM SDE (equation 2), and if we use the expression for Ito’s lemma (equation 3), we’ll have:</p><p>$$f(S_t) = R_t = \log(S_t)$$<strong>--------------- 6</strong></p><p>and,</p><p>$$dR_t = \frac{dS_t}{S_t} - \frac{d[S_t, S_t]}{2S_t^2}$$<strong>--------------- 7</strong></p><p>Since $$dS_t = \mu S_t , dt + \sigma S_t , dW_t$$ and</p><p>$$d[R, R]_t = \sigma^2 S^2 \, dt$$ (equation 4), </p><p>we can rewrite equation 7 as:</p><p>$$dR_t = \left(\mu - \frac{\sigma^2}{2}\right)dt + \sigma dW_t$$<strong>--------------- 8</strong>   	</p><p>Since the second term on the RHS doesn’t depend on the LHS, we can use direct integration to solve equation 8:</p><p>$$R_t = R_0 + \left(\mu - \frac{\sigma^2}{2}\right)t + \sigma W_t$$<strong>--------------- 9</strong>		   		</p><p>Since </p><!--kg-card-begin: html--><p>\[ R_t = \log(S_t) \quad \text{and} \quad S_t = \exp(R_t), \] </p>
<!--kg-card-end: html--><p>Thus, equation 9 changes to:</p><p>$$S_t = S_0 \cdot e^{\left(\mu - \frac{\sigma^2}{2}\right)t + \sigma W_t}$$<strong>--------------- 10</strong></p><p>Let’s understand what the equation means here. The stock price at time t = 0, when multiplied by this term:</p><p>$$e^{\left(\mu - \frac{\sigma^2}{2}\right)t + \sigma W_t}$$<strong>--------------- 11</strong></p><p>would give the stock price at time t.</p><!--kg-card-begin: html--><p>In equation 2, the drift component had just \( \mu \), but in equation 10, we subtract \( \frac{\sigma^2}{2} \) from \( \mu \). Why so? Remember how we obtain \( \mu \)? By taking the mean of daily log returns, right?</p>
<!--kg-card-end: html--><p>Umm, no! As mentioned in part I, μ is the average percentage drift (or returns), and NOT the logarithmic drift.</p><p>As we saw from the drift component and volatility component graphs, the close price isn’t just the drift component, but also the volatility component added to it. Hence, we need to correct the drift to consider the volatility component as well. It is towards this correction that we subtract \( \frac{\sigma^2}{2} \) from μ. The intuition here is that the arithmetic mean of a set of non-negative real numbers is greater than or equal to the geometric mean of the same set of numbers. The value of μ before the correction is the arithmetic mean, and after the correction, it is close to the geometric mean. When taken on an annual basis, the geometric mean is the CAGR.</p><p>How do we interpret equation 10? The current stock price is simply a function of the past stock price, the corrected drift, and the volatility.</p><p>How do we use this in the markets? Let’s see…</p><hr><h3 id="use-case-i-of-ito-s-lemma">Use Case - I of Ito's Lemma</h3><p><strong>Note:</strong> The codes in this part are continued from part I, and the graphs and values obtained are as of October 18, 2024.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/75ac5565e66274bea9fab9291ebc0370.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>The mean of the daily percent returns = 0.00109
The standard deviation of the daily percent returns = 0.01707
The variance of the daily percent returns = 0.00029</pre><!--kg-card-end: html--><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/d0be2517ff12e6824778308da48f7787.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Daily compounded returns = 0.00094878</pre><!--kg-card-end: html--><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/e6b1f7092a9f1d58a8b19817e7eaf184.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Corrected daily percent returns = 0.000949</pre><!--kg-card-end: html--><p>The arithmetic mean of the returns was initially <strong>0.00109</strong>, and the geometric mean (daily compounded returns) computes to <strong>0.00094878</strong>. After incorporating the drift correction, the arithmetic mean stood at <strong>0.000949</strong>. Quite close to the geometric mean!</p><p>How do we use this for trading?</p><p>Suppose we wanna predict the range within which the price of Microsoft is likely to lie after, say, 42 trading days (2 calendar months) from now.</p><p>Let’s seek refuge in Python again:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/1ee25636dc0af2b2f4569dc14d801b87.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Corrected drift for 42 days = 0.03985788
Variance for 42 days = 0.01223456
Standard deviation for 42 days = 0.11060996</pre><!--kg-card-end: html--><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/b695de34e0eb29c1aa40673a6a91ccab.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Price below which the stock isn't likely to trade with a 95% probability after 42 days = 347.6
Price above which the stock isn't likely to trade with a 95% probability after 42 days = 541.04</pre><!--kg-card-end: html--><p>We know with 95% confidence between which ranges the stock is likely to lie after 42 trading days from now! How do we trade this? Ways are many, but I’ll share one specific method.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/50deeb9e49801b543c42917f82f44a6c.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>
Put with strike 345:

Contract Symbol:   MSFT241220P00345000  
Last Trade Date:   2024-10-17 19:44:37+00:00  
Strike:            345.0  
Last Price:        <b>1.53</b>  
Bid:               0.0  
Ask:               0.0  
Change:            0.0  
Percent Change:    0.0  
Volume:            1.0  
Open Interest:     0  
Implied Volatility: 0.125009  
In The Money:      False  
Contract Size:     REGULAR  
Currency:          USD  
</pre>
<!--kg-card-end: html--><!--kg-card-begin: html--><pre>Call with strike 545:

Contract Symbol:   MSFT241220C00545000  
Last Trade Date:   2024-10-16 13:45:27+00:00  
Strike:            545.0  
Last Price:        <b>0.25</b>  
Bid:               0.0  
Ask:               0.0  
Change:            0.0  
Percent Change:    0.0  
Volume:            169  
Open Interest:     0  
Implied Volatility: 0.125009  
In The Money:      False  
Contract Size:     REGULAR  
Currency:          USD  
</pre><!--kg-card-end: html--><p>We have chosen out-of-the-money strikes near the 95% confidence price range we obtained earlier.</p><p>This way, we can pocket around $1.53 + $0.25 (emboldened in the above output) = $1.78 per pair of stock options sold, if held till expiry. If we sell one lot each of these call and put option contracts, we can pocket $178, since the lot size is 100. And what’s the assurance of us making this profit? 95%, right? Simplistically, yes, but let’s move closer to reality now.</p><hr><h3 id="important-considerations">Important Considerations</h3><p><strong>Assumption of Normality:</strong> We used mean +/- 2 standard deviations and kept talking about 95% confidence. This works in a world where the stock returns are normally distributed. But in the real world, they are not! And more often than not, this deviation from a normal distribution works against us since people react faster to news of impending doom over news of euphoria.</p><p><strong>Transaction Costs:</strong> We didn’t consider the transaction costs, taxes, and implementation shortfalls.</p><p><strong>Backtesting:</strong> We haven’t backtested (and forward tested) whether the prices have historically lied (and would lie in the future) within the predicted price ranges.</p><p><strong>Opportunity Costs:</strong> We also didn’t consider the margin requirements and the opportunity costs, were we to deploy some margin amount in this strategy.</p><p><strong>Volatility:</strong> Finally, we are trading volatility here, not the price. We’ll end up pocketing the whole premium only if both the options expire worthless, i.e., out-of-the-money. But for that to happen, the volatility must be low until the expiry. We must account for the implied volatilities obtained in the previous code output. Oh, and by the way, how is this implied volatility calculated?</p><p>To better understand how volatility affects options pricing, consider exploring our course on <a href="https://quantra.quantinsti.com/course/options-volatility-trading">option volatility</a>, where you'll learn key concepts like implied volatility and its impact on your trades.</p><hr><h3 id="use-case-ii-of-ito-s-lemma">Use Case - II of Ito's Lemma</h3><p>We calculate the implied volatility from the classic Black-ScholesMerton model for option pricing. And how did Fischer Black, Myron Scholes, and Robert Merton develop this model? They stood on the shoulders of Kiyoshi Ito! 🙂</p><hr><h3 id="till-next-time">Till Next Time</h3><p>And this is where I bid au revoir! Do backtest the code and check whether it can predict the range of future prices with reasonable accuracy. You can also use mean +/- 1 standard deviation in place of 2 standard deviation. The benefit? The range would be tighter, and you could pocket more premium. The flip side? The chances of being profitable get reduced to around 68%! You can also think of other ways how to capitalise on this prediction. Do let us know in the comments what you tried.</p><hr><h3 id="references-">References:</h3><p><strong>Main Reference:</strong></p><p><a href="https://research.tilburguniversity.edu/files/51558907/INTRODUCTION_TO_FINANCIAL_DERIVATIVES.pdf">https://research.tilburguniversity.edu/files/51558907/INTRODUCTION_TO_FINANCIAL_DERIVATIVES.pdf</a></p><p><strong>Auxiliary References:</strong></p><p>Wikipedia pages of Ito’s lemma, Brownian motion, geometric Brownian motion, quadratic variation, and, AM-GM inequality</p><p>EPAT lectures on statistics and options trading</p><hr><h3 id="file-in-the-download">File in the download</h3><ul><li>Ito's_Lemma - Python notebook</li></ul><!--kg-card-begin: html--><p style="text-align: center;"><a href="https://blog.quantinsti.com/itos-lemma-applied-stock-trading" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: html--><hr><!--kg-card-begin: html--><p><em><small>All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Laying the Groundwork for Ito's Lemma and Financial Stochastic Models]]></title><description><![CDATA[Explore the foundational concepts behind Ito's Lemma in trading, including the chain rule, deterministic and stochastic processes, the drift and volatility components of stock prices, and how stocks follow a Weiner process.
]]></description><link>https://blog.quantinsti.com/itos-lemma-trading-concepts-guide/</link><guid isPermaLink="false">673fe7cdda24e139f544d53a</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Mahavir A. Bhattacharya]]></dc:creator><pubDate>Fri, 06 Dec 2024 11:15:14 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/mahavir-bhattacharya-1303b011b/">Mahavir A. Bhattacharya</a><br><br>This is a two-part blog where we’ll explore how Ito’s Lemma extends traditional calculus to model the randomness in financial markets. Using real-world examples and Python code, we’ll break down concepts like drift, volatility, and geometric Brownian motion, showing how they help us understand and model financial data, and we’ll also have a sneak peek into how to use the same for trading in the markets.</p><p>In the first part, we’ll see how classical calculus cannot be used for modeling stock prices, and in the second part, we’ll have an intuition of Ito’s lemma and see how it can be used in the financial markets.</p><p>If you are already conversant with the chain rule in calculus, the concepts of deterministic and stochastic processes, drift and volatility components in asset prices, and Wiener processes, you can skip this blog and directly read this one: <a href="https://blog.quantinsti.com/itos-lemma-applied-stock-trading/">Ito's Lemma Applied to Stock Trading</a></p><p>It has an involved discussion on Ito’s lemma, and how it is harnessed for trading in the financial markets.</p><hr><p>This blog covers:</p><!--kg-card-begin: html--><div>
    <ul style="font-size: 20px;">
        <li><a href="#pre-requisites">Pre-requisites</a></li>
        <li><a href="#etymology-of-sorts">Etymology of Sorts</a></li>
        <li><a href="#the-chain-rule">The Chain Rule</a></li>
        <li><a href="#deterministic-and-stochastic-processes">Deterministic and Stochastic Processes</a></li>
        <li><a href="#drift-and-volatility-components-on-python">Drift and Volatility Components on Python</a></li>
        <li><a href="#weiner-weiner-stochastic-dinner">Weiner Weiner Stochastic Dinner</a></li>
    </ul>
</div><!--kg-card-end: html--><hr><h3 id="pre-requisites">Pre-requisites</h3><p>You will be able to follow the article smoothly if you have elementary-level proficiency in:</p><ul><li>Calculus</li><li>Python coding</li></ul><hr><h3 id="etymology-of-sorts">Etymology of Sorts</h3><p>You would have learned theorems in high school math. Simply put, a lemma is like a milestone in attempting to prove a theorem. So what is Ito’s lemma? Kiyoshi Ito came up with his own ways of calculus (as if the existing ones weren’t hard to learn already 😝). Why did he do that? Were there any problems with the existing methods? Let’s understand this with an example.</p><hr><h3 id="the-chain-rule">The Chain Rule</h3><p>Suppose we have the following function:</p><p>$$ y = \sin(3x) $$</p><p>This function can also be written as:</p><p>$$y = \sin(z), \quad \text{where} \quad z = 3x$$</p><p>Here, y is a function of z, which itself is a function of x. Such functions are known as composite functions.</p><p>This means that whatever value x takes, z would take thrice its value, and whatever value z takes, y would take its corresponding sine value.</p><p>Suppose x doubles, what would happen to z? It would also double. And when x halves, z would also halve. Thus, z would always bear the same ratio with x, i.e., 3. The ratio between the change in z, and the change in x would also be 3. We refer to this as the derivative of z with respect to x, also denoted by: dz/dx.</p><p>From elementary calculus, you would know that dz/dx = 3.</p><p>Similarly, dy/dz = cos(x), that is, the tangent to the slope of the sinusoidal curve sin(x) at every point on the curve would be cos(x).</p><p>What about dy/dx?</p><p>We can solve this using the chain rule, shown below:</p><p>$$ \frac{dy}{dx} = \frac{dy}{dz} \cdot \frac{dz}{dx} $$					–-------------- 1</p><p>Substituting the above values for dy/dz and dz/dx,</p><p>$$ \frac{dy}{dx} = \cos(x) \cdot 3 = 3 \cos(x) $$</p><p>Straightforward, isn’t it?</p><p>Sure, but only when we deal with ‘functions’. The problem is, when it comes to finance, we deal with processes. What kind of processes? Well, we can have deterministic processes and stochastic processes.</p><hr><h3 id="deterministic-and-stochastic-processes">Deterministic and Stochastic Processes</h3><p>A deterministic process is one whose realized path, and value after certain intervals of time is known beforehand with certainty.  Examples would be the returns on a fixed deposit or the payouts of an annuity.</p><p>What about a stochastic process then? Can you think of something whose value can never be predicted with certainty, even for the next second? The path traversed by a stock! Can you imagine a world where the stock prices follow a deterministic path? No, right? But hey, we’ll discuss this too in a while now!</p><p>Coming back, in financial literature, stock prices are assumed to follow a Geometric Brownian motion. What’s that? Keep reading!</p><p>Suppose you ignite an incense stick. What variables contribute to the path that a single particle of fumes from the stick would follow? The wind speed in the surroundings, the direction of the wind, the density of the surrounding air, the absolute and relative proportion of other particles already present in the air, the size of the particles of the incense stick, the gap between each particle, the molecular orientation of the particles, their inflammability, and so on.</p><p>Even if you can create an elegant model that factors in the effect of all these variables, would you be able to predict with certainty the exact path that a single fume particle would traverse? No! Same is the case with asset prices. Suppose you know the fundamentals of the underlying, values of all technical indicators, the drift (we’ll come to this in a while), the volatility, the risk-free rate, macro-economic metrics, market sentiments, and everything else. Can you predict the exact path the price will take tomorrow? </p><p>If yes, well, you don’t need to read any further. Keep your secrets and make a ton of money 😁. Realistically, we cannot predict it with certainty. Stock returns follow a path similar to the incense stick fumes. We call it  “Brownian motion” or “Wiener process”.</p><p>How do we characterise them?</p><p>Firstly, the value of the random variable at time t = 0, is 0.</p><p>Secondly, the value of the random variable at one time instant would be independent of its value in any previous time instant.</p><p>Thirdly, the random variable would have a normal distribution.</p><p>Finally, the random variable would follow a continuous path, not a discrete one.</p><p>Now, stock prices don’t have values = 0, at time t =0 (when they get listed). Stock prices are also known to have autocorrelations; i.e., the price at any given instant depends on one or more of the prices in previous instances. Stock prices also don’t follow a normal distribution. Still, how can it be that they follow a Brownian motion?</p><p>There’s a minor tweak that we need to do here. We shall use the daily returns of the adjusted close prices as a proxy for the increments in the stock prices. And since the price returns follow a Brownian motion, the prices themselves follow what is known as a geometric Brownian motion (GBM).</p><p>Let’s explore the GBM further using math notation. Suppose we have a stochastic process S. We say that it follows a GBM if it can be written in the following form:</p><p>$$ dS_t = \mu S_t \, dt + \sigma S_t \, dW_t $$							--------------- 2</p><p>Let’s treat S as the stock price here.</p><!--kg-card-begin: html--><p><em>dS<sub>t</sub></em> simply refers to the change in the stock price over time <em>t</em>. Suppose the current price is $200, and it becomes $203 the next day. In this case, <em>dS<sub>t</sub></em> = $3, and <em>t</em> = 1 day.</p>
<!--kg-card-end: html--><p>The Greek alphabet μ (written as mu, and pronounced as ‘mew’) represents the drift. Let’s take the Microsoft stock to understand this.</p><hr><h3 id="drift-and-volatility-components-on-python">Drift and Volatility Components on Python</h3><p><strong>Note:</strong> The graphs and values obtained are as of October 18, 2024.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/178eda47686896117b627ca754c99502.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/1-year-close-prices.png" class="kg-image" alt="Figure 1: Adjusted Close Price"><figcaption><em>Figure 1: Adjusted Close Price</em></figcaption></figure><p></p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/bd9f49662150a47f788d7119a9ca87a1.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Drift-component-of-close-price.png" class="kg-image" alt="Figure 2: Drift Component of the Close Price"><figcaption><em>Figure 2: Drift Component of the Close Price</em></figcaption></figure><p></p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/4c211f159695905d4a2a836a93002887.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Volatility-Component-of-the-Close-Price-.png" class="kg-image" alt="Figure 3: Volatility Component of the Close Price"><figcaption><em>Figure 3: Volatility Component of the Close Price</em></figcaption></figure><p></p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/4c211f159695905d4a2a836a93002887.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Close-Prices-and-Drift-Component-.png" class="kg-image" alt="Figure 4 Close Prices and Drift Component"><figcaption><em>Figure 4 Close Prices and Drift Component</em></figcaption></figure><p></p><p>This last plot (Figure 4) is the crux of everything we did on Python. What’s the blue line denoting? It’s the path taken by Microsoft stock's adjusted close prices over the past ten years. And what’s the orange line for? Well, it’s just a simple straight line that connects the first day's adjusted closing price and the most recent adjusted closing price.</p><p>I’m trying to show here that irrespective of which of the two paths the stock would have taken, it would have reached the same destination today. We can see from the blue line that the stock price has increased over the past ten years. That explains the positive slope of the orange line. This is known as the “drift”. We have essentially broken down the path of the adjusted close price into two components: the drift, and the volatility. When we add these two, we get the adjusted close prices. The following plot (Figure 5) illustrates this by plotting all three together:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/650794dde3d4e45b5447c75408f35d40.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Close--Drift-Component--and-Volatility-Component-.png" class="kg-image" alt="Figure 5 Close, Drift Component, and Volatility Component"><figcaption><em>Figure 5 Close, Drift Component, and Volatility Component</em></figcaption></figure><p></p><p><strong>Stock Price = Drift Component + Volatility Component</strong></p><p>If you need more intuition on the drift and volatility component, imagine driving from cities A to B. As much as you would like to take the imaginary path that connects both cities straight, you can’t since there will be buildings, trees, mountains, etc. You would need to take detours and turns to reach your destination.</p><p>Remember I asked you to imagine a world where the stock prices follow a deterministic path? That’s what the drift component is, after all! Can you imagine trading in a world where stock prices follow only the drift component and don’t have any volatility component?</p><p>We have taken a long detour from our main discussion (yup, we have drifted away from our drift)! Coming back to the GBM, we understood what μ is. σ is another Greek alphabet (called and pronounced as ‘sigma’) and denotes the volatility. </p><p>In equation 2, the first term is the deterministic component, and the second term is the stochastic or random or indeterministic, or noise component. Also, μ is the percentage drift, and σ is the percentage volatility.</p><p>The equation essentially tells that the change in the stock price at time t is an additive combination of the change in the stock price due to the drift component and the volatility component.</p><p>The drift component here is the product of the drift μ, the stock price at time t, and the unit change in time dt. Let’s consider dt to be one day, as mentioned earlier, for the sake of simplicity. If the stock price S is treated as a continuous random variable, ideally, we should measure dt in milli, micro, nano, or even picoseconds.</p><hr><h3 id="weiner-weiner-stochastic-dinner">Weiner Weiner Stochastic Dinner<br></h3><p>The volatility component is more nuanced.  We know what σ and St denote in the equation. What we don’t know yet is: $$ W_t $$</p><p>Or do we? </p><p>Remember Brownian motion (the fumes of the incense stick)? That’s what \( W_t \) denotes here. The letter W is used since this motion is called a Wiener process. I’ll (hopefully) discuss Wiener processes in depth in a subsequent blog. But for now, just know that the increments follow a normal distribution with mean = 0 and variance = t for a Wiener process.</p><p>This means if the value of \( W_t \) changes from \( W_1 \) to \( W_2 \), \( W_2\) to \( W_3 \), and so on, the changes \( W_2 \) – \( W_1 \), \( W_3 \) – \( W_2 \), and so on follow a normal distribution. The mean or expected value of this distribution is 0. This means that if we have many samples of such changes, the average of these changes would be 0 (or very close to it). What about the variance? The variance is equal to the time duration; hence, the standard deviation would be the root of this time duration.</p><!--kg-card-begin: html--><p>When we say \( W_t \) follows a normal distribution with mean = 0 and variance = t, multiplying this with \( \sigma \), we can conclude that the volatility component follows a normal distribution with mean = 0, and variance = \( \sigma_t \).</p>
<!--kg-card-end: html--><p>Wanna see what a Weiner process looks like!</p><p>Here you go…</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/fbfa498cb7c7ef9f640cb1cb35bed3a4.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Weiner-Process-Plot.png" class="kg-image"><figcaption><em><em>Figure 6 Weiner Process Plot</em></em></figcaption></figure><p>We simulated 15 paths that the Wiener process could have taken, over 10 days. At what frequency are the values getting updated? Every second. The shaded region is the expected standard deviation of the returns. This is how the fumes from an incense stick would look if you tilt it sideways!</p><hr><h3 id="conclusion">Conclusion</h3><p>With this, we come to the end of part I. We learned about the chain rule in classical calculus, Brownian motion, geometric Brownian motion, and how stock prices follow a geometric Brownian motion. We also developed a visual intuition for Wiener processes (Brownian motion).</p><p>In part II, we’ll cover Ito calculus, and show how to use it for developing a trading strategy. Here’s the link to the second part: <a href="https://blog.quantinsti.com/itos-lemma-applied-stock-trading/">Ito's Lemma Applied to Stock Trading</a>.</p><p>You can avail of the below-mentioned free <a href="https://quantra.quantinsti.com/courses">Quantitative Finance Course</a> offerings on Quantra to gain insights into Python for trading, data procurement, and stock market basics:</p><ol><li><a href="https://quantra.quantinsti.com/course/python-trading-basic">Python for Trading</a></li><li><a href="https://quantra.quantinsti.com/course/getting-market-data">Get Market Data</a></li><li><a href="https://quantra.quantinsti.com/course/stock-market-basics">Stock Market Beginner Course</a></li></ol><p>If you need a small primer on the math required for trading in the financial markets, you can go through this blog article: https://blog.quantinsti.com/algorithmic-trading-maths/</p><p>If you want to get started with algorithmic trading and need knowledge on how to do so, you can learn from here: </p><p><a href="https://quantra.quantinsti.com/course/getting-started-with-algorithmic-trading">Algorithmic Trading for Beginners</a></p><p>And, if you want to learn in detail the basic and advanced statistics used in algo trading, data modeling, strategy building, backtesting using Python, how to set up your <a href="https://www.quantinsti.com/articles/proprietary-trading-desk/">proprietary trading desk</a> and much more, you can check out the EPAT:</p><p><a href="https://www.quantinsti.com/epat">Algorithmic Trading Course</a></p><hr><h3 id="references-">References:</h3><p><strong>Main Reference:</strong></p><p><a href="https://research.tilburguniversity.edu/files/51558907/INTRODUCTION_TO_FINANCIAL_DERIVATIVES.pdf">https://research.tilburguniversity.edu/files/51558907/INTRODUCTION_TO_FINANCIAL_DERIVATIVES.pdf</a></p><p><strong>Auxiliary References:</strong></p><ol><li>Wikipedia pages of Ito’s lemma, Brownian motion, geometric Brownian motion, quadratic variation, and, AM-GM inequality</li></ol><p>2. EPAT lectures on statistics and options trading</p><hr><!--kg-card-begin: html--><p><em><small>All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[The Risk-Constrained Kelly Criterion: From the foundations to trading]]></title><description><![CDATA[Learn about the risk-constrained Kelly Criterion to make your trading have less drawdown and better strategy performance!]]></description><link>https://blog.quantinsti.com/risk-constrained-kelly-criterion/</link><guid isPermaLink="false">67335295c293147e1029091e</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Jose Carlos Gonzales Tanaka]]></dc:creator><pubDate>Mon, 25 Nov 2024 04:42:35 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/jos%C3%A9-carlos-gonz%C3%A1les-tanaka-60859284/">José Carlos Gonzáles Tanaka</a></p><p>The Kelly Criterion is good enough for long-term trading where the investor is risk-neutral and can handle big drawdowns. However, we cannot accept long-duration and big drawdowns in real trading. To overcome the big drawdowns caused by the Kelly Criterion, Busseti et al. (2016) offered a risk-constrained Kelly Criterion that incorporates maximizing the long-term log-growth rate together with the drawdown as a constraint. This constraint allows us to have a smoother equity curve. You will learn everything about the new type of Kelly Criterion here and apply a trading strategy to it. You can find the risk-constraint Kelly criterion code on <a href="https://github.com/quantra-go-algo/Algorithmic-Trading-Code-Examples/tree/main/blog_articles/risk-constrained-kelly-criterion">GitHub</a> as well.</p><p>This blog covers:</p><ul><li><a href="#the-kelly-criterion">The Kelly criterion</a></li><li><a href="#the-risk-constrained-kelly-criterion">The risk-constrained Kelly criterion</a></li><li><a href="#a-trading-strategy-based-on-the-risk-constrained-kelly-criterion">A trading strategy based on the risk-constrained Kelly Criterion</a></li></ul><hr><h2 id="the-kelly-criterion">The Kelly criterion</h2><p>The Kelly Criterion is a well-known formula for allocating resources into a portfolio.</p><p>You can learn more about it by using many resources on the Internet. For example, you can find a quick <a href="https://quantra.quantinsti.com/glossary/Kelly-criterion">definition of Kelly Criterion</a>, <a href="https://blog.quantinsti.com/position-sizing/">a blog with an example of position sizing</a>, and even a <a href="https://blog.quantinsti.com/risk-management-webinar-25-october-2018/">webinar on Risk Management</a>.</p><p>We won’t go deep on the explanation since the above links already do that. Here, we provide the formula and some basic explanation for using it.</p><!--kg-card-begin: html-->$$K\% = W - \frac{1 - W}{R}$$<!--kg-card-end: html--><p>where,</p><ul><li>K% = The Kelly percentage</li><li>W = Winning probability</li><li>R = Win/loss ratio</li></ul><p>Let’s understand how to apply.</p><p>Suppose we have your strategy returns for the past 100 days. We get the hit ratio of those strategy returns and set it as “W”. Then we get the absolute value of the mean positive return divided by the mean negative return. The resulting K% will be the fraction of your capital for your next trade.</p><p>The Kelly Criterion ensures the maximum long-term return for your trading strategy. This is from a theoretical perspective. In practice, if you applied the criterion in your trading strategy, you would face many long-lasting big drawdowns. </p><p>To solve this problem, Busseti et al. (2016) provided the “risk-constrained Kelly Criterion”, which allows us to have a smoother equity curve with less frequent and small drawdowns.</p><hr><h2 id="the-risk-constrained-kelly-criterion">The risk-constrained Kelly criterion</h2><p>The Kelly criterion relates to an optimization problem. For the risk-constraint version, we add, as the name says, a constraint. The basic principle of the constraint can be formulated as:</p><!--kg-card-begin: html-->$$Prob(Minimum\; wealth < alpha) < beta$$<!--kg-card-end: html--><p>The drawdown risk is defined as Prob(Minimum Wealth &lt; alpha), where alpha ∈ (0, 1) is a given target (undesired) minimum wealth. This risk depends on the bet vector b in a very complicated way. The constraint limits the probability of a drop in wealth to value alpha to be no more than beta. </p><p>The authors highlight the important issue that the optimization problem with this constraint is highly complex thing to solve. Consequently, to make it easier to solve it, Busseti et al. (2016) provided a simpler optimization problem in case we have only 2 outcomes (win and loss), which is the following:<br></p><!--kg-card-begin: html-->$$\text{maximize } \pi \log(b_1 P + (1 - b_1)) + (1 - \pi)(1 - b_1),\\
\text{ subject to } 0 \leq b_1 \leq 1,\\
\pi(b_1 P + (1 - b_1))^{-\frac{\log \beta}{\log \alpha}} + (1 - \pi)(1 - b_1)^{-\frac{\log \beta}{\log \alpha}} \leq 1.$$<!--kg-card-end: html--><p>Where:</p><p>Pi: Winning probability</p><p>P: The payoff of the win case.</p><p>b1: The kelly fraction to be found. b1= K%. The control variable of the maximization problem</p><p>Lambda: The risk aversion of the trader: log(beta)/log(alpha)</p><p>Please take into account that the win/loss ratio defined in the basic criterion named as R is:</p><p>R = P - 1, where P is the payoff of the win case described for the risk-constrained Kelly criterion.</p><p>You might ask now: I don’t know how to solve that optimization problem! Oh no!</p><p>I can surely help with that! The authors have proposed a solution. See below!</p><p>The solution algorithm for the risk-constrained Kelly criterion goes like this:</p><p>If B1 = (pi*P-1)/(P-1) satisfies the risk constraint, then that is the solution. Otherwise, we find b1 by finding the b1 value for which</p><!--kg-card-begin: html-->$$\pi(b_1 P + (1 - b_1))^{-\lambda} + (1 - \pi)(1 - b_1)^{-\log \lambda} = 1.$$<!--kg-card-end: html--><p>As explained by the authors, the solution can be found with a bisection algorithm.</p><hr><h2 id="a-trading-strategy-based-on-the-risk-constrained-kelly-criterion">A trading strategy based on the risk-constrained Kelly Criterion</h2><p>Let’s inspect a trading strategy based on the risk-constrained Kelly criterion!</p><p>Let’s import the libraries.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/10b478e05cb03a523babf627e3c46327.js"></script><!--kg-card-end: html--><p>Let’s define our customized bisection method for later use:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/cd24f69a01dcf3fac590cb82d98de1e3.js"></script><!--kg-card-end: html--><p>Let’s define our 2 functions to be used to compute the risk-constraint Kelly criterion bet size:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/619e3b79de5f3ff3cbd3d1c228694053.js"></script><!--kg-card-end: html--><p>Let’s import the MSFT stock data from 1990 to October 2024 and compute the buy-and-hold returns.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/dc49e50a429260d0e40c9dc19263a92c.js"></script><!--kg-card-end: html--><p>Let’s get all the available technical indicators in the “ta” library:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/aced8538f5ba45993fd7e8c89af15645.js"></script><!--kg-card-end: html--><p>Let’s create the prediction feature and some relevant columns.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/636cf80844649f371b78e90a22700dbf.js"></script><!--kg-card-end: html--><p>Let’s define the seed and some other relevant variables.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/0643a02c61af25ba7f063d71778a0d30.js"></script><!--kg-card-end: html--><p>We will use a for loop  to iterate through each date.</p><p>The algorithm goes like this, for each day:</p><ol><li>Sub-sample the data where we’ll use one year of data and the last 60 days as the test span for the sub-sample data</li><li>Split the data into X and y and their respective train and test sections</li><li>Fit a Support Vector machine model</li><li>Predict the signal</li><li>Obtain the strategy returns</li><li>Get the positive mean return as pos_avg</li><li>Get the negative mean return as neg_avg</li><li>Get the number of positive returns as pos_ret_num</li><li>Get the number of negative returns as neg_ret_num</li><li>Set some conditions to get the position size for the day</li><li>Get the basic-Kelly and risk-constraint Kelly fraction</li><li>Split the data once again as train and test data to</li><li>Estimate once again the model, and</li><li>Predict the next-day signal</li></ol><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/517422ff3f8034e06359b3e2a72da2fa.js"></script><!--kg-card-end: html--><p>Let’s compute the strategy returns. We compute 2 strategies, the basic Kelly strategy and the risk-constrained Kelly strategy. Apart from that,  I’ve incorporated an “improved” version of the strategy which consists of having the same signal of the previous 2 strategies, but with the condition that the buy-and-hold cumulative returns is higher than their 30-day moving average.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/6f2a1c25470f9fe0631c907ed67a6936.js"></script><!--kg-card-end: html--><p>Let’s see now the graphs. We see the basic Kelly position sizes.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/416e5631db4fc482e0ab0efc4c8d0b8e.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Kelly-position-sizes.png" class="kg-image" alt="Kelly position sizes"></figure><p>It has high volatility. It ranges from 0 to 0.6.</p><p>Let’s see the risk-contraint Kelly fractions.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/d07eb50604d8e957335e86d702764427.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Risk-constraint-kelly-sizes.png" class="kg-image" alt="Risk-constraint kelly position sizes"></figure><p>It now ranges from 0 to 0.25. It has a lower range of volatility.</p><p>Let’s see the strategy returns from the both.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/9488a815f109eb5a75cd340febb27c94.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Buy-and-hold-kelly.png" class="kg-image" alt="Buy and hold kelly bases strategies"></figure><p>The basic Kelly strategy has a higher drawdown, as informally checked. The main drawback of the risk-constraint Kelly strategy is the lower equity curve.</p><p>Let’s see the improved strategy returns.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/9488a815f109eb5a75cd340febb27c94.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/11/Buy-and-hold-improved-kelly.png" class="kg-image" alt="Buy and hold improved kelly and risk-constraint"></figure><p>It’s interesting to see that the basic Kelly strategy gets to reduce its drawdown, the same for the risk-constrained strategy. The risk-constrained strategy keeps having a low equity curve.</p><p>Some comments:</p><ul><li>Once you have a good Sharpe ratio, you can increase the leverage. So, don’t get disappointed by the low equity curve of the risk-constraint Kelly strategy. I leave as an exercise to check that.</li><li>You can increase the equity returns with stop-loss and take-profit targets.</li><li>You can combine the risk-constraint Kelly criterion with meta-labelling.</li><li>The risk-constraint Kelly criterion limitation is the low equity curve. You can imagine solutions to improve the results!</li><li>You can use the pyfolio-reloaded library to implement the trading summary statistics and analytics to check formally the lower drawdown and volatility of the risk-constraint Kelly strategy.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>As you can see, you can implement the risk-constraint Kelly Criterion to get a smoother equity curve. The main issue might be that it gets you a lower cumulative return, but it can help find days you don’t need to trade, saving you drawdowns!</p><p>If you want to learn more about position sizing, don’t forget to take our course on <a href="https://quantra.quantinsti.com/course/position-sizing-trading">position sizing</a>!</p><hr><h3 id="references">References</h3><p>Busseti, E., Ryu, E. K., Boyd, S. (2016), “Risk-Constrained Kelly Gambling”, Working paper. <a href="https://web.stanford.edu/~boyd/papers/pdf/kelly.pdf">https://web.stanford.edu/~boyd/papers/pdf/kelly.pdf</a></p><hr><p><strong>File in the download</strong></p><ul><li>The Kelly Criterion - Python notebook</li></ul><!--kg-card-begin: html--><p style="text-align: center;"><a href="https://blog.quantinsti.com/risk-constrained-kelly-criterion" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: html--><hr><!--kg-card-begin: html--><p><em><small>Disclaimer: All data and information provided in this article are for informational purposes only. QuantInsti<sup>®</sup> makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information in this article and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis..</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[A time-varying-parameter vector autoregression model with stochastic volatility]]></title><description><![CDATA[Learn about the TVP-VAR model that is being heavily used in macroeconomics. It can give you better results than a basic VAR for trading. Enjoy it!]]></description><link>https://blog.quantinsti.com/tvp-var-stochastic-volatility/</link><guid isPermaLink="false">6721fbb0c293147e10290786</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Jose Carlos Gonzales Tanaka]]></dc:creator><pubDate>Thu, 07 Nov 2024 14:44:45 GMT</pubDate><content:encoded><![CDATA[<p><br><strong>By</strong> <a href="https://www.linkedin.com/in/jos%C3%A9-carlos-gonz%C3%A1les-tanaka-60859284/">José Carlos Gonzáles Tanaka</a></p><p>The basic Vector Autoregression (VAR) model is heavily used in macro-econometrics for explanatory purposes and forecasting purposes in trading. In recent years, a VAR model with time-varying parameters has been used to understand the interrelationships between macroeconomic variables. Since Primiceri (2005), econometricians have been applying these models using macroeconomic variables such as:</p><ul><li>Japan time series (Nakahima, 2011)</li><li>US Bond yields (Fischer et al., 2022)</li><li>Monthly Stock Indices from industrialized countries (Gupta et al., 2020)</li><li>Peruvian exchange rate (Rodriguez et al., 2024)</li><li>Indian exchange rate (Kumar, M., 2010)</li></ul><p>This article extends the model usage to something our audience greatly cares about: trading! You’ll learn the basics of the estimation procedure and how to create a trading strategy based on the model. You can find the TVP-VAR-SV model code on <a href="https://github.com/quantra-go-algo/Algorithmic-Trading-Code-Examples/tree/main/blog_articles/A-time-varying-parameter-vector-autoregression-model-with-stochastic-volatility">GitHub</a> as well.</p><p>Are you excited? I was when I started writing this article. Let me share what I’ve learned with you!</p><p>This blog covers:</p><ul><li><a href="#what-is-the-difference-between-a-basic-var-and-a-tvp-var-sv-model">What is the difference between a basic VAR and a TVP-VAR-SV model?</a></li><li><a href="#the-tvp-var-sv-model-variables">The TVP-VAR-SV model variables</a></li><li><a href="#the-priors">The priors</a></li><li><a href="#the-mixture-of-indicators">The mixture of indicators</a></li><li><a href="#the-tvp-var-sv-model-estimation-algorithm">The TVP-VAR-SV model estimation algorithm</a></li><li><a href="#a-tvp-var-sv-estimation-in-r">A TVP-VAR-SV estimation in R</a></li><li><a href="#a-trading-strategy-using-the-tvp-var-sv-model-in-r">A trading strategy using the TVP-VAR-SV model in R</a></li><li><a href="#notes-about-the-tvp-var-sv-strategy">Notes about the TVP-VAR-SV strategy</a></li></ul><hr><h2 id="what-is-the-difference-between-a-basic-var-and-a-tvp-var-sv-model">What is the difference between a basic VAR and a TVP-VAR-SV model?</h2><p>All the explanations of the basic VAR can be found in our previous article on <a href="https://blog.quantinsti.com/vector-autoregression/">VAR models</a>. Here, we’ll provide the system of equations and compare them with our new model.</p><p>Let’s remember the basic model. For example, a basic bivariate VAR(1) can be described as a system of equations:</p><!--kg-card-begin: html-->\[
Y_{1,t} = \phi_{11} Y_{1,t-1} + \phi_{12} Y_{2,t-1} + u_{1,t}
\]
\[
Y_{2,t} = \phi_{21} Y_{1,t-1} + \phi_{22} Y_{2,t-1} + u_{2,t}
\]
<!--kg-card-end: html--><p>Or,</p><!--kg-card-begin: html-->\[
Y_t = \Phi Y_{t-1} + U_t
\]<!--kg-card-end: html--><p>Where</p><!--kg-card-begin: html-->\[
Y_t = \begin{bmatrix} Y_{1,t} \\ Y_{2,t} \end{bmatrix}
\]
\[
\Phi_t = \begin{bmatrix} \phi_{11} & \phi_{12} \\ \phi_{21} & \phi_{22} \end{bmatrix}
\]
\[
Y_{t-1} = \begin{bmatrix} Y_{1,t-1} \\ Y_{2,t-1} \end{bmatrix}
\]
\[
U_t = \begin{bmatrix} u_{1,t} \\ u_{2,t} \end{bmatrix}
\]<!--kg-card-end: html--><p>A time-varying parameter VAR would be something like the following:</p><!--kg-card-begin: html-->\[
Y_{1,t} = \phi_{11,t} Y_{1,t-1} + \phi_{12,t} Y_{2,t-1} + \epsilon_{1,t}
\]
\[
Y_{2,t} = \phi_{21,t} Y_{1,t-1} + \phi_{22,t} Y_{2,t-1} + \epsilon_{2,t}
\]
<!--kg-card-end: html--><p>Do you get to see the difference between the two models? Not yet?</p><p>Let’s use matrices to see it clearly.</p><!--kg-card-begin: html-->\[
Y_t = \Phi_t Y_{t-1} + U_t
\]
<!--kg-card-end: html--><p>Where:</p><!--kg-card-begin: html-->\[
Y_t = \begin{bmatrix} Y_{1,t} \\ Y_{2,t} \end{bmatrix}
\]
\[
\Phi_t = \begin{bmatrix} \phi_{11,t} & \phi_{12,t} \\ \phi_{21,t} & \phi_{22,t} \end{bmatrix}
\]
\[
Y_{t-1} = \begin{bmatrix} Y_{1,t-1} \\ Y_{2,t-1} \end{bmatrix}
\]
\[
\mathcal{E}_t = \begin{bmatrix} \epsilon_{1,t} \\ \epsilon_{2,t} \end{bmatrix}
\]
<!--kg-card-end: html--><p>Now you see it?</p><p>The only difference is that the model's parameters vary as time passes. Hence, it’s referred to as a  “time-varying-parameter” model.</p><p>Even though the difference appears simple,  the estimation procedure is much more complex than the basic VAR estimation. </p><p>You now say: I know we can have time-varying parameters, but where is the stochastic volatility in the previous equations? </p><p>Wait for it, my friend! We’ll see it later!</p><p>Don’t worry, we’ll keep it simple!</p><hr><h2 id="the-tvp-var-sv-model-variables">The TVP-VAR-SV model variables</h2><h3 id="the-system-of-equations-of-the-model">The system of equations of the model</h3><p>Using a new notation provided by Primiceri (2005):</p><!--kg-card-begin: html-->$$Y_t = B_t Y_{t-1} + A_t^{-1} \Sigma_t^{-1} \varepsilon_t$$<!--kg-card-end: html--><p>Where:</p><p>Y: The vector of time series</p><p>B: The parameters of the lagged time series of this reduced model</p><p>A: The contemporary parameters of the time series vector</p><p>Sigma: The time-varying <a href="https://blog.quantinsti.com/standard-deviation/">standard deviation</a> (volatility) of each equation in the VAR.</p><p>Epsilon: A vector of shocks of each equation in the VAR.</p><h3 id="what-is-the-reduced-model-and-what-are-contemporary-parameters">What is the reduced model and what are contemporary parameters?</h3><p>Well, in macroeconometrics, the reduced model can be understood as a simple VAR as modeled in our previous article on <a href="https://blog.quantinsti.com/vector-autoregression/">VAR models</a>. In this model, today’s time series values of the VAR vector are impacted only by their lag versions.</p><p>However, economists also talk about the impact that the same today’s time series values have on each other today’s time series values. This can be modeled as:</p><!--kg-card-begin: html-->$$A_t Y_t = C_t Y_{t-1} + \Sigma_t \varepsilon_t$$
<!--kg-card-end: html--><p>This can shown as a matrix below:</p><!--kg-card-begin: html-->$$\begin{bmatrix}
a_{11,t} & a_{12,t} \\
a_{21,t} & a_{22,t}
\end{bmatrix}
\begin{bmatrix}
y_{1,t} \\
y_{2,t}
\end{bmatrix}
=
\begin{bmatrix}
c_{11,t} & c_{12,t} \\
c_{21,t} & c_{22,t}
\end{bmatrix}
\begin{bmatrix}
y_{1,t-1} \\
y_{2,t-1}
\end{bmatrix}
+ 
\begin{bmatrix}
\sigma_{1,t} & 0 \\
0 & \sigma_{2,t}
\end{bmatrix}
\begin{bmatrix}
\epsilon_{1,t} \\
\epsilon_{2,t}
\end{bmatrix}$$<!--kg-card-end: html--><p>Which can also be presented as a system of equations:</p><!--kg-card-begin: html-->$$\begin{aligned}
a_{11,t}y_{1,t} + a_{12,t}y_{2,t} &= c_{11,t}y_{1,t-1} + c_{12,t}y_{2,t-1} + \sigma_{1,t}\epsilon_{1,t} \\
a_{21,t}y_{1,t} + a_{22,t}y_{2,t} &= c_{21,t}y_{1,t-1} + c_{22,t}y_{2,t-1} + \sigma_{2,t}\epsilon_{2,t}
\end{aligned}$$<!--kg-card-end: html--><p>The above model is understood in econometrics as a structural model to comprehend the time series interrelationships, contemporary or not, between the time series analyzed.</p><p>So, assuming we have daily data, the first question, which belongs to y1, has a12*y2 as today’s y2 impact on today’s y1. The same is true for the second question, which belongs to y2, where we see a21*y1, which is today’s time series y1 impact on y2. In a VAR, we have lag periods impacting today’s variables, in a structural VAR we have today’s variables impacting today’s other variables.</p><p>Due to these contemporary relationships, there is a problem called endogeneity, where the error terms epsilons are correlated with Y_t-1. To estimate a structural VAR, we need to clearly identify the matrix A variables. As Eric (2021) explained, there are 3 ways in the economic literature. But it’s not only that, as per this model, A is also time-varying. We’ll see later how this variables are estimated.</p><p>When you pre-multiply the system of equations by A^-1, you get something like:</p><!--kg-card-begin: html-->$$Y_t = A_t^{-1} C_t Y_{t-1} + A_t^{-1} \Sigma_t \varepsilon_t$$<!--kg-card-end: html--><p>Which can be further simplified as:</p><!--kg-card-begin: html-->$$Y_t = B_t Y_{t-1} + U_t$$<!--kg-card-end: html--><p>So,</p><!--kg-card-begin: html-->$$B_t = \Phi_t = A_t^{-1} C_t \\
U_t = A_t^{-1} \Sigma_t \mathcal{E}_t$$<!--kg-card-end: html--><h3 id="time-varying-volatilities">Time-varying volatilities?</h3><p>Yes! In a basic VAR, the error terms are homoskedastic, meaning, they present constant variance. In this case, we have variances that change over time; they’re time-variant. </p><h3 id="the-time-varying-parameter-stochastic-behaviors">The time-varying parameter stochastic behaviors</h3><p>The basic VAR had its parameters constant. In this TVP-VAR-SV, we have almost all of our parameters time-variant. Due to this, we need to assign them stochastic processes. As in Primiceri (2005), we define them as:</p><!--kg-card-begin: html-->$$\begin{aligned}
B_t &= B_{t-1} + \nu_t \\
a_t &= a_{t-1} + \zeta_t \\
\log \sigma_t &= \log \sigma_{t-1} + \eta_t
\end{aligned}$$<!--kg-card-end: html--><p>We can then specify the matrix of variances of all the model’s shocks as:</p><!--kg-card-begin: html-->$$V = Var \left\{ \begin{bmatrix} \epsilon_t \\ \nu_t \\ \zeta_t \\ \eta_t \end{bmatrix} \right\} = \begin{bmatrix} I_n & 0 & 0 & 0 \\ 0 & Q & 0 & 0 \\ 0 & 0 & S & 0 \\ 0 & 0 & 0 & W \end{bmatrix}$$<!--kg-card-end: html--><p>Where I_n is the identity matrix and n is the number of time series in the VAR (in our case it’s 2). Q, S, and W are square positive-definite <a href="https://blog.quantinsti.com/calculating-covariance-matrix-portfolio-variance/">covariance matrices</a> with a number of rows (or columns) equal to the number of parameters in B, A, and Sigma, respectively.</p><p>Something else to note: sigma is stochastic-based, which can be interpreted as stochastic volatility as, e.g., the <a href="https://blog.quantinsti.com/heston-model/">Heston model</a> is.</p><hr><h2 id="the-priors">The priors</h2><p>For a Bayesian inference, you always need priors. In the Primiceri (2005) algorithm, the priors are computed using your data sample's first “T1” observations.</p><p>Using our previously defined variables, you can specify the priors (following Primiceri, 2005, and Del Negro and Primiceri, 2015):</p><!--kg-card-begin: html-->$$\begin{aligned}
B_0 &\sim N(B_{OLS}, 4V(B_{OLS})) \\
A_0 &\sim N(A_{OLS}, 4V(A_{OLS})) \\
\log \sigma_0 &\sim N(\log \sigma_{OLS}, I_n) \\
Q_0 &\sim IW(k_Q^2 \cdot 40 \cdot V(B_{OLS}), 40) \\
W_0 &\sim IW(k_W^2 \cdot 2 \cdot I_n, 2) \\
S_0 &\sim IW(k_S^2 \cdot 2 \cdot V(A_{OLS}), 2)
\end{aligned}$$<!--kg-card-end: html--><p>Where</p><ul><li>N(): Normal distribution</li><li>B_ols: This is the point estimate of the B parameters obtained by estimating a basic time-invariant VAR using the first T1 observations of the data sample.</li><li>V(B_ols): This is the point estimate of the B parameters’ variances obtained by estimating a basic time-invariant structural VAR using the first T1 observations of the data sample. In B_0, the variance is multiplied by 4. This value can be named k_B.</li><li>A_ols: This is the point estimate of the A parameters obtained by estimating a basic time-invariant structural VAR using the first T1 observations of the data sample.</li><li>V(A_ols): This is the point estimate of the A parameters’ variances obtained by estimating a basic time-invariant structural VAR using the first T1 observations of the data sample. In A_0, this variance is multiplied by 4. This value can be named k_A.</li><li>log(sigma_0): This is the point estimate of the standard errors obtained by estimating a basic time-invariant structural VAR using the first T1 observations of the data sample.}</li><li>I_n: This is the identity matrix with “nxn” dimensions, where “n” is the number of time series used to estimate the VAR on them. Contrary to to A_0 and B_0, this variance is just multiplied by 1, where this value can be named k_sig.</li><li>IW: The inverse Wishart distribution</li><li>Q_0 follows an IW distribution with a scale matrix of k_Q^2 times 40 times V(B_ols) and 40 degrees of freedom</li><li>W_0 follows an IW distribution with a scale matrix of k_W^2 times 2 times V(B_ols) and 2 degrees of freedom</li><li>Q_0 follows an IW distribution with a scale matrix of k_S^2 times 2 times V(B_ols) and 2 degrees of freedom</li><li>k_Q^2, k_W^2 and k_S^2 are 1, 0.01 and 0.1, respectively.</li></ul><p>Once you estimate the priors with the first T1 observations, then you get the posterior distribution using the rest of the data sample.</p><hr><h2 id="the-mixture-of-indicators">The mixture of indicators</h2><p>Before we dive into the algorithm, let’s learn something else. Do you remember the reduced-form model:</p><!--kg-card-begin: html-->$$Y_t = B_t Y_{t-1} + A_t^{-1} \Sigma_t \varepsilon_t$$<!--kg-card-end: html--><p>To clear the error term, we get</p><!--kg-card-begin: html-->$$A_t(Y_t - B_t Y_{t-1}) = A_t \hat{y}_t = \Sigma_t \varepsilon_t$$<!--kg-card-end: html--><p>Primiceri (2005), appendix A.2 explains that the above model has a Gaussian non-linear state space representation. The difficulty with drawing Sigma_t is that they enter the model multiplicatively. </p><p>This presents the issue of not making it easy for the Kalman filter estimation done inside the whole estimation algorithm (The Kalman filter is linear-based). To overcome this issue, Primiceri (2005) applies squaring and takes the logarithms of every element of the previous equation. As a consequence of this transformation, the resulting state-space form becomes non-Gaussian, because the log(epsilon_t^2) has a <a href="https://www.oreilly.com/library/view/bayesian-statistics-an/9781118359778/OEBPS/c1-sec1-0007.htm">log chi-squared distribution</a>. To finally get a normal distribution for the error terms, Kim et al. (1998) use a mixture of normals to approximate each element of log(epsilon_t^2). Thus, the estimation algorithm uses the mixture indicators for each error term and each date.</p><!--kg-card-begin: html-->$$S^T \equiv \{s_t\}_{t=1}^T$$<!--kg-card-end: html--><hr><h2 id="the-tvp-var-sv-model-estimation-algorithm">The TVP-VAR-SV model estimation algorithm</h2><p>First of all, you need to know the TVP-VAR model estimation explained here follows the Primiceri (2005) methodology and Del Negro and Primiceri (2015).</p><p>This methodology uses the modified Bayesian-based Gibbs sampling algorithm provided by Cogley and Sargent (2005) to estimate the parameters.</p><p>Now you say: What? Is that Chinese?</p><p>We’ve got it! Don’t worry! Let’s explain the algorithm in simple words in detail. To let you know, regarding the Bayesian estimation approach, please refer to this article on <a href="https://blog.quantinsti.com/bayesian-inference/">Bayesian Statistics In Finance </a>and this other one on <a href="https://blog.quantinsti.com/introduction-to-bayesian-statistics-in-finance/">Foundations of Bayesian Inference</a> to fully learn more about it.</p><p>Let’s explain the algorithm. Following Del Negro and Primiceri (2015), the algorithm consists of the following loop:</p><!--kg-card-begin: html--><br>\( \text{for each MCMC iteration:} \)
<br>\( \hspace{1em}\text{- Draw } \Sigma^T \text{ from } p(\Sigma^T | y^T, \theta^T, s^T) \)
<br>\( \hspace{1em}\text{- Draw } \theta \text{ from } p(\theta | y^T, \Sigma^T) \)
<br>\( \hspace{1em}\text{- Draw } s^T \text{ from } p(s^T | y^T, \Sigma^T, \theta) \)<!--kg-card-end: html--><p>Where</p><ul><li>Draw means</li></ul><ol><li>Use the Kalman filter to update the state equation and compute the likelihood.</li><li>Sample the variable from its posterior distribution using a Metropolis-Hastings step.</li></ol><ul><li>MCMC is Markov Chain Monte Carlo. Please refer to our article on <a href="https://blog.quantinsti.com/introduction-monte-carlo-analysis/">Introduction To Monte Carlo Analysis</a> to learn more about this type of Monte Carlo and the Metropolis-Hastings algorithm.</li><li>Theta is [B, A, V] where these 3 variables were defined previously.</li><li>p(e|d) is the corresponding probability distribution of “e” given “d”.</li></ul><p>You iterate until you make the distribution converge. Even though we say the algorithm is based on MCMC and Metropolis-Hastings, Primiceri (2005) applies his own specifications for his TVP-VAR-SV model.</p><hr><h3 id="a-tvp-var-sv-estimation-in-r">A TVP-VAR-SV estimation in R</h3><p>Let’s see how we can estimate the model in this programming language. Let’s install the corresponding libraries.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/c77466ecb12f24d15a310f972e8b4aaf.js"></script><!--kg-card-end: html--><p>Then let’s import them</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/133eb6185de63b7b03cf9d9fb6572dfc.js"></script><!--kg-card-end: html--><p>Let’s import the data and compute the log returns.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/a6ce0b166c3c4e1038cbee6aacb74a24.js"></script><!--kg-card-end: html--><p>Let’s estimate the model with all the available data and forecast the next-day return. To get this forecast, we get draws from the converged posterior distribution and we use the mean of all the draws to output a forecast point estimate. You can also use the median or any other measure of central tendency (Giannone, Lenza, and Primiceri, 2015).</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/46efaad9dea9854d6c70baee6549bbf2.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>[0.015880450, 0.013688861, 0.014319192, 0.002445156, 0.005108312, 0.020364678, 0.015684312]</pre><!--kg-card-end: html--><p>These returns’ signs will depend on each day’s estimation.</p><p>There are 4 inputs to discuss:</p><ul><li>tau: is the length of the training sample used for determining prior parameters via least squares (LS). In this case, we set it to one year: 250 observations. So, if we have “n” observations, we use the first 250 observations to get the priors and the last “n-250” for model estimation.</li><li>nf: Number of future time periods for which forecasts are computed. In this case, we’re interested in the next-day return.</li><li>nrep: It’s the number of MCMC draws excluding the burn-in observations. We set it to 300. You can read more about it in our blog on <a href="https://blog.quantinsti.com/introduction-monte-carlo-analysis/">Introduction To Monte Carlo Analysis.</a></li><li>nburn: The number of MCMC draws used to initialize the sampler used for convergence to get the posterior distribution. We set it to 20. So, since we have 300 draws, we compute the posterior distributions with the last 280 draws (300-20).</li></ul><p>The function actually has more inputs, let’s see them together with their default values:</p><p>k_B = 4, k_A = 4, k_sig = 1, k_Q = 0.01, k_S = 0.1, k_W = 0.01,</p><p>pQ = NULL, pW = NULL, pS = NULL</p><p>You can relate k_B, k_A and k_sig with the previous section priors. Regarding the other inputs, see below:</p><!--kg-card-begin: html-->$$\begin{aligned}
k_Q &= 0.01 \\
k_S &= 0.1 \\
k_W &= 0.01 \\
p_Q &= 40 \\
p_W &= 2 \\
p_S &= 2
\end{aligned}$$<!--kg-card-end: html--><hr><h2 id="a-trading-strategy-using-the-tvp-var-sv-model-in-r">A trading strategy using the TVP-VAR-SV model in R</h2><p>Now we get to the place you wanted! We will use the same imported libraries and the same dataframe called var_data, which contains the stocks’ price log returns.</p><p>Some things to say:</p><ul><li>We initialize the forecasts from 2019 onwards.</li><li>We estimate using 1500 observations as span.</li><li>We also estimate a basic VAR to compare performance with our TVP-VAR-SV strategy.</li><li>The strategy for both models will be long only.</li><li>Since the TVP-VAR-SV model estimation takes a lot of time each trading period, we have made the code script so that if you need to stop the code from running, you can do it and run it later by running the whole code again.</li></ul><p>Let’s first define the function that will allow us to import the dataframe of the forecast results dataframe of the basic VAR and the TVP-VAR-SV model in case you have done so previously.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/f601ee0f2db5d384374d57a8094a7c3e.js"></script><!--kg-card-end: html--><p>Then, we</p><ol><li>Set the initial date to start the forecasting process.</li><li>Import the saved df_forecasts dataframe, otherwise, we create a new one without the previous function.</li><li>Set the span as 1500.</li></ol><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/753c7e7cbf21d6eb49a8c28ab0b6a6e3.js"></script><!--kg-card-end: html--><p>Next, we create the basic-VAR-based strategy signals. The code follows our previous article on  <a href="https://blog.quantinsti.com/vector-autoregression/">Vector AutoRegression model</a>.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/09020380d3c7a8b40616ce397c41c72f.js"></script><!--kg-card-end: html--><p>Next, we create the TVP-VAR-SV model signals through a similar loop. This time we set tau to 40. The input can be chosen arbitrarily as long as you respect the proportions between nrep and nburn.</p><p>The estimation of the model each day will take some minutes, thus, the whole loop will take a long time. Be careful. In case you need to turn off your computer before the loop runs, you can just turn on once again your computer and run the script once again. The code is written in such a way that whenever you want to continue running the for loop, you can just run the whole code.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/8c385d4f88abfa70a60a4bdc3bf380ac.js"></script><!--kg-card-end: html--><p>Next, we compute the strategy returns. We have four strategies</p><ul><li>A Buy-and-Hold strategy</li><li>A basic-VAR-based strategy</li><li>A TVP-VAR-SV-based strategy</li><li>A strategy based on the TVP-VAR-SV model makes its long signals if and only if the Buy-and-Hold cumulative returns are higher than their 15-window simple moving average.</li></ul><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/8870609e109e62ece42a9511d86acf8d.js"></script><!--kg-card-end: html--><p>See, Focusing only on equity returns, the basic VAR performs the worst. </p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/10/Buy-and-hold.png" class="kg-image" alt="Buy and hold strategies"></figure><p>The TVP-VAR-SV and the SMA-based TVP-VAR-SV strategy perform closely to the Buy-and-hold strategy. However, the latter performs the best in almost all the years. Let’s see their trading summary statistics.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/10/Trading-summary-stats.png" class="kg-image" alt="Trading summaries"></figure><p>The equity-curve informal conclusion can be further confirmed by the summary statistics.</p><ol><li>The basic VAR performs the worst with respect to not only returns but also equity volatility. This is reflected in poor results for the Sharpe, Calmar, and Sortino ratios. The maximum drawdown is also huge.</li><li>The TVP-VAR-SV performs slightly better with respect to the Buy-and-Hold strategy.</li><li>The SMA-based TVP-VAR-SV is the best performer. It has an increased 80% equity curve return with respect to the Buy-and-Hold strategy and the other statistics are clearly better. The Sortino ratio is quite good, too.</li></ol><hr><h2 id="notes-about-the-tvp-var-sv-strategy">Notes about the TVP-VAR-SV strategy</h2><p>There are some things we need to take into account while developing a strategy based on this model:</p><ul><li>We chose tau equal to 40 arbitrarily, which is probably not enough. Choosing another number would likely produce different results. The seed is also arbitrarily chosen. Do a hyperparameter tuning to get the best results while doing a walk-forward optimization.</li><li>We have chosen nrep equal to 300. This is quite small compared to macroeconometric standards, where nrep gets to be 50,000 in some cases. The reason econometricians use such a large number is that macroeconomic data samples are usually very small compared to financial data samples. Due to the low quantity of data samples, macroeconomic data tends to be fitted with this model very quickly even though they use nrep high. Due to our span being equal to 1500, if we used nrep equal to 50,000, the estimation for each day will surely take hours or even days. That’s why we use only 300 as nrep. Please feel free to change nrep at your convenience. Just make sure that, if you trade hourly, the model estimation should take less time than an hour for live trading, if you trade daily, the model estimation should take less than a day, and so on.</li><li>We haven’t incorporated stop-loss and take-profit targets. Please do so to improve your results.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>We have delved into the basic definition of a TVP-VAR-SV model. We then explained a little bit the model estimation, and finally we opted for a trading strategy backtesting loop script to test the model performance.</p><p>Do you want to learn the basics of the financial time series analysis? Do not hesitate to learn from our course <a href="https://quantra.quantinsti.com/course/financial-time-series-analysis-trading">Financial Time Series Analysis for Trading</a>.</p><p>Do you want more models to be tested?</p><p>Do not hesitate to follow our blog, we’re always creating more strategies for you!</p><hr><h3 id="references">References</h3><ul><li>Cogley, T. and Sargent, T. J. (2005), “Drifts and Volatilities: Monetary Policies and Outcomes in the Post WWII U.S.,” Review of Economic Dynamics, 8(2), 262-302.</li><li>Del Negro, M. and Primiceri, G., (2015), Time Varying Structural Vector Autoregressions and Monetary Policy: A Corrigendum, The Review of Economic Studies, 82, issue 4, p. 1342-1345.</li><li>Eric (2021) “Understanding and Solving the Structural Vector Autoregressive Identification Problem” in https://www.aptech.com/blog/understanding-and-solving-the-structural-vector-autoregressive-identification-problem/, consulted on August 1st, 2024.</li><li>Fischer MM, Hauzenberger N, Huber F, Pfarrhofer M (2023) General Bayesian time-varying parameter VARs for predicting government bond yields. J Appl Econom 38(1):69–87</li><li>Giannone, Domenico, Lenza, Michele and Primiceri, Giorgio, (2015), Prior Selection for Vector Autoregressions, The Review of Economics and Statistics, 97, issue 2, p. 436-451.</li><li>Gupta, R., Huber, F., and Piribauer, P. (2020) Predicting international equity returns: Evidence from time-varying parameter vector autoregressive models, International Review of Financial Analysis, Volume 68, 101456, ISSN 1057-5219.</li><li>Kim, S., Shephard, N., and Chib, S., (1998), Stochastic Volatility: Likelihood Inference and Comparison with ARCH Models, The Review of Economic Studies, 65, issue 3, p. 361-393.</li><li>Kumar, M., (2010) A time-varying parameter vector autoregression model for forecasting emerging market exchange rates, International Journal of Economic Sciences and Applied Research, ISSN 1791-3373, Kavala Institute of Technology, Kavala, Vol. 3, Iss. 2, pp. 21-39</li><li>Nakajima, Jouchi, (2011), Time-Varying Parameter VAR Model with Stochastic Volatility: An Overview of Methodology and Empirical Applications, Monetary and Economic Studies, 29, issue, p. 107-142.</li><li>Primiceri, Giorgio, (2005), Time Varying Structural Vector Autoregressions and Monetary Policy, The Review of Economic Studies, 72, issue 3, p. 821-852.</li><li>Rodriguez, G., Castillo, P., Calero, R., Salcedo, R., Arellano, M. A., (2024), Evolution of the exchange rate pass-through into prices in Peru: An empirical application using TVP-VAR-SV models, Journal of International Money and Finance, Volume 142, 2024, 103023, ISSN 0261-5606.</li></ul><hr><p><strong>File in the download:</strong></p><ul><li>Trading strategy using the TVP-VAR-SV model in R - Python notebook</li></ul><!--kg-card-begin: html--><p style="text-align: center;"><a href="https://blog.quantinsti.com/tvp-var-stochastic-volatility" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: html--><hr><p><em>Disclaimer: All data and information provided in this article are for informational purposes only. QuantInsti</em><sup><em>®</em></sup><em> makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information in this article and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis.</em></p>]]></content:encoded></item><item><title><![CDATA[Fibonacci Retracement: Trading Strategy, Python implementation, and more]]></title><description><![CDATA[Get to know all about Fibonacci retracement trading strategy in Python. Master the art of identifying potential price reversal levels using Fibonacci ratios for informed trading decisions. This blog makes for a beginner-friendly guide with everything included from basics to advanced.]]></description><link>https://blog.quantinsti.com/fibonacci-retracement-trading-strategy-python/</link><guid isPermaLink="false">66289795c8fd9b0aacb930d2</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Ishan Shah]]></dc:creator><pubDate>Mon, 29 Apr 2024 10:38:00 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/ishan-shah-18393828">Ishan Shah</a></p><p>Fibonacci trading tools are used to determine support/resistance levels or to identify price targets. It is the presence of the Fibonacci series in nature which attracted technical analysts’ attention to use Fibonacci for trading. Fibonacci numbers may work like magic in some cases, in finding key levels in any widely traded security. Fibonacci's retracement strategy relies on key retracement levels to predict future price movements. </p><p>In this guide, we delve into Fibonacci retracement levels and their implementation using Python, enabling traders to leverage these mathematical principles for informed decision-making. </p><p>By combining technical analysis with programming capabilities, traders gain a deeper understanding of market dynamics and enhance their ability to execute trades with maximum returns. So let us dive in and unlock the potential of the Fibonacci Retracement Trading Strategy in Python for navigating volatile financial markets.</p><p>Moving ahead, let us find out more with this blog that covers:</p><!--kg-card-begin: html--><ul>
  <li><a href="#what-is-the-fibonacci-sequence">What is the Fibonacci sequence?</a></li>
  <li><a href="#what-is-the-fibonacci-retracement-strategy">What is the Fibonacci retracement strategy?</a></li>
  <li><a href="#how-to-use-fibonacci-retracement-in-trading">How to use Fibonacci retracement in trading?</a></li>
  <li><a href="#calculating-fibonacci-retracement-levels-using-python">Calculating Fibonacci retracement levels using Python</a></li>
  <li><a href="#best-practices-for-optimising-fibonacci-trading-strategy-in-python">Best practices for optimising Fibonacci trading strategy in Python</a></li>
  <li><a href="#overcoming-challenges-faced-while-using-fibonacci-trading-strategy">Overcoming challenges faced while using Fibonacci trading strategy</a></li>
</ul>
<!--kg-card-end: html--><hr><h2 id="what-is-the-fibonacci-sequence">What is the Fibonacci sequence?</h2><p>The Fibonacci retracement strategy involves the use of the Fibonacci sequence. So, let us first of all learn about the Fibonacci sequence.</p><p>The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence usually is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.</p><p>The sum is in the following order:</p><figure class="kg-card kg-image-card"><img src="https://lh7-us.googleusercontent.com/AI3b3Rv_ck4BP_uQI3lcTZSML198yq8M6oAgEzqP4IbtvNN61rTiNoyxm6eg4en7CEnJzagR0jXN-HeC0SGrKM72zgmRqsTb6driGtT1jGzaNIO3SwqsM0909qTNZZGO8ZZf1_BG-bT42x-YoG-O1WU" class="kg-image"></figure><p>In mathematical terms, the Fibonacci sequence can be defined recursively by the formula:</p><p><strong>X(n) = X(n-1) + X(n-2)</strong></p><p>Where:</p><ul><li>X(n) is the nth number in the sequence</li><li>X(n-1) is the (n-1)th number in the sequence</li><li>X(n-2) is the (n-2)th number in the sequence</li></ul><p>In finance and trading, the Fibonacci sequence is widely used in technical analysis to identify potential support and resistance levels and is an essential part of the Fibonacci retracement strategy.</p><p>Moreover, there are some interesting properties of the Fibonacci sequence. </p><ol><li>Divide any number in the sequence by the previous number; the ratio is always approximately 1.618.</li></ol><p>Xn/Xn-1 = 1.618</p><p>55/34 = 1.618</p><p>89/55 = 1.618</p><p>144/89 = 1.618</p><p>1.618 is known as the <strong>golden ratio</strong>. I suggest searching for the golden ratio examples on the Google images and you will be pleasantly astonished by the relevance of the ratio in nature.</p><p>2. Similarly, divide any number in the sequence by the next number; the ratio is always approximately 0.618.</p><p>Xn/Xn+1 = 0.618</p><p>34/55 = 0.618</p><p>55/89 = 0.618</p><p>89/144 = 0.618</p><p>3. 0.618 expressed in percentage is 61.8%. The square root of 0.618 is 0.786 (78.6%).</p><p>Similar consistency is found when any number in the sequence is divided by a number two places right to it.</p><p>Xn/Xn+2 = 0.382</p><p>13/34 = 0.382</p><p>21/55 = 0.382</p><p>34/89 = 0.382</p><p>0.382 expressed in percentage is 38.2%</p><p>4. Also, there is consistency when any number in the sequence is divided by a number three places right to it.</p><p>Xn/Xn+3 = 0.236</p><p>21/89 = 0.236</p><p>34/144 = 0.236</p><p>55/233 = 0.236</p><p>0.236 expressed in percentage terms is 23.6%.</p><p>5. The ratios 23.6%, 38.2%, 61.8%, and 78.6% are known as the Fibonacci ratios.</p><p>Now we can move to learning about Fibonacci retracement strategy.</p><hr><h2 id="what-is-the-fibonacci-retracement-strategy">What is the Fibonacci retracement strategy?</h2><p>The Fibonacci retracement strategy is a popular technical analysis tool to identify potential reversal levels in financial markets and is used by traders. Based on the Fibonacci sequence, this strategy involves plotting key retracement levels. The typical or default levels are 23.6%, 38.2%, 50%, 61.8%, and 78.6%, against a price movement.</p><p>These levels are derived from ratios found in the Fibonacci sequence, believed to represent areas of support or resistance.</p><p>Fibonacci retracement levels help traders to identify the entry and exit points for trades. Hence, the determination of the stop-loss and take-profit levels is done. When the price of an asset retraces to one of these Fibonacci levels, it may indicate a potential reversal in the prevailing trend.</p><p>The Fibonacci ratios, 23.6%, 38.2%, and 61.8%, can be applied for <a href="https://blog.quantinsti.com/starting-time-series/">time series analysis</a> to find support levels. Whenever the price moves substantially upwards or downwards, it tends to retrace back before it continues moving in the original direction.</p><p>For example, if the stock price has moved from $200 to $250, it is likely to retrace to $230 before it continues to move upward. The retracement level of $230 is forecasted using the Fibonacci ratios.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://lh7-us.googleusercontent.com/r3GByXj9mwEkGhO9sEm1hL5E5E67axSFxGZlk8mKRpzdpXpt1Uj_mvy14KfsR1zIcdZzTC4ckAoD4gASitEHJq5GMAYfY43rpys20Fnx4pqamG3-wZs-TIvGh8NjCWMqjmkWXX2WdNv-H9IjwSZaNLo" class="kg-image" alt="Fibonacci retracement example"></figure><p>We can arrive at $230 by using simple maths.</p><ul><li>Total up move = $250 - $200 = $50 38.2% of up move = 38.2% * 50 = $19.1</li><li>Retracement forecast = $250 - $19.1 = $230.9</li></ul><p>Any price below $230 provides a good opportunity for the traders to enter into new positions in the direction of the trend. Likewise, we can calculate for 23.6%, 61.8% and the other Fibonacci ratios.</p><p>The Fibonacci retracement strategy is commonly applied alongside other technical indicators and analysis techniques to confirm signals and enhance trading decisions. Additionally, it can be used across various financial instruments and timeframes, making it a versatile tool for traders across different markets.</p><p>Let us now find out how to use Fibonacci retracement in trading.</p><hr><h2 id="how-to-use-fibonacci-retracement-in-trading">How to use Fibonacci retracement in trading?</h2><p>The retracement levels can be used to buy a particular stock but you have not been able to because of a sharp run-up in the stock price.</p><p>In such a situation, it is recommended to wait for the price to correct to Fibonacci retracement levels such as 23.6%, 38.2%, and 61.8% and then buy the stock. The ratios 38.2% and 61.8% are the most important support levels.</p><p>This Fibonacci retracement trading strategy is more effective over a longer time interval and like any indicator, using the strategy with other <a href="https://blog.quantinsti.com/build-technical-indicators-in-python/">technical indicators</a> such as <a href="https://blog.quantinsti.com/rsi-indicator/">RSI</a>, <a href="https://blog.quantinsti.com/strategy-using-trend-following-indicators-macd-st-adx/">MACD</a>, and <a href="https://blog.quantinsti.com/candlestick-patterns-meaning/">candlestick patterns</a> can improve the probability of success.</p><p>Now, we will head to calculating Fibonacci retracement levels using Python.</p><hr><h2 id="calculating-fibonacci-retracement-levels-using-python">Calculating Fibonacci retracement levels using Python</h2><p>As we now know, retracements are the price movements that go against the original trend. To forecast the Fibonacci retracement level we should first identify the total up move or total down move. To mark the move, we need to pick the most recent high and low on the chart.</p><p>Let’s take an example of Exxon Mobil to understand the Fibonacci retracement construction.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/26b1911d5ff97f548e82080afcaf6b4d.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/04/Exxon-price.png" class="kg-image" alt="Fibonacci retracement price data"></figure><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/1e889831a7a1d484a733b27da1675691.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Minimum Price: 31.56999969482422
Maximum Price: 121.37000274658203</pre><!--kg-card-end: html--><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/44678483cee9a1431eb74f7254e56963.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Level	Price
0	 121.37000274658203
0.236	 100.17720202636718
0.382	 87.06640158081055
0.618	 65.8736008605957
1	 31.56999969482422 </pre><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/04/Retracement-levels.png" class="kg-image" alt="Fibonacci retracement levels"></figure><p>It is visible that the maximum price is 121.37 where the level is 0 since there is no retracement at the maximum price.</p><p>The first retracement level is at 23.6% is $100.17, the second retracement level is at 38.2% is $87.06, and the next retracement level is at 61.8% is $65.87.</p><hr><h2 id="best-practices-for-optimising-fibonacci-trading-strategy-in-python">Best practices for optimising Fibonacci trading strategy in Python</h2><p>When you implement Python for the Fibonacci trading strategy, there are chances that optimisation will be required to improve the strategy performance.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/04/Best-practices-for-optimising-Fibonacci-trading-strategy-in-Python.png" class="kg-image" alt="Best practices for Fibonacci retracement strategy"></figure><p>Consider the following tips and best practices for the same:</p><ul><li><strong>Define clear trading rules:</strong> Establish clear rules for identifying Fibonacci retracement levels and trade setups. This helps to remove subjectivity and emotion from the decision-making process.</li><li><strong>Backtest the strategy: </strong>Use historical market data to backtest the Fibonacci strategy across various market conditions. This helps validate the effectiveness of the strategy and identify its strengths and weaknesses.</li><li><strong>Optimise parameters:</strong> Fine-tune the parameters of the Fibonacci strategy, such as the anchor points for drawing retracement levels or the threshold for confirming trade signals. Optimisation can be done using techniques like grid search.</li><li><strong>Incorporate risk management:</strong> Implement robust risk management techniques to protect capital and minimise losses. This may include setting stop-loss orders, position sizing based on risk tolerance, and diversifying across multiple assets or instruments.</li><li><strong>Combine with other indicators: </strong>Enhance the Fibonacci strategy by integrating it with other technical indicators or chart patterns. This can help confirm trade signals and increase the probability of successful trades.</li><li><strong>Continuously monitor and adapt:</strong> Regularly monitor the performance of the Fibonacci strategy and make adjustments as needed based on evolving market conditions. This may involve refining the strategy parameters, adding new filters, or incorporating feedback from live trading experiences.</li></ul><p>By following these tips and best practices, traders can optimise their Fibonacci trading strategy in Python and improve their overall trading performance.</p><p>Moving to the next section, we will find out how to overcome the challenges faced while using the Fibonacci trading strategy.</p><hr><h2 id="overcoming-challenges-faced-while-using-fibonacci-trading-strategy">Overcoming challenges faced while using Fibonacci trading strategy<br></h2><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p><strong>Challenges with the Fibonacci Trading Strategy</strong></p>
</td>
<td>
<p><strong>Ways to Overcome the Challenges</strong></p>
</td>
</tr>
<tr>
<td>
<p>Subjectivity: Identifying the correct swing highs and lows to anchor Fibonacci retracement levels can be subjective and may vary among traders.</p>
</td>
<td>
<p>Use Objective Criteria: Define clear criteria for identifying swing highs and lows, such as significant price peaks and troughs, or use automated tools to detect these points. Additionally, consider using multiple timeframes to confirm key levels.</p>
</td>
</tr>
<tr>
<td>
<p>Overfitting: There is a risk of overfitting the Fibonacci levels to historical data, leading to poor performance in real-time trading.</p>
</td>
<td>
<p>Validate with Backtesting: Test the Fibonacci strategy on historical data across different market conditions to ensure robustness. Avoid over-optimising the strategy based on specific past events. Incorporate risk management rules to limit potential losses.</p>
</td>
</tr>
<tr>
<td>
<p>False Signals: Fibonacci retracement levels may sometimes generate false signals, resulting in poor trade execution and losses.</p>
</td>
<td>
<p>Combine with Other Indicators: Use Fibonacci levels in conjunction with other technical indicators, such as moving averages, trendlines, or candlestick patterns, to confirm trade setups. This can help filter out false signals and improve the reliability of the strategy.</p>
</td>
</tr>
<tr>
<td>
<p>Emotional Bias: Traders may become emotionally attached to Fibonacci levels, leading to biased decision-making and reluctance to adapt to changing market conditions.</p>
</td>
<td>
<p>Stay Disciplined: Stick to predefined trading rules and objectives, regardless of emotional impulses or attachment to Fibonacci levels. Regularly review and adjust the strategy based on objective performance metrics and market feedback.</p>
</td>
</tr>
<tr>
<td>
<p>Market Noise: In choppy or volatile market conditions, Fibonacci levels may not accurately capture price movements, resulting in increased noise and false signals.</p>
</td>
<td>
<p>Adjust Parameters: Consider adjusting the sensitivity of Fibonacci levels by modifying the anchor points or using alternative Fibonacci tools, such as Fibonacci extensions or clusters, to better align with prevailing market dynamics. Additionally, apply filters to smooth out noise and focus on high-probability trade setups.</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><hr><h3 id="conclusion">Conclusion</h3><p>The Fibonacci retracement trading strategy in Python offers traders a systematic approach to navigating volatile financial markets and enables them to unlock the potential for maximum returns.</p><p>Mastering the Fibonacci retracement trading strategy in Python equips traders with a powerful tool for identifying potential price reversal levels and making informed trading decisions. By leveraging the Fibonacci sequence and ratios, traders can pinpoint key support and resistance levels, allowing for precise entry and exit points in the market. Through the implementation of Python programming, traders gain the ability to calculate and visualise Fibonacci retracement levels accurately, enhancing their technical analysis capabilities.</p><p>If you wish to learn more about the Fibonacci retracement strategy, check out the course on <a href="https://quantra.quantinsti.com/course/price-action-trading-strategies">price action trading strategies</a>. This course will help you learn the strategies and codes that help you to tweak, fine-tune and implement this strategy in the live markets. Learn how to spot and trade the most important trading patterns: double tops/double bottoms, triple tops/triple bottoms, head and shoulders. Get acquainted with several trading strategies, and price action tools such as pivot points and the Fibonacci Retracement levels via a practical approach. Enroll now!</p><hr><p><strong>File in the download</strong></p><ul><li>Fibonacci retracement strategy - Python notebook</li></ul><!--kg-card-begin: html--><p class="custom-download-link"><a href="https://blog.quantinsti.com/fibonacci-retracement-trading-strategy-python" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: html--><hr><!--kg-card-begin: html--><p><em><small>Note: The original post has been revamped on 29<sup>th</sup> April 2024 for recentness, and accuracy.</small></em></p><!--kg-card-end: html--><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Standard Deviation in Trading: Calculations, Use Cases, Examples and more]]></title><description><![CDATA[Learn about standard deviation in trading: its calculations, use cases, examples, and more. Enhance your trading strategies by learning to use this statistical measure for assessing risk and volatility in financial markets.]]></description><link>https://blog.quantinsti.com/standard-deviation/</link><guid isPermaLink="false">65df3c3c7d529126d0749ef9</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Chainika Thakar]]></dc:creator><pubDate>Thu, 07 Mar 2024 05:51:58 GMT</pubDate><content:encoded><![CDATA[<p>Whether you're a seasoned trader or just starting in quantitative finance, grasping the concept of standard deviation is crucial. Standard deviation helps traders with volatility measures in finance. With this helpful tool, traders can make sense of market fluctuations and manage risks effectively. </p><p>In this blog, we break down the idea of standard deviation by imparting all the necessary information related to standard deviation in the trading domain. Let's dive into the exciting journey of understanding standard deviation’s role in trading as we cover:</p><!--kg-card-begin: html--><ul>
<li><a href="#what-is-standard-deviation">What is standard deviation?</a></li>
<li><a href="#formula-of-standard-deviation">Formula of standard deviation</a></li>
<li><a href="#how-to-calculate-standard-deviation">How to calculate standard deviation?</a></li>
<li><a href="#examples-of-applications-of-standard-deviation">Examples of applications of standard deviation</a></li>
<li><a href="#use-cases-of-standard-deviation">Use cases of standard deviation</a>
<ul>
<li><a href="#risk-assessment">Risk assessment</a></li>
<li><a href="#volatility-analysis">Volatility analysis</a></li>
<li><a href="#portfolio-management">Portfolio management</a></li>
</ul>
</li>
<li><a href="#essential-components-of-standard-deviation">Essential components of standard deviation</a>
<ul>
<li><a href="#unit-of-standard-deviation">Unit of standard deviation</a></li>
<li><a href="#standard-deviation-vs-variance">Standard deviation vs variance</a></li>
<li><a href="#standard-deviation-for-sample-data-bessels-correction">Standard deviation for sample data - Bessel&rsquo;s correction</a></li>
</ul>
</li>
<li><a href="#standard-deviation-in-trading-as-a-measure-of-volatility">Standard deviation in trading as a measure of volatility</a></li>
<li><a href="#computing-annualized-volatility-of-stocks-using-python">Computing annualized volatility of stocks using Python</a>
<ul>
<li><a href="#the-z-score">The z-score</a></li>
<li><a href="#value-at-risk">Value at Risk</a></li>
<li><a href="#confidence-intervals">Confidence intervals</a></li>
</ul>
</li>
<li><a href="#real-world-case-studies-of-standard-deviation">Real-world Case Studies of standard deviation</a>
<ul>
<li><a href="#application-in-different-markets">Application in Different Markets</a></li>
<li><a href="#impact-on-trading-decisions">Impact on Trading Decisions</a></li>
</ul>
</li>
<li><a href="#correlation-of-standard-deviation-with-other-indicators">Correlation of standard deviation with other indicators</a></li>
<li><a href="#limitations-of-standard-deviation-in-trading">Limitations of standard deviation in trading</a></li>
<li><a href="#common-misconceptions-about-standard-deviation-in-trading">Common misconceptions about standard deviation in trading</a></li>
<li><a href="#risk-management-tips-using-standard-deviation">Risk management tips using standard deviation</a></li>
</ul><!--kg-card-end: html--><hr><h2 id="what-is-standard-deviation">What is standard deviation?</h2><p>Let us see a famous quote defining standard deviation by John Bollinger, a well-known figure in the trading world, primarily recognised for developing the widely-used technical analysis tool known as <a href="https://blog.quantinsti.com/bollinger-bands/">Bollinger Bands</a>.</p><!--kg-card-begin: html-->"Standard deviation is a key tool for traders to quantify the uncertainty and risk in the market. It allows us to better understand the potential variability of returns and make informed decisions to manage our portfolios effectively." 
- John Bollinger<!--kg-card-end: html--><p><strong>Definition of standard deviation</strong></p><!--kg-card-begin: html-->“The standard deviation (σ) is a measure that is used to quantify the amount of variation or dispersion of data from its mean.”<!--kg-card-end: html--><p>Let's simplify the concept of deviation from the mean.</p><p>In essence, deviation refers to how far a data point is from the average. Imagine we have a set of observations represented by the variable X, consisting of various values: x₁, x₂, ..., xn.</p><p>Now, let's consider two of these observations (as shown in the image below), x₁ and x₂, and their deviations from the mean of X.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/Standard-deviation-1.png" class="kg-image" alt="Standard deviation meaning"></figure><p>Deviations are straightforward: they tell us if an observation is above or below the mean, shown by positive or negative values respectively.</p><p><strong>What if we add up all these deviations?</strong></p><p>Interestingly, they would balance out to zero due to the mix of positive and negative values. To overcome this, we square each difference to remove the sign and find their average. This yields the variance, indicating how spread out the data is.</p><p>Standard deviation, derived from the variance, provides a standardised measure of dispersion. It involves taking the positive square root of the variance. This process ensures we're dealing with values in the same units as the original data. In the following section, we'll delve into the formula for calculating standard deviation.⁽<a href="https://www.kotaksecurities.com/investing-guide/articles/heres-how-to-read-and-use-the-standard-deviation-indicator-in-trading/">¹</a>⁾</p><hr><h2 id="formula-of-standard-deviation">Formula of standard deviation</h2><p>The formula for calculating the standard deviation (denoted by σ) is as follows:</p><p>$$σ = \sqrt\sum(x_i-μ)^2/n)$$</p><p>$$\text{Where,}\\<br>σ\;\text{is the standard deviation}\\<br>x_i\;\text{represents each individual data point}\\<br>μ\;\text{is the mean of the data set}\\<br>Σ\;\text{denotes the sum of all the values}\\<br>n\;\text{is the total number of data points}$$</p><p>Going forward, we will discuss the calculation of standard deviation.</p><hr><h2 id="how-to-calculate-standard-deviation">How to calculate standard deviation?</h2><p>To calculate the standard deviation using Python, you can utilise libraries such as pandas and numpy. Here's a step-by-step guide to calculate the standard deviation using historical price data:</p><h3 id="step-1-install-required-libraries-and-import-packages">Step 1: Install Required Libraries and import packages</h3><p>If you haven't already installed numpy, you can install it using pip:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/1f74fcef34acf66f7d11b2cc25197793.js"></script><!--kg-card-end: html--><h3 id="step-2-define-an-example-data">Step 2: Define an example data</h3><p>Here we have taken an array of numbers to show the calculation.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/35b51af2342271521c77b405085ffe4c.js"></script><!--kg-card-end: html--><h3 id="step-3-compute-standard-deviation">Step 3: Compute Standard Deviation</h3><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/da591c1a32cda8b5a62eab91f75fd4cd.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Standard Deviation of Data: 7.0710678118654755</pre><!--kg-card-end: html--><p>We will now discuss some examples of the applications of standard deviation in general as well as in trading.</p><hr><h2 id="examples-of-applications-of-standard-deviation">Examples of applications of standard deviation</h2><p>Let us check out the general examples of applying standard deviation before heading to the trade oriented example.</p><h3 id="general-examples">General examples</h3><p>The term standard deviation sounds like something you hear in a statistics class, but don’t dismiss it as an overly technical term just yet. It can be used in different aspects of our lives.</p><p>A teacher can use the standard deviation of marks of her students in an exam as a metric to assess the overall level of understanding of the subject. If the mean and standard deviation are both high, it indicates that, on average, students have a good understanding of the subject.</p><p>However, there would be many students who have scores that are much above and much below the average scores. In case the mean is high and the standard deviation is low, it indicates that the average scores are similar to the previous case.</p><p>The low standard deviation tells her that most students have scores that are close (i.e. slightly above and slightly below) to the mean. In weather forecasting, it can be used to compare the weather patterns in two or more regions.</p><p>If we compare the standard deviation of temperatures in Jaisalmer (which has extreme weather) with Mumbai (which has moderate weather), we would find that the former has more variability in temperature around the mean.</p><h3 id="examples-of-application-in-trading">Examples of application in trading</h3><p><strong>Example: Amazon (AMZN) Stock</strong></p><ul><li><a href="https://quantra.quantinsti.com/course/volatility-trading-strategies"><strong>Volatility Analysis</strong></a><strong>:</strong> Traders analysing Amazon's stock may calculate the standard deviation of its daily returns over a specific period, such as the past year. A higher standard deviation indicates greater price volatility, implying larger price swings.<br>For instance, if Amazon's stock has a daily standard deviation of 2% over the past year, it suggests that, on average, the daily price movements deviate by 2% from the mean daily return.<br></li><li><a href="https://quantra.quantinsti.com/course/options-trading-strategies-python-basic"><strong>Options Trading</strong></a><strong>:</strong> Standard deviation is a crucial factor in <a href="https://quantra.quantinsti.com/course/options-trading-strategies-python-intermediate">options</a> pricing models like the Black-Scholes model. Traders estimating the implied volatility of Amazon's options contracts may use historical standard deviation as a reference point.<br>For instance, if the historical standard deviation of Amazon's stock is 20% and the implied volatility of its <a href="https://quantra.quantinsti.com/course/options-trading-strategies-python-advanced">options</a> is significantly higher, it might suggest that options are relatively expensive, potentially presenting trading opportunities.<br>To build on your understanding of implied volatility and options pricing, consider exploring <a href="https://quantra.quantinsti.com/course/options-volatility-trading">trading volatility options</a> course, where you’ll gain practical experience in strategies and techniques for analyzing and capitalizing on market fluctuations.<br></li><li><a href="https://blog.quantinsti.com/tag/portfolio-risk-management/"><strong>Risk Management</strong></a><strong>:</strong> Investors holding Amazon's stock in their portfolio may use standard deviation to assess and manage risk. By calculating the standard deviation of Amazon's daily returns, investors can estimate the potential range of price movements and set stop-loss orders or position sizes accordingly.<br>For instance, if an investor is comfortable with a certain level of risk, they may adjust their position size based on Amazon's historical standard deviation to align with their risk tolerance.</li></ul><hr><h2 id="use-cases-of-standard-deviation">Use cases of standard deviation</h2><p>Here are the use cases of standard deviation in risk assessment, volatility analysis, and portfolio management:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/Use-cases.png" class="kg-image" alt="Use cases of standard deviation"></figure><h3 id="risk-assessment">Risk Assessment</h3><ul><li><strong>Credit Risk Evaluation: </strong>In financial institutions, standard deviation is used to assess the variability of returns on loans or investments. A higher standard deviation indicates higher volatility, implying greater risk. Lenders may use standard deviation to evaluate the creditworthiness of borrowers and determine appropriate interest rates.</li><li><strong>Market Risk Management: </strong>Standard deviation helps quantify market risk by measuring the variability of asset prices or portfolio returns. Traders and investors use standard deviation to assess the potential downside risk of their investments and implement risk mitigation strategies accordingly.</li></ul><h3 id="volatility-analysis">Volatility Analysis</h3><ul><li><strong>Options Pricing: </strong>Standard deviation is a key input in options pricing models like the Black-Scholes model. A higher standard deviation implies higher implied volatility, leading to higher option premiums. Traders use standard deviation to estimate the future volatility of underlying assets and determine the fair value of options contracts.</li><li><strong>Technical Analysis: </strong>Standard deviation is used to calculate volatility indicators such as Bollinger Bands. These bands consist of a moving average and upper and lower bands representing standard deviations from the mean. Traders use Bollinger Bands to identify potential buy or sell signals based on volatility levels.</li></ul><h3 id="portfolio-management">Portfolio Management</h3><ul><li><strong>Diversification: </strong>Standard deviation is used to measure the risk of individual assets and portfolios. By diversifying investments across assets with low or negatively correlated returns, investors can reduce portfolio risk. Standard deviation helps investors assess the effectiveness of diversification strategies and optimise asset allocation to achieve desired risk-return profiles.</li><li><strong>Risk-adjusted Performance: </strong>Standard deviation is used to calculate risk-adjusted performance measures such as the Sharpe ratio and the Sortino ratio. These ratios quantify the excess return generated per unit of risk (measured by standard deviation). Portfolio managers use these metrics to evaluate investment strategies and compare the risk-adjusted returns of different portfolios.⁽²⁾</li></ul><p>Let us now head to the essential components concerning standard deviation that are used in the calculation part.</p><hr><h2 id="essential-components-of-standard-deviation">Essential components of standard deviation</h2><p>Let us now see the essential components that are required for calculating standard deviation in the trading domain.</p><p>These are:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/Essential-components.png" class="kg-image" alt="Essential components of standard deviation"></figure><h3 id="unit-of-standard-deviation">Unit of standard deviation</h3><p>The unit of standard deviation would be the same as the unit of our data. This makes it easier to interpret compared to the variance. In the next section, we do a detailed comparison between these two measures of dispersion.</p><h3 id="standard-deviation-vs-variance">Standard deviation vs Variance</h3><p>$$The\;variance(σ ^2)\;of\;a\;random\;variable\;X\;is\;given\;by\;the\;formula\;below:\\Variance=\frac{\sum_{i=1}^N(x_i-μ)^2}{N}$$</p><p>As we can see, by its very construction, the variance is in the square of the original unit. This means that if we are dealing with distances in kilometres, the unit of variance would be in square kilometres.</p><p>Now, square kilometres may be easy to visualise as a unit, but what about year2 or IQ2, if we are working with ages or IQs of a group? They are harder to interpret. Hence, it makes sense to use a measure that can be comparable to the data on the same scale/units, like the standard deviation.</p><p>Standard deviation is calculated as the square root of variance. It has the same unit as our data and this makes it easy to use and interpret. For example, consider a scenario where we are looking at a dataset of the heights of residents of a neighbourhood. Assume that the heights are normally distributed with a mean of 165 cm and a standard deviation of 5 cm.</p><p>We know that for a <a href="https://quantra.quantinsti.com/glossary/Standard-Normal-Distribution">normal distribution</a>,</p><ul><li>68% of the data points fall within one standard deviation,</li><li>95% within two standard deviations, and</li><li>99.7% fall within three standard deviations from the mean.</li></ul><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/standard-nominal-distribution.png" class="kg-image" alt="Standard normal distribution"></figure><p>Thus, we can conclude that the height of almost 68% of the residents would lie between one standard deviation from the mean, i.e., between 160 cm (mean – sd) and 170 cm (mean + sd).<a href="https://www.geeksforgeeks.org/difference-between-variance-and-standard-deviation/">⁽³⁾</a></p><hr><h3 id="standard-deviation-for-sample-data-bessel-s-correction">Standard deviation for sample data - Bessel's correction</h3><p>When calculating the standard deviation of a population, we use the formula discussed above. However, we modify it slightly when dealing with a sample instead.</p><p>This is because the sample is much smaller compared to the entire population. To account for differences in a randomly selected sample and the entire population, we ‘unbias’ the calculation by using '(n-1)' instead of 'n' in the denominator of equation 1. This is referred to as Bessel's correction.<a href="https://www.uio.no/studier/emner/matnat/math/MAT4010/data/forelesningsnotater/bessel-s-correction---wikipedia.pdf">⁽⁴⁾</a></p><p>Thus, we use the following formula to calculate the sample standard deviation (s).</p><p>$$s= \sqrt\frac{\sum_{i=1}^n (x_i-\bar x)^2}{n-1}$$</p><p>$$\text{Where,}\\<br>x_i = \text{value of the } i\text{th point in the sample}\\<br>\bar{x} = \text{sample mean}\\<br>n = \text{total number of data points in the sample}\\<br>\text{Do note that as the sample size } n \text{ gets larger, the impact of dividing by } (n - 1) \text{ or } n \text{ will become lesser.}$$</p><p>Now, we can discuss the standard deviation in trading as a measure of the volatility.</p><hr><h2 id="standard-deviation-in-trading-as-a-measure-of-volatility">Standard deviation in trading as a measure of volatility</h2><p>In trading and finance, it is important to quantify the volatility of an asset. An asset’s volatility, unlike its return or price, is an unobserved variable.</p><p>Standard deviation has a special significance in risk management and performance analysis as it is often used as a proxy for the volatility of a security. For example, the well-established blue-chip securities have a lower standard deviation in their returns compared to that of small-cap stocks.</p><p>On the other hand, assets like cryptocurrency have a higher standard deviation, as their returns vary widely from their mean. To explore trading approaches for such assets, consider an intermediate <a href="https://quantra.quantinsti.com/course/crypto-trading-strategies-intermediate">crypto trading course</a>.</p><p>Moving forward, let us discuss the computation of the annualised volatility of stocks using Python.</p><hr><h2 id="computing-annualised-volatility-of-stocks-using-python">Computing annualised volatility of stocks using Python</h2><p>Let us now compute and compare the annualized volatility for two Indian stocks namely, ITC and Reliance. We begin with fetching the end of day close price data using the yfinance library for a period of the last 5 years:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/51b44057ea9d4a8e150f4a671653447b.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Date           Adj Close
2021-10-19     245.949997
2021-10-20     246.600006
2021-10-21     244.699997
2021-10-22     236.600006
2021-10-25     234.350006</pre><!--kg-card-end: html--><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/8d46c32b06156292169503a1e3d08838.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Date          Adj Close
2021-10-19   2731.850098
2021-10-20   2700.399902
2021-10-21   2622.500000
2021-10-22   2627.399902
2021-10-25   2607.300049</pre><!--kg-card-end: html--><p>Below, we calculate the daily returns using the <em>pct_change()</em> method and the standard deviation of those returns using the <em>std()</em> method to get the daily volatilities of the two stocks:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/343280687eda287260816ad36da59fc3.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Date         Adj Close   Returns
2016-10-25   511.991608       NaN
2016-10-26   508.709717 -0.006410
2016-10-27   506.127686 -0.005076
2016-10-28   509.144104  0.005960
2016-11-01   507.237701 -0.003744
...                 ...       ...
2021-10-19  2731.850098  0.008956
2021-10-20  2700.399902 -0.011512
2021-10-21  2622.500000 -0.028848
2021-10-22  2627.399902  0.001868
2021-10-25  2607.300049 -0.007650</pre><!--kg-card-end: html--><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/ab1af16fa12be5f21bc86ec4b47bb4d1.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Date            Adj Close	 Returns
2016-10-26	508.709717	-0.006410
2016-10-27	506.127686	-0.005076
2016-10-28	509.144104	 0.005960
2016-11-01	507.237701	-0.003744
2016-11-02	494.086243	-0.025928</pre><!--kg-card-end: html--><p>In general, the volatility of assets is quoted in annual terms. So below, we convert the daily volatilities to annual volatilities by multiplying with the square root of 252 (the number of trading days in a year):</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/4567b231e8f4a37560056501ae5e8022.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>The annualized standard deviation of the ITC stock daily returns is: 27.39%
The annualized standard deviation of the Reliance stock daily returns is: 31.07%</pre><!--kg-card-end: html--><p>Now we will compute the standard deviation with Bessel's correction. To do this, we provide a ddof parameter to the Numpy std function. Here, <em>ddof</em> means 'Delta Degrees of Freedom'.</p><p>By default, Numpy uses <em>ddof=0</em> for calculating standard deviation- this is the standard deviation of the population. For calculating the standard deviation of a sample, we give <em>ddof=1</em>, so that in the formula, (n−1) is used as the divisor. Below, we do the same:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/51eadcf7196f05b5b399ddc03788243b.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>The annualized standard deviation of the ITC stock daily returns with Bessel's correction is: 27.39%

The annualized standard deviation of the Reliance stock daily returns with Bessel's correction is: 31.07%</pre><!--kg-card-end: html--><p>Thus, we can observe that, as the sample size is very large, Bessel's correction does not have much impact on the obtained values of standard deviation. In addition, based on the given data, we can say that the Reliance stock is more volatile compared to the ITC stock.</p><p><em><strong>Note:</strong> The purpose of this illustration is to show how standard deviation is used in the context of the financial <a href="https://quantra.quantinsti.com/course/getting-market-data">markets</a>, in a highly simplified manner. There are factors such as rolling statistics (outside the scope of this write-up) that should be explored when using these concepts in strategy implementation.</em></p><h3 id="the-z-score">The z-score</h3><p>Z-score is a metric that tells us how many standard deviations away a particular data point is from the mean. It can be negative or positive. A positive z-score, like 1, indicates that the data point lies one standard deviation above the mean and a negative z-score, like -2, implies that the data point lies two standard deviations below the mean.</p><p>In financial terms, when calculating the z-score on the returns of an asset, a higher value of z-score (either positive or negative) means that the return of the security differs significantly from its mean value. So, the z-score tells us how well the data point conforms to the norm.</p><p>Usually, if the absolute value of a z score of a data point is very high (say, more than 3), it indicates that the data point is quite different from the other data points. We use standard deviation to calculate the z-score using the following formula in case we have sample data:</p><p>$$z=\frac{x_i-\bar x}{s}$$</p><p>$$Where,\\ x_i = a\; single\; data\; point \\ \bar x = the\; sample\; mean\\ s = the\; sample\; standard\; deviation$$</p><p>Below we calculate and plot the z-scores for the ITC stock returns using the above formula in Python:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/facddad80796e6827a31dad9dcce2f1d.js"></script><!--kg-card-end: html--><p>Output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/zscores_plot.png" class="kg-image" alt="Z-scores"></figure><p>From the above figure, we observe that around March of 2020, the ITC stock returns had a z-score reaching below -3 several times, indicating that the returns were more than 3 standard deviations below the mean for the given data sample. As we know this was during the sell-off triggered by the COVID pandemic.</p><p>In addition, a standardised measure like the z-score is used widely to generate signals for mean-reverting trading strategies such as <a href="https://blog.quantinsti.com/pairs-trading-basics/#z-score">pairs trading</a>.</p><p>Also, one can use the z score function from the <em>scipy.stats</em> module to calculate the z-scores as follows:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/facddad80796e6827a31dad9dcce2f1d.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>Date		 Adj Close	 Returns     Returns_zscore
2021-10-19	2731.850098	 0.008956	 0.380491
2021-10-20	2700.399902	-0.011512	-0.665617
2021-10-21	2622.500000	-0.028848	-1.551575
2021-10-22	2627.399902	 0.001868	 0.018247
2021-10-25	2607.300049	-0.007650	-0.468222</pre><!--kg-card-end: html--><h3 id="value-at-risk">Value at Risk</h3><p>Value at Risk (VaR) is an important financial risk management metric that quantifies the maximum loss that can be realized in a given time with a given level of confidence/probability for a given strategy, portfolio or trading desk.</p><p>It can be computed in three ways, one of which is the variance-covariance method. In this method, we assume that the returns are normally distributed for the lookback period. Understand how <a href="https://blog.quantinsti.com/calculating-value-at-risk-in-excel-python/">VaR calculation</a> can help enhance your skills in financial risk management.</p><p>The idea is simple. We calculate the z-score of the returns of the strategy based on the confidence level we want and then multiply it with the standard deviation to get the VaR. To get the VaR in dollar terms, we can multiply it with the investment in the strategy.</p><p>For example, if we want the 95% confidence VaR, we are essentially finding the cut-off point for the worst 5% of the losses from the returns distribution. If we assume that the stock returns are normally distributed, then their z-scores will have a standard normal distribution. So, the cut-off point for the worst 5% returns is -1.64:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/VaR.png" class="kg-image" alt="VaR"></figure><p>Thus the 1-year 95% VaR of a simple strategy of investing in the ITC stock is given by:</p><p>VaR = (−1.64) ∗ (s) ∗ investment</p><p>where, s is the annualized standard deviation of the ITC stocks.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/378d10e4ecc27233a78e5ebb531f56e0.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>z_score_cut_off
-1.6448536269514722
VaR = z_score_cut_off * annual_standard_deviation * initial_investment
VaR
-45045.34407051503</pre><!--kg-card-end: html--><p>Thus, we can say that the maximum loss that can be realised in 1 year with 95% confidence is INR 45045. Of course, this was calculated under the assumption that ITC stock returns follow a normal distribution.</p><h3 id="confidence-intervals">Confidence intervals</h3><p>Another common use case for standard deviation is in computing the confidence intervals. In general, when we work with data, we assume that the population from which the data has been generated follows a certain distribution and the population parameters for that distribution are not known. These population parameters have to be estimated using the sample.</p><p>For example, the mean daily return of the ITC stock is a population parameter, which we try to estimate using the sample mean. This gives us a point estimate. However, <a href="https://quantra.quantinsti.com/course/stock-market-basics">financial market</a> forecasts are probabilistic, and hence, it would make more sense to work with an interval estimate rather than a point estimate.</p><p>A confidence interval gives a probable estimated range within which the value of the population parameter may lie. Assuming the data to be normally distributed, we can use the empirical rule to describe the percentage of data that falls within 1, 2, and 3 standard deviations from the mean.</p><ol><li>About 68% of the values lie between -1 and +1 standard deviation from the mean.</li><li>About 95% of the values lie within two standard deviations from the mean.</li><li>About 99.7% of the values lie within three standard deviations from the mean.</li></ol><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/9950b1db8dd237d506e1f26ab97413be.js"></script><!--kg-card-end: html--><p>Output:</p><!--kg-card-begin: html--><pre>The 95% confidence interval of the ITC stock daily returns is: [-0.03,0.03]</pre><!--kg-card-end: html--><p>Thus, we can say with 95% confidence that the stock’s daily returns will lie in a range of  -3% and +3% (assuming the ITC stock returns are normally distributed).</p><p>Let us now discuss the real world case studies of standard deviation in the trading domain to make the concept clearer.</p><hr><h2 id="real-world-case-studies-of-standard-deviation">Real-world Case Studies of standard deviation</h2><p>Here are a couple of real-world case studies demonstrating the application of standard deviation in different markets and its impact on trading decisions:</p><h3 id="case-study-standard-deviation-in-forex-trading">Case Study: Standard Deviation in Forex Trading</h3><ul><li><strong>Application: </strong>Forex traders often use standard deviation to measure the volatility of currency pairs and assess the risk associated with their trading positions. For example, consider a trader who is analysing the EUR/USD currency pair. By calculating the standard deviation of the pair's daily returns over a specific period, the trader can gauge the level of price volatility.</li><li><strong>Impact on Trading Decisions: </strong>If the standard deviation of EUR/USD's daily returns is relatively high, it indicates greater price volatility and potentially higher risk. In such cases, the trader may adjust their position size or set wider stop-loss orders to account for the increased volatility. Conversely, if the standard deviation is low, the trader may opt for tighter risk management measures.</li></ul><h3 id="case-study-standard-deviation-in-stock-market-trading">Case Study: Standard Deviation in Stock Market Trading</h3><ul><li><strong>Application:</strong> <a href="https://quantra.quantinsti.com/course/stock-market-basics">Stock market</a> traders use standard deviation to assess the risk and volatility of individual stocks or entire portfolios. For instance, consider an investor analysing the standard deviation of Apple Inc. (AAPL) stock returns over the past year. By calculating the standard deviation, the investor can quantify the level of price variability in AAPL stock. Start building your understanding of the stock market with our free <a href="https://quantra.quantinsti.com/course/stock-market-basics">Stock Market Beginner Course</a>.</li><li><strong>Impact on Trading Decisions:</strong> If the standard deviation of AAPL's returns is high, it suggests that the stock experiences significant price fluctuations, indicating higher risk. In response, traders may adopt risk mitigation strategies such as diversification or hedging. Conversely, a low standard deviation implies lower volatility and may lead traders to adjust their trading strategies accordingly, potentially by pursuing more aggressive trading opportunities.</li></ul><p>Now that you are familiar with most of the standard deviation related concepts, in the next section you will see how correlation of standard deviation with other indicators can help.</p><hr><h2 id="correlation-of-standard-deviation-with-other-indicators">Correlation of standard deviation with other indicators</h2><p>The correlation of standard deviation with other indicators can provide valuable insights into market dynamics and help traders make informed decisions. Here are some common indicators with which standard deviation is often correlated:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/Correlation-of-standard-deviation.png" class="kg-image" alt="Correlation of standard deviation"></figure><ul><li><strong>Mean (Average): </strong>The mean and standard deviation are closely related. A higher standard deviation indicates greater variability of data points around the mean, while a lower standard deviation suggests less variability.</li><li><strong>Variance: </strong>Variance is the square of the standard deviation. As such, they are directly related. Higher variance implies a higher dispersion of data points from the mean, leading to a higher standard deviation.</li><li><strong>Volatility Measures: </strong>Standard deviation is a key component of volatility measures such as historical volatility and implied volatility. These measures assess the magnitude of price fluctuations in financial instruments. High standard deviation values indicate high volatility, while low values suggest low volatility.</li><li><strong>Bollinger Bands: </strong>Bollinger Bands consist of a moving average line and upper and lower bands, which are typically set at a certain number of standard deviations above and below the moving average. Changes in standard deviation affect the width of the bands, with wider bands indicating higher volatility and narrower bands suggesting lower volatility.</li><li><strong>Sharpe Ratio: </strong>The Sharpe ratio measures the risk-adjusted return of an investment. It is calculated by dividing the excess return (return above risk-free rate) by the standard deviation of returns. A higher standard deviation leads to a lower Sharpe ratio, indicating a higher risk for a given level of return.</li><li><strong>Sortino Ratio: </strong>Similar to the Sharpe ratio, the Sortino ratio measures risk-adjusted return but focuses only on downside risk, considering only the standard deviation of negative returns. A higher standard deviation of negative returns leads to a lower Sortino ratio, indicating higher downside risk.</li></ul><p>Let us now see some limitations of standard deviation in trading.</p><hr><h2 id="limitations-of-standard-deviation-in-trading">Limitations of standard deviation in trading</h2><p>While standard deviation is a widely used and valuable tool in trading, it does have several limitations that traders should be aware of:</p><ul><li><strong>Assumption of Normal Distribution: </strong>Standard deviation assumes that the data follows a normal distribution. However, financial markets often exhibit non-normal distributions, such as fat tails or skewness. In such cases, the standard deviation may not accurately capture the true risk and volatility of the market.</li><li><strong>Sensitivity to Outliers: </strong>Standard deviation is highly sensitive to outliers, or extreme values, in the data. A single outlier can significantly affect the standard deviation, leading to potentially misleading results. Traders should be cautious when interpreting standard deviation in the presence of outliers.</li><li><strong>Equal Weighting of Data Points:</strong> Standard deviation treats all data points equally, regardless of their significance or relevance. In financial markets, recent data points may be more informative than older ones, especially in fast-moving markets. Standard deviation may not adequately reflect changes in market conditions or sentiment.</li><li><strong>Limited Interpretation of Volatility:</strong> Standard deviation measures total volatility, including both upside and downside movements. However, traders may be more interested in downside volatility, as it represents the risk of losses. Other measures such as the downside deviation or semi-deviation may provide more relevant insights into downside risk.</li><li><strong>Lack of Context: </strong>Standard deviation provides a numerical measure of volatility but does not provide any context or explanation for the observed variability. Traders should complement standard deviation with qualitative analysis and market knowledge to fully understand the drivers of volatility and risk.</li><li><strong>Inability to Capture Non-linear Relationships: </strong>Standard deviation assumes a linear relationship between data points, which may not always hold true in financial markets. Complex interactions and non-linear relationships between variables may not be fully captured by standard deviation alone.</li></ul><p>Overall, while standard deviation is a useful tool for measuring volatility and risk in trading, traders should be mindful of its limitations and use it in conjunction with other tools and techniques for a comprehensive analysis of market conditions.</p><p>Let us now find out some common misconceptions about standard deviation in trading next.</p><hr><h2 id="common-misconceptions-about-standard-deviation-in-trading">Common misconceptions about standard deviation in trading</h2><p>Several misconceptions about standard deviation exist in trading, which can lead to misinterpretation of market data and incorrect decision-making. Here are some common misconceptions:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/Common-misconceptions.png" class="kg-image" alt="Common misconceptions of standard deviation"></figure><ul><li><strong>Standard Deviation Predicts Future Returns: </strong>One common misconception is that high standard deviation implies high returns and vice versa. While volatility can indicate potential opportunities for maximising returns, it does not guarantee future returns. High volatility can also lead to significant losses if not managed properly.</li><li><strong>Standard Deviation is the Only Measure of Risk: </strong>While standard deviation is widely used to measure volatility and risk, it is not the only measure of risk. Other factors such as correlation, liquidity, and fundamental analysis should also be considered when assessing risk in trading.</li><li><strong>Standard Deviation Reflects Market Direction: </strong>Some traders mistakenly believe that changes in standard deviation indicate the direction of the market. However, standard deviation measures volatility, not market direction. It is possible for standard deviation to increase or decrease even if the market remains relatively unchanged.</li><li><strong>Standard Deviation is Static: </strong>Another misconception is that standard deviation remains constant over time. In reality, volatility can change dynamically in response to various factors such as news events, market sentiment, and economic conditions. Traders should regularly monitor and adjust their risk management strategies accordingly.</li><li><strong>Standard Deviation Measures Risk in Isolation:</strong> While standard deviation quantifies the variability of returns, it does not account for other factors that may influence risk, such as leverage, position size, and trading frequency. Traders should consider these factors holistically when assessing risk in their portfolios.</li><li><strong>Standard Deviation Provides Complete Information:</strong> Traders may mistakenly believe that standard deviation provides a comprehensive understanding of market risk. While standard deviation is a useful tool, it has limitations and should be used in conjunction with other risk measures and analysis techniques for a more accurate assessment of market conditions.</li></ul><p>By understanding and avoiding these misconceptions, traders can make more informed decisions and better manage risk in their trading activities.</p><p>Now let us discuss the risk management tips for using standard deviation next. These tips can help traders successfully use this helpful concept, which is, standard deviation.</p><hr><h2 id="risk-management-tips-for-using-standard-deviation">Risk management tips for using standard deviation</h2><p>Using standard deviation as part of a <a href="https://blog.quantinsti.com/trading-risk-management/">risk management trading</a> strategy can help traders better understand and mitigate risks in their trading activities.</p><p>Here are some tips for incorporating standard deviation into your risk management approach:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2024/03/Risk-management-tips.png" class="kg-image" alt="Tips using standard deviation"></figure><ul><li><strong>Set Risk Tolerance Levels:</strong> Determine your risk tolerance level based on factors such as your investment objectives, time horizon, and personal risk preferences. Use standard deviation to quantify the potential volatility and downside risk of your trades and investments.</li><li><strong>Use Stop-loss Orders: </strong>Set stop-loss orders based on the standard deviation of asset prices or portfolio returns. Place stop-loss levels at a certain number of standard deviations away from the mean to limit losses and protect capital in case of adverse price movements.</li><li><strong>Position Sizing: </strong>Adjust position sizes based on the standard deviation of asset returns. Increase position sizes for assets with lower volatility and decrease position sizes for assets with higher volatility to maintain consistent risk exposure across your portfolio.</li><li><strong>Diversify Your Portfolio:</strong> Diversification can help reduce overall portfolio risk by spreading investments across different asset classes, sectors, and geographical regions. Use standard deviation to assess the correlation between assets and ensure that your portfolio is adequately diversified.</li><li><strong>Monitor and Rebalance Regularly: </strong>Monitor the standard deviation of asset prices and portfolio returns regularly to identify changes in market conditions and adjust your risk management strategy accordingly. Rebalance your portfolio periodically to maintain desired risk levels and adapt to evolving market trends.</li><li><strong>Consider Risk-adjusted Performance:</strong> Evaluate the risk-adjusted performance of your trades and investments using metrics such as the Sharpe ratio or Sortino ratio, which take into account both returns and volatility. Aim to achieve positive risk-adjusted returns by optimising your risk-return trade-off.</li><li><strong>Stay Informed and Adapt:</strong> Stay informed about market news, economic indicators, and geopolitical events that may impact asset prices and market volatility. Be prepared to adjust your risk management strategy in response to changing market conditions and unexpected developments.</li></ul><p>By incorporating these risk management tips into your trading approach and leveraging standard deviation as a tool for measuring and managing risk, you can improve your chances of achieving long-term success and preserving capital in the financial markets.</p><hr><h3 id="conclusion">Conclusion</h3><p>Standard deviation is pivotal for traders, offering insights into volatility, risk, and informed decision-making. It quantifies uncertainty and variability of returns, aiding in options pricing, portfolio management, and volatility analysis.</p><p>Despite its usefulness, traders must acknowledge its limitations and supplement it with qualitative judgement. By integrating standard deviation into risk management practices, traders can navigate market complexities more effectively, optimise risk-return profiles, and strive for success in financial markets.</p><p>If you wish to learn more about standard deviation, you can enrol into the course on <a href="https://quantra.quantinsti.com/course/volatility-trading-strategies">Volatility Trading Strategies for Beginners</a>. With this course, you will learn how volatility can be your friend if you have the right tools and knowledge. In this course, you will learn four different ways to measure volatility, namely ATR, standard deviation, VIX and Beta. Hence, you will learn how to set dynamic stop loss and take profit levels, hedge your portfolio using VIX and select stocks in your portfolio.</p><hr><p><strong>File in the download</strong></p><ul><li>Standard deviation in trading - Python notebook</li></ul><!--kg-card-begin: markdown--><p class="custom-download-link"><a href="https://blog.quantinsti.com/standard-deviation" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: markdown--><hr><p><strong>Author:</strong> <a href="https://www.linkedin.com/in/chainika-bahl-thakar-b32971155/">Chainika Thakar</a> (Originally written by <a href="https://www.linkedin.com/in/ashutosh-dave-frm-2112551a/">Ashutosh Dave</a> and <a href="https://www.linkedin.com/in/udisha-alok/">Udisha Alok</a>)</p><hr><!--kg-card-begin: html--><p><em><small>Note: The original post has been revamped on 7th March 2024 for recentness, and accuracy.</small></em></p><!--kg-card-end: html--><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Autocorrelation and Autocovariance: Calculation, Examples, and More]]></title><description><![CDATA[Autocorrelation and Autocovariance are essential in the time series analysis topic! This tutorial will guide you on their definitions, their computations and plotting using Python and R. Read now!]]></description><link>https://blog.quantinsti.com/autocorrelation-autocovariance/</link><guid isPermaLink="false">6335c364201dfc1b4e2bb459</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Jose Carlos Gonzales Tanaka]]></dc:creator><pubDate>Mon, 17 Oct 2022 09:03:51 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/jos%C3%A9-carlos-gonz%C3%A1les-tanaka-60859284/">José Carlos Gonzáles Tanaka</a></p><p>Autocorrelation and autocovariance are one of the most critical metrics in financial time series econometrics. Both functions are based on covariance and correlation metrics. You will learn more about them. This easy-to-learn essential guide will help you understand better about ARMA models. </p><ul><li><a href="#what-is-autocovariance">What is autocovariance?</a></li><li><a href="#what-is-autocorrelation">What is autocorrelation?</a></li><li><a href="#what-are-the-autocovariance-and-autocorrelation-at-lag-zero">What are the autocovariance and autocorrelation at lag zero?</a></li><li><a href="#calculation-of-the-autocovariance-with-an-example">Calculation of autocovariance with an example</a></li><li><a href="#calculation-of-the-autocorrelation-with-an-example">Calculation of autocorrelation with an example</a></li><li><a href="#computation-of-autocovariance-and-autocorrelation-in-python">Computation of autocovariance and autocorrelation in Python</a></li><li><a href="#plot-the-autocorrelation-function-in-python">Plot the autocorrelation function in Python</a></li><li><a href="#computation-of-autocovariance-and-autocorrelation-in-r">Computation of autocovariance and autocorrelation in R</a></li><li><a href="#plot-the-autocorrelation-function-in-r">Plot the autocorrelation functions in R</a></li><li><a href="#what-is-partial-autocorrelation">What is partial autocorrelation?</a></li><li><a href="#computation-of-partial-autocorrelation-in-python-and-r">Computation of partial autocorrelation in Python and R</a></li></ul><p>You might have encountered yourself trying to learn the Autoregressive <a href="https://blog.quantinsti.com/moving-average-trading-strategies/">Moving Average</a> (ARMA) model. You then started to see a lot of use of covariances and correlations, but strangely enough, you see those two words with the prefix "<em>auto" </em>and you get frightened! </p><p>Don’t worry, this article will help you understand their details. Just keep the focus on the article and everything will be ok!</p><hr><h2 id="what-is-autocovariance">What is autocovariance?</h2><p>First, you need to understand what <a href="https://blog.quantinsti.com/covariance-correlation/">covariance and correlation</a> are. Remember that covariance is applied to 2 assets. The autocovariance is the same as the covariance. </p><p>The only difference is that the autocovariance is applied to the same asset, i.e., you compute the covariance of the asset price return X with the same asset price return X, but from a previous period. </p><p><em>How’s that possible?</em> Simple, check it out:</p><!--kg-card-begin: html-->$$ \text{Cov(X,Y)} =  \frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)\left(Y_{i}-\overline{Y}\right)}{N-1}$$<!--kg-card-end: html--><p>Where X and Y can be the returns of asset X and Y, respectively.</p><p>Now, the autocovariance function can be defined as:</p><!--kg-card-begin: html-->$$ \gamma_{s} =  \frac{\sum_{t=1}^{T}\left(r_{t}-\overline{r}\right)\left(r_{t-s}-\overline{r}\right)}{N-1}$$<!--kg-card-end: html--><p>Where:</p><!--kg-card-begin: html--><li>\( \gamma_{s} \text{: Autocovariance at lag “}s\text{”}.\) </li>
<li>\( r_{t} \text{: Asset price returns at time “}t\text{”}.\) </li>
<li>\( r_{t-s} \text{: Asset price returns at time “}t-s\text{”}.\) </li><!--kg-card-end: html--><hr><h2 id="what-is-autocorrelation">What is autocorrelation?</h2><p>In simple terms, <a href="https://blog.quantinsti.com/autoregression/">autocorrelation</a> is the same as the correlation function! To be specific, autocorrelation, as the autocovariance, is applied to the same asset. </p><p>Check the difference between correlation and autocorrelation (also called serial correlation) below:</p><!--kg-card-begin: markdown--><p>$$ \text{Corr(X,Y)} =  \frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)\left(Y_{i}-\overline{Y}\right)}<br>
{<br>
\sqrt{<br>
\left(\sum_{i=1}^{n} \left( X_{i}-\overline{X} \right)^2 \right)<br>
\left(\sum_{i=1}^{n} \left( Y_{i}-\overline{Y} \right)^2 \right)<br>
} }<br>
<br><br>
= \frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)\left(Y_{i}-\overline{Y}\right)}<br>
{<br>
\sqrt{<br>
\sum_{i=1}^{n} \left( X_{i}-\overline{X} \right)^2<br>
}<br>
\sqrt{<br>
\sum_{i=1}^{n} \left( Y_{i}-\overline{Y} \right)^2<br>
}<br>
}<br>
$$<br>
$$<br>
\text{Corr(X,Y)} = \frac{Cov(X,Y)}{SD_{X}SD_{Y}}<br>
$$</p>
<!--kg-card-end: markdown--><p>Where:</p><!--kg-card-begin: html--><li>\( \text{Cov(}X,Y\text{: Covariance between }X \text{ and }Y.\) </li>
<li>\( SD_{X} \text{: Standard Deviation of variable }\text{X}.\) </li>
<li>\( SD_{Y} \text{: Standard Deviation of variable }\text{Y}.\) </li><!--kg-card-end: html--><p>Now let’s check the autocorrelation:</p><!--kg-card-begin: html-->$$ \rho_{s} =  \frac{\text{Cov}\left(r_t,r_{t-s}\right)}{\text{Var}\left(r_t\right)}$$<!--kg-card-end: html--><p>Where:</p><!--kg-card-begin: html--><li>\( \rho_{s} \text{: Autocorrelation at lag “}s\text{”}.\) </li>
<li>\( r_{t} \text{: Asset price returns at time “}t\text{”}.\) </li>
<li>\( r_{t-s} \text{: Asset price returns at time “}t-s\text{”}.\) </li>
<li>\( \text{Var}\left(r_t\right) \text{: Variance of returns}.\) </li><!--kg-card-end: html--><p>You might ask us: </p><p><em>Why variance and not the multiplication of the <a href="https://blog.quantinsti.com/standard-deviation/">standard deviation</a> of the returns at the different lags? </em></p><p>Well, you must remember that an ARMA model is applied to stationary time series. This topic belongs to <a href="https://blog.quantinsti.com/time-series-analysis/">time series analysis</a>. Consequently, it is assumed that the price returns, if stationary, have the same variance for any lag, i.e.:</p><!--kg-card-begin: html-->$$ \text{Var}\left(r_t\right) = \text{Var}\left(r_{t-1}\right) = \text{Var}\left(r_{t-2}\right) = ... = \text{Var}\left(r_{0}\right) $$<!--kg-card-end: html--><hr><h2 id="what-are-the-autocovariance-and-autocorrelation-at-lag-zero">What are the autocovariance and autocorrelation at lag zero?</h2><p>Interesting question and simple to answer! Let’s see first for the former:</p><!--kg-card-begin: html-->$$ \gamma_{0} =  \frac{\sum_{t=1}^{T}\left(r_{t}-\overline{r}\right)\left(r_{t-0}-\overline{r}\right)}{N-1}
= 
\gamma_{0} =  \frac{\sum_{t=1}^{T}\left(r_{t}-\overline{r}\right)\left(r_{t}-\overline{r}\right)}{N-1}
= \gamma_{0} =  \frac{\sum_{t=1}^{T}\left(r_{t}-\overline{r}\right)^2}{N-1}
$$<!--kg-card-end: html--><p><em>Can you guess what the last part resembles?</em><br>It is the variance of the price returns!</p><p>Consequently, the autocovariance of the returns at lag 0 is the variance of the returns.</p><p><em>Can you guess now what the autocorrelation of the returns would be at lag 0?</em>Let’s use the formulas to find out:</p><!--kg-card-begin: html-->$$ \rho_{0} =  \frac{\text{Cov}\left(r_t,r_{t-0}\right)}{\text{Var}\left(r_t\right)}
=  \frac{\text{Cov}\left(r_t,r_{t-0}\right)}{\text{Var}\left(r_t\right)}
= \frac{\text{Cov}\left(r_t,r_{t}\right)}{\text{Var}\left(r_t\right)}$$<!--kg-card-end: html--><p>Since we know, from the above algebraic calculation, that the covariance of the same variable is its variance, we have the following:</p><!--kg-card-begin: html-->$$ \rho_{0} = \frac{\text{Cov}\left(r_t,r_{t}\right)}{\text{Var}\left(r_t\right)} 
= \frac{
\text{Var}\left(r_t\right)}
{\text{Var}\left(r_t\right)}$$
$$
\rho_{0} = 1
$$<!--kg-card-end: html--><p>Consequently, the autocorrelation function for any asset price return at lag 0 is always 1.</p><hr><h2 id="calculation-of-the-autocovariance-with-an-example">Calculation of the autocovariance with an example</h2><p>You might have been thinking up to now:<br><em>Why are the autocovariance and autocorrelation defined with an “s” subscript?</em><br><em>Great question!</em></p><p>Let us explain: Actually, the autocovariance formula defined above is a function which allows the calculation of the autocovariance for different lags. The same for the autocorrelation function.</p><p><em>Confused? Don’t worry! We got you covered!</em></p><p>Let’s see an example to make the concept clear to your thoughts! We are going to make an example of how to calculate the autocovariance of the Microsoft price returns at lag 1. We are going to use the autocovariance function shown above.</p><p>Imagine we have the following returns for Microsoft prices:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Day 1</p>
</td>
<td>
<p>Day 2</p>
</td>
<td>
<p>Day 3</p>
</td>
<td>
<p>Day 4</p>
</td>
<td>
<p>Day 5</p>
</td>
<td>
<p>Day 6</p>
</td>
<td>
<p>Day 7</p>
</td>
<td>
<p>Day 8</p>
</td>
<td>
<p>Day 9</p>
</td>
<td>
<p>Day 10</p>
</td>
</tr>
<tr>
<td>
<p>5%</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>-3%</p>
</td>
<td>
<p>4%</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>Let’s suppose we want to compute the autocovariance at lag 1. You will need the returns up to day 10, and the 1-period lagged returns up to day 9.</p><p>Thus, you have the following data structure for returns on days 10 and 9: </p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Variable</p>
</td>
<td>
<p>Day 1</p>
</td>
<td>
<p>Day 2</p>
</td>
<td>
<p>Day 3</p>
</td>
<td>
<p>Day 4</p>
</td>
<td>
<p>Day 5</p>
</td>
<td>
<p>Day 6</p>
</td>
<td>
<p>Day 7</p>
</td>
<td>
<p>Day 8</p>
</td>
<td>
<p>Day 9</p>
</td>
<td>
<p>Day 10</p>
</td>
</tr>
<tr>
<td>
<p>\( r_{t} \)</p>
</td>
<td>
<p>5%</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>-3%</p>
</td>
<td>
<p>4%</p>
</td>
</tr>
<tr>
<td>
<p>\( r_{t-1} \)</p>
</td>
<td>
</td>
<td>
<p>5%</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>-3%</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p><em>Do you get to see the difference between the 2 variables?</em><br>The second one is the first lag of Xt. </p><p>Now, since the 2 variables have different dimensions (the first one has 10 observations, while the second one has 9), we are going to use data from day 2 onwards.</p><p>Consequently, our data is as follows:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Variable</p>
</td>
<td>
<p>Day 2</p>
</td>
<td>
<p>Day 3</p>
</td>
<td>
<p>Day 4</p>
</td>
<td>
<p>Day 5</p>
</td>
<td>
<p>Day 6</p>
</td>
<td>
<p>Day 7</p>
</td>
<td>
<p>Day 8</p>
</td>
<td>
<p>Day 9</p>
</td>
<td>
<p>Day 10</p>
</td>
</tr>
<tr>
<td>
<p>\( r_{t} \)</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>-3%</p>
</td>
<td>
<p>4%</p>
</td>
</tr>
<tr>
<td>
<p>\( r_{t-1} \)</p>
</td>
<td>
<p>5%</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>-3%</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>The covariance between these 2 variables will be the autocovariance of the returns at lag 1. </p><p><em>You can do this, right?</em><br>Check an example we give in our previous article. </p><p>Before you get ready to use a pencil and a piece of paper, let us tell you something important. </p><p>Remember the autocovariance formula:</p><!--kg-card-begin: html-->$$ \gamma_{s} =  \frac{\sum_{t=1}^{T}\left(r_{t}-\overline{r}\right)\left(r_{t-s}-\overline{r}\right)}{N-1}$$<!--kg-card-end: html--><p>If you paid attention to details, you could see that the average return is the same for both returns, in our case, for returns up to day 10 and up to day 9. As we explained before, autocovariance and autocorrelation functions are applied only to <a href="https://blog.quantinsti.com/stationarity/">stationary time series</a>. </p><p>Consequently, not only the variance but also the mean is a unique value for the whole span. That’s why the mean is the same for any lag of the price returns.</p><p>The mean of the Microsoft price returns is 1.1%. Let’s follow the procedure to compute the autocovariance:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Variable</p>
</td>
<td>
<p>\( r_{t} \)</p>
</td>
<td>
<p>\( r_{t-1} \)</p>
</td>
<td>
<p>\( \left(r_{t}-\overline{r}\right) \)</p>
</td>
<td>
<p>\( \left(r_{t-1}-\overline{r}\right) \)</p>
</td>
<td>
<p>\( \left(r_{t}-\overline{r}\right) \)\( \left(r_{t-1}-\overline{r}\right) \)</p>
</td>
</tr>
<tr>
<td>
<p>Day 2</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>5%</p>
</td>
<td>
<p>-0.100%</p>
</td>
<td>
<p>3.900%</p>
</td>
<td>
<p>-0.004%</p>
</td>
</tr>
<tr>
<td>
<p>Day 3</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>1%</p>
</td>
<td>
<p>-3.100%</p>
</td>
<td>
<p>-0.100%</p>
</td>
<td>
<p>0.003%</p>
</td>
</tr>
<tr>
<td>
<p>Day 4</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-2%</p>
</td>
<td>
<p>1.900%</p>
</td>
<td>
<p>-3.100%</p>
</td>
<td>
<p>-0.059%</p>
</td>
</tr>
<tr>
<td>
<p>Day 5</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>3%</p>
</td>
<td>
<p>-5.100%</p>
</td>
<td>
<p>1.900%</p>
</td>
<td>
<p>-0.097%</p>
</td>
</tr>
<tr>
<td>
<p>Day 6</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>-4%</p>
</td>
<td>
<p>4.900%</p>
</td>
<td>
<p>-5.100%</p>
</td>
<td>
<p>-0.250%</p>
</td>
</tr>
<tr>
<td>
<p>Day 7</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>6%</p>
</td>
<td>
<p>0.900%</p>
</td>
<td>
<p>4.900%</p>
</td>
<td>
<p>0.044%</p>
</td>
</tr>
<tr>
<td>
<p>Day 8</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>2%</p>
</td>
<td>
<p>-2.100%</p>
</td>
<td>
<p>0.900%</p>
</td>
<td>
<p>-0.019%</p>
</td>
</tr>
<tr>
<td>
<p>Day 9</p>
</td>
<td>
<p>-3%</p>
</td>
<td>
<p>-1%</p>
</td>
<td>
<p>-4.100%</p>
</td>
<td>
<p>-2.100%</p>
</td>
<td>
<p>0.086%</p>
</td>
</tr>
<tr>
<td>
<p>Day 10</p>
</td>
<td>
<p>4%</p>
</td>
<td>
<p>-3%</p>
</td>
<td>
<p>2.900%</p>
</td>
<td>
<p>-4.100%</p>
</td>
<td>
<p>-0.119%</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>The autocovariance is just the sum of the last column values divided by (N-1, equal to 8), which results in -0.046%. </p><hr><h2 id="calculation-of-the-autocorrelation-with-an-example">Calculation of the autocorrelation with an example</h2><p>Let’s follow the same exercise and compute the autocorrelation of the Microsoft price returns up to day 10 at lag 1. The autocorrelation is the autocovariance divided by the variance. We give you the exact hint you need: The variance of Microsoft price returns up to day 10 is 0.121%.</p><p>Let’s follow the algebraic formulas and use the numbers to compute the autocorrelation:</p><!--kg-card-begin: html-->$$ \rho_{s} =  \frac{\text{Cov}\left(r_t,r_{t-s}\right)}{\text{Var}\left(r_t\right)}=\frac{-0.046%}{0.121%}$$
$$ \rho_{s} = -0.38 $$<!--kg-card-end: html--><hr><h2 id="computation-of-autocovariance-and-autocorrelation-in-python">Computation of autocovariance and autocorrelation in Python</h2><p>Before we do this section, let us tell you something. We have computed the autocovariance and autocorrelation of the Microsoft price returns at lag 1. We couldn’t have computed at lag 2, lag 3, etc. We leave you that as an exercise!</p><p>In <a href="https://quantra.quantinsti.com/course/python-for-trading">Python</a>, or any other programming language, when you are required to compute these two important metrics, you will need to compute them at many lags, not only 1, as we did previously above. </p><p>So, keep in mind that we are going to use Python to compute the autocovariance and autocorrelation functions, i.e., the autocovariance and autocorrelation at different lags.</p><p>First, let’s import the necessary libraries to use:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/39fbfa057983d0378d752d4c41ba53c8.js"></script><!--kg-card-end: html--><p>We now download the Microsoft close prices from January 2021 to August 2022:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/a724513481c05a1bf23802a5916eb0f4.js"></script><!--kg-card-end: html--><p>We compute the price returns:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/b44e2232a5efe85a599a865d40bbc6c1.js"></script><!--kg-card-end: html--><p>As we told you above, in any programming language which has available a library to compute the autocovariance and autocorrelation, you will see you’re going to have functions to get their values for many lags with just that unique functions.</p><p>So, let’s compute the autocovariance function up to lag 10 for the Microsoft price returns.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/a2e73bc3e153a45c3f56084d5878d1e9.js"></script><!--kg-card-end: html--><p>Check the values below:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>\( \gamma_{0} \)</p>
</td>
<td>
<p>0.00028672</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{1} \)</p>
</td>
<td>
<p>-0.00001403</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{2} \)</p>
</td>
<td>
<p>-0.00000250</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{3} \)</p>
</td>
<td>
<p>-0.00001941</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{4} \)</p>
</td>
<td>
<p>0.00002185</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{5} \)</p>
</td>
<td>
<p>0.00000488</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{6} \)</p>
</td>
<td>
<p>-0.00001460</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{7} \)</p>
</td>
<td>
<p>0.00001332</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{8} \)</p>
</td>
<td>
<p>-0.00002423</p>
</td>
</tr>
<tr>
<td>
<p>\( \gamma_{9} \)</p>
</td>
<td>
<p>0.00002422</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>Where </p><!--kg-card-begin: html-->\( \gamma_{s} \text{: Autocovariance at lag “}s\text{”}.\)<!--kg-card-end: html--><p>Let’s compute the first 10 autocorrelation values:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/3d3a5809932e7aa324703497de7b57f9.js"></script><!--kg-card-end: html--><p>See the values:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>\( \rho_{0} \)</p>
</td>
<td>
<p>1</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{1} \)</p>
</td>
<td>
<p>-0.04893</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{2} \)</p>
</td>
<td>
<p>-0.00871</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{3} \)</p>
</td>
<td>
<p>-0.0677</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{4} \)</p>
</td>
<td>
<p>0.076198</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{5} \)</p>
</td>
<td>
<p>0.017024</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{6} \)</p>
</td>
<td>
<p>-0.05092</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{7} \)</p>
</td>
<td>
<p>0.046457</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{8} \)</p>
</td>
<td>
<p>-0.08451</p>
</td>
</tr>
<tr>
<td>
<p>\( \rho_{9} \)</p>
</td>
<td>
<p>0.084456</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>As you learned previously, you see that the autocorrelation at lag 0 is 1. </p><hr><h2 id="plot-the-autocorrelation-function-in-python">Plot the autocorrelation function in Python</h2><p>What is usually done in econometrics is to plot the autocorrelation function. We, of course, are going to do that, see:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/374d5d8c4107a720a1389d32ac223b2e.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/10/autocorrelation-in-python.png" class="kg-image" alt="Autocorrelation in Python"><figcaption>Autocorrelation in Python</figcaption></figure><p>You see something strange in the plot, right? What is that blue-coloured highlighted zone? Well, it’s the confidence interval. You can compute that zone with the following formula:</p><!--kg-card-begin: html-->$$ \left[-\frac{1.96}{\sqrt{T}},\frac{1.96}{\sqrt{T}}\right] $$<!--kg-card-end: html--><p>Where T is the total number of observations.</p><hr><h2 id="computation-of-autocovariance-and-autocorrelation-in-r">Computation of autocovariance and autocorrelation in R</h2><p>Let’s go through this excellent programming language. We install the necessary packages and import them:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/c193371d1c330a8a7bcffb1f8f353245.js"></script><!--kg-card-end: html--><p>Next, we use the getSymbols method to download the Tesla stock data with the same span as for Microsoft.</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/d46c1681e9f0050995a2cc9f643b4e22.js"></script><!--kg-card-end: html--><p>We compute the returns:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/0b77d0d5a42cf04a176075038d25a741.js"></script><!--kg-card-end: html--><p>And we obtain the autocovariance function up to lag 10:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/ad4a4d676813b918cb10eb5c1e15e57a.js"></script><!--kg-card-end: html--><p>Let’s now compute the autocorrelation function up to lag 10:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/8e2430adb997da3d34c3d18c4e370b02.js"></script><!--kg-card-end: html--><p>As you can deduct, the default value for “type” is the autocorrelation function.</p><hr><h2 id="plot-the-autocorrelation-function-in-r">Plot the Autocorrelation Function in R</h2><p>Finally, let’s plot the autocorrelation function:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/6759c1dd5af2749a63a7b8df3b9c8817.js"></script><!--kg-card-end: html--><p>We specify first the graph parameters: The main size increase, the axis values increase and the axis labels increase all of them with respect to the plot default value. Besides, we define the margins of the plot. </p><p>Next, we plot the autocorrelation function. Finally, we apply the graph parameters to the autocorrelation function plot.</p><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/10/autocorrelation_in_R.jpg" class="kg-image" alt="Autocorrelation in R"><figcaption>Autocorrelation in R</figcaption></figure><hr><h2 id="what-is-partial-autocorrelation">What Is partial autocorrelation?</h2><p>Since our mission is to prepare you to model an ARMA process, we need to explain to you this function.</p><p>What is it? Let’s explain the function of intuition.</p><p>For example, the autocorrelation function at lag 5 might have correlations with its previous lags’ autocorrelations. The partial autocorrelation function gives the autocorrelation at lag 5, but without the relationship of the shorter lags’ autocorrelations.</p><p>Putting it in another way, the autocorrelation of Microsoft price returns at lag 5 is about the autocorrelation between returns at time t and at the time (t-5). But this autocorrelation is also influenced by the correlations from lag 1 to lag 4. </p><p>The partial autocorrelation is a function that allows having the autocorrelation of returns t and (t-5) removing the indirect relationship that returns from lag 1 to 4 have on it.</p><hr><h2 id="computation-of-partial-autocorrelation-in-python-and-r">Computation of partial autocorrelation in Python and R</h2><p>Let’s compute them in python and R. </p><p>We follow our previous order. We begin with Python. We plot the partial autocorrelation function for Microsoft:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/747bee527f0c77e776581a372356c5cf.js"></script><!--kg-card-end: html--><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/10/partial-autocorrelation-in-python.png" class="kg-image" alt="Partial Autocorrelation in Python"><figcaption>Partial Autocorrelation in Python</figcaption></figure><p>Let’s compute the partial autocorrelation function for the Tesla stock price returns in R:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/6b866c5f9024bf980d704cdd0ae33c9c.js"></script><!--kg-card-end: html--><p>We use the same code as for the autocorrelation function, but this time we specify “type=partial” to get the desired output.</p><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/10/partial_autocorrelation_in_R.jpg" class="kg-image" alt="Partial Autocorrelation in R"><figcaption>Partial Autocorrelation in R</figcaption></figure><hr><h3 id="conclusion">Conclusion</h3><p>ARMA models based their construction of inspection of the autocovariance and autocorrelation functions. Here, we have helped you understand the most important things about them and their applications in Python and R.</p><p>This will help you whenever you want to trade algorithmically since you have here useful code to use. Whenever you initiate yourself on the ARMA models, you will definitely remember this article and be well prepared to understand those types of models. Bookmark this article in your browser, you will not regret it! </p><p>As we told you before, this two formulas belong to the time series analysis topic. We guess you're already excited about the topic, aren't you? Do you want to continue learning about it? Check this course on <a href="https://quantra.quantinsti.com/course/financial-time-series-analysis-trading">time series analysis</a> to start trading algorithmically!</p><p>Are you ready to create your ARMA model? We bet you are!<br>Ready? Set?<br>Go algo!</p><hr><p><strong>File in the download</strong></p><p>Autocorrelation and autocovariance in Python</p><!--kg-card-begin: markdown--><p class="custom-download-link"><a href="https://blog.quantinsti.com/autocorrelation-autocovariance" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: markdown--><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Covariance and Correlation: Intro, Formula, Calculation, and More]]></title><description><![CDATA[Covariance and Correlation - what are they? Learn the various concepts, industry applications and Python computations in this tutorial.]]></description><link>https://blog.quantinsti.com/covariance-correlation/</link><guid isPermaLink="false">6246e361cffb700439467855</guid><category><![CDATA[Mathematics and Econometrics]]></category><dc:creator><![CDATA[Jose Carlos Gonzales Tanaka]]></dc:creator><pubDate>Wed, 04 May 2022 03:30:00 GMT</pubDate><content:encoded><![CDATA[<p>By <a href="https://www.linkedin.com/in/jos%C3%A9-carlos-gonz%C3%A1les-tanaka-60859284/">José Carlos Gonzáles Tanaka</a></p><p>Let us know a little bit more about you. <em>Do you think you would need to see a “Covariance vs Correlation” fight in a boxing ring so you could choose properly between them?</em></p><ul><li><em>Are you a beginner in the financial markets and want to know basic concepts in order to start trading?</em></li><li><em>Do you know how crude oil moves together with the dollar, the euro or the Japanese Yen?</em></li><li><em>Do you know how gold prices and interest rates change when the world is in a recession?</em></li></ul><p>Whatever the position you have in the industry or doubts you might have, this easy-to-read article will take you through all about these two concepts: From the definitions and formulas to trading applications, and you will also be prepared to properly analyze the relationships between important financial variables.</p><p>So, take a comfortable seat and enjoy this learning experience with a cup of coffee!</p><ul><li><a href="#what-is-covariance">What is Covariance?</a></li><li><a href="#what-is-correlation">What is Correlation?</a></li><li><a href="#what-are-the-differences-between-covariance-and-correlation">What are the differences between Covariance and Correlation?</a></li><li><a href="#how-to-calculate-covariance-and-correlation">How to calculate Covariance and Correlation?</a></li><li><a href="#importance-of-covariance-and-correlation">Importance of Covariance and Correlation</a></li><li><a href="#trading-applications-of-covariance-and-correlation">Trading applications of Covariance and Correlation</a></li><li><a href="#covariance-and-correlation-simple-exercise-examples">Covariance and Correlation Simple Exercise Examples</a></li><li><a href="#covariance-and-correlation-computation-examples-in-python">Covariance and Correlation Computation Examples in Python</a></li></ul><hr><h2 id="what-is-covariance">What is Covariance?</h2><p>Covariance is a statistical measurement with the following definition: It measures the direction of the linear association between two variables.</p><p>With this explanation, you then start to imagine that we are your teacher and you raise your hand to say: “<em>Teacher, I don’t understand.</em>”</p><p>Don’t worry about it! Let’s make it simpler: It measures the comovement direction between two variables. Put it in another way, you have data of two variables and Covariance measures whether these two variables move in the same or opposite direction. </p><p>We say positive Covariance, if both variables move in the same direction: If a stock price goes up, then the other stock price goes up, too. We say negative Covariance, when a stock price goes up and the other stock price goes in the opposite direction, meaning, goes down.</p><p>About the words “linear association”, you’ll get the point later. So, yes, Covariance can be either positive or negative.</p><p>Imagine we have data from four stock prices:</p><ul><li>Amazon,</li><li>Apple,</li><li>Walmart, and</li><li>Microsoft.</li></ul><p>At the top, you have a graph in which you could see a positive Covariance: While Amazon stock price moves higher, Apple moves in the same positive direction. At the bottom, you can see that, when Microsoft moves down, Walmart does the opposite, moves higher, which means there is a negative Covariance between them.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/positive_covariance-4.png" class="kg-image" alt="positive_covariance"></figure><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/negative_covariance-2.png" class="kg-image" alt="negative_covariance"></figure><p><strong>Question:</strong> <em>If variable A and B  have a positive Covariance, then should we interpret that whenever variable A goes higher in value, B “always” goes in a higher value too?”</em></p><p>Not always. This direct or inverse comovement could also be strong or weak. If the positive or negative Covariance value is big, in absolute terms, then we say that the comovement is strong, if it is low, we say the comovement is weak. </p><p><em>What is a strong or weak comovement?</em></p><p>Well, what we can say is that a big positive Covariance, or a strong positive comovement, means that, most of the time, the two variables will move in the same positive direction. </p><p>The same for a negative Covariance: If we have a big negative Covariance value for two variables, in absolute terms, this means that we expect to see, most of the time, the two variables move in the opposite direction.</p><p>So, now with a clearer definition, you have a deduction and two more questions to test your knowledge:</p><ol><li><em>Does Covariance measure the strong or weak relationship between two variables?</em></li><li><em>Can we have a perfect direct or inverse comovement between two variables?</em></li></ol><p>For these questions, let us take you to our other important concept called Correlation.</p><hr><h2 id="what-is-correlation">What is Correlation?</h2><p>You might have made a pause and taken a sip of your cup of coffee and might be saying to yourself: “<em>Oh, here comes another definition, it’s a lot of information!</em>”</p><p>Hey! Don’t worry at all! Correlation has, actually, a similar definition. Let’s put it formally first. Correlation measures the degree of the linear association between two variables.</p><p>We know, you are surprised, and ask: “<em>Do we have the words ‘linear association”, again?</em>”</p><p>Hey! Don’t hurry, we’re talking about this later. For now, we could say: While Covariance measures the direction of the comovement, Correlation not only measures that, but also the degree, or “<strong>strength</strong>”, of this relationship direction.</p><p>We’ll see later how this ‘strength’ looks like. For now, let’s express the differences between these two concepts below:</p><hr><h2 id="what-are-the-differences-between-covariance-and-correlation">What are the differences between Covariance and Correlation?</h2><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
    <p><strong>Covariance</strong></p>
</td>
<td>
<p><strong>Correlation</strong></p>
</td>
</tr>
<tr>
<td>
<p>Measures one thing</p>
</td>
<td>
<p>Measures two things</p>
</td>
</tr>
<tr>
<td>
<p>Infinite range</p>
</td>
<td>
<p>Finite range</p>
</td>
</tr>
<tr>
<td>
<p>It has unit of measurement</p>
</td>
<td>
<p>Free of unit of measurement</p>
</td>
</tr>
<tr>
<td>
<p>Scalable value</p>
</td>
<td>
<p>Non-scalable value</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><h3 id="difference-1-covariance-measures-one-thing-and-correlation-measures-two-things-">Difference #1: Covariance measures one thing and Correlation measures two things.</h3><p>Covariance, as explained above, measures only the direction of the comovement of two variables. Correlation measures not only the direction of the relationship, but also the strength of this relationship. </p><p><em>So how well do Amazon and Apple stock prices move in the same or opposite direction?</em></p><p>You now have two technical tools to answer this question:</p><ul><li>To find out whether two variables move in the same or opposite direction, you could use either the Covariance or the Correlation functions.</li><li>About “how well” this direct or inverse relationship is, you need to answer this with the latter.</li></ul><h3 id="difference-2-covariance-and-correlation-value-range-are-not-the-same-">Difference #2: Covariance and Correlation value range are not the same.</h3><p>Covariance could have an infinite positive value or an infinite negative value, the range of values takes the whole real number spectrum. However, Correlation value range is only between -1 and +1.</p><p>So your question regarding a perfect comovement could be answered here: Since Covariance could have any real value, we could not appreciate with this statistical measure a perfect degree of linear association between two variables. </p><p>The best way to approach this question is with Correlation. If the Correlation of variables A and B has the value of +1, you can say without any doubt that both variables “always” move in the same direction. The same for a Correlation with a -1 value: you can say without any doubt that both variables “always” move in the opposite direction. </p><p>Here you can understand Difference #1. When the Correlation is between -1 and 1, the comovement is not perfectly negative or positive, respectively. Last but not least about this difference, we must say that it’s almost impossible to see real world variables having a Correlation exactly equal to +1 or -1.</p><h3 id="difference-3-covariance-and-correlation-have-different-measure-units-">Difference #3: Covariance and Correlation have different measure units.</h3><p>You will get to understand it mathematically later. By now, we can say that Covariance has as a unit of measurement the multiplication of the two variables’ units of measurement. </p><p>For example, if you have two stock prices which are Amazon and Apple, which both have as unit of measurement the dollar, you will have for the Covariance a unit of measurement of: Dollar times Dollar, which is Dollar squared.</p><p>However, Correlation doesn’t have any unit of measurement at all. Don’t hurry to worry! Sip your coffee and wait a little bit more to fully understand this.</p><h3 id="difference-4-covariance-could-change-in-value-if-the-variables-are-scaled-differently-correlation-is-not-affected-by-this-">Difference #4: Covariance could change in value if the variables are scaled differently, Correlation is not affected by this.</h3><p>Let us give you an example to understand this difference. You have two stock prices, Amazon and Apple, and then you calculate their Covariance and Correlation, which result in “a” and “b” respectively.</p><p>Next, you decide to multiply the two stock prices by 1000, and you calculate, again, their Covariance and Correlation, which result in values “c” and “d”. Something interesting that you will find is that:</p><ul><li>Covariance “a” is different from Covariance “c” and,</li><li>Correlation “b” is equal to Correlation “d”.</li></ul><p>When you scale one or both variables, Covariance will change in value accordingly. However, Correlation is not affected by the scale change.</p><hr><h2 id="how-to-calculate-covariance-and-correlation">How to Calculate Covariance and Correlation?</h2><p>Up until now, we explained to you everything about their concepts and their properties. But from now on, you will have a better grasp with the mathematical formulas.</p><p>First, you must differentiate between what is a <a href="https://quantra.quantinsti.com/glossary/Population">population</a> and <a href="https://quantra.quantinsti.com/glossary/Sample">sample</a> data. Once you are familiar with these two concepts, let’s begin with the presentation of the formulas:</p><p>We start with Covariance.</p><p><strong>Population Covariance:</strong></p><!--kg-card-begin: html-->$$ \sigma_{X,Y}^{2} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{N} $$<!--kg-card-end: html--><!--kg-card-begin: html-->Where:
<br>\( \sigma_{X,Y}^{2} \):  Population Covariance between variables \(X\) and \(Y\).
<br>\(X_{i}\): The \(i^{th}\) observation of the \(X\) variable.
<br>\(\overline{X}\): The mean value of variable \(X\).
<br>\(Y_{i}\): The \(i^{th}\) observation of the \(Y\) variable.
<br>\(\overline{Y}\): The mean value of variable \(Y\).
<br>\(N\): Total number of observations for variable \(X\) o \(Y\).<!--kg-card-end: html--><p><strong>Sample Covariance:</strong></p><!--kg-card-begin: html-->$$ S_{X,Y}^{2} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{N-1} $$<!--kg-card-end: html--><!--kg-card-begin: html-->Where:
<br>\( S_{X,Y}^{2} \):  Sample Covariance between variables \(X\) and \(Y\). The other variables are the same as for the Population Covariance <p>
<!--kg-card-end: html--></p><p>So, in simple words, how could we explain the Covariance formula? Let’s say it in this way: Covariance is a measure in which we multiply each deviation from the mean of X and Y, given by (Xi-X) and (Yi-Y) respectively, and then we sum all these products and divide them by N. </p><p>It resembles the <a href="https://quantra.quantinsti.com/glossary/Variance">formula</a> of the Variance of a variable, right? Well, both formulas are almost similar, the only difference is that in the Variance formula you see the deviations from the mean squared, for the Covariance, you don’t see a squared deviation.</p><p>But the Variance formula can also be written as: </p><!--kg-card-begin: html-->$$ \sigma_{X,Y}^{2} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2}{N}=\frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(X_{i}-\overline{X}\Bigr)}{N} $$<!--kg-card-end: html--><p>So, you get it? Variance and Covariance formulas are actually identical; the difference resides in the second parenthesis, which is replaced by the deviations of a second variable. Variance refers to a single variable, Covariance refers to two variables, that is why it’s called “Co” Variance.</p><p>The sample Covariance is the same as the population variance, but instead of N, we divide the dividend by N-1. The explanation of this difference can be found in the “<a href="https://blog.quantinsti.com/standard-deviation/">Standard deviation</a> for sample data - Bessel's correction” section of this blog. </p><p>As you could guess, X is in X units, and Y is in Y units. So, the Covariance formula, since it is a multiplication of these two variables, will be in XY measure units. </p><p>Let’s go now for the Correlation formula:</p><!--kg-card-begin: html-->\( \rho_{X,Y} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{\sqrt{\biggl(\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2\biggr)\biggl(\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2\biggr)}} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{\sqrt{\biggl(\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2\biggr)}\sqrt{\biggl(\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2\biggr)}}\)<!--kg-card-end: html--><!--kg-card-begin: html-->$$ \rho_{X,Y} = \frac{Cov(X,Y)}{\sigma_X\:\sigma_Y} $$<!--kg-card-end: html--><!--kg-card-begin: html-->Where:
<br>\( \rho_{X,Y} \):  Correlation between variables \(X\) and \(Y\).
<br>\(Cov(X,Y)\): Covariance between \(X\) and \(Y\).
<br>\(\sigma_X\): Standard Deviation of variable \(X\).
<br>\(\sigma_Y\): Standard Deviation of variable \(Y\).<!--kg-card-end: html--><p>So, how could we explain this formula in simple words? Well, you already know the dividend, and about the divisor, if you could remember the Variance <a href="https://blog.quantinsti.com/standard-deviation/">formula</a>, you can realize that the divisor is the multiplication of the standard deviation of both variables X and Y. </p><p>So we can say that Correlation is the Covariance divided by the Standard Deviations of the two variables. You might be thinking that the Covariance and the Standard Deviation have as a divisor “N” or “N-1”, so you could think that we wrote the first formula wrongly.</p><p>Don’t worry, let us make you see what happened with the divisors:</p><!--kg-card-begin: html--><p>\( \rho_{X,Y} = \frac{\frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{N}}{\sqrt{\Biggl(\frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2}{N}\Biggr)}\sqrt{\Biggl(\frac{\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2}{N}\Biggr)}} = \frac{\frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{N}}{\sqrt{\biggl(\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2\biggr)\biggl(\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2\biggr)\Biggl(\frac{1}{N^2}\Biggr)}} \)</p>
<p>\( \rho_{X,Y} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)\Biggl(\frac{1}{N}\Biggr)}{\sqrt{\biggl(\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2\biggr)\biggl(\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2\biggr)}\Biggl(\frac{1}{N}\Biggr)} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{\sqrt{\biggl(\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2\biggr)\biggl(\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2\biggr)}}\frac{\Biggl(\frac{1}{N}\Biggr)}{\Biggl(\frac{1}{N}\Biggr)} \)</p>
<p>\( \rho_{X,Y} = \frac{\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)\Bigl(Y_{i}-\overline{Y}\Bigr)}{\sqrt{\Biggl(\sum_{i=1}^{N}\Bigl(X_{i}-\overline{X}\Bigr)^2\Biggr)}\sqrt{\Biggl(\sum_{i=1}^{N}\Bigl(Y_{i}-\overline{Y}\Bigr)^2\Biggr)}} \)</p><!--kg-card-end: html--><!--kg-card-begin: html-->$$ \rho_{X,Y} = \frac{Cov(X,Y)}{\sigma_X\:\sigma_Y} $$<!--kg-card-end: html--><p>Now you get it? The divisors from the Covariance and the Standard Deviations canceled each other. Besides, the dividend, as explained earlier, has as a measure unit the multiplication of both the measure units of X and Y. The divisor has as a measure unit, also, the multiplication of the measure units of both Standard Deviations, which are from X and Y. </p><p>Consequently, since the dividend and the divisor have the same XY measure unit, they cancel each other and you get the Correlation value free of a measure unit. Now you can understand the Difference #3 explained before, right?</p><p>Besides, you can now understand Difference #4. Why? Because the Covariance ends with a XY measure unit, so whenever you change the scale of any of the two variables, then you will scale, too, the divisor’s measure unit. </p><p>Meanwhile, since the Correlation formula does not have a measure unit, the change of scale you could make to, again, any of the two variables, won’t affect the Correlation range which is between -1 and 1.</p><p>We got through all these explanations and you might ask now about:</p><hr><h2 id="importance-of-covariance-and-correlation">Importance of Covariance and Correlation</h2><p>Well, you now ask this important question. The answer resides in the essence of Economics and Finance. Finance, as an essential part of Economics, is about markets where economic agents buy and sell assets from one or more markets.</p><p>Within markets or between markets, assets can move in the same or opposite direction with any other asset due to the same agents that make transactions everyday. </p><p>Asset prices change according to agent’s behaviors, market conditions, etc. If there’s a person who buys 100 shares of Apple or if there’s a crowd who sells their bank shares due to a bank run, every single person’s transaction has consequences not only on the asset itself, but also on other stocks or in other markets. </p><p>Markets are interrelated, so Correlation and Covariance are an essential part of the study of financial markets. If markets or financial assets weren’t interconnected, we wouldn't need to take care of comovements. </p><p>You now know not only what these two concepts mean but also why they are important. We get to our main purpose.</p><p>So, now, you want to trade, right?<br><em>You are ready to check the correlation of the Apple and Amazon stock prices and now you are prepared to press the BUY and SELL buttons in your broker’s platform to start investing.</em> Aren’t you? </p><p>No! Wait a minute! Let us explain to you, before you make a decision, the real world applications of Covariance and Correlation in trading and investment.</p><hr><h2 id="trading-applications-of-covariance-and-correlation">Trading Applications of Covariance and Correlation</h2><h3 id="trading-application-1-portfolio-volatility-computation">Trading Application #1: Portfolio Volatility Computation</h3><p>When you start investing in more than one stock, you must consider how well the volatility of your portfolio is behaving. The computation of this Portfolio Volatility is only possible to be done once you fully understand both how Covariance and Correlation work. </p><p><em>So, please, don’t press the BUY button yet</em>. You can check our course on <a href="https://quantra.quantinsti.com/course/quantitative-portfolio-management">Portfolio Management</a> on Quantra to get to know more about it. Wait a bit more to let us explain to you more.</p><h3 id="trading-application-2-statistical-arbitrage">Trading Application #2: Statistical Arbitrage</h3><p>Whenever you get into Statistical Arbitrage you have to understand the definitions of  Correlation and Cointegration. Statistical Arbitrage does not make use of Correlation, but it’s really important to comprehend the difference between the two concepts. </p><p>Our course on <a href="https://quantra.quantinsti.com/course/statistical-arbitrage-trading">Statistical Arbitrage Trading</a> explains all about this. <em>We can guess that you want now to start pressing the BUY and SELL buttons to do arbitrage, right?</em> We told you, wait for more!</p><h3 id="trading-application-3-correlated-variables-in-a-regression-estimation">Trading Application #3: Correlated Variables in a Regression Estimation</h3><p>One of the main conditions to make a regression between two or more variables is to have uncorrelated independent variables. So, since you already know the meaning of Correlation, you are now able to correct a problem in case there is a violation of this condition in your regression estimates. You can expand your knowledge about this topic with this course on <a href="https://quantra.quantinsti.com/course/trading-with-machine-learning-regression">Trading with Machine Learning: Regression</a>.</p><h3 id="trading-application-4-correlation-to-predict-asset-prices">Trading Application #4: Correlation to Predict Asset Prices</h3><p>See, financial asset prices, contrary to what happens to variables in a controlled physics experiment, tend to suffer <a href="https://blog.quantinsti.com/regime-changes-webinar-michael-harris-8-october-2020/">regime changes</a> across time. So in case you calculate the Correlation of a US Treasury 2-year Bond Yield with the FED Funds Rate using data from 2021, this value won’t necessarily be the same for the year 2022. </p><p>Correlation through time could vary greatly and this mostly happens in adverse economic shocks or economic or financial crises. Be careful while using Correlation to predict your next signal to trade!</p><h3 id="trading-application-5-arma-models-to-predict-asset-price-returns">Trading Application #5: ARMA Models to Predict Asset Price Returns</h3><p>So, have you heard about Autoregressive Moving Average (ARMA) Models? This model tries to forecast asset price returns with their past returns estimates calculated through a regression model, in which the <a href="https://blog.quantinsti.com/moving-average-trading-strategies/">moving average</a> of the regression errors is also important. </p><p>Here you will get to know what <a href="https://blog.quantinsti.com/autocorrelation-autocovariance/">AutoCovariance and AutoCorrelation</a> functions are. So in order to understand these two concepts, you have first to understand the two concepts of this article.</p><p><em>What does an autocorrelation function look like?</em></p><p>Well, remember that the Correlation function is calculated based on two variables and remember also that the ARMA models try to predict asset price returns with their previous returns. So if you say these returns could be called rt, then, the autocorrelation function can be expressed as:</p><!--kg-card-begin: html-->$$ \rho_{r_{t},r_{(t-1)}} = \frac{Cov(r_{t},r_{(t-1)})}{\sigma_{r_{t}}\:\sigma_{r_{(t-1)}}} $$<!--kg-card-end: html--><p>Do you want to know more? Get access to this amazing course on <a href="https://quantra.quantinsti.com/course/financial-time-series-analysis-trading">Time Series Analysis</a> in Quantra.</p><h3 id="trading-application-6-causality-and-correlation-are-not-the-same-thing">Trading Application #6: Causality and Correlation Are Not the Same Thing</h3><p>This is more of a trading knowledge so pay attention to this. Causation means that a movement in Apple Stock price causes a movement in Amazon Stock price. But, what do we mean by “causes” here? Well, Causation is even discussed philosophically in Economics. The philosophical discussion hasn’t ended up to now. Let me give you an example so you could understand it better.</p><p>Imagine we have the number of litres of rainwater that falls each month in New York City and we also have the monthly GDP of New York city as well. You calculate the Correlation between them and get a value of 0.95. </p><p>You get to say: <em>“Oh, that’s interesting! I can say, then, that, whenever it’s raining a lot in the city, this will cause the NY GDP to increase.”</em> No! You can’t say that a lot of rainwater ‘causes’ an increase in GDP; or vice versa, that an increase in GDP ‘will cause’ an increase in rainwater in the city. </p><p>Correlation simply means that you could find a pattern of comovement between these two variables but it doesn’t mean that there is an economic causation between rainwater and GDP.</p><p>So, whenever you are talking, as a trader, about Correlation, you must always keep in mind that this concept is not necessarily the same as Causation. Putting it in another way:</p><blockquote>Causation always implies Correlation, but Correlation doesn’t always imply Causation.</blockquote><h3 id="trading-application-7-correlation-stylized-facts">Trading Application #7: Correlation Stylized Facts</h3><p>This is also important information to incorporate into your background knowledge. Some worldwide correlations are important to consider when you want to trade in some financial assets.</p><p>Here we present you some stylized facts to keep in mind whenever you want to trade with these assets:</p><ul><li><strong>Crude Oil and Currencies:</strong> Crude-oil net exporters like Russia, Canada, Venezuela or Saudi Arabia see their currencies fall whenever the crude oil price falls. However, crude net importers like Japan tend to see their currency appreciate whenever the crude oil price falls.</li><li><strong>Flight-to-Quality:</strong> Whenever there is a financial turmoil in an important country or part of the world, like the 1997 Asian financial crisis, investors tend to get their money out of these high-yield countries and buy US Treasury bonds. This action makes the affected countries’ currencies depreciate highly against the dollar and the US Treasury bonds tend to soar in value. Consequently, in the Asian crisis, there was a negative correlation between the asian countries’ currencies and the US bond prices.</li><li><strong>Equity-Bond Negative Correlation:</strong> For example, whenever the US economy starts to boom, investors reallocate their portfolios. They invest heavily in more risky assets and less in Treasury bonds. When the economy enters a recession, it happens the opposite, there’s a greater investment in fixed income and less in equity securities. This negative correlation between Equity and Bonds is a common feature of countries around the world.</li><li><strong>Gold Time-Varying Correlation:</strong> When world investors are more prone to invest in risky assets, there is an increase in the positive correlation between gold and the US stock market. When they become more risk averse, due to a global recession, gold becomes inversely correlated with the US stock market.</li><li><strong>Gold and Inflation:</strong> When world inflation goes up, investors tend to increase their portfolio allocation to gold, meaning, the correlation between gold and inflation is positive. Gold behaves as a hedge against inflation. The precious metal maintains your buying power when inflation rises above expectations.</li><li><strong>Gold and US interest rates:</strong> When the US sees its interest rates go up, then this means the economy is in good strength. This makes world investors allocate their resources to more risky assets. Thus, gold starts to decline in value in this period. We can say Gold and US interest rates have a negative correlation throughout time.</li><li><strong>Geopolitics and Gold:</strong> Whenever there are adverse geopolitical shocks that affect the whole world, gold price tends to increase, since this precious metal acts as a ‘safe haven’.</li><li><strong>Returns-Volatility Correlation:</strong> When stock prices fall, companies suffer an increase in their debt-to-equity ratio, which in turn, makes its stock price return volatility increase. This negative correlation between stock price returns and its volatility is called “the leverage effect”. When you trade with stocks and want to model volatility, you should consider this effect on your estimation in order to capture the negative correlation.</li></ul><hr><h2 id="covariance-and-correlation-simple-exercise-examples">Covariance and Correlation Simple Exercise Examples</h2><h3 id="how-to-calculate-covariance">How to Calculate Covariance?</h3><p>You are now ready for this, right? Ok, let’s start with a simple example. Imagine we have two asset prices called Microsoft and Tesla, and we have 5 days of data for each stock.</p><p>Below we have the data as a table presented below:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Date \ Stock</p>
</td>
<td>
<p>Microsoft</p>
</td>
<td>
<p>Tesla</p>
</td>
</tr>
<tr>
<td>
<p>Day 1</p>
</td>
<td>
<p>240</p>
</td>
<td>
<p>850</p>
</td>
</tr>
<tr>
<td>
<p>Day 2</p>
</td>
<td>
<p>265</p>
</td>
<td>
<p>800</p>
</td>
</tr>
<tr>
<td>
<p>Day 3</p>
</td>
<td>
<p>255</p>
</td>
<td>
<p>820</p>
</td>
</tr>
<tr>
<td>
<p>Day 4</p>
</td>
<td>
<p>280</p>
</td>
<td>
<p>870</p>
</td>
</tr>
<tr>
<td>
<p>Day 5</p>
</td>
<td>
<p>301</p>
</td>
<td>
<p>900</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>Since we have a sample instead of a population data, we will use the sample Covariance and the Correlation function. First of all, we know that we have 5 observations, that’s why our N variable is 5. </p><p>Then, we have to calculate the mean for each Stock. We’ll help you with that, these two means are: 268.2 and 848 for Microsoft and Tesla, respectively. Next, we have to calculate the deviations of each observation from the mean, this must be done for each stock:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Date \ Stock</p>
</td>
<td>
<p>Microsoft</p>
</td>
<td>
<p>Tesla</p>
</td>
<td>
<p>Microsoft Deviations from the Mean</p>
</td>
<td>
<p>Tesla Deviations from the Mean</p>
</td>
</tr>
<tr>
<td>
<p>Day 1</p>
</td>
<td>
<p>240</p>
</td>
<td>
<p>850</p>
</td>
<td>
<p>-28.2</p>
</td>
<td>
<p>2</p>
</td>
</tr>
<tr>
<td>
<p>Day 2</p>
</td>
<td>
<p>265</p>
</td>
<td>
<p>800</p>
</td>
<td>
<p>-3.2</p>
</td>
<td>
<p>-48</p>
</td>
</tr>
<tr>
<td>
<p>Day 3</p>
</td>
<td>
<p>255</p>
</td>
<td>
<p>820</p>
</td>
<td>
<p>-13.2</p>
</td>
<td>
<p>-28</p>
</td>
</tr>
<tr>
<td>
<p>Day 4</p>
</td>
<td>
<p>280</p>
</td>
<td>
<p>870</p>
</td>
<td>
<p>11.8</p>
</td>
<td>
<p>22</p>
</td>
</tr>
<tr>
<td>
<p>Day 5</p>
</td>
<td>
<p>301</p>
</td>
<td>
<p>900</p>
</td>
<td>
<p>32.8</p>
</td>
<td>
<p>52</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p>Once you are done with that, you can proceed to multiply both deviations for each date and then sum all the multiplications to get the dividend of the Covariance Formula:</p><!--kg-card-begin: html--><table>
<tbody>
<tr>
<td>
<p>Microsoft&rsquo;s Deviations from the Mean</p>
</td>
<td>
<p>Tesla&rsquo;s Deviations from the Mean</p>
</td>
<td>
<p>Multiplication of both Deviations</p>
</td>
</tr>
<tr>
<td>
<p>-28.2</p>
</td>
<td>
<p>2</p>
</td>
<td>
<p>-56.2</p>
</td>
</tr>
<tr>
<td>
<p>-3.2</p>
</td>
<td>
<p>-48</p>
</td>
<td>
<p>153.6</p>
</td>
</tr>
<tr>
<td>
<p>-13.2</p>
</td>
<td>
<p>-28</p>
</td>
<td>
<p>369.6</p>
</td>
</tr>
<tr>
<td>
<p>11.8</p>
</td>
<td>
<p>22</p>
</td>
<td>
<p>259.6</p>
</td>
</tr>
<tr>
<td>
<p>32.8</p>
</td>
<td>
<p>52</p>
</td>
<td>
<p>1705.6</p>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<p>Covariance Dividend</p>
</td>
<td>
<p>2432</p>
</td>
</tr>
</tbody>
</table><!--kg-card-end: html--><p><strong>What’s missing to calculate Covariance?</strong></p><p>You’re almost done. You have the dividend, you’re missing the divisor. The divisor is just the total number of observations minus one. So let’s divide the Covariance Dividend with (N - 1):</p><!--kg-card-begin: html-->\( Cov(Microsoft,Tesla) = \frac{2432}{5-1} = \frac{2432}{4} \)
<br>\( Cov(Microsoft,Tesla) = 608 \)<!--kg-card-end: html--><p>Remember the definition? Covariance measures the direction of the comovement, in this case, between Microsoft and Tesla. So what interpretation can we get from this value? Well, we can say that, since 608 is a positive number, we conclude that there is a positive comovement between these two stock prices.</p><p>Now you ask me, How “strong” is this comovement between Microsoft and Tesla? That could be answered with the Correlation coefficient.</p><h3 id="how-to-calculate-the-correlation-coefficient">How to Calculate the Correlation coefficient?</h3><p>Once we have the Covariance value, you can remember from above, we only need the Standard Deviations from both Microsoft and Tesla. We are going to help you with those values. The Standard Deviation of both Microsoft and Tesla are 23.42 and 39.62, respectively. So applying the formula, we get:</p><!--kg-card-begin: html-->\( Cov(Microsoft,Tesla) = \frac{2432}{23.42*39.62} = \frac{2432}{928.15} \)
<br>\( Cov(Microsoft,Tesla) = 0.66 \)<!--kg-card-end: html--><p>If we choose 0.5 as our threshold to decide if a correlation value is close to 1 or close to zero, that depends on the researcher, and since 0.66 is greater than 0.5, we could say that the comovement between Microsoft and Tesla is positive and also strong.</p><h3 id="what-did-we-mean-by-degree-of-linear-association-in-the-correlation-definition">What did we mean by “degree of linear association” in the Correlation definition?</h3><p>Way before, we explained to you that Correlation measures the degree of the linear association between two variables. This explanation is the formal definition you will find in textbooks of Statistics.</p><p><em>How could you face this explanation with a simple understanding?</em><br>Let’s do that now.</p><p>We know that Correlation has a value range between -1 and +1. It could also be zero, right? Let’s graph those two extreme cases and a close-to-zero one in a scatter plot:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/perfect_positive_correlation-2.png" class="kg-image" alt="perfect_positive_correlation"></figure><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/zero_correlation-3.png" class="kg-image" alt="zero_correlation"></figure><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/perfect_negative_correlation-1.png" class="kg-image" alt="perfect_negative_correlation"></figure><p>As you can see, when Correlation is perfectly +1 or -1, the scatter plot forms itself like a line. That means both variables A and B have a linear relationship or linear association. </p><p>If the Correlation is close to one, you could say that, if you graph a line throughout the values, you will have this line with a positive slope. If the Correlation is close to -1, and if you graph a line throughout the values, you will have a line with a negative slope. As the value decreases from 1 to zero, this linear association becomes less clear, the same as the value increases from -1 to zero. </p><p>Correlation equal to zero or very close to zero means that there is no correlation at all between the two variables and you will also see for this Correlation value almost a random scatter plot. </p><p>Using our correlation definition from above, the strength of a positive correlation can be understood as the formula value tending from zero to +1. The strength of a negative correlation can be understood as the formula value tending from zero to -1.</p><p>Let’s see graphically how weak or strong correlations behave:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/strong_negative_correlation-1.png" class="kg-image" alt="strong_negative_correlation"></figure><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/weak_negative_correlation-2.png" class="kg-image" alt="weak_negative_correlation"></figure><p>You already saw what a perfectly negative Correlation looks like. Now you can see from the above graphs what strong and weak correlations might look like. The top graph shows a negative Correlation of -0.83 and the bottom graph shows a Correlation equal to -0.25. </p><p>As you can see, when the value gets close to -1, you can say that this negative Correlation is strong. However, as the Correlation approaches zero, the linear association can’t be seen clearly in the graph, and we also say that this negative correlation is weak.</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/strong_positive_correlation-1.png" class="kg-image" alt="strong_positive_correlation"></figure><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/weak_positive_correlation-1.png" class="kg-image" alt="weak_positive_correlation"></figure><p>Next, let’s see the case for positive Correlations. The top graph shows a positive Correlation of 0.84 and the bottom graph shows a Correlation equal to 0.29. As you can see, when the value gets close to 1, you can say that this positive Correlation is strong.</p><p>However, as the Correlation approaches zero, the linear association can’t be seen clearly in the graph, and we also say that this positive Correlation is weak.</p><p>We showed above a graph with a zero Correlation case. Now, you could ask us maybe, isn’t there any other form of no correlation?</p><p>Let’s see this other graph:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/non_linear_zero_correlation-1.png" class="kg-image" alt="non_linear_zero_correlation"></figure><p>As you can see, this Correlation between X and Y is zero, it has both a positive and negative linear association at the same time. So there are two types of graphs regarding a Correlation equal to zero:</p><ul><li>A random scatter plot, and</li><li>A non-linear scatter plot.</li></ul><hr><h3 id="what-are-good-covariance-and-correlation-values">What are good Covariance and Correlation values?</h3><p>Seeing the last graphs or even before, you might have asked yourself this question. You must know the answer so we’ll explain it here. Actually, there is no “good” or “perfect” value for a Covariance and Correlations function for all cases. </p><p>For example, for portfolio management, it’s a good value for the Stock Covariances to be negative, so you can have a better diversification between assets. For the independent variables in a regression estimation, you consider a good value for their Correlations to be close to zero. </p><p>For an ARMA model, you will want to have the autocorrelation functions be different from zero, in order to confirm that the construction of the model is appropriate for the stock price returns.</p><p>As you could see, a good value for our Covariance or Correlation formulas depends on what you’re looking for: It depends on the trader or the researcher, and also on the topic you are talking about.</p><hr><h2 id="covariance-and-correlation-computation-examples-in-python">Covariance and Correlation Computation Examples in Python</h2><p>Now let’s make use of real-world data to compute these two important concepts in our main programming language called Python:</p><h3 id="how-to-calculate-covariance-and-correlation-in-python">How to Calculate Covariance and Correlation in Python</h3><p>Let’s download Microsoft and Tesla Stock prices to use them for our calculations:</p><p>We first set up the environment to get things done. Don’t forget to install the ‘yfinance’ library in case you don’t have it:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/94f4cacf38a7eb2635c8c3cb7297c622.js"></script><!--kg-card-end: html--><p>Then we get daily historical data with the ‘yfinance’ API. We will download data from the year 2021 up until March 3, 2022. We also adjust the OHLC and Volume values, with their corresponding Adjusted Close, setting to True to the auto_adjust condition. </p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/e6758066a3d2e2f56cbf3d2033bc4a22.js"></script><!--kg-card-end: html--><p>Next, we calculate the Covariance and Correlation for the whole sample period:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/063d81b04053b56267f0fe43119eed56.js"></script><!--kg-card-end: html--><p>Here's the output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/05/covariance-correlation-table-1.png" class="kg-image" alt="covariance correlation table 1"></figure><p>Here we have to explain something about this output. As you can see, both for the Covariance and Correlation there is a table for each one.</p><p>The special tables you see are actually a Covariance Matrix for the above matrix and the Correlation matrix for the below matrix. You will have in the Covariance matrix diagonal the Variances, which are 1312.74 and 26796.55 for Microsoft and Tesla respectively. The matrix lower triangular should be a mirror of the upper triangular, meaning it should have the same values. </p><p>The same for the Correlation matrix shown below. The Correlation matrix diagonal represents the Correlation function applied not with another variable, but with the same one. We mean, for the Matrix(1,1), it is a correlation function applied with the Microsoft Stock Price against the same Stock Price, Corr(Microsoft,Microsoft). </p><p>You can prove that we leave you this as an exercise when you apply a Correlation function only with one Stock price, you will always get +1 as value. These <a href="https://blog.quantinsti.com/calculating-covariance-matrix-portfolio-variance/">Covariance and Correlation matrices</a> could be deployed for more than two variables too, and they will follow the same properties as per the lines above explained.</p><p>Once you understand what we just explained, we can go to our final Covariance and Correlation computations:</p><h3 id="how-to-calculate-the-rolling-covariances-and-correlations-in-python-">How to Calculate the Rolling Covariances and Correlations in Python.</h3><p>As we explained before, Correlation and Covariance could change in value as time passes. That’s why it’s essential to calculate Correlation or Covariance throughout time. One way to do this is by calculating the rolling Covariances and Correlations for our Microsoft and Tesla Stock Prices. </p><p>We mean rolling here in the sense that, specifying first a number of days called “n”, you will get both the Covariance and the Correlation functions applied for each day with “n” previous days as the history data window to estimate them. </p><p>It’s super simple. Just pay attention to the following. Since you know that the pandas properties called “.cov” and “.corr” get you a matrix, you might guess that if you applied a rolling Covariance and Correlation functions you will also get a matrix for each day. </p><p>In order to avoid getting the whole matrix for each day, you extend each property called by unstacking them and, then, calling, for both functions, the Covariance and Correlation functions between MSFT and TSLA only. We want to set as the historical data for each observation a 20-day window to calculate the functions, a monthly window. See below:</p><!--kg-card-begin: html--><script src="https://gist.github.com/quantra-go-algo/55fa687b3f672782664607930c124f00.js"></script><!--kg-card-end: html--><p>Here's the output:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/05/covariance--correlation-dataframe-2.png" class="kg-image" alt="covariance  correlation dataframe 2"></figure><p>Now let’s see graphically how Covariance and Correlation look throughout time:</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/rolling_covariance.png" class="kg-image" alt="rolling_covariance"></figure><figure class="kg-card kg-image-card kg-width-full"><img src="https://d1rwhvwstyk9gu.cloudfront.net/2022/04/rolling_correlation.png" class="kg-image" alt="rolling_correlation"></figure><p>As we told you before, you can see that both Covariance and Correlation change throughout time. There are some periods where Microsoft and Tesla move in the same direction, while there are other periods where they move in the opposite direction.</p><p>Be careful and be patient when trading! <a href="https://quantra.quantinsti.com/glossary/Risk-Management-System">Risk management</a> is something valuable in order to trade well in the financial markets!</p><hr><h3 id="conclusion">Conclusion</h3><p>Now, you have a better understanding of what these two concepts mean. This article also made you knowledgeable about the intricacies of the formulas. You not only know that but also comprehend how to apply Covariance or Correlation in Trading.</p><p><em>You are almost there to press the BUY button</em>. It’s time now to start learning strategies in which you can potentially use these two concepts without any problem. </p><p>So, do you want to start trading with more than one asset and use the Correlation and Covariance formulas? Why not? You can enroll into our course <a href="https://quantra.quantinsti.com/course/quantitative-portfolio-management">Quantitative Portfolio Management</a> so you could start using these concepts now!</p><p>Are you ready? Go Algo!</p><hr><h3 id="file-in-the-download-">File in the download:</h3><p><strong>Covariance vs Correlation - Python Notebook</strong></p><!--kg-card-begin: html--><p style="text-align: center;"><a href="https://blog.quantinsti.com/covariance-correlation" class="download-button button"> Visit blog to download </a></p><!--kg-card-end: html--><hr><!--kg-card-begin: html--><p><em><small>Disclaimer: All investments and trading in the stock market involve risk. Any decision to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.</small></em></p><!--kg-card-end: html-->]]></content:encoded></item></channel></rss>