al correlation between the two stocks: their price movement seems to have similar ups and downs.</p><h2 id="7a9f">3. Regression Analysis</h2><p id="2523">Let’s do a regression analysis to further our correlation analysis between these two stocks: To do so, we use the NumPy log method to calculate the logarithmic returns for both stocks and assign them variable returns:</p>
<figure id="bc40">
<div>
<div>
<iframe class="gist-iframe" src="/gist/khuonglan/96787acc08ff8e0a1f420f81a11b463d.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><figure id="02f0"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*UqY-GgwdfZQrwJhA2mbu_w.png"><figcaption></figcaption></figure><p id="5652">We can observe some similarities again in the volatility patterns.</p><p id="f0e9">Let’s perform the regression analysis.</p><p id="0091">To do so, we will use the polyfit and polyval methods.</p>
<figure id="bf55">
<div>
<div>
<iframe class="gist-iframe" src="/gist/khuonglan/280d470c8684f1631d35e4839f8f5477.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><figure id="5314"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*62jnzp0-8Kp_EoHddID4tQ.png"><figcaption>Image by the author</figcaption></figure><p id="b08f">The slope of the regression line is positive, lending support to the above-mentioned postulate of a positive correlation between BA and MDT.</p><h2 id="2852">4. Rolling and Static Correlation</h2><p id="61fd">In statistics, we frequently want to know how two variables are related to one another.</p><p id="8bcd">The Pearson correlation coefficient, which is a measure of the linear association between two variables, is one of the most common ways we quantify a relationship between two variables in statistics.</p><p id="b90a">It has a value between -1 and 1 and is calculated as follows:</p><ul><li>-1 denotes a perfectly negative linear correlation between two variables.</li><li>0 indicates that there is no linear correlation between two variables.</li><li>1 denotes a perfectly positive linear correlation between two variables.</li></ul><p id="27b5">Let’s see for our case here the static correlation using the .corr method. It said static as it analyzes it for the entire dataset:</p>
<figure id="ec15">
<div>
<div>
<iframe class="gist-iframe" src="/gist/khuonglan/263ecb28546daad3cf5b63f0ad013118.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><figure id="9042"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*63GVN32xp9dxTN7m3dDEZQ.png"><figcaption>Image by the author</figcaption></figure><p id="77ad">We have a 0.46 static correlation. This is considered as a weak correlation as 0.5–0.7 is moderate and greater than 0.7 is strong.</p><p id="b83a">Let’s focus now on the rolling correlation using the .rolling method.</p><p id="b66d">A rolling correlation is looking at a fixed window over time. We will also plot the static correlation line in orange we calculated just before.</p>
<figu
Options
re id="45f2">
<div>
<div>
<iframe class="gist-iframe" src="/gist/khuonglan/ac67a476ddb493c31456034c45b416b4.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><figure id="256a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*H870ZJ9sewKkvM-bEpZqVA.png"><figcaption></figcaption></figure><p id="5452">We can observe that the rolling correlation is positive most of the times. However, there are some periods where it is negative. This is aligned with the 0.46 static correlation which is close to moderate level.</p><p id="7574">Based on these elements, we can conclude that the stock prices of Boeing and Medtronic have a low correlation and present a lower risk of similar stock price patterns occurring at the same time.</p><h2 id="c619">Conclusion</h2><p id="4518">It is critical to be cautious and diligent when selecting stocks for your portfolio. With just a few lines of Python code, you can determine whether or not there is a strong correlation between different stocks. This will help your portfolio in times like the current bear market by preventing all of your stocks from falling at the same time.</p><div id="f2b2" class="link-block">
<a href="https://medium.com/@Eyquem/membership">
<div>
<div>
<h2>Join Medium with my referral link - Khuong Lân Cao Thai</h2>
<div><h3>Read every story from Khuong Lân Cao Thai (and thousands of other writers on Medium). Your membership fee directly…</h3></div>
<div><p>medium.com</p></div>
</div>
<div>
<div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*vl8gPEQ7fcmsXY39)"></div>
</div>
</div>
</a>
</div><p id="2a3f">For more of these, get my free weekly newsletter “The Mindful Data Path”.</p><p id="147e"><a href="https://themindfuldatapath.beehiiv.com/">Posts | The Mindful Data Path (beehiiv.com)</a></p><p id="92e2">Each week, I simplify a finance topic. I make you practice Data Science with me. I give you one mindful look at one piece of data.</p><p id="9884">References:</p><p id="8d4d"><a href="https://www.investopedia.com/articles/financial-theory/09/uncorrelated-assets-diversification.asp#:~:text=When%20it%20comes%20to%20diversified,prices%20move%20in%20opposite%20directions.">Protecting Portfolios Using Correlation Diversification (investopedia.com)</a></p><p id="079c"><a href="https://readmedium.com/how-to-perform-correlation-analysis-on-stock-data-with-python-d5609ab9f46c">How to Perform Correlation Analysis on Stock Data with Python | by Bee Guan Teo | Python in Plain English (medium.com)</a></p><p id="85d7"><a href="https://readmedium.com/how-to-expand-your-correlation-matrix-plot-options-in-python-12eedb188a3c">How to Expand Your Correlation Matrix Plot Options In Python | by Khuong Lân Cao Thai | Sep, 2022 | Python in Plain English (medium.com)</a></p><p id="cfe9">Subscribe to DDIntel <a href="https://ddintel.datadriveninvestor.com/">Here</a>.</p><p id="c295">Visit our website here: <a href="https://www.datadriveninvestor.com/">https://www.datadriveninvestor.com</a></p><p id="6a93">Join our network here: <a href="https://datadriveninvestor.com/collaborate">https://datadriveninvestor.com/collaborate</a></p></article></body>
How to Assess the Correlation of Stock Prices to Protect Your Portfolio
This is crucial to minimize it. Let’s see how to do this in Python with Boeing and Medtronic stocks.
If you are into finance and trading, or just want to protect your portfolio from the risk of losing it all, then you need to know how to assess the correlation of stock data.
The last thing you want is for your portfolio to have stock that moves in correlation with one another — especially if they are actually negative correlated stocks.
That’s precisely this correlation you need to know how to calculate it in Python so you can make your choices accordingly.
Disclaimer: This blog post is written only for educational purposes. There is no investment advice or promotion for any stock.
1. Concrete Use Case: Boeing and Medtronic
You are looking for stocks to invest in and are drawn to Boeing and Medtronic. Boeing manufactures airplanes, while Medtronic manufactures medical devices and provides healthcare. You chose two industries and believe you have diversified your portfolio.
But is it the case? Let’s check it.
You need first to retrieve the stock data for both companies. As per my previous blog posts, let’s import yfinance and other needed libraries:
To retrieve Boeing and Medtronic stock data, we will use their tickers:
Extract
2. Plotting Stock Prices Changes and Returns
Visualizing data is always helpful so let’s plot Boeing and Medtronic stock data:
We can see from the plot that there is a visual correlation between the two stocks: their price movement seems to have similar ups and downs.
3. Regression Analysis
Let’s do a regression analysis to further our correlation analysis between these two stocks: To do so, we use the NumPy log method to calculate the logarithmic returns for both stocks and assign them variable returns:
We can observe some similarities again in the volatility patterns.
Let’s perform the regression analysis.
To do so, we will use the polyfit and polyval methods.
Image by the author
The slope of the regression line is positive, lending support to the above-mentioned postulate of a positive correlation between BA and MDT.
4. Rolling and Static Correlation
In statistics, we frequently want to know how two variables are related to one another.
The Pearson correlation coefficient, which is a measure of the linear association between two variables, is one of the most common ways we quantify a relationship between two variables in statistics.
It has a value between -1 and 1 and is calculated as follows:
-1 denotes a perfectly negative linear correlation between two variables.
0 indicates that there is no linear correlation between two variables.
1 denotes a perfectly positive linear correlation between two variables.
Let’s see for our case here the static correlation using the .corr method. It said static as it analyzes it for the entire dataset:
Image by the author
We have a 0.46 static correlation. This is considered as a weak correlation as 0.5–0.7 is moderate and greater than 0.7 is strong.
Let’s focus now on the rolling correlation using the .rolling method.
A rolling correlation is looking at a fixed window over time. We will also plot the static correlation line in orange we calculated just before.
We can observe that the rolling correlation is positive most of the times. However, there are some periods where it is negative. This is aligned with the 0.46 static correlation which is close to moderate level.
Based on these elements, we can conclude that the stock prices of Boeing and Medtronic have a low correlation and present a lower risk of similar stock price patterns occurring at the same time.
Conclusion
It is critical to be cautious and diligent when selecting stocks for your portfolio. With just a few lines of Python code, you can determine whether or not there is a strong correlation between different stocks. This will help your portfolio in times like the current bear market by preventing all of your stocks from falling at the same time.