Quantitative Risk Management in Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Welcome!

Q U A N T I TAT I V E R I S K M A N A G E M E N T I N P Y T H O N

Dr. Jamsheed Shorish


Computational Economist
About Me
Computational Economist

Specializing in:
asset pricing

nancial technologies ("FinTech")

computer applications to economics and nance

Co-instructor, "Economic Analysis of the Digital Economy" at the ANU

Shorish Research (Belgium): computational business applications

QUANTITATIVE RISK MANAGEMENT IN PYTHON


What is Quantitative Risk Management?
Quantitative Risk Management: Study of quanti able uncertainty

Uncertainty:
Future outcomes are unknown

Outcomes impact planning decisions

Risk management: mitigate (reduce e ects of) adverse outcomes

Quanti able uncertainty: identify factors to measure risk


Example: Fire insurance. What factors make re more likely?

This course: focus upon risk associated with a nancial portfolio

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Risk management and the Global Financial Crisis
Great Recession (2007 - 2010)
Global growth loss more than $2 trillion

United States: nearly $10 trillion lost in household wealth

U.S. stock markets lost c. $8 trillion in value

Global Financial Crisis (2007-2009)


Large-scale changes in fundamental asset values

Massive uncertainty about future returns

High asset returns volatility

Risk management critical to success or failure

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Quick recap: financial portfolios
Financial portfolio
Collection of assets with uncertain future returns

Stocks

Bonds

Foreign exchange holdings ('forex')

Stock options

Challenge: quantify risk to manage uncertainty


Make optimal investment decisions

Maximize portfolio return, conditional on risk appetite

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Quantifying return
Portfolio return: weighted sum of individual asset returns
Pandas data analysis library

DataFrame prices

.pct_change() method

.dot() method of returns

prices = pandas.read_csv("portfolio.csv")
returns = prices.pct_change()
weights = (weight_1, weight_2, ...)
portfolio_returns = returns.dot(weights)

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Quantifying risk
Portfolio return volatility = risk

Calculate volatility via covariance matrix

Use .cov() DataFrame method of


returns and annualize

covariance = returns.cov()*252
print(covariance)

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Quantifying risk
Portfolio return volatility = risk

Calculate volatility via covariance matrix

Use .cov() DataFrame method of


returns and annualize

Diagonal of covariance is individual asset


variances

covariance = returns.cov()*252
print(covariance)

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Quantifying risk
Portfolio return volatility = risk

Calculate volatility via covariance matrix

Use .cov() DataFrame method of


returns and annualize

Diagonal of covariance is individual asset


variances

O -diagonals of covariance are


covariances between assets

covariance = returns.cov()*252
print(covariance)

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Portfolio risk
Depends upon asset weights in portfolio

Portfolio variance σp2 is


σp2 := wT ⋅ Covp ⋅ w

Matrix multiplication can be computed using @ operator in Python

Standard deviation is usually used instead of variance

weights = [0.25, 0.25, 0.25, 0.25] # Assumes four assets in portfolio


portfolio_variance = np.transpose(weights) @ covariance @ weights
portfolio_volatility = np.sqrt(portfolio_variance)

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Volatility time series
Can also calculate portfolio volatility over
time

Use a 'window' to compute volatility over a


xed time period (e.g. week, 30-day
'month')

Series.rolling() creates a window

Observe volatility trend and possible


extreme events

windowed = portfolio_returns.rolling(30)
volatility = windowed.std()*np.sqrt(252)
volatility.plot()
.set ylabel("Standard Deviation...")

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Let's practice!
Q U A N T I TAT I V E R I S K M A N A G E M E N T I N P Y T H O N
Risk factors and the
financial crisis
Q U A N T I TAT I V E R I S K M A N A G E M E N T I N P Y T H O N

Jamsheed Shorish
Computational Economist
Risk factors
Volatility: measure of dispersion of returns
around expected value

Time series: expected value = sample


average

What drives expectation and dispersion?

Risk factors: variables or events driving


portfolio return and volatility

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Risk exposure
Risk exposure: measure of possible portfolio loss
Risk factors determine risk exposure

Example: Flood Insurance


Deductible: out-of-pocket payment regardless of loss

100% coverage still leaves deductible to be paid

So deductible is risk exposure

Frequent ooding => more volatile ood outcome

Frequent ooding => higher risk exposure

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Systematic risk
Systematic risk: risk factor(s) a ecting
volatility of all portfolio assets
Market risk: systematic risk from general
nancial market movements

Airplane engine failure: systematic risk!

Examples of nancial systematic risk


factors:
Price level changes, i.e. in ation

Interest rate changes

Economic climate changes

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Idiosyncratic risk
Idiosyncratic risk: risk speci c to a
particular asset/asset class.

Turbulence and the unfastened seatbelt:


idiosyncratic risk!

Examples of idiosyncratic risk:


Bond portfolio: issuer risk of default

Firm/sector characteristics
Firm size (market capitalization)

Book-to-market ratio

Sector shocks

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Factor models
Factor model: assessment of risk factors a ecting portfolio return

Statistical regression, e.g. Ordinary Least Squares (OLS):


dependent variable: returns (or volatility)

independent variable(s): systemic and/or idiosyncratic risk factors

Fama-French factor model: combination of


market risk and

idiosyncratic risk ( rm size, rm value)

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Crisis risk factor: mortgage-backed securities
Investment banks: borrowed heavily just
before the crisis

Collateral: mortgage-backed securities


(MBS)

MBS: supposed to diversify risk by holding


many mortgages of di erent characteristics
Flaw: mortgage default risk in fact was
highly correlated

Avalanche of delinquencies/default
destroyed collateral value

90-day mortgage delinquency: risk factor


for investment bank portfolio during the

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Crisis factor model
Factor model regression: portfolio returns vs. mortgage delinquency

Import statsmodels.api library for regression tools

Fit regression using .OLS() object and its .fit() method

Display results using regression's .summary() method

import statsmodels.api as sm
regression = sm.OLS(returns, delinquencies).fit()
print(regression.summary())

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Regression .summary() results

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Let's practice!
Q U A N T I TAT I V E R I S K M A N A G E M E N T I N P Y T H O N
Modern portfolio
theory
Q U A N T I TAT I V E R I S K M A N A G E M E N T I N P Y T H O N

Jamsheed Shorish
Computational Economist
The risk-return trade-off
Risk factors: sources of uncertainty a ecting return

Intuitively: greater uncertainty (more risk) compensated by greater return

Cannot guarantee return: need some measure of expected return


average (mean) historical return: proxy for expected future return

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Investor risk appetite
Investor survey: minimum return required for given level of risk?

Survey response creates (risk, return) risk pro le "data point"

Vary risk level => set of (risk, return) points

Investor risk appetite: de nes one quanti ed relationship between risk and return

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Choosing portfolio weights
Vary portfolio weights of given portfolio => creates set of (risk, return) pairs

Changing weights = beginning risk management!

Goal: change weights to maximize expected return, given risk level


Equivalently: minimize risk, given expected return level

Changing weights = adjusting investor's risk exposure

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Modern portfolio theory
E cient portfolio: portfolio with weights generating highest expected return for given level
of risk

Modern Portfolio Theory (MPT), 1952


H. M. Markowitz (Nobel Laureate 1990)

E cient portfolio weight vector w⋆ solves:

QUANTITATIVE RISK MANAGEMENT IN PYTHON


The efficient frontier
Compute many e cient portfolios for di erent levels of risk

E cient frontier: locus of (risk, return) pairs created by e cient portfolios

PyPortfolioOpt library: optimized tools for MPT


EfficientFrontier class: generates one optimal portfolio at a time

Constrained Line Algorithm ( CLA ) class: generates the entire e cient frontier
Requires covariance matrix of returns

Requires proxy for expected future returns: mean historical returns

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Investment bank portfolio 2005 - 2010
Expected returns: historical data

Covariance matrix: Covariance Shrinkage improves e ciency of estimate

Constrained Line Algorithm object CLA

Minimum variance portfolio: cla.min_volatility()

E cient frontier: cla.efficient_frontier()

expected_returns = mean_historical_return(prices)
efficient_cov = CovarianceShrinkage(prices).ledoit_wolf()
cla = CLA(expected_returns, efficient_cov)
minimum_variance = cla.min_volatility()
(ret, vol, weights) = cla.efficient_frontier()

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Visualizing the efficient frontier
Sca er plot of (vol, ret) pairs

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Visualizing the efficient frontier
Sca er plot of (vol, ret) pairs

Minimum variance portfolio: smallest


volatility of all possible e cient portfolios

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Visualizing the efficient frontier
Sca er plot of (vol, ret) pairs

Minimum variance portfolio: smallest


volatility of all possible e cient portfolios

Increasing risk appetite: move along the


frontier

QUANTITATIVE RISK MANAGEMENT IN PYTHON


Let's practice!
Q U A N T I TAT I V E R I S K M A N A G E M E N T I N P Y T H O N

You might also like