Mathew K Analytics

Lesson 12 · Real-World Data Analytics

Efficient Frontier in Python: Portfolio Risk, Return & Sharpe Ratio | Data Analytics #12

Modern portfolio theory, built step by step in Python: we combine Apple and Tesla into a two-asset portfolio, compute return, variance and the Sharpe ratio…

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.

📓 Full notebook

Download .ipynb

Data Analytics 100, Video 12: Portfolio Returns, Risk, and the Efficient Frontier#

  • Video twelve of the hundred-video real-world data analytics series.
  • Building a real two-asset portfolio from the real same Apple and Tesla data cleaned last video, and tracing out its real efficient frontier.
  • Let's get into it.

This lesson is for learners who finished the previous video's stock cleaning and want to move from describing two stocks to combining them. The business question: if you split money between Apple and Tesla, what mix gives the lowest risk, what mix gives the best return per unit of risk, and how much does combining them actually help?

You reuse aapl_tsla_merged.csv, the aligned table saved last lesson, which holds 338 shared trading days from October 2015 to February 2017 with AAPL_Return and TSLA_Return daily returns. From these you build the efficient frontier: the set of risk and return combinations you can reach by changing the weights of the two stocks.

In this lesson you will:

  • Annualise daily mean returns and volatility
  • Write portfolio return and variance formulas using covariance
  • Sweep 41 weightings to find the minimum-variance and maximum-Sharpe portfolios
  • Backtest strategies and measure the diversification benefit

Prerequisites: you should have run the previous lesson so the merged CSV exists, and be comfortable with pct_change(), standard deviation and simple Python functions.

Part 1: Reusing the Real Cleaned Data#

Starting from a saved, cleaned file means every number in this lesson is built on data you have already checked. The code reads aapl_tsla_merged.csv with parse_dates=['Date'], which turns the date text back into real datetimes on load. It then keeps only the two return columns and calls .dropna() to remove the first row, which has no return because there was no previous day. The output shows 337 usable daily returns, one fewer than the 338 merged days. Forgetting that missing first return is a common cause of off-by-one mismatches later.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
merged = pd.read_csv('aapl_tsla_merged.csv', parse_dates=['Date'])
returns = merged[['AAPL_Return', 'TSLA_Return']].dropna()
returns.shape[0]
337

Part 2: Real Individual Asset Statistics#

Portfolio maths needs two ingredients for each stock: its average return and its volatility. The code uses .mean() for the average daily return and .std() for the standard deviation, the typical spread of returns around that average. The output shows Apple averaging 0.00067 (about 0.067% a day) with a standard deviation of 0.01477, and Tesla averaging 0.00088 with 0.02447. Tesla earned slightly more per day but was clearly more volatile. Daily numbers are tiny and hard to compare with what investors quote, which is why the next step annualises them.

mean_aapl = returns['AAPL_Return'].mean()
mean_tsla = returns['TSLA_Return'].mean()
std_aapl = returns['AAPL_Return'].std()
std_tsla = returns['TSLA_Return'].std()
round(mean_aapl, 5), round(mean_tsla, 5), round(std_aapl, 5), round(std_tsla, 5)
(np.float64(0.00067),
 np.float64(0.00088),
 np.float64(0.01477),
 np.float64(0.02447))

Part 3: Real Annualized Statistics#

Investors talk in yearly figures, so you convert daily statistics to annual ones. Returns are scaled by 252, the usual number of trading days in a year, while volatility is scaled by the square root of 252, because variance grows with time but standard deviation grows with its square root. The output shows Apple at about 17.0% annual return and 23.5% volatility, Tesla at 22.1% return and 38.8% volatility. A common mistake is multiplying volatility by 252 instead of np.sqrt(252), which wildly overstates risk.

annual_return_aapl = mean_aapl * 252
annual_return_tsla = mean_tsla * 252
annual_vol_aapl = std_aapl * np.sqrt(252)
annual_vol_tsla = std_tsla * np.sqrt(252)
round(annual_return_aapl * 100, 1), round(annual_return_tsla * 100, 1), round(annual_vol_aapl * 100, 1), round(annual_vol_tsla * 100, 1)
(np.float64(17.0), np.float64(22.1), np.float64(23.5), np.float64(38.8))

Part 4: Real Covariance and Correlation#

How two stocks move together drives how much risk a mix can remove. Covariance measures this joint movement in squared return units, while correlation rescales it to a -1 to +1 range that is easier to read. The code builds full matrices with .cov() and .corr() and picks the Apple and Tesla cell with .loc. The output shows a covariance of 0.000078 and a correlation of 0.217, a weak positive link. The formulas use covariance, but correlation is what you quote to a colleague.

covariance = returns.cov().loc['AAPL_Return', 'TSLA_Return']
correlation = returns.corr().loc['AAPL_Return', 'TSLA_Return']
round(covariance, 6), round(correlation, 3)
(np.float64(7.8e-05), np.float64(0.217))

Part 5: Real Portfolio Return Formula#

The return of a portfolio is simply the weighted average of the returns of its parts. The function takes the Apple weight w_aapl and gives Tesla the rest, 1 - w_aapl, so the weights always sum to 1. Default arguments plug in the daily mean returns from earlier. For a 50/50 split the output is 0.00078 per day, exactly halfway between Apple's 0.00067 and Tesla's 0.00088. Defining this as a function lets you reuse it for any weight in the steps ahead.

def portfolio_return(w_aapl, r_aapl=mean_aapl, r_tsla=mean_tsla):
    return w_aapl * r_aapl + (1 - w_aapl) * r_tsla
round(portfolio_return(0.5), 5)
np.float64(0.00078)

Part 6: Real Portfolio Variance Formula#

Risk does not average in the same simple way, and this is the key idea of portfolio theory. Portfolio variance is each weight squared times that stock's variance, plus a cross term, 2 * w_aapl * w_tsla * cov, which captures how the two move together. When covariance is low or negative, that term is small and the mix becomes less risky than its parts suggest. The output for a 50/50 split is a daily variance of 0.000243. Variance is in squared units, so take its square root to get volatility in percent terms.

def portfolio_variance(w_aapl, s_aapl=std_aapl, s_tsla=std_tsla, cov=covariance):
    w_tsla = 1 - w_aapl
    return (w_aapl ** 2) * s_aapl ** 2 + (w_tsla ** 2) * s_tsla ** 2 + 2 * w_aapl * w_tsla * cov
round(portfolio_variance(0.5), 6)
np.float64(0.000243)

Part 7: Real Grid of Portfolio Weights#

Instead of solving equations, you can test many weightings and see which works best. np.linspace(0, 1, 41) creates 41 evenly spaced values from 0 to 1 inclusive, so the Apple weight moves in steps of 0.025, or 2.5 percentage points. The output confirms 41 weights. A finer grid gives smoother results but more calculation; for two assets this level of detail is plenty.

weights = np.linspace(0, 1, 41)
len(weights)
41

Part 8: Computing Every Real Candidate Portfolio#

Now you compute return and risk for every candidate mix, which traces the frontier. The loop calls both formula functions for each weight, annualises the return with * 252 and the volatility with np.sqrt(...) * np.sqrt(252), and stores a tuple. pd.DataFrame(results, columns=[...]) turns the list into a table. The first rows show that at 0% Apple (all Tesla) the portfolio returns 22.13% with 38.84% volatility, and adding just 5% Apple cuts volatility to 37.17% while return only slips to 21.88%. That uneven trade is diversification at work.

results = []
for w in weights:
    ann_ret = portfolio_return(w) * 252
    ann_vol = np.sqrt(portfolio_variance(w)) * np.sqrt(252)
    results.append((w, ann_ret, ann_vol))
frontier = pd.DataFrame(results, columns=['w_aapl', 'AnnualReturn', 'AnnualVol'])
frontier.head(3).round(4)
w_aapl AnnualReturn AnnualVol
0 0.000 0.2213 0.3884
1 0.025 0.2201 0.3800
2 0.050 0.2188 0.3717

Part 9: Real Minimum-Variance Portfolio#

The minimum-variance portfolio is the mix with the lowest possible risk, a natural choice for a cautious investor. The code finds the row with the smallest AnnualVol using idxmin() and selects it with .loc. The output shows the lowest-risk mix holds 80% Apple, with an annual return of 18.0% and volatility of 21.8%. Notice that this volatility is lower than Apple alone at 23.5%: adding a riskier stock in a small amount actually reduced total risk.

min_var_row = frontier.loc[frontier['AnnualVol'].idxmin()]
round(min_var_row['w_aapl'], 2), round(min_var_row['AnnualReturn'] * 100, 1), round(min_var_row['AnnualVol'] * 100, 1)
(np.float64(0.8), np.float64(18.0), np.float64(21.8))

Part 10: Real Sharpe Ratio#

Risk on its own does not tell you whether you are being paid for it. The Sharpe ratio, here simply annual return divided by annual volatility, measures return earned per unit of risk; a higher number is better. The textbook version subtracts a risk-free rate, such as a government bond yield, from the return, but this simplified form is fine for comparing mixes of the same two stocks. The output shows the all-Tesla portfolio scores 0.570, rising to 0.589 with 5% Apple. Adding a new column with plain division like this applies the calculation to every row at once.

frontier['Sharpe'] = frontier['AnnualReturn'] / frontier['AnnualVol']
frontier[['w_aapl', 'Sharpe']].head(3).round(3)
w_aapl Sharpe
0 0.000 0.570
1 0.025 0.579
2 0.050 0.589

Part 11: Real Maximum-Sharpe Portfolio#

The maximum-Sharpe portfolio is the mix that gives the most return per unit of risk. The code finds it with idxmax() on the Sharpe column. The output shows it holds 70% Apple, with an annual return of 18.5%, volatility of 22.1% and a Sharpe ratio of 0.839. Compared with the all-Tesla starting point at 0.570, that is a large improvement in efficiency. It sits close to, but not at, the minimum-variance mix, accepting a little more risk for a bit more return.

max_sharpe_row = frontier.loc[frontier['Sharpe'].idxmax()]
round(max_sharpe_row['w_aapl'], 2), round(max_sharpe_row['AnnualReturn'] * 100, 1), round(max_sharpe_row['AnnualVol'] * 100, 1), round(max_sharpe_row['Sharpe'], 3)
(np.float64(0.7), np.float64(18.5), np.float64(22.1), np.float64(0.839))

Part 12: Visualizing the Real Efficient Frontier#

A chart makes the trade-off visible in a way a table cannot. The code plots annual volatility on the x-axis against annual return on the y-axis to draw the frontier curve, then overlays coloured points for 100% Apple and 100% Tesla and star markers for the minimum-variance and maximum-Sharpe portfolios. zorder=5 draws the markers on top of the line. The chart is saved to a PNG, so there is no inline output. Look for the curve bending to the left of a straight line joining the two stocks: that bulge is the diversification benefit.

plt.figure(figsize=(9, 7))
plt.plot(frontier['AnnualVol'], frontier['AnnualReturn'], color='steelblue')
plt.scatter([annual_vol_aapl], [annual_return_aapl], color='green', s=100, label='Real 100% Apple', zorder=5)
plt.scatter([annual_vol_tsla], [annual_return_tsla], color='red', s=100, label='Real 100% Tesla', zorder=5)
plt.scatter([min_var_row['AnnualVol']], [min_var_row['AnnualReturn']], color='black', s=120, marker='*', label='Real min-variance portfolio', zorder=5)
plt.scatter([max_sharpe_row['AnnualVol']], [max_sharpe_row['AnnualReturn']], color='gold', s=120, marker='*', edgecolor='black', label='Real max-Sharpe portfolio', zorder=5)
plt.xlabel('Real Annualized Volatility')
plt.ylabel('Real Annualized Return')
plt.title('Real Efficient Frontier, Apple and Tesla')
plt.legend()
plt.tight_layout()
plt.savefig('efficient_frontier.png', dpi=120)
plt.close()

Part 13: Real Diversification Benefit#

This step puts a number on the diversification benefit. If risk simply averaged, an 80/20 portfolio would have the weighted average of the two volatilities; the code calculates that naive figure and subtracts the true volatility of the minimum-variance portfolio. The output shows the real portfolio is 4.72 percentage points less volatile than the naive average suggests. That reduction comes entirely from the two stocks not moving perfectly together, the covariance term from the variance formula.

naive_avg_vol = min_var_row['w_aapl'] * annual_vol_aapl + (1 - min_var_row['w_aapl']) * annual_vol_tsla
actual_vol = min_var_row['AnnualVol']
round((naive_avg_vol - actual_vol) * 100, 2)
np.float64(4.72)

Part 14: Real Equal-Weight Portfolio#

An equal split is the simplest strategy and a useful benchmark. Because the grid may not contain exactly 0.5 in every case, the code finds the row whose weight is closest to 0.5 by taking (frontier['w_aapl'] - 0.5).abs() and its idxmin(). The output shows the 50/50 portfolio returns 19.6% a year with 24.8% volatility. It earns more than the minimum-variance mix but carries 3 more points of risk, and its volatility is higher than Apple on its own.

equal_weight_row = frontier.iloc[(frontier['w_aapl'] - 0.5).abs().idxmin()]
round(equal_weight_row['AnnualReturn'] * 100, 1), round(equal_weight_row['AnnualVol'] * 100, 1)
(np.float64(19.6), np.float64(24.8))

Part 15: Real Backtest, Three Portfolios Over Time#

Formulas based on averages are a model; a backtest checks what would actually have happened. The code builds the minimum-variance portfolio's daily return as a weighted sum of the two stocks, then compounds each series with (1 + returns).cumprod() to get the growth of 1 dollar. The output shows final values of 1.233 for the 80/20 mix, 1.21 for Apple alone and 1.215 for Tesla alone. So the lowest-risk mix also ended slightly ahead of both stocks over this window, which will not always be true.

min_var_w = min_var_row['w_aapl']
returns['MinVarPort'] = min_var_w * returns['AAPL_Return'] + (1 - min_var_w) * returns['TSLA_Return']
returns['MinVarCumulative'] = (1 + returns['MinVarPort']).cumprod()
returns['AAPLCumulative'] = (1 + returns['AAPL_Return']).cumprod()
returns['TSLACumulative'] = (1 + returns['TSLA_Return']).cumprod()
round(returns['MinVarCumulative'].iloc[-1], 3), round(returns['AAPLCumulative'].iloc[-1], 3), round(returns['TSLACumulative'].iloc[-1], 3)
(np.float64(1.233), np.float64(1.21), np.float64(1.215))

Part 16: Visualizing the Real Backtest#

The final values hide the path, and the path is what an investor lives through. The code plots the three cumulative series against merged['Date'].iloc[1:], skipping the first date because the returns table lost that row to dropna(). The figure is saved to portfolio_backtest.png rather than shown inline. When you open it, look at how much shallower the minimum-variance line's dips are compared with Tesla's, even though all three finish close together.

plt.figure(figsize=(10, 6))
plt.plot(merged['Date'].iloc[1:], returns['MinVarCumulative'], label='Real Min-Variance Portfolio')
plt.plot(merged['Date'].iloc[1:], returns['AAPLCumulative'], label='Real 100% Apple')
plt.plot(merged['Date'].iloc[1:], returns['TSLACumulative'], label='Real 100% Tesla')
plt.xlabel('Real Date')
plt.ylabel('Real Growth of $1 Invested')
plt.title('Real Backtest, Three Portfolio Strategies')
plt.legend()
plt.tight_layout()
plt.savefig('portfolio_backtest.png', dpi=120)
plt.close()

Part 17: Real Sanity Check on the Variance Formula#

A quick test of a formula against a case where you know the answer catches typing mistakes. If you put 100% in Apple, portfolio variance must equal Apple's own variance, std_aapl ** 2. The code compares the two and checks the absolute difference is smaller than 1e-10, a tiny tolerance that allows for floating-point rounding. The output is True. Comparing floats with a tolerance, not ==, is the safe habit in numerical code.

manual_var_full_aapl = portfolio_variance(1.0)
abs(manual_var_full_aapl - std_aapl ** 2) < 1e-10
np.True_

Part 18: Saving the Real Frontier Table#

Saving the frontier table lets you reuse it in reports or later lessons without rerunning the sweep. The code rounds to five decimals with .round(5), writes it with index=False to avoid an extra index column, reads it back and compares row counts. The output is True, confirming all 41 rows were written and reloaded. The Sharpe column added earlier is included, since it is part of frontier by this point.

frontier.round(5).to_csv('efficient_frontier_table.csv', index=False)
reloaded = pd.read_csv('efficient_frontier_table.csv')
reloaded.shape[0] == frontier.shape[0]
True

Part 19: Real Recap Print#

A plain-English summary line turns numbers into something a non-analyst can act on. The code uses an f-string and round() to format the minimum-variance weights and volatility. The output reads: 80% Apple, 20% Tesla, 21.8% annual volatility. Note the inner quotes in the f-string are double quotes because the outer string uses single quotes; mixing them up is a common syntax error.

print(f'Minimum-variance portfolio: {round(min_var_row["w_aapl"]*100)}% Apple, {round((1-min_var_row["w_aapl"])*100)}% Tesla, {round(min_var_row["AnnualVol"]*100,1)}% annual volatility.')
Minimum-variance portfolio: 80% Apple, 20% Tesla, 21.8% annual volatility.

Part 20: Real Rolling Correlation Over Time#

A single correlation for the whole period can hide big changes over time. rolling(30).corr(...) computes the correlation over each 30-day window as it slides forward one day at a time. The first 29 values are NaN, so .dropna() leaves 308 windows, and .describe() summarises them. The output shows a mean of 0.210 and a median of 0.242, but a range from -0.259 to 0.476. So at times the two stocks moved in opposite directions and at others fairly closely together, which matters if you rely on diversification.

rolling_corr = returns['AAPL_Return'].rolling(30).corr(returns['TSLA_Return'])
rolling_corr.dropna().describe().round(3)
count    308.000
mean       0.210
std        0.160
min       -0.259
25%        0.149
50%        0.242
75%        0.300
max        0.476
dtype: float64

Part 21: Visualizing Real Rolling Correlation#

Seeing the rolling correlation over time shows when the relationship shifted. The code plots the 30-day series in purple and draws a dashed grey line at the full-period correlation of about 0.22 with axhline. The chart is saved to a PNG with no inline output. When you open it, look for stretches where the line dips below zero, when diversification was strongest, and peaks near 0.48, when the two behaved most alike.

plt.figure(figsize=(10, 5))
plt.plot(merged['Date'].iloc[1:], rolling_corr, color='purple')
plt.axhline(correlation, color='gray', linestyle='--', label='Real full-period correlation')
plt.xlabel('Real Date')
plt.ylabel('Real 30-Day Rolling Correlation')
plt.title('Real Rolling Correlation, Apple and Tesla')
plt.legend()
plt.tight_layout()
plt.savefig('rolling_correlation.png', dpi=120)
plt.close()

Part 22: Real Sanity Check at Full Tesla Weight#

Testing both ends of the formula gives more confidence than testing one. At 0% Apple the portfolio is all Tesla, so its variance must equal std_tsla ** 2. The code checks the difference is below 1e-10, and the output is True. With both extremes matching, you can trust the formula for weights in between.

manual_var_full_tsla = portfolio_variance(0.0)
abs(manual_var_full_tsla - std_tsla ** 2) < 1e-10
np.True_

Part 23: What If These Two Stocks Were Uncorrelated#

A what-if helps you see how much correlation matters. The code calculates the variance of a 50/50 portfolio as if the stocks were completely uncorrelated by leaving out the covariance term, then compares it with the real 50/50 variance. Both are annualised and expressed as percentages. The output shows 22.69% volatility if uncorrelated versus 24.77% in reality. Because the actual correlation of 0.217 is positive, it adds about 2 points of risk; a negative correlation would have reduced it below 22.69%.

hypothetical_var = (0.5 ** 2) * std_aapl ** 2 + (0.5 ** 2) * std_tsla ** 2
actual_var_50 = portfolio_variance(0.5)
round(np.sqrt(hypothetical_var) * np.sqrt(252) * 100, 2), round(np.sqrt(actual_var_50) * np.sqrt(252) * 100, 2)
(np.float64(22.69), np.float64(24.77))

Part 24: Real Total Return Comparison Over the Full Window#

Total return is the plainest answer to how much each stock made. The code takes the last cumulative value with .iloc[-1] and subtracts 1, turning a growth factor of 1.21 into a 21% gain. The output shows Apple at 21.0% and Tesla at 21.5% over the full window. Almost identical outcomes, yet Tesla's volatility was much higher, which is why risk-adjusted measures like Sharpe are needed to separate them.

total_return_aapl = returns['AAPLCumulative'].iloc[-1] - 1
total_return_tsla = returns['TSLACumulative'].iloc[-1] - 1
round(total_return_aapl * 100, 1), round(total_return_tsla * 100, 1)
(np.float64(21.0), np.float64(21.5))

Part 25: Real Days Each Stock Outperformed the Other#

Counting wins gives a simple, intuitive view of day-to-day performance. The code compares the two return columns row by row, which gives True or False, and .sum() counts the Trues. The output shows Apple beat Tesla on 164 days and Tesla beat Apple on 172. That adds up to 336, so on one of the 337 days the returns were equal. The split is close to even, which fits a weak correlation and similar total returns.

aapl_wins = (returns['AAPL_Return'] > returns['TSLA_Return']).sum()
tsla_wins = (returns['TSLA_Return'] > returns['AAPL_Return']).sum()
aapl_wins, tsla_wins
(np.int64(164), np.int64(172))

Part 26: Real Downside-Only Risk, the Sortino Idea#

Standard deviation treats big gains and big losses as equally risky, but investors mostly worry about losses. The Sortino idea, named after the Sortino ratio, measures only downside risk. The code filters each return series to negative days with a boolean mask, takes the .std() of those, and annualises with np.sqrt(252). The output shows downside volatility of 16.9% for Apple and 28.0% for Tesla. Tesla's losing days are clearly more severe. A full Sortino ratio would divide return by this downside figure.

downside_aapl = returns['AAPL_Return'][returns['AAPL_Return'] < 0].std()
downside_tsla = returns['TSLA_Return'][returns['TSLA_Return'] < 0].std()
round(downside_aapl * np.sqrt(252) * 100, 1), round(downside_tsla * np.sqrt(252) * 100, 1)
(np.float64(16.9), np.float64(28.0))

Part 27: Real Min-Variance vs Real Max-Sharpe Side by Side#

Putting the two optimal portfolios in one small table makes the choice clear. The code builds a DataFrame from a dictionary, where each key becomes a column, and rounds to three decimals. The output shows the minimum-variance mix at 80% Apple with 18.0% return and 21.8% volatility, and the maximum-Sharpe mix at 70% Apple with 18.5% return and 22.1% volatility. Moving 10 points of weight to Tesla buys half a point of return for about a third of a point of extra risk.

comparison = pd.DataFrame({'Portfolio': ['Min-Variance', 'Max-Sharpe'], 'AppleWeight': [min_var_row['w_aapl'], max_sharpe_row['w_aapl']], 'AnnualReturn': [min_var_row['AnnualReturn'], max_sharpe_row['AnnualReturn']], 'AnnualVol': [min_var_row['AnnualVol'], max_sharpe_row['AnnualVol']]})
comparison.round(3)
Portfolio AppleWeight AnnualReturn AnnualVol
0 Min-Variance 0.8 0.180 0.218
1 Max-Sharpe 0.7 0.185 0.221

Part 28: Real Range of Achievable Portfolio Returns#

Knowing the full range of outcomes shows how much the weighting decision actually matters. The code takes the minimum and maximum of the AnnualReturn column. The output shows achievable annual returns from about 0.170 (17.0%, all Apple) to about 0.221 (22.1%, all Tesla). Since return is a straight weighted average, the extremes are always the single stocks; for volatility, by contrast, the minimum sits inside the range, which is the whole point of the frontier.

frontier['AnnualReturn'].min(), frontier['AnnualReturn'].max()
(np.float64(0.16989436201780417), np.float64(0.2213412462908012))

Part 29: Real Volatility Reduction from Min-Variance vs Naive 50/50#

This compares the smartest low-risk mix with the simplest one. The code looks up the volatility of the portfolio closest to 50/50 and subtracts the minimum-variance volatility. The output shows a reduction of 2.96 percentage points, from roughly 24.8% to 21.8%. The equal split is not a bad default, but using the data to choose weights removes noticeably more risk. Keep in mind these weights are tuned to past data and may not be optimal in future.

vol_50_50 = frontier.loc[(frontier['w_aapl'] - 0.5).abs().idxmin(), 'AnnualVol']
round((vol_50_50 - min_var_row['AnnualVol']) * 100, 2)
np.float64(2.96)

Part 30: Real Final Recap Numbers#

Closing with headline numbers helps you check the story hangs together. The f-string reports the number of candidate portfolios with len(frontier) and the full-period correlation rounded to two decimals. The output confirms 41 portfolios were tested and the correlation was 0.22. Those two figures, the size of the search and the strength of the relationship, are the ones to quote first when you explain the frontier to someone else.

print(f'Tested {len(frontier)} real candidate portfolios; correlation between Apple and Tesla over this window was {round(correlation, 2)}.')
Tested 41 real candidate portfolios; correlation between Apple and Tesla over this window was 0.22.

Wrap-Up: What You Learned#

  • Portfolio return is genuinely just a weighted average of the real individual asset returns.
  • Portfolio variance is not a plain weighted average; the real covariance term is exactly what captures diversification benefit.
  • Sweeping a real grid of weights traces out the real efficient frontier, every achievable risk-return combination between two assets.
  • The real minimum-variance portfolio and the real maximum-Sharpe portfolio are two different, both genuinely useful, optimal points on that real frontier.
  • A real backtest turns the theory concrete: tracking how one real dollar would have actually grown under each real strategy.
  • Next video: real technical indicators, moving averages and momentum signals computed directly on these real price series.

Practice on your own

  • Change the grid to np.linspace(0, 1, 101) and check whether the minimum-variance and maximum-Sharpe weights move from 80% and 70% Apple.
  • Recalculate the Sharpe column with a risk-free rate, for example (frontier['AnnualReturn'] - 0.02) / frontier['AnnualVol'], and see which weight now wins.
  • Backtest the maximum-Sharpe portfolio alongside the minimum-variance one and compare their final values and maximum drawdowns using the drawdown function from the previous lesson.

Each exercise reuses functions you already wrote, so you only need to change one or two lines. The next lesson computes technical indicators, moving averages and momentum signals, directly on these same price series.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. In the lesson's two-asset portfolio, how is portfolio return computed from weight w in Apple?

  2. Which term in the portfolio variance formula captures the diversification benefit?

  3. The lesson annualizes daily volatility with std * np.sqrt(252). Why square root?

  4. How does the lesson define the Sharpe ratio on its frontier table?

  5. What is the minimum-variance portfolio found by frontier.loc[frontier['AnnualVol'].idxmin()]?

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Two assets have annual returns of 10% and 6%. Compute the return of a portfolio with 60% in the first and 40% in the second.

    💡 Hint

    Use the weighted average of returns.

    ✅ Show solution
    w1, w2 = 0.6, 0.4
    r1, r2 = 0.10, 0.06
    port_return = w1 * r1 + w2 * r2
    print(round(port_return, 4))   # 0.084
    
  2. Given daily volatilities 0.02 and 0.03, correlation 0.3 and weights 0.5/0.5, compute portfolio daily variance, its volatility, and annualized volatility (252 days). Compare with the correlation = 1 case.

    💡 Hint

    Covariance = corr * s1 * s2; variance = w1^2 s1^2 + w2^2 s2^2 + 2 w1 w2 cov.

    ✅ Show solution
    import numpy as np
    
    s1, s2 = 0.02, 0.03
    w1, w2 = 0.5, 0.5
    
    def port_vol(corr):
        cov = corr * s1 * s2
        var = w1**2 * s1**2 + w2**2 * s2**2 + 2 * w1 * w2 * cov
        return np.sqrt(var)
    
    for corr in (0.3, 1.0):
        v = port_vol(corr)
        print(f'corr={corr}: daily vol={v:.4f}, annual vol={v*np.sqrt(252):.4f}')
    # Lower correlation gives lower portfolio risk
    
  3. Simulate 500 days of daily returns for two assets (seed 3; asset A mean 0.0006 std 0.01; asset B mean 0.0004 std 0.02). Sweep Apple-style weights w in A from 0 to 1 in 41 steps, build a frontier DataFrame with annual return, annual vol and Sharpe (return/vol), then print the min-variance and max-Sharpe rows.

    💡 Hint

    Estimate means and covariance with pandas, then loop over np.linspace(0, 1, 41).

    ✅ Show solution
    import numpy as np
    import pandas as pd
    
    rng = np.random.default_rng(3)
    rets = pd.DataFrame({
        'A': rng.normal(0.0006, 0.01, 500),
        'B': rng.normal(0.0004, 0.02, 500),
    })
    mean = rets.mean()
    cov = rets.cov().loc['A', 'B']
    sa, sb = rets['A'].std(), rets['B'].std()
    
    rows = []
    for w in np.linspace(0, 1, 41):
        ret = (w * mean['A'] + (1 - w) * mean['B']) * 252
        var = w**2 * sa**2 + (1 - w)**2 * sb**2 + 2 * w * (1 - w) * cov
        vol = np.sqrt(var) * np.sqrt(252)
        rows.append((w, ret, vol, ret / vol))
    frontier = pd.DataFrame(rows, columns=['w_A', 'AnnualReturn', 'AnnualVol', 'Sharpe'])
    
    print('Min variance:')
    print(frontier.loc[frontier['AnnualVol'].idxmin()].round(3))
    print('Max Sharpe:')
    print(frontier.loc[frontier['Sharpe'].idxmax()].round(3))
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.