0% found this document useful (0 votes)
56 views30 pages

Chapter 1

This document introduces portfolio risk management in Python. It discusses measuring investment risk through standard deviation and other metrics. It explains how to calculate stock returns in Python using pandas and numpy libraries. It also covers calculating moments like mean, variance, skewness and kurtosis of return distributions and performing statistical tests for normality. The document provides code examples for calculating various risk measures in Python.

Uploaded by

nishant
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)
56 views30 pages

Chapter 1

This document introduces portfolio risk management in Python. It discusses measuring investment risk through standard deviation and other metrics. It explains how to calculate stock returns in Python using pandas and numpy libraries. It also covers calculating moments like mean, variance, skewness and kurtosis of return distributions and performing statistical tests for normality. The document provides code examples for calculating various risk measures in Python.

Uploaded by

nishant
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/ 30

Financial returns

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
Course overview
Learn how to analyze investment return distributions, build
portfolios and reduce risk, and identify key factors which are
driving portfolio returns.

Univariate Investment Risk

Portfolio Investing

Factor Investing

Forecasting and Reducing Risk

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Investment risk
What is Risk?

Risk in nancial markets is a measure of uncertainty

Dispersion or variance of nancial returns

How do you typically measure risk?

Standard deviation or variance of daily returns

Kurtosis of the daily returns distribution

Skewness of the daily returns distribution

Historical drawdown

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Financial risk
Returns Probability

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


A tale of two returns
Returns are derived from
stock prices

Discrete returns (simple


returns) are the most
commonly used, and
represent periodic (e.g.
daily, weekly, monthly, etc.)
price movements

Log returns are o en used


in academic research and
nancial modeling. They
assume continuous
compounding.

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Calculating stock returns
Discrete returns are
calculated as the change in
price as a percentage of the
previous period's price

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Calculating log returns
Log returns are calculated
as the di erence between
Pt2
the log of two prices Rl = ln( )
Pt1
Log returns aggregate
across time, while discrete or equivalently
returns aggregate across
Rl = ln(Pt2 ) − ln(Pt1 )
assets

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Calculating stock returns in Python
Step 1:
Load in stock prices data and store it as a pandas DataFrame
organized by date:

import pandas as pd
StockPrices = pd.read_csv('StockData.csv', parse_dates=['Date'])
StockPrices = StockPrices.sort_values(by='Date')
StockPrices.set_index('Date', inplace=True)

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Calculating stock Returns in Python
Step 2:
Calculate daily returns of the adjusted close prices and append
the returns as a new column in the DataFrame.

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


StockPrices["Returns"].head()

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Visualizing return distributions
import matplotlib.pyplot as plt
plt.hist(StockPrices["Returns"].dropna(), bins=75, density=False)
plt.show()

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
Mean, variance, and
normal distribution
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
Moments of distributions
Probability distributions have the following moments:

1) Mean (μ)

2) Variance ( σ2 )

3) Skewness

4) Kurtosis

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


There are many types of
distributions. Some are normal
and some are non-normal. A
random variable with a
Gaussian distribution is said
to be normally distributed.

Normal Distributions have the


following properties:

Mean = μ
Variance = σ2
Skewness = 0

Kurtosis = 3

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


The standard normal distribution
The Standard Normal is a special case of the Normal
Distribution when:

σ=1
μ=0

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Comparing against a normal distribution
Normal distributions have a skewness near 0 and a kurtosis
near 3.

Financial returns tend not to be normally distributed

Financial returns can have high kurtosis

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Comparing against a normal distribution

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Calculating mean returns in python
To calculate the average daily return, use the np.mean()
function:

import numpy as np
np.mean(StockPrices["Returns"])

0.0003

To calculate the average annualized return assuming 252


trading days in a year:

import numpy as np
((1+np.mean(StockPrices["Returns"]))**252)-1

0.0785

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Standard deviation and variance
Standard Deviation
(Volatility)

Variance = σ2
O en represented in
mathematical notation as σ,
or referred to as volatility

An investment with higher σ


is viewed as a higher risk
investment

Measures the dispersion of


returns

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Standard deviation and variance in Python
Assume you have pre-loaded stock returns data in the
StockData object. To calculate the periodic standard deviation
of returns:

import numpy as np
np.std(StockPrices["Returns"])

0.0256

To calculate variance, simply square the standard deviation:

np.std(StockPrices["Returns"])**2

0.000655

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Scaling volatility
Volatility scales with the
square root of time

You can normally assume


252 trading days in a given
year, and 21 trading days in
a given month

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Scaling volatility in Python
Assume you have pre-loaded stock returns data in the
StockData object. To calculate the annualized volatility of
returns:

import numpy as np
np.std(StockPrices["Returns"]) * np.sqrt(252)

0.3071

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
Skewness and
kurtosis
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
Skewness is the third moment
of a distribution.

Negative Skew: The mass of


the distribution is
concentrated on the right.
Usually a right-leaning
curve

Positive Skew: The mass of


the distribution is
concentrated on the le .
Usually a le -leaning curve

In nance, you would tend


to want positive skewness

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Skewness in Python
Assume you have pre-loaded stock returns data in the
StockData object.

To calculate the skewness of returns:

from scipy.stats import skew


skew(StockData["Returns"].dropna())

0.225

Note that the skewness is higher than 0 in this example,


suggesting non-normality.

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Kurtosis is a measure of the
thickness of the tails of a
distribution

Most nancial returns are


leptokurtic

Leptokurtic: When a
distribution has positive
excess kurtosis (kurtosis
greater than 3)

Excess Kurtosis: Subtract 3


from the sample kurtosis to
calculate "Excess Kurtosis"

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Excess kurtosis in Python
Assume you have pre-loaded stock returns data in the
StockData object. To calculate the excess kurtosis of returns:

from scipy.stats import kurtosis


kurtosis(StockData["Returns"].dropna())

2.44

Note the excess kurtosis greater than 0 in this example,


suggesting non-normality.

INTRODUCTION TO PORTFOLIO RISK MANAGEMENT IN PYTHON


Testing for normality in Python
How do you perform a statistical test for normality?

The null hypothesis of the Shapiro-Wilk test is that the data are
normally distributed.

# Run the Shapiro-Wilk normality test in Python


from scipy import stats
p_value = stats.shapiro(StockData["Returns"].dropna())[1]
if p_value <= 0.05:
print("Null hypothesis of normality is rejected.")
else:
print("Null hypothesis of normality is accepted.")

The p-value is the second variable returned in the list. If the p-


value is less than 0.05, the null hypothesis is rejected because
the data are most likely non-normal.

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