0% found this document useful (0 votes)
111 views34 pages

Portfolio Composition and Backtesting: Dakota Wixom

This document provides an introduction to portfolio composition, backtesting, risk management, and optimization in Python. It discusses calculating portfolio returns using weighted averages of constituent returns. It also covers calculating equally weighted and market capitalization weighted portfolios. The document reviews correlation and covariance matrices and calculates portfolio risk using these matrices. Finally, it discusses generating random portfolios, calculating the efficient frontier, and selecting the maximum Sharpe ratio and minimum volatility portfolios.

Uploaded by

Gedela Bharadwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views34 pages

Portfolio Composition and Backtesting: Dakota Wixom

This document provides an introduction to portfolio composition, backtesting, risk management, and optimization in Python. It discusses calculating portfolio returns using weighted averages of constituent returns. It also covers calculating equally weighted and market capitalization weighted portfolios. The document reviews correlation and covariance matrices and calculates portfolio risk using these matrices. Finally, it discusses generating random portfolios, calculating the efficient frontier, and selecting the maximum Sharpe ratio and minimum volatility portfolios.

Uploaded by

Gedela Bharadwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Portfolio

composition and
backtesting
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON

Dakota Wixom
Quantitative Analyst | QuantCourse.com
Calculating portfolio returns
Portfolio Return Formula:
Rp = Ra1 wa1 + Ra2 wa2 + ... + Ran wa1

Rp : Portfolio return
Ran : Return for asset n
wan : Weight for asset n

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Assuming StockReturns is a pandas DataFrame of stock
returns, you can calculate the portfolio return for a set of
portfolio weights as follows:

import numpy as np
portfolio_weights = np.array([0.25, 0.35, 0.10, 0.20, 0.10])
port_ret = StockReturns.mul(portfolio_weights, axis=1).sum(axis=1)
port_ret

Date
2017-01-03 0.008082
2017-01-04 0.000161
2017-01-05 0.003448
...

StockReturns["Portfolio"] = port_ret

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Equally weighted portfolios in Python
Assuming StockReturns is a pandas DataFrame of stock
returns, you can calculate the portfolio return for an equally
weighted portfolio as follows:

import numpy as np
numstocks = 5
portfolio_weights_ew = np.repeat(1/numstocks, numstocks)
StockReturns.iloc[:,0:numstocks].mul(portfolio_weights_ew, axis=1).sum(axis=1)

Date
2017-01-03 0.008082
2017-01-04 0.000161
2017-01-05 0.003448
...

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Plotting portfolio returns in Python
To plot the daily returns in Python:

StockPrices["Returns"] = StockPrices["Adj Close"].pct_change()


StockReturns = StockPrices["Returns"]
StockReturns.plot()

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Plotting portfolio cumulative returns
In order to plot the cumulative returns of multiple portfolios:

import matplotlib.pyplot as plt


CumulativeReturns = ((1 + StockReturns).cumprod() - 1)
CumulativeReturns[["Portfolio","Portfolio_EW"]].plot()

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Market capitalization

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Market capitalization
Market capitalization: The value of a company's publicly
traded shares.

Also referred to as Market cap.

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Market-cap weighted portfolios
In order to calculate the market cap weight of a given stock n:

mcapn
wmcapn = n
∑i=1 mcapi

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Market-Cap weights in Python
To calculate market cap weights in python, assuming you have
data on the market caps of each company:

import numpy as np
market_capitalizations = np.array([100, 200, 100, 100])
mcap_weights = market_capitalizations/sum(market_capitalizations)
mcap_weights

array([0.2, 0.4, 0.2, 0.2])

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Let's practice!
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON
Correlation and co-
variance
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON

Dakota Wixom
Quantitative Analyst | QuantCourse.com
Pearson correlation
Examples of di erent correlations between two
random variables:

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Pearson correlation
A heatmap of a correlation matrix:

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Correlation matrix in Python
Assuming StockReturns is a pandas DataFrame of stock
returns, you can calculate the correlation matrix as follows:

correlation_matrix = StockReturns.corr()
print(correlation_matrix)

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Portfolio standard deviation
Portfolio standard deviation for a two asset portfolio:

σp = √w12 σ12 + w22 σ22 + 2w1 w2 ρ1,2 σ1 σ2

σp : Portfolio standard deviation


w: Asset weight

σ : Asset volatility
ρ1,2 : Correlation between assets 1 and 2

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


The Co-variance matrix
To calculate the co-variance matrix (Σ) of returns X:

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


The Co-variance matrix in Python
Assuming StockReturns is a pandas DataFrame of stock
returns, you can calculate the covariance matrix as follows:

cov_mat = StockReturns.cov()
cov_mat

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Annualizing the covariance matrix
To annualize the covariance matrix:

cov_mat_annual = cov_mat * 252

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Portfolio standard deviation using covariance
The formula for portfolio volatility is:

σP ortf olio = √wT ⋅ Σ ⋅ w

σP ortf olio : Portfolio volatility


Σ: Covariance matrix of returns
w: Portfolio weights (wT is transposed portfolio weights)

⋅ The dot-multiplication operator

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Matrix transpose
Examples of matrix transpose operations:

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Dot product
The dot product operation of two vectors a and b:

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Portfolio standard deviation using Python
To calculate portfolio volatility assume a weights array and a
covariance matrix:

import numpy as np
port_vol = np.sqrt(np.dot(weights.T, np.dot(cov_mat, weights)))
port_vol

0.035

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Let's practice!
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON
Markowitz portfolios
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON

Dakota Wixom
Quantitative Analyst | QuantCourse.com
100,000 randomly generated portfolios

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Sharpe ratio
The Sharpe ratio is a measure of risk-adjusted return.

To calculate the 1966 version of the Sharpe ratio:

Ra − rf
S=
σa
S: Sharpe Ratio

Ra : Asset return
rf : Risk-free rate of return
σa : Asset volatility

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


The efficient frontier

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


The Markowitz portfolios
Any point on the e cient
frontier is an optimum
portfolio.

These two common points are


called Markowitz Portfolios:

MSR: Max Sharpe Ratio


portfolio

GMV: Global Minimum


Volatility portfolio

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Choosing a portfolio
How do you choose the best portfolio?

Try to pick a portfolio on the bounding edge of the e cient


frontier

Higher return is available if you can stomach higher risk

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Selecting the MSR in Python
Assuming a DataFrame df of random portfolios with
Volatility and Returns columns:

numstocks = 5
risk_free = 0
df["Sharpe"] = (df["Returns"] - risk_free) / df["Volatility
MSR = df.sort_values(by=['Sharpe'], ascending=False)
MSR_weights = MSR.iloc[0, 0:numstocks]
np.array(MSR_weights)

array([0.15, 0.35, 0.10, 0.15, 0.25])

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Past performance is not a guarantee of future returns
Even though a Max Sharpe Ratio portfolio might sound nice, in
practice, returns are extremely di cult to predict.

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Selecting the GMV in Python
Assuming a DataFrame df of random portfolios with
Volatility and Returns columns:

numstocks = 5
GMV = df.sort_values(by=['Volatility'], ascending=True)
GMV_weights = GMV.iloc[0, 0:numstocks]
np.array(GMV_weights)

array([0.25, 0.15, 0.35, 0.15, 0.10])

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Let's practice!
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON

You might also like