Workshop 3, Financial Modeling and Programming

Portfolio optimization and backtesting

Author

Alberto Dorantes, Ph.D.

Published

November 1, 2026

Abstract
This is an INDIVIDUAL workshop. We start with the basics: what a portfolio is, and how its expected return and risk are calculated with matrix algebra and the variance-covariance matrix. In the Algorithms course you simulated thousands of random portfolios and looked for the best one in the cloud. Here we find the optimal portfolios exactly: the Global Minimum Variance portfolio and the tangency (maximum Sharpe ratio) portfolio with matrix algebra, the efficient frontier and the Capital Market Line, and portfolios without short sales with a numerical optimizer. Then we learn why optimized portfolios are fragile (estimation risk) and we test our portfolio with data the model never saw: an out-of-sample backtest against the market and against an equally weighted portfolio.

1 General directions

Same rules as before: notebook W3-FinProg-YourFirstName-YourLastName, Predict → Run → Investigate → Modify → Make, pseudocode before the LLM, verification, and submission of the .ipynb file. Grade: notebook 60% + Canvas Quiz W3 40%.

import os, io, requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize

def import_csv(file, base_url="https://www.apradie.com/datos/", **kwargs):
    """Imports a csv file from base_url; downloads it only once and keeps a local copy."""
    if not os.path.exists(file):
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                                 "(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
        response = requests.get(base_url + file, headers=headers)
        response.raise_for_status()
        with open(file, "wb") as f:
            f.write(response.content)
    return pd.read_csv(file, **kwargs)

prices = import_csv("fz2024_prices_monthly.csv", index_col="date", parse_dates=True)
rf = import_csv("fz2024_rf_monthly.csv", index_col="date", parse_dates=True)
R = prices.pct_change(fill_method=None).iloc[1:]          # simple returns
r = np.log(prices).diff().iloc[1:]                        # cc returns

2 What is a portfolio?

A portfolio is a set of two or more financial assets held together: stocks, bonds, ETFs, T-Bills, commodities, etc. The owner of a portfolio has to make one key decision: how much of the money goes to each asset. That decision is summarized by the weights of the portfolio:

w_i=\frac{\text{money invested in asset } i}{\text{total money invested in the portfolio}} \qquad\qquad \sum_{i=1}^{N} w_i = 1

For example, if you invest $10,000 as follows: $5,000 in Walmart, $2,000 in Tesla and $3,000 in Coca-Cola, the weights of your portfolio are w=[0.50,\;0.20,\;0.30]. The weights add up to 1 (100% of your money).

A weight can be negative: this is a short sale. You borrow shares of a stock, sell them, and use that cash to buy more of the other assets; then the positive weights add up to more than 1, but the sum of all weights is still 1. We will use short sales later in this workshop.

Why do investors hold portfolios instead of putting all the money in the “best” stock? Because of diversification: when we combine assets that do not move exactly together, the bad months of one asset are partially compensated by the good months of the others, so the risk of the portfolio is lower than the average risk of its assets, and we do not have to give up expected return. In this workshop we measure exactly how much risk we eliminate, and then we find the best possible weights.

2.1 Our running example: a 3-stock portfolio

We use 3 companies that you know, with very different businesses:

  • WMT (Walmart): retail, a defensive stock (people buy groceries in good and bad times).
  • TSLA (Tesla): electric cars, a growth stock with very high volatility.
  • KO (Coca-Cola): beverages, another defensive stock.

We invest $10,000 on September 30, 2021 with weights 50% WMT, 20% TSLA and 30% KO, and we look at the following 5 years (60 months, up to September 2026). The prices come from the dataset we already imported (prices):

PF = ["WMT", "TSLA", "KO"]
w_pf = np.array([0.50, 0.20, 0.30])            # weights in the same order as PF
P_START, P_END = "2021-09-30", "2026-09-30"     # 61 month-end prices = 60 monthly returns
pf_prices = prices.loc[P_START:P_END, PF]
print("Sum of the weights:", w_pf.sum())
pf_prices.head()
Sum of the weights: 1.0
WMT TSLA KO
date
2021-09-30 43.643288 258.493347 45.326878
2021-10-31 46.787052 371.333344 48.695953
2021-11-30 44.034695 381.586670 45.660976
2021-12-31 45.488377 352.260010 51.545979
2022-01-31 43.954193 312.239990 53.112988

Always check that the order of the weights is the same as the order of the columns. Here we selected the columns with the list PF, so the first weight is for WMT, the second for TSLA and the third for KO.

2.2 A portfolio in action: buy and hold

If we divide each price by its first price, we get the value of $1 invested in each stock (a growth index). If we buy the portfolio and do nothing (buy and hold), the money in each stock grows with its own growth index, and the value of the portfolio is the sum of the money in the 3 stocks:

growth = pf_prices / pf_prices.iloc[0]          # value of $1 invested in each stock
money = 10000 * w_pf * growth                   # dollars in each stock over time (buy and hold)
port_value = money.sum(axis=1)                  # total value of the portfolio
growth_all = growth.assign(PORT=port_value / 10000)

growth_all.plot(figsize=(9, 4.5), title="Value of $1 invested on September 30, 2021")
plt.ylabel("value ($)"); plt.grid(alpha=0.3); plt.show()

The holding period return (HPR) is the % gained from the start up to the end. For a buy-and-hold portfolio, the HPR of the portfolio is exactly the weighted average of the HPRs of the stocks, using the initial weights:

hpr = growth_all.iloc[-1] - 1
print(hpr.round(4))
print(f"Weighted average of the stock HPRs: {w_pf @ hpr[PF].values:.4f}")
WMT     1.3811
TSLA    0.3726
KO      0.8991
PORT    1.0348
Name: 2026-09-30 00:00:00, dtype: float64
Weighted average of the stock HPRs: 1.0348

Notice that the weights we chose are only the initial weights. With buy and hold, the stocks that go up gain weight and the stocks that go down lose weight:

weights_t = money.div(port_value, axis=0)       # weight of each stock month by month
weights_t.plot.area(figsize=(9, 3.5), title="Buy and hold: the weights drift over time")
plt.ylabel("weight"); plt.ylim(0, 1); plt.legend(loc="lower left"); plt.show()

An investor who wants to keep the weights fixed has to rebalance: sell some of the winners and buy some of the losers to go back to the target weights (for example, every month). We will use both ways of holding a portfolio in the backtesting section.

2.3 Historical return and risk of the portfolio

To measure the risk of the portfolio we need its period (monthly) returns, not its cumulative return. We treat the portfolio value as if it were a price, and we calculate monthly continuously compounded (cc) returns for the 3 stocks and the portfolio:

hist_r = np.log(growth_all).diff().dropna()     # monthly cc returns of the stocks and the portfolio
hist = pd.DataFrame({
    "annual mean return": np.exp(12 * hist_r.mean()) - 1,       # geometric mean, annualized
    "annual volatility": hist_r.std() * np.sqrt(12)})
hist.round(4)
annual mean return annual volatility
WMT 0.1895 0.2057
TSLA 0.0654 0.5988
KO 0.1369 0.1608
PORT 0.1527 0.1735

Remember:

  • The volatility is the standard deviation of the period returns. To annualize a monthly volatility we multiply it by \sqrt{12} (variance grows with time, so volatility grows with the square root of time).
  • The variance is the average of the squared deviations from the mean: Var(r)=\frac{\sum_{t=1}^{N}(r_t-\bar r)^2}{N-1}. Pandas divides by N-1 (sample variance); with 60 months the difference with dividing by N is very small.
  • The mean monthly cc return, multiplied by 12 and converted with e^{x}-1, gives the annual (geometric) mean return.

A box plot of the monthly simple returns helps to see the risk (we humans understand simple returns better than cc returns):

hist_R = np.exp(hist_r) - 1
plt.figure(figsize=(8, 4))
plt.boxplot(hist_R.values, showmeans=True)
plt.xticks(range(1, hist_R.shape[1] + 1), hist_R.columns)
plt.axhline(0, color="gray", lw=0.8); plt.ylabel("monthly return")
plt.title("Monthly simple returns, Oct 2021 - Sep 2026"); plt.grid(alpha=0.3); plt.show()

Before you continue, answer: Which instrument was the most volatile? Is the volatility of the portfolio higher or lower than the weighted average of the volatilities of the 3 stocks (0.5\times\sigma_{WMT}+0.2\times\sigma_{TSLA}+0.3\times\sigma_{KO})? Calculate it. Why do you think that happens?

The answer to the last question is the topic of the next section: the risk of a portfolio depends not only on the risk of each asset, but on how the assets move together.

3 Calculating expected returns and risk of a portfolio

Up to now we measured what happened (historical return and risk). To decide how to invest today we need what we expect to happen. Portfolio theory (Harry Markowitz, 1952) says that we need two inputs:

  1. The expected return of each asset: a vector \mu (one number per asset).
  2. The variance-covariance matrix \Sigma: the variance of each asset and the covariance of every pair of assets (how they move together).

With these two inputs, matrix algebra gives us the expected return and the expected risk of any portfolio. We estimate both inputs with historical monthly data (later in your career you will see other methods, such as the CAPM for expected returns).

3.1 Expected return of each asset

We use the geometric mean of historical returns: the constant monthly return that would have produced the same final value. The easy way to calculate it is with the arithmetic mean of the cc returns:

E[R_i]=e^{\bar r_i}-1 \qquad\qquad \bar r_i=\frac{r_{i,1}+r_{i,2}+\dots+r_{i,N}}{N}

pf_r = np.log(pf_prices).diff().dropna()        # 60 monthly cc returns of the 3 stocks
mu_m = np.exp(pf_r.mean()) - 1                  # expected MONTHLY simple return of each stock
mu_m.round(5)
WMT     0.01456
TSLA    0.00529
KO      0.01075
dtype: float64

3.2 Expected return of the portfolio

The expected return of a portfolio is the weighted average of the expected returns of its assets.

3.2.1 Method 1: sum of products

E[R_P]=w_1E[R_1]+w_2E[R_2]+w_3E[R_3]

terms = w_pf * mu_m.values                      # element by element: w_i * E[R_i]
print(" + ".join(f"{w:.2f}*{m:.5f}" for w, m in zip(w_pf, mu_m)), f"= {terms.sum():.5f}")
0.50*0.01456 + 0.20*0.00529 + 0.30*0.01075 = 0.01156

3.2.2 Method 2: matrix multiplication

The same weighted average is a matrix multiplication of the (transposed) vector of weights times the vector of expected returns:

E[R_P]=w^{T}\mu

How does matrix multiplication work? To multiply a matrix A (with m rows and n columns) by a matrix B (with n rows and p columns):

  • The inner dimensions must match: the number of columns of A must be equal to the number of rows of B: (m\times \boxed{n})\,(\boxed{n}\times p).
  • The result has the outer dimensions: m\times p.
  • Each element (i,j) of the result is row i of A times column j of B: multiply the elements one by one and add up the products. A row “walks” from left to right while a column “walks” from top to bottom.

The vector of weights is a column (3\times1); its transpose w^T “rotates” it into a row (1\times3). Then w^T\mu is (1\times3)(3\times1)=1\times1, a single number:

\underbrace{\begin{bmatrix}\textcolor{blue}{w_1} & \textcolor{red}{w_2} & \textcolor{green}{w_3}\end{bmatrix}}_{1\times 3} \underbrace{\begin{bmatrix}\textcolor{blue}{E[R_1]}\\ \textcolor{red}{E[R_2]}\\ \textcolor{green}{E[R_3]}\end{bmatrix}}_{3\times 1} =\underbrace{\textcolor{blue}{w_1E[R_1]}+\textcolor{red}{w_2E[R_2]}+\textcolor{green}{w_3E[R_3]}}_{1\times 1}

This is exactly Method 1. In Python, the operator @ does matrix multiplication. With 1-dimensional numpy arrays we do not need to transpose: w @ mu already multiplies “row times column”:

ER_p = w_pf @ mu_m.values
print(f"Expected monthly return of the portfolio: {ER_p:.5f}")
assert np.isclose(ER_p, terms.sum())            # both methods must give the same number
Expected monthly return of the portfolio: 0.01156

With 3 assets the sum of products is easy. With 500 assets, w @ mu is still one line of code.

3.3 The variance-covariance matrix

Why can’t we just take the weighted average of the volatilities as the risk of the portfolio? Because when one stock has a bad month, another stock may have a good month, and they compensate each other. To measure this we need the covariance of each pair of stocks.

3.3.1 Covariance: do two returns move together?

The covariance of 2 returns is the average of the products of their deviations from their means:

Cov(r_1,r_2)=\frac{\sum_{t=1}^{N}(r_{1,t}-\bar r_1)(r_{2,t}-\bar r_2)}{N-1}

Look at the product of deviations month by month: when both stocks are above their means (or both below), the product is positive; when one is above and the other is below, the product is negative. The covariance is positive when the first case dominates (they tend to move together) and negative when the second case dominates (they tend to move in opposite directions):

D = pf_r - pf_r.mean()                          # deviations from the mean, month by month
example = pd.DataFrame({"r WMT": pf_r["WMT"], "r TSLA": pf_r["TSLA"],
                        "dev WMT": D["WMT"], "dev TSLA": D["TSLA"],
                        "product": D["WMT"] * D["TSLA"]})
print(example.head(6).round(4))
print(f"Cov(WMT, TSLA) = sum of products / (N-1) = {example['product'].sum() / (len(D) - 1):.6f}")
print(f"Pandas: {pf_r['WMT'].cov(pf_r['TSLA']):.6f}")
             r WMT  r TSLA  dev WMT  dev TSLA  product
date                                                  
2021-10-31  0.0696  0.3622   0.0551    0.3570   0.0197
2021-11-30 -0.0606  0.0272  -0.0751    0.0220  -0.0016
2021-12-31  0.0325 -0.0800   0.0180   -0.0852  -0.0015
2022-01-31 -0.0343 -0.1206  -0.0488   -0.1259   0.0061
2022-02-28 -0.0338 -0.0734  -0.0483   -0.0787   0.0038
2022-03-31  0.1008  0.2135   0.0864    0.2082   0.0180
Cov(WMT, TSLA) = sum of products / (N-1) = 0.002239
Pandas: 0.002239

The magnitude of a covariance is hard to interpret, so we standardize it into the correlation, which is always between -1 and +1:

Corr(r_1,r_2)=\frac{Cov(r_1,r_2)}{SD(r_1)\,SD(r_2)}

pairs = [("WMT", "TSLA"), ("WMT", "KO"), ("TSLA", "KO")]
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8), sharey=False)
for ax, (a, b) in zip(axes, pairs):
    ax.scatter(pf_r[a], pf_r[b], s=14, alpha=0.7)
    ax.axhline(pf_r[b].mean(), color="gray", lw=0.8); ax.axvline(pf_r[a].mean(), color="gray", lw=0.8)
    ax.set_xlabel(f"r {a}"); ax.set_ylabel(f"r {b}")
    ax.set_title(f"{a} vs {b}: corr = {pf_r[a].corr(pf_r[b]):.2f}"); ax.grid(alpha=0.3)
plt.tight_layout(); plt.show()

The gray lines are the means, and they divide each plot in 4 quadrants. Points in the upper-right and lower-left quadrants add to the covariance (positive products); points in the other two quadrants subtract from it. Which pair offers more diversification?

3.3.2 All the pairs at once: the matrix

With N assets we organize all the variances and covariances in an N\times N table, the variance-covariance matrix. The cell in row i and column j is Cov(r_i,r_j):

\Sigma=\begin{bmatrix} \textcolor{blue}{Var(r_1)} & Cov(r_1,r_2) & Cov(r_1,r_3)\\ Cov(r_2,r_1) & \textcolor{blue}{Var(r_2)} & Cov(r_2,r_3)\\ Cov(r_3,r_1) & Cov(r_3,r_2) & \textcolor{blue}{Var(r_3)} \end{bmatrix}

  • The diagonal has the variances: the covariance of a return with itself is its variance, Cov(r_i,r_i)=Var(r_i).
  • Outside the diagonal are the covariances. The matrix is symmetric: Cov(r_1,r_2)=Cov(r_2,r_1), so the part above the diagonal is a mirror of the part below.
  • With N assets there are N variances and \frac{N(N-1)}{2} different covariances: 3 + 3 for our 3 stocks, but 500 + 124,750 for the S&P 500!

3.3.3 (optional) Calculating the covariance matrix with matrix multiplication

Here matrix multiplication shows its power. Put the deviations of the 3 stocks in a matrix D with 60 rows (months) and 3 columns (stocks). Then:

\Sigma=\frac{D^{T}D}{N-1} \qquad\qquad (3\times60)\,(60\times3)=3\times3

Row i of D^T has the 60 deviations of stock i, and column j of D has the 60 deviations of stock j. Row times column is the sum of the products of the deviations: the numerator of Cov(r_i,r_j). One multiplication calculates the 9 cells of the matrix at once!

COV_manual = (D.T @ D) / (len(D) - 1)           # (3x60) @ (60x3) = 3x3
COV_m = pf_r.cov()                              # monthly variance-covariance matrix (pandas)
assert np.allclose(COV_manual, COV_m)
COV_m.round(6)
WMT TSLA KO
WMT 0.003525 0.002239 0.000902
TSLA 0.002239 0.029884 -0.001935
KO 0.000902 -0.001935 0.002156

We can get the correlation matrix from the covariance matrix by dividing each cell by the product of the 2 standard deviations (pandas does it with .corr()):

sd = np.sqrt(np.diag(COV_m))                    # the volatilities are the sqrt of the diagonal
CORR_m = COV_m / np.outer(sd, sd)               # cell (i,j) divided by sd_i * sd_j
assert np.allclose(CORR_m, pf_r.corr())

fig, axes = plt.subplots(1, 2, figsize=(11, 4))
for ax, M, title, cmap, lims in [(axes[0], COV_m, "Variance-covariance matrix (monthly)", "Blues", (0, COV_m.values.max())),
                                 (axes[1], CORR_m, "Correlation matrix", "RdBu_r", (-1, 1))]:
    ax.imshow(M.values, cmap=cmap, vmin=lims[0], vmax=lims[1])
    ax.set_xticks(range(3), PF); ax.set_yticks(range(3), PF); ax.set_title(title)
    for i in range(3):
        for j in range(3):
            v = M.values[i, j]
            dark = abs(v) > 0.6 * lims[1]                # white text on dark cells
            ax.text(j, i, f"{v:.4f}" if M is COV_m else f"{v:.2f}", ha="center", va="center",
                    fontsize=10, color="white" if dark else "black")
plt.tight_layout(); plt.show()

Notice the symmetry of both matrices, the diagonal of the correlation matrix (always 1), and the large variance of TSLA in the diagonal of the covariance matrix.

3.4 Expected risk of the portfolio

3.4.1 Method 1: sum of products

For a 2-asset portfolio, the variance of the portfolio is:

Var(R_P)=w_1^2Var(r_1)+w_2^2Var(r_2)+2w_1w_2Cov(r_1,r_2)

For 3 assets there are 3 variance terms and 3 pairs of covariances:

Var(R_P)=w_1^2\sigma_1^2+w_2^2\sigma_2^2+w_3^2\sigma_3^2+2w_1w_2\sigma_{12}+2w_1w_3\sigma_{13}+2w_2w_3\sigma_{23}

There is a simple way to remember this formula: multiply each cell (i,j) of the covariance matrix by its row weight and its column weight, w_i\,w_j\,\sigma_{ij}, and add up all the cells. The diagonal gives the 3 variance terms, and each covariance appears twice (above and below the diagonal): that is where the “2” comes from.

contrib = COV_m.values * np.outer(w_pf, w_pf)   # cell (i,j) = w_i * w_j * Cov(r_i, r_j)
var_p1 = contrib.sum()
print(pd.DataFrame(contrib, index=PF, columns=PF).round(6))
print(f"Portfolio variance (sum of the 9 cells): {var_p1:.6f}")
           WMT      TSLA        KO
WMT   0.000881  0.000224  0.000135
TSLA  0.000224  0.001195 -0.000116
KO    0.000135 -0.000116  0.000194
Portfolio variance (sum of the 9 cells): 0.002757
share = contrib / var_p1                        # % of the portfolio variance in each cell
plt.figure(figsize=(5, 4))
plt.imshow(share, cmap="Blues", vmin=0)
plt.xticks(range(3), PF); plt.yticks(range(3), PF)
for i in range(3):
    for j in range(3):
        plt.text(j, i, f"{share[i, j]:.1%}", ha="center", va="center",
                 color="white" if share[i, j] > 0.6 * share.max() else "black")
plt.title("Where does the portfolio variance come from?\n(w_i * w_j * Cov_ij as % of the total)")
plt.show()

Read the heat map: the cells with negative covariance (TSLA–KO) reduce the variance of the portfolio. This is diversification in action.

3.4.2 Method 2: matrix algebra

The sum of all the cells w_iw_j\sigma_{ij} is exactly what this matrix product calculates:

Var(R_P)=w^{T}\,\Sigma\,w \qquad\qquad (1\times3)\,(3\times3)\,(3\times1)=1\times1

Let’s do it in two steps. Step 1: \Sigma w is (3\times3)(3\times1)=3\times1. Each element is a row of \Sigma times the column of weights:

\Sigma w= \begin{bmatrix} \textcolor{blue}{\sigma_1^2} & \textcolor{blue}{\sigma_{12}} & \textcolor{blue}{\sigma_{13}}\\ \textcolor{red}{\sigma_{21}} & \textcolor{red}{\sigma_2^2} & \textcolor{red}{\sigma_{23}}\\ \textcolor{green}{\sigma_{31}} & \textcolor{green}{\sigma_{32}} & \textcolor{green}{\sigma_3^2} \end{bmatrix} \begin{bmatrix}w_1\\ w_2\\ w_3\end{bmatrix} =\begin{bmatrix} \textcolor{blue}{\sigma_1^2w_1+\sigma_{12}w_2+\sigma_{13}w_3}\\ \textcolor{red}{\sigma_{21}w_1+\sigma_2^2w_2+\sigma_{23}w_3}\\ \textcolor{green}{\sigma_{31}w_1+\sigma_{32}w_2+\sigma_3^2w_3} \end{bmatrix}

Each element of \Sigma w has a meaning: it is the covariance of each stock with the portfolio, Cov(r_i,R_P).

Step 2: w^T(\Sigma w) is (1\times3)(3\times1)=1\times1: the weighted sum of the covariances of the stocks with the portfolio, which is the variance of the portfolio:

w^{T}(\Sigma w)=w_1\,Cov(r_1,R_P)+w_2\,Cov(r_2,R_P)+w_3\,Cov(r_3,R_P)=Var(R_P)

Sw = COV_m.values @ w_pf                        # step 1: (3x3) @ (3,) -> 3 covariances with the portfolio
var_p2 = w_pf @ Sw                              # step 2: (3,) @ (3,) -> 1 number
print("Step 1, Sigma @ w =", Sw.round(6))
print(f"Step 2, w @ (Sigma @ w) = {var_p2:.6f}")
print(f"In one line, w @ Sigma @ w = {w_pf @ COV_m.values @ w_pf:.6f}")
assert np.isclose(var_p1, var_p2)               # Method 1 and Method 2 must give the same number
Step 1, Sigma @ w = [0.002481 0.006516 0.000711]
Step 2, w @ (Sigma @ w) = 0.002757
In one line, w @ Sigma @ w = 0.002757

Step 2 also tells us how much of the portfolio risk comes from each stock: the term w_i\,Cov(r_i,R_P) divided by Var(R_P) is the risk contribution of stock i (these are the row sums of the previous heat map). Compare the weights with the risk contributions:

pd.DataFrame({"weight": w_pf, "risk contribution": w_pf * Sw / var_p2}, index=PF).round(4)
weight risk contribution
WMT 0.5 0.4499
TSLA 0.2 0.4727
KO 0.3 0.0774

TSLA receives only 20% of the money, but it is responsible for almost half of the risk of the portfolio; KO receives 30% of the money and adds very little risk, thanks to its low (even negative) covariances with the other stocks. Money weights are not risk weights.

3.4.3 From variance to risk, and from monthly to annual

The expected risk (volatility) of the portfolio is the square root of its variance:

\sigma_P=\sqrt{w^{T}\Sigma w}

Our inputs are monthly. To annualize we follow the same conventions of the next sections: the annual covariance matrix is 12\times\Sigma_{monthly} (then the annual volatility is \sqrt{12} times the monthly volatility), and the annual expected return of each stock is e^{12\bar r_i}-1:

mu_a = np.exp(12 * pf_r.mean()) - 1             # annual expected return of each stock
COV_a = 12 * COV_m                              # annual variance-covariance matrix
ER_a = w_pf @ mu_a.values
vol_a = np.sqrt(w_pf @ COV_a.values @ w_pf)
avg_vol = w_pf @ np.sqrt(np.diag(COV_a))        # weighted average of the stock volatilities
print(f"Expected annual return of the portfolio: {ER_a:.4f}")
print(f"Expected annual volatility of the portfolio: {vol_a:.4f}")
print(f"Weighted average of the 3 volatilities: {avg_vol:.4f}  -> risk eliminated by diversification: {avg_vol - vol_a:.4f}")
Expected annual return of the portfolio: 0.1489
Expected annual volatility of the portfolio: 0.1819
Weighted average of the 3 volatilities: 0.2709  -> risk eliminated by diversification: 0.0890

The weighted average of the volatilities would be the risk of the portfolio only if all the correlations were +1. Since the correlations of our stocks are much lower than 1 (and TSLA–KO is even negative), the volatility of the portfolio is much lower. This is the diversification effect, and it has two drivers: the number of assets and the correlations between them. We cannot change the correlations, but we can change the weights: in the next sections we look for the weights that give the best combination of expected return and risk.

TipIs w^T\Sigma w really the variance of the portfolio? A check

With simple returns, the return of a portfolio rebalanced every month is exactly the weighted average of the stock returns: R_{P,t}=w_1R_{1,t}+w_2R_{2,t}+w_3R_{3,t} (in Python, R @ w). Then the variance of that series must be exactly w^T\Sigma w, with \Sigma calculated from simple returns:

pf_R = pf_prices.pct_change().dropna()          # monthly simple returns
Rp = pf_R @ w_pf                                # monthly returns of the rebalanced portfolio
print(f"Variance of the portfolio return series: {Rp.var():.6f}")
print(f"w' Sigma w with simple returns:          {w_pf @ pf_R.cov().values @ w_pf:.6f}")
assert np.isclose(Rp.var(), w_pf @ pf_R.cov().values @ w_pf)
Variance of the portfolio return series: 0.002853
w' Sigma w with simple returns:          0.002853

The formula is not magic: it is an algebraic identity. In the rest of the workshop we estimate \Sigma with cc returns (our convention from the Algorithms course); the result is very close, but not identical, because the cc return of a portfolio is not the weighted average of the cc returns of its assets.

Predict, then modify: before running anything, predict what happens to the expected return and to the volatility of the portfolio if you move 10 percentage points from KO to TSLA (w_pf = np.array([0.50, 0.30, 0.20])). Then change the weights and run the code of this section again. Was your prediction right? Which risk contribution changed the most?

4 Inputs of portfolio optimization

We keep the conventions of the Algorithms course:

  • Expected returns: the annual expected simple return of each asset, from the mean of its monthly cc returns: E[R_i]=e^{12\bar r_i}-1.
  • Risk: the annual variance-covariance matrix of cc returns, \Sigma = 12\times Cov(r).
  • Portfolio returns over time: weights times simple returns, R[ASSETS] @ w.

We use 5 assets as a running example (the same ones of the Algorithms course) and the 36-month window before our decision date (March 31, 2023):

ASSETS = ["AAPL", "JPM", "WMT", "XOM", "GLD"]
START, END = "2020-04-30", "2023-03-31"

def opt_inputs(assets, start, end):
    """Annual expected simple returns (from cc means) and annual covariance matrix of cc returns."""
    rr = r.loc[start:end, assets].dropna()
    mu = np.exp(12 * rr.mean()) - 1
    cov = 12 * rr.cov()
    return mu, cov

mu, COV = opt_inputs(ASSETS, START, END)
RF_ANNUAL = rf.loc[END, "tb3ms"] / 100           # T-Bill rate at the decision date
print(mu.round(4)); print(f"Annual risk-free rate at {END}: {RF_ANNUAL:.2%}")
AAPL    0.3830
JPM     0.1666
WMT     0.1082
XOM     0.5065
GLD     0.0736
dtype: float64
Annual risk-free rate at 2023-03-31: 4.64%

The expected return and the volatility of a portfolio with weights w are (in matrix form):

E[R_P]=w^{T}\mu \qquad\qquad \sigma_P=\sqrt{w^{T}\Sigma w}

def port_perf(w, mu, cov, rf=0.0):
    """Expected return, volatility and Sharpe ratio of a portfolio with weights w."""
    w = np.asarray(w)
    ret = w @ mu.values
    vol = np.sqrt(w @ cov.values @ w)
    return ret, vol, (ret - rf) / vol

w_eq = np.repeat(1 / len(ASSETS), len(ASSETS))
print("Equally weighted: return = %.4f, volatility = %.4f, Sharpe = %.4f" % port_perf(w_eq, mu, COV, RF_ANNUAL))
Equally weighted: return = 0.2476, volatility = 0.1649, Sharpe = 1.2204

4.1 From random portfolios to exact optimization

In the Algorithms course you simulated random portfolios. Let’s do it again, to see the cloud of feasible portfolios:

rng = np.random.default_rng(seed=42)                 # random number generator with a fixed seed (reproducible results)
W = rng.random((5000, len(ASSETS)))                  # 5,000 rows (portfolios) x 5 columns (assets) of random numbers between 0 and 1
W = W / W.sum(axis=1, keepdims=True)                 # divide each row by its sum, so the weights of each portfolio add up to 1
cloud_ret = W @ mu.values                            # (5000x5) @ (5,) -> expected return of each of the 5,000 portfolios
VCOV_P = W @ COV.values @ W.T                        # (5000x5) @ (5x5) @ (5x5000) -> 5000x5000 matrix; its diagonal has w' COV w of each portfolio
cloud_vol = np.sqrt(np.diag(VCOV_P))                 # the diagonal has the variances; its square root gives the volatility of each portfolio
sharpe = (cloud_ret - RF_ANNUAL) / cloud_vol         # Sharpe ratio of each portfolio
best = np.argmax(sharpe)                             # position (row) of the portfolio with the highest Sharpe ratio
print("Best random portfolio (Sharpe):", dict(zip(ASSETS, W[best].round(3).tolist())))   # weights of that portfolio, with the asset names
Best random portfolio (Sharpe): {'AAPL': 0.382, 'JPM': 0.022, 'WMT': 0.028, 'XOM': 0.491, 'GLD': 0.077}

Each row of W is one portfolio. The product W @ COV @ W.T is a 5,000 x 5,000 matrix: the cell (i,j) is w_i^T\Sigma\, w_j, the covariance between portfolio i and portfolio j. On the diagonal (i=j) we get w_i^T\Sigma\, w_i, the variance of portfolio i: exactly the formula of the previous section, calculated for the 5,000 portfolios at once (it replaces the loop or list comprehension of the Algorithms course). The square root of the diagonal gives the 5,000 volatilities. We only need the diagonal, so this calculates many products we do not use (25 million cells, about 200 MB of memory); with many more portfolios it would be better to calculate only the diagonal, for example with np.sum((W @ COV.values) * W, axis=1). The best random portfolio is only an approximation: with 5,000 tries we never hit the exact optimum, and with 20 assets random search becomes hopeless. We need optimization.

5 The Global Minimum Variance (GMV) portfolio

The GMV portfolio has the lowest possible volatility. It solves:

\min_{w}\; w^{T}\Sigma w \qquad \text{subject to} \qquad w^{T}\mathbf{1}=1

If short sales are allowed (weights can be negative), this problem has an exact solution (using the method of Lagrange multipliers):

w_{GMV}=\frac{\Sigma^{-1}\mathbf{1}}{\mathbf{1}^{T}\Sigma^{-1}\mathbf{1}}

Read it as an algorithm: (1) invert the covariance matrix, (2) multiply it by a vector of ones (this gives a “raw” weight for each asset: higher for assets with low variance and low covariances), (3) divide by the sum of the raw weights so that they add up to 1.

ones = np.ones(len(ASSETS))                          # vector of ones, one for each asset
Sinv = np.linalg.inv(COV.values)                     # inverse of the annual variance-covariance matrix
raw = Sinv @ ones                                    # (5x5) @ (5,) -> "raw" weight of each asset: the sum of each row of Sinv
w_gmv = raw / (ones @ raw)                           # divide by the sum of the raw weights (ones @ raw), so the weights add up to 1
ret_gmv, vol_gmv, sh_gmv = port_perf(w_gmv, mu, COV, RF_ANNUAL)   # expected return, volatility and Sharpe ratio of the GMV
print(pd.Series(w_gmv, index=ASSETS).round(4))       # show the GMV weights with the asset names
# compare the GMV volatility with the lowest volatility of the 5,000 random portfolios:
print(f"GMV: return = {ret_gmv:.4f}, volatility = {vol_gmv:.4f}; minimum random volatility = {cloud_vol.min():.4f}")
AAPL   -0.0706
JPM     0.0913
WMT     0.2477
XOM     0.1349
GLD     0.5967
dtype: float64
GMV: return = 0.1272, volatility = 0.1229; minimum random volatility = 0.1249

The GMV volatility is lower than the volatility of every random portfolio. Notice that the GMV portfolio does not use the expected returns \mu: only the covariance matrix.

6 The tangency (maximum Sharpe ratio) portfolio

The Sharpe ratio is the premium return per unit of risk: \frac{E[R_P]-R_f}{\sigma_P}. The portfolio with the highest Sharpe ratio is called the tangency (or optimal) portfolio. With short sales allowed:

w_{T}=\frac{\Sigma^{-1}(\mu-R_f\mathbf{1})}{\mathbf{1}^{T}\Sigma^{-1}(\mu-R_f\mathbf{1})}

It is the same algorithm as the GMV, but the vector of ones is replaced by the vector of premium returns: assets with a higher premium return get a higher raw weight.

raw_t = Sinv @ (mu.values - RF_ANNUAL)               # (5x5) @ (5,) -> "raw" weights from the premium returns (mu - Rf)
w_tan = raw_t / (ones @ raw_t)                       # divide by the sum of the raw weights, so the weights add up to 1
ret_tan, vol_tan, sh_tan = port_perf(w_tan, mu, COV, RF_ANNUAL)   # expected return, volatility and Sharpe ratio of the tangency portfolio
print(pd.Series(w_tan, index=ASSETS).round(4))       # show the tangency weights with the asset names
print(f"Tangency: return = {ret_tan:.4f}, volatility = {vol_tan:.4f}, Sharpe = {sh_tan:.4f}")   # show its performance
AAPL    0.5827
JPM    -0.5032
WMT    -0.1962
XOM     0.9266
GLD     0.1901
dtype: float64
Tangency: return = 0.6015, volatility = 0.3221, Sharpe = 1.7232

7 The efficient frontier and the Capital Market Line

A beautiful result of portfolio theory (the two-fund theorem): every portfolio on the efficient frontier is a combination of any two frontier portfolios. Then, we can draw the whole frontier by combining the GMV and the tangency portfolios: w(\lambda)=\lambda\, w_T+(1-\lambda)\,w_{GMV}.

Adding the risk-free asset, the best possible portfolios lie on a straight line from R_f through the tangency portfolio: the Capital Market Line (CML):

E[R_P]=R_f+Sharpe_T\times\sigma_P

An investor puts a fraction y in the tangency portfolio and 1-y in T-Bills: y<1 for conservative investors; y>1 means borrowing at the risk-free rate (leverage).

lams = np.linspace(-0.5, 2.0, 200)                   # 200 values of lambda between -0.5 and 2 (the weight of the tangency portfolio)
front = [port_perf(l * w_tan + (1 - l) * w_gmv, mu, COV) for l in lams]   # (return, volatility, Sharpe) of each combination of tangency and GMV
f_ret = np.array([f[0] for f in front])              # expected returns of the frontier portfolios (first element of each tuple)
f_vol = np.array([f[1] for f in front])              # volatilities of the frontier portfolios (second element of each tuple)
x = np.linspace(0, f_vol.max(), 50)                  # 50 volatility values from 0 to the maximum, to draw the CML

plt.figure(figsize=(9, 6))                           # new figure of 9 x 6 inches
plt.scatter(cloud_vol, cloud_ret, s=4, alpha=0.3, label="random portfolios (long only)")   # the cloud of random portfolios
plt.plot(f_vol, f_ret, color="black", label="efficient frontier (short sales allowed)")    # the frontier (two-fund theorem)
plt.plot(x, RF_ANNUAL + sh_tan * x, color="green", ls="--", label="Capital Market Line")  # CML: Rf + Sharpe_T * volatility
plt.scatter(vol_gmv, ret_gmv, marker="D", s=90, color="red", label="GMV", zorder=5)        # the GMV portfolio (diamond)
plt.scatter(vol_tan, ret_tan, marker="*", s=250, color="orange", label="Tangency", zorder=5)   # the tangency portfolio (star)
asset_vol = np.sqrt(np.diag(COV.values))             # volatility of each asset: square root of the diagonal of COV
plt.scatter(asset_vol, mu.values, color="purple", zorder=5)   # the individual assets
for i, a in enumerate(ASSETS):                       # for each asset (i = position, a = ticker) ...
    plt.annotate(a, (asset_vol[i], mu.values[i]), fontsize=8)   # ... write its ticker next to its point
plt.xlabel("annual volatility")                      # label of the x axis
plt.ylabel("annual expected return")                 # label of the y axis
plt.legend(fontsize=8)                               # show the legend with small letters
plt.grid(alpha=0.3)                                  # light grid
plt.show()                                           # display the plot

8 Without short sales: a numerical optimizer

Most investors (and most funds) cannot short-sell. With the constraint w_i\geq0 there is no formula, so we use a numerical optimizer: scipy.optimize.minimize. It works like the bisection and gradient descent algorithms of the Algorithms course: start from an initial guess and improve it step by step until the objective cannot be improved. We must give it:

  • the objective function to minimize (the variance, or the negative Sharpe ratio, because the function minimizes);
  • an initial guess (equal weights);
  • bounds for each weight: (0, 1);
  • constraints: the weights add up to 1.
def optimize_portfolio(mu, cov, objective="gmv", rf=0.0, long_only=True):
    """GMV or max-Sharpe portfolio with scipy (SLSQP)."""
    n = len(mu)                                      # number of assets
    if objective == "gmv":                           # if we want the minimum variance portfolio ...
        fun = lambda w: w @ cov.values @ w           # ... the objective is the portfolio variance w' COV w
    else:                                            # otherwise (max Sharpe) ...
        fun = lambda w: -port_perf(w, mu, cov, rf)[2]   # ... the objective is the NEGATIVE Sharpe ratio (minimize = maximize the Sharpe)
    bounds = [(0, 1)] * n if long_only else [(-2, 2)] * n   # limits of each weight: 0 to 1 (long only) or -2 to 2 (short sales)
    cons = [{"type": "eq", "fun": lambda w: w.sum() - 1}]   # equality constraint: sum of weights - 1 = 0
    res = minimize(fun, np.repeat(1 / n, n), method="SLSQP", bounds=bounds, constraints=cons,   # start from equal weights
                   options={"ftol": 1e-12, "maxiter": 1000})   # high precision and up to 1,000 iterations
    assert res.success, res.message                  # stop with the optimizer's message if it did not converge
    return pd.Series(res.x, index=mu.index)          # optimal weights (res.x) with the asset names

# Check: without the long-only restriction, the optimizer must find the closed-form GMV
w_check = optimize_portfolio(mu, COV, "gmv", long_only=False)   # GMV with short sales, found by the optimizer
assert np.allclose(w_check.values, w_gmv, atol=1e-4)            # it must be (almost) equal to the formula's GMV
w_gmv_lo = optimize_portfolio(mu, COV, "gmv")                    # GMV without short sales (long only)
w_gmv_lo.round(4)                                                # show its weights
AAPL    0.0000
JPM     0.0858
WMT     0.2048
XOM     0.1286
GLD     0.5808
dtype: float64

The assert is our verification: when the optimizer solves the same problem as the formula, both must give the same answer.

NotePyPortfolioOpt (optional)

The library PyPortfolioOpt does the same calculations (!pip install PyPortfolioOpt in Colab). If you use it, be careful: max_sharpe() uses a risk-free rate of 2% unless you give it risk_free_rate=, and portfolio_performance() reports the portfolio of the last optimization you ran on that object. Always verify its results with your own code.

from pypfopt import EfficientFrontier                # import the class that builds the efficient frontier
ef = EfficientFrontier(mu, COV, weight_bounds=(0, 1))   # create the frontier object with our inputs; weights between 0 and 1 (long only)
ef.max_sharpe(risk_free_rate=RF_ANNUAL)              # find the maximum Sharpe portfolio with OUR risk-free rate
print(ef.clean_weights())                            # show the weights, rounded (tiny weights become 0)
ef.portfolio_performance(risk_free_rate=RF_ANNUAL, verbose=True)   # expected return, volatility and Sharpe of that portfolio

9 CHALLENGE 1: Optimal portfolios for your 5 stocks

In Workshop 2 (Challenge 2, step 5) you selected 5 stocks: from the 20 stocks of the ROA screen, the 10 with the highest alpha, and from them the 5 with the lowest beta.

  1. Using the window April 2020 – March 2023, calculate mu and COV for your 5 stocks with opt_inputs, and the correlation matrix of their monthly cc returns. Which pair is the most correlated?
  2. Calculate the GMV and the tangency portfolios with short sales allowed (closed-form formulas), and their expected return, volatility and Sharpe ratio (use the T-Bill rate of March 2023).
  3. Calculate the GMV and the tangency portfolios without short sales (optimize_portfolio). Compare the weights with the previous ones. Which version would you recommend to a client, and why?
  4. Interpret the long-only GMV portfolio: weights, expected return and volatility, in words that a client understands.
# Write your code here

10 CHALLENGE 2: Efficient frontier and CML of your 5 stocks

  1. Draw, in the same plot: 5,000 random long-only portfolios of your 5 stocks, the efficient frontier with short sales (two-fund theorem), the CML, the 5 stocks, the two GMV portfolios and the two tangency portfolios.
  2. A client wants an expected volatility of 15% per year. Using the CML, what fraction y must be invested in the tangency portfolio (short sales allowed) and what is the expected return? Is the client borrowing or lending at the risk-free rate?
# Write your code here

11 Estimation risk: why optimized portfolios are fragile

The inputs \mu and \Sigma are estimates from 36 months of data, and the expected returns are especially noisy: the standard error of a mean annual return is about \sigma/\sqrt{T}, which for a stock with 30% volatility and 3 years of data is about 17 percentage points! The optimizer takes the estimates as if they were true, and it puts large weights on the assets whose expected returns are overestimated. This is why many practitioners prefer the GMV (which does not use \mu) or simply equal weights.

Let’s see it with our 5 example assets: we add a small random error (standard deviation of 3 percentage points, much smaller than the real estimation error) to the expected returns, 20 times, and recompute the tangency portfolio with and without short sales. The table shows the lowest and the highest weight that each asset received in the 20 experiments:

rng = np.random.default_rng(seed=1)                  # random number generator with a fixed seed
w_short, w_long = [], []                             # empty lists to save the weights of each experiment
for k in range(20):                                  # 20 experiments
    mu_noisy = mu + rng.normal(0, 0.03, len(mu))     # expected returns + a random error (mean 0, sd = 3 percentage points)
    raw_k = Sinv @ (mu_noisy.values - RF_ANNUAL)     # raw tangency weights with the noisy expected returns
    w_short.append(pd.Series(raw_k / (ones @ raw_k), index=ASSETS))          # tangency weights, short sales allowed
    w_long.append(optimize_portfolio(mu_noisy, COV, "sharpe", rf=RF_ANNUAL))   # tangency weights, long only
w_short, w_long = pd.DataFrame(w_short), pd.DataFrame(w_long)   # convert the lists into data frames (20 rows x 5 assets)
# lowest and highest weight of each asset in the 20 experiments:
pd.DataFrame({"short allowed: min": w_short.min(), "short allowed: max": w_short.max(),
              "long only: min": w_long.min(), "long only: max": w_long.max()}).round(2)
short allowed: min short allowed: max long only: min long only: max
AAPL 0.38 1.06 0.24 0.44
JPM -1.09 -0.29 0.00 0.00
WMT -0.69 0.23 0.00 0.00
XOM 0.68 1.72 0.45 0.61
GLD -0.92 0.41 0.00 0.24

Errors of only 3 percentage points in the expected returns move the “optimal” weights a lot, especially when short sales are allowed. The long-only constraint makes the portfolio more stable, but the weights still change by many percentage points. The GMV does not change at all in this experiment, because it does not use \mu.

12 Backtesting

A backtest answers: if I had invested with this rule in the past, what would have happened? To be honest, a backtest must be out of sample: the portfolio is estimated with data before the decision date, and it is evaluated with data after the decision date. Evaluating a portfolio in the same window used to estimate it is meaningless: of course the optimized portfolio looks great with the data that was used to optimize it.

Two ways to hold a portfolio:

  • Buy and hold: buy the initial weights and do nothing. The weights drift: the assets that go up gain weight.
  • Monthly rebalancing: every month, trade back to the initial weights. The monthly portfolio return is simply R[assets] @ w.
def backtest(w, assets, start, end, rebalance=False):
    """Monthly simple returns of a portfolio held from start to end."""
    Rw = R.loc[start:end, assets].fillna(0)          # simple returns of the assets in the window; a missing return is treated as 0
    w = np.asarray(w)                                # weights as a numpy array (works with lists, Series or arrays)
    if rebalance:                                    # with monthly rebalancing ...
        return Rw @ w                                # ... the portfolio return is the weighted average of the returns each month
    growth = (1 + Rw).cumprod()                      # buy and hold: value of $1 in each asset (cumulative product of growth factors)
    value = growth @ w                               # value of the portfolio: the money in each asset grows with its own index
    return value.pct_change().fillna(value.iloc[0] - 1)   # monthly returns of the portfolio value (the 1st month: value - 1)

def summary_stats(port_R, rf_annual=0.0):
    """HPR, annualized return, annualized volatility and Sharpe ratio from monthly simple returns."""
    n = len(port_R)                                  # number of months
    hpr = (1 + port_R).prod() - 1                    # holding period return: product of growth factors - 1
    ann_ret = (1 + hpr) ** (12 / n) - 1              # annualized (geometric) return
    ann_vol = np.log(1 + port_R).std() * np.sqrt(12)   # annual volatility, using cc returns
    return pd.Series({"HPR": hpr, "annual return": ann_ret, "annual volatility": ann_vol,   # all the results in one Series
                      "Sharpe": (ann_ret - rf_annual) / ann_vol, "months": n})

OOS_START, OOS_END = "2023-04-30", "2024-03-31"      # the 12 months after the decision date (out of sample)
bt = pd.DataFrame({                                  # monthly returns of the 3 portfolios to compare (one column each):
    "GMV long-only (B&H)": backtest(w_gmv_lo, ASSETS, OOS_START, OOS_END),   # long-only GMV, buy and hold
    "Equal weights (B&H)": backtest(w_eq, ASSETS, OOS_START, OOS_END),       # equally weighted, buy and hold
    "SPY": R.loc[OOS_START:OOS_END, "SPY"]})                                 # the market (S&P 500 ETF)
rf_oos = (1 + rf.loc[OOS_START:OOS_END, "rf"]).prod() ** (12 / len(bt)) - 1   # annualized risk-free rate of the same 12 months
bt.apply(summary_stats, rf_annual=rf_oos).T.round(4)   # apply summary_stats to each column; transpose: one row per portfolio
HPR annual return annual volatility Sharpe months
GMV long-only (B&H) 0.1833 0.1833 0.0935 1.3918 12.0
Equal weights (B&H) 0.2178 0.2178 0.1004 1.6397 12.0
SPY 0.2962 0.2962 0.1332 1.8240 12.0
((1 + bt).cumprod()).plot(figsize=(9, 4.5), title="Value of $1 invested on March 31, 2023 (out of sample)")   # value of $1 in each portfolio
plt.grid(alpha=0.3)                                  # light grid
plt.show()                                           # display the plot

summary_stats calculates the HPR with the product of the growth factors, \prod(1+R_t)-1, and then the annualized (geometric) return (1+HPR)^{12/n}-1. The volatility is calculated with cc returns, as in the Algorithms course.

13 CHALLENGE 3: Out-of-sample backtest of your portfolio

  1. Backtest from April 2023 to March 2024 (buy and hold) the following portfolios of your 5 stocks: the long-only GMV, the long-only tangency, and the equally weighted portfolio. Add SPY as the benchmark.
  2. Report the HPR, annual return, volatility and Sharpe ratio of each one, and plot the value of $1.
  3. Repeat the backtest of the long-only GMV with monthly rebalancing. Is the difference large? Why?
  4. Did the optimized portfolios beat the equally weighted portfolio and the market? Was the realized volatility of the GMV close to its expected volatility? Write a short paragraph for your investment committee.
  5. Extension: extend the backtest to the last month of the data. Does your conclusion change?
# Write your code here

14 CHALLENGE 4: Bug hunt

4.1 Weights and returns:

w = np.array([0.4, 0.3, 0.2, 0.1, 0.0])           # weights for ["XOM", "AAPL", "WMT", "JPM", "GLD"]
port = R[["AAPL", "GLD", "JPM", "WMT", "XOM"]] @ w

4.2 Portfolio returns with log returns:

port_r = r[ASSETS] @ w_eq
hpr = np.exp(port_r.sum()) - 1

4.3 Inputs:

mu = np.exp(12 * r.loc[START:END, ASSETS].mean()) - 1
COV = r.loc[START:END, ASSETS].cov()

4.4 Backtest:

w = optimize_portfolio(mu, COV, "gmv")
bt = backtest(w, ASSETS, START, END)               # START, END = estimation window

4.5 PyPortfolioOpt:

ef = EfficientFrontier(mu, COV, weight_bounds=(0, 1))
w = ef.min_volatility()
print("Tangency portfolio:", ef.portfolio_performance(risk_free_rate=0.045))

Write your answers here

15 Reflection: beyond the rational investor

Portfolio theory assumes that investors are rational and that the expected returns and covariances are known. Neither is true. Based on what you learned in this workshop (estimation risk, out-of-sample tests) and on your own view of the market (trends, regulations, fears, technologies), propose in a short paragraph how you would modify the optimized portfolio for a real client, and why.

16 DataCamp

Take the chapter “Portfolio Investing” (Chapter 2 of Introduction to Portfolio Risk Management in Python): efficient frontier, GMV and maximum-Sharpe portfolios.

17 W3 submission

Submit your .ipynb file in Canvas and answer the Canvas Quiz W3 before the first class of next week.