Lesson 15 · Real-World Data Analytics
Correlation Matrix & Diversification in Python: Stocks vs Market | Data Analytics #15
Does diversification really reduce risk? We add three more stocks and a market index, build a correlation matrix and heatmap in pandas, calculate each…
- CourseReal-World Data Analytics
- Lesson15 of 100
- FormatJupyter notebook · 30 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- multi_stock_2007.csv preview55.7 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 15: Correlation and Diversification Across Real Assets#
- Video fifteen of the hundred-video real-world data analytics series.
- Bringing in three more real stocks and a real market index to actually test what diversification does to real risk.
- Let's get into it.
This lesson is for learners who have analysed a two-stock portfolio and want to see how diversification works with more assets and a market benchmark. The business question: if you spread money across several stocks, how much risk actually disappears, which stocks move most with the market, and does the diversified mix beat simply holding the index?
The data is multi_stock_2007.csv, a long-format file with one row per stock per date and columns Date, stock and value (the price). It covers 2007 for four stocks, Microsoft (MSFT), IBM (IBM), Starbucks (SBUX) and Apple (AAPL), plus GSPC, the ticker for the S&P 500 index, which stands in for the overall market.
In this lesson you will:
- Reshape long data to wide with
pivotand compute returns for every asset - Read a correlation matrix and heatmap, and find the least correlated pair
- Calculate beta, each stock's sensitivity to the market
- Measure the diversification benefit of an equal-weight portfolio using the matrix form of portfolio variance
Prerequisites: you should be comfortable with daily returns, annualised volatility and the two-asset portfolio maths from earlier lessons in this domain.
Part 1: Beyond Just Two Assets#
Two assets show the idea of diversification, but real portfolios hold many, so you now bring in more stocks and a market index. The code reads multi_stock_2007.csv with parse_dates=['Date'] and calls .unique() on the stock column to list the distinct tickers. The output shows five: MSFT, IBM, SBUX, AAPL and GSPC, the S&P 500 index. Listing unique values is a fast way to understand a long-format file, where each row is one stock on one date rather than one date with every stock.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
raw = pd.read_csv('multi_stock_2007.csv', parse_dates=['Date'])
raw['stock'].unique()
Part 2: Real Long-to-Wide Reshape#
Most return and correlation calculations need one column per asset and one row per date, called wide format. raw.pivot(index='Date', columns='stock', values='value') reshapes the data so dates become the index, each ticker becomes a column and the prices fill the cells. .sort_index() puts dates in order. The output shape is (220, 5): 220 dates and 5 assets. If the same stock and date appeared twice, pivot would raise an error, which is a useful built-in duplicate check.
wide = raw.pivot(index='Date', columns='stock', values='value')
wide = wide.sort_index()
wide.shape
Part 3: Real Missing-Day Cleanup#
After pivoting, any date where one asset is missing a price shows as NaN, and that would break returns and correlations. The code first counts missing values per column with wide.isna().sum(), though only the last line is displayed, then drops incomplete rows with .dropna(). The output shape is (219, 5), so exactly one date was removed. Run the isna().sum() line on its own to see which asset was missing. With only one row affected, dropping is safe; with many gaps, you might fill them instead.
wide.isna().sum()
wide_clean = wide.dropna()
wide_clean.shape
Part 4: Real Daily Returns for Every Asset#
Returns, not prices, are what you compare across assets, since a 100 dollar stock and a 1,500 point index cannot be compared directly. pct_change() works on every column at once, and .dropna() removes the first row, which has no previous day. Only head(3) is displayed: on 2007-01-04, Apple rose 2.22% while the S&P 500 rose just 0.12%. On 2007-01-05 every asset fell, a reminder that stocks often move together on market-wide news.
returns = wide_clean.pct_change().dropna()
returns.shape
returns.head(3).round(4)
Part 5: Real Individual Volatility Comparison#
Volatility shows how risky each asset is on its own before you combine them. The code takes each column's .std() and multiplies by np.sqrt(252) to annualise, then sorts from highest to lowest with sort_values(ascending=False). The output shows Apple was by far the riskiest at 38.9%, followed by Microsoft at 22.7%, Starbucks 22.2% and IBM 19.9%, with the S&P 500 lowest at 15.3%. The index is calmer than any single stock because it is already a diversified basket of 500 companies.
annualized_vol = returns.std() * np.sqrt(252)
annualized_vol.round(3).sort_values(ascending=False)
Part 6: Real Correlation Matrix#
A correlation matrix shows how every pair of assets moves together in one table, from -1 to +1. returns.corr() builds it, with 1.000 along the diagonal because each asset is perfectly correlated with itself. The output shows all pairs are positive, from 0.305 for Apple and Starbucks to 0.644 for Microsoft and the S&P 500. Every stock correlates more with the index than with most other single stocks. The matrix is symmetric, so you only need to read one half of it.
corr_matrix = returns.corr()
corr_matrix.round(3)
Part 7: Visualizing the Real Correlation Matrix#
A heatmap turns the correlation matrix into colours, which makes patterns easier to spot with more assets. plt.imshow draws the matrix with the coolwarm colour map, and vmin=-1, vmax=1 fixes the scale so 0 sits in the neutral middle. The tick calls label each row and column with the tickers and colorbar adds a legend. The chart is saved to correlation_heatmap.png. When you open it, expect warm tones everywhere, since all correlations are positive, with the strongest colours in the GSPC row and column.
plt.figure(figsize=(7, 6))
im = plt.imshow(corr_matrix, cmap='coolwarm', vmin=-1, vmax=1)
plt.xticks(range(len(corr_matrix.columns)), corr_matrix.columns, rotation=45)
plt.yticks(range(len(corr_matrix.columns)), corr_matrix.columns)
plt.colorbar(im, label='Real Correlation')
plt.title('Real Correlation Matrix, Five Real Assets')
plt.tight_layout()
plt.savefig('correlation_heatmap.png', dpi=120)
plt.close()
Part 8: Real Most and Real Least Correlated Pair#
To find the extremes, you need each pair once, without the diagonal or duplicates. np.triu(np.ones(...), k=1) builds a mask of the upper triangle above the diagonal, .where() keeps only those cells, and .stack() turns them into a list of pairs. The code computes both the most and least correlated pair, but only the last line is displayed: Apple and Starbucks, at 0.305, are the least correlated. Run the idxmax() line on its own to see the most correlated pair, which the matrix shows is Microsoft and the S&P 500.
corr_pairs = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool)).stack()
corr_pairs.idxmax(), round(corr_pairs.max(), 3)
corr_pairs.idxmin(), round(corr_pairs.min(), 3)
Part 9: Real Market Beta for Each Stock#
Beta measures how much a stock tends to move when the market moves. A beta of 1 means it moves in line with the market, above 1 means bigger swings, and below 1 means smaller ones. The code calculates it as the covariance of each stock with GSPC divided by the market's variance, using .cov() and .var() in a loop. The output shows Apple at 1.243, Microsoft 0.951, Starbucks 0.843 and IBM 0.715. So a 1% market move was typically associated with about a 1.24% move in Apple.
market_var = returns['GSPC'].var()
betas = {}
for ticker in ['AAPL', 'MSFT', 'IBM', 'SBUX']:
cov_with_market = returns[ticker].cov(returns['GSPC'])
betas[ticker] = cov_with_market / market_var
pd.Series(betas).round(3).sort_values(ascending=False)
Part 10: Interpreting Real Beta Values#
Putting labels on the extremes makes beta practical. The code turns the betas dictionary into a Series and uses idxmax() and idxmin() to return the tickers with the highest and lowest values. The output confirms Apple has the highest beta and IBM the lowest. In plain terms, Apple was the aggressive holding that amplified market moves, while IBM was the defensive one. Remember beta measures market-linked risk; a low-beta stock can still be volatile for company-specific reasons.
high_beta_stock = pd.Series(betas).idxmax()
low_beta_stock = pd.Series(betas).idxmin()
high_beta_stock, low_beta_stock
Part 11: Building a Real Equal-Weight Portfolio#
An equal-weight portfolio, 25% in each of the four stocks, is the simplest diversified mix and a good baseline. Because the weights are equal, the portfolio's daily return is just the average across the four columns, which mean(axis=1) computes row by row. The output shows the portfolio gained 0.81% on 2007-01-04, fell 0.65% on 2007-01-05 and rose 0.66% on 2007-01-08. Note axis=1 averages across columns; the default axis=0 would average down each column instead. This also assumes daily rebalancing back to equal weights.
stock_cols = ['AAPL', 'MSFT', 'IBM', 'SBUX']
portfolio_returns = returns[stock_cols].mean(axis=1)
portfolio_returns.head(3).round(4)
Part 12: Real Portfolio Volatility vs Real Individual Volatility#
This is the moment that shows diversification working. The code annualises the portfolio's volatility and each stock's volatility and displays them together, with .to_dict() making the stock figures compact. The output shows the portfolio at 19.6%, lower than Apple (38.9%), Microsoft (22.7%) and Starbucks (22.2%), and even slightly below IBM (19.9%), the calmest single stock. Combining four imperfectly correlated stocks produced a mix less risky than any one of them.
portfolio_vol = portfolio_returns.std() * np.sqrt(252)
individual_vols = returns[stock_cols].std() * np.sqrt(252)
round(portfolio_vol, 3), individual_vols.round(3).to_dict()
Part 13: Quantifying the Real Diversification Benefit#
A single percentage makes the benefit easy to communicate. The code compares the portfolio's volatility with the simple average of the four individual volatilities, using 1 - portfolio_vol / average_individual_vol, and converts to a percentage. The output shows a 24.5% risk reduction. If all four stocks were perfectly correlated, this figure would be zero; the reduction comes entirely from them not moving in lockstep.
average_individual_vol = individual_vols.mean()
diversification_benefit_pct = (1 - portfolio_vol / average_individual_vol) * 100
round(diversification_benefit_pct, 1)
Part 14: Visualizing Real Portfolio vs Real Individual Growth#
Lower risk is only half the story: you also want to see how the portfolio's growth compares with its parts. The code compounds daily returns with (1 + returns).cumprod() for the portfolio and each stock, plots the stocks semi-transparent with alpha=0.5 in a loop, and draws the portfolio as a thick black line. The chart is saved to diversification_growth.png. When you open it, look for the black line sitting in the middle of the pack with noticeably smaller wiggles than the individual stocks.
cumulative_portfolio = (1 + portfolio_returns).cumprod()
cumulative_individual = (1 + returns[stock_cols]).cumprod()
plt.figure(figsize=(11, 6))
for ticker in stock_cols:
plt.plot(cumulative_individual.index, cumulative_individual[ticker], alpha=0.5, label=f'Real {ticker}')
plt.plot(cumulative_portfolio.index, cumulative_portfolio, color='black', linewidth=2.5, label='Real Equal-Weight Portfolio')
plt.xlabel('Real Date')
plt.ylabel('Real Growth of $1 Invested')
plt.title('Real Diversified Portfolio vs Real Individual Stocks')
plt.legend()
plt.tight_layout()
plt.savefig('diversification_growth.png', dpi=120)
plt.close()
Part 15: Real Portfolio vs Real Market Index#
Any stock-picking approach should be judged against the market, because holding the index is the easy alternative. The code compounds the S&P 500's daily returns and compares the final values. The output shows 1 dollar in the equal-weight portfolio grew to 1.171 in 2007, a 17.1% gain, while the market grew to 1.045, a 4.5% gain. This is one year and four large technology and consumer names, so it is not evidence that the approach will beat the market in general.
cumulative_market = (1 + returns['GSPC']).cumprod()
round(cumulative_portfolio.iloc[-1], 3), round(cumulative_market.iloc[-1], 3)
Part 16: Real Sharpe Ratio Comparison#
To compare return and risk together, you use the Sharpe ratio: annualised return divided by annualised volatility, with no risk-free rate subtracted here. The code calculates it for the portfolio and for GSPC. The output shows the portfolio at 1.033 and the market at 0.412. So the portfolio earned more than twice as much return per unit of risk as the index over this period. A Sharpe above 1 is generally considered strong, but a single year is a short sample.
portfolio_sharpe = (portfolio_returns.mean() * 252) / portfolio_vol
market_sharpe = (returns['GSPC'].mean() * 252) / (returns['GSPC'].std() * np.sqrt(252))
round(portfolio_sharpe, 3), round(market_sharpe, 3)
Part 17: Real Rolling Correlation with the Market#
Correlation with the market is not fixed: it tends to rise during stress, just when you want diversification most. rolling(30).corr(...) computes the correlation of each stock with GSPC over every 30-day window. Both Apple and IBM are computed, but only Apple's summary is displayed. It covers 189 windows, with a mean of 0.419 and a range from 0.040 to 0.785. So Apple's link to the market swung from almost none to very strong within the same year.
rolling_corr_aapl = returns['AAPL'].rolling(30).corr(returns['GSPC'])
rolling_corr_ibm = returns['IBM'].rolling(30).corr(returns['GSPC'])
rolling_corr_aapl.dropna().describe().round(3)
Part 18: Visualizing Real Rolling Market Correlation#
A chart shows when correlations rose and fell together. The code plots Apple's and IBM's 30-day rolling correlation with the market and adds a dashed zero line with axhline(0). The figure is saved to rolling_market_correlation.png. When you open it, look for periods where both lines rise at the same time, which often point to market-wide events, and compare IBM's line with Apple's, since IBM is the stock you did not see summarised.
plt.figure(figsize=(11, 5))
plt.plot(rolling_corr_aapl.index, rolling_corr_aapl, label='Real Apple vs Market')
plt.plot(rolling_corr_ibm.index, rolling_corr_ibm, label='Real IBM vs Market')
plt.axhline(0, color='gray', linestyle='--')
plt.xlabel('Real Date')
plt.ylabel('Real 30-Day Rolling Correlation')
plt.title('Real Rolling Correlation with the Market Index')
plt.legend()
plt.tight_layout()
plt.savefig('rolling_market_correlation.png', dpi=120)
plt.close()
Part 19: Real Weighted Portfolio Variance, More Than Two Assets#
With two assets you wrote out the variance formula by hand; with many assets the matrix form scales neatly. The code sets equal weights of 0.25, builds the annualised covariance matrix with .cov() * 252, and computes weights @ cov_matrix.values @ weights, where @ is matrix multiplication. This single line includes every variance and covariance term. The square root of the result is compared with the portfolio volatility from earlier, and the output is True, confirming both methods agree to three decimals.
weights = np.array([0.25, 0.25, 0.25, 0.25])
cov_matrix = returns[stock_cols].cov() * 252
portfolio_variance = weights @ cov_matrix.values @ weights
round(np.sqrt(portfolio_variance), 3) == round(portfolio_vol, 3)
Part 20: Real Minimum-Correlation Two-Stock Pair#
If correlation drives diversification, the least correlated pair of stocks should be a good two-stock combination. The code repeats the upper-triangle trick on the four stocks only, leaving out the index, and finds the minimum with idxmin(). The output shows Apple and Starbucks again, at 0.305. This makes sense: a technology company and a coffee chain are driven by quite different business factors.
stock_corr = returns[stock_cols].corr()
stock_corr_pairs = stock_corr.where(np.triu(np.ones(stock_corr.shape), k=1).astype(bool)).stack()
best_pair = stock_corr_pairs.idxmin()
best_pair, round(stock_corr_pairs.min(), 3)
Part 21: Real Two-Stock Minimum-Correlation Portfolio#
Now test how well that low-correlation pair diversifies on its own. The code takes the equal-weight average of Apple and Starbucks returns with mean(axis=1) and annualises its volatility. The output is 25.2%. That is well below Apple alone at 38.9%, but above Starbucks alone at 22.2%, because half the money is still in the very volatile Apple. Low correlation helps, but the volatility of each holding still matters.
pair_returns = returns[list(best_pair)].mean(axis=1)
pair_vol = pair_returns.std() * np.sqrt(252)
round(pair_vol, 3)
Part 22: Real Number of Assets vs Real Risk Reduction#
Putting the numbers side by side shows how risk changes as you add holdings. The output lists the average single-stock volatility at about 0.259, the two-stock pair at about 0.252, and the four-stock portfolio at about 0.196. The pair barely improves on the average single stock, because it contains Apple, while going to four stocks cuts risk much further. Comparisons like this are approximate, since the result depends on which stocks you pick, not only how many.
one_stock_vol = individual_vols.mean()
two_stock_vol = pair_vol
four_stock_vol = portfolio_vol
one_stock_vol, two_stock_vol, four_stock_vol
Part 23: Saving the Real Multi-Asset Summary Table#
A compact summary table is useful for reports and later lessons. The code builds a DataFrame with annualised volatility and beta for each asset; .reindex(annualized_vol.index) lines the betas up with the volatility rows, which leaves a blank beta for GSPC since the index was not given one. The table is saved with its index so the tickers are kept, then reloaded with index_col=0. The output is True, confirming the row count matches.
summary = pd.DataFrame({'AnnualizedVol': annualized_vol, 'Beta': pd.Series(betas).reindex(annualized_vol.index)})
summary.round(3).to_csv('multi_asset_summary.csv')
reloaded = pd.read_csv('multi_asset_summary.csv', index_col=0)
reloaded.shape[0] == summary.shape[0]
Part 24: Real Correlation Matrix Export#
Exporting the correlation matrix lets you reuse it in a spreadsheet or dashboard. The code rounds to four decimals, writes it with the index so row labels are kept, and reloads it with index_col=0 so those labels become the index again. Comparing .shape with the original returns True, confirming the 5 by 5 matrix survived intact. Forgetting index_col=0 on reload is a common mistake that adds an extra unnamed column.
corr_matrix.round(4).to_csv('correlation_matrix.csv')
reloaded_corr = pd.read_csv('correlation_matrix.csv', index_col=0)
reloaded_corr.shape == corr_matrix.shape
Part 25: Real Sanity Check on Correlation Bounds#
Correlations must lie between -1 and 1, and the diagonal must be exactly 1. The code checks both, but only the last expression is displayed. np.diag pulls the diagonal values and np.allclose(..., 1.0) confirms they are all 1 within a tiny tolerance; the output is True. The bounds check uses 1.0001 rather than 1 to allow for floating-point rounding. Run that line separately to see its result too.
(corr_matrix.values >= -1.0001).all() and (corr_matrix.values <= 1.0001).all()
np.allclose(np.diag(corr_matrix.values), 1.0)
Part 26: Real Recap Print#
A one-sentence summary captures the headline finding. The f-string reports the number of stocks with len(stock_cols), the average and portfolio volatilities as percentages, and the reduction. The output reads: combining 4 stocks cut annualised volatility from a 25.9% average to 19.6%, a 24.5% risk reduction. These figures match the earlier steps, so the story is consistent from start to finish.
print(f'Combining {len(stock_cols)} real stocks cut annualized volatility from {round(average_individual_vol*100,1)}% average to {round(portfolio_vol*100,1)}%, a real {round(diversification_benefit_pct,1)}% risk reduction.')
Part 27: Real Portfolio Drawdown vs Real Market Drawdown#
Volatility is not the whole risk picture; the worst peak-to-trough fall matters to investors too. The max_drawdown function tracks the highest value so far with .cummax(), measures each day's fall from that peak and returns the deepest. The output shows a maximum drawdown of -13.46% for the portfolio and -9.43% for the market. So although the portfolio had a better return and Sharpe ratio, it went through a deeper slump than the index, a trade-off worth mentioning to anyone choosing between them.
def max_drawdown(cumulative):
running_peak = cumulative.cummax()
drawdown = (cumulative - running_peak) / running_peak
return drawdown.min()
round(max_drawdown(cumulative_portfolio) * 100, 2), round(max_drawdown(cumulative_market) * 100, 2)
Part 28: Real Skewness and Kurtosis of Returns#
Volatility assumes returns are roughly bell-shaped, which is often not true. Skewness measures lopsidedness and kurtosis measures how heavy the tails are, meaning how often extreme days occur. The code computes both, but only kurtosis is displayed. pandas reports excess kurtosis, where 0 matches a normal distribution. The output shows Microsoft at 8.262, IBM 2.988, Apple 2.184 and Starbucks 0.615. Microsoft had far more extreme days than a bell curve would predict, which standard deviation alone understates.
returns[stock_cols].skew().round(3)
returns[stock_cols].kurtosis().round(3)
Part 29: Real Days Each Stock Beat the Market#
Counting days a stock beats the index is a simple, intuitive measure of relative performance. A dictionary comprehension compares each stock's return with GSPC row by row and sums the Trues. The output shows Apple beat the market on 119 days, IBM 117, Microsoft 108 and Starbucks 75, out of 218 trading days with returns. Starbucks beat the market on just over a third of days, so Apple and IBM did most of the work in lifting the portfolio.
beat_market = {ticker: (returns[ticker] > returns['GSPC']).sum() for ticker in stock_cols}
pd.Series(beat_market).sort_values(ascending=False)
Part 30: Real Best and Worst Single Day for the Portfolio#
Extreme days show what the portfolio actually felt like to hold. The code uses idxmax() and idxmin() on the portfolio returns to find the dates, and .max() and .min() for the sizes. The output shows the best day was 2007-11-13 at +5.39% and the worst was 2007-11-09 at -4.43%. Both fall in the same week in November 2007, a clear example of volatility clustering: big moves tend to arrive close together.
port_best_day = portfolio_returns.idxmax()
port_worst_day = portfolio_returns.idxmin()
port_best_pct = round(portfolio_returns.max() * 100, 2)
port_worst_pct = round(portfolio_returns.min() * 100, 2)
port_best_day, port_best_pct, port_worst_day, port_worst_pct
Wrap-Up: What You Learned#
- Correlation measures how real assets genuinely move together, and low correlation is exactly what makes diversification work.
- Beta measures how much a real stock swings relative to the real broader market, a different lens on risk than volatility alone.
- Combining real assets into a portfolio reduces total volatility below the real average of the individual pieces, purely from imperfect correlation.
- The real matrix form of portfolio variance generalizes cleanly beyond just two assets to any real number of holdings.
- More real assets is not automatically better, the real correlation between them matters just as much as the real count.
- Next video: turning these real indicators and real risk metrics into an actual backtested real trading strategy.
Practice on your own
- Build a portfolio from the three lowest-beta stocks, Microsoft, Starbucks and IBM, and compare its volatility, Sharpe ratio and maximum drawdown with the four-stock mix.
- Print the result of the skewness line on its own, then check whether the stock with the most negative skew also had the worst single day.
- Weight the four stocks by the inverse of their volatility (
1 / individual_vols, normalised to sum to 1) and use the matrix formula to see whether you can beat the 19.6% equal-weight volatility.
The next lesson turns these indicators and risk metrics into an actual backtested trading strategy.
🧠 Test yourself
Pick an answer to check it. Your best score is saved in this browser.
In the lesson, the beta of a stock is computed as...
Beta is covariance with the market divided by the market's variance. It measures how much a stock moves per unit of market move.
A stock has covariance 0.0003 with the market, and the market's variance is 0.0002. What is its beta?
Beta = 0.0003 / 0.0002 = 1.5, so the stock tends to move about 1.5 times as much as the market.
Two stocks each have 20% annual volatility and correlation 0.5. What is the volatility of a 50/50 portfolio?
Variance = 0.25*0.04 + 0.25*0.04 + 2*0.25*0.5*0.04 = 0.03, so volatility is sqrt(0.03), about 17.3%. Correlation below 1 reduces risk.
What does
raw.pivot(index='Date', columns='stock', values='value')do in this lesson?The raw file has one row per date and stock. pivot gives a wide table with dates as rows and each stock as a column, ready for pct_change and corr.
The lesson checks
weights @ cov_matrix.values @ weights. What does it compute?The matrix form w'Σw sums every weighted variance and covariance term, which generalizes the two-asset formula to any number of holdings.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
Given returns of two assets A = [0.01, 0.02, -0.01, 0.00, 0.015] and B = [0.012, 0.018, -0.008, 0.002, 0.01], compute the correlation between them and print it rounded to 3 decimals.
💡 Hint
Put the lists in a DataFrame and call .corr().
✅ Show solution
import pandas as pd df = pd.DataFrame({ 'A': [0.01, 0.02, -0.01, 0.00, 0.015], 'B': [0.012, 0.018, -0.008, 0.002, 0.01], }) print(df.corr().round(3)) print(round(df['A'].corr(df['B']), 3))
Simulate 250 daily returns for a market (seed 1, normal mean 0.0003 std 0.01) and a stock built as 1.3 * market + noise (noise normal with std 0.005, seed 2). Compute the stock's beta as cov / var and print it. It should be close to 1.3.
💡 Hint
beta = stock.cov(market) / market.var().
✅ Show solution
import numpy as np import pandas as pd market = pd.Series(np.random.default_rng(1).normal(0.0003, 0.01, 250)) noise = np.random.default_rng(2).normal(0, 0.005, 250) stock = 1.3 * market + noise beta = stock.cov(market) / market.var() print(round(beta, 3))
Simulate 300 days of returns for 4 stocks with seed 4: each is a common market factor (normal std 0.008) plus its own noise (normal std 0.01). Compute the correlation matrix, the most-correlated pair, annualized vol of each stock, annualized vol of the equal-weight portfolio, and the diversification benefit as (1 - portfolio vol / average individual vol) * 100.
💡 Hint
Use np.triu with k=1 to pick each pair once, then stack().
✅ Show solution
import numpy as np import pandas as pd rng = np.random.default_rng(4) market = rng.normal(0, 0.008, 300) cols = ['S1', 'S2', 'S3', 'S4'] returns = pd.DataFrame({c: market + rng.normal(0, 0.01, 300) for c in cols}) corr = returns.corr() pairs = corr.where(np.triu(np.ones(corr.shape), k=1).astype(bool)).stack() print('Most correlated pair:', pairs.idxmax(), round(pairs.max(), 3)) vols = returns.std() * np.sqrt(252) port = returns.mean(axis=1) port_vol = port.std() * np.sqrt(252) benefit = (1 - port_vol / vols.mean()) * 100 print(vols.round(3).to_dict()) print('Portfolio vol:', round(port_vol, 3)) print('Diversification benefit %:', round(benefit, 1))
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



